diff --git "a/6206.jsonl" "b/6206.jsonl" new file mode 100644--- /dev/null +++ "b/6206.jsonl" @@ -0,0 +1,719 @@ +{"seq_id":"123089443","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nDate: 20200413\nUser: Alan Viegas\nProject: API para fazer um Rest API de CRUD básico para persistir os dados do ReclameAqui\nv101: Initial version\n\n## Tests \n curl -X POST \"http://localhost:5005/scores?company=Cielo&date=20200421\"\n curl -X GET \"http://localhost:5005/scores?company=Cielo\"\n curl -X DELETE \"http://localhost:5005/scores?company=Cielo&date=20200421\"\n curl -X DELETE \"http://localhost:5005/scores?company=Cielo\"\n\nRef:\n https://pynative.com/python-json-validation/\n\n\"\"\"\n\nimport sys\n\n# Para subir a API no Docker\nsys.path.append('/app')\n\n# Para subir localmente \n#sys.path.append('/home/alanviegas/Documentos/estudos/desafioSemantix/apps/API_persistenciaDados')\n\nimport json\nfrom flask import Flask, Response, jsonify, request, abort\nfrom datetime import datetime\nfrom src.dao.model import ReclameAquiScore, ReclameAquiReclamation\nfrom utils.utils import validateJSON\n\napp = Flask(__name__)\napp.config['JSON_AS_ASCII'] = False\n\n@app.route('/')\ndef home():\n return \"API para fazer um Rest API de CRUD básico para persistir os dados do ReclameAqui\"\n\n\n@app.route('/scores/', methods=['POST'])\ndef post_scores():\n company = request.args['company']\n date = request.args['date']\n \n json_raw = request.get_json()\n\n isValid = validateJSON(json_raw, 'scores')\n if not isValid:\n return jsonify({'Formato Invalido', 400})\n\n json_id = {'_id' : date + company.upper(), 'company' : company, 'date' : date}\n json_final = {**json_id, **json_raw}\n \n score = ReclameAquiScore(**json_final)\n score.save()\n id = score._id\n\n response = app.response_class(\n response=json.dumps({'id': str(id)}),\n status=200,\n mimetype='application/json'\n )\n return response\n\n@app.route('/reclamations/', methods=['POST'])\ndef post_reclamations():\n company = request.args['company']\n date = request.args['date']\n \n json_raw = request.get_json()\n\n isValid = validateJSON(json_raw, 'reclamations')\n if not isValid:\n return jsonify({'Formato Invalido', 400})\n\n result = {}\n for key in json_raw:\n json_id = {'_id' : date + company.upper() + key, 'company' : company, 'date' : date}\n json_final = {**json_id, **json_raw['{}'.format(key)]}\n reclamations = ReclameAquiReclamation(**json_final)\n reclamations.save()\n \n result[str(reclamations._id)] = str('ok')\n \n response = app.response_class(\n response=json.dumps(result),\n status=200,\n mimetype='application/json'\n )\n return response\n\n\n@app.route('/scores/', methods=['GET'])\ndef get_scores():\n company = request.args['company']\n\n scores = ReclameAquiScore({\"company\": company})\n scores = scores.query\n \n result = {}\n for score in scores:\n id = score['_id']\n company = score['company']\n date = score['date']\n answered = score['answered']\n reclamations = score['reclamations']\n response_time = score['response_time']\n unanswered = score['unanswered']\n \n result[str(id)] = {'company' : company, \n 'date' : date , \n 'answered' : answered, \n 'reclamations' : reclamations, \n 'response_time' : response_time,\n 'unanswered' : unanswered}\n \n response = app.response_class(\n response=json.dumps(result),\n status=200,\n mimetype='application/json',\n )\n return response\n\n\n@app.route('/reclamations/', methods=['GET'])\ndef get_reclamations():\n company = request.args['company']\n if 'date' in request.args:\n date = request.args['date']\n else:\n date = None\n \n if date is None:\n reclamations = ReclameAquiReclamation({\"company\": company})\n else:\n reclamations = ReclameAquiReclamation({\"company\": company, \"date\": date})\n\n reclamations = reclamations.query\n \n result = {}\n for reclamation in reclamations:\n id = reclamation['_id']\n company = reclamation['company']\n date = reclamation['date']\n description = reclamation['description']\n locale_date = reclamation['locale_date']\n title = reclamation['title']\n \n result[str(id)] = {'company' : company, \n 'date' : date , \n 'description' : description, \n 'locale_date' : locale_date, \n 'title' : title}\n \n response = app.response_class(\n response=json.dumps(result, ensure_ascii=False),\n status=200,\n mimetype='application/json'\n )\n return response\n\n\n@app.route('/scores/', methods=['DELETE'])\ndef delete_scores():\n company = request.args['company']\n if 'date' in request.args:\n date = request.args['date']\n else:\n date = None\n \n if date is None:\n scores = ReclameAquiScore({\"company\": company})\n scores = scores.remove_all\n return jsonify('Deleted')\n \n json_id = {'_id' : date + company.upper()}\n score = ReclameAquiScore(json_id)\n score.remove()\n return jsonify('Deleted')\n\n\n@app.route('/reclamations/', methods=['DELETE'])\ndef delete_reclamations():\n company = request.args['company']\n if 'date' in request.args:\n date = request.args['date']\n else:\n date = None\n \n if date is None:\n reclamations = ReclameAquiReclamation({\"company\": company})\n reclamations = reclamations.remove_all\n return jsonify('Deleted')\n else:\n reclamations = ReclameAquiReclamation({\"company\": company, \"date\": date})\n reclamations = reclamations.remove_all\n return jsonify('Deleted')\n\n\nif __name__ == '__main__':\n try:\n app.run(debug=True, host='0.0.0.0', port=5005)\n except:\n abort(400)\n ","sub_path":"apps/API_persistenciaDados/src/service/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"59392471","text":"\n\ndef string_to_int(s):\n negative = False\n if s[0] == '-':\n del(s[0])\n negative = True\n\n int_value = 0\n place = 1\n mapping = {\"1\":1,\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 \"0\":0\n }\n\n for i in range(len(s)-1, -1, -1):\n char = s[i]\n digit = mapping[char]\n int_value += digit*place\n place *=10\n\n if negative:\n int_value = -int_value\n return int_value\n\n\n\ndef int_to_string(integer):\n if integer < 0:\n negative = True\n integer = -integer\n\n mapping = {1:\"1\", 2:\"2\",3:\"3\", 4:\"4\", 5:\"5\", 6:\"6\", 7:\"7\", 8:\"8\", 9:\"9\", 0:\"0\"}\n\n string = ''\n\n #get total number of digits\n num_digits = 0\n integer_cp = integer\n while integer_cp != 0:\n integer_cp = integer_cp//10\n num_digits +=1\n\n while num_digits > 0:\n rounded_down = 10**(num_digits -1)\n first_digit = integer // rounded_down\n char = mapping[first_digit]\n string = string + char\n\n #remove first digit\n integer = integer - first_digit*(10**(num_digits-1))\n num_digits -=1\n\n if negative:\n string = '-' + string\n\n return string\n\ndef int_to_string2(integer):\n\n negative = False\n if integer < 0:\n negative = True\n integer = -integer\n\n mapping = {1:\"1\", 2:\"2\",3:\"3\", 4:\"4\", 5:\"5\", 6:\"6\", 7:\"7\", 8:\"8\", 9:\"9\", 0:\"0\"}\n string = ''\n\n while integer != 0:\n digit = integer%10\n integer = integer // 10\n char = mapping[digit]\n string = char + string\n\n if negative:\n string = '-' + string\n return string\n\nprint(string_to_int(\"123\"))\n\nprint(string_to_int(\"10930190\"))\nprint()\nprint(int_to_string2(-1209090))\nprint(int_to_string2(10930193809181))","sub_path":"elements/strings/string_to_int.py","file_name":"string_to_int.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"237406830","text":"import fysikkscript as fys\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nplt.style.use('bmh')\r\n\r\ndef rep(old):\r\n new = []\r\n t=0.0\r\n\r\n for x in old:\r\n t=float(x.replace(\",\",\".\"))\r\n new.append(t)\r\n return new\r\n\r\ndef readfile(filename):\r\n data = pd.read_csv(filename, sep= \";\")\r\n t = data[\"t\"]\r\n y = data[\"y\"]\r\n x = data[\"x\"]\r\n x=rep(x)\r\n y=rep(y)\r\n t = rep(t)\r\n return (x,y,t)\r\n\r\n\r\n\r\ndef average_x(xarray_1,xarray_2):\r\n size = 0\r\n avgarray =[]\r\n if len(xarray_1)>len(xarray_2):\r\n size = len(xarray_2)\r\n else:\r\n size = len(xarray_1)\r\n for i in range(size):\r\n avgarray.append((xarray_2[i]+xarray_1[i])/2)\r\n return avgarray\r\n\r\n\r\n\r\n\r\n\r\nx_avg,y_avg,t_avg=readfile(\"v1.txy\")\r\n\r\nfor i in range(2,11):\r\n filename = \"v\"+str(i)+\".txy\"\r\n x,y,t=readfile(filename)\r\n x_avg= average_x(x,x_avg)\r\n y_avg=average_x(y,y_avg)\r\n t_avg=average_x(t,t_avg)\r\n\r\n\r\nprint(\"-----------\")\r\nprint(x_avg[0])\r\nprint(y_avg[0])\r\n\r\n\r\n\r\n\r\n#korrigering\r\n\r\ndef korriger(x_org, y_org):\r\n val= 100.0\r\n for i in range(125):\r\n if fys.yfysikk[i] < val:\r\n val = fys.yfysikk[i]\r\n result1 = np.where(fys.yfysikk == val)\r\n\r\n\r\n coreksx=[]\r\n coreksy=[]\r\n min_point = np.where(y_org ==np.min(y_org) )\r\n\r\n correctiony = val-np.min(y_org)+0.01\r\n correctionx = fys.xfysikk[result1[0][0]]-x_org[min_point[0][0]]\r\n for i in y_org:\r\n coreksy.append(i+correctiony)\r\n for i in x_org:\r\n coreksx.append(i+correctionx)\r\n\r\n return coreksx, coreksy\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"Henter ut alle 10 datasenete med fart og kjører snittet av disse\"\"\"\r\n\r\ndef readfile_v(filename):\r\n data = pd.read_csv(filename, sep= \";\")\r\n t = data[\"t\"]\r\n v = data[\"v\"]\r\n\r\n v=rep(v)\r\n t = rep(t)\r\n return (t,v)\r\n\r\nt_v, v_t = readfile_v(\"v1.v(t)\")\r\n\r\nfor i in range(2,11):\r\n filename = \"v\"+str(i)+\".v(t)\"\r\n t_1,v_1=readfile_v(filename)\r\n t_v= average_x(t_1,t_v)\r\n v_t=average_x(v_1,v_t)\r\n\r\n\r\n\r\n","sub_path":"average.py","file_name":"average.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"476826221","text":"class Node:\n def __init__(self, val):\n self.val = val\n self.next = None\n\n\nclass Stack:\n def __init__(self):\n self.top = None\n\n\n def isEmpty(self):\n return self.top is None\n\n\n def push(self, val):\n if self.isEmpty():\n self.top = Node(val)\n else:\n node = Node(val)\n node.next = self.top\n self.top = node\n\n\n def pop(self):\n if self.isEmpty():\n raise RuntimeError('No item to pop!')\n else:\n val = self.top.val\n self.top = self.top.next\n return val\n\n\n def peek(self):\n if self.isEmpty():\n raise RuntimeError('Empty Stack!')\n\n return self.top.val\n\n\n\nstack = Stack()\nfor i in range(5):\n stack.push(i)\n print(stack.peek())\n\nprint('-----')\n\nfor i in range(6):\n print(stack.pop())\n","sub_path":"CrackCodeInterview/stack_queue/stack_use_linkedlist.py","file_name":"stack_use_linkedlist.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"63181322","text":"#!/usr/bin/env python\n\nimport subprocess\nimport time\n\nIP_LIST = [ 'www.baidu.com',\n 'www.163.com',\n 'www.sohu.com',\n 'www.sina.com.cn']\n\ncmd_stub = 'ping -c 5 {}'\n\n\ndef do_ping(addr):\n print(time.asctime(), \"DOING PING FOR\", addr)\n cmd = cmd_stub.format(addr)\n return subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n\n\nfor domain in IP_LIST:\n do_ping(domain)\n\n","sub_path":"os_soup/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"532416623","text":"import unittest\nimport requests\nimport os\nimport sys\nimport random\n\nsys.path.insert(1, os.path.join(sys.path[0], '..'))\nfrom plugins.engines.jade import Jade\nfrom core.channel import Channel\n\nclass JadeTest(unittest.TestCase):\n\n expected_data = {\n 'language': 'javascript',\n 'engine': 'jade',\n 'eval' : 'javascript' ,\n 'exec' : True,\n 'trailer_tag': '\\n= %(trailer)s\\n',\n 'header_tag': '\\n= %(header)s\\n',\n 'render_tag': '\\n= %(payload)s\\n',\n }\n\n def test_reflection(self):\n \n template = '%s'\n \n channel = Channel({\n 'url' : 'http://127.0.0.1:15004/jade?inj=*'\n })\n Jade(channel).detect()\n del channel.data['os']\n self.assertEqual(channel.data, self.expected_data)\n\n \n def test_reflection_within_text(self):\n template = 'AAAA%sAAAA'\n \n channel = Channel({\n 'url' : 'http://127.0.0.1:15004/jade?inj=*'\n })\n Jade(channel).detect()\n del channel.data['os']\n self.assertEqual(channel.data, self.expected_data)\n ","sub_path":"tests/test_node_jade.py","file_name":"test_node_jade.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"624727926","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nimport pandas as pd\n\nprocessos = {\n 'processo': ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9', 'p10'],\n 'prioridade': [3,2,5,8,3,1,1,4,6,1],\n 'tempo': [300, 250, 100, 200, 250, 150, 100, 200, 300, 200]\n}\n\ndf = pd.DataFrame(data=processos)\ndf = df.sort_values(by=['tempo','prioridade'], ascending=False)\ndf.index = [1,2,3,4,5,6,7,8,9,10]\ndf['processou'] = [0,0,0,0,0,0,0,0,0,0]\n\n\n\n# In[6]:\n\n\ndef escalona_RR():\n global df\n \n print('Nesse exercício a cada quantum a atenção do processador será atribuída ao primeira do fila.')\n print('A cada time sharing a fila será atualizada dando a segunda chance ao processo.')\n print('Cada processo executará 3 quantuns')\n \n print(df)\n \n \n for chance in range(1,4):\n for x in range(1,11): \n a = df.loc[x].at['processo']\n print(\"****Executando Processo \", a,', na chance número ',chance) \n df.at[x, 'processou'] = chance\n print(df)\n\n\n# In[7]:\n\n\nescalona_RR()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"exec_escalonamento.py","file_name":"exec_escalonamento.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"294340101","text":"import importlib\nimport inspect\nimport logging\nimport os\n\nfrom flask import Blueprint, Flask, _request_ctx_stack\nfrom flask_dance.contrib.discord import make_discord_blueprint\nfrom flask_sockets import Sockets\nfrom gunicorn_config import _when_ready as when_ready\n\nfrom pysite.base_route import APIView, BaseView, ErrorView, RedirectView, RouteView, TemplateView\nfrom pysite.constants import (\n CSRF, DEBUG_MODE, DISCORD_OAUTH_AUTHORIZED, DISCORD_OAUTH_ID, DISCORD_OAUTH_REDIRECT,\n DISCORD_OAUTH_SCOPE, DISCORD_OAUTH_SECRET, PREFERRED_URL_SCHEME)\nfrom pysite.database import RethinkDB\nfrom pysite.oauth import OAuthBackend\nfrom pysite.websockets import WS\n\nTEMPLATES_PATH = \"../templates\"\nSTATIC_PATH = \"../static\"\n\n\nclass RouteManager:\n def __init__(self):\n\n # Set up the app and the database\n self.app = Flask(\n __name__, template_folder=TEMPLATES_PATH, static_folder=STATIC_PATH, static_url_path=\"/static\",\n )\n self.sockets = Sockets(self.app)\n\n self.db = RethinkDB()\n self.log = logging.getLogger(__name__)\n self.app.secret_key = os.environ.get(\"WEBPAGE_SECRET_KEY\", \"super_secret\")\n self.app.config[\"SERVER_NAME\"] = os.environ.get(\"SERVER_NAME\", \"pythondiscord.local:8080\")\n self.app.config[\"PREFERRED_URL_SCHEME\"] = PREFERRED_URL_SCHEME\n self.app.config[\"WTF_CSRF_CHECK_DEFAULT\"] = False # We only want to protect specific routes\n\n # Trim blocks so that {% block %} statements in templates don't generate blank lines\n self.app.jinja_env.trim_blocks = True\n self.app.jinja_env.lstrip_blocks = True\n\n # We make the token valid for the lifetime of the session because of the wiki - you might spend some\n # time editing an article, and it seems that session lifetime is a good analogue for how long you have\n # to edit\n self.app.config[\"WTF_CSRF_TIME_LIMIT\"] = None\n\n if DEBUG_MODE:\n # Migrate the database, as we would in prod\n when_ready(output_func=self.db.log.info)\n\n self.app.before_request(self.db.before_request)\n self.app.teardown_request(self.db.teardown_request)\n\n CSRF.init_app(self.app) # Set up CSRF protection\n\n # Load the oauth blueprint\n self.oauth_backend = OAuthBackend(self)\n self.oauth_blueprint = make_discord_blueprint(\n DISCORD_OAUTH_ID,\n DISCORD_OAUTH_SECRET,\n DISCORD_OAUTH_SCOPE,\n login_url=DISCORD_OAUTH_REDIRECT,\n authorized_url=DISCORD_OAUTH_AUTHORIZED,\n redirect_to=\"main.auth.done\",\n backend=self.oauth_backend\n )\n self.log.debug(f\"Loading Blueprint: {self.oauth_blueprint.name}\")\n self.app.register_blueprint(self.oauth_blueprint)\n self.log.debug(\"\")\n\n # Load the main blueprint\n self.main_blueprint = Blueprint(\"main\", __name__)\n self.log.debug(f\"Loading Blueprint: {self.main_blueprint.name}\")\n self.load_views(self.main_blueprint, \"pysite/views/main\")\n self.load_views(self.main_blueprint, \"pysite/views/error_handlers\")\n self.app.register_blueprint(self.main_blueprint)\n self.log.debug(\"\")\n\n # Load the subdomains\n self.subdomains = [\"api\", \"staff\", \"wiki\"]\n\n for sub in self.subdomains:\n try:\n sub_blueprint = Blueprint(sub, __name__, subdomain=sub)\n self.log.debug(f\"Loading Blueprint: {sub_blueprint.name}\")\n self.load_views(sub_blueprint, f\"pysite/views/{sub}\")\n self.app.register_blueprint(sub_blueprint)\n except Exception:\n logging.getLogger(__name__).exception(f\"Failed to register blueprint for subdomain: {sub}\")\n\n # Load the websockets\n self.ws_blueprint = Blueprint(\"ws\", __name__)\n\n self.log.debug(\"Loading websocket routes...\")\n self.load_views(self.ws_blueprint, \"pysite/views/ws\")\n self.sockets.register_blueprint(self.ws_blueprint, url_prefix=\"/ws\")\n\n self.app.before_request(self.https_fixing_hook) # Try to fix HTTPS issues\n\n def https_fixing_hook(self):\n \"\"\"\n Attempt to fix HTTPS issues by modifying the request context stack\n \"\"\"\n\n if _request_ctx_stack is not None:\n reqctx = _request_ctx_stack.top\n reqctx.url_adapter.url_scheme = PREFERRED_URL_SCHEME\n\n def run(self):\n from gevent.pywsgi import WSGIServer\n from geventwebsocket.handler import WebSocketHandler\n\n server = WSGIServer(\n (\"0.0.0.0\", int(os.environ.get(\"WEBPAGE_PORT\", 8080))), # noqa: B104, S104\n self.app, handler_class=WebSocketHandler\n )\n server.serve_forever()\n\n def load_views(self, blueprint, location=\"pysite/views\"):\n for filename in os.listdir(location):\n if os.path.isdir(f\"{location}/{filename}\"):\n # Recurse if it's a directory; load ALL the views!\n self.load_views(blueprint, location=f\"{location}/{filename}\")\n continue\n\n if filename.endswith(\".py\") and not filename.startswith(\"__init__\"):\n module = importlib.import_module(f\"{location}/{filename}\".replace(\"/\", \".\")[:-3])\n\n for cls_name, cls in inspect.getmembers(module):\n if (\n inspect.isclass(cls) and\n cls is not BaseView and\n cls is not ErrorView and\n cls is not RouteView and\n cls is not APIView and\n cls is not WS and\n cls is not TemplateView and\n cls is not RedirectView and\n (\n BaseView in cls.__mro__ or\n WS in cls.__mro__\n )\n ):\n cls.setup(self, blueprint)\n self.log.debug(f\">> View loaded: {cls.name: <15} ({module.__name__}.{cls_name})\")\n","sub_path":"pysite/route_manager.py","file_name":"route_manager.py","file_ext":"py","file_size_in_byte":6106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"193814687","text":"__author__ = 'kurakar'\n\nfrom django import forms\nfrom questions.models import questions, category\n\n\nclass candidateResponseForm(forms.Form):\n categoryCode = forms.CharField(max_length=55)\n questionID = forms.CharField(max_length=55)\n\n def clean_category_code(self):\n category_code = self.cleaned_data['categoryCode']\n if category.objects.filter(categoryCode=category_code).count():\n return category_code\n else:\n raise forms.ValidationError('Category doesnot exist')\n\n def clean_question_set_id(self):\n question_set_id = self.cleaned_data['questionID']\n if questions.objects.filter(questionSetID=question_set_id).count():\n return question_set_id\n else:\n raise forms.ValidationError('Question Set doesnot exist')\n","sub_path":"results/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"155107731","text":"\n\n#calss header\nclass _TARPAULIN():\n\tdef __init__(self,): \n\t\tself.name = \"TARPAULIN\"\n\t\tself.definitions = [u'(a large piece of) heavy waterproof cloth used as a covering']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_tarpaulin.py","file_name":"_tarpaulin.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"95068340","text":"from typing import Optional\n\nfrom starlette.exceptions import HTTPException\nfrom starlette.status import HTTP_404_NOT_FOUND\n\nfrom ..crud.user import get_user\nfrom ..db.mongodb import AsyncIOMotorClient\nfrom ..core.config import database_name, station_collection_name\nfrom ..models.station import Station,StationInDB, StationInCreate, StationInUpdate \n\n\nasync def get_station(\n conn: AsyncIOMotorClient,\n target_username: str, \n current_username: Optional[str] = None\n ) -> Station:\n user = await get_user(conn, target_username)\n if not user:\n raise HTTPException(\n status_code=HTTP_404_NOT_FOUND, detail=f\"User {target_username} not found\"\n )\n station = Station(**user.dict())\n station.following = await is_following_for_user(\n conn, current_username, target_username\n )\n return station\n\n\nasync def create_station(\n conn: AsyncIOMotorClient, \n station: StationInCreate,\n ) -> StationInDB:\n dbstation = StationInDB(**station.dict()) \n dbstation.id = row.inserted_id\n dbstation.created_at = ObjectId(dbstation.id ).generation_time\n dbstation.updated_at = ObjectId(dbstation.id ).generation_time\n row = await conn[database_name][station_collection_name].insert_one(dbsensor.dict())\n return dbstation \n\n\n\nasync def update_station(\n conn: AsyncIOMotorClient, \n sensor: StationInUpdate\n ) -> StationInDB:\n dbstation = StationInUpdate(**sensor.dict()) \n dbstation.id = row.inserted_id\n dbstation.created_at = ObjectId(dbstation.id ).generation_time\n dbstation.updated_at = ObjectId(dbstation.id ).generation_time\n row = await conn[database_name][station_collection_name].update_one({\"username\": dbuser.username}, {'$set': dbsensor.dict()})\n return dbstation \n\n \n\nasync def delete_sensor(conn: AsyncIOMotorClient, id: int, username: str):\n await conn[database_name][station_collection_name].delete_many({\"id\": id, \"username\": username})","sub_path":"app/crud/station.py","file_name":"station.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"276835089","text":"from test_socket import server, client\nimport sys, os\nfrom threading import Thread\n\nmode = sys.argv[1]\nif mode == 's':\n\tserver()\nelif mode == 'c':\n\tclient('client: process = %d' %os.getpid())\nelse:\n\tfor i in range(7):\n\t\tThread(target = client, args = ('client: thread = %d' %i,)).start()\n\t\t\n\n\n\n","sub_path":"old/Python/OLD/OLD/IPC/socket/test_socket2.py","file_name":"test_socket2.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"227499403","text":"import requests\nimport sys\nimport cloud_api\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\n\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\ndebug_mode = False\n\nif debug_mode is False:\n\n abc_prefix = sys.argv[1]\n abc_login = sys.argv[2]\n abc_group_name = sys.argv[3]\n abc_group_type = sys.argv[4]\n user_login = sys.argv[5]\n\n if len(sys.argv) == 7:\n number_of_groups = sys.argv[6]\n elif len(sys.argv) == 6:\n number_of_groups = '1'\n else:\n cloud_api.usage_example(sys.argv[0])\n sys.exit()\n\nelse:\n abc_prefix = \"cloud\"\n abc_login = \"testlogin\"\n abc_group_name = \"testname\"\n abc_group_type = \"customer\"\n user_login = \"testuser\"\n\n# Define group type - customer or partner\ngroup_kind = cloud_api.define_group_type(abc_group_type)\nsession = requests.Session() # Create new session\ncloud_api.session = session # Transfer variable to cloud_api\nabc_url = cloud_api.define_dc(abc_prefix, abc_login) # Define full URL to perform requests\ncloud_api.abc_url = abc_url # Transfer variable to cloud_api\nadmin_group_id = cloud_api.abc_login(abc_login) # Get ID of partner group\nstorage_name = cloud_api.define_storage(admin_group_id)\n\nif number_of_groups:\n # Configure JSON for all required operations for cycle\n for group_number in range(1, int(number_of_groups) + 1):\n cloud_api.json_config(cloud_api.cred_json, cloud_api.group_json, cloud_api.activate_json, cloud_api.user_json,\n cloud_api.admin_json, abc_login,\n abc_group_name + \".\" + str(group_number),\n user_login + \".\" + str(group_number))\n\n created_group_id = cloud_api.create_group(admin_group_id, cloud_api.group_json, abc_group_name)\n user_id, user_version = cloud_api.create_admin(abc_group_type, created_group_id,\n cloud_api.user_json, cloud_api.admin_json)\n\n jwt_token = cloud_api.get_jwt(cloud_api.user_json, user_id)\n cloud_api.activate_user(jwt_token, cloud_api.user_act_json)\n print(\"{0}. Group {1} (ID={2}) and user (ID={3}) were created\".format(group_number, abc_group_name,\n created_group_id, user_id))\n print(\"------------------------------------------------------------------\")\nelse:\n # Configure JSON for all required operations withou cycle\n cloud_api.json_config(cloud_api.cred_json, cloud_api.group_json, cloud_api.activate_json, cloud_api.user_json,\n cloud_api.admin_json, abc_login, abc_group_name, user_login)\n\n created_group_id = cloud_api.create_group(admin_group_id, cloud_api.group_json, abc_group_name)\n user_id, user_version = cloud_api.create_admin(abc_group_type, created_group_id,\n cloud_api.user_json, cloud_api.admin_json)\n\n jwt_token = cloud_api.get_jwt(cloud_api.user_json, user_id)\n cloud_api.activate_user(jwt_token, cloud_api.user_act_json)\n print(\"Group {1} (ID={2}) and user (ID={3}) were created\".format(abc_group_name, created_group_id, user_id))\n print(\"------------------------------------------------------------------\")\n","sub_path":"abc_scripts/abc_group_create.py","file_name":"abc_group_create.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"513339283","text":"#import MySQLdb for connection to our db.\nimport MySQLdb\n\n\n#define connection to our MySQL db.\nconnection = MySQLdb.connect(host = \"localhost\", user = \"root\", passwd = \"mysql123\", db = \"pizza\")\ncur = connection.cursor()\n\nfinal = open(\"The Cicilian's.20130201.csv\", 'r')\n\ncur.execute(\"INSERT INTO STORES (STORE_NAME) VALUES('Tiny Pizzas');\")\nSTORE_ID = cur.lastrowid\nconnection.commit()\n\ncur_pizzas = []\ncur_drivers = []\ncur_customers = []\n\noutFile = open('temp.csv','w')\n\nlines = []\n\nadd_pizzas = []\n\nwith final as f:\n for line in f:\n lines.append(line)\n\n thisSplit = line.split(',')\n\n pizza = thisSplit[9]\n\n toppings = thisSplit[10:]\n toppingsFormatted = ''\n for i in xrange(len(toppings)):\n total = toppings[i].strip('\\r')\n total = toppings[i].strip('\\n')\n toppingsFormatted += total\n if i != len(toppings)-1:\n toppingsFormatted += ', '\n\n found = False\n for tuple in add_pizzas:\n if pizza == tuple[0]:\n found = True\n\n if (not found):\n add_pizzas.append((pizza, toppingsFormatted))\n\nfor tuple in add_pizzas:\n cur.execute(\"INSERT INTO PIZZAS (STORE_ID, PIZZA_NAME, PIZZA_TOPPINGS) VALUES(%s,%s,%s);\", (STORE_ID, tuple[0], tuple[1]))\n \n\n\ncompleted = []\n\nfor i in xrange(len(lines)):\n if (i < len(lines)-1):\n curSplit = lines[i].split(',')\n nextSplit = lines[i+1].split(',')\n if curSplit[0] not in completed:\n if curSplit[0] == nextSplit[0]:\n # Duplicate ids\n pizza = nextSplit[9]\n\n curLen = 0\n for j in xrange(len(curSplit[10:])):\n curLen += len(curSplit[10:][j])\n curLen += 2\n\n outLine = lines[i][:-curLen] + ', ' + pizza + '\\n'\n outFile.write(outLine)\n completed.append(curSplit[0])\n else:\n curLen = 0\n for j in xrange(len(curSplit[10:])):\n curLen += len(curSplit[10:][j])\n curLen += 2\n\n outLine = lines[i][:-curLen] + '\\n'\n outFile.write(outLine)\n completed.append(curSplit[0])\n\noutFile.close()\n\nfresh = open('temp.csv','r')\n\n\nwith fresh as f:\n for line in f:\n result = line.split(',')\n ORDER_ID = result[0]\n driver = result[3]\n ORDER_DATE = result[1] + result[2]\n customer = result[4]\n address = result[5]+ ' ' + result[6] + ' ' + result[7]+', '+result[8]\n PIZZA_NAME = result[9]\n for name in result[10:]:\n PIZZA_NAME += ', '\n PIZZA_NAME += name\n\n # toppings = result[10:]\n # toppingsFormatted = ''\n # for i in xrange(len(toppings)):\n # line = toppings[i].strip('\\r')\n # line = toppings[i].strip('\\n')\n # toppingsFormatted += line\n # if i != len(toppings)-1:\n # toppingsFormatted += ', '\n\n # print \"Order ID: \" + ORDER_ID\n # print \"Driver: \" + driver\n # print \"Date: \" + ORDER_DATE\n # print \"Customer: \" + customer\n # print \"Address: \" + address\n # print \"Pizzas: \" + PIZZA_NAME\n # print \"Toppings: \" + toppingsFormatted\n\n\n DRIVER_ID = -1\n for driver_tuple in cur_drivers:\n if driver_tuple[0] == driver:\n DRIVER_ID = driver_tuple[1]\n\n if DRIVER_ID == -1:\n cur.execute(\"INSERT INTO DRIVERS (DRIVER_NAME, DRIVER_STORE_ID) VALUES(%s,%s);\", (driver, STORE_ID))\n DRIVER_ID = cur.lastrowid\n connection.commit()\n cur_drivers.append((driver, DRIVER_ID))\n\n CUSTOMER_ID = -1\n for customer_tuple in cur_customers:\n if customer_tuple[0] == customer:\n if customer_tuple[1] == address:\n CUSTOMER_ID = customer_tuple[2]\n\n if CUSTOMER_ID == -1:\n # Insert customer into db\n cur.execute(\"INSERT INTO CUSTOMERS (CUSTOMER_NAME, CUSTOMER_ADDRESS) VALUES(%s,%s);\", (customer, address))\n CUSTOMER_ID = cur.lastrowid\n connection.commit()\n cur_customers.append((customer, address, CUSTOMER_ID))\n\n cur.execute(\"INSERT INTO ORDERS (ORDER_ID, CUSTOMER_ID, ORDER_DATE, STORE_ID, PIZZA_NAMES) VALUES(%s,%s,%s,%s,%s);\", \n (ORDER_ID, CUSTOMER_ID, ORDER_DATE, STORE_ID, PIZZA_NAME))\n connection.commit()\n\n # PIZZA_ID = -1\n # for pizza_tuple in cur_pizzas:\n # if pizza_tuple == PIZZA_NAME:\n # PIZZA_ID = 1\n\n # if PIZZA_ID == -1:\n # # We need to insert this pizza\n # cur.execute(\"INSERT INTO PIZZAS (STORE_ID, PIZZA_NAME, PIZZA_TOPPINGS) VALUES(%s,%s,%s);\", (STORE_ID, PIZZA_NAME, toppingsFormatted))\n # connection.commit()\n # cur_pizzas.append(PIZZA_NAME)\n","sub_path":"data/TheCicilians/Cicilians.py","file_name":"Cicilians.py","file_ext":"py","file_size_in_byte":4925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"571277415","text":"\nprint(\"!! 최초 실행시 약간의 로딩이 발생할 수 있으니 잠시만 기다려주세요!(최대 1분)\")\nprint(\"인터넷 연결이 되어있어야 합니다!!\" )\nimport os\nfrom bs4 import BeautifulSoup\nimport urllib.parse as rep\nimport urllib.request as req\nfrom fake_useragent import UserAgent\nimport time as t\n\n# 헤더 정보 초기화\nopener = req.build_opener()\n# User Agent 정보\nopener.addheaders = [('User-agent', UserAgent().ie)]\n# 헤더 정보 삽입\nreq.install_opener(opener)\n\n# 네이버 이미지 기본 URL\nbase = 'https://search.naver.com/search.naver?where=image&sm=tab_jum&query='\n\nprint(\"\\n### 검색어를 입력하시면 해당 검색어에 맞는 이미지를 50개 다운로드 받습니다.\")\nprint(\"### 이미지 자료는 네이버 검색자료를 수집합니다.\")\nprint(\"### 다운받은 이미지는 C드라이브 imagedown폴더에 자동 저장됩니다.\")\n\n# 검색어\ns = input(\"### 검색어 입력: \")\nquote = rep.quote_plus(s)\n# URL 완성\nurl = base + quote\n\n# 요청 url 확인\n# print(\"req url:\",url)\n\n# Request\nres = req.urlopen(url)\n\n# 이미지 저장 경로\nsavePath = \"C:/imagedown/\"\n\n# 폴더 생성 예외처리\ntry:\n # 기존 폴더 있는지 체크\n if not os.path.isdir(savePath):\n # 없으면 폴더 생성\n os.mkdir(savePath)\nexcept OSError as e:\n print(\"folder creation failed.\")\n print(\"folder name: {}\".format(e.filename))\n\n #런타임 에러\n raise RuntimeError(\"System exit!\")\n\nelse:\n # 폴더 생성이 되었거나, 존재할 경우\n print(\"folder created\")\n\n\n# bs4 초기화\nsoup = BeautifulSoup(res, 'html.parser')\n\n# print(soup.prettify())\n\n# select 사용\nimg_list = soup.select('div.img_area > a.thumb._thumb > img')\n# print(img_list)\n\nfor i, img in enumerate(img_list, 1):\n # 속성 확인\n # print(img, i)\n \n # 저장 파일명 및 경로\n full_file_name = os.path.join(savePath, savePath + str(i) + '.png')\n\n # 파일명\n # print(full_file_name)\n\n # 다운로드 요청\n req.urlretrieve(img['data-source'], full_file_name)\n\n\n# 다운 완료\nprint(\"download success!\")\n\n\npath = os.path.realpath(savePath)\nos.startfile(path)\n\nprint(\"5초 뒤 자동 종료됩니다!\")\nt.sleep(5)\n\n","sub_path":"Day07/자동 이미지 수집.py","file_name":"자동 이미지 수집.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"110746212","text":"import multiprocessing\nimport fire\nimport os\nimport time\nimport datetime\nimport signal\nimport sys\nimport recorder\nimport json\n\nopenChannels = {}\n\ndef start():\n with open('config.json') as file:\n config = json.load(file)\n for item in config.get('record'):\n host = item.get('host')\n for channel in item.get('channels'):\n scheduleChannel(host, channel, config)\n\ndef scheduleChannel(host, channel, config):\n print(\"[{}] Starting...\".format(channel))\n storagePath = config.get('storagePath')\n quality = config.get('quality')\n retryInterval = config.get('retryInterval')\n videoFormat = config.get('videoFormat')\n x = multiprocessing.Process(target=startChannel, args=(host, channel, storagePath, quality, retryInterval, videoFormat))\n x.start()\n\ndef startChannel(host, channel, storagePath=\"storage\", quality=\"720p,480p\", retryInterval=60, videoFormat=\"mp4\"):\n openChannels[channel] = recorder.Recorder(host, channel, storagePath, quality, retryInterval, videoFormat)\n openChannels[channel].start()\n\ndef signal_handler(sig, frame):\n print('Killing all recorders gracefully...')\n for k in openChannels.keys():\n openChannels[k].stop()\n time.sleep(5)\n sys.exit(0)\n\nsignal.signal(signal.SIGINT, signal_handler)\n\nif __name__ == '__main__':\n fire.Fire()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"34689163","text":"import random\n\ns = int(input())\nrandom.seed(s)\t\nn = 1000\na = []\nfor i in range(n):\n\ta.append(random.randint(0, 1000))\na = list(map(str, a))\t\nprint(n)\t\nprint(' '.join(a))\t\n","sub_path":"tureochtrad/data/generator.py3","file_name":"generator.py3","file_ext":"py3","file_size_in_byte":171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"622721593","text":"from scrapy import Spider, Request\n\nfrom selenium import webdriver\n\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nfrom selenium.webdriver.support import expected_conditions as ec\n\nfrom selenium.webdriver.common.by import By\n\nfrom os import getcwd, path, makedirs\n\nfrom time import sleep\n\n__all__ = ['Data']\n\n# It is also possible to download the files through the id\n# of the document, present in the body tag, and the URL:\n#\n# https://data.gov.in/node/id/download\n#\n# Try to don't resize the window in a way that Selenium\n# can't scroll, e.g extreme small in the vertical axis\n#\n# If the IP its blocked, there are 3 main ways to fix this\n# issue:\n#\n# 1. Configure the network to change its external IP\n#\n# 2. Configure the Requests package, before make any request https://stackoverflow.com/questions/23013220/max-retries-exceeded-with-url-in-requests\n#\n# 3. Change the IP dynamically using the Scrapy and a Proxy https://stackoverflow.com/questions/28852057/change-ip-address-dynamically\n\n\nclass Data(Spider):\n name = 'Data'\n\n start_urls = [\n r'https://data.gov.in/search/site?query=maharajganj&field_search=title%5E2&item=10&exact_match=1'\n ]\n\n base = 'https://data.gov.in'\n\n def __init__(self):\n self.driver = webdriver.Chrome(\n executable_path=path.join(getcwd(), 'chromedriver'),\n chrome_options=Data.chrome_options()\n )\n\n @classmethod\n def check_folder(cls, name):\n folder_path = path.join(getcwd(), name)\n\n if not path.exists(folder_path):\n makedirs(folder_path)\n\n print(f'Folder {name} created')\n\n return\n\n print(f'Folder {name} already exists')\n\n @classmethod\n def chrome_options(cls):\n Data.check_folder('csv')\n\n options = webdriver.ChromeOptions()\n\n preferences = {\n # Define the folder to save file (s)\n 'download.default_directory': path.join(getcwd(), 'csv'),\n # Disable image (s) download\n 'profile.managed_default_content_settings.images': 2,\n # Enable disk cache\n 'profile.managed_default_content_settings.images': 2,\n # Set disk cache size\n 'disk-cache-size': 4096\n }\n\n options.add_experimental_option('prefs', preferences)\n\n return options\n\n def parse(self, response):\n links = response.xpath('//div[@class=\\'row\\']//h3//a/@href').getall()\n\n # Get CSV files\n for link in links:\n self.driver.get(link)\n\n sleep(1)\n\n # Click on CSV banner\n self.driver.find_element_by_xpath(\n '//html/body/div[1]/div[1]/div/div[7]/div/div[2]/section/div/div/div/div/div/article/div/div/div[2]/div/div[1]/div/div[2]/div/a'\n ).click()\n\n # Click on usage type (non-commercial)\n WebDriverWait(self.driver, 5).until(\n ec.visibility_of_element_located(\n (By.XPATH, '/html/body/div[1]/div[1]/div/div[7]/div/div[2]/section/div/div/div/div/div/article/div/div/div[2]/div/div[1]/div/div[2]/div[2]/div[2]/form/div/div[4]/div/div[2]/label')\n )\n ).click()\n\n # Click on purpose (academia)\n self.driver.find_element_by_xpath(\n '/html/body/div[1]/div[1]/div/div[7]/div/div[2]/section/div/div/div/div/div/article/div/div/div[2]/div/div[1]/div/div[2]/div[2]/div[2]/form/div/div[5]/div/div[1]'\n ).click()\n\n # Click on submit\n self.driver.find_element_by_xpath(\n '//*[@id=\\'edit-submit\\']'\n ).click()\n\n # Wait the download page to load. Decrease the value if your internet its fast\n sleep(3)\n\n # Close opened window\n if len(self.driver.window_handles) > 1:\n window_before = self.driver.window_handles[0]\n\n window_after = self.driver.window_handles[1]\n\n self.driver.switch_to_window(window_after)\n\n self.driver.close()\n\n self.driver.switch_to_window(window_before)\n\n # Go to next page\n next_page = response.xpath(\n '/html/body/div[1]/div[1]/div/div[7]/div[1]/div/section/div/div/div/div/div/div/div[3]/div/ul/li/a[@class=\\'pager-item-next\\']/@href'\n ).getall()[-1]\n\n if next_page:\n next_page_url = Data.base + next_page\n\n yield Request(next_page_url, dont_filter=True)\n \n # Quit the driver\n driver.quit()","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"140232461","text":"from src import *\nfrom discord.ext import commands\nimport discord\n\nclass KdCommand(commands.Cog):\n def __init__(self, client: commands.Bot):\n self.client = client\n\n @commands.Cog.listener()\n async def on_message(self, message: discord.Message):\n if isinstance(message.channel, discord.TextChannel):\n command = isCommand(message.content, ('k', 'kd'))\n\n if command[0]:\n finalp = None\n if len(message.mentions) == 1:\n if not db.exists(id=message.mentions[0].id, active=True):\n await message.channel.send(embed=eEmbed('Error', f'El usuario {str(message.mentions[0])} no tiene ninguna cuenta vinculada'))\n else:\n entry = db.searchone(id=message.mentions[0].id)\n\n player = check_player(entry['username'])\n\n if not player[0]:\n await message.channel.send(embed=eEmbed('Error', f'La cuenta que tiene {str(message.mentions[0])} no corresponde a ninguna cuenta de fortnite'))\n else:\n finalp = player[0], player[1], entry['platform'], entry['platformstr']\n typ = 1\n\n elif command[1]:\n player = check_player(command[2])\n\n if not player[0]:\n await message.channel.send(embed=eEmbed(\n 'Error',\n 'El nombre de usuario introducido no corresponde a ninguna cuenta de Fortnite'\n ))\n else:\n finalp = player\n typ = 3\n\n else:\n if not db.exists(id=message.author.id, active=True):\n await message.channel.send(embed=eEmbed(\n 'Error',\n 'No tienes ninguna cuenta vinculada'\n ))\n else:\n entry = db.searchone(id=message.author.id)\n\n player = check_player(entry['username'])\n\n if not player[0]:\n await message.channel.send(embed=eEmbed(\n 'Error',\n 'El nombre de usuario vinculado no corresponde a ninguna cuenta de Fortnite'\n ))\n else:\n finalp = player[0], player[1], entry['platform'], entry['platformstr']\n typ = 2\n\n if finalp and finalp[0]:\n stats = brstats(finalp[1], finalp[2])\n \n if typ == 2:\n kd = float(stats[1][11]['value'])\n\n if kd > 6.0:\n role = message.guild.get_role(573527081447587844)\n elif kd >= 5.0:\n role = message.guild.get_role(573527011973398528)\n elif kd >= 4.0:\n role = message.guild.get_role(573526927512698900)\n elif kd >= 3.0:\n role = message.guild.get_role(573526857153118238)\n elif kd >= 2.0:\n role = message.guild.get_role(573526610582700032)\n elif kd >= 1.0:\n role = message.guild.get_role(573526247020429322)\n elif kd < 1.0:\n role = message.guild.get_role(573526157132038145)\n \n roleids = [573527081447587844, 573527011973398528, 573526927512698900, 573526857153118238, 573526610582700032, 573526247020429322, 573526157132038145]\n\n for erole in message.author.roles:\n if erole.id in roleids and erole != role: await message.author.remove_roles(erole)\n \n if not role in message.author.roles and kd <= 12: \n await message.author.add_roles(role)\n await message.channel.send(embed=eEmbed(\n 'Se te ha añadido un rol por tu kd',\n 'Rol: ' + str(role.name)\n ))\n\n route = kdImage(stats)\n\n with open(route, 'rb') as f:\n file = discord.File(f, finalp[1] + 'Stats.png')\n f.close()\n\n await message.channel.send(file=file)\n\n deleteImage(route)\n\n if float(stats[1][11]['value']) > 12:\n if not typ == 3:\n await message.channel.send(embed=eEmbed('No apareceras en el top del servidor', 'Tienes un kd desproporcional'))\n\ndef setup(client):\n client.add_cog(KdCommand(client))","sub_path":"modules/stats/kd.py","file_name":"kd.py","file_ext":"py","file_size_in_byte":5181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"612873064","text":"import os\nfrom socket import *\nhost = \"192.168.0.108\" # set to IP address of target computer\nport = 1497\naddr = (host, port)\nUDPSock = socket(AF_INET, SOCK_DGRAM)\nwhile True:\n data = bytes(input(\"Enter message to send or type 'exit': \"), \"utf-8\")\n UDPSock.sendto(data, addr)\n if data == \"exit\":\n UDPSock.close()\n os._exit(0)\n break\nUDPSock.close()\nos._exit(0)\n","sub_path":"py_game_project/net_client.py","file_name":"net_client.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"281844262","text":"import sys, os\n\nfrom PyQt5.QtWidgets import QApplication, QWidget\nfrom PyQt5.QtCore import QRect, Qt, QPoint\nfrom PyQt5.QtGui import QPainter, QFont\n\nimport main, static\n\nD = static.D\nR = static.R\n\n\ndef draw_some_dot():\n yield (QPoint(2 * D, 3 * D), R // 4, R // 4)\n yield (QPoint(8 * D, 3 * D), R // 4, R // 4)\n yield (QPoint(2 * D, 8 * D), R // 4, R // 4)\n yield (QPoint(8 * D, 8 * D), R // 4, R // 4)\n for i in range(1, 10, 2):\n yield (QPoint(i * D, 4 * D), R // 4, R // 4)\n yield (QPoint(i * D, 7 * D), R // 4, R // 4)\n\n\nclass Example(QWidget):\n def __init__(self, parent=None):\n super().__init__(parent=parent)\n\n self.memory = -1\n self.side = None\n self.turn_move = False # False红方,True代表黑方\n self.preces = static.board[:]\n\n self.setGeometry(200, 200, 500, 550)\n self.setWindowTitle(\"中国象棋\")\n\n self.show()\n\n def paintEvent(self, e):\n if self.side:\n self.preces = self.preces[::-1]\n\n q = QPainter(self)\n q.setFont(QFont(\"system\", R * 1.3, 1100, False))\n q.drawText(QRect(D * 2, D * 5, D * 2, D), Qt.AlignHCenter | Qt.AlignVCenter, \"楚河\")\n q.drawText(QRect(D * 6, D * 5, D * 2, D), Qt.AlignHCenter | Qt.AlignVCenter, \"汉界\")\n\n for i in static.draw_some_line():\n q.drawLine(*i)\n\n q.setBrush(Qt.black)\n for i in draw_some_dot():\n q.drawEllipse(*i)\n\n for i, v in enumerate(self.preces):\n _x, _y = main.index_2_pos(i)\n if not v:\n continue\n if v < 0:\n q.setBrush(Qt.gray)\n else:\n q.setBrush(Qt.black) if v // 32 else q.setBrush(Qt.red) # v//32,黑方1,红方0\n\n q.setPen(Qt.gray)\n q.drawEllipse(QPoint(_x + R, _y + R), R, R)\n\n q.setPen(Qt.white)\n q.setFont(QFont(\"楷体\", R * 1.5, 1500, False))\n\n member = static.members[f\"p{abs(v)}\"]\n q.drawText(QRect(_x, _y, D, D), Qt.AlignHCenter | Qt.AlignVCenter, member.name)\n\n def mouseReleaseEvent(self, e):\n POS = main.in_board(e.pos().x(), e.pos().y())\n ID = main.pos_2_index(POS)\n main.move_stone(self, ID)\n # if main.can_move(ID):\n # main.move_stone(self, ID)\n self.update()\n\n os.system('clear')\n print(f\"{main.show_board(self.preces)}\")\n\n def restart(self, side):\n self.side = self.side\n self.preces = static.board[:] if side else static.board[::-1]\n self.turn_move = False\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = Example()\n ex.side = 0\n\n app.exit(app.exec_())\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"604103113","text":"from XmlGenerator import XMLGenerator\nfrom MyExcel import MyExcel\nfrom MySvn import MySvn\nfrom MyTxt import MyTxt\nimport os\nimport shutil\n\nfile = r\"‪F:\\Github\\python\\excel-in-python\\day.xlsx\"\na = MyExcel(file)\nsheet_name = \"clock_cli\"\ncolumn_name = \"A\"\ncount = a.read_rows(sheet_name, column_name)\n\ntxtpath = r\"‪F:\\Github\\python\\excel-in-python\"\ntxtname = \"result\"\nresult_txt = MyTxt(txtpath, txtname)\n\nsvnC = MySvn()\n\nprint(count)\n\n\ndef generate_svn_script(files, log=True):\n if log:\n result_txt.text_write(\"(\", True)\n filescount = len(files)\n print(filescount)\n for i in range(1, filescount):\n msg = svnC.svnclient + ' lock \"' + files[i] + '\"' + '\\n'\n print(files[i])\n result_txt.text_write(msg)\n if log:\n svnlog = \"log.txt\"\n endmsg = \")>\" + svnlog + \" 2>&1 Collatz.tmp\n\n% diff Collatz.tmp Collatz.out\n\"\"\"\n\n\"\"\" ----------------------------------------------------------------------\nRedefine collatz_eval() such that it takes a generator of integer pairs\nand produces a generator of integer triples.\n\nRedefine collatz_print() such that it takes a generator of integer\ntriples and produces a generator of strings.\n\"\"\"\n\nfrom sys import stdin, stdout\n\ndef collatz_read (r) :\n return ([int(v) for v in s.split()] for s in r)\n\ndef cycle_length (n) :\n assert n > 0\n c = 1\n while n > 1 :\n if (n % 2) == 0 :\n n = (n / 2)\n else :\n n = (3 * n) + 1\n c += 1\n assert c > 0\n return c\n\ndef collatz_eval (i, j) :\n v = 0\n for n in range(i, j + 1) :\n c = cycle_length(n)\n if c > v :\n v = c\n return v\n\ndef collatz_print (w, i, j, v) :\n w.write(str(i) + \" \" + str(j) + \" \" + str(v) + \"\\n\")\n\ndef collatz_solve (r, w) :\n for a in collatz_read(r) :\n i, j = a\n v = collatz_eval(i, j)\n collatz_print(w, i, j, v)\n\nif __name__ == '__main__' :\n collatz_solve(stdin, stdout)\n","sub_path":"exercises/Collatz3.py","file_name":"Collatz3.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"493787836","text":"# Import the xmltodict library\nimport xmltodict\n\n# Open thet sample xml file and read it into variable\nwith open(\"xml_example.xml\") as f:\n xml_example = f.read()\n\n# Print the raw XML data\nprint(\"Raw XML data:\\n\", xml_example)\n\n# Parse the XML into a Python dictionary\nxml_dict = xmltodict.parse(xml_example)\n\n# Save the interface name into a variable using\n# XML nodes as keys\ninterface_name = xml_dict[\"interface\"][\"name\"]\n\n# Print the interface name\nprint(\"\\nInterface name:\\n\", interface_name)\n\n# Change the IP address of the interface\nxml_dict[\"interface\"][\"ipv4\"][\"address\"][\"ip\"] = \"192.168.0.2\"\n\n# Revert to the XML string version of the dictionary\nprint(\"\\nModified XML data:\\n\", xmltodict.unparse(xml_dict))","sub_path":"xml/xml_example.py","file_name":"xml_example.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"364879604","text":"import json\n\n\n# Dict-based in-memory storage.\nclass Storage:\n\n\tdef __init__(self):\n\t\tself.storage = {}\n\n\tdef _find(self, typ_, user_id, course_name):\n\t\tif user_id not in self.storage:\n\t\t\treturn None\n\t\tdata = self.storage[user_id][typ_]\n\t\tfor item in data:\n\t\t\tcurrent = set(item['name'].lower().split())\n\t\t\tpassed = set(course_name.lower().split())\n\t\t\tif current.issubset(passed) or current.issuperset(passed):\n\t\t\t\treturn item\n\t\treturn None\n\n\tdef add_user(self, user_id):\n\t\tself.storage[user_id] = {\n\t\t\t'exams': [],\n\t\t\t'credits': []\n\t\t}\n\t\t\n\tdef has_user(self, user_id):\n\t\treturn user_id in self.storage\n\t\n\tdef has_exam(self, user_id, exam_info):\n\t\treturn self._find('exams', user_id, exam_info[0].strip().lower()) is not None\n\t\n\tdef has_credit(self, user_id, credit_info):\n\t\treturn self._find('credits', user_id, credit_info[0].strip().lower()) is not None\n\t\n\tdef add_credit(self, user_id, new_credit):\n\t\tself.storage[user_id]['credits'].append({\n\t\t\t'name': new_credit[0].strip(),\n\t\t\t'date': new_credit[1].strip(),\n\t\t\t'time': new_credit[2].strip()\n\t\t})\n\t\n\tdef add_exam(self, user_id, new_exam):\n\t\tself.storage[user_id]['exams'].append({\n\t\t\t'name': new_exam[0].strip(),\n\t\t\t'date': new_exam[1].strip(),\n\t\t\t'time': new_exam[2].strip()\n\t\t})\n\t\n\tdef get_exam_info(self, user_id, exam_name):\n\t\texam = self._find('exams', user_id, exam_name.strip().lower())\n\t\tif not exam:\n\t\t\treturn None\n\t\treturn '{} is an exam, it will be held on {} at {}'.format(\n\t\t\texam['name'],\n\t\t\texam['date'],\n\t\t\texam['time']\n\t\t)\n\t\n\tdef get_credit_info(self, user_id, credit_name):\n\t\tcredit = self._find('credits', user_id, credit_name.strip().lower())\n\t\tif not credit:\n\t\t\treturn None\n\t\treturn '{} is a credit, it will be held on {} at {}'.format(\n\t\t\tcredit['name'],\n\t\t\tcredit['date'],\n\t\t\tcredit['time']\n\t\t)\n\t\n\tdef get_exams(self, user_id):\n\t\treturn '\\n'.join(['{}) {}'.format(idx + 1, x['name']) for idx, x in enumerate(\n\t\t\tself.storage[user_id]['exams']\n\t\t)])\n\t\n\tdef get_courses(self, user_id):\n\t\texams = self.storage[user_id]['exams']\n\t\tcredits_ = self.storage[user_id]['credits']\n\t\treturn '\\n'.join(['{}) {}'.format(idx + 1, x['name']) for idx, x in enumerate(credits_ + exams)])\n\t\n\tdef print(self):\n\t\tprint(json.dumps(self.storage, sort_keys=True, indent=4))\n","sub_path":"NLP/task_1/app/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"285998077","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# author: bigfoolliu\n\n\n\"\"\"\n哈希表\n\n在哈希查找算法中会使用\n\"\"\"\nfrom number_theory.prime_numbers import next_prime\n\n\nclass HashTable(object):\n\n def __init__(self, size_table, charge_factor=None, lim_charge=None):\n self.size_table = size_table # hash表的大小\n self.values = [None] * self.size_table # 哈希表的初始值\n self.lim_charge = 0.75 if lim_charge is None else lim_charge\n self.charge_factor = 1 if charge_factor is None else charge_factor\n self.__aux_list = []\n self._keys = {}\n\n def keys(self):\n return self._keys\n\n def balanced_factor(self):\n \"\"\"平衡因子\"\"\"\n return sum([1 for slot in self.values if slot is None]) / (self.size_table * self.charge_factor)\n\n def hash_function(self, key):\n \"\"\"创建哈希表的哈希函数\"\"\"\n return key % self.size_table\n\n def _step_by_step(self, step_ord):\n print(\"step {0}\".format(step_ord))\n print([i for i in range(len(self.values))])\n print(self.values)\n\n def bulk_insert(self, values):\n \"\"\"块插入\"\"\"\n i = 1\n self.__aux_list = values\n for value in values:\n self.insert_data(value)\n self._step_by_step(i)\n i += 1\n\n def _set_value(self, key, data):\n \"\"\"设置值\"\"\"\n self.values[key] = data\n self._keys[key] = data\n\n def _colison_resolution(self, key, data=None):\n \"\"\"碰撞解决\"\"\"\n new_key = self.hash_function(key + 1)\n while self.values[new_key] is not None and self.values[new_key] != key:\n if self.values.count(None) > 0:\n new_key += 1\n new_key = self.hash_function(new_key)\n else:\n new_key = None\n break\n\n def rehashing(self):\n \"\"\"重新hash\"\"\"\n survivor_values = [value for value in self.values if value is not None]\n self.size_table = next_prime(self.size_table, factor=2)\n self._keys.clear()\n self.values = [None] * self.size_table\n map(self.insert_data, survivor_values)\n\n def insert_data(self, data):\n \"\"\"hash表插入数据\"\"\"\n key = self.hash_function(data)\n if self.values[key] is None:\n self._set_value(key, data)\n elif self.values[key] == data:\n pass\n else:\n colison_resolution = self._colison_resolution(key, data)\n if colison_resolution is not None:\n self._set_value(colison_resolution, data)\n else:\n self.rehashing()\n self.insert_data(data)\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"dataStructure/hashing/hash_table.py","file_name":"hash_table.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"539445125","text":"#!/usr/bin/python3\nimport sys\nsys.stdin = open('input.in', 'r')\nsys.stdout = open('output.out', 'w')\nsys.stderr = open('cerr.ce', 'w')\n\nfrom urllib import request, parse\ndef readText():\n quotes = open(\"D:\\Dropbox\\DangKhoa\\CEE_Cache\\Cpp\\CppWorkplace\\quotes.txt\")\n contents = quotes.read()\n quotes.close()\n checkProfanity(contents)\n\ndef checkProfanity(text):\n # request\n url = \"http://www.wdylike.appspot.com/?q=\" + parse.quote(text)\n conn = request.urlopen(url)\n out = conn.read()\n conn.close()\n\n # print output\n if b\"true\" in out:\n print(\"Profanity Alert!!\")\n elif b\"false\" in out:\n print(\"No curse words\")\n else:\n print(\"There was a problem\")\n\n\n# main\nreadText()\n\n","sub_path":"python_mini_projects/projects/checkProfanity.py","file_name":"checkProfanity.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"434907019","text":"from toga_winforms.libs import proactor, WinForms\nimport unittest\nimport unittest.mock as mock\nimport asyncio\nfrom threading import Thread\n\n\nclass Counter(object):\n def __init__(self):\n self.count = 0\n\n def increment(self):\n self.count += 1\n\n\nclass TestProactor(unittest.TestCase):\n def setUp(self):\n self.loop = proactor.WinformsProactorEventLoop()\n # asyncio.set_event_loop(self.loop)\n self.app_context = WinForms.ApplicationContext()\n\n def test_proactor_loop(self):\n print(\"=====================================================================\")\n # c = Counter()\n # with mock.patch.object(Counter, 'increment', wraps=c.increment) as fake_increment:\n thread = Thread(target=self.loop.run_forever, args=(self.app_context))\n thread.start()\n # await asyncio.sleep(5)\n print('Started!')\n self.loop.call_soon_threadsafe(self.loop.stop) # here\n print('Requested stop!')\n thread.join()\n # self.loop.run_forever(self.app_context)\n print('Finished!')\n # print(\"fake_increment:\", fake_increment)\n # unittest.TestCase.assertGreaterEqual(1, fake_increment.count)\n","sub_path":"src/winforms/tests/test_proactor.py","file_name":"test_proactor.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"452476013","text":"\"\"\"\nObjective: create genetic programming algorithm to solve the equation x^2 + x + 1\n\"\"\"\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nimport copy\n\n\nfset = ['+', '-', '*']\ntset = ['x'] + list(np.round(np.arange(-5.0, 5.1, 1), 4))\n\nn = 4 # population size\ndepth = 2 # initial program depth\nmax_gen = 500 # max number of generations to run the experiment for\nsolution = ['+', ['*', 'x', 'x'], ['+', 'x', '1']] # x^2 + x + 1\nfitness_goal = 0.1\n\n# Genetic operation rates\ncrossover_rate = 8\nreproduction_rate = 1\nmutation_rate = 1\n\n# Probability range for selection (used in all genetic operations)\nselection_prob_min = 0.1\nselection_prob_max = 1.0\n\ndef run(n, depth, max_gen, fitness_goal, solution, repr_rate, cross_rate, mutation_rate):\n\t\"\"\"\n\tPerforms one run of the experiment, subject to the given parameters.\n\n\t@n - population size\n\t@depth - initial individual depth\n\t@max_gen - maximum number of generations to run the experiment for\n\t@solution - the function the algorithm is trying to find\n\t@fitness_goal - stop the experiment when at least one individual achieves this score\n\t\"\"\"\n\n\t# Initialisation\n\tpopulation = init(n)\n\tbest_fitness_scores = [] # best fitness from each generation\n\tavg_fitness_scores = [] # average fitness from each generation\n\tbest_individuals = [] # best individuals of each population\n\n\tprint(\"Generation\")\n\n\t# Main loop\n\tfor gen_counter in range(1, max_gen+1):\n\n\t\t# Compute fitness scores\n\t\tfitness_scores = batch_fitness(population, solution)\n\t\tbest_fitness_scores.append(min(fitness_scores))\n\t\tavg_fitness_scores.append(np.mean(fitness_scores))\n\n\t\t# Store best individual of each population\n\t\tbest_individuals.append(population[fitness_scores.index(min(fitness_scores))])\n\n\t\t# Display generation info\n\t\tprint('\\t \\033[A' + str(gen_counter))\n\t\t# for idx in range(len(population)):\n\t\t# \tprint(population[idx], fitness_scores[idx])\n\t\t# print()\n\n\t\t# Check for winner\n\t\tidx = 0\n\t\twinner_found = False\n\t\twhile not winner_found and idx < len(population):\n\t\t\tif fitness_scores[idx] <= fitness_goal:\n\t\t\t\twinner_found = True\n\t\t\telse:\n\t\t\t\tidx += 1\n\n\t\tif winner_found:\n\t\t\tprint(\"Winner!\")\n\t\t\tprint(interpret(population[idx]))\n\t\t\tprint()\n\t\t\tbreak\n\n\t\t# Generate individuals for next generation\n\t\tpopulation = [select(population, fitness_scores) for _ in range(repr_rate)] + \\\n\t\t\t\t\t [mutate(select(population, fitness_scores)) for _ in range(mutation_rate)] + \\\n\t\t\t\t\t [crossover(select(population, fitness_scores), select(population, fitness_scores)) for _ in range(cross_rate)]\n\n\treturn (best_fitness_scores, avg_fitness_scores, best_individuals)\n\ndef init(n):\n\t\"\"\"\n\tCreates an initial random population of the given depth,\n\tusing the given function and terminal sets\n\t\"\"\"\n\n\tpopulation = []\n\n\tfor _ in range(n):\n\t\tpopulation.append(gen_rnd_exp(fset, tset, depth))\n\t\n\treturn population\n\ndef fitness(p, solution):\n\t\"\"\"\n\tComputes the fitness of the program p against the solution.\n\t\"\"\"\n\n\terrors = []\n\n\tfor x in np.arange(-1, 1.1, 0.1):\n\t\tp_out = eval(p, x)\n\t\ts_out = eval(solution, x)\n\t\terrors.append(abs(s_out - p_out))\n\n\treturn sum(errors)\n\ndef batch_fitness(ps, solution):\n\t\"\"\"\n\tComputes the fitness of a list of programs, ps, against the solution.\n\t\"\"\"\n\n\treturn [fitness(p, solution) for p in ps]\n\ndef select(population, fitness_scores):\n\t\"\"\"\n\tSelects a program from a population randomly, based on the fitness scores.\n\t\"\"\"\n\n\tprobs = [] # probability of selection of each program\n\tselected = [] # selected program\n\n\t# Compute selection probabilities\n\tfor i in range(len(population)):\n\t\tprobs.append(np.random.choice(np.arange(selection_prob_min, selection_prob_max, 0.1)) / fitness_scores[i])\n\t\t# probs.append(random.random() / fitness_scores[i])\n\n\t# Select program with highest probability\n\tmax_prob = max(probs)\n\tfor j in range(len(population)):\n\t\tif probs[j] == max_prob:\n\t\t\tselected = copy.deepcopy(population[j])\n\n\treturn selected\n\ndef mutate(p):\n\t\"\"\"\n\tMutates the node of a program p (tree-based mutation).\n\t\"\"\"\n\n\t# Randomly select a mutation point on p (node index)\n\tmutation_point = select_rnd_point(p)\n\n\t# Randomly mutate selected node in p\n\treplace_node(p, mutation_point)\n\n\treturn copy.deepcopy(p)\n\ndef crossover(p1, p2):\n\t\"\"\"\n\tPerforms crossover on two programs (parents) and returns the resulting program.\n\t\"\"\"\n\n\tp3 = copy.deepcopy(p1) # crossover result\n\n\t# Select crossover points on the parents\n\tp1_point = select_rnd_point(p1)\n\tp2_point = select_rnd_point(p2)\n\n\t# Get node at selected point in parent 2\n\tp2_node = []\n\tget_node_at_point(p2, p2_point, p2_node)\n\n\t# Replace node in parent 1 with node in parent 2\n\treplace_node(p3, p1_point, p2_node[0])\n\n\treturn p3\n\ndef select_rnd_point(p):\n\t\"\"\"\n\tRandomly selects a node in p and returns its index.\n\t\"\"\"\n\n\t# Assign a probability to each node of p\n\tnode_probs = []\n\tassign_node_probs(p, node_probs)\n\n\t# Select node index with highest probability\n\treturn node_probs.index(max(node_probs))\t\n\ndef get_node_at_point(p, point, node):\n\t\"\"\"\n\tFinds the node at a point in a program and loads it into a given node.\n\t\"\"\"\n\n\tidx = 1\n\twhile point > -1 and idx < len(p):\n\t\tif point == 0:\n\t\t\tnode.append(copy.deepcopy(p[idx]))\n\t\t\tpoint -= 1\n\t\telse:\n\t\t\tpoint -= 1\n\t\t\tif isinstance(p[idx], list):\n\t\t\t\tpoint = get_node_at_point(p[idx], point, node)\n\t\tidx += 1\n\treturn point\n\ndef assign_node_probs(node, probs):\n\t\"\"\"\n\tAssigns a random probability to all the sub-nodes of a node (including terminals).\n\t\"\"\"\n\n\tif isinstance(node, list):\n\t\tfor subnode_i in range(1, len(node)):\n\t\t\tprobs.append(random.random())\n\t\t\tassign_node_probs(node[subnode_i], probs)\n\ndef replace_node(p, point, new_node=None):\n\t\"\"\"\n\tFinds and replaces the node at a point in a program, \n\teither with a randomly generated node of the same depth or a given node.\n\t\"\"\"\n\n\tidx = 1\n\twhile point > -1 and idx < len(p):\n\t\tif point == 0:\n\n\t\t\t# Randomly generate new node (used in mutation)\n\t\t\tif new_node == None:\n\t\t\t\tif isinstance(p[idx], list):\n\t\t\t\t\tp[idx] = gen_rnd_exp(fset, tset, 1)\n\t\t\t\telif p[idx] in tset:\n\t\t\t\t\tp[idx] = gen_rnd_exp(fset, tset, 0)\n\t\t\t\n\t\t\t# Replace with given node (used in crossover)\n\t\t\telse:\n\t\t\t\tp[idx] = new_node\n\n\t\t\tpoint -= 1\n\n\t\telse:\n\t\t\tpoint -= 1\n\t\t\tif isinstance(p[idx], list):\n\t\t\t\tpoint = replace_node(p[idx], point, new_node)\n\n\t\tidx += 1\n\n\treturn point\n\ndef eval(exp, x):\n\t\"\"\"\n\tEvaluates an expression, using the given the value for x.\n\t\"\"\"\n\n\tvalue = 0\n\n\t# If the expression is a function\n\tif isinstance(exp, list):\n\t\tfunc = exp[0]\n\n\t\t# TODO: don't assume function arity\n\t\targ1 = eval(exp[1], x)\n\t\targ2 = eval(exp[2], x)\n\n\t\tvalue = apply(func, arg1, arg2)\n\t\n\t# If the expression is a terminal\n\telse:\n\t\tif exp == 'x': # variable\n\t\t\tvalue = x\n\t\telif isinstance(float(exp), float): # constant\n\t\t\tvalue = float(exp)\n\n\treturn value\n\t\ndef apply(func, arg1, arg2):\n\t\"\"\"\n\tApplies function func to arguments.\n\t\"\"\"\n\n\tresult = 0\n\n\tif func in fset:\n\t\tif func == '+':\n\t\t\tresult = arg1 + arg2\n\t\telif func == '-':\n\t\t\tresult = arg1 - arg2\n\t\telif func == '*':\n\t\t\tresult = arg1 * arg2\n\t\telif func == '/':\n\t\t\tif arg2 == 0:\n\t\t\t\tresult = arg1 / 0.01\n\t\t\telse:\n\t\t\t\tresult = arg1 / arg2\n\n\treturn result\n\ndef gen_rnd_exp(fset, tset, max_depth):\n\texp = \"\"\n\n\tif max_depth == 0:\n\t\treturn choose_rnd_element(tset)\n\n\telse:\n\t\tfunc = choose_rnd_element(fset)\n\t\targ1 = gen_rnd_exp(fset, tset, max_depth-1)\n\t\targ2 = gen_rnd_exp(fset, tset, max_depth-1)\n\n\t\texp = [func, arg1, arg2]\n\n\treturn exp\n\ndef choose_rnd_element(set):\n\treturn np.random.choice(set)\n\ndef interpret(expression):\n\t\"\"\"\n\tConverts an expression to a readable format.\n\t\"\"\"\n\n\tif isinstance(expression, list):\n\t\treturn interpret(expression[1]) + \" \" + expression[0] + \" \" + interpret(expression[2])\n\telse:\n\t\treturn expression\n\n\n\n\n# Run the epxeriment\nbest_fitness_scores, avg_fitness_scores, best_individuals = run(\n\tn, \n\tdepth, \n\tmax_gen, \n\tfitness_goal, \n\tsolution, \n\treproduction_rate, \n\tcrossover_rate, \n\tmutation_rate)\n\n\n# Output fitness statistics\nprint()\nprint(\"Best performance: \" + str(min(best_fitness_scores)))\nprint(\"Average performance: \" + str(sum(avg_fitness_scores) / len(avg_fitness_scores)))\n\n# Display best individuals of latest generations\nnum_display = 10\nfor idx, val in enumerate(best_individuals[-num_display:]):\n\tprint(\"\\nGeneration {:d} \\n {:s}\".format((idx + max_gen-num_display + 1), interpret(val)))\n\n# Plot best fitness\ngen_counts = [i+1 for i in range(len(best_fitness_scores))]\nplt.plot(gen_counts, best_fitness_scores, '-r')\nplt.ylabel('highest fitness score')\nplt.xlabel('generation number')\n\n# Plot average fitness\ngen_counts = [i+1 for i in range(len(best_fitness_scores))]\nplt.plot(gen_counts, avg_fitness_scores, '-b')\nplt.title('Best/Average Fitness')\nplt.ylabel('fitness score')\nplt.xlabel('generation number')\nplt.show()\n","sub_path":"simplegp.py","file_name":"simplegp.py","file_ext":"py","file_size_in_byte":8718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"412870904","text":"#-*- coding: utf-8 -*-\n#@Time :2018/12/8 20:47\n#@Author :yangjuan\n#@Email :269573175@qq.com\n#@File :test_HttpRequest.py\n\nimport unittest\nfrom http请求.http_request import Http_request\nfrom ddt import ddt,data,unpack\nfrom http请求_01.read_config import ReadConfig\nfrom http请求_01.do_excel import Do_Excel\nfrom http请求_01.do_logging import Do_Logging\nimport time\n\nCOOKIES=None\n\nconfig_value = ReadConfig().read_config('case.conf', 'CASE', 'button')\ntest_data=Do_Excel().get_data('test_case.xlsx','Sheet',config_value)\n\n@ddt\nclass Test_HttpRequest(unittest.TestCase): #测试类的类名 Test_HttpRequest继承TestCase,父类有初始化函数,超继承\n\n @data(*test_data)\n def test_api(self,item):\n # 登录\n global COOKIES\n log=Do_Logging().DoLogging()\n log.info('目前正在执行第{}条用例:{}'.format(item['case_id'],item['title']))\n log.info('--------------------开始检查我们的URL地址-------------------------------')\n log.info('url:',item['url'])\n log.info('----------------------开始检查我们的param-------------------------------')\n log.info('param:',item['param'])\n\n log.info('-------------------------开始HTTP请求-----------------------------------')\n res_login = Http_request().http(item['url'], item['method'], eval(item['param']),COOKIES)\n log.info('登录请求结果:', res_login.json())\n log.info('-------------------------结束HTTP请求-----------------------------------')\n\n if res_login.cookies: #如果登录获取的cookies不为空,则赋值给全局变量\n COOKIES=res_login.cookies\n actual = res_login.json()['msg']\n\n log.info('---------------------------开始断言-------------------------------------')\n TestResult=None\n try:\n self.assertEqual(actual, item['expected'])\n TestResult='用例通过'\n except Exception as e:\n print('断言出错了,{}'.format(e))\n TestResult = '用例不通过'\n raise e\n log.debug('本条用例的测试结论是:{}'.format(TestResult))\n log.info('---------------------------结束断言-------------------------------------')\n time.sleep(1) #1秒执行一个用例\n","sub_path":"python_interface/api_auto_3/common/test_HttpRequest.py","file_name":"test_HttpRequest.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"547079497","text":"import asyncio\nfrom datetime import datetime\n\n\nclass Bucket:\n\n def __init__(self, size, refRate, startFill=0, raced=False):\n self.maxSize = size\n self.refRate = refRate\n self.__startSize = startFill\n self.__startTs = datetime.now().timestamp()\n self.lock = asyncio.Lock() if not raced else None\n\n def state(self):\n return max(self.__startSize - self._deltaFill(), 0)\n\n def push(self, fill):\n if fill > self.maxSize:\n raise Exception('Fill bigger than max bucket size')\n state = self.state()\n if fill + state > self.maxSize:\n raise Exception('Bucket too full as of now.')\n elif state == 0:\n self.__startSize = fill\n self.__startTs = datetime.now().timestamp()\n else:\n self.__startSize += fill\n return state + fill\n\n def _deltaFill(self):\n return self.refRate * self._deltaTime()\n\n def _deltaTime(self):\n return datetime.now().timestamp() - self.__startTs\n\n def timeToWait(self, fill):\n return max(fill + self.state() - self.maxSize, 0)/self.refRate\n\n async def add(self, fill):\n await self.wait(fill)\n return self.push(fill)\n\n async def wait(self, fill):\n if self.lock:\n async with self.lock:\n await self.__wait(fill)\n else:\n await self.__wait(fill)\n\n async def __wait(self, fill):\n delay = self.timeToWait(fill)\n while delay != 0:\n await asyncio.sleep(delay)\n delay = self.timeToWait(fill)\n\n\n","sub_path":"ccxt_microservice/bucket.py","file_name":"bucket.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"215346654","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\\\n© Copyright 2016 Plumcarehealth. All rights reserved.\n\nA specialized JSON serializer that:\n\n * manages datetimes as ISO-8601\n * converts callables to their package notation as a string\n * puts file-like objects in data backend and inserts the URL into the json as a string\n\nNB: Object references are potentially nested types: that is, you can take a pickle, say, and if it's big,\nyou might create an object reference of it that includes the <_pickle... reference. That means that\nthese object references must be treated with special care during deserialization.\n\nTODO: Add function signatures to verify that this function string was created by trusted code.\n\nIncludes: implementation of StringSpecialEncoder\n\nThis is copied from the standard library and changed only to override string encoding behavior, which appears to be\nnot amenable to any other override.\n\n\"\"\"\n\nfrom base64 import b64encode\nfrom base64 import b64decode\nfrom datetime import datetime\nimport hashlib\nfrom importlib import import_module\nfrom io import StringIO\nimport json\nfrom json.encoder import _make_iterencode\nfrom json.encoder import INFINITY, FLOAT_REPR\nfrom json.encoder import encode_basestring_ascii\nfrom json.encoder import c_make_encoder, encode_basestring\nimport logging\nimport os.path\nimport pickle\n\nfrom pomegranite.config import get_config_var\nfrom pomegranite.security.utils import get_hmac\nfrom pomegranite.utils.data_backends import S3Backend, BACKEND_MAP\n\n\nLOGGER = logging.getLogger(__name__)\n\nFUNC_FORMAT = \"<_function:%s>\"\nFUNC_PREFIX = \"<_function:\"\nDATA_URL_FORMAT = \"\"\nDATA_URL_PREFIX = \"\"\nCOMPLEX_TYPE_PREFIX = \"<_type`\"\nPICKLE_PREFIX = \"<_pickle:\"\nPICKLE_FORMAT = \"<_pickle:%s:%s>\"\nSTD_SERIALIZATION_BUCKET = 'serializer-v1-pomegranite'\nSTD_SERIALIZATION_PATH = 'serialized'\nOBJREF_FORMAT = \"<_objref:%s:%s>\"\nOBJREF_PREFIX = \"<_objref:\"\nMAX_NATIVE_SIZE = 16 * 1024 # 16 k bytes\nPROCESS_CACHE_HIT_STATISTICS = {'serialized_objrefs': 0, 'cache_hits': 0}\n# The SQS size limit is about 256k, so we shoot for under that\nFULL_MESSAGE_SIZE_LIMIT_BYTES = 224 * 1024\nCUSTOM_MESSAGE_KEY = '__custom_serialization__results__'\nSERIALIZER_HMAC_KEY = get_config_var('SerializerSecrets', 'serializer_hmac_key')\n\n\n# Reconstructing a string encoder from the json encoder of the standard library\nclass StringSpecialEncoder(json.JSONEncoder):\n \"\"\"Extensible JSON encoder for Python data structures.\n\n \"\"\"\n def iterencode(self, obj, _one_shot=False):\n \"\"\"Encode the given object and yield each string\n representation as available.\n\n For example::\n\n for chunk in StringSpecialEncoder().iterencode(bigobject):\n mysocket.write(chunk)\n\n \"\"\"\n if self.check_circular:\n markers = {}\n else:\n markers = None\n if self.ensure_ascii:\n o_encoder = encode_basestring_ascii\n else:\n o_encoder = encode_basestring\n _encoder = o_encoder\n\n # now build a wrapped encoder that will create an object reference for the object if it's too big\n def wrapped_encoder(instr):\n \"\"\"Check size and optionally create object reference\"\"\"\n output = _encoder(instr)\n if must_replace_with_reference(output):\n # output is a string with a leading quote and a trailing quote, so strip those,\n # and add them back to the objref tag\n return '\"' + handle_serialize_object_ref(output[1:-1], self.backend_type) + '\"'\n return output\n\n def floatstr(obj, allow_nan=self.allow_nan,\n _repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY):\n \"\"\"Check for specials. Note that this type of test is processor\n and/or platform-specific, so do tests which don't depend on the\n internals.\"\"\"\n if obj != obj:\n text = 'NaN'\n elif obj == _inf:\n text = 'Infinity'\n elif obj == _neginf:\n text = '-Infinity'\n else:\n return _repr(obj)\n\n if not allow_nan:\n raise ValueError(\n \"Out of range float values are not JSON compliant: \" +\n repr(obj))\n\n return text\n\n if (_one_shot and c_make_encoder is not None and self.indent is None and not self.sort_keys):\n _iterencode = c_make_encoder(\n markers, self.default, wrapped_encoder, self.indent,\n self.key_separator, self.item_separator, self.sort_keys,\n self.skipkeys, self.allow_nan)\n else:\n _iterencode = _make_iterencode(\n markers, self.default, wrapped_encoder, self.indent, floatstr,\n self.key_separator, self.item_separator, self.sort_keys,\n self.skipkeys, _one_shot)\n return _iterencode(obj, 0)\n\n\ndef get_encoder_class(serializer=None, backend_type=S3Backend):\n \"\"\"\\\n Get the class that will override the string encoding to use object references.\n serializer carries with it its backend type.\n\n \"\"\"\n cls = StringSpecialEncoder\n if serializer is not None:\n backend_type = serializer.backend_type\n cls.backend_type = backend_type\n return cls\n\n\ndef custom_json_dumps(obj, serializer=None, custom_types=None, backend_type=S3Backend):\n \"\"\"\\\n Convenience method. If the body of the message exceeds FULL_MESSAGE_SIZE_LIMIT_BYTES, we double-wrap\n it so that the objref serializer will kick in. This is necessary because some of the stream encoders\n don't kick off the must_replace_with_reference routine (for example, list encoding iterates over the\n elements of the list, leaving the possibility that while each element may be below MAX_NATIVE_SIZE, the\n list as a whole will be bigger than MAX_NATIVE_SIZE).\n\n \"\"\"\n if serializer is None:\n serializer = create_custom_object_serializer(bucket=STD_SERIALIZATION_BUCKET, path=STD_SERIALIZATION_PATH,\n backend_type=backend_type)\n if custom_types is not None:\n serializer.register(custom_types)\n results_txt = json.dumps(obj, cls=get_encoder_class(serializer), default=serializer)\n # though the custom_json_dumps attempts to create references for large data objects, it can't always appropriately\n # slim down iterable types such as lists, whose chunks will obey the max size rule but which as a whole might not.\n # therefore, we test here again and create a custom notation for the object if it's too big: we double-custom-json-\n # encode it.\n if len(results_txt) > FULL_MESSAGE_SIZE_LIMIT_BYTES:\n custom_message = {\n CUSTOM_MESSAGE_KEY: results_txt\n }\n results_txt = json.dumps(custom_message, cls=get_encoder_class(serializer), default=serializer)\n # sign the resulting obj/obj_ref\n signed_txt = json.dumps({get_hmac(results_txt, key=SERIALIZER_HMAC_KEY): results_txt})\n return signed_txt\n\n\ndef custom_json_loads(rawstr):\n \"\"\"\\\n Convenience method. Uses CUSTOM_MESSAGE_KEY to potentially double-unwrap a serialization string that was\n double-wrapped for size.\n\n :raises: ValueError if signature is wrong\n :raises: AttributeError, IndexError if not even a signed object of any kind (dict with 1 or more items)\n\n \"\"\"\n # make sure the package has a signature and that it matches ours\n signed_result = json.loads(rawstr)\n sig, packet = list(signed_result.items())[0]\n if sig != get_hmac(packet, key=SERIALIZER_HMAC_KEY):\n raise ValueError(\"Hash of object is different\")\n results_obj = json.loads(packet, object_hook=custom_object_deserializer)\n if isinstance(results_obj, dict) and results_obj.get(CUSTOM_MESSAGE_KEY, None) is not None:\n results_obj = json.loads(results_obj[CUSTOM_MESSAGE_KEY], object_hook=custom_object_deserializer)\n return results_obj\n\n\ndef must_replace_with_reference(objstring):\n \"\"\"\\\n If the size is too big, return true.\n\n \"\"\"\n if len(objstring) > MAX_NATIVE_SIZE:\n return True\n return False\n\n\ndef handle_serialize_object_ref(objstring, backend_type):\n \"\"\"\\\n The string was big: create an object reference for it. Replace one string with another. Save\n artifact to backend.\n\n \"\"\"\n # create a custom backend that is pointed at a special path for collecting objects\n backend = backend_type(STD_SERIALIZATION_BUCKET, STD_SERIALIZATION_PATH + '/artifacts')\n # get fingerprint of object\n sha = hashlib.sha1()\n sha.update(objstring.encode('utf-8'))\n fingerprint = sha.hexdigest()\n # does this fingerprint exist in the backend?\n already_there = backend.exists(fingerprint)\n # if not, stow, else, just return replacement\n replacement_string = OBJREF_FORMAT % (backend.get_name(), fingerprint)\n if not already_there:\n backend.stow(fingerprint, objstring)\n else:\n PROCESS_CACHE_HIT_STATISTICS['cache_hits'] += 1\n PROCESS_CACHE_HIT_STATISTICS['serialized_objrefs'] += 1\n return replacement_string\n\n\ndef handle_deserialize_object_ref(value):\n \"\"\"\\\n The string was big: create an object reference for it. Replace one string with another. Restore\n artifact from backend.\n\n \"\"\"\n # discover the object inside\n # looks like <_objref:backend_name:id>\n structure = value[1:-1].split(':')\n backend_type = structure[1]\n id_ = structure[2]\n # create a custom backend that is pointed at a special path for collecting objects\n backend = BACKEND_MAP[backend_type](STD_SERIALIZATION_BUCKET, STD_SERIALIZATION_PATH + '/artifacts')\n # fetch\n idval = backend.fetch(id_)\n # return possibly still wrapped object string\n return idval\n\n\ndef base64_pickle(obj):\n \"\"\"\\\n Pickle this safe object. Base64 encode the result and return as a string.\n\n \"\"\"\n return b64encode(pickle.dumps(obj))\n\n\ndef handle_pickle(obj, backend_type):\n \"\"\"\\\n Create a custom structure for a pickle object. We're guaranteed not to find : or <> in it,\n because it's base64 encoded. Voila.\n\n \"\"\"\n pickle_type = str(type(obj))\n pickle_data = base64_pickle(obj)\n serialized = PICKLE_FORMAT % (pickle_type, pickle_data)\n if must_replace_with_reference(serialized):\n return handle_serialize_object_ref(serialized, backend_type)\n return serialized\n\n\ndef handle_deserialize_pickle(value):\n \"\"\"\\\n Unpickle the thing we pickled.\n\n \"\"\"\n armored = value[1:-1].split(':')[2]\n unarmored = b64decode(armored)\n return pickle.loads(unarmored)\n\n\ndef create_custom_object_serializer(bucket=STD_SERIALIZATION_BUCKET, path=STD_SERIALIZATION_PATH,\n backend_type=S3Backend):\n \"\"\"\\\n Wrapper: create a closure over bucket, path\n\n :param bucket: The bucket name we'll bind the serializer to\n :param path: The key prefix path\n\n :returns: A closure over custom_object_serializer bound to these variables\n\n \"\"\"\n class CustomObjectSerializer(object):\n \"\"\"\\\n Callable class to hold registered custom types for serialization.\n\n \"\"\"\n def __init__(self, backend, backend_type):\n \"\"\"Constructor: set up custom types array\"\"\"\n self.backend = backend\n self.backend_type = backend_type\n self.custom_types = []\n\n def register(self, pickle_types):\n \"\"\"\\\n This will register a type for pickle handling.\n\n \"\"\"\n self.custom_types = pickle_types\n\n def normalize_custom_types(self):\n \"\"\"\\\n Some classes, e.g. numpy.random.RandomState, have weird behavior (false advertised names, etc.)\n Custom types allows string names of classes and will import the proper module that way.\n\n \"\"\"\n ret = []\n for type_ in self.custom_types:\n if type(type_) == str:\n type_name = type_.split('.')\n classname = type_name.pop()\n class_module = import_module('.'.join(type_name))\n class_ = getattr(class_module, classname)\n ret.append(class_)\n else:\n ret.append(type_)\n return ret\n\n def __call__(self, obj):\n \"\"\"\\\n Accepts obj, which can be, in addition to standard JSON encoding types:\n\n * datetime\n * function reference\n * file handle\n * complex type providing to_json (object) and from_json (class) methods\n\n For complex types, to_json lets an instance of a complex novel type (a class) output to the json stream\n NB: backtick ('`') is used in the formatting of the json value wrapper, so to_json and from_json MUST NOT\n use '`' in their internal formatting unless it is encoded in some way.\n\n :param obj: The object to serialize\n\n :returns: The serialized version of the object, or the object if we're not handling this case.\n\n \"\"\"\n if isinstance(obj, datetime):\n obj = obj.strftime('%Y-%m-%dT%H:%M:%SZ')\n elif type(obj) in self.normalize_custom_types():\n obj = handle_pickle(obj, self.backend_type)\n elif callable(obj):\n obj = func_to_str(obj)\n elif callable(getattr(obj, 'read', None)):\n obj = handle_put_file(obj, self.backend)\n elif callable(getattr(obj, 'to_json', None)):\n obj = handle_complex_serialization(obj, self.backend_type)\n return obj\n my_backend = backend_type(bucket, path)\n return CustomObjectSerializer(my_backend, backend_type)\n\n\ndef handle_complex_serialization(obj, backend_type):\n \"\"\"\\\n Handle the serialization, which means calling to_json and wrapping in a holder. Obj should be an instance,\n not a class.\n\n :param obj: An object that provides a to_json object methods\n\n :returns: the result of calling to_json, wrapped in our custom string for identifying complex types\n\n \"\"\"\n # NB: backtick ('`') is used in the formatting of the json string, so to_json and from_json\n # MUST NOT use '`' in their internal formatting unless it is encoded in some way\n objtype = \"%s.%s\" % (obj.__module__, obj.__class__.__name__)\n try:\n serialized = COMPLEX_TYPE_FORMAT % (objtype, obj.to_json())\n except ValueError as ex:\n raise ValueError(\"Failed to encode {}\".format(objtype), ex)\n if must_replace_with_reference(serialized):\n return handle_serialize_object_ref(serialized, backend_type)\n return serialized\n\n\ndef handle_complex_deserialization(complexstring):\n \"\"\"\\\n Handle the serialization, which means calling to_json and wrapping in a holder. Obj should be an instance,\n not a class.\n\n :param complexstring: A wrapped complex string\n\n :returns: The result of using the class found in complexstring, and calling its class method from_json\n\n \"\"\"\n # starts as <_type:xxxx:yyyyy>\n # NB: backtick ('`') is used in the formatting of the json string, so to_json and from_json\n # MUST NOT use '`' in their internal formatting unless it is encoded in some way\n complexstring_parts = complexstring[1:-1].split('`')\n complextype_name = complexstring_parts[1].split('.')\n complextype_data = complexstring_parts[2]\n classname = complextype_name.pop()\n class_module = import_module('.'.join(complextype_name))\n class_ = getattr(class_module, classname)\n return class_.from_json(complextype_data)\n\n\ndef handle_put_file(fileobj, backend):\n \"\"\"\\\n Read the data. Store it in our data backend. Create a custom string that points to the created\n object and return it.\n\n :param fileobj: a file-like object (.read())\n :param backend: the data backend we chose\n\n :returns: A wrapped data url string to the created object\n\n \"\"\"\n filedata = fileobj.read()\n filename = os.path.basename(fileobj.name)\n # to data backend:\n backend.stow(filename, filedata)\n return data_url(backend_name=backend.get_name(), bucket=backend.bucket_name,\n path=backend.path, filestring=filename)\n\n\ndef handle_get_file(dataurl):\n \"\"\"\\\n Grab the data from data backend and send it along as a file handle (StringIO).\n\n :param dataurl: The wrapped data url string to a created object\n\n :returns: A file-like object (.read()) for the deserialization stream\n\n \"\"\"\n # dataurl looks like \n structure = dataurl[1:-1].split(':')\n backend_type = structure[1]\n dataparts = structure[2].split('/')\n bucket = dataparts[0]\n if len(dataparts) > 2:\n key = dataparts.pop()\n path = '/'.join(dataparts[1:])\n else:\n key = dataparts.pop()\n path = ''\n backend = BACKEND_MAP[backend_type](bucket, path, init_path=path)\n filedata = backend.fetch(key)\n return StringIO(filedata)\n\n\ndef custom_object_deserializer(dict_):\n \"\"\"\\\n Unwinds, in addition to standard JSON decoding types:\n\n * datetime\n * function reference\n * file handle\n\n :param dict_: This is called on every dict in the json deserializer, and dict_ is the\n dictionary it is scanning\n\n :returns: If we handle this deserialization case, the string we want added to the stream, otherwise the dict_\n\n \"\"\"\n for (key, value) in dict_.items():\n if hasattr(value, \"startswith\"):\n # object reference must be unwound first and then value has to be reset to that unwound string\n if value.startswith(OBJREF_PREFIX):\n value = handle_deserialize_object_ref(value)\n dict_[key] = value\n # no else! it could be an embedded type! continue processing this item:\n if value.startswith(FUNC_PREFIX):\n funcnotation = value[len(FUNC_PREFIX):-1].split('.')\n symbol = funcnotation.pop()\n module = import_module('.'.join(funcnotation))\n dict_[key] = getattr(module, symbol)\n elif value.startswith(DATA_URL_PREFIX):\n dict_[key] = handle_get_file(value)\n elif value.startswith(COMPLEX_TYPE_PREFIX):\n dict_[key] = handle_complex_deserialization(value)\n elif value.startswith(PICKLE_PREFIX):\n dict_[key] = handle_deserialize_pickle(value)\n else:\n try:\n # try zulu time\n dict_[key] = datetime.strptime(value, \"%Y-%m-%dT%H:%M:%SZ\")\n except ValueError:\n try:\n # try non-zulu iso-8601 variant\n dict_[key] = datetime.strptime(value, \"%Y-%m-%dT%H:%M:%S\")\n except ValueError:\n pass\n return dict_\n\n\ndef data_url(backend_name='s3', pathstr=None, bucket=None, path=None, filestring=None):\n \"\"\"\\\n Produce a formatted URL for our data serialized resources. Uses either pathstr as a fully qualified\n string to the resource, or composits it from bucket, path and filestring (key)\n\n :param pathstr: The full path to wrap -- if this is sent, no other parameters are used\n :param bucket: the bucket for this wrapped string (requried if no pathstr)\n :param path: the path for the wrapped string (optional)\n :param filestring: the key (requried if no pathstr)\n\n :returns: a fully qualified wrapped data string\n\n \"\"\"\n if pathstr is not None:\n return DATA_URL_FORMAT % (backend_name, pathstr)\n else:\n if bucket is None:\n raise TypeError(\"Must specify a bucket\")\n if filestring is None:\n raise TypeError(\"Must specify either pathstr or filestring\")\n if path is None:\n return DATA_URL_FORMAT % (backend_name, bucket + '/' + filestring)\n else:\n return DATA_URL_FORMAT % (backend_name, bucket + '/' + path + '/' + filestring)\n\n\ndef f_func(funcstr):\n \"\"\"\\\n Return a properly serialized formatted function string from a function string.\n\n :funcstr: The string version of this function\n\n :returns: Wrapped version\n\n \"\"\"\n return FUNC_FORMAT % funcstr\n\n\ndef func_to_str(func):\n \"\"\"\\\n Creates a string for a python function in a module. Class and object methods not supported currently.\n\n :param func: a python function\n\n :returns: a string representing this function\n\n \"\"\"\n fullqual = \"%s.%s\" % (func.__module__, func.__name__)\n return f_func(fullqual)\n","sub_path":"code/pomegranite/pomegranite/jason.py","file_name":"jason.py","file_ext":"py","file_size_in_byte":20636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"351371254","text":"from django.conf.urls.defaults import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\nhandler500 = 'Alak.misc.util.serverError'\nhandler404 = 'Alak.misc.util.pageNotFound'\n\nurlpatterns = patterns('',\n\n url(r'^', include ('Alak.home.urls')),\n url(r'^libraryPortal/', include ('Alak.libraryPortal.urls')),\n # Examples:\n # url(r'^$', 'Alak.views.home', name='home'),\n # url(r'^Alak/', include('Alak.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"Alak/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"265745930","text":"\"\"\"\n원제: 범위 내의 숫자를 분해하여 곱한 후 합 구하기 \n\n10 20\n\n45\n\n\n10 100\n\n2025\n\n\"\"\"\n\nimport sys\n\ninput = lambda: sys.stdin.readline().rstrip()\n\n\nstart, end = map(int, input().split())\n\nresult = 0\n\nfor num in range(start, end + 1):\n num_str = list(str(num))\n multipleOfNum = 1\n for n in num_str:\n multipleOfNum *= int(n)\n result += multipleOfNum\n\nprint(result)\n","sub_path":"구름레벨/쉽게푼문제/goorm_범위내의숫자분해.py","file_name":"goorm_범위내의숫자분해.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"116246779","text":"import csv\r\nimport time\r\nimport numpy as np\r\nimport os\r\nimport re\r\nimport sys\r\nimport datetime\r\nimport glob\r\nfrom scipy import signal\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.manifold import MDS\r\nfrom pandas.tseries.offsets import DateOffset\r\nfrom matplotlib.dates import DateFormatter\r\nimport matplotlib.ticker as ticker\r\nimport matplotlib.dates as mdates\r\nfrom matplotlib.dates import date2num\r\n\r\ndef load_file_NIMAX(fname):\r\n csv = pd.read_csv(fname, sep = '\\t', encoding = \"shift-jis\", error_bad_lines = False, header = None,skiprows=[0])\r\n data = np.array(csv, dtype = np.float32).T\r\n\r\n def0 = data[0][0]\r\n def1 = data[1][0]\r\n def2 = data[2][0]\r\n\r\n for index, item in enumerate(data[0]):\r\n #最初の値を引くとき\r\n data[0][index] = data[0][index] - def0\r\n data[1][index] = data[1][index] - def1\r\n data[2][index] = data[2][index] - def2\r\n\r\n return np.array(data, dtype = np.float32)\r\n\r\ndef load_file_acc(fname):\r\n csv = pd.read_csv(fname, sep = ',', encoding = \"shift-jis\", error_bad_lines = False, header = None,skiprows=[0])\r\n# with codecs.open(\"fname\", \"r\", \"Shift-JIS\", \"ignore\") as file:\r\n# csv = pd.read_table(file, delimiter=\",\")\r\n #date = np.array(csv.iloc[:,:1], dtype = np.datetime64).T\r\n #data = np.array(csv.iloc[:,2:4], dtype = np.float32).T\r\n temp = csv.values.T\r\n date = temp[0][:]\r\n data = temp[1:][:]\r\n #print(type(test))\r\n def0 = data[0][0]\r\n def1 = data[1][0]\r\n def2 = data[2][0]\r\n\r\n for index, item in enumerate(data[0]):\r\n #最初の値を引くとき\r\n data[0][index] = data[0][index] - def0\r\n data[1][index] = data[1][index] - def1\r\n data[2][index] = data[2][index] - def2\r\n\r\n return date, data\r\n\r\n# ローパスフィルタ処理\r\ndef lowpass(data, SAMPLE_RATE):\r\n # 時系列のサンプルデータ作成\r\n # n = len(data[0]) # データ数\r\n dt = 1/SAMPLE_RATE # サンプリング間隔\r\n fn = 1/(2*dt) # ナイキスト周波数\r\n # t = np.linspace(1, n, n)*dt-dt\r\n\r\n # パラメータ設定\r\n fp = 10 # 通過域端周波数[Hz]\r\n fs = 50 # 阻止域端周波数[Hz]\r\n gpass = 1 # 通過域最大損失量[dB]\r\n gstop = 40 # 阻止域最小減衰量[dB]\r\n # 正規化\r\n Wp = fp/fn\r\n Ws = fs/fn\r\n\r\n # ローパスフィルタで波形整形\r\n # バターワースフィルタ\r\n N, Wn = signal.buttord(Wp, Ws, gpass, gstop)\r\n b1, a1 = signal.butter(N, Wn, \"low\")\r\n\r\n data_0_lp = signal.filtfilt(b1, a1, data[0])\r\n data_1_lp = signal.filtfilt(b1, a1, data[1])\r\n data_2_lp = signal.filtfilt(b1, a1, data[2])\r\n\r\n return data_0_lp, data_1_lp, data_2_lp\r\n\r\n# 微分処理\r\ndef differential(data):\r\n data_roll_0 = np.roll(data[0], 300)\r\n data_roll_1 = np.roll(data[1], 300)\r\n data_roll_2 = np.roll(data[2], 300)\r\n diff_0 = data[0] - data_roll_0\r\n diff_1 = data[1] - data_roll_1\r\n diff_2 = data[2] - data_roll_2\r\n\r\n return diff_0, diff_1, diff_2\r\n\r\ndef main():\r\n #名前のリストを取得する\r\n datadir = \"/Users/sota/Labratory_Local/FoodRecognition/data/test\"\r\n formalized_csvdatadir = \"/Users/sota/Labratory_Local/FoodRecognition/data/formalized_data\"\r\n files = os.listdir(datadir)\r\n print(files)\r\n\r\n SAMPLE_RATE = 2000 #1秒で取るサンプル数[hz]\r\n UPDATE_RATE = 20 #秒間のデータ更新間隔[hz]\r\n index = 0\r\n\r\n for file_name in files:\r\n\r\n with open(datadir + \"/\" + file_name, encoding=\"utf_8\", errors='ignore') as f:\r\n\r\n reader = csv.reader(f, delimiter='\\t')\r\n l = [row for row in reader]\r\n\r\n data = load_file_NIMAX(datadir + \"/\" + file_name)\r\n data_lp = np.array(lowpass(data, SAMPLE_RATE), dtype = np.float32) #カンチレバー3軸の値が出てくる\r\n\r\n a = data_lp[1]\r\n maxid = signal.argrelmax(a, order=6000) # 局所的最大値, 6000はデータ幅\r\n #print(maxid)\r\n start_flag = False\r\n end_flag = False\r\n\r\n #ここで点を2つ計算する ピーク値の10分の1が出たら終わりとする\r\n for k in maxid[0]:\r\n #print(k)\r\n #print(a[k])\r\n\r\n x =a[k]/10\r\n for t in range(len(a)-k):\r\n if x > a[k+t]:\r\n end_id = k+t\r\n #print(k+t)\r\n end_flag = True\r\n break\r\n\r\n for k in maxid[0]:\r\n #print(k)\r\n #print(a[k])\r\n x =a[k]/10\r\n for t in range(len(a)):\r\n if x > a[k-t]:\r\n start_id = k-t\r\n #print(k-t)\r\n start_flag = True\r\n break\r\n\r\n # new_filename = splited_file_name[0] + \".\" + splited_file_name[1] + \".\" + splited_file_name[2] + \".csv\"\r\n\r\n\r\n if start_flag and end_flag and not os.path.exists(formalized_csvdatadir + \"/\" + file_name):\r\n index +=1\r\n with open(formalized_csvdatadir + \"/\" + file_name, 'w',newline=\"\") as wf:\r\n writer = csv.writer(wf,delimiter='\\t')\r\n print(l)\r\n for a in range(start_id, end_id):\r\n writer.writerow(l[a])\r\n\r\n\r\n #print(\"-\" * 20)\r\n print(\"index\")\r\n print(index)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"FoodRecognition/DataProcessing_forFoodRecognition/formalize_rawdata.py","file_name":"formalize_rawdata.py","file_ext":"py","file_size_in_byte":5492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"503317147","text":"\"\"\"\n题目:\n给定一个二叉树,返回它的中序 遍历。\n示例:\n输入: [1,null,2,3]\n 1\n \\\n 2\n /\n 3\n\n输出: [1,3,2]\n\"\"\"\n\n\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.right = None\n self.left = None\n\n\nclass Solution(object):\n def inorderTraversal1(self, root):\n WHITE, GRAY = 0, 1\n res = []\n stack = [(WHITE, root)]\n while stack:\n color, node = stack.pop()\n print(color)\n print(node)\n if node is None:\n continue\n if color == WHITE:\n stack.append((WHITE, node.right))\n stack.append((GRAY, node))\n stack.append((WHITE, node.left))\n else:\n res.append(node.val)\n return res\n\n\ndef main():\n root = TreeNode([1, None, 2, 3])\n\n s = Solution()\n\n res = s.inorderTraversal1(root)\n print(res)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Week 1/id_710/LeetCode_94_710.py","file_name":"LeetCode_94_710.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"647854582","text":"import requests\n'''\nurl = \"http://rank.ezme.net/?ckattempt=2\"\nheaders = {\"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36 Edg/88.0.705.81\",\"Referer\":\"http://rank.ezme.net/\",\"cookie\":\"CUPID=722b43102fa07181ef7b9ca172ce0e92; _ga=GA1.2.664659738.1614773369; _gid=GA1.2.1522281994.1614773369; __gads=ID=096dd3b10f5f7387-22d000c40db900e0:T=1614773369:RT=1614773369:S=ALNI_MY_WitjpWG6N_RO7XD0rMRAXQcvDA; _gat=1\",\"Accept-Language\":\"ko,en;q=0.9,en-US;q=0.8\"}\nresp = requests.get(url=url,headers=headers)\nresp.encoding='utf-8'\nabc = resp.text\n\nresp_arr = resp_text.split('\"demo-card-image__filename\">')\nfor i in range(1,11):\n print(resp_arr[i].split('<')[0])\n'''\nurl = \"https://m.stock.naver.com/sise/siseList.nhn?menu=market_sum&sosok=0\"\nresp = requests.get(url=url)\nresp_text = resp.text\nresp_arr = resp_text.split('nm\":\"')\nprint(resp_arr)\n\n","sub_path":"coding.py","file_name":"coding.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"241600879","text":"import random\n\nclass Monty(object):\n def __init__(self):\n '''\n Initialize instance variables:\n doors: list of strings\n wins: integer\n total: integer\n '''\n self.doors = ['a', 'b', 'c']\n self.wins = 0\n self.total = 0\n\n def play(self, strategy, chosen='a'):\n '''\n INPUT: function, string\n OUTPUT: Boolean\n\n Play the Monty Hall game once. The first choice is given by the\n argument chosen. Randomly choose a prize door and an empty door to\n reveal. The users strategy is given by the function strategy which\n takes a list of the door names, the prize door, and the door that was\n shown to be empty.\n\n Update the counters according to the results of the game and return\n True if the player wins, False otherwise.\n '''\n winner = random.randint(0,2)\n chosen_index = self.doors.index(chosen)\n self.total+=1\n if self.doors[winner]==chosen:\n self.wins+=1\n return True\n empty = list(set(self.doors)-set(self.doors[winner]) )[random.randint(0,1)]\n #print('winner =',self.doors[winner],' chosen =',chosen, ' empty =',empty)\n newanswer = self.doors[strategy(self.doors,chosen,empty)]\n if self.doors[winner]==newanswer:\n self.wins+=1\n return True\n \n return False \n\n\n\n def play_n_times(self, n, strategy):\n chosen = self.doors[random.randint(0,2)]\n for i in range(n):\n self.play(strategy,chosen)\n return self.wins/self.total\n","sub_path":"bayes-intro-ASSIGNMENT/src/monty.py","file_name":"monty.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"302414627","text":"import socket\n\ndef sendMessage(socket, message):\n socket.send(bytes(message, 'utf-8'))\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ns.connect(('127.0.0.1', 3334))\n\nwhile True:\n message = input(\"Input message: \" )\n sendMessage(s, message)\n\n","sub_path":"src/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"120040995","text":"from pylearn2.utils import serial\nfrom pylearn2.train_extensions import TrainExtension\n\nclass MonitorBasedSaveLatest(TrainExtension):\n \"\"\"\n A callback that saves a copy of the model every time it achieves\n a new minimal value of a monitoring channel.\n \"\"\"\n def __init__(self, save_path):\n \"\"\"\n Parameters\n ----------\n channel_name : str\n The name of the channel we want to minimize\n save_path : str\n Path to save the best model to\n \"\"\"\n\n self.__dict__.update(locals())\n del self.self\n\n\n def on_monitor(self, model, dataset, algorithm):\n \"\"\"\n Looks whether the model performs better than earlier. If it's the\n case, saves the model.\n\n Parameters\n ----------\n model : pylearn2.models.model.Model\n model.monitor must contain a channel with name given by \\\n self.channel_name\n dataset : pylearn2.datasets.dataset.Dataset\n Not used\n algorithm : TrainingAlgorithm\n Not used\n \"\"\"\n\n monitor = model.monitor\n if monitor.get_epochs_seen()%5==0 :\n\n serial.save(self.save_path + \"%05d\" % monitor.get_epochs_seen() + '.pkl', model, on_overwrite = 'backup')\n","sub_path":"model/save_latest.py","file_name":"save_latest.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"412812224","text":"import cv2\nimport numpy as np\nimport time\n\ni=0\nwidth=480\nlength=852\ngps_list=[(35.832909,128.754458),(35.832842,128.754476),(35.832852,128.754121),(35.832776,128.754171)]\n\nhuman_list=[(254,427)] #warping 사람 픽셀 list\nhuman_warp_list=[]\npixel_list=[(198,298),(343,300),(69,625),(386,634)]\n\ndef warp(frame_rotate):\n # Locate points of the documents or object which you want to transform\n pts1 = np.float32(pixel_list)\n pts2 = np.float32([[0, 0],[480, 0],[0,852],[480, 852]])\n # Apply Perspective Transform Algorithm\n matrix = cv2.getPerspectiveTransform(pts1, pts2)\n result = cv2.warpPerspective(frame_rotate, matrix, (width, length))\n cv2.imshow(\"frame_rotate\",result)\n\ndef cal():\n global human_warp_list,human_list,width,length,i \n\n human_lat=gps_list[0][0]-human_list[i][0]*lat_pixel\n human_long=gps_list[0][1]-human_list[i][1]*long_pixel\n print(human_lat)\n print(human_long)\n human_warp_list[i][0].append(human_lat)\n human_warp_list[i][1].append(human_long) \n \nfilepath=r'D:\\git repos\\NetCC\\NetCC_-Image-recognition\\python\\gps1..jpg'\n\nframe = cv2.imread(filepath)\nret = cv2.imread(filepath)\nframe=cv2.resize(frame,dsize=(480,852),interpolation=cv2.INTER_AREA)\ncv2.imshow('original',frame)\n\nwarp(frame)\nlat_mean=((gps_list[0][0]-gps_list[1][0])+(gps_list[2][0]-gps_list[3][0]))/2\nlong_mean=((gps_list[0][1]-gps_list[2][1])+(gps_list[1][1]-gps_list[3][1]))/2\n\nlat_pixel=lat_mean/width\nprint(lat_pixel)\nlong_pixel=long_mean/length\nprint(long_pixel)\n\nfor i in range(len(human_list)):\n cal()\n","sub_path":"Test & Study/cal_gps.py","file_name":"cal_gps.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"42697528","text":"from time import time\nimport pandas as pd\nimport os\nimport re\nimport numpy as np\nfrom pprint import pprint\n\nt0 = time()\n\nprint('INFO: done importing libraries and dataset in %0.3fs.' % (time() - t0))\n\n\nt0 = time()\n\nhits = pd.read_json('datasets/20200126-20200312-hits.json', lines=True)\nhits.head()\n\nprint('INFO: done reading in dataset to pandas dataframe in %0.3fs.' % (time() - t0))\n\n\n\nt0 = time()\n\nhits = hits.drop(columns=['_id', 'hit_set_id', 'requester_id','requester_name', 'assignment_duration_in_seconds', 'creation_time', 'assignable_hits_count', 'latest_expiration_time', 'caller_meets_requirements', 'caller_meets_preview_requirements', 'last_updated_time', 'monetary_reward', 'accept_project_task_url', 'requester_url', 'project_tasks_url', 'project_requirements', 'requesterInfo'], axis=1)\nhits.head()\n\nprint('INFO: done columns from dataframe in %0.3fs.' % (time() - t0))\n\n# removes all punctuation from the description and title if any\nt0 = time()\n\nhits['processed_description'] = hits['description'].map(lambda d : re.sub('[,.$()@#%&~!?]', ' ', d))\nhits['processed_title'] = hits['title'].map(lambda t : re.sub('[,.$()@#%&~!?]', ' ', t))\n\n\nhits['processed_description'] = hits['processed_description'].str.replace('\\W', ' ')\nhits['processed_description'] = hits['processed_description'].map(lambda d : re.sub('\\d', '', d))\nhits['processed_description'] = hits['processed_description'].str.replace('\\s+', ' ')\n\nhits['processed_title'] = hits['processed_title'].map(lambda d : re.sub('\\d', '', d))\nhits['processed_title'] = hits['processed_title'].str.replace('\\W', ' ')\nhits['processed_title'] = hits['processed_title'].str.replace('\\s+', ' ')\n\n\n\nprint('INFO: done removing punctuation and numbers from title and description in %0.3fs.' % (time() - t0))\n\nprint(hits['processed_description'])\n# cleans dataframe by converting all characters to lowercase and removing non-english characters\n# t0 = time()\n\ndef clean_dat(chunk):\n # Read stopwords\n with open('datasets/stops.txt', 'r') as f:\n stops = f.read().split('\\n')\n\n return ' '.join([ w for w in chunk.split() if w not in set(stops)])\n\n# converts to low caps\nhits['processed_description'] = hits['processed_description'].map(lambda x: x.lower())\n\nhits['processed_title'] = hits['processed_title'].map(lambda x: x.lower())\n\nprint('INFO: removing stopwords, duplicates, and numbers')\n\nprint('INFO: processed_description shape before dropping empty descriptions',hits['processed_description'].shape[0])\nprint('INFO: processed_title shape before dropping stop words and number', hits['processed_title'].shape[0])\n\nt0 = time()\n\n# removes non allowable characters\nhits['processed_description'] = hits['processed_description'].map(lambda x: clean_dat(x))\nhits['processed_title'] = hits['processed_title'].map(lambda x: clean_dat(x))\n\nprint(hits['processed_description'])\n\nnan_value = float(\"NaN\")\nhits.replace(\"\", nan_value, inplace=True)\n\nhits.dropna(subset = ['processed_description', 'processed_title'], inplace=True)\n\n\nhits['processed_description'].drop_duplicates(keep=False, inplace=True)\nhits['processed_title'].drop_duplicates(keep=False, inplace=True)\n\n\nprint('INFO: processed_description shape after removing stopwords, duplicates, and numbers', hits['processed_description'].shape[0])\n\nprint('INFO: processed_title shape after removing stopwords, duplicates, and numbers', hits['processed_title'].shape[0])\n\nprint('INFO: finished removing stopwords, duplicates, and numbers in %0.3fs' % (time() - t0))\n\n# print out the first couple processed descriptions\nt0 = time()\nprint('INFO: loading descriptions into text file')\n\nhits['processed_description'].to_csv(r'datasets/parsed_full_descriptions.txt', header=None, index=None, sep=' ', mode='a')\n\n# print out the first couple processed titles\nt0 = time()\nprint('INFO: loading titles into text file')\n\nhits['processed_title'].to_csv(r'datasets/parsed_full_titles.txt', header=None, index=None, sep=' ', mode='a')\nprint('INFO: finished loading titles into text file in %0.3fs' % (time() - t0))\n\n\n","sub_path":"notebooks/clean_data.py","file_name":"clean_data.py","file_ext":"py","file_size_in_byte":4030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"334172856","text":"# _*_coding:utf-8_*_\n\nfrom utils import Utils\nfrom ftp_tools import FTPTools\n\nif __name__ == '__main__':\n tools = Utils()\n tools.init_dir()\n ftp_tool = FTPTools('10.102.4.219', 21, 'ceshi', 'ceshi123')\n ftp_tool.connect_ftp()\n # ftp_tool.mkdir_ftp('new_testDir/test/test')\n # ftp_tool.upload_file('/new_testDir', '.\\\\Log\\\\Log_20210203.log', 'Log_20210203')\n # ftp_tool.delete_file('.', 'Log_20210203.log')\n # ftp_tool.download_file('Macallan/15A/Log/HW/QW1900/SC_UL10V100R001C00B132/x001/CALJNJGQCYKNJRKJ', './code/',\n # '0121_1801.zip')\n des_path = tools.get_store_dir('DOU', 'HW', 'QW1900', 'SC_Number')\n source_path = ftp_tool.trans_to_ftp('http://10.102.4.219:58443/r/Test/StressDemo.git', 'v1.0',\n des_path)\n ftp_tool.close_ftp()\n ftp_tool.connect_ftp()\n path = tools.make_dir_by_level('code\\\\test\\\\demo\\\\')\n ftp_tool.download_file(source_path, path, 'v1.0.zip')\n ftp_tool.close_ftp()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"451805725","text":"import re\n\nlista_nombre=[\n 'Ana Gomez',\n 'Maria Martín',\n 'Sandra López',\n 'Santiago Martín',\n 'Sandra Fernández']\n\ndominios=[\n 'https://www.google.com.do/',\n 'http://facebook.com',\n 'https://twitter.com/',\n 'https://trello.com',\n 'ftp://loventine.com',\n 'https://pildorasinformaticas.es']\n\n#Metacaracter que dice que comience \"^\"\n#Meta caracter que dice que termine \"$\"\n#Meta caracter que devuelve las considencias que tenga dentro \"[]\"\n\nListaPalabra=[\n 'Hombres',\n 'Mujeres',\n 'Mascotas',\n 'Niños',\n 'niñas',\n 'camión',\n 'camion']\n\nfor elemento in ListaPalabra:\n\n if re.findall('[nN]iñ[oa]s',elemento):\n print(elemento)","sub_path":"Expresiones Regulares/Practica_regex2.py","file_name":"Practica_regex2.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"129769036","text":"import numpy as np\nimport pandas as pd\n\narg_list=['SVM','Robust','Forest','LocalOut','MultiNormal']\n\nnp.random.random()\n\n\n\na = np.array([[3, 7, 4,5], [2,4, 1,9]])\nprint(np.percentile(a, 90,axis=1))\n\nab_cnt_list=[]\nab_cnt_list.append(arg_list)\ndf_rst= pd.DataFrame(ab_cnt_list)\ndf_rst.columns=arg_list\n\ndf_rst2=df_rst.T\ndf_rst2.columns=['aaa']\ndf_rst=df_rst2.T\nprint(df_rst)\n# print(np.percentile(np.array(df.iloc[:,2:].values), 10,axis=0))\n# print(np.percentile(np.array(df.iloc[:,2:].values), 90,axis=0))","sub_path":"002.abnormal_dect/99.test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"594137427","text":"def binary_search(l, r, arr, item):\n ans = -1\n while l <= r:\n mid = (l+r)//2\n print(\"mid\", mid, arr[mid])\n if arr[mid] < item:\n l = mid+1\n elif arr[mid] > item:\n print(\"hrere2\")\n ans = mid\n r = mid -1\n else:\n return mid\n return ans\n \n\narr = [2,7,9,13,25,56]\nindex = binary_search(0, len(arr)-1, arr, 24)\nprint(index)\nprint(arr[index])","sub_path":"binary_search.py","file_name":"binary_search.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"351870130","text":"# -*- coding: utf-8 -*-\nimport django_filters\nfrom models import Payments\nfrom django.db import models\nfrom core.utilites import get_lovs\n\nclass PaymentsFilter(django_filters.FilterSet):\n payment_method = django_filters.ChoiceFilter(choices=get_lovs(\"PM_payment_method\"), required=False, label=\"Метод платежа\")\n status = django_filters.ChoiceFilter(choices=get_lovs(\"PM_status\"), required=False, label=\"Статус\")\n class Meta:\n model = Payments\n fields = ['payment_number', 'account_id', 'invoice_num', 'status']\n filter_overrides = {\n models.CharField: {\n 'filter_class': django_filters.CharFilter,\n 'extra': lambda f: {\n 'lookup_expr': 'icontains',\n },\n },\n\n }","sub_path":"payments/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"49122409","text":"from supervised import print_data_stats\nfrom util import load_data, GoogleData\n\n\ndef main():\n all_data = load_data(\"../../data/esat3/games_part.csv\", shuffle=True)\n test_fraction = 0.02\n\n split_index = int((1 - test_fraction) * len(all_data))\n train_data = GoogleData.from_generic(all_data.pick_batch(slice(None, split_index)))\n test_data = GoogleData.from_generic(all_data.pick_batch(slice(split_index, None)))\n\n print_data_stats(test_data, train_data)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/mini/print_data_stats.py","file_name":"print_data_stats.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"421925861","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"wNTuple\")\n\nfrom TerraNova.CommonTools.countingSequences_cfi import *\nfrom PhysicsTools.SelectorUtils.pfJetIDSelector_cfi import pfJetIDSelector\nmyJetId = pfJetIDSelector.clone()\n\nfrom TerraNova.NtupleMaker.wLeptonSelector_cfi import *\nfrom TerraNova.NtupleMaker.triggerFilterByRun_cfi import *\nfrom TerraNova.NtupleMaker.wHLTfilter_cff import *\nfrom TerraNova.CommonTools.PileUpWeight_cff import *\nfrom TerraNova.CommonTools.JetEnergyScale_cfi import *\n\nVertexFilter = cms.EDFilter('VertexFilter',\n vertexLabel = cms.InputTag('offlinePrimaryVertices'),\n min = cms.untracked.int32(1),\n max = cms.untracked.int32(999),\n)\n\nGenZmassFilter = cms.EDFilter('GenZmassFilter',\n genParticlesLabel = cms.InputTag('genParticles'),\n applyFilter = cms.untracked.bool( False ),\n decayMode = cms.untracked.vint32(11, 13, 15),\n min = cms.untracked.int32(0),\n max = cms.untracked.int32(999),\n)\n\nGenWtransversemassFilter = cms.EDFilter('GenWtransversemassFilter',\n genParticlesLabel = cms.InputTag('genParticles'),\n applyFilter = cms.untracked.bool( False ),\n decayMode = cms.untracked.vint32(11, 13, 15),\n min = cms.untracked.int32(0),\n max = cms.untracked.int32(999),\n)\n\nWLeptonGenFilter = cms.EDFilter(\"GenParticleDecayFilter\",\n applyFilter = cms.untracked.bool( False ),\n motherPdgId = cms.untracked.uint32(6),\n pdgId = cms.untracked.uint32(24),\n daughterPdgIds = cms.untracked.vuint32(11, 13, 15),\n minCount = cms.untracked.uint32(2),\n)\n\npatMuonFilter = cms.EDFilter(\"CandViewCountFilter\",\n src = cms.InputTag('Muons'),\n minNumber = cms.uint32(1)\n)\n\npatElectronFilter = cms.EDFilter(\"CandViewCountFilter\",\n src = cms.InputTag('Electrons'),\n minNumber = cms.uint32(1)\n)\n\n#patMuonFilterForMuEl = patMuonFilter.clone()\n#patElectronFilterForMuEl = patElectronFilter.clone()\n#patMuonFilterForMuEl.minNumber = 1\n#patElectronFilterForMuEl.minNumber = 1\n\n#patMuonFilterForMuJet = patMuonFilter.clone()\n#patMuonFilterForMuJet.minNumber = 1\n#patElectronFilterForElJet = patElectronFilter.clone()\n#patElectronFilterForElJet.minNumber = 1\n\n#topWLeptonGenFilterForLJ = topWLeptonGenFilter.clone()\n#topWLeptonGenFilterForLJ.daughterPdgIds = 11,13\n#topWLeptonGenFilterForLJ.minCount = 1\n\nDYmmFilter = cms.EDFilter(\"ZmmFilter\",\n muonLabel1 = cms.InputTag('acceptedMuons'),\n muonLabel2 = cms.InputTag('acceptedMuons'),\n min = cms.double(12),\n max = cms.double(99999),\n)\n\n#correctedPatJetsPFlow = cms.EDProducer('KoCorrectJetProducer',\n# src = cms.InputTag('selectedPatJetsPFlow'),\n# correctors = cms.vstring('ak5PFL2L3')\n#)\n\n\nWEleNeu = cms.EDFilter('wEleNeuFilter',\n TriggerResultsTag = cms.untracked.InputTag('TriggerResults','','HLT'),\n HLTTriggers = cms.untracked.vstring('HLT_Ele22_CaloIdL_CaloIsoVL'),\n #HLTTriggers = cms.untracked.vstring('HLT_Ele22_CaloIdL_CaloIsoVL','HLT_Ele27_WP80'),\n genParticlesLabel = cms.InputTag('genParticles'),\n Channel = cms.untracked.string('Electron'),\n leptonLabel1 = cms.InputTag('Electrons'),\n leptonLabel2 = cms.InputTag('Electrons'),\n metLabel = cms.InputTag('patMETsPFlow'),\n #metLabel = cms.InputTag('JetEnergyScale','patMETsPFlow'),\n jetLabel = cms.InputTag('selectedPatJetsPFlow'),\n #jetLabel = cms.InputTag('JetEnergyScale','selectedPatJetsPFlow'),\n vertexLabel = cms.untracked.InputTag('offlinePrimaryVertices'),\n #vertexLabel = cms.untracked.InputTag('goodOfflinePrimaryVertices'),\n useEventCounter = cms.bool( True ),\n filters = cms.untracked.vstring(\n 'nEventsTotal',\n 'nEventsClean',\n 'nEventsHLT',\n 'nEventsFiltered',\n 'nEventsPatHLT',\n ),\n relIso1 = cms.untracked.double(0.17),\n relIso2 = cms.untracked.double(0.17),\n #bTagSets = bTagSets,\n PileUpRD = PuRD2012Low,\n PileUpMC = PuMC2012Low,\n)\n\nWMuNeu = cms.EDFilter('wMuNeuFilter',\n TriggerResultsTag = cms.untracked.InputTag('TriggerResults','','HLT'),\n HLTTriggers = cms.untracked.vstring('HLT_Mu15_eta2p1','HLT_IsoMu24_eta2p1'),\n genParticlesLabel = cms.InputTag('genParticles'),\n Channel = cms.untracked.string('Muon'),\n leptonLabel1 = cms.InputTag('Muons'),\n leptonLabel2 = cms.InputTag('Muons'),\n metLabel = cms.InputTag('patMETsPFlow'),\n #metLabel = cms.InputTag('JetEnergyScale','patMETsPFlow'),\n jetLabel = cms.InputTag('selectedPatJetsPFlow'),\n #jetLabel = cms.InputTag('JetEnergyScale','selectedPatJetsPFlow'),\n vertexLabel = cms.untracked.InputTag('offlinePrimaryVertices'),\n #vertexLabel = cms.untracked.InputTag('goodOfflinePrimaryVertices'),\n useEventCounter = cms.bool( True ),\n filters = cms.untracked.vstring(\n 'nEventsTotal',\n 'nEventsClean',\n 'nEventsHLT',\n 'nEventsFiltered',\n 'nEventsPatHLT',\n ),\n #for jet cleaning overlapping with isolated epton within 0.4\n relIso1 = cms.untracked.double(0.20),\n relIso2 = cms.untracked.double(0.20),\n #bTagSets = bTagSets,\n PileUpRD = PuRD2012Low,\n PileUpMC = PuMC2012Low,\n #PileUpRD = PileUpRD2011,\n #PileUpMC = Fall11,\n #hahahahaha,\n)\n\nremoveDuplicate = cms.EDFilter(\"RemoveDuplicate\",\n applyFilter = cms.untracked.bool( True )\n)\n\n#ElectronAna = cms.EDAnalyzer(\n# \"pfElectronAnalyzer\",\n# ptcut = cms.untracked.double(20),\n# electronLabel = cms.InputTag(\"acceptedElectrons\"),\n# beamSpotLabel = cms.InputTag(\"offlineBeamSpot\"),\n#)\n\nnEventsPatHLT = cms.EDProducer(\"EventCountProducer\")\n\nWMuNeuAnalysisMCSequence = cms.Sequence(\n hltHighLevelSingleMuLoPU*\n nEventsPatHLT*\n# topWLeptonGenFilter*\n# GenZmassFilter*\n# selectedPatJetsPFlow*\n# PUweight*\n# DYmmFilter*\n Muons*\n patMuonFilter*\n# JetEnergyScale*\n WMuNeu\n# mm\n)\n\nWMuNeuAnalysisRealDataSequence = cms.Sequence(\n hltHighLevelSingleMuRD*\n# muonTriggerFilterByRun*\n nEventsPatHLT*\n removeDuplicate*\n# DYmmFilter*\n# selectedPatJetsPFlow*\n Muons*\n patMuonFilter*\n# JetEnergyScale*\n WMuNeu\n# mm\n)\nWEleNeuAnalysisMCSequence = cms.Sequence(\n hltHighLevelSingleEleMC*\n nEventsPatHLT*\n# removeDuplicate*\n# WLeptonGenFilter*\n# GenZmassFilter*\n## selectedPatJetsPFlow*\n## PUweight*\n## ElectronAna*\n Electrons*\n patElectronFilter*\n# JetEnergyScale*\n# ElEl\n WEleNeu\n# ee\n)\n\nWEleNeuAnalysisRealDataSequence = cms.Sequence(\n hltHighLevelSingleEleRD*\n# electronTriggerFilterByRun*\n nEventsPatHLT*\n removeDuplicate*\n# selectedPatJetsPFlow*\n# ElectronAna*\n Electrons*\n patElectronFilter*\n# JetEnergyScale*\n WEleNeu\n# ee\n)\n","sub_path":"NtupleMaker/python/wAnalysis_cff.py","file_name":"wAnalysis_cff.py","file_ext":"py","file_size_in_byte":6610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"124471635","text":"# Imports\n\nimport os\nimport geopandas as gpd\nimport numpy as np\nimport copy\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport pandas\nimport math\n\nfrom gerrychain import (\n Graph, GeographicPartition, Partition, Election, accept, MarkovChain, constraints\n)\nfrom gerrychain.updaters import Tally, cut_edges\nfrom gerrychain.constraints import (\n single_flip_contiguous, no_vanishing_districts\n)\nfrom gerrychain.proposals import propose_random_flip, recom\nfrom gerrychain.accept import always_accept\nfrom gerrychain.metrics import polsby_popper\nfrom gerrychain.random import random\n\nfrom collections import defaultdict, Counter\nfrom itertools import combinations_with_replacement\nfrom functools import partial\n\n# setup -- SLOW\n\nshapefile = \"https://github.com/mggg-states/NC-shapefiles/raw/master/NC_VTD.zip\"\nprint(\"shapefile loaded\")\ndf = gpd.read_file(shapefile)\nprint(\"dataframe saved\")\n\ncounty_col = \"County\"\npop_col = \"PL10AA_TOT\"\nuid = \"VTD\"\n\ngraph = Graph.from_geodataframe(df,ignore_errors=True)\nprint(\"made graph\")\ngraph.add_data(df,list(df))\ngraph = nx.relabel_nodes(graph, df[uid])\ncounties = (set(list(df[county_col])))\ncountydict = dict(graph.nodes(data=county_col))\n\nstarting_partition = GeographicPartition(\n graph,\n assignment=\"2011_PLA_1\",\n updaters={\n \"polsby_popper\" : polsby_popper,\n \"cut_edges\": cut_edges,\n \"population\": Tally(pop_col, alias=\"population\"),\n\n }\n)\n\ncounty_edge_count = {}\nfor i in counties:\n county_graph = graph.subgraph([n for n,v in graph.nodes(data = True) if v[county_col] == i])\n total_edges = len(county_graph.edges())\n county_edge_count[i] = total_edges\n\ndef county_splits_dict(partition):\n \"\"\"\n From a partition, generates a dictionary of counter dictionaries.\n\n Args: \n partition: the partition for which a dictionary is being generated.\n\n Returns: \n A dictionary with keys as dictrict numbers and values as Counter() dictionaries.\n These counter dictionaries have pairs County_ID: NUM which counts the number of\n VTDs in the county in the district. \n \"\"\"\n\n county_splits = {k:[] for k in counties}\n county_splits = { k:[countydict[v] for v in d] for k,d in partition.assignment.parts.items() }\n county_splits = {k: Counter(v) for k,v in county_splits.items()}\n return county_splits\n\ndef cut_edges_in_county(partition):\n \"\"\"\n Computes a sum over all county scores, which are each calculated by\n taking the number of cut edges and dividing by the number of total edges.\n\n Args: \n partition: the partition to be scored.\n\n Returns: \n An integer score that is the sum of all county scores generated.\n \"\"\"\n\n county_cut_edge_dict = {}\n cut_edge_set = partition[\"cut_edges\"]\n for k in cut_edge_set:\n vtd_1 = k[0]\n vtd_2 = k[1]\n county_1 = countydict.get(vtd_1)\n county_2 = countydict.get(vtd_2)\n if county_1 == county_2:\n if county_1 in county_cut_edge_dict.keys():\n county_cut_edge_dict[county_1] += 1\n else:\n county_cut_edge_dict[county_1] = 1\n ratio_dict = {}\n for i in county_cut_edge_dict.keys():\n ratio = county_cut_edge_dict[i]/county_edge_count[i]\n ratio_dict[i] = ratio\n return sum(ratio_dict.values())\n\ndef cut_edges_in_district(partition):\n \"\"\"\n Computes a ratio of the cut edges between two counties over the total number of cut edges.\n\n Args: \n partition: the partition to be scored.\n\n Returns: \n The ratio of cut edges between two counties over the total number of cut edges.\n \"\"\"\n cut_edges_between = 0\n cut_edge_set = partition[\"cut_edges\"]\n for i in cut_edge_set:\n vtd_1 = i[0]\n vtd_2 = i[1]\n county_1 = countydict.get(vtd_1)\n county_2 = countydict.get(vtd_2)\n if county_1 != county_2:\n cut_edges_between += 1\n num_cut_edges = len(cut_edge_set)\n score = cut_edges_between/num_cut_edges\n return score\n\ndef VTDs_to_Counties(partition):\n \"\"\"\n Converts a partition into a dictionary with keys as districts and values as a list of VTDs in that district.\n\n Args: \n partition: the partition to be converted.\n\n Returns:\n A dictionary with keys as districts and values as dictionaries of county-population key-value pairs. \n This represents the population of each county that is in each district.\n \"\"\"\n\n district_dict = dict(partition.parts)\n new_district_dict = dict(partition.parts)\n for district in district_dict.keys():\n vtds = district_dict[district]\n county_pop = {k:0 for k in counties}\n for vtd in vtds:\n county_pop[countydict[vtd]] += graph.nodes[vtd][pop_col]\n new_district_dict[district] = county_pop\n return new_district_dict\n\ndef dictionary_to_score(dictionary):\n \"\"\"\n Calculates the half score of the Moon splitting score corresponding to the given dictionary.\n\n Args: \n dictionary: the dictionary to be scored.\n\n Returns: \n The half score of the dictionary.\n \"\"\"\n\n district_dict = dictionary\n score = 0\n for dist in district_dict.keys():\n counties_and_pops = district_dict[dist]\n total = sum(counties_and_pops.values())\n fractional_sum = 0\n for county in counties_and_pops.keys():\n fractional_sum += np.sqrt(counties_and_pops[county]/total)\n score += total*fractional_sum\n return score\n\ndef invert_dict(dictionary):\n \"\"\"\n Inverts a dictionary of dictionaries, switching the keys and values.\n\n Args:\n dictionary: dictionary to be inverted.\n\n Returns:\n An inverted dictionary.\n \"\"\"\n\n new_dict = defaultdict(dict)\n for k,v in dictionary.items():\n for k2,v2 in v.items():\n new_dict[k2][k] = v2\n return new_dict\n \ndef moon_score(partition):\n \"\"\"\n Calculates the Moon splitting score of a partition. \n\n Args: \n partition: the partition to be scored.\n\n Returns: \n The Moon splitting score of the partition.\n\n \"\"\"\n\n dictionary = VTDs_to_Counties(partition)\n return dictionary_to_score(dictionary) + dictionary_to_score(invert_dict(dictionary))\n\ndef mattingly(partition, M_C = 1000):\n \"\"\"\n Calculates the Mattingly splitting score of a partition.\n\n Args: \n partition: the partition to be scored.\n M_C: (default 1000).\n\n Returns: \n The Mattingly splitting score of the partition.\n\n \"\"\"\n\n num_2_splits = 0\n num_2_splits_W = 0\n num_greater_splits = 0\n num_greater_splits_W = 0\n county_splits = {k:[] for k in counties}\n dct = { k:[countydict[v] for v in d] for k,d in partition.assignment.parts.items() }\n dct = {k: Counter(v) for k,v in dct.items()}\n \n for v in dct.values():\n for k,ct in v.items():\n county_splits[k].append(ct)\n \n for county in county_splits.keys():\n if len( county_splits[county]) == 2:\n total = sum( county_splits[county])\n max_2 = min( county_splits[county])\n num_2_splits += 1\n num_2_splits_W += np.sqrt( max_2 / total )\n elif len(county_splits[county]) > 2:\n total = sum(county_splits[county])\n county_splits[county].sort()\n left_overs = total - county_splits[county][-1] - county_splits[county][-2]\n num_greater_splits += 1\n num_greater_splits_W += np.sqrt( left_overs / total)\n return num_2_splits * num_2_splits_W + M_C * num_greater_splits * num_greater_splits_W\n\ndef edge_entropy(partition):\n \"\"\"\n\n\n Args: \n partition: the partition\n\n Returns: \n entropy\n \"\"\"\n entropy = 0\n total_edges = len(graph.edges())\n countynodelist = {\n county: frozenset(\n [node for node in graph.nodes() if graph.nodes[node][county_col] == county]) for county in counties\n }\n districts_in_counties = {\n county: frozenset([partition.assignment[d] for d in countynodelist[county]]) for county in counties\n }\n for county in counties:\n county_subgraph = graph.subgraph([n for n in graph.nodes if graph.nodes[n][county_col] == county])\n county_edges = len(county_subgraph.edges())\n for (district1, district2) in combinations_with_replacement(districts_in_counties[county],2):\n p_ij = len([e for e in county_subgraph.edges() if set(\n [partition.assignment[e[0]], partition.assignment[e[1]]]) == set([district1, district2])])\n p_ij = p_ij/len(county_subgraph.edges())\n if (p_ij != 0):\n entropy -= p_ij*np.log(p_ij)*county_edges/total_edges\n return entropy\n\ndef num_of_splittings(partition):\n \"\"\"\n Calculates the number of splittings in a partition.\n\n Args: \n partition: the partition to be scored.\n\n Returns:\n The number of splittings in the partition.\n \"\"\"\n dictionary = county_splits_dict(partition)\n counter = 0\n for district in dictionary.keys():\n counter += len(dictionary[district])\n return counter\n\n#-------------------------------------------------------------------------------------------\ntotpop = 0\nnum_districts = 13\nfor n in graph.nodes():\n graph.node[n][pop_col] = int(graph.node[n][pop_col])\n totpop += graph.node[n][pop_col]\n\nproposal = partial(\n recom, pop_col=pop_col, pop_target=totpop/num_districts, epsilon=0.02, node_repeats=1\n )\n\ncompactness_bound = constraints.UpperBound(\n lambda p: len(p[\"cut_edges\"]), 2 * len(starting_partition[\"cut_edges\"])\n )\n\nchain = MarkovChain(\n proposal,\n constraints=[\n constraints.within_percent_of_ideal_population(starting_partition, 0.05),compactness_bound\n #constraints.single_flip_contiguous#no_more_discontiguous\n ],\n accept=accept.always_accept,\n initial_state=starting_partition,\n total_steps=5000\n )\n\ncuts = []\nsplittings = []\nmoon_metric_scores = [] #CHANGE\n\n\nt = 0\nfor part in chain:\n cuts.append(len(part[\"cut_edges\"]))\n splittings.append(num_of_splittings(part))\n moon_metric_scores.append(moon_score(part)) #CHANGE\n \n t += 1\n if t % 100 == 0:\n print(\"finished chain \" + str(t))\n \nnp.savetxt(\"NC_cuts.txt\", cuts)\nnp.savetxt(\"NC_splittings.txt\", splittings)\nnp.savetxt(\"NC_symmetric_entropy_moon.txt\", moon_metric_scores) #CHANGE\n\n#CHANGE\nplt.figure()\nplt.hist(moon_metric_scores)\nplt.title(\"Histogram of Symmetric Entropy (Moon)\")\nplt.xlabel(\"Symmetric Entropy\")\nplt.savefig(\"NC_hist_symmetric_entropy_5000.png\")\nplt.show()\n\n#CHANGE\nplt.figure()\nplt.scatter(splittings, moon_metric_scores)\nplt.title(\"Symmetric Entropy (Moon) vs. Number of Splits\")\nplt.xlabel('Splits')\nplt.ylabel('Symmetric Entropy')\nplt.xlim(min(splittings) - 5, max(splittings) + 5)\nplt.savefig(\"NC_scatter_symmetric_entropy_splits_5000.png\")\nplt.show()\n#CHANGE\nplt.figure()\nplt.scatter(cuts, moon_metric_scores)\nplt.title(\"Symmetric Entropy (Moon) vs. Number of Cut Edges\")\nplt.xlabel('Cut Edges')\nplt.ylabel('Symmetric Entropy')\nplt.savefig(\"NC_scatter_symmetric_entropy_cut_edges_5000.png\")\nplt.show()\n\n\n\n\n#print(moon_score(starting_partition))\n#print(list(starting_partition.assignment.keys()))\n#print([n for n in graph.nodes if n not in starting_partition.assignment])\n#print(df[\"VTD\"])\n#print(starting_partition[\"cut_edges\"])\n\n\n#d = county_splits_dict(starting_partition)\n#print(cut_edges_in_county(starting_partition))\n#print(cut_edges_in_district(starting_partition))\n#sum( [ len([ dd for dd in [dict(v) for v in d.values()] if k in dd.keys()]) > 1 for k in counties] )","sub_path":"NC_splits.py","file_name":"NC_splits.py","file_ext":"py","file_size_in_byte":11615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"377365418","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# 15.py\n\nimport sys\n\nwith open(sys.argv[1]) as f :\n lines = f.readlines()\n\nfor line in lines [len(lines) - int(sys.argv[2]):]:\n print(line, end='')\n","sub_path":"2ndSec/15.py","file_name":"15.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"622575188","text":"from flask_restful import fields, marshal_with, reqparse, Resource\nfrom flask import request\nfrom models.response import CustomResponse\nfrom models.status import Status\nimport werkzeug\nfrom flask import send_file\nimport os\nimport config\nimport logging\nimport uuid\nfrom datetime import datetime\nimport magic\nfrom models.user_files import UserFiles\nimport json\n\nALLOWED_FILE_TYPES = config.ALLOWED_FILE_TYPES\nALLOWED_FILE_EXTENSIONS = config.ALLOWED_FILE_EXTENSIONS\nparser = reqparse.RequestParser(bundle_errors=True)\n\nclass FileUploader(Resource):\n\n def post(self):\n parse = reqparse.RequestParser()\n parse.add_argument('file', type=werkzeug.datastructures.FileStorage, location='files',help='File is required', required=True)\n args = parse.parse_args()\n f = args['file']\n # file_real_name, file_extension = os.path.splitext(f.filename)\n # filename = str(uuid.uuid4())+file_extension\n # filepath = os.path.join(config.download_folder, filename)\n # f.save(filepath)\n # with open(filepath, 'rb') as f:\n # filetype = magic.from_buffer(f.read(), mime=True)\n # f.close()\n # if filetype in ALLOWED_FILE_TYPES:\n # userfile = UserFiles(created_by=request.headers.get('ad-userid'),\n # filename=filename,file_real_name=file_real_name+file_extension, created_on=datetime.now())\n # userfile.save()\n # res = CustomResponse(Status.SUCCESS.value, filename)\n # return res.getres()\n # else:\n # f.close()\n # os.remove(filepath)\n # res = CustomResponse(Status.ERROR_UNSUPPORTED_FILE.value, None)\n # return res.getresjson(), 400\n file_real_name, file_extension = os.path.splitext(f.filename)\n fileallowed = False\n filename = str(uuid.uuid4())+file_extension\n filepath = os.path.join(config.download_folder, filename)\n for allowed_file_extension in ALLOWED_FILE_EXTENSIONS:\n if file_extension.endswith(allowed_file_extension):\n fileallowed = True\n break\n if fileallowed:\n f.save(filepath)\n file_size = os.stat(filepath).st_size\n file_size = file_size/(1024*1024)\n if file_size > 20:\n os.remove(filepath)\n res = CustomResponse(Status.ERROR_FILE_SIZE.value, None)\n return res.getresjson(), 400\n userfile = UserFiles(created_by=request.headers.get('ad-userid'),\n filename=filename,file_real_name=file_real_name+file_extension, created_on=datetime.now())\n userfile.save()\n res = CustomResponse(Status.SUCCESS.value, filename)\n return res.getres()\n else:\n res = CustomResponse(Status.ERROR_UNSUPPORTED_FILE.value, None)\n return res.getresjson(), 400\n\n \n\nclass FileDownloader(Resource):\n def get(self):\n parse = reqparse.RequestParser()\n parse.add_argument('filename', type=str, location='args',help='Filename is required', required=True)\n parse.add_argument('userid', type=str, location='args',help='UserId is required', required=True)\n args = parse.parse_args()\n filename = args['filename']\n userid = args['userid']\n filepath = os.path.join(config.download_folder, filename)\n userfiles = UserFiles.objects(filename=filename,created_by=userid)\n if userfiles is not None and len(userfiles) > 0:\n if(os.path.exists(filepath)):\n result = send_file(filepath, as_attachment=True)\n result.headers[\"x-suggested-filename\"] = filename\n return result\n else:\n res = CustomResponse(Status.ERROR_NOTFOUND_FILE.value, None)\n return res.getresjson(), 400\n else:\n res = CustomResponse(Status.ERROR_NOTFOUND_FILE.value, None)\n return res.getresjson(), 400\n\n\nclass FileServe(Resource):\n\n def get(self):\n parse = reqparse.RequestParser()\n parse.add_argument('filename', type=str, location='args',help='Filename is required', required=True)\n args = parse.parse_args()\n filename = args['filename']\n filepath = os.path.join(config.download_folder, filename)\n if(os.path.exists(filepath)):\n with open(filepath) as json_file:\n data = json.load(json_file)\n res = CustomResponse(Status.SUCCESS.value, data)\n return res.getres()\n else:\n res = CustomResponse(Status.ERROR_NOTFOUND_FILE.value, None)\n return res.getresjson(), 400","sub_path":"anuvaad-etl/anuvaad-extractor/file-uploader/src/resources/file_handler.py","file_name":"file_handler.py","file_ext":"py","file_size_in_byte":4764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"202585114","text":"import inspect\nimport enum\nfrom functools import partial\n\nfrom dagger.exceptions import FunctionNotImplementedError, ContentVerifyFailed\n\n__all__ = (\"Declare\", \"declare\")\n\n\nclass RunMode(enum.IntEnum):\n THREAD_RUN = 0\n ASYNC_RUN = 1\n SYNC_RUN = 2\n\n\ndef _make_dummy(name):\n def _dummy_server(*args):\n raise FunctionNotImplementedError(name)\n\n return _dummy_server\n\n\nclass Declare:\n THREAD_RUN = RunMode.THREAD_RUN\n ASYNC_RUN = RunMode.ASYNC_RUN\n SYNC_RUN = RunMode.SYNC_RUN\n _DUMMY = False\n\n def __init__(self, name: str, module: str, doc: str, signature: inspect.Signature):\n self.name = name\n self.__name__ = name\n self.__module__ = module\n self.__doc__ = doc\n dummy = _make_dummy(name)\n self._server_impl = dummy\n self._client = None\n self._signature = signature\n self.runmode = self.THREAD_RUN\n self._parameter_check = None\n if not self._DUMMY:\n self._check_args()\n\n def set_server_impl(self, func, thread=None, asynchronous=None):\n assert not all((thread, asynchronous))\n if thread is None and asynchronous is None:\n thread = True\n asynchronous = False\n if thread:\n self.runmode = self.THREAD_RUN\n elif asynchronous:\n self.runmode = self.ASYNC_RUN\n else:\n self.runmode = self.SYNC_RUN\n\n self._server_impl = func\n\n def server_impl(self, func=None, *, thread=None, asynchronous=None):\n if func is None:\n return partial(self.server_impl, thread=thread, asynchronous=asynchronous)\n self.set_server_impl(func, thread, asynchronous)\n return func\n\n def assured_parameters(self, *args, **kwargs):\n bond_args: inspect.BoundArguments = self._signature.bind(*args, **kwargs)\n bond_args.apply_defaults()\n args = bond_args.args\n if self._parameter_check:\n args = self._parameter_check(*args)\n return args\n\n def parameters_assure(self, func):\n self._parameter_check = func\n return func\n\n def dispatch_request(self, client, args=(), kwargs=None):\n if kwargs:\n args = self.assured_parameters(*args, **kwargs)\n else:\n args = self.assured_parameters(*args)\n\n return client.dispatch_request(self.name, args)\n\n def server_call(self, *args):\n try:\n bond_args: inspect.BoundArguments = self._signature.bind(*args)\n bond_args.apply_defaults()\n except TypeError as e:\n raise ContentVerifyFailed(e)\n else:\n return self._server_impl(*bond_args.args)\n\n def setdefault_client(self, client):\n self._client = client\n\n def remote_call(self, *args, **kwargs):\n if self._client is None:\n raise RuntimeError(\"client is not set\")\n return self.dispatch_request(self._client, args, kwargs)\n\n def __call__(self, *args, **kwargs):\n raise RuntimeError(\"declare is not callable, use server_call or async_call or sync_call\")\n\n def __str__(self):\n return \"<%s name='%s' runmode=%s>\" % (self.__class__.__name__, self.__name__, self.runmode)\n\n __repr__ = __str__\n\n @classmethod\n def make_dummy(cls, name):\n dummy_sig = inspect.signature(_make_dummy(name))\n return _DummyDeclare(name, cls.__module__, \"dummy declare\", dummy_sig)\n\n _DISALLOW_KIND = (\n inspect.Parameter.VAR_POSITIONAL,\n inspect.Parameter.KEYWORD_ONLY,\n inspect.Parameter.VAR_KEYWORD,\n )\n\n def _check_args(self):\n for k, v in self._signature.parameters.items():\n if v.kind in self._DISALLOW_KIND:\n raise TypeError(\n f\"Declared function({self.name}) could only accept positional parameter.\"\n )\n\n\nclass _DummyDeclare(Declare):\n _DUMMY = True\n\n\ndef declare(func) -> Declare:\n name = func.__name__\n signature = inspect.signature(func)\n module = func.__module__\n doc = func.__doc__\n return Declare(name, module, doc, signature)\n\n\ndel RunMode\n","sub_path":"dagger/declare.py","file_name":"declare.py","file_ext":"py","file_size_in_byte":4096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"613621875","text":"#########################################################################\n'''Task 8. Написати функцію, яка буде реалізувати логіку циклічного зсуву\nелементів в списку. Тобто, функція приймає два аргументи: список і величину\nзсуву (якщо ця величина додатня - пересуваємо з кінця на початок,\nякщо від'ємна - навпаки - пересуваємо елементи з початку списку в його\nкінець). Наприклад:\n fnc([1, 2, 3, 4, 5], shift=1) --> [5, 1, 2, 3, 4]\n fnc([1, 2, 3, 4, 5], shift=-2) --> [3, 4, 5, 1, 2]\n'''\n#######################################\ndef fun_lan(List, shift):\n \n if shift > 0:\n for i in range(shift):\n List.insert(0,List[-1])\n List.pop(-1)\n elif shift < 0:\n for i in range(0,abs(shift)):\n List.append(List[0])\n List.remove(List[0])\n \n print('Output list ->',List)\n return List\n########################################\n#List=list(input('Input List:'))\nList=[1, 2, 3, 4, 5]\nprint('Input list -> ',List)\nshift=int(input( 'Input shift -> '))\nfun_lan(List, shift)","sub_path":"HT_3/8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"57583969","text":"# -*- coding: utf-8 -*-\nfrom unittest import TestCase\n\nfrom simple_object_model import OBJECT, TYPE, Class, Instance\n\n\nclass CallMethodTest(TestCase):\n def test_call_method(self):\n class A(object):\n def f(self):\n return self.x + 1\n\n\n obj = A()\n obj.x = 1\n assert obj.f() == 2\n\n\n class B(A):\n pass\n\n\n obj = B()\n obj.x = 2\n assert obj.f() == 3\n\n def f_A(self):\n return self.read_attr(\"x\") + 1\n\n A = Class(\n class_name=\"A\", base_class=OBJECT, metaclass=TYPE,\n fields={\"f\": f_A})\n\n B = Class(\n class_name=\"B\", base_class=A, metaclass=TYPE,\n fields={})\n\n obj = Instance(A)\n obj.write_attr(\"x\", 1)\n assert obj.callmethod(\"f\") == 2\n\n obj = Instance(B)\n obj.write_attr(\"x\", 2)\n assert obj.callmethod(\"f\") == 3\n\n def test_call_method_args(self):\n class A(object):\n def g(self, num):\n return self.x + num\n\n\n a = A()\n a.x = 2\n assert a.g(2) == 4\n\n\n class B(A):\n pass\n\n\n b = B()\n b.x = 2\n assert b.g(2) == 4\n\n def g_A(self, num):\n return self.read_attr(\"x\") + num\n\n A = Class(\n class_name=\"A\", base_class=OBJECT, metaclass=TYPE,\n fields={\"g\": g_A}\n\n )\n a = Instance(A)\n a.write_attr(\"x\", 2)\n assert a.callmethod(\"g\", 2) == 4\n\n B = Class(\n class_name=\"B\", base_class=A, metaclass=TYPE,\n fields={}\n )\n\n b = Instance(B)\n b.write_attr(\"x\", 2)\n assert b.callmethod(\"g\", 2) == 4\n","sub_path":"test/test_callmethod.py","file_name":"test_callmethod.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"236685814","text":"\"\"\"\nProvide the function visualize_blobs to display\nformed blobs interactively.\n\"\"\"\n\nimport sys\nimport numpy as np\nimport cv2 as cv\n\nfrom types import SimpleNamespace\n\nMIN_WINDOW_WIDTH = 640\nMIN_WINDOW_HEIGHT = 480\nWHITE = 255, 255, 255\nBLACK = 0, 0, 0\nRED = 0, 0, 255\nGREEN = 0, 255, 0\nBLUE = 255, 0, 0\nPOSE2COLOR = {\n 0:RED,\n 1:GREEN,\n 2:BLUE,\n}\n\nMASKING_VAL = 128 # Pixel at this value can be over-written\n\n\ndef visualize_blobs(frame, layer='r', window_size=None, winname=\"Blobs\"):\n \"\"\"\n Visualize blobs after clustering.\n Highlight the blob the mouse is hovering on and its\n adjacents.\n Parameters\n ----------\n frame : CBlob\n The frame of layer to visualize.\n layer : str, optional\n The layer to visualize. Must be 'r' or 'd'. Defaults to 'r'.\n window_size : tuple, optional\n The size of the window to display.\n winname : str, optional\n The name of the window. Defaults to \"Blobs\".\n \"\"\"\n print(\"Preparing for visualization ...\", end=\"\")\n\n height, width = frame.dert__[0].shape\n if window_size is None:\n window_size = (\n max(width, MIN_WINDOW_WIDTH),\n max(height, MIN_WINDOW_HEIGHT),\n )\n\n # Prepare state object\n state = SimpleNamespace(\n img=None, background=None, idmap=None, blob_id=None, img_slice=None, blob_cls=None,\n layers_stack=[(frame, layer)],\n )\n\n def reset_state():\n frame, layer = state.layers_stack[-1]\n\n if layer == 'r':\n blob_ = frame.rlayers[0]\n elif layer == 'd':\n blob_ = frame.dlayers[0]\n else:\n raise ValueError(\"layer must be 'r' or 'd'\")\n\n state.blob_cls = blob_[0].__class__\n y0, yn, x0, xn = frame.box\n rY, rX = frame.root_dert__[0].shape\n y0e = max(0, y0 - 1)\n yne = min(rY, yn + 1)\n x0e = max(0, x0 - 1)\n xne = min(rX, xn + 1) # e is for extended\n state.img_slice = slice(y0e, yne), slice(x0e, xne)\n state.background = blank_image((height, width))\n idmap = np.full((height, width), -1).astype('int64')\n # Prepare blob ID map and background\n for blob in blob_:\n paint_over(idmap[state.img_slice], None, blob.box,\n mask=blob.mask__,\n fill_color=blob.id)\n paint_over(state.background[state.img_slice], None, blob.box,\n mask=blob.mask__,\n fill_color=[blob.sign * 32] * 3)\n state.img = state.background.copy()\n state.idmap = cv.resize(idmap.astype('uint64'), window_size,\n interpolation=cv.INTER_NEAREST)\n state.blob_id = -1\n\n reset_state()\n def mouse_call(event, x, y, flags, param):\n wx, wy = window_size\n x = max(0, min(wx - 1, x))\n y = max(0, min(wy - 1, y))\n blob_id = state.idmap[y, x]\n if event == cv.EVENT_MOUSEMOVE:\n if state.blob_id != blob_id:\n state.blob_id = blob_id\n # override color of the blob\n state.img[:] = state.background[:]\n blob = state.blob_cls.get_instance(state.blob_id)\n if blob is None:\n print(\"\\r\", end=\"\\t\\t\\t\\t\\t\\t\\t\")\n sys.stdout.flush()\n return\n paint_over(state.img[state.img_slice], None, blob.box,\n mask=blob.mask__,\n fill_color=WHITE)\n # ... and its adjacents\n for adj_blob, pose in zip(*blob.adj_blobs):\n paint_over(state.img[state.img_slice], None, adj_blob.box,\n mask=adj_blob.mask__,\n fill_color=POSE2COLOR[pose])\n\n\n # ... print blobs properties.\n print(\"\\rblob:\",\n \"id =\", blob.id,\n \"sign =\", \"'+'\" if blob.sign else \"'-'\",\n \"I =\", blob.I,\n \"Dy =\", blob.Dy,\n \"Dx =\", blob.Dx,\n \"G =\", blob.G,\n \"M = \",blob.M,\n \"A =\", blob.A,\n \"box =\", blob.box,\n \"fork =\", ''.join(blob.prior_forks),\n end=\"\\t\\t\\t\")\n sys.stdout.flush()\n elif event == cv.EVENT_LBUTTONUP:\n blob = state.blob_cls.get_instance(state.blob_id)\n if flags & cv.EVENT_FLAG_CTRLKEY: # Look into rlayer\n if blob.rlayers and blob.rlayers[0] and blob is not None:\n state.layers_stack.append((blob, 'r'))\n reset_state()\n elif flags & cv.EVENT_FLAG_SHIFTKEY: # Look into dlayer\n if blob.dlayers and blob.dlayers[0] and blob is not None:\n state.layers_stack.append((blob, 'd'))\n reset_state()\n else: # Go back to parent\n if (len(state.layers_stack) > 1):\n state.layers_stack.pop()\n reset_state()\n\n\n cv.namedWindow(winname)\n cv.setMouseCallback(winname, mouse_call)\n print(\"hit 'q' to exit\")\n\n while True:\n cv.imshow(winname,\n cv.resize(state.img,\n window_size,\n interpolation=cv.INTER_NEAREST))\n if cv.waitKey(1) == ord('q'):\n break\n cv.destroyAllWindows()\n print()\n\ndef blank_image(shape, fill_val=None):\n '''Create an empty numpy array of desired shape.'''\n\n if len(shape) == 2:\n height, width = shape\n else:\n y0, yn, x0, xn = shape\n height = yn - y0\n width = xn - x0\n if fill_val is None:\n fill_val = MASKING_VAL\n return np.full((height, width, 3), fill_val, 'uint8')\n\ndef paint_over(map, sub_map, sub_box,\n box=None, mask=None, mv=MASKING_VAL,\n fill_color=None):\n '''Paint the map of a sub-structure onto that of parent-structure.'''\n\n if box is None:\n y0, yn, x0, xn = sub_box\n else:\n y0, yn, x0, xn = localize_box(sub_box, box)\n if mask is None:\n if fill_color is None:\n map[y0:yn, x0:xn][sub_map != mv] = sub_map[sub_map != mv]\n else:\n map[y0:yn, x0:xn][sub_map != mv] = fill_color\n else:\n if fill_color is None:\n map[y0:yn, x0:xn][~mask] = sub_map[~mask]\n else:\n map[y0:yn, x0:xn][~mask] = fill_color\n return map\n\ndef localize_box(box, global_box):\n '''\n Compute local coordinates for given bounding box.\n Used for overwriting map of parent structure with\n maps of sub-structure, or other similar purposes.\n Parameters\n ----------\n box : tuple\n Bounding box need to be localized.\n global_box : tuple\n Reference to which box is localized.\n Return\n ------\n out : tuple\n Box localized with localized coordinates.\n '''\n y0s, yns, x0s, xns = box\n y0, yn, x0, xn = global_box\n\n return y0s - y0, yns - y0, x0s - x0, xns - x0","sub_path":"frame_2D_alg/visualization/draw_frame_blobs.py","file_name":"draw_frame_blobs.py","file_ext":"py","file_size_in_byte":7137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"157037890","text":"# -*- coding: utf-8 -*-\n\"\"\"This module contains tests that exercise the canned VMware Automate stuff.\"\"\"\nimport fauxfactory\nimport pytest\n\nfrom cfme.automate.buttons import ButtonGroup, Button\nfrom cfme.automate.explorer import Namespace, Class, Instance, Domain\nfrom cfme.automate.service_dialogs import ServiceDialog\nfrom cfme.infrastructure.virtual_machines import Vm\nfrom cfme.web_ui import fill, flash, form_buttons, toolbar, Input\nfrom utils import testgen\nfrom utils.providers import setup_provider\nfrom utils.version import current_version # NOQA\nfrom utils.wait import wait_for\n\nsubmit = form_buttons.FormButton(\"Submit\")\npytestmark = [\n pytest.mark.meta(server_roles=\"+automate\"),\n pytest.mark.ignore_stream(\"upstream\", \"5.3\"), ]\n\n\ndef pytest_generate_tests(metafunc):\n argnames, argvalues, idlist = testgen.provider_by_type(\n metafunc, ['virtualcenter'], 'provisioning')\n metafunc.parametrize(argnames, argvalues, ids=idlist, scope='module')\n\n\n@pytest.fixture(scope=\"module\")\ndef domain(request):\n if current_version < \"5.3\":\n return None\n domain = Domain(name=fauxfactory.gen_alphanumeric(), enabled=True)\n domain.create()\n request.addfinalizer(lambda: domain.delete() if domain.exists() else None)\n return domain\n\n\n@pytest.fixture(scope=\"module\")\ndef namespace(request, domain):\n namespace = Namespace(name=\"System\", description=\"System\", parent=domain)\n namespace.create()\n request.addfinalizer(lambda: namespace.delete() if namespace.exists() else None)\n return namespace\n\n\n@pytest.fixture(scope=\"module\")\ndef cls(request, domain, namespace):\n tcls = Class(name=\"Request\", namespace=namespace,\n setup_schema=[Class.SchemaField(name=\"rel5\", type_=\"Relationship\")])\n tcls.create()\n request.addfinalizer(lambda: tcls.delete() if tcls.exists() else None)\n return tcls\n\n\n@pytest.fixture(scope=\"module\")\ndef testing_group(request):\n group_desc = fauxfactory.gen_alphanumeric()\n group = ButtonGroup(\n text=group_desc,\n hover=group_desc,\n type=ButtonGroup.VM_INSTANCE\n )\n request.addfinalizer(group.delete_if_exists)\n group.create()\n return group\n\n\n@pytest.fixture(scope=\"function\")\ndef testing_vm(request, provisioning, provider):\n setup_provider(provider.key)\n vm = Vm(\n name=\"test_ae_hd_{}\".format(fauxfactory.gen_alphanumeric()),\n provider_crud=provider,\n template_name=provisioning[\"template\"]\n )\n\n def _finalize():\n vm.delete_from_provider()\n if vm.does_vm_exist_in_cfme():\n vm.remove_from_cfme()\n request.addfinalizer(_finalize)\n vm.create_on_provider(find_in_cfme=True, allow_skip=\"default\")\n return vm\n\n\n@pytest.mark.meta(blockers=[1211627])\ndef test_vmware_vimapi_hotadd_disk(\n request, testing_group, provider, testing_vm, domain, namespace, cls):\n \"\"\" Tests hot adding a disk to vmware vm.\n\n This test exercises the ``VMware_HotAdd_Disk`` method, located either in\n ``/Integration/VimApi/`` (<5.3) or ``/Integration/VMware/VimApi`` (5.3 and up).\n\n Steps:\n * It creates an instance in ``System/Request`` that can be accessible from eg. a button.\n * Then it creates a service dialog that contains a field with the desired disk size, the\n text field name should be ``size``\n * Then it creates a button, that refers to the ``VMware_HotAdd_Disk`` in ``Request``. The\n button shall belong in the VM and instance button group.\n * After the button is created, it goes to a VM's summary page, clicks the button, enters\n the size of the disk and submits the dialog.\n * The test waits until the number of disks is raised.\n\n Metadata:\n test_flag: hotdisk, provision\n \"\"\"\n # Instance that calls the method and is accessible from the button\n if current_version() < \"5.3\":\n rel = \"/Integration/VimApi/VMware_HotAdd_Disk\"\n else:\n rel = \"/Integration/VMware/VimApi/VMware_HotAdd_Disk\"\n instance = Instance(\n name=\"VMware_HotAdd_Disk\",\n values={\n \"rel5\": rel,\n },\n cls=cls\n )\n if not instance.exists():\n request.addfinalizer(lambda: instance.delete() if instance.exists() else None)\n instance.create()\n # Dialog to put the disk capacity\n return\n element_data = {\n 'ele_label': \"Disk size\",\n 'ele_name': \"size\",\n 'ele_desc': \"Disk size\",\n 'choose_type': \"Text Box\",\n 'default_text_box': \"Default text\"\n }\n dialog = ServiceDialog(\n label=fauxfactory.gen_alphanumeric(),\n description=fauxfactory.gen_alphanumeric(),\n submit=True,\n tab_label=fauxfactory.gen_alphanumeric(),\n tab_desc=fauxfactory.gen_alphanumeric(),\n box_label=fauxfactory.gen_alphanumeric(),\n box_desc=fauxfactory.gen_alphanumeric(),\n )\n dialog.create(element_data)\n request.addfinalizer(lambda: dialog.delete())\n # Button that will invoke the dialog and action\n button_name = fauxfactory.gen_alphanumeric()\n button = Button(group=testing_group,\n text=button_name,\n hover=button_name,\n dialog=dialog, system=\"Request\", request=\"VMware_HotAdd_Disk\")\n request.addfinalizer(button.delete_if_exists)\n button.create()\n # Now do the funny stuff\n\n def _get_disk_count():\n return int(testing_vm.get_detail(\n properties=(\"Datastore Allocation Summary\", \"Number of Disks\")).strip())\n original_disk_count = _get_disk_count()\n toolbar.select(testing_group.text, button.text)\n fill(Input(\"size\"), \"1\")\n pytest.sel.click(submit)\n flash.assert_no_errors()\n wait_for(lambda: original_disk_count + 1 == _get_disk_count(), num_sec=180, delay=5)\n","sub_path":"cfme/tests/automate/test_vmware_methods.py","file_name":"test_vmware_methods.py","file_ext":"py","file_size_in_byte":5786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"618515666","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 1 21:02:29 2020\n\n@author: Silverxenfx\n\"\"\"\n\n\n\nimport sys\nclass excep(Exception):\n pass\nclass bank:\n def __init__(self,name,acctype):\n self.setbalance()\n self.name=name\n #self.__bal+=b\n self.__acctype=acctype\n print(\"Name of Customer is\",self.name)\n print(\"Account Type is \",self.__acctype)\n self.menu()\n def setbalance(self):\n self.__bal=1000\n\n\n def menu(self):\n print(\"Enter 1 for Deposition\")\n print(\"Enter 2 for Withdrawl\")\n inp=int(input(\"Enter your Choice:\"))\n if(inp==1):\n self.Deposit()\n elif(inp==2):\n self.withdrawl()\n\n\n def Deposit(self):\n self.dep=eval(input(\"Enter Amount to be Deposited:\"))\n self.__bal=self.dep+int(self.__bal)\n print(\"Updated Amount is \",self.__bal)\n\n def withdrawl(self):\n self.wit=eval(input(\"Enter Amount to be Withdrawn:\"))\n\n try:\n\n if(int(self.__bal)-self.wit<1000):\n raise excep\n except excep:\n print(\"Withdrawl is Not Possible as Balance Goes Below 1000\")\n\n else:\n self.__bal=int(self.__bal)-self.wit\n print(\"Remaining Amount is \",self.__bal)\n def Details(self):\n print(\"Name:\",self.name)\n print(\"Account-Type\",self.__acctype)\n print(\"Balance\",self.__bal)\n\n\nn=input(\"Enter Name:\")\n\na=input(\"Current or Savings\")\nob=bank(n,a)\nob.Details()","sub_path":"LAB8/prac8_1.py","file_name":"prac8_1.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"541638676","text":"\n# d1 = {1: 'valor 1', 'chave2': 'valor 2', 3: 'valor 3', 'chave4': 'valor 4'}\n#\n# print(d1[3])\n\n# clientes = {\n# 'cliente1' : {\n# 'nome': 'André',\n# 'sobrenome': 'Luiz',\n#\n# },\n# 'cliente2': {\n# 'nome': 'Maria',\n# 'sobrenome': 'Vicky',\n#\n# },\n#\n# }\n#\n# for clientes_k, clientes_v in clientes.items():\n# print(f'Exibindo {clientes_k}')\n# for dados_k, dados_v in clientes_v.items():\n# print(f'\\t{dados_k} = {dados_v}')\n\n########################################XX############################\nimport copy\n\nd1 = {1: 'a', 2: 'b', 3: 'c', 'd': ('André', 'Luiz' )}\nv = d1.copy()\n\nv[1] = 'André'\nv['d'] = ('Luiz', 'André')\n\nprint(d1)\nprint(v)\n\n","sub_path":"ProgramacaoProcedural/DicionarioemPython.py","file_name":"DicionarioemPython.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"491055742","text":"# -*- encoding: utf-8 -*-\n\n\nfrom django.urls import path\nfrom .views import login_view, register_user,productview, bankdetails,analyse, companyuser,indivisualuser,statement\nfrom django.contrib.auth.views import LogoutView\n\nurlpatterns = [\n\n path('login/', login_view, name=\"login\"),\n path('register/', register_user, name=\"register\"),\n path(\"logout/\", LogoutView.as_view(), name=\"logout\"),\n path(\"indivisualuser/\", indivisualuser, name=\"indivisualuser\"),\n path(\"companyuser\", companyuser, name=\"companyuser\"),\n path('bankdetails',bankdetails,name='bankdetails'),\n path('statement',statement,name='statement'),\n path('productview',productview,name='productview'),\n path('analyse',analyse,name='analyse')\n\n]\n","sub_path":"authentication/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"233289856","text":"#!/usr/bin/env python\n# coding: utf-8\nimport socket\nimport multiprocessing\nfrom time import localtime\nimport time\nimport struct\nfrom multiprocessing import Queue\nimport json\n\nBUFSIZ = 24\n\n\ndef socket_for_holovitality(port_for_holovitality, q_to_raw_data, filepath):\n \"\"\"\n :param local_host: ip address for python\n :param port_for_ultrasonic: the port set for receiving ultrasonic stream\n :param q_to_raw_data: the queue for raw data\n :param filepath: file path for data saving\n :return:\n \"\"\"\n \n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n host_name = socket.gethostname() \n local_host = socket.gethostbyname(host_name) \n print(local_host)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n addr = (local_host, port_for_holovitality)\n sock.bind(addr)\n sock.listen(2)\n\n print('Wait for HoloVitality, port: %d' % (port_for_holovitality))\n tcpClientSock, (addr_from_phone, port1) = sock.accept()\n print(addr_from_phone)\n is_Receiving = True\n with open(filepath+'data.json', 'a') as f:\n while is_Receiving:\n try:\n stream_data = tcpClientSock.recv(BUFSIZ)\n data = struct.unpack(\"2d1l\", stream_data)\n heart_rate, variance, timestamp = data\n timestamp = timestamp // 1000\n print(heart_rate, variance, timestamp)\n q_to_raw_data.put(data)\n # write to file\n jsondata = {'timestamp': timestamp, 'heart_rate': heart_rate, 'variance': variance}\n json.dump(jsondata, f)\n except Exception as e:\n print(e)\n tcpClientSock.close()\n break\n if data is None:\n break\n f.close()\n sock.close()\n\ndef transport(port_for_holelens, q_from_raw_data):\n \"\"\"\n :param local_host: ip address for python\n :param port_for_ultrasonic: the port set for receiving ultrasonic stream\n :param q_to_raw_data: the queue for raw data\n :param filepath: file path for data saving\n :return:\n \"\"\"\n \n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n host_name = socket.gethostname() \n local_host = socket.gethostbyname(host_name) \n print(local_host)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n addr = (local_host, port_for_holelens)\n sock.bind(addr)\n sock.listen(2)\n\n print('Wait for HoloLens, port: %d' % (port_for_holelens))\n# tcpClientSock, (addr_from_hololens, port1) = sock.accept()\n# print(addr_from_hololens)\n \n while True:\n while q_from_raw_data.empty():\n continue\n current_data = q_from_raw_data.get_nowait()\n \n heart_rate, variance, timestamp = current_data\n print(current_data)\n data_bytes = struct.pack(\"2d1l\", heart_rate, variance, timestamp)\n \n# tcpClientSock.send(data_bytes)\n\n sock.close()\n\n\n\nqueue = Queue()\nsocket_process = multiprocessing.Process(target=socket_for_holovitality, args=(12345, queue, '~/Desktop/'))\nsocket_process.start()\ntransport_process = multiprocessing.Process(target=transport, args=(12346, queue))\ntransport_process.start()\n","sub_path":"Server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"482821418","text":"\"\"\"\nImporting and using module:\nimport detect_english\ndetect_english.is_english(string) #Returns True or False\n\nNote: There must be a 'words_dictionary.json' file in the root directory with one word on each line\nThis can be downloaded from https://github.com/dwyl/english-words\n\"\"\"\n\nimport json\nimport time\n\n\ntime_start = time.time()\nUPPER_LETTERS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nALPHABET = UPPER_LETTERS + UPPER_LETTERS.lower() + \" \\t\\n\"\n\ndef load_dictionary():\n with open(\"words_dictionary.json\") as dictionary_file:\n english_words = json.loads(dictionary_file.read())\n \n return english_words\n\nENGLISH_WORDS = load_dictionary()\n\ndef match_percentage(message):\n message = message.lower()\n message = remove_non_letters(message)\n words_split = message.split()\n\n if not words_split:\n return 0.0 #Empty message, return 0.0\n\n matches = 0\n\n for word in words_split:\n if word in ENGLISH_WORDS:\n matches += 1\n\n return float(matches) / len(words_split)\n\ndef remove_non_letters(message):\n parsed_string = []\n for char in message:\n if char in ALPHABET:\n parsed_string.append(char)\n\n return \"\".join(parsed_string)\n\ndef is_english(message, percentage_words = 75, percentage_letters = 85):\n \"\"\"\n By default 20% of the words must exist in the dictionary file\n 85% of all the characters in the message must be letters or spaces (not special chars or numbers)\n \"\"\"\n msg_words_match = match_percentage(message) * 100 >= percentage_words\n msg_num_letters = len(remove_non_letters(message))\n msg_percentage_letter = (float(msg_num_letters) / len(message)) * 100\n msg_letters_match = msg_percentage_letter >= percentage_letters\n\n return msg_words_match and msg_letters_match \n\ndef main():\n text_file = open(\"frankenstein.txt\")\n text = text_file.read()\n text_file.close()\n\n time_elapsed = time.time() - time_start\n\n print(\"Is in english: %s\" % (is_english(text)))\n print(format(\"Time elapsed: %s seconds\" % (format(time_elapsed, \".5f\"))))\n # while(True):\n # # user_input = input()\n # time_start = time.time()\n # text_file = open(\"frankenstein.txt\")\n # text = text_file.read()\n # text_file.close()\n # time_end = time.time() - time_start\n # print(is_english(text))\n # print(time_end)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"detect_english/detect_english.py","file_name":"detect_english.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"203501814","text":"import sys\nimport os\nimport shutil\nfrom PIL import Image, ImageFile\n#ImageFile.LOAD_TRUNCATED_IMAGES = True\nimport time\nimport random\n\n# Read in image and parameters\nfile = str(sys.argv[1])\ncomp = str(sys.argv[2])\npos = int(sys.argv[3])\nfactor = 5\n\n# Paths for preserving files\ncurrent = os.getcwd()\nwork = current + \"/work\" + str(pos)\nif not (os.path.isdir(work)):\n os.mkdir(work)\n\n# What are the coordinates? (2000x1500)\nwidth = 2000 * factor\nheight = 1500 * factor\nleft = 0\nmidLeft = width / 4\nmidRight = width * 2 / 4\nright = width * 3 / 4\ntop = 0\nmiddle = height / 3\nbottom = height * 2 / 3\n\n# Assign x based on order in array\nif pos == 0 or pos == 4 or pos == 8:\n x = left\nelif pos == 1 or pos == 5 or pos == 9:\n x = midLeft\nelif pos == 2 or pos == 6 or pos == 10:\n x = midRight\nelse:\n x = right\n# Assign y based on order in array\nif pos <= 3:\n y = top\nelif 4 <= pos <= 7:\n y = middle\nelse:\n y = bottom\n\ntime.sleep(random.random()*10.) # sleep to prevent simultaneous access\nimg = Image.open(file) # open the image to paste\n\nwhile True:\n try:\n # Try to move the file\n shutil.move(current + \"/\" + comp, work + \"/\" + comp)\n # If this is false then run the except block\n os.path.isfile(work + \"/\" + comp)\n break\n except:\n # If you can't find the file, then wait\n time.sleep(10.)\n\nos.chdir(work) # change to working directory\ncomp_img = Image.open(comp) # open composite\nimg2 = img.resize((500*factor,500*factor)) # resize to prepare for paste\ncomp_img.paste(img2,(x,y)) # paste into composite image\ncomp_img.save(comp) # resave image\n\n# Move the file back\nshutil.move(work + \"/\" + comp, current + \"/\" + comp)\n","sub_path":"deprecated/placeMovieFrame.py","file_name":"placeMovieFrame.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"73402853","text":"#!/usr/bin/python27\n#coding:utf-8\n#lab-04-1-multi-variable-linear-regression\n\nimport tensorflow as tf\ntf.set_random_seed(777)\n\n\nx1_data = [73.,93.,89.,96.,73.]\nx2_data = [80.,88.,91.,98.,66.]\nx3_data = [75., 93., 90., 100., 70.]\n\ny_data = [152., 185., 180., 196., 142.]\n\nx1 = tf.placeholder(tf.float32)\nx2 = tf.placeholder(tf.float32)\nx3 = tf.placeholder(tf.float32)\n\nY = tf.placeholder(tf.float32)\n\nw1 = tf.Variable(tf.random_normal([1],name= 'weight1'))\nw2 = tf.Variable(tf.random_normal([1],name= 'weight2'))\nw3 = tf.Variable(tf.random_normal([1],name= 'weight3'))\nb = tf.Variable(tf.random_normal([1],name= 'bias'))\n\nhypotheis = w1 * x1 + w2*x2 + w3 *x3 + b\n\n#最小二乘\nloss = tf.reduce_mean(tf.square(hypotheis-Y))\nprint(loss)\nprint(loss.shape)\nt = tf.Print(loss,[loss,loss],message='loss',summarize=20)\n\noptimizer = tf.train.GradientDescentOptimizer(learning_rate= 1e-5)\ntrain = optimizer.minimize(loss)\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\nfor step in range(1000):\n cost_value,hy_val,_ = sess.run([loss,hypotheis,train],\n feed_dict={x1:x1_data,x2:x2_data,x3:x3_data,Y:y_data})\n\n if step % 10 == 0:\n print(step,\"cost : \",cost_value,\"\\nprediction :\\n\",hy_val)\n\n\n","sub_path":"t0072_multi_variable_linear_regression.py","file_name":"t0072_multi_variable_linear_regression.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"429001738","text":"\"\"\"FoodCorner URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom FoodApp import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n \n path('addfood/',views.addFood),\n path('menu/',views.menu),\n path('update/', views.updateFood),\n path('delete/',views.deleteFood),\n path('signup/',views.signup),\n path('login/',views.loginUser),\n path('logout/',views.logoutUser),\n path(\"\",views.index),\n path(\"addtocart/\",views.addCart),\n path('profile/', views.userProfile),\n path('updatecust/', views.updateProfile),\n path('cart/', views.showCart),\n path('updatecart/', views.updateCart),\n path('deleteCart/',views.deleteCart),\n path('placeOrder',views.placeOrder),\n path('myorders/', views.showOrders),\n path('allorders/', views.allOrders)\n\n\n]\nif settings.DEBUG:\n print(static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT))\n\n urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)\n\n\n","sub_path":"FoodCorner/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"420402078","text":"#!/usr/bin/python3\n\nimport configparser\nimport libvirt\nimport logging\nimport os\nimport time\n\nfrom . import recipe\nfrom . import virtual_environ\nfrom . import settings\nfrom . import cmd\n\nlogger = logging.getLogger(\"nitsi.test\")\n\n\nclass TestException(Exception):\n def __init__(self, message):\n self.message = message\n\nclass Test():\n def __init__(self, log_path, dir=None, recipe_file=None, settings_file=None, settings=None, default_settings_file=None):\n # init settings var\n self.settings = settings\n\n self.log_path = log_path\n\n # Init all vars with None\n self.settings_file = None\n self.recipe_file = None\n self.path = None\n\n self.default_settings_file = default_settings_file\n\n # We need at least a path to a recipe file or a dir to a test\n if not dir and not recipe:\n raise TestException(\"Did not get a path to a test or to a recipe file\")\n\n # We cannot decide which to use when we get both\n if (dir and recipe_file) or (dir and settings_file):\n raise TestException(\"Get dir and path to recipe or settings file\")\n\n if dir:\n try:\n if not os.path.isabs(dir):\n self.path = os.path.abspath(dir)\n except BaseException as e:\n logger.error(\"Could not get absolute path\")\n raise e\n\n logger.debug(\"Path of this test is: {}\".format(self.path))\n\n self.recipe_file = \"{}/recipe\".format(self.path)\n self.settings_file = \"{}/settings\".format(self.path)\n\n\n # We can also go on without a settings file\n self.settings_file = self.check_file(self.settings_file, log_level=logging.WARNING)\n\n self.recipe_file = self.check_file(self.recipe_file)\n if not self.recipe_file:\n raise TestException(\"No recipe file found\")\n\n self.default_settings_file = self.check_file(self.default_settings_file)\n\n # Init logging\n if dir:\n self.log = logger.getChild(os.path.basename(self.path))\n # We get a recipe when we get here\n else:\n self.log = logger.getChild(os.path.basename(self.recipe_file))\n\n # Parse config and settings:\n if self.settings_file:\n self.settings.set_config_values_from_file(self.settings_file, type=\"settings-file\")\n\n if self.default_settings_file:\n self.settings.set_config_values_from_file(self.default_settings_file, type=\"default-settings-file\")\n\n # Check settings\n self.settings.check_config_values()\n\n # Checks the file:\n # is the path valid ?\n # returns an absolut path, when the file is valid, None when not\n def check_file(self, file, log_level=logging.ERROR):\n if file:\n logger.debug(\"File to check is: {}\".format(file))\n if not os.path.isfile(file):\n err_msg = \"No such file: {}\".format(file)\n logger.log(log_level,err_msg)\n return None\n if not os.path.isabs(file):\n file = os.path.abspath(file)\n\n return file\n return None\n\n def virtual_environ_setup_stage_1(self):\n self.virtual_environ = virtual_environ.VirtualEnviron(self.settings.get_config_value(\"virtual_environ_path\"))\n\n self.virtual_networks = self.virtual_environ.get_networks()\n\n self.virtual_machines = self.virtual_environ.get_machines()\n\n def virtual_environ_setup_stage_2(self):\n # built up which machines which are used in our recipe\n used_machines = []\n\n for line in self.recipe.recipe:\n if not line[0] in used_machines:\n used_machines.append(line[0])\n\n self.log.debug(\"Machines used in this recipe {}\".format(used_machines))\n\n self.used_machine_names = used_machines\n\n for machine in self.used_machine_names:\n if not machine in self.virtual_environ.machine_names:\n raise TestException(\"{} is listed as machine in the recipe, but the virtual environmet does not have such a machine\".format(machine))\n\n\n def virtual_environ_start(self):\n for name in self.virtual_environ.network_names:\n self.virtual_networks[name].define()\n self.virtual_networks[name].start()\n\n for name in self.used_machine_names:\n self.virtual_machines[name].define()\n self.virtual_machines[name].create_snapshot()\n # We can only copy files when we know which and to which dir\n if self.settings.get_config_value(\"copy_from\") and self.settings.get_config_value(\"copy_to\"):\n self.virtual_machines[name].copy_in(self.settings.get_config_value(\"copy_from\"), self.settings.get_config_value(\"copy_to\"))\n self.virtual_machines[name].start()\n\n # Time to which all serial output log entries are relativ\n log_start_time = time.time()\n\n # Number of chars of the longest machine name\n longest_machine_name = self.virtual_environ.longest_machine_name\n\n self.log.info(\"Try to intialize the serial connection, connect and login on all machines\")\n for name in self.used_machine_names:\n self.log.info(\"Try to initialize the serial connection connect and login on {}\".format(name))\n self.virtual_machines[name].serial_init(log_file=\"{}/test.log\".format(self.log_path),\n log_start_time=log_start_time,\n longest_machine_name=longest_machine_name)\n self.virtual_machines[name].serial_connect()\n\n def load_recipe(self):\n self.log.info(\"Going to load the recipe\")\n try:\n self.recipe = recipe.Recipe(self.recipe_file,\n fallback_machines=self.virtual_environ.machine_names,\n include_path=self.settings.get_config_value(\"include_path\"))\n\n for line in self.recipe.recipe:\n self.log.debug(line)\n\n self.log.debug(\"This was the recipe\")\n except BaseException as e:\n self.log.error(\"Failed to load recipe\")\n raise e\n\n # This functions tries to handle an error of the test (eg. when 'echo \"Hello World\"' failed)\n # in an interactive way\n # returns False when the test should exit right now, and True when the test should go on\n def interactive_error_handling(self):\n if not self.settings.get_config_value(\"interactive_error_handling\"):\n return False\n\n _cmd = cmd.CMD(intro=\"You are droppped into an interative debugging shell because of the previous errors\",\n help={\"exit\": \"Exit the test rigth now\",\n \"continue\": \"Continues the test without any error handling, so do not expect that the test succeeds.\",\n \"debug\": \"Disconnects from the serial console and prints the devices to manually connect to the virtual machines.\" \\\n \"This is useful when you can fix th error with some manual commands. Please disconnect from the serial consoles and \" \\\n \"choose 'exit or 'continue' when you are done\"})\n\n command = _cmd.get_input(valid_commands=[\"continue\", \"exit\", \"debug\"])\n\n if command == \"continue\":\n # The test should go on but we do not any debugging, so we return True\n return True\n elif command == \"exit\":\n # The test should exit right now (normal behaviour)\n return False\n\n # If we get here we are in debugging mode\n # Disconnect from the serial console:\n\n for name in self.used_machine_names:\n _cmd.print_to_cmd(\"Disconnect from the serial console of {}\".format(name))\n self.virtual_machines[name].serial_disconnect()\n\n # Print the serial device for each machine\n for name in self.used_machine_names:\n device = self.virtual_machines[name].get_serial_device()\n _cmd.print_to_cmd(\"Serial device of {} is {}\".format(name, device))\n\n _cmd.print_to_cmd(\"You can now connect to all serial devices, and send custom commands to the virtual machines.\" \\\n \"Please type 'continue' or 'exit' when you disconnected from als serial devices and want to go on.\")\n\n command = _cmd.get_input(valid_commands=[\"continue\", \"exit\"])\n\n if command == \"exit\":\n return False\n\n # We should continue whit the test\n # Reconnect to the serial devices\n\n for name in self.used_machine_names:\n self.log.info(\"Try to reconnect to {}\".format(name))\n self.virtual_machines[name].serial_connect()\n\n return True\n\n def run_recipe(self):\n for line in self.recipe.recipe:\n return_value = self.virtual_machines[line[0]].cmd(line[2])\n self.log.debug(\"Return value is: {}\".format(return_value))\n if return_value != \"0\" and line[1] == \"\":\n err_msg = \"Failed to execute command '{}' on {}, return code: {}\".format(line[2],line[0], return_value)\n # Try to handle this error in an interactive way, if we cannot go on\n # raise an exception and exit\n if not self.interactive_error_handling():\n raise TestException(err_msg)\n\n elif return_value == \"0\" and line[1] == \"!\":\n err_msg = \"Succeded to execute command '{}' on {}, return code: {}\".format(line[2],line[0],return_value)\n self.log.error(err_msg)\n # Try to handle this error in an interactive way, if we cannot go on\n # raise an exception and exit\n if not self.interactive_error_handling():\n raise TestException(err_msg)\n else:\n self.log.debug(\"Command '{}' on {} returned with: {}\".format(line[2],line[0],return_value))\n\n def virtual_environ_stop(self):\n for name in self.used_machine_names:\n # We just catch exception here to avoid\n # that we stop the cleanup process if only one command fails\n try:\n self.virtual_machines[name].shutdown()\n self.virtual_machines[name].revert_snapshot()\n self.virtual_machines[name].undefine()\n except BaseException as e:\n self.log.exception(e)\n\n for name in self.virtual_environ.network_names:\n try:\n self.virtual_networks[name].undefine()\n except BaseException as e:\n self.log.exception(e)\n\n","sub_path":"src/nitsi/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":10569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"447854611","text":"import unittest\n\n\ndef reverse_integer(num):\n abs_num = abs(num)\n result = 0\n while abs_num != 0:\n pop = abs_num % 10\n abs_num //= 10\n result = result*10 + pop\n\n return result if num > 0 else -1*result\n\n\nclass test(unittest.TestCase):\n\n def test_rev(self):\n test_vals = [1234, -678, 0]\n expected_vals = [4321, -876, 0]\n\n actual_vals = [reverse_integer(v) for v in test_vals]\n\n for i, ev in enumerate(expected_vals):\n assert(ev == actual_vals[i])\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"reverse_integer.py","file_name":"reverse_integer.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"93438911","text":"\nfrom util.operate_mysql import *\nfrom urllib.request import *\nfrom util.common import *\nimport numpy as np\nimport pandas as pd\nimport os\nimport codecs\n\ndef init_sql_by_excel():\n clear_table('stock_deal')\n operatMySQl = OperateMySQL()\n path = u\"D:\\\\s_data\\\\\"\n #遍历目录所有文件\n s_data_list = os.listdir(path)\n for list_index in s_data_list:\n #读取交割单\n content_file = open(path+list_index, \"r\")\n contentss = content_file.read()\n content_file.close()\n contents_list = contentss.split('\\n')\n index = 0\n for content_item in contents_list:\n #忽略第一行,表单头\n if index ==0 :\n index = 1\n continue\n\n line_list = content_item.split(',')\n #深市代码补全0\n if len(line_list[0])>0 and int(line_list[0])>0 and int(line_list[0])<4000 :\n line_list[0] = '%06d' %int(line_list[0])\n\n if(len(line_list)>10):\n sqli = \"insert into stock_deal values ('{0[0]}','{0[1]}','{0[2]}',{0[3]},{0[4]},{0[5]},{0[6]},{0[7]},{0[8]},\" \\\n \"{0[9]},{0[10]},{0[11]},'{0[12]}','{0[13]}',\\\"{0[14]}\\\",{0[15]},{0[16]},{0[17]},'{0[18]}');\"\n sqlm = sqli.format(line_list)\n #print(sqlm)\n operatMySQl.execute(sqlm)\n operatMySQl.commit()\n\n#查询转入账户的金额之和\ndef query_amount_transferred_into_account():\n operatMySQl = OperateMySQL()\n conn, cur = operatMySQl.get_operater()\n sqlin =\"SELECT * FROM stock_deal where deal_type = '银行转证券'\"\n df_in = pd.read_sql(sqlin, conn)\n print(\"转入:%s笔, 共\" %len(df_in), sum(df_in['real_money']))\n sqlout =\"SELECT * FROM stock_deal where deal_type = '证券转银行'\"\n df_out = pd.read_sql(sqlout, conn)\n print(\"转出:%s笔, 共\" %len(df_out),sum(df_out['real_money']))\n\n print(\"账户:\", sum(df_in['real_money'])+sum(df_out['real_money']))\n\n sqlInterest =\"SELECT * FROM stock_deal where deal_type = '利息归本'\"\n df_sqlInterest = pd.read_sql(sqlInterest, conn)\n print(\"利息:%s笔, 共\" %len(df_sqlInterest),sum(df_sqlInterest['real_money']))\n\ndef query_reverse_repo():\n operatMySQl = OperateMySQL()\n conn, cur = operatMySQl.get_operater()\n sql_list = []\n sql_list.append((\"沪市1日\",\"SELECT * FROM stock_deal where stock_index = '204001'\"))\n sql_list.append((\"深市1日\",\"SELECT * FROM stock_deal where stock_index = '131810'\"))\n sql_list.append((\"天天1日\",\"SELECT * FROM stock_deal where stock_index = '205001'\"))\n sql_list.append((\"共计\", \"SELECT * FROM stock_deal where stock_index = '204001' or stock_index = '131810' or stock_index = '205001'\"))\n for sql in sql_list:\n df = pd.read_sql(sql[1], conn)\n print(\"{0}:{1}笔, 共:{2}\".format(sql[0], len(df),my_round(sum(df['real_money']))))\n\n '''\n sqlsh =\n df_sh = pd.read_sql(sqlsh, conn)\n print(\"沪市1日:%s笔, 共\" % len(df_sh), sum(df_sh['real_money']))\n\n sqlsz = \"SELECT * FROM stock_deal where stock_index = '131810'\"\n df_sz = pd.read_sql(sqlsz, conn)\n print(\"深市1日:%s笔, 共\" % len(df_sz), sum(df_sz['real_money']))\n\n sqlttl = \"SELECT * FROM stock_deal where stock_index = '205001'\"\n df_ttl = pd.read_sql(sqlttl, conn)\n print(\"天天1日:%s笔, 共\" % len(df_ttl), sum(df_ttl['real_money']))\n\n print(\"共计:%s笔, 共\" %(len(df_sh)+len(df_sz)+len(df_ttl)),sum(df_sh['real_money'])+sum(df_sz['real_money'])+sum(df_ttl['real_money']))\n '''\n#查询手续费 印花税\ndef query_fees_stamp_duty():\n operatMySQl = OperateMySQL()\n conn, cur = operatMySQl.get_operater()\n\n sql_list = []\n sql_list.append((\"沪市\", \"SELECT * FROM stock_deal where stock_index > '600000' and stock_index < '700000'\"))\n sql_list.append((\"深市\", \"SELECT * FROM stock_deal where stock_index > '000000' and stock_index < '100000'\"))\n sql_list.append((\"创业\", \"SELECT * FROM stock_deal where stock_index > '300000' and stock_index < '400000'\"))\n sql_list.append((\"基金\", \"SELECT * FROM stock_deal where stock_index > '150000' and stock_index < '200000'\"))\n sql_list.append((\"合计\", \"SELECT * FROM stock_deal where \"\n \"((stock_index > '300000' and stock_index < '700000') or (stock_index > '150000' and stock_index < '200000') or (stock_index > '000000' and stock_index < '100000'))\"))\n\n for sql in sql_list:\n df = pd.read_sql(sql[1], conn)\n print(\"{0}:{1}笔, 共:{2}, 手续费:{3},印花税:{4}, 成交额:{5}\".format(sql[0], len(df),\n my_round(sum(df['real_money'])), my_round(sum(df['fees'])),\n my_round(sum(df['stamp_duty'])), my_round(sum(df['deal_money']))))\n\ndef query_stock():\n operatMySQl = OperateMySQL()\n conn, cur = operatMySQl.get_operater()\n\n sql = \"SELECT * FROM stock_deal where \" \\\n \"((stock_index > '300000' and stock_index < '700000') or \" \\\n \"(stock_index > '150000' and stock_index < '200000') or \" \\\n \"(stock_index > '000000' and stock_index < '100000')) group by stock_index\"\n\n sql_read_row = \"SELECT * FROM stock_deal where stock_index = {0};\"\n sqli = \"insert into stock_earnings values ({0},{1},'{2}','{3}');\"\n df = pd.read_sql(sql, conn)\n print(len(df))\n df_result = pd.DataFrame(columns=['len','stock_index', 'stock_name', 'real_money' ])\n sum_r = 0.0\n for index,row in df.iterrows():\n sql_formated = sql_read_row.format(row['stock_index'])\n #print(sql_row)\n df_line = pd.read_sql(sql_formated, conn)\n #print(df_line)\n row_append = pd.DataFrame([dict(len=len(df_line),stock_index=row['stock_index'], stock_name =row['stock_name'], real_money=my_round(sum(df_line['real_money'])))])\n df_result = df_result.append(row_append, ignore_index=True)\n sum_r = sum_r + my_round(sum(df_line['real_money'])) #累计盈利\n\n sql_formated =sqli.format(len(df_line),my_round(sum(df_line['real_money'])),row['stock_index'],row['stock_name'])\n #print(row['stock_index'],row['stock_name'],my_round(sum(df_line['real_money'])), len(df_line))\n operatMySQl.execute(sql_formated)\n operatMySQl.commit()\n df_result=df_result.sort_values(by='real_money')\n #df_result=df_result.reset_index()\n\n #df_result.to_csv('d:\\\\result.csv')\n print(df_result)\n print(sum_r)\n\n\ndef query_earnings():\n operatMySQl = OperateMySQL()\n conn, cur = operatMySQl.get_operater()\n full_tabl = \"SELECT stock_index,len,real_money,stock_name,industry,area,pe,outstanding,totals,reservedPerShare FROM stock_earnings natural join stock_basic where \"\n deal_table = \"SELECT * FROM stock_earnings where \"\n sh_stock = \"(stock_index > '600000' and stock_index < '700000')\"\n sz_stock = \"(stock_index > '000000' and stock_index < '100000')\"\n cy_stock = \"(stock_index > '300000' and stock_index < '400000')\"\n jj_stock = \"(stock_index > '150000' and stock_index < '200000')\"\n money_greater = \"real_money>0\"\n money_lower = \"real_money<0\"\n order_by = \"order by real_money\"\n sql_list = []\n sql_list.append((\"沪市\", \"盈利\", \"{0} {1} and {2} {3} desc\".format(full_tabl,sh_stock,money_greater,order_by)))\n sql_list.append((\"深市\", \"盈利\", \"{0} {1} and {2} {3} desc\".format(full_tabl,sz_stock,money_greater,order_by)))\n sql_list.append((\"创业\", \"盈利\", \"{0} {1} and {2} {3} desc\".format(full_tabl,cy_stock,money_greater,order_by)))\n sql_list.append((\"基金\", \"盈利\", \"{0} {1} and {2} {3} desc\".format(deal_table,jj_stock,money_greater,order_by)))\n\n sql_list.append((\"沪市\", \"亏损\", \"{0} {1} and {2} {3} asc\".format(full_tabl,sh_stock,money_lower,order_by)))\n sql_list.append((\"深市\", \"亏损\", \"{0} {1} and {2} {3} asc\".format(full_tabl,sz_stock,money_lower,order_by)))\n sql_list.append((\"创业\", \"亏损\", \"{0} {1} and {2} {3} asc\".format(full_tabl,cy_stock,money_lower,order_by)))\n sql_list.append((\"基金\", \"亏损\", \"{0} {1} and {2} {3} asc\".format(deal_table,jj_stock,money_lower,order_by)))\n\n sql_list.append((\"沪市\", \"盈亏\", \"{0} {1} {2}\".format(full_tabl,sh_stock,order_by)))\n sql_list.append((\"深市\", \"盈亏\", \"{0} {1} {2}\".format(full_tabl,sz_stock,order_by)))\n sql_list.append((\"创业\", \"盈亏\", \"{0} {1} {2}\".format(full_tabl,cy_stock,order_by)))\n sql_list.append((\"基金\", \"盈亏\", \"{0} {1} {2}\".format(deal_table,jj_stock,order_by)))\n\n sql_list.append((\"合计\", \"盈亏\", \"SELECT * FROM stock_earnings \"))\n #\"((stock_index > '300000' and stock_index < '700000') or (stock_index > '150000' and stock_index < '200000') or (stock_index > '000000' and stock_index < '100000'))\"))\n\n save_file = 'd:\\\\result.csv'\n try:\n os.remove(save_file)\n except:\n pass\n\n for sql in sql_list:\n df = pd.read_sql(sql[2], conn)\n reslut_str = u\"{0},{1},{2}只, {3}笔, {4}\\n\".format(sql[0], sql[1], len(df), sum(df['len']), my_round(sum(df['real_money'])))\n\n #统计结果写入文件\n file_object = codecs.open(save_file, 'a')\n file_object.write(reslut_str)\n file_object.close()\n\n #替换表头\n if(len(df.columns)>4):\n df.columns = ['代码', '交易次数', '交割金额', '名称', '行业', '地区', '市盈', '流通', '总股本', '每股公积']\n elif(len(df.columns)==4):\n df.columns = [ '交易次数', '交割金额','代码', '名称']\n\n df.head(10).to_csv(save_file, index=False, mode = 'a')\n\n\ndef query_total_deal_money():\n operatMySQl = OperateMySQL()\n conn, cur = operatMySQl.get_operater()\n\n sql = \"SELECT * FROM stock_deal where \" \\\n \"((stock_index > '300000' and stock_index < '700000') or \" \\\n \"(stock_index > '150000' and stock_index < '200000') or \" \\\n \"(stock_index > '000000' and stock_index < '100000'))\"\n\n df = pd.read_sql(sql, conn)\n #print(df['stock_index'],df['stock_name'])\n print(len(df))\nif __name__ == '__main__':\n #init_sql_by_excel()\n #query_amount_transferred_into_account()\n #query_reverse_repo()\n #query_fees_stamp_duty()\n #query_total_deal_money()\n #query_stock()\n query_earnings()\n\n","sub_path":"account_calculation.py","file_name":"account_calculation.py","file_ext":"py","file_size_in_byte":10285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"186140961","text":"\"\"\"\nnat.py\n\nHandles network address translation for the tethering server. Provides a\nmany-to-many mapping from tethering clients to remote servers on the Internet.\n\n\nTHEORY\n\nThe central idea of this NAT implementation is that, if a port is bound \nlocally and nothing has been sent from that port, then there is little to\nno chance traffic will arrive on that port. \n\nTo provide network access translation, nat.py tracks (TCP and UDP) connections\nbeing established by local endpoints. When a connection is established by a \nlocal endpoint, nat.py binds to a 'physical' port, on the router. It maps the \ndetails of this virtual connection (bridge IP, client IP, protocol, port) to\nthe 'physical' port.\n\nOnce this is complete, the router can modify the IP packet initiating the\nvirtual connection such that:\n\n o The address corresponds to the router's Internet-facing IP address\n o The port number corresponds to the physical port allocated for this\n connection\n\nAt this point, we can be reasonably sure that any packet that is addressed\nto the router over that physical port is meant for the client who established\nthe virtual connection. This holds even for protocols like DNS, where the\nIP address over the server who responded to the request might be different\nfrom the request's original address.\n\nnat.py doesn't do deep-packet inspection, so it has no way of knowing (for\nsure) when a connection is terminated. Instead, a configurable quota \ndetermines how many physical ports nat.py is allowed to bind. Once the\nquota is exceeded, the least recently used connection is recycled.\n\n\nUSAGE\n\nThe number of physical ports nat.py can bind is {nat.quota}.\n\n nat.quota = 2048 # allow a max of 2048 unique outgoing connections\n\nNetwork address translation can be performed in two directions.\nTo translate an outgoing packet, simply call\n\n nat.translate_outgoing(packet, bridgeIP)\n\nwhere {packet} is a scapy packet object and {bridgeIP} is a string. \nThe packet is modified in place, and a boolean value is returned indicating \nwhether or not a new connection was established.\n\nTo translate an incoming packet, call\n\n nat.translate_incoming(packet)\n\n. Again, {packet} is a scapy packet object, which will be modified in place.\nThe function returns a string containing the bridge IP the packet should be\nsent to, or None if the packet doesn't correspond to a known connection. In\nthe latter case, the packet was likely meant for the system on top of which\nthe router is running.\n\n\"\"\"\n\n\nfrom collections import deque\nfrom scapy.all import *\nfrom socket import *\nfrom time import time\n\n\nclass _Connection:\n \"\"\" Information about a virtual connection initiated by a client \"\"\"\n\n def __init__(self):\n baddr = \"\" # IP address of bridge (to whom the packet is sent)\n caddr = \"\" # IP address of client (to whom the packet is addressed)\n prot = \"\" # Protocol, \"tcp\" or \"udp\" or \"unk\"\n vport = 0 # Port number on client packets should be sent to\n port = 0 # Port number on router allocated for this connection\n updated = 0.0 # Time the connection was last touched\n\n def onopen(self):\n \"\"\"\n Updates global data structures.\n Should be called when a connection is opened or recycled.\n \"\"\"\n\n global _physconn\n global _virtconn\n \n _physconn[(self.prot, self.port)] = self\n _virtconn[(self.prot, self.vport, self.baddr)] = self\n\n self.touch()\n\n def touch(self): # lols\n \"\"\" \n Updates the updated field to correspond to the current time.\n Should= be called whenever this connection is involved in a \n translate_outgoing() or translate_incoming() operation\n \"\"\"\n\n global _tcplru\n global _udplru\n\n assert self.prot == \"tcp\" or self.prot == \"udp\" # NYI \"unk\"\n lru = _tcplru if self.prot == \"tcp\" else _udplru\n\n if self in lru:\n lru.remove(self)\n\n self.updated = time()\n lru.append(self)\n\n def onclose(self):\n \"\"\"\n Updates global data structures.\n Should be called when a connection is deleted.\n \"\"\"\n\n global _physconn\n global _virtconn\n global _tcplru\n global _udplru\n\n del(_physconn[(self.prot, self.port)])\n del(_virtconn[(self.prot, self.vport, self.baddr)])\n\n if _tcplru.contains(self):\n _tcplru.remove(self)\n\n if _udplru.contains(self):\n _udplru.remove(self)\n \n\n\ndef _prot(packet):\n \"\"\" Determine the protocol of a packet \"\"\"\n if packet.haslayer(TCP):\n return \"tcp\"\n\n if packet.haslayer(UDP):\n return \"udp\"\n\n return \"unk\"\n\ndef _sport(packet):\n \"\"\" Determine the source port of a packet, -1 if n/a \"\"\"\n if packet.haslayer(TCP):\n return packet[TCP].sport\n\n if packet.haslayer(UDP):\n return packet[UDP].sport\n\n return -1\n\ndef _dport(packet):\n \"\"\" Determine the destination port of a packet, -1 if n/a \"\"\"\n if packet.haslayer(TCP):\n return packet[TCP].dport\n\n if packet.haslayer(UDP):\n return packet[UDP].dport\n\n return -1\n\n_myip = None\ndef me():\n global _myip\n if _myip == None:\n s = socket(AF_INET, SOCK_DGRAM)\n s.connect((\"gmail.com\",80))\n _myip = s.getsockname()[0]\n s.close()\n\n return _myip\n\ndef _alloc(prot):\n \"\"\" Allocate a physical port for a virtual connection \"\"\"\n\n global _tcplru\n global _udplru\n\n assert prot == \"tcp\" or prot == \"udp\"\n lru = _tcplru if prot == \"tcp\" else _udplru\n\n # If quota reached, recycle a stale connection's port\n if len(lru) >= quota: \n c = lru.popleft()\n c.onclose()\n return c.port\n\n # Quota not reached -- allocate a new port\n sock = socket(AF_INET, SOCK_STREAM if prot == \"tcp\" else SOCK_DGRAM)\n sock.bind((\"\", 0))\n return sock.getsockname()[1]\n\n\n_physconn = { } # (prot, port) => _Connection\n_virtconn = { } # (prot, vport, baddr) => _Connection\n_tcplru = deque([ ]) # queue of _Connection, sorted by _Connection.updated, TCP only\n_udplru = deque([ ]) # queue of _Connection, sorted by _Connection.updated, UDP only\n\n\nquota = 1024\n\n\ndef translate_outgoing(packet, bridgeIP):\n \"\"\" \n Perform network address translation on a packet leaving the router,\n from a local endpoint to the Internet.\n\n Returns a boolean indicating whether a the packet was successfully translated\n and should therefore be sent out\n \"\"\"\n\n prot = _prot(packet)\n if prot != \"tcp\" and prot != \"udp\":\n return False\n\n virt = (_prot(packet), _sport(packet), bridgeIP)\n c = None\n\n if not virt in _virtconn: # new connection\n c = _Connection()\n c.baddr = bridgeIP\n c.caddr = packet[IP].src\n c.prot = virt[0]\n c.vport = virt[1]\n c.port = _alloc(c.prot)\n c.onopen()\n else: # new packet in existing connection\n c = _virtconn[virt]\n\n packet.src = me()\n del(packet[IP].chksum)\n\n if packet.haslayer(TCP):\n packet[TCP].sport = c.port\n del(packet[TCP].chksum)\n elif packet.haslayer(UDP):\n packet[UDP].sport = c.port\n del(packet[UDP].chksum)\n\n return True\n\n\ndef translate_incoming(packet):\n \"\"\"\n Perform network address translation on a packet arriving at the router,\n from the Internet to a local endpoint.\n\n Returns a string containing the bridge IP, or None if connection is\n established.\n \"\"\"\n if not packet.haslayer(IP):\n return None # can't forward\n\n if packet[IP].dst != me():\n return None # not addressed to me\n\n phys = (_prot(packet), _dport(packet))\n\n if not phys in _physconn:\n return None # no virtual connection over this protocol+port\n\n c = _physconn[phys]\n\n packet[IP].dst = c.caddr\n del(packet[IP].chksum)\n\n if packet.haslayer(TCP):\n packet[TCP].dport = c.vport\n del(packet[TCP].chksum)\n elif packet.haslayer(UDP):\n packet[UDP].dport = c.vport\n del(packet[UDP].chksum)\n del(packet[IP].len)\n del(packet[UDP].len)\n\n return c.baddr\n\n","sub_path":"server/nat.py","file_name":"nat.py","file_ext":"py","file_size_in_byte":7697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"268837980","text":"\"\"\"\nMikkel Hansen\n\"\"\"\n\n\ndef main():\n name = get_name()\n\n freq = int(input(\"input the frequency of letters to print: \"))\n print_letters_of_freq(name, freq)\n\n\ndef get_name():\n name = str(input(\"input your name: \"))\n status = error_check(name)\n while status != \"Only alphabetical letters and spaces: yes\":\n print(status)\n name = str(input(\"error!! input your name: \"))\n status = error_check(name)\n print(status)\n return name\n\n\ndef error_check(name):\n if all(x.isalpha() or x.isspace() for x in name):\n return \"Only alphabetical letters and spaces: yes\"\n else:\n return \"Only alphabetical letters and spaces: no\"\n\n\ndef print_letters_of_freq(name, freq):\n for i in range(len(name)):\n if i % freq == 0:\n print(name[i], end=\" \")\n\n\nmain()\n","sub_path":"oddName.py","file_name":"oddName.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"543553817","text":"\"\"\"icapitstop URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path,include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom . import views\n\nurlpatterns = [\n path('',views.index, name='index'),\n path('login.html',views.login, name='login'),\n path('admin.html',views.adminPage, name='adminPage'),\n path('index.html',views.index, name='index'),\n path('account.html',views.account, name='account'),\n path('shop.html',views.shopShowAllProducts, name='shopShowAllProducts'),\n path('shopShowAllProducts',views.shopShowAllProducts, name='shopShowAllProducts'),\n path('cart.html',views.displayCartProducts, name='displayCartProducts'),\n path('place_order',views.place_order, name='place_order'),\n path('checkout.html',views.checkout, name='checkout'),\n path('supplier-orders.html',views.supplierPage, name='supplierPage'),\n path('supplier-products.html',views.supplierPageProducts, name='supplierPageProducts'),\n path('modifyOrderState',views.modifyOrderState, name='modifyOrderState'),\n path('logout.html',views.logout,name='logout'),\n path('addProductToCart',views.addProductToCart,name='addProductToCart'),\n path('addOneProduct',views.addOneProduct,name='addOneProduct'),\n path('removeOneProduct',views.removeOneProduct,name='removeOneProduct'),\n path('interested',views.interested,name='interested'),\n path('contact_us',views.contact_us,name='contact_us'),\n path('delete_supp',views.delete_supp,name='delete_supp'),\n path('update_infos',views.update_infos,name='update_infos'),\n path('change_password',views.change_password,name='change_password'),\n path('update_discount',views.update_discount,name='update_discount'),\n path('create_supplier',views.create_supplier,name='create_supplier'),\n path('read_msg',views.read_msg,name='read_msg'),\n path('send_msg',views.send_msg,name='send_msg'),\n path('send_mail_to_client',views.send_mail_to_client,name='send_mail_to_client'),\n path('delete_msg',views.delete_msg,name='delete_msg'),\n path('add_new_product',views.add_new_product, name='add_new_product'),\n path('deleteProductFromCart',views.deleteProductFromCart,name='deleteProductFromCart'),\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)","sub_path":"icapitstop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"106176545","text":"import speech_recognition as sr\nimport os\nimport signal\nimport sys\nimport pyvona\nfrom urllib import request\nimport json\n\nr = sr.Recognizer()\nskyeListening = False\nvoice = pyvona.create_voice('GDNAJLXBSXZ5SF2J65LA', 'ZEPIRgVi/bppB7gq4VGlKDesbvJYir24LAdAhRAO')\nvoice.voice_name = \"Salli\"\n\ndef timeHandler(signum, frame):\n print(\"Speech Exceeds Timeout Limit!\")\n raise OverflowError(\"Speech Limit Exceeded\")\n\n\nwith sr.Microphone(device_index=2, sample_rate=48000) as source:\n print(\"Initializing Microphone...\")\n r.adjust_for_ambient_noise(source, duration = 1)\n r.dynamic_energy_threshold = False\n r.dynamic_energy_adjustment_damping = 0.15\n r.dynamic_energy_adjustment_ratio = 1.5\n if r.energy_threshold < 400:\n r.energy_threshold = 420\n r.pause_threshold = 0.5\n\ndef speechListen():\n try:\n audio = r.listen(source, timeout = 3)\n return audio\n except sr.WaitTimeoutError as e: \n raise e\n\n\ndef transcribe(audio):\n global skyeListening\n try:\n if skyeListening:\n text = r.recognize_google(audio)\n print(text)\n os.popen(\"aplay SkyeProcessing.wav\")\n query_msg = \"+\".join(text.split())\n request_url = \"https://ec2-54-201-211-179.us-west-2.compute.amazonaws.com/chat?apiKey=2309sdlsdlk3420923sdlksdlk2423l3490244dlf&msg=\" + query_msg + \"&user=aef57655-6967-472c-8c7e-c9c1f6193f09\"\n skye_response_api = request.urlopen(request_url)\n skye_response_json = \"\"\n\n while True:\n line = bytes.decode((skye_response_api.readline()))\n if line != '':\n skye_response_json += line\n else:\n break\n \n data = json.loads(skye_response_json)\n msg = data.get(\"msg\")\n voice.speak(msg)\n if 'bye' in str(text).lower():\n os.popen(\"aplay SkyeOff.wav\")\n sys.exit(0)\n os.popen(\"aplay SkyeOn.wav\")\n else:\n text = r.recognize_google(audio, show_all=True)\n print(\"Google Speech Recognition thinks you said \" + str(text))\n if \"sky\" in str(text).lower():\n os.popen(\"aplay SkyeOn.wav\")\n skyeListening = True\n if 'bye' in str(text).lower():\n os.popen(\"aplay SkyeOff.wav\")\n sys.exit(0)\n except sr.UnknownValueError:\n print(\"Google Speech Recognition could not understand audio\")\n except sr.RequestError as e:\n print(\"Could not request results from Google Speech Recognition service; {0}\".format(e))\n\nwith sr.Microphone(device_index=2, sample_rate=48000) as source:\n voice.speak(\"Skye is ready.\")\n while True:\n print(\"Start speaking...\")\n print(r.energy_threshold)\n try:\n signal.signal(signal.SIGALRM, timeHandler)\n signal.alarm(10)\n audio = speechListen()\n except sr.WaitTimeoutError:\n print(\"Timeout...\")\n print(\"Restarting...\")\n continue\n except OverflowError:\n continue\n signal.alarm(0)\n print(\"Stopped!\")\n transcribe(audio)\n","sub_path":"RobotCortex/SkyeCortex/SkyeVoiceDetection/Python/Test/tts.py","file_name":"tts.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"304492787","text":"from django.db import models\n\nfrom datetime import datetime\n\n# Create your models here.\n\n\nclass Patient(models.Model):\n first_name = models.CharField(default=\"\",max_length=20);\n last_name = models.CharField(default=\"\",max_length=20);\n doctor = models.PositiveIntegerField(default=-1);\n gender = models.CharField(default=\"Male\",max_length=60);\n date_of_birth = models.CharField(default=str(datetime.now()), max_length= 10);\n\n\n# python manage.py makemigrations\n# python manage.py migrate\n\nclass User(models.Model):\n user_name = models.CharField(max_length=20);\n access_token = models.CharField(max_length=100);\n\nclass Appointment(models.Model):\n patient = models.PositiveIntegerField(default=-1);\n status = models.CharField(default=\"\",max_length=20);\n scheduled_time = models.DateTimeField(blank=True,default=datetime.now());\n duration = models.PositiveIntegerField(default=0);\n dr_seeing = models.BooleanField(default=False)\n dr_seeing_time = models.DateTimeField(null=True, blank=True)\n \n ","sub_path":"drchrono/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"134301083","text":"from numpy import *\nimport os\n# 将文件中的数据存到数组中\ndef loadDataSet():\n dataMat = []; labelMat = []\n with open('./Ch05/testSet.txt') as fr:\n for line in fr.readlines():\n lineArr = line.strip().split()\n # 两个特征X1,X2,即z=w0*x0+w1*x1+w2*x2,而x0=1\n # 由假设函数可知,两个分类的分界线是z=0\n dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])\n labelMat.append(int(lineArr[2]))\n return dataMat, labelMat\n\n# sigmoid函数\ndef sigmoid(inX):\n return 1.0 / (1+exp(-inX))\n\n# 梯度上升算法:求最大值。对应的梯度下降算法求最小值\ndef gradAscent(dataMatIn, classLabels):\n dataMatrix = mat(dataMatIn) # ndarray转matrix\n labelMat = mat(classLabels).transpose() # 等价于mat(classLabels).T\n m, n = shape(dataMatrix) #矩阵的维数\n alpha = 0.001\n maxCycles = 500\n weights = ones((n, 1)) # numpy.ndarray\n for i in range(maxCycles):\n h = sigmoid(dataMatrix*weights) # 矩阵可直接和数组相乘\n error = labelMat - h \n weights = weights + alpha*dataMatrix.transpose()*error\n '''\n 梯度下降算法\n error = h - labelMat\n weights = weights - alpah*dataMatrix.T*error\n '''\n return weights\n\n# 随机梯度上升算法\ndef stocGranAscent0(dataArr, classLabels, iterNum=1):\n m,n = shape(dataArr) # dataArr需要为numpy.ndarray\n alpha = 0.01\n weights = ones(n)\n for j in range(iterNum):\n for i in range(m):\n h = sigmoid(sum(dataArr[i]*weights))\n error = classLabels[i] - h\n weights = weights + alpha*error*dataArr[i]\n return weights\n\n# 改进的随机梯度上升算法:1.每次迭代更新alpha 2.随机选取样本更新回归系数:防止系数出现周期性波动(部分样本不能正确分类)\ndef stocGranAscent1(dataArr, classLabels, iterNum=150):\n m, n =shape(dataArr)\n weights = ones(n)\n for j in range(iterNum):\n dataIndex = list(range(m))\n for i in range(m):\n alpha = 4/(1.0+j+i) + 0.001 # 这里留有疑问\n randIndex = int(random.uniform(0, len(dataIndex)))\n h = sigmoid(sum(dataArr[randIndex]*weights))\n error = classLabels[randIndex] - h\n weights = weights + alpha*error*dataArr[randIndex]\n del(dataIndex[randIndex])\n return weights\n\n# 画图\ndef plotBestFit(weights) :\n import matplotlib.pyplot as plt\n dataMat, labelMat = loadDataSet()\n dataArr = array(dataMat) # 转成ndarray\n n = shape(dataArr)[0]\n xcord1 = []; ycord1 = []\n xcord2 = []; ycord2 = []\n for i in range(n):\n if int(labelMat[i]) == 1:\n xcord1.append(dataArr[i,1])\n ycord1.append(dataArr[i,2])\n else:\n xcord2.append(dataArr[i,1])\n ycord2.append(dataArr[i,2])\n fig = plt.figure()\n ax = fig.add_subplot(111) # 画在1行1列,第一块\n # scatter(x,y,s=size,c=color,marker=形状),画散点图\n ax.scatter(xcord1, ycord1, s=30, c='red', marker='s')\n ax.scatter(xcord2, ycord2, s=30, c='green')\n x = arange(-3.0, 3.0, 0.1)\n y = (-weights[0]-weights[1]*x) / weights[2] # z=0是两个分类的分界线,由此解出x1与x2的关系\n ax.plot(x,y) # 根据x和y画线\n plt.xlabel('X1'); plt.ylabel('X2')\n plt.show()\n \ndef classifyVector(inX, weights):\n p = sigmoid(sum(inX*weights))\n if p > 0.5: return 1.0\n else: return 0.0\n \ndef colicTest():\n trainingSet = []; trainingLabels = []\n with open('./Ch05/horseColicTraining.txt') as ftTrain:\n for line in ftTrain.readlines():\n currLine = line.strip().split('\\t')\n lineArr = []\n for i in range(21):\n lineArr.append(float(currLine[i]))\n trainingSet.append(lineArr)\n trainingLabels.append(float(currLine[21])) # 标签\n trainWeights = stocGranAscent1(array(trainingSet), trainingLabels,500)\n errorCount = 0; numTestVec = 0.0\n with open('./Ch05/horseColicTest.txt') as frTest:\n for line in frTest.readlines():\n numTestVec += 1.0\n currLine = line.strip().split('\\t')\n lineArr = []\n for i in range(21):\n lineArr.append(float(currLine[i]))\n if int(classifyVector(array(lineArr), trainWeights)) != int(currLine[21]):\n errorCount += 1\n errorRate = float(errorCount) / numTestVec\n print('error rate is', errorRate)\n return errorRate\n\ndef multiTest():\n numTests = 10; errorSum = 0.0\n for k in range(numTests):\n errorSum += colicTest()\n print('after',numTests,'iterations the average over error rate is',errorSum/float(numTests))\n\n\nif __name__ == \"__main__\":\n # print(os.getcwd())\n dataArr, labelMat = loadDataSet()\n result = gradAscent(dataArr, labelMat)\n print(result)\n plotBestFit(result.getA()) # matrix.getA():矩阵转ndarray\n","sub_path":"mycode/Ch05/logRegres.py","file_name":"logRegres.py","file_ext":"py","file_size_in_byte":4972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"584614499","text":"import torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\n\nfrom transformers import Trainer\n\nimport numpy as np\nimport itertools\nfrom tqdm import trange\nimport pickle\nimport json\nimport os\n\nimport logging\n\nlogger = logging.getLogger(\"sequence_tagger_auto\")\n\n\nclass TextClassifier:\n def __init__(\n self,\n auto_model,\n bpe_tokenizer,\n max_len=192,\n pred_loader_args={\"num_workers\": 1},\n pred_batch_size=100,\n training_args=None,\n trainer=None,\n ):\n super().__init__()\n\n self._auto_model = auto_model\n self._bpe_tokenizer = bpe_tokenizer\n self._pred_loader_args = pred_loader_args\n self._pred_batch_size = pred_batch_size\n self._training_args = training_args\n self._trainer = trainer\n self._named_parameters = auto_model.named_parameters\n\n def predict(self, eval_dataset, evaluate=False, metrics=None):\n if metrics is None:\n metrics = []\n\n self._auto_model.eval()\n\n logits, _, metrics = self._trainer.predict(eval_dataset)\n probs = F.softmax(torch.tensor(logits), dim=1).numpy()\n preds = np.argmax(probs, axis=1)\n print(metrics)\n\n return preds, probs\n","sub_path":"src/ue4nlp/text_classifier.py","file_name":"text_classifier.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"401432247","text":"\"\"\"\nIt is an efficient way of computing the matrix multiplication MTxM,\nwhere M[i,j] is the user i's view count on page j.\nIn the result, scores[i,j] = Σ(M[k,i]*M[k,j]), 0 <= k < number of users.\n\"\"\"\nimport sys\nfrom collections import defaultdict\n\ndef addCooccurrencesPerUser(pageViews, scores):\n \"\"\"\n pageViews = [(page1, views1), ..., (pageN, viewsN)]\n \"\"\"\n\n if len(pageViews) <= 1:\n return\n\n scores[(-1, -1)] += 1\n for c1 in pageViews:\n scores[(c1[0], -1)] += c1[1]\n for c2 in pageViews:\n scores[(c1[0], c2[0])] += c1[1] * c2[1]\n\ndef computeCooccurrences(userPageViews):\n \"\"\"\n userPageViews = {user1: pageViews1, ..., userM: pageViewsM},\n pageViews1 = [(page1, views1), ..., (pageN, viewsN)]\n \"\"\"\n\n scores = defaultdict(int)\n for user, pageViews in userPageViews.items():\n addCooccurrencesPerUser(pageViews, scores)\n return scores\n\nif __name__ == '__main__':\n userPageViews = {\n 11: [(1, 0), (2, 2), (3, 5)],\n 22: [(1, 1), (2, 3), (3, 4)],\n }\n scores = computeCooccurrences(userPageViews)\n print(scores)\n","sub_path":"algorithms/ReadCooccurrences/ReadCooccurrences.py","file_name":"ReadCooccurrences.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"2379179","text":"from conans import ConanFile, CMake, tools\nimport os\n\nclass QtMqttConan(ConanFile):\n name = \"qt6mqtt\"\n url = \"https://github.com/kevanvanderstichelen/QtMqtt\"\n license = \"MIT\"\n description = \"MQTT protocol implementation in Qt\"\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n options = {\"shared\": [True, False] }\n default_options = \"shared=False\"\n generators = \"cmake\"\n exports_sources = \"*\"\n\n def config_options(self):\n if self.settings.compiler == 'gcc' and float(self.settings.compiler.version.value) >= 5.1:\n self.settings.compiler.libcxx = 'libstdc++11'\n if self.settings.compiler == 'clang' and float(self.settings.compiler.version.value) >= 11:\n self.settings.compiler.libcxx = 'libstdc++11'\n\n def source(self):\n self.run(\"git clone --branch 1.0.1 https://github.com/kevanvanderstichelen/QtMqtt.git qt6mqtt\")\n \n def build(self):\n cmake = CMake(self)\n cmake.definitions[\"CMAKE_PREFIX_PATH\"] = os.environ[\"QTDIR\"]\n cmake.definitions[\"QT_QMAKE_EXECUTABLE\"] = os.environ[\"QTDIR\"] + \"/bin/qmake\"\n if self.settings.compiler == 'clang' and self.settings.os == \"Linux\":\n cmake.definitions[\"CMAKE_EXE_LINKER_FLAGS\"] = \"-stdlib=libc++\"\n cmake.definitions[\"CMAKE_CXX_FLAGS\"] = \"-stdlib=libc++\"\n cmake.configure(source_folder=\"qt6mqtt\")\n cmake.build()\n cmake.test(output_on_failure=True)\n cmake.install()\n\n def package(self):\n #nothing to do here. All is handled by cmake.install() above.\n pass\n\n def package_info(self):\n self.cpp_info.libs = [\"Qt6Mqtt\"]\n","sub_path":"conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"15701017","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.gaussian_process.kernels import RBF, WhiteKernel\nimport csv\nimport time\n\nimport matplotlib as mpl\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# Function for converting time to formatted string\ndef convert_time(t):\n minutes = np.floor((t/3600.0) * 60)\n seconds = np.ceil(((t/3600.0) * 60 - minutes) * 60)\n if (minutes >= 1):\n minutes = np.floor(t/60.0)\n seconds = np.ceil((t/60.0 - minutes) * 60)\n t_str = str(int(minutes)).rjust(2) + 'm ' + \\\n str(int(seconds)).rjust(2) + 's'\n else:\n seconds = (t/60.0 - minutes) * 60\n t_str = str(seconds) + 's'\n return t_str\n\n# Define function for removing axes from MatPlotLib plots\ndef remove_axes(ax):\n # make the panes transparent\n ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n # make the grid lines transparent\n ax.xaxis._axinfo[\"grid\"]['color'] = (1,1,1,0)\n ax.yaxis._axinfo[\"grid\"]['color'] = (1,1,1,0)\n ax.zaxis._axinfo[\"grid\"]['color'] = (1,1,1,0)\n # remove axes\n ax._axis3don = False\n\n\n# Evaluate SciKit Learn Gaussian Process Regressor and Plot Results\ndef main():\n\n\n # First determine the dimension of the input values\n filename = \"predictions.csv\"\n with open(filename, \"r\") as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',', quotechar='|')\n row = next(csvreader)\n nonInputLength = 3\n inputDim = len(row) - nonInputLength\n\n # Get prediction data\n filename = \"predictions.csv\"\n inVals = []; trueVals = []; predMean = []; predStd = []\n with open(filename, \"r\") as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',', quotechar='|')\n for row in csvreader:\n\n if inputDim == 2:\n i1, i2, t, m, v = row\n inVals.append([i1,i2])\n else:\n i, t, m, v = row\n inVals.append(i)\n \n trueVals.append(t)\n predMean.append(m)\n predStd.append(v)\n inVals = np.array(inVals).astype(np.float32)\n trueVals = np.array(trueVals).astype(np.float32)\n predMean = np.array(predMean).astype(np.float32)\n predStd = np.array(predStd).astype(np.float32)\n\n ## Get observation data\n filename = \"observations.csv\"\n obsX = []; obsY = []\n with open(filename, \"r\") as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',', quotechar='|')\n for row in csvreader:\n if inputDim == 2:\n x1, x2, y = row\n obsX.append([x1,x2])\n else:\n x, y = row\n obsX.append(x)\n obsY.append(y)\n obsX = np.array(obsX).astype(np.float32)\n obsY = np.array(obsY).astype(np.float32)\n\n\n\n if inputDim == 1:\n # Get posterior samples\n filename = \"samples.csv\"\n samples = []\n with open(filename, \"r\") as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',', quotechar='|')\n for row in csvreader:\n vals = np.array(row)\n samples.append(vals)\n samples = np.array(samples).astype(np.float32)\n \n \n ### SCIKIT LEARN IMPLEMENTATION\n X = np.reshape(obsX, [-1, inputDim])\n Y = np.reshape(obsY, [-1])\n Xtest = np.reshape(inVals, [-1, inputDim])\n\n\n # Model parameters\n n_restarts = 0\n normalize_y = False\n use_white_noise = True\n RBF_bounds = [0.01, 100.0]\n Noise_bounds = [0.00001, 10.0]\n jitter = 1e-7\n\n # Define kernel for SciKit Learn Gaussian process regression model\n if use_white_noise:\n kernel = RBF(length_scale=1.0, length_scale_bounds=(RBF_bounds[0],RBF_bounds[1])) + \\\n WhiteKernel(noise_level=1, noise_level_bounds=(Noise_bounds[0], Noise_bounds[1]))\n else:\n kernel = RBF(length_scale=1.0, length_scale_bounds=(RBF_bounds[0],RBF_bounds[1]))\n\n # Fit model to data\n start_time = time.time()\n model = GaussianProcessRegressor(kernel=kernel, alpha=jitter, optimizer='fmin_l_bfgs_b',\n normalize_y=normalize_y, n_restarts_optimizer=n_restarts).fit(X, Y)\n end_time = time.time()\n\n # Display computation time \n time_elapsed = convert_time(end_time-start_time)\n print('\\nComputation Time: ' + time_elapsed + '\\n') \n\n print(\"Optimized Kernel Parameters:\")\n print(model.kernel_)\n print(\" \")\n mean, std = model.predict(Xtest, return_std=True)\n\n if inputDim == 1:\n model_samples = model.sample_y(Xtest, samples.shape[0])\n\n NLML = -model.log_marginal_likelihood()\n print(\"NLML: {:.4f}\\n\".format(NLML))\n\n\n\n\n ### ###\n ### PLOT RESULTS ###\n ### ###\n\n if inputDim == 1:\n\n \"\"\" ONE-DIMENSIONAL PLOTS \"\"\"\n \n # Plot Scikit Learn results\n plt.figure()\n plt.plot(inVals, mean, 'C0', linewidth=2.0)\n alpha = 0.075\n for k in [1,2,3]:\n plt.fill_between(inVals, mean-k*std, mean+k*std, where=1 >= 0, facecolor=\"C0\", alpha=alpha, interpolate=True, label=None)\n plt.plot(inVals, trueVals, 'C1', linewidth=1.0, linestyle=\"dashed\")\n alpha_scatter = 0.5\n plt.scatter(obsX, obsY, alpha=alpha_scatter)\n for i in range(0,model_samples.shape[1]):\n plt.plot(inVals, model_samples[:,i], 'C0', alpha=0.2, linewidth=1.0, linestyle=\"dashed\")\n plt.suptitle(\"Scikit Learn Implementation\")\n\n\n ### C++ IMPLEMENTATION\n plt.figure() \n plt.plot(inVals, predMean, 'C0', linewidth=2.0)\n for k in [1,2,3]:\n plt.fill_between(inVals, predMean-k*predStd, predMean+k*predStd, where=1>=0, facecolor=\"C0\", alpha=alpha, interpolate=True)\n plt.plot(inVals, trueVals, 'C1', linewidth=1.0, linestyle=\"dashed\")\n plt.scatter(obsX, obsY, alpha=alpha_scatter)\n for i in range(0,samples.shape[0]):\n plt.plot(inVals, samples[i,:], 'C0', alpha=0.2, linewidth=1.0, linestyle=\"dashed\")\n plt.suptitle(\"C++ Implementation\") \n plt.show()\n\n\n\n\n \n \n elif inputDim == 2:\n\n \"\"\" TWO-DIMENSIONAL PLOTS \"\"\"\n \n # Flatten input values for compatibility with MatPlotLib's tri_surf\n plot_X_flat = []; plot_Y_flat = []\n R = inVals.shape[0]\n for n in range(0,R):\n plot_X_flat.append(inVals[n,0])\n plot_Y_flat.append(inVals[n,1])\n\n tri_fig = plt.figure()\n tri_ax1 = tri_fig.add_subplot(121, projection='3d')\n linewidth = 0.1\n cmap = \"Blues\"\n\n # Plot CppGPs results\n tri_ax1.plot_trisurf(plot_X_flat,plot_Y_flat, predMean, cmap=cmap, linewidth=linewidth, antialiased=True)\n pred_title = \"CppGPs\"\n tri_ax1.set_title(pred_title, fontsize=24)\n\n # Plot SciKit Learn results \n tri_ax2 = tri_fig.add_subplot(122, projection='3d')\n tri_ax2.plot_trisurf(plot_X_flat,plot_Y_flat, mean, cmap=cmap, linewidth=linewidth, antialiased=True)\n soln_title = \"SciKit Learn\"\n tri_ax2.set_title(soln_title, fontsize=24)\n\n # Remove axes from plots\n remove_axes(tri_ax1) \n remove_axes(tri_ax2) \n\n # Bind axes for comparison\n def tri_on_move(event):\n if event.inaxes == tri_ax1:\n if tri_ax1.button_pressed in tri_ax1._rotate_btn:\n tri_ax2.view_init(elev=tri_ax1.elev, azim=tri_ax1.azim)\n elif tri_ax1.button_pressed in tri_ax1._zoom_btn:\n tri_ax2.set_xlim3d(tri_ax1.get_xlim3d())\n tri_ax2.set_ylim3d(tri_ax1.get_ylim3d())\n tri_ax2.set_zlim3d(tri_ax1.get_zlim3d())\n elif event.inaxes == tri_ax2:\n if tri_ax2.button_pressed in tri_ax2._rotate_btn:\n tri_ax1.view_init(elev=tri_ax2.elev, azim=tri_ax2.azim)\n elif tri_ax2.button_pressed in tri_ax2._zoom_btn:\n tri_ax1.set_xlim3d(tri_ax2.get_xlim3d())\n tri_ax1.set_ylim3d(tri_ax2.get_ylim3d())\n tri_ax1.set_zlim3d(tri_ax2.get_zlim3d())\n else:\n return\n tri_fig.canvas.draw_idle()\n tri_c1 = tri_fig.canvas.mpl_connect('motion_notify_event', tri_on_move)\n\n\n\n \"\"\" Zoom in to view predictive uncertainty \"\"\"\n plot_radius = 0.5\n plot_x_min = -0.125\n plot_y_min = -0.125\n plot_x_max = 0.25\n\n # Define conditions for including values associated with an input point (x,y)\n def include_conditions(x,y,delta=0.0):\n rad = np.sqrt(np.power(x,2) + np.power(y,2))\n return (x-delta<=plot_x_max) and (x+delta>=plot_x_min) and (y+delta>=plot_y_min) and (rad-delta<=plot_radius)\n\n\n # Restrict plots to values corresponding to valid input points\n R = inVals.shape[0] \n plot_X_zoom = []; plot_Y_zoom = []; predMean_zoom = []\n predMean_plus_std = []; predMean_minus_std = []\n predMean_plus_std2 = []; predMean_minus_std2 = []\n predMean_plus_std3 = []; predMean_minus_std3 = []\n trueVals_zoom = []\n for n in range(0,R):\n x = plot_X_flat[n]\n y = plot_Y_flat[n]\n if include_conditions(x,y,delta=0.025):\n plot_X_zoom.append(x)\n plot_Y_zoom.append(y)\n predMean_zoom.append(predMean[n])\n predMean_plus_std.append( predMean[n] + 1 * predStd[n] )\n predMean_minus_std.append( predMean[n] - 1 * predStd[n] )\n predMean_plus_std2.append( predMean[n] + 2 * predStd[n] )\n predMean_minus_std2.append( predMean[n] - 2 * predStd[n] )\n predMean_plus_std3.append( predMean[n] + 3 * predStd[n] )\n predMean_minus_std3.append( predMean[n] - 3 * predStd[n] )\n trueVals_zoom.append(trueVals[n])\n\n\n # Restrict observations to valid input points\n obsX_x_zoom = []; obsX_y_zoom = []; obsY_zoom = []\n for n in range(0, obsX.shape[0]):\n x = obsX[n,0]\n y = obsX[n,1]\n if include_conditions(x,y):\n obsX_x_zoom.append(x)\n obsX_y_zoom.append(y)\n obsY_zoom.append(obsY[n])\n\n\n # Initialize plot for assessing predictive uncertainty \n tri_fig2 = plt.figure()\n tri2_ax1 = tri_fig2.add_subplot(111, projection='3d')\n\n\n ## Plot Predictive Mean\n linewidth = 0.1; alpha = 0.85\n tri2_ax1.plot_trisurf(plot_X_zoom,plot_Y_zoom, predMean_zoom, cmap=cmap, linewidth=linewidth, antialiased=True, alpha=alpha)\n\n\n ## One Standard Deviation\n linewidth = 0.075; alpha = 0.2\n tri2_ax1.plot_trisurf(plot_X_zoom,plot_Y_zoom, predMean_plus_std, cmap=cmap, linewidth=linewidth, antialiased=True,alpha=alpha)\n tri2_ax1.plot_trisurf(plot_X_zoom,plot_Y_zoom, predMean_minus_std, cmap=cmap, linewidth=linewidth,antialiased=True,alpha=alpha)\n\n ## Two Standard Deviations\n linewidth = 0.05; alpha = 0.1\n tri2_ax1.plot_trisurf(plot_X_zoom,plot_Y_zoom, predMean_plus_std2, cmap=cmap, linewidth=linewidth,antialiased=True,alpha=alpha)\n tri2_ax1.plot_trisurf(plot_X_zoom,plot_Y_zoom, predMean_minus_std2, cmap=cmap, linewidth=linewidth,antialiased=True,alpha=alpha)\n\n ## Three Standard Deviations\n linewidth = 0.01; alpha = 0.01\n tri2_ax1.plot_trisurf(plot_X_zoom,plot_Y_zoom, predMean_plus_std3, cmap=cmap, linewidth=linewidth,antialiased=True,alpha=alpha)\n tri2_ax1.plot_trisurf(plot_X_zoom,plot_Y_zoom, predMean_minus_std3, cmap=cmap, linewidth=linewidth,antialiased=True,alpha=alpha)\n\n ## Scatter plot of training observations\n alpha = 0.4\n tri2_ax1.scatter(obsX_x_zoom, obsX_y_zoom, obsY_zoom, c='k', marker='o', s=15.0, alpha=alpha)\n\n # Remove axes from plot\n remove_axes(tri2_ax1)\n\n # Display plots\n plt.show()\n \n\n\n# Run main() function when called directly\nif __name__ == '__main__':\n main()\n","sub_path":"misc/TEST_CODE/Two_Dimensional/SciKit_Learn_Comparison_2D.py","file_name":"SciKit_Learn_Comparison_2D.py","file_ext":"py","file_size_in_byte":12178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"590252791","text":"# Ivan Alejandre\r\n# Line Art Function\r\n\r\nimport os\r\n\r\ndef getPic():\r\n return makePicture(pickAFile())\r\n \r\ndef lineArt(pic):\r\n threshold = 20\r\n for x in range(0, getWidth(pic)):\r\n # if we're at the rightmost column, don't check right pixel\r\n if x == (getWidth(pic) - 1):\r\n # if we're at the bottom right pixel, just change to white. No pixels to compare.\r\n if (y + 1) == getHeight(pic):\r\n setColor(pixel, white)\r\n \r\n # grab bottom pixel and its luminance\r\n else:\r\n pixelBottom = getPixel(pic, x, (y + 1))\r\n luminanceBottom = (getRed(pixelBottom) + getBlue(pixelBottom) + getGreen(pixelBottom)) / 3\r\n #luminanceBottom = (getRed(pixelBottom) * 0.299) + (getBlue(pixelBottom) * 0.587) + (getGreen(pixelBottom) * 0.114)\r\n \r\n # check the luminance difference and change its color\r\n if abs(luminance - luminanceBottom) > threshold:\r\n setColor(pixel, black)\r\n else:\r\n setColor(pixel, white)\r\n \r\n # for all other columns, check the right pixel AND bottom pixel UNLESS we're at the bottom pixel, then only check\r\n # the right pixel\r\n else:\r\n for y in range(0, getHeight(pic)):\r\n # grab current pixel and its luminance\r\n pixel = getPixel(pic, x, y)\r\n luminance = (getRed(pixel) * 0.299) + (getBlue(pixel) * 0.587) + (getGreen(pixel) * 0.114)\r\n \r\n # if we reach the bottom of the column, just compare the right pixel and modify\r\n if y + 1 == getHeight(pic):\r\n # grab right pixel and its luminance\r\n pixelRight = getPixel(pic, x + 1, y)\r\n luminanceRight = (getRed(pixelBottom) + getBlue(pixelBottom) + getGreen(pixelBottom)) / 3\r\n #luminanceRight = (getRed(pixelRight) * 0.299) + (getBlue(pixelRight) * 0.587) + (getGreen(pixelRight) * 0.114)\r\n \r\n # change the working pixel's color\r\n if abs(luminance - luminanceRight) > threshold:\r\n setColor(pixel, black)\r\n else:\r\n setColor(pixel, white)\r\n \r\n else:\r\n # grab right and bottom pixel and their luminances\r\n pixelBottom = getPixel(pic, x, y + 1)\r\n pixelRight = getPixel(pic, x + 1, y)\r\n luminanceBottom = (getRed(pixelBottom) + getBlue(pixelBottom) + getGreen(pixelBottom)) / 3\r\n luminanceRight = (getRed(pixelBottom) + getBlue(pixelBottom) + getGreen(pixelBottom)) / 3\r\n #luminanceBottom = (getRed(pixelBottom) * 0.299) + (getBlue(pixelBottom) * 0.587) + (getGreen(pixelBottom) * 0.114)\r\n # luminanceRight = (getRed(pixelRight) * 0.299) + (getBlue(pixelRight) * 0.587) + (getGreen(pixelRight) * 0.114)\r\n \r\n # change to black if BOTH right and lower pixel are over threshold\r\n if abs(luminance - luminanceRight) > threshold and abs(luminance - luminanceBottom) > threshold:\r\n setColor(pixel, black)\r\n else:\r\n setColor(pixel, white)\r\n \r\n return pic\r\n\r\ndef makeLineArt():\r\n pic = getPic()\r\n \r\n file = r\"C://temp/lineArt.jpg\"\r\n \r\n writePictureTo(lineArt(pic), file)","sub_path":"mod 3/Compilation 3-7/Line Art/lineArt.py","file_name":"lineArt.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"63879891","text":"import logging\n\nimport sklearn\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score\n\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(\"INFO\")\n\n\ndef createModel(features, target, rfRandState, splitRandState, n_est, mx_d, test_sz):\n \"\"\"\n Build a random forest model and create test set\n\n Args:\n features: dataframe, required, dataframe of all input values for model\n target: dataframe, required, one column datafame of output (0, 1)\n rfRandState: (int), required, starting point to set seed for model\n splitRandState: (int), required, starting point to set seed for spliting data\n n_est: (int), required, number of estimators in random forest\n mx_d: (int), required, max depth of random forest\n test_sz: (double), between 0 and 1, required, proportion of data in test set\n\n Returns:\n random forset model, test set of predictors, test set of dependent variables\n \"\"\"\n try:\n rf = RandomForestClassifier(n_estimators=n_est, max_depth=mx_d, random_state=rfRandState)\n X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(\n features, target, test_size=test_sz, random_state=splitRandState)\n rf.fit(X_train, y_train)\n logger.info(\"Succesfully created model\")\n return rf, X_test, y_test\n except:\n logger.error(\"Unable to create model\")\n\ndef scoreModel(rf, X_test, y_test):\n \"\"\"\n Provide model evaluation metrics for Random Forest model produced in createModel function\n\n Args:\n rf: (model), required, model produced from createModel function\n X_test: dataframe, required, test inputs for model\n y_test: dataframe, required, test outputs for model\n\n Returns:\n accuracy\n \"\"\"\n try:\n ypred_bin_test = rf.predict(X_test)\n accuracy = accuracy_score(y_test, ypred_bin_test)\n logger.info(\"Succesfully scored model with accuracy = %s\", str(accuracy))\n return accuracy\n except:\n logger.error(\"Unable to score model\")\n","sub_path":"src/getModel.py","file_name":"getModel.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"649373206","text":"import os\n\nimport torch\nfrom torch import nn\nfrom tqdm import tqdm\n\nfrom args import args\nfrom helper import compute_accuracy, count_parameters\nfrom models import ReviewClassifierRNN\nfrom datasets import ReviewDataset, get_num_batches, generate_rnn_batches\n\nif not os.path.exists(args.reviews_json_test_filepath):\n with open(args.reviews_json_filepath, 'r') as source, open(args.reviews_json_test_filepath, 'w') as dest:\n for i, line in enumerate(source):\n if i < args.reviews_train:\n continue\n if i >= args.reviews_train + args.reviews_test:\n break\n dest.write(line)\n\ntest_dataset = ReviewDataset.load_dataset_and_load_vectorizer(args.reviews_json_test_filepath,\n args.vectorizer_filepath)\n\nvectorizer = test_dataset.get_vectorizer()\nclassifier = ReviewClassifierRNN(input_dim=len(vectorizer.review_vocab),\n embedding_dim=args.embedding_dim,\n hidden_dim=args.hidden_features,\n output_dim=len(vectorizer.rating_vocab),\n padding_idx=vectorizer.review_vocab[''])\nclassifier.to(args.device)\nclassifier.load_state_dict(torch.load(args.model_state_filepath, map_location=torch.device(args.device)))\nclassifier.eval()\nprint(f'The model has {count_parameters(classifier):,} trainable parameters')\n\nloss_func = nn.CrossEntropyLoss()\nrunning_loss = 0.\nrunning_acc = 0.\n\nwith tqdm(total=get_num_batches(test_dataset, args.batch_size)) as train_bar:\n batch_generator = generate_rnn_batches(test_dataset, batch_size=args.batch_size, device=args.device)\n\n for batch_index, batch_dict in enumerate(batch_generator):\n # compute the output\n y_pred = classifier(batch_dict['x_data'], batch_dict['x_length'])\n\n # compute the loss\n loss = loss_func(y_pred, batch_dict['y_target'])\n loss_t = loss.item()\n running_loss += (loss_t - running_loss) / (batch_index + 1)\n\n # compute the accuracy\n acc_t = compute_accuracy(y_pred, batch_dict['y_target'])\n running_acc += (acc_t - running_acc) / (batch_index + 1)\n\n # update bar\n train_bar.set_postfix(loss=running_loss, acc=running_acc)\n train_bar.update()\n\nprint(f\"Test loss: {running_loss}. Test acc:{running_acc}\")","sub_path":"Yelp rewiews ElmanRNN/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"5870942","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\n\nimport time\n\nimport zencad\n\nclass AnimateThread(QThread):\n\tafter_update_signal = pyqtSignal()\n\n\tdef __init__(self, widget, updater_function, animate_step=0.01):\n\t\tQThread.__init__(self)\n\t\tself.updater_function = updater_function\n\t\t#self.parent = widget\n\t\twidget.animate_thread = self\n\t\tself.wdg = widget\n\t\tself.animate_step = animate_step\n\t\tself.cancelled = False\n\n\t\tself.after_update_signal.connect(widget.continuous_redraw)\n\n\tdef finish(self):\n\t\tself.cancelled = True\n\t\tself.wdg.animate_updated.set()\n\n\tdef set_animate_step(self, step):\n\t\t\tself.animate_step = step\n\n\tdef run(self):\n\t\ttime.sleep(0.1)\n\t\tlasttime = time.time() - self.animate_step\n\t\twhile 1:\n\t\t\tcurtime = time.time()\n\t\t\tdeltatime = curtime - lasttime\n\n\t\t\tif deltatime < self.animate_step:\n\t\t\t\ttime.sleep(self.animate_step - deltatime)\n\n\t\t\tlasttime = time.time()\n\n\t\t\tensave = zencad.lazy.encache\n\t\t\tdesave = zencad.lazy.decache\n\t\t\tonplace = zencad.lazy.onplace\n\t\t\tdiag = zencad.lazy.diag\n\t\t\tif self.wdg.inited:\n\t\t\t\tzencad.lazy.encache = False\n\t\t\t\tzencad.lazy.decache = False\n\t\t\t\tzencad.lazy.onplace = True\n\t\t\t\tzencad.lazy.diag = False\n\t\t\t\tself.updater_function(self.wdg)\n\t\t\t\tzencad.lazy.onplace = onplace\n\t\t\t\tzencad.lazy.encache = ensave\n\t\t\t\tzencad.lazy.decache = desave\n\t\t\t\tzencad.lazy.diag = diag\n\n\t\t\t\tself.wdg.animate_updated.clear()\n\t\t\t\tif self.cancelled:\n\t\t\t\t\treturn\n\n\t\t\t\tself.after_update_signal.emit()\n\t\t\t\tself.wdg.animate_updated.wait()\n\n\t\t\t\tif self.cancelled:\n\t\t\t\t\treturn\n","sub_path":"zencad/animate.py","file_name":"animate.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"446341105","text":"\"\"\"\nTransition from Json to Spacy understandable format\n\n\"\"\"\nimport logging\nimport json\n\n\nclass DS_to_SPACY():\n \n def __init__(self, JasonFile):\n \n self.JFile = JasonFile;\n \n def retDsToSpacy(self):\n \n try:\n self.training = []\n self.lines = []\n \n with open(self.JFile, 'r') as self.fl:\n self.lines = self.fl.readlines()\n \n for self.lin in self.lines:\n self.content = json.loads(self.lin)\n self.txt = self.content['content']\n self.entities = []\n \n for self.annot in self.content['annotation']:\n \n #only a single point in text annotation.\n self.pnt = self.annot['points'][0]\n self.lbls = self.annot['label']\n \n # handle both list of labels or a single label.\n if not isinstance(self.lbls, list):\n self.lbls = [self.lbls]\n\n for self.lbl in self.lbls:\n \n self.entities.append((self.pnt['start'], self.pnt['end'] + 1 ,self.lbl))\n\n self.training.append((self.txt, {\"entities\" : self.entities}))\n\n return self.training\n \n except Exception as e:\n \n logging.exception(\"Unable to process \" + self.JFile + \"\\n\" + \"error = \" + str(e))\n \n return None\n \n \n","sub_path":"Problem1/JasonToSpacy.py","file_name":"JasonToSpacy.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"101430393","text":"#!/usr/bin/env python\n\nimport sys\n\nfrom oslo.config import cfg\n\nfrom billingstack import service\nfrom billingstack.samples import get_samples\nfrom billingstack.storage.utils import get_connection\nfrom billingstack.openstack.common.context import get_admin_context\n\n\ncfg.CONF.import_opt('storage_driver', 'billingstack.central',\n group='service:central')\n\ncfg.CONF.import_opt('state_path', 'billingstack.paths')\n\ncfg.CONF.import_opt(\n 'database_connection',\n 'billingstack.central.storage.impl_sqlalchemy',\n group='central:sqlalchemy')\n\n\nSAMPLES = get_samples()\n\n\ndef get_fixture(name, fixture=0, values={}):\n f = SAMPLES[name][fixture].copy()\n f.update(values)\n return f\n\n\nif __name__ == '__main__':\n service.prepare_service(sys.argv)\n conn = get_connection('central')\n\n samples = get_samples()\n\n ctxt = get_admin_context()\n\n currencies = {}\n for c in samples['currency']:\n currencies[c['name']] = conn.create_currency(ctxt, c)\n\n languages = {}\n for l in samples['language']:\n languages[l['name']] = conn.create_language(ctxt, l)\n\n country_data = {\n \"currency_name\": currencies['nok']['name'],\n \"language_name\": languages['nor']['name']}\n\n merchant = conn.create_merchant(\n ctxt, get_fixture('merchant', values=country_data))\n\n customer = conn.create_customer(\n ctxt, merchant['id'], get_fixture('customer', values=country_data))\n\n #contact_info = get_fixture('contact_info')\n\n #merchant_user = get_fixture('user')\n #merchant_user['username'] = 'demo_merchant'\n #merchant_user['contact_info'] = contact_info\n\n #merchant_user = conn.user_add(\n #ctxt, merchant['id'], merchant_user)\n\n #customer_user = get_fixture('user')\n #customer_user['username'] = 'demo_customer'\n #customer_user['contact_info'] = contact_info\n #customer_user['customer_id'] = customer['id']\n\n #customer_user = conn.user_add(\n # ctxt,\n # merchant['id'],\n # customer_user)\n\n products = {}\n for p in samples['product']:\n products[p['name']] = conn.create_product(ctxt, merchant['id'], p)\n\n values = {\n 'plan_items': [\n {'product_id': products['memory']},\n {'product_id': products['vcpus']},\n {'product_id': products['root_disk_size']},\n {'product_id': products['network.incoming.bytes']},\n {'product_id': products['network.outgoing.bytes']}]}\n\n plan = get_fixture('plan', values=values)\n\n conn.create_plan(ctxt, merchant['id'], get_fixture('plan'))\n","sub_path":"tools/load_samples.py","file_name":"load_samples.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"394787772","text":"import math\n\n\nclass Solution:\n def findMissingRanges(self, nums, lower, upper):\n \"\"\"\n :type nums: List[int]\n :type lower: int\n :type upper: int\n :rtype: List[str]\n \"\"\"\n ranges = [[lower, upper]]\n lastNum = math.nan\n for n in nums:\n if n == lastNum:\n continue\n lastNum = n\n currRange = ranges[-1]\n if n == currRange[0]:\n if currRange[0] == currRange[1]:\n ranges.pop()\n else:\n currRange[0] += 1\n elif n == currRange[1]:\n currRange[1] -= 1\n else:\n ranges.append([n + 1, currRange[1]])\n currRange[1] = n - 1\n output = []\n for rg in ranges:\n if rg[0] == rg[1]:\n output.append(str(rg[0]))\n else:\n output.append(str(rg[0]) + '->' + str(rg[1]))\n return output\n\n\nsol = Solution()\nsol.findMissingRanges([1, 1, 1, ], 1, 1)\n","sub_path":"src/missing-ranges.py","file_name":"missing-ranges.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"475192569","text":"import os\nimport pygame as pg\nfrom random import choice, randrange\n\nclass Symbol:\n def __init__(self, x, y, speed):\n self.x = x\n self.y = y\n self.speed = speed\n self.value = choice(green_katakana)\n self.interval = randrange(5, 30)\n\n def draw(self, color):\n frames = pg.time.get_ticks()\n if not frames % self.interval:\n self.value = choice(green_katakana if color == 'green' else lightgreen_katakana)\n self.y = self.y + self.speed if self.y < height else - font_size\n screen.blit(self.value, (self.x, self.y))\n\nclass Column:\n def __init__(self, x, y):\n self.column_height = randrange(15, 25)\n self.speed = randrange(4, 6)\n self.symbols = [Symbol(x, i, self.speed) for i in range(y, y - font_size * self.column_height, - font_size)]\n\n def draw(self):\n [symbol.draw('green') if i else symbol.draw('lightgreen') for i, symbol in enumerate(self.symbols)]\n\nos.environ['SDL_VIDEO_CENTERED'] = '1'\nwidth = 800\nheight = 500\nfont_size = 15\nalpha = 1200\n\npg.init()\nscreen = pg.display.set_mode([width, height])\nsurface = pg.Surface([width, height])\nsurface.set_alpha(alpha)\nclock = pg.time.Clock()\n\nkatakana = [chr(int('0x30a0', 16) + i) for i in range(96)]\nfont = pg.font.Font('font/ms mincho.ttf', font_size)\ngreen_katakana = [font.render(char, True, (0, randrange(30, 256), 0)) for char in katakana]\nlightgreen_katakana = [font.render(char, True, pg.Color('lightgreen')) for char in katakana]\n\n\nsymbol_columns = [Column(x, randrange(- height, 0)) for x in range(0, width, font_size)]\nwhile True:\n screen.blit(surface, (0, 0))\n surface.fill(pg.Color('black'))\n\n [symbol_column.draw() for symbol_column in symbol_columns]\n\n for event in pg.event.get():\n if event.type == pg.QUIT:\n exit()\n\n pg.display.flip()\n clock.tick(60)","sub_path":"Matrix/Matrix.py","file_name":"Matrix.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"524703939","text":"from tkinter import *\n#creating window object\nwindow=Tk()\n#define labels\nl1=Label(window, text=\"Company\")\nl1.grid(row=0,column=0)\nl2=Label(window, text=\"Departments\")\nl2.grid(row=1,column=0)\nl3=Label(window, text=\"Sections\")\nl3.grid(row=0,column=2)\nl4=Label(window, text=\"EmpName\")\nl4.grid(row=1,column=2)\n#define entries\nCompany_text=StringVar()\ne1=Entry(window,textvariable=Company_text)\ne1.grid(row=0,column=1)\n\nDepartment_text=StringVar()\ne2=Entry(window,textvariable=Department_text)\ne2.grid(row=1,column=1)\n\nSections_text=StringVar()\ne3=Entry(window,textvariable=Sections_text)\ne3.grid(row=0,column=3)\n\nEmpName_text=StringVar()\ne4=Entry(window,textvariable=EmpName_text)\ne4.grid(row=1,column=3)\n\n#define listbox\n\nlist1=Listbox(window,height=8,width=25)\nlist1.grid(row=2,column=0,rowspan=2)\n\n#attach scrollbar\n\nscbar1=Scrollbar(window)\nscbar1.grid(row=2,column=2,columnspan=2)\nlist1.configure(yscrollcommand=scbar1.set)\nscbar1.configure(command=list1.yview)\n\n#define buttons\n\nb1=Button(window,text=\"View All\",width=12)\nb1.grid(row=2,column=3)\nb2=Button(window,text=\"Search\",width=12)\nb2.grid(row=3,column=3)\nb3=Button(window,text=\"Add Entry\",width=12)\nb3.grid(row=4,column=3)\nb4=Button(window,text=\"Update\",width=12)\nb4.grid(row=5,column=3)\nb5=Button(window,text=\"CLose\",width=12)\nb5.grid(row=6,column=3)\n","sub_path":"CompanyRecordGui.py","file_name":"CompanyRecordGui.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"151366565","text":"# Reading from a csv file\nimport csv\n\n# with statement\nwith open( 'examplefromvideo.csv' ) as csvFile:\n readCSV = csv.reader( csvFile, delimiter=',')\n\n dates = []\n colors = []\n\n for row in readCSV:\n color = row[ 3 ]\n date = row[ 0 ]\n\n dates.append( date )\n colors.append( color )\n\n print( dates )\n print( colors )\n\n try:\n WhatColor = input( 'What color do you wish to know the date of? ' )\n WhatColor = WhatColor.lower()\n\n if WhatColor in colors:\n coldex = colors.index( WhatColor )\n dteColorDate = dates[ coldex ]\n print( 'The date of', WhatColor, 'is ', dteColorDate )\n else:\n print( 'Color not found or is not a color' )\n\n except Exception as excError:\n print(excError)\n\n print( 'Continuing' )\n","sub_path":"Python/tryandexcept.py","file_name":"tryandexcept.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"147215842","text":"#!/bin/python\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nimport itertools\nfrom curses import has_key\nfrom math import log\nimport sys\nimport copy\nimport string\n\n# Python 3 backwards compatibility tricks\nif sys.version_info.major > 2:\n\n def xrange(*args, **kwargs):\n return iter(range(*args, **kwargs))\n\n def unicode(*args, **kwargs):\n return str(*args, **kwargs)\n\nclass LangModel:\n def fit_corpus(self, corpus):\n \"\"\"Learn the language model for the whole corpus.\n The corpus consists of a list of sentences.\"\"\"\n self.vocab_words = {}\n for s in corpus:\n for word in s:\n if word in self.vocab_words:\n self.vocab_words[word] += 1.0\n else:\n self.vocab_words[word] = 1.0\n #keep counts of each word\n\n min_count = 2\n vocabulary = copy.deepcopy(self.vocab_words)\n for word in self.vocab_words:\n #if count is less than min_count, delete it from vocabulary\n if self.vocab_words[word] < min_count:\n del vocabulary[word]\n\n self.vocab_words = copy.deepcopy(vocabulary)\n\n # x = 0\n for s in corpus:\n self.fit_sentence(s)\n # x += 1\n # if x > 2:\n # self.norm()\n # exit()\n self.norm()\n\n def perplexity(self, corpus):\n \"\"\"Computes the perplexity of the corpus by the model.\n\n Assumes the model uses an EOS symbol at the end of each sentence.\n \"\"\"\n numOOV = self.get_num_oov(corpus)\n return pow(2.0, self.entropy(corpus, numOOV))\n\n def get_num_oov(self, corpus):\n vocab_set = set(self.vocab())\n words_set = set(itertools.chain(*corpus))\n numOOV = len(words_set - vocab_set)\n return numOOV\n\n def entropy(self, corpus, numOOV):\n num_words = 0.0\n sum_logprob = 0.0\n for s in corpus:\n num_words += len(s) + 1 # for EOS\n sum_logprob += self.logprob_sentence(s, numOOV)\n return -(1.0/num_words)*(sum_logprob)\n\n def logprob_sentence(self, sentence, numOOV):\n p = 0.0\n for i in xrange(len(sentence)):\n p += self.cond_logprob(sentence[i], sentence[:i], numOOV)\n p += self.cond_logprob('END_OF_SENTENCE', sentence, numOOV)\n return p\n\n # required, update the model when a sentence is observed\n def fit_sentence(self, sentence): pass\n # optional, if there are any post-training steps (such as normalizing probabilities)\n def norm(self): pass\n # required, return the log2 of the conditional prob of word, given previous words\n def cond_logprob(self, word, previous, numOOV): pass\n # required, the list of words the language model supports (including EOS)\n def vocab(self): pass\n\nclass Unigram(LangModel):\n def __init__(self, unk_prob=0.0001):\n self.model = dict()\n self.lunk_prob = log(unk_prob, 2)\n\n def inc_word(self, w):\n if w in self.model:\n self.model[w] += 1.0\n else:\n self.model[w] = 1.0\n\n def fit_sentence(self, sentence):\n for w in sentence:\n self.inc_word(w)\n self.inc_word('END_OF_SENTENCE')\n\n def norm(self):\n \"\"\"Normalize and convert to log2-probs.\"\"\"\n tot = 0.0\n for word in self.model:\n tot += self.model[word]\n ltot = log(tot, 2)\n for word in self.model:\n self.model[word] = log(self.model[word], 2) - ltot\n\n def cond_logprob(self, word, previous, numOOV):\n if word in self.model:\n return self.model[word]\n else:\n return self.lunk_prob-log(numOOV, 2)\n\n def vocab(self):\n return self.model.keys()\n\nclass Ngram(LangModel):\n def __init__(self, ngram_size, unk_prob=0.0001):\n\n self.lunk_prob = log(unk_prob, 2)\n self.ngram_size = ngram_size\n self.ngram_counts = {}\n self.ngram_context_counts = {}\n\n def get_ngrams(self, num, tokens):\n for i in range(num-1):\n tokens.insert(0, \"\")\n tokens.append(\"END_OF_SENTENCE\")\n output = []\n for i in range(len(tokens) - num + 1):\n output.append(tokens[i:i + num])\n return output\n\n def unkify(self, sentence):\n for w in sentence:\n if w not in self.vocab_words:\n sentence = ['UNK' if i==w else i for i in sentence]\n return sentence\n\n # required, update the model when a sentence is observed\n def fit_sentence(self, sentence):\n \"\"\"\n Updates Language Model\n :param sentence: input text\n \"\"\"\n sentence = self.unkify(sentence)\n ngrams = self.get_ngrams(self.ngram_size, sentence)\n for ngram in ngrams:\n prev, current = ' '.join(ngram[:-1]), ngram[-1]\n if prev not in self.ngram_counts:\n self.ngram_counts[prev] = {}\n self.ngram_context_counts[prev] = {}\n if current not in self.ngram_counts[prev]:\n self.ngram_counts[prev][current] = 1\n else:\n self.ngram_counts[prev][current] += 1\n\n\n # optional, if there are any post-training steps (such as normalizing probabilities)\n def norm(self):\n\n for prev in self.ngram_counts:\n total_count = 0.0\n for word in self.ngram_counts[prev]:\n total_count += self.ngram_counts[prev][word]\n for word in self.ngram_counts[prev]:\n self.ngram_counts[prev][word] = log((1 + self.ngram_counts[prev][word]) / (total_count + 1*len(self.vocab_words)),2) #saves ngram_counts[prev][word] as a percentage\n self.ngram_context_counts[prev] = log(1 / (total_count + 1 * len(self.vocab_words)), 2)\n\n # required, return the log2 of the conditional prob of word, given previous words\n def cond_logprob(self, word, previous, numOOV):\n\n word = self.unkify(word)\n previous = self.unkify(previous)\n word = ' '.join(word)\n previous_temp = previous\n for i in range(self.ngram_size-1):\n previous_temp.insert(0, \"\")\n\n prev = ' '.join(previous_temp[-(self.ngram_size - 1):])\n\n if prev in self.ngram_counts:\n if word in self.ngram_counts[prev]: #both previous and word are in dictionary\n return self.ngram_counts[prev][word]\n else: #previous but not word\n return self.ngram_context_counts[prev]\n else:\n if word in self.vocab_words: #word but not previous\n return log((1-.0001)/len(self.vocab_words),2)\n else: #neither word nor previous\n return log(.0001,2)\n\n\n # required, the list of words the language model supports (including EOS)\n def vocab(self):\n return self.ngram_counts.keys()\n","sub_path":"hw2/lm.py","file_name":"lm.py","file_ext":"py","file_size_in_byte":6927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"209061944","text":"import logging\nimport os\nimport shutil\nimport subprocess\nimport time\nimport sys\nimport json\nimport mysql.connector\nimport syslog\nimport pika\nimport threading\nimport traceback\nimport socket\n\nFFMPEG_CREATE_WAIT = 0.2 # wait from when create request to get m3u8 playlist file\nFFMPEG_MAX_WAIT_FOR_PLAYLIST = 20\n\n#logging utility\ndef log(log_type, log_msg):\n syslog.syslog(log_type, '{0}:{1}'.format(threading.currentThread().getName(), log_msg))\ndef log_long(log_type, log_msg):\n msg_max = 400\n msg_len = len(log_msg)\n chunks = int(msg_len / msg_max)\n for i in range(chunks):\n startindex = i * msg_max\n remaining_len = msg_len - startindex\n endindex = (i + 1) * msg_max if remaining_len > 0 else msg_len\n syslog.syslog(log_type, '- {0}:{1}'.format(threading.currentThread().getName(), msg[startindex : endindex]))\n\ndef get_ip_addr():\n log(syslog.LOG_INFO, 'Getting local ip address')\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect(('google.com', 0))\n ip = s.getsockname()[0]\n return ip\n\ndef get_request_params(msg):\n log(syslog.LOG_INFO, 'Getting request params from msg')\n request = json.loads(msg)\n request_type = request['type']\n request_id = request['id']\n request_url = request['url']\n request_proxy = request['proxy']\n return (request_type, request_id, request_url, request_proxy)\n\ndef FinishWithError(requestid, error):\n log(syslog.LOG_INFO, 'Updating database of failed download transcoding')\n cnx = mysql.connector.connect(host=db_host, user=db_user, password=db_pwd, database=db_name)\n cursor = cnx.cursor()\n args = (requestid, 'ERROR', error)\n cursor.callproc('request_error', args)\n cnx.close()\ndef UpdateRequestPlaylistCreated(requestid, url):\n log(syslog.LOG_INFO, 'Updating database of successful extraction playlist creation')\n cnx = mysql.connector.connect(host=db_host, user=db_user, password=db_pwd, database=db_name)\n cursor = cnx.cursor()\n hostname = get_ip_addr()\n args = (hostname, requestid, url)\n cursor.callproc('update_extract_location', args)\n cnx.close()\n\ndef CreateDirectoryForVideo(id):\n directory = '{0}/extracts/{1}'.format(video_base_directory, id)\n log(syslog.LOG_INFO, 'Creating directory for video at {0}'.format(directory))\n if os.path.exists(directory):\n log(syslog.LOG_INFO, 'Removing existing')\n shutil.rmtree(directory)\n os.makedirs(directory)\n return directory\ndef TryFFMPEG(requestid, request_url, directory, request_proxy):\n os.chdir(directory)\n\n env = os.environ\n env['http_proxy'] = '{0}:{1}'.format(request_proxy['ip'], request_proxy['port'])\n\n dest_playlist_path = 'playlist.m3u8'\n dest_segmentfmt_path = 'out%03d.ts'\n ffmpeg_cmd = r'ffmpeg -i \"{0}\" -map 0 -codec:v libx264 -codec:a libfaac -f ssegment -segment_list {1} -segment_list_flags +cache -segment_time 10 {2}'.format(request_url, dest_playlist_path, dest_segmentfmt_path)\n log(syslog.LOG_INFO, 'Running: {0}'.format(ffmpeg_cmd))\n p = subprocess.Popen(ffmpeg_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, env=env)\n\n dest_playlist_path = '{0}/{1}'.format(directory, dest_playlist_path)\n playlistAvailable = False\n total_wait = 0\n while not playlistAvailable:\n time.sleep(FFMPEG_CREATE_WAIT)\n if os.path.exists(dest_playlist_path):\n UpdateRequestPlaylistCreated(requestid, dest_playlist_path)\n playlistAvailable = True\n break;\n\n total_wait += FFMPEG_CREATE_WAIT\n if total_wait >= FFMPEG_MAX_WAIT_FOR_PLAYLIST:\n p.kill()\n FinishWithError(requestid, \"Could not process video via ffmpeg\")\n return False\n\n log(syslog.LOG_INFO, 'Allowing ffmpeg to finish but relieving this thread')\n return True\n\ndef OnDownloadTranscoderMessage(ch, method, properties, body):\n try:\n log(syslog.LOG_INFO, 'Received extract request')\n request_type, request_id, request_url, request_proxy = get_request_params(body)\n directory = CreateDirectoryForVideo(request_id)\n if TryFFMPEG(request_id, request_url, directory, request_proxy):\n ch.basic_ack(delivery_tag = method.delivery_tag)\n else:\n ch.basic_nack(delivery_tag = method.delivery_tag)\n except:\n log(syslog.LOG_WARNING, 'Oops something bad happened with download transcoding:')\n log_long(syslog.LOG_WARNING, '{0}'.format(traceback.print_exc()))\n ch.basic_nack(delivery_tag = method.delivery_tag)\n\ndef StartRabbitConsumer():\n rabbit_credentials = pika.PlainCredentials(rabbit_user, rabbit_pwd)\n rabbit_parameters = pika.ConnectionParameters(rabbit_host, rabbit_port, '/', rabbit_credentials)\n rabbit_connection = pika.BlockingConnection(rabbit_parameters)\n rabbit_extractor_channel = rabbit_connection.channel()\n rabbit_extractor_channel.basic_qos(prefetch_count=1)\n rabbit_extractor_channel.basic_consume(OnDownloadTranscoderMessage, queue=rabbit_q_dl_transcoder)\n rabbit_extractor_channel.start_consuming()\n\nsyslog.openlog('extractor', syslog.LOG_PID, syslog.LOG_USER)\n\nrabbit_user = 'guest'\nrabbit_pwd = 'guest'\nrabbit_host = 'localhost'\nrabbit_port = 5672\nrabbit_url = 'amqp://{0}:{1}@{2}:{3}/'.format(rabbit_user, rabbit_pwd, rabbit_host, rabbit_port)\nrabbit_q_extractor = 'extractor'\nrabbit_q_dl_transcoder = 'downloadtranscoder'\n\n# setup mysql connection\ndb_host = '167.88.34.62'\ndb_user = 'Brun0'\ndb_pwd = '65UB3b3$'\ndb_name = 'vidblit'\n\nvideo_base_directory = '/var/vidblit/videos'\nmax_threads = 10\nfor i in range(max_threads):\n t = threading.Thread(name='T[{0}]'.format(i + 1), target=StartRabbitConsumer)\n log(syslog.LOG_INFO, 'Starting consumer thread {0}'.format(t.getName()))\n t.start()","sub_path":"var/vidblit/scripts/python/download_transcoder.py","file_name":"download_transcoder.py","file_ext":"py","file_size_in_byte":5787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"608528029","text":"import os\nimport ConfigParser\nfrom section import Section\n\nclass Config():\n def __init__(self):\n # Define the configuration file's default section,\n # option and value pairs.\n self._section_1_name = \"names\"\n self._section_1 = [(\"applications\", \"apps\"),\n (\"documents\", \"documents\"),\n (\"compressed files\", \"compressed files\"),\n (\"images\", \"images\"),\n (\"music\", \"music\"),\n (\"movies\", \"movies\"),\n (\"subtitles\", \"subs\"),\n (\"torrents\", \"torrents\"),\n (\"development\", \"development\")]\n\n self._section_2_name = \"extensions\"\n self._section_2 = [(\"applications ext\", \".dmg, .pkg, .app, .deb\"),\n (\"documents ext\", \".xmcd, .doc, .docx, .pdf, .txt, \\\n .xls, .ppt\"),\n (\"compressed ext\", \".iso, .tar.gz, .gz, .tar, .zip, \\\n .rar, .tar.bz, .tar.bz2\"),\n (\"images ext\", \".jpg, .jpeg, .png, .gif, .bmp\"),\n (\"music ext\", \".mp3, .flac, .wav, .m4r\"),\n (\"movies ext\", \".mp4, .mkv, .avi\"),\n (\"subtitles ext\", \".srt\"),\n (\"torrents ext\", \".torrent\"),\n (\"development ext\", \".ino, .html, .css, .js, .php, \\\n .cpp, .cs, .py\")]\n\n self._section_3_name = \"directories\"\n self._section_3 = [(\"download directory\", \"\")]\n\n self._default_sections = self._build_default_sections()\n\n self.download_dir = None\n\n self._cfg = ConfigParser.ConfigParser()\n self._load(self._cfg) # defines multiple global vars,\n # be sure to check out what gets defined there.\n\n\n\n def _build_default_sections(self):\n \"\"\" Defines the section objects, returns them in a list. \"\"\"\n sec_1 = Section(self._section_1_name, self._section_1)\n sec_2 = Section(self._section_2_name, self._section_2)\n sec_3 = Section(self._section_3_name, self._section_3)\n return [sec_1, sec_2, sec_3]\n\n\n def _config_exists(self):\n \"\"\" Returns bool if the config file exists. \"\"\"\n return os.path.isfile(\"organizer.cfg\")\n\n\n def _add_options(self, cfg):\n \"\"\" Adds the section and options for the config file. \"\"\"\n # add the sections\n for sectObj in self._default_sections:\n cfg.add_section(sectObj.name)\n # add the option and value pairs\n for sectObj in self._default_sections:\n for option, value in sectObj.options:\n cfg.set(sectObj.name, option, value.replace(\" \", \"\"))\n\n\n def _write_config(self):\n \"\"\" Creates the default config file. \"\"\"\n cfg = ConfigParser.ConfigParser()\n self._add_options(cfg)\n with open(\"organizer.cfg\", \"w\") as f:\n cfg.write(f)\n \n\n def _options_match(self, cfg, section):\n \"\"\" Checks each option from the passed section, if one doesn't\n exist it will raise an error. \"\"\"\n for option, value in section.options:\n if(not cfg.has_option(section.name, option)):\n raise ValueError\n\n\n def _sections_match(self, cfg):\n \"\"\" Makes sure that each section exists. \"\"\"\n required_sections = [sect.name for sect in self._default_sections]\n return required_sections == cfg.sections()\n\n\n def _config_OK(self, cfg):\n \"\"\" Makes sure every value is set, if this isn't the case\n the config file gets overwritten with the default one. \"\"\"\n try:\n cfg_file = cfg.read(\"organizer.cfg\")\n if(not cfg_file):\n raise ValueError(\"Config file missing\")\n \n if(not self._sections_match(cfg)):\n raise ValueError(\"Sections don't match!\")\n \n for i in range(2):\n self._options_match(cfg, self._default_sections[i])\n \n if(self._download_dir_in_config(cfg)):\n self.download_dir = cfg.get(self._section_3_name, \"download directory\")\n except ValueError:\n return False\n else:\n return True\n\n\n def _get_file_ext(self, cfg, option):\n \"\"\" Returns the file extension string as a list. \"\"\"\n # For instance: (\"applications ext\", \".dmg, .pkg, .app, .deb\")\n # becomes [\".dmb\", \".pkg\", \".app\", \".deb\"]\n ext = cfg.get(self._section_2_name, option)\n ext = [e.strip() for e in ext.split(\",\")]\n return ext\n\n\n def _download_dir_in_config(self, cfg):\n \"\"\" Checks if the download directory is defined in the config file,\n returns bool. \"\"\"\n try:\n ddir = cfg.get(self._section_3_name, \"download directory\")\n except ConfigParser.NoOptionError:\n return False\n if(not ddir):\n return False\n else:\n return True\n\n\n def _create_directory(self, path):\n \"\"\" Creates the passed directory. \"\"\"\n if(not os.path.isdir(path)):\n os.makedirs(path)\n\n\n def set_download_dir(self, path):\n \"\"\" Writes the download directory variable into the config file. \"\"\"\n cfg = ConfigParser.ConfigParser()\n cfg.read(\"organizer.cfg\")\n cfg.set(\"directories\", \"download directory\", path)\n with open(\"organizer.cfg\", \"w\") as f:\n cfg.write(f)\n\n self.download_dir = path\n\n\n def _get_directory_names(self, cfg):\n \"\"\" Returns the list of directory names from the config file. \"\"\"\n # get the options from section 1 and .get() it's value\n names = [cfg.get(self._section_1_name, opt)\\\n for opt in cfg.options(self._section_1_name)]\n return names\n \n\n def _load(self, cfg):\n \"\"\" First checks the config file, if it doesn't exist or if\n it's corrupt it will get overwritten by a default version\n of it. After that the config file gets parsed. \"\"\"\n \n if(not self._config_OK(cfg)):\n # overwrite the config file as it is not valid\n # and then read the freshly generated file.\n self._write_config()\n cfg.read(\"organizer.cfg\")\n\n\n # assign the file extensions to the correct list\n self.applications_ext = self._get_file_ext(cfg, \"applications ext\")\n self.documents_ext = self._get_file_ext(cfg, \"documents ext\")\n self.compressed_ext = self._get_file_ext(cfg, \"compressed ext\")\n self.images_ext = self._get_file_ext(cfg, \"images ext\")\n self.music_ext = self._get_file_ext(cfg, \"music ext\")\n self.movies_ext = self._get_file_ext(cfg, \"movies ext\")\n self.subtitles_ext = self._get_file_ext(cfg, \"subtitles ext\")\n self.torrents_ext = self._get_file_ext(cfg, \"torrents ext\")\n self.development_ext = self._get_file_ext(cfg, \"development ext\")\n \n # Get a list of directory names which are specified in\n # the first section of the config file.\n self.directory_names = self._get_directory_names(cfg)\n \n\n","sub_path":"modules/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":7299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"227868451","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# pylint: disable=invalid-name\nimport ast\nimport re\n\nfrom setuptools import find_packages, setup\n\n_version_re = re.compile(r\"__version__\\s+=\\s+(.*)\")\n_init_file = \"locust_plugins/__init__.py\"\nwith open(_init_file, \"rb\") as f:\n version = str(ast.literal_eval(_version_re.search(f.read().decode(\"utf-8\")).group(1)))\n\nsetup(\n name=\"locust-plugins\",\n version=version,\n description=\"Useful plugins/extensions for Locust\",\n long_description=\"\"\"https://github.com/SvenskaSpel/locust-plugins\"\"\",\n classifiers=[\n \"Topic :: Software Development :: Testing :: Traffic Generation\",\n \"Development Status :: 4 - Beta\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Operating System :: MacOS\",\n \"Operating System :: POSIX :: Linux\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: System Administrators\",\n ],\n python_requires=\">=3.7, <4\",\n keywords=\"\",\n author=\"Lars Holmberg\",\n url=\"https://github.com/SvenskaSpel/locust-plugins\",\n license=\"Apache-2.0\",\n packages=find_packages(exclude=[\"examples\"]),\n include_package_data=True,\n package_data={\"locust_plugins\": [\"py.typed\"]},\n zip_safe=False,\n install_requires=[\n \"playwright\",\n \"locust>=2.4.0\",\n \"psycogreen\",\n \"psycopg2-binary\",\n \"websocket-client\",\n \"python-dateutil\",\n \"pymongo\",\n \"confluent-kafka\",\n \"selenium>=4.0.0\",\n \"lxml\",\n \"opencensus-ext-azure\",\n \"paho-mqtt>=1.5.0\",\n ],\n scripts=[\"bin/locust-compose\"],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"490998723","text":"import pandas as pd\n\ndef editTAHours(filename, course, hour):\n\n flag = 0\n\n try:\n df = pd.read_csv(filename)\n\n except FileNotFoundError:\n print(\"Sorry, the file {} does not exist\".format(filename))\n quit()\n\n dict = df.to_dict(orient='list')\n\n courseCode = dict['Course']\n hours = dict['Hours']\n\n sum = 0\n\n for c in courseCode:\n if c == course:\n hours[sum] = hour\n break\n else:\n sum += 1\n\n with open(filename, 'w') as f:\n f.write('Course,Hours\\n')\n a = 0\n for i in courseCode:\n f.write(str(i))\n f.write(',')\n f.write(str(hours[a]))\n f.write('\\n')\n a += 1\n f.close()\n flag = 1\n\n if flag == 0:\n return False\n else:\n return True\n","sub_path":"editTAHours.py","file_name":"editTAHours.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"505072826","text":"\"\"\"Пользователь вводит месяц в виде целого числа от 1 до 12.\nСообщить к какому времени года относится месяц (зима, весна, лето, осень).\nНапишите решения через list и через dict.\n\"\"\"\n# list solution\n#мне кажется, должно быть посимпатичнее решение, но не нашла возвращение названия списка,\n#т.е. если создавать список year с вложенными списками - yeartime, то при проверке month in yeartime,\n#выводит содержимое каждого списка yeartime, а не его название: [12, 1, 2] вместо \"зима\"\n\ntry:\n month = int(input(\"введите номер месяца: \"))\n winter = [12, 1, 2]\n summer = [6, 7, 8]\n spring = [3, 4, 5]\n autumn = [9, 10, 11]\n if month in winter:\n print('месяц относится к зиме')\n elif month in summer:\n print('месяц относится к лету')\n elif month in spring:\n print('месяц относится к весне')\n elif month in autumn:\n print('месяц относится к осени')\n else:\n print('вы ввели неверный номер месяца нужно число от 1 до 12')\nexcept ValueError:\n print('вы ввели неверный номер месяца, нужно число от 1 до 12')\n\n#dict solution\n# try:\n# range(12)\n# month = int(input(\"введите номер месяца: \"))\n# winter = [12, 1, 2]\n# summer = [6, 7, 8]\n# spring = [3, 4, 5]\n# autumn = [9, 10, 11]\n# year = {'лету': summer,\n# 'осени': autumn,\n# 'зиме': winter,\n# 'весне': spring,\n# }\n# if month in range(1,13):\n# for yeartime in year.keys():\n# if month in year[yeartime]:\n# print(f'месяц относится к {yeartime}')\n# else: print('вы ввели неверный номер месяца, нужно число от 1 до 12')\n# except ValueError:\n# print('вы ввели неверный номер месяца, нужно число от 1 до 12')","sub_path":"task2.3.py","file_name":"task2.3.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"475232105","text":"from functools import partial\nimport itertools\nfrom typing import Sequence, Optional, Callable\n\nfrom joblib import Memory\n\nimport numpy as np\nimport pandas as pd\nimport pandas_datareader as pdr\n\n\nmem = Memory(location='.tmp-joblib')\n\n\ndef generate_uniform(size: Sequence[int]) -> pd.DataFrame:\n \"\"\"Generate sample data from uniform integers.\"\"\"\n return pd.DataFrame(np.random.randint(0, 100, size=size))\n\n\ndef build_accessor_alphavantage(key):\n from alpha_vantage.timeseries import TimeSeries\n \n @mem.cache(ignore=['ts', ])\n def single_accessor(ts: TimeSeries, ticker: str) -> pd.Series:\n data, meta = ts.get_daily(ticker)\n return data['1. open'].reset_index(drop=True)\n \n def accessor(tickers: Sequence[str]) -> pd.DataFrame:\n ts = TimeSeries(key, output_format='pandas')\n\n data, rows_calc_data = itertools.tee(map(partial(single_accessor, ts), tickers))\n min_rows = min(map(lambda d: d.shape[0], rows_calc_data))\n same_size_data = map(lambda d: d.iloc[:min_rows,], data) \n combine = pd.concat(list(same_size_data), axis=1)\n combine.columns = list(range(combine.shape[1]))\n return combine\n\n return accessor\n\n\ndef generate_tickers(tickers: Optional[Sequence[str]], accessor: Callable[[Sequence[str],], pd.DataFrame]) -> pd.DataFrame:\n \"\"\"Create a sample data from asset tickers.\n\n :param tickers: The NASDAQ Tickers one wants to use. Has a default of 12\n tickers.\n \"\"\"\n if not tickers:\n # Just some default tickers. There is no meaning behind the list and\n # are chosen without any order or relation.\n tickers = ['AAPL', 'ABC', 'IBM',\n 'MSFT', 'FB', 'AMZN',\n 'SAP', 'VLKAY', 'BASFY',\n 'PG', \n # 'NSRGF', \n 'DB']\n\n df = accessor(tickers)\n return df\n\n\ndef impute_missings(src: pd.DataFrame, p_missings: float) -> pd.DataFrame:\n missings = np.random.binomial(1, p_missings, size=src.shape)\n missings = pd.DataFrame(missings.astype(bool))\n\n return src.where(~missings, np.nan)\n\n\ndef anonymize(orig: pd.DataFrame, sd: float=1.0) -> pd.DataFrame:\n errors = np.random.normal(0.0, scale=sd, size=orig.shape)\n result = orig + errors # type: pd.DataFrame\n return result\n","sub_path":"anon_experiments/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"321957961","text":"import time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\n# -------------------------------FUNCTION------------------------------------\n# The code is used for playing audio files of given Korean words.\n# The audio files are from http://krdic.naver.com/ which is created by Korean.\n# By setting the environment and parameters, the code will automatically operate Chrome for given words,\n\n# -----------------------------ENVIRONMENT-----------------------------------\n# PyCharm 2017.3.2 (Community Edition)\n# Build #PC-173.4127.16, built on December 19, 2017\n# JRE: 1.8.0_152-release-1024-b8 amd64\n# JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o\n# Windows 10 10.0\n# Python 3.6.2\n# Selenium 2\n# ChromeDriver\n\n# Selenium: https://selenium-python.readthedocs.io/index.html\n# ChromeDriver: https://sites.google.com/a/chromium.org/chromedriver/getting-started\n\n# ---------------------------INITIALIZATION----------------------------------\nchrome = webdriver.Chrome()\nchrome.get('http://krdic.naver.com/')\n\n# -----------------------------PARAMETER-------------------------------------\n# wordString is used for storing the word list.\nwordString = ' 하나 둘 셋 넷 다섯 여섯 일곱 여덟 아홉 열 스물 서른 마흔 쉰 일 이 삼 사 오 육 칠 팔 구 십 백 천 만 영 공 ' \\\n '처음 마지막 번째 첫 번째 두 번째 개 번 명 대 잔 시 분 초 살 '\n# timeStep is used for control the time break between each word.\ntimeStep = 3.5\n\n# --------------------------------CODE---------------------------------------\nwordList = wordString.split()\n\n# loop in wordList\nfor word in wordList:\n # open the website\n chrome.get('http://krdic.naver.com/')\n\n # input the work into search box\n searchBox = chrome.find_element_by_id('krdicQuery')\n searchBox.send_keys(word)\n searchBox.send_keys(Keys.ENTER)\n\n # switch to 단어\n chrome.find_element_by_xpath('//*[@id=\"content\"]/ul/li[2]/a').click()\n\n try:\n # try the first search result\n for i in range(1, 5):\n buttonFatherXPath = '//*[@id=\"content\"]/div[2]/ul/li[1]/div/span[' + str(i) + ']'\n print(word + ': ' + str(i))\n # '//*[@id=\"content\"]/div[2]/ul/*' is the root to get the buttons\n #\n # the following path is organized as follows\n # li[\\d]: search results are listed by order, the [\\d] refers to its index.\n # if [\\d] == 1, it's the first result.\n # span[\\d]: the link is under which \n # if [\\d] == 1, it's under the first tag.\n if chrome.find_element_by_xpath(buttonFatherXPath).get_attribute(\n 'class') == 'player_search ajax_pron_sound_0':\n print(word + ' is going to play')\n buttonXPath = buttonFatherXPath + '/span'\n button = chrome.find_element_by_xpath(buttonXPath)\n\n # play the mp3\n button.click()\n time.sleep(timeStep)\n break\n else:\n continue\n except:\n # the first search result is incorrect, try the second\n try:\n # try the second search result\n for i in range(1, 5):\n buttonFatherXPath = '//*[@id=\"content\"]/div[2]/ul/li[2]/div/span[' + str(i) + ']'\n print(word + ': ' + str(i))\n # '//*[@id=\"content\"]/div[2]/ul/*' is the root to get the buttons\n #\n # the following path is organized as follows\n # li[\\d]: search results are listed by order, the [\\d] refers to its index.\n # if [\\d] == 1, it's the first result.\n # span[\\d]: the link is under which \n # if [\\d] == 1, it's under the first tag.\n if chrome.find_element_by_xpath(buttonFatherXPath).get_attribute(\n 'class') == 'player_search ajax_pron_sound_0':\n print(word + ' is going to play')\n buttonXPath = buttonFatherXPath + '/span'\n button = chrome.find_element_by_xpath(buttonXPath)\n\n # play the mp3\n button.click()\n time.sleep(timeStep)\n break\n else:\n continue\n except:\n # the second search result is incorrect, try the third\n try:\n # try the third search result\n for i in range(1, 5):\n buttonFatherXPath = '//*[@id=\"content\"]/div[2]/ul/li[3]/div/span[' + str(i) + ']'\n print(word + ': ' + str(i))\n # '//*[@id=\"content\"]/div[2]/ul/*' is the root to get the buttons\n #\n # the following path is organized as follows\n # li[\\d]: search results are listed by order, the [\\d] refers to its index.\n # if [\\d] == 1, it's the first result.\n # span[\\d]: the link is under which \n # if [\\d] == 1, it's under the first tag.\n if chrome.find_element_by_xpath(buttonFatherXPath).get_attribute(\n 'class') == 'player_search ajax_pron_sound_0':\n print(word + ' is going to play')\n buttonXPath = buttonFatherXPath + '/span'\n button = chrome.find_element_by_xpath(buttonXPath)\n\n # play the mp3\n button.click()\n time.sleep(timeStep)\n break\n else:\n continue\n except:\n print(\"There isn't a word similar to \" + word)\n continue\n\n print(word + \" is processed\")\nprint('word list finished')\n\nchrome.quit()\n","sub_path":"Vocabulary Player.py","file_name":"Vocabulary Player.py","file_ext":"py","file_size_in_byte":5909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"418948536","text":"from tkinter import *\nfrom bs4 import BeautifulSoup as bs\nimport urllib.request\nfrom apg import apagar\nimport os\nfrom PIL import ImageTk, Image\nimport time\nimport webbrowser\nimport requests\ntk = Tk()\n\ndef calcular():\n resultado = (float(valimentacao.get())-float(vled.get()))/float(i.get())\n resultado = int(resultado)\n def resul():\n resu.delete('0','end')\n resu.insert('0',str(resultado)+' ohms')\n gera = Button(text='foto', command=GerarFoto)\n gera.grid(row=3, column=1)\n def GerarFoto():\n foto = requests.get(\n f'https://www.google.com/search?q=resistor+{resultado}+ohms&source=lnms&tbm=isch&sa=X&ved=0ahUKEwibk_qv0ZPiAhVgHLkGHfgtBQsQ_AUIDygC&biw=497&bih=674')\n foto = bs(foto.text, 'html.parser')\n foto0 = foto.find_all('img')\n fotoo = foto0[1].get('src')\n\n def dl_jpg(url, file_name):\n full_path = str(file_name) + '.jpg'\n urllib.request.urlretrieve(url, full_path)\n dl_jpg(fotoo,resultado)\n from PIL import ImageTk, Image\n\n def imag():\n #############################################\n im = Tk()\n img = ImageTk.PhotoImage(Image.open(str(resultado)+\".jpg\"))\n l = Label(image=img)\n l.grid(row=4, column=1)\n im.geometry('400x400')\n apagar(str(resultado))\n ################################################\n lab = Label(text='Shop: ')\n lab.grid(row=5, column=1)\n lab['bg']='black'\n lab['fg']='white'\n ##################################################\n lin = Entry()\n lin.insert('end',f'https://www.google.com/search?biw=1745&bih=881&tbm=shop&ei=ze_WXOTPMPiy5OUP8aon&q=resistor+{str(resultado)}+ohms')\n lin.grid(row=6,column=1)\n lin['bg']='black'\n lin['fg']='white'\n def site():\n webbrowser.open(f'https://www.google.com/search?biw=1745&bih=881&tbm=shop&ei=ze_WXOTPMPiy5OUP8aon&q=resistor+{str(resultado)}+ohms', autoraise=True)\n ir = Button(text='Ir',command=site)\n ir.grid(row=6,column=2)\n\n\n\n\n\n\n im.title('foto')\n im.destroy()\n im.mainloop()\n imag()\n resul()\n\n\ndef del1(event):\n valimentacao.delete('0','end')\ndef del2(event):\n vled.delete('0','end')\ndef del3(event):\n i.delete('0','end')\n\n\n\n\n\n\ncal = Button(text='calcular',command=calcular)\ncal.grid(row=2,column=1)\n######################################\nvalimentacao = Entry()\nvalimentacao.grid(row=1,column=0)\nvalimentacao.insert('0','Alimentação')\nvalimentacao.bind(\"\",del1)\nvalimentacao['bg']='red'\n\n########################################\nvled = Entry()\nvled.grid(row=1,column=1)\nvled.insert('0','Saida')\nvled.bind(\"\",del2)\nvled['bg']='yellow'\n\n##########################################\ni = Entry()\ni.grid(row=1,column=2)\ni.insert('0','Amperes')\ni.bind(\"\",del3)\ni['bg']='green'\n\n\nresu = Entry()\nresu.grid(row=2,column=2)\nresu.insert('0','resultado')\nresu['bg']='black'\nresu['fg']='white'\n\n\n\n\ntk.geometry('400x300')\ntk.title('Calculator')\ntk['bg']='black'\ntk.mainloop()","sub_path":"calculadora.py","file_name":"calculadora.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"342508390","text":"from django.conf.urls import patterns, url\nfrom italiansushi import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n url(r'^createuser/$', views.createuser, name='createuser'),\n url(r'^login/$', views.site_login, name='login'),\n url(r'^logout/$', views.site_logout, name='logout'),\n url(r'^upload/$', views.receive_upload, name='upload'),\n url(r'^view-items/$', views.get_items, name='get_items'),\n url(r'^load-item-info/$', views.load_item_info, name='load_item_info'),\n url(r'^load-champ-info/$', views.load_champ_info, name='load_champ_info'),\n url(r'^delete-itemset/$', views.delete_itemset, name='delete_itemset'),\n url(r'^error/$', views.error_page, name='error'),\n # url(r'^ac-champ/$', views.autocomplete_champ, name='autocomplete_champ'),\n url(r'^matchup_generate_item/$', views.matchup_generate_item, name='matchup_generate_item'),\n url(r'^search-itemsets/$', views.search_itemsets, name='search_itemsets'),\n url(r'^matchup-save-file/$', views.matchup_save_file, name='matchup_save_file'),\n url(r'^custom-save-file/$', views.custom_save_file, name='custom_save_file'),\n url(r'^search-save-file/$', views.search_save_file, name='search_save_file'),\n url(r'^search-upvote-file/$', views.search_upvote_file, name='search_upvote_file'),\n url(r'^createuser-and-save/$', views.createuser_save, name='createuser'),\n url(r'^login-and-save/$', views.site_login_save, name='login'),\n url(r'^.*\\.json$', views.view_itemset, name='view_itemset'),\n url(r'^about/$', views.about_page, name = 'about'),\n url(r'^faq/$', views.faq_page, name = 'faq'),\n url(r'.*', views.bad_url, name='bad-url'),\n )","sub_path":"italiansushi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"556584776","text":"CASE = 'RedSea-AC-75mEnv'\n\nSF_TOP = '/home/teclee/DAC/FWI/SpecFEM/seisflows/'\n\nSPECFEM_BIN = SF_TOP+'../specfem2d/bin'\n\nSPECFEM_DATA = './specfem2d/DATA'\n\nSF_SCRATCH = '/scratch/teclee/seisdata/SFtests/'\n\nLOCAL = '/ssd1/teclee/'+CASE\n\nWORKDIR = SF_SCRATCH+CASE\n\n#DATA = '/data/seis/RedSea/SEM/obs_5hz_dz100'\n\nMODEL_TRUE = './model_75m'\n\nMODEL_INIT = './model_75m_sm51'\n\nMASK = './mask_75m'\n\nPRECOND = ''\n\n","sub_path":"examples/RedSea-AC/paths.py","file_name":"paths.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"214548264","text":"import serial\nimport threading;\nimport time\nimport platform\nimport signal\nfrom PyQt5 import QtCore\nimport binascii,sys,time\n\nclass SerialPortContext(QtCore.QObject,object):\n _recvSignal_ = QtCore.pyqtSignal(bytes,name=\"recvsignal\")\n \n def __init__(self,port = None,baud = 115200,bits = 8,stop_bits = 1,check=None):\n super(SerialPortContext,self).__init__()\n self._port_ = port\n if self._port_ == None:\n if platform.system() == \"Windows\":\n self._port_ = 1\n else:\n self._port_ = \"/dev/ttyUSB0\"\n \n self._baud_ = baud\n if self._baud_ <= 50 or self._baud_ > 115200:\n self._baud_ = 115200\n \n self._is_running_ = False\n self._all_counts_ = 0\n self._recv_counts_ = 0\n self._sent_counts_ = 0\n self._serial_port_ = None\n \n \n def getAllCounts(self):\n return self._all_counts_\n \n def getSendCounts(self):\n return self._sent_counts_\n \n def getRecvCounts(self):\n return self._recv_counts_\n \n def clearAllCounts(self):\n self._all_counts_ = 0\n self._recv_counts_ = 0\n self._sent_counts_ = 0\n \n def clearRecvCounts(self):\n self._recv_counts_ = 0\n def clearSentCounts(self):\n self._sent_counts_ = 0\n \n def setRXD(self,value):\n self._RXD_ = value\n if self._serial_port_ == None:\n self._RXD_ = value\n else:\n self._serial_port_.setRTS(value)\n \n def setCD(self,value):\n self._CD_ = value\n if self._serial_port_ == None:\n self._CD_ = value\n else:\n self._serial_port_.setDTR(value)\n \n def setDTR(self,value = True):\n self._DTR_ = value\n if self._serial_port_ == None:\n self._DTR_ = value\n else:\n self._serial_port_.setDTR(value)\n def setRTS(self,value = True):\n self._RTS_ = value\n if self._serial_port_ == None:\n self._RTS_ = value\n else:\n self._serial_port_.setRTS(value)\n \n def __recv_func__(self,context):\n while context.isRunning():\n if not context._serial_port_.inWaiting():\n time.sleep(0.1)\n continue\n line = context._serial_port_.read(context._serial_port_.inWaiting())\n context._recvSignal_.emit(line)\n buf_len = len(line)\n self._recv_counts_ += buf_len\n self._all_counts_ += self._recv_counts_ + self._recv_counts_\n print(\"close serial port\")\n \n def registerReceivedCallback(self,callback):\n self._recvSignal_.connect(callback)\n \n def open(self):\n self._serial_port_ = serial.Serial(self._port_,int(self._baud_))\n self._serial_port_.setRTS(self._RTS_)\n self._serial_port_.setDTR(self._DTR_)\n ## thread begin\n self._received_thread_ = threading.Thread(target = self.__recv_func__,args=(self,))\n self._is_running_ = True\n self._received_thread_.setDaemon(True)\n self._received_thread_.setName(\"SerialPortRecvThread\")\n self._received_thread_.start()\n \n def close(self):\n print(\"serial context is running: %s\" % self.isRunning())\n self._is_running_ = False\n self._received_thread_.join()\n self._serial_port_.close()\n \n def send(self,data,isHex):\n if not self.isRunning():\n return\n if not isHex:\n buff = data.encode(\"utf-8\")\n self._serial_port_.write(buff)\n buf_len = len(data)\n self._sent_counts_ += buf_len\n self._all_counts_ += self._recv_counts_ + self._recv_counts_\n\n else:\n try:\n # hex_datas = data.split(' ')\n # buffer = ''\n # for d in hex_datas:\n # buffer += d\n buffer = bytearray.fromhex(data)\n buf_len = len(buffer)\n self._sent_counts_ += buf_len\n self._all_counts_ += self._recv_counts_ + self._recv_counts_\n self._serial_port_.write(buffer)\n \n except :\n print(sys.exc_info[0])\n \n \n \n def isRunning(self):\n return self._is_running_ and self._serial_port_.isOpen()\n \n \n ","sub_path":"PyCodes/PyQt5/pyqt-serialport/serialport/serialportcontext.py","file_name":"serialportcontext.py","file_ext":"py","file_size_in_byte":4431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"318056801","text":"import sys\nimport json\n\nimport yaml\n\n# outer\nINFO_TEMPLATE = '''\nFORMAT: 1A\nHOST: {host}{basePath}\n\n# {title}\n\n{description}\n\n> Version: {version}\n'''.strip('\\n') # info & groups\n\n# each group (#)\nGROUP_TEMPLATE = '''\n# Group {group}\n\n{routes}\n'''.strip('\\n')\n\n# each route (##)\nROUTE_TEMPLATE = '''\n## {summary} [{route}]\n\n{methods}\n'''.strip('\\n')\n\n# each route method info (GET - xxx)\nMETHOD_INFO_TEMPLATE = '''\n> {method} `{route}` - {summary} {description}\n'''.strip('\\n') # req & resp\n\n# each route method demo (###)\nMETHOD_DEMO_TEMPLATE = '''\n### {summary} [{method}]\n'''.strip('\\n') # req & resp\n\n\ndef md_url(name: str, url: str, *, other: str = '') -> str:\n ret = ''\n if name != '' and url == '':\n ret = name\n elif name == '' and url != '':\n ret = url\n elif name != '' and url != '':\n ret = f'[{name}]({url})'\n if other != '':\n if ret == '':\n ret = other\n else:\n ret = f'{ret} - {other}'\n return ret\n\n\ndef pretty_json(obj: str) -> str:\n # noinspection PyBroadException\n try:\n return json.dumps(json.loads(obj), indent=4)\n except:\n return ''\n\n\ndef indent(content: str, size: int) -> str:\n \"\"\"\n make multiline have an indent\n \"\"\"\n lines = content.splitlines()\n for idx, line in enumerate(lines):\n lines[idx] = size * ' ' + line\n return '\\n'.join(lines)\n\n\ndef strcat(src: str, new: str, new_line_cnt: int = 0) -> str:\n \"\"\"\n concat string with blank lines\n \"\"\"\n src = src.strip('\\n')\n new = new.strip('\\n')\n bls = (new_line_cnt + 1) * '\\n'\n return src + bls + new\n\n\ndef field(obj: {}, *names: str):\n out = obj\n for name in names:\n if name in out:\n out = out[name]\n else:\n return ''\n return out\n\n\ndef tmpl_main(obj: {}) -> str:\n service_info = field(field(obj, 'info', 'termsOfService'))\n license_info = md_url(field(obj, 'info', 'license', 'name'), field(obj, 'info', 'license', 'url'))\n contact_info = md_url(field(obj, 'info', 'contact', 'name'), field(obj, 'info', 'contact', 'url'),\n other=field(obj, 'info', 'contact', 'email'))\n if service_info != '':\n service_info = f'>\\n> [Terms of services]({service_info})'\n if license_info != '':\n license_info = f'>\\n> License: {license_info}'\n if contact_info != '':\n contact_info = f'>\\n> Contact: {contact_info}'\n\n info = INFO_TEMPLATE.format(\n host=obj['host'],\n basePath=obj['basePath'],\n title=obj['info']['title'],\n description=obj['info']['description'],\n version=obj['info']['version']\n )\n info = strcat(info, service_info)\n info = strcat(info, license_info)\n info = strcat(info, contact_info)\n return info\n\n\ndef prehandle_paths(paths: {}) -> {}:\n \"\"\"\n parse paths dict to \"group -> route -> method\"\n \"\"\"\n groups = {}\n for route, route_obj in paths.items():\n for method, method_obj in route_obj.items():\n tab = 'Default' if len(method_obj['tags']) == 0 else method_obj['tags'][0]\n if tab not in groups:\n groups[tab] = {}\n if route not in groups[tab]:\n groups[tab][route] = {}\n groups[tab][route][method] = method_obj\n return groups\n\n\ndef tmpl_model(def_obj: {}, token: str, is_req: bool, *, prefix: str = 'body') -> str:\n \"\"\"\n parse #/definitions/xxx for request or response param\n \"\"\"\n token = token.split('/')[-1]\n if token not in def_obj:\n return ''\n obj = def_obj[token]\n if 'properties' not in obj:\n return ''\n if 'required' not in obj:\n obj['required'] = []\n ret = ''\n if is_req:\n # in: `name` (type) req - desc (empty) (def)\n for prop, po in obj['properties'].items():\n p_type = po['type']\n p_desc = po['description']\n p_req = 'required' if prop in obj['required'] else 'not required'\n p_def = f' (default: {po[\"default\"]})' if 'default' in po else ''\n if 'allowEmptyValue' in po:\n p_empty = ' (allow empty)' if po['allowEmptyValue'] else ' (not empty)'\n else:\n p_empty = ''\n ret = strcat(ret, f'+ `{prefix}` : `{prop}` ({p_type}) {p_req} - {p_desc}{p_empty}{p_def}')\n if 'enum' in po:\n ret = strcat(ret, indent(f'+ enum: {po[\"enum\"]}', 4))\n nest_type = ''\n if p_type == 'object':\n nest_type = po['$ref']\n elif p_type == 'array':\n nest_type = po['items']['$ref']\n if nest_type != '':\n nest_tmpl = tmpl_model(def_obj, nest_type, is_req, prefix=prop).strip('\\n')\n ret = strcat(ret, indent(nest_tmpl, 4))\n else:\n # in: `name` (type) - desc (empty) (example)\n for prop, po in obj['properties'].items():\n p_type = po['type']\n p_desc = po['description']\n p_ex = f' (example: {po[\"example\"]})' if 'example' in po else ''\n if 'allowEmptyValue' in po:\n p_empty = ' (allow empty)' if po['allowEmptyValue'] else ' (not empty)'\n else:\n p_empty = ''\n ret = strcat(ret, f'+ `{prefix}` : `{prop}` ({p_type}) - {p_desc}{p_empty}{p_ex}')\n if 'enum' in po:\n ret = strcat(ret, indent(f'+ enum: {po[\"enum\"]}', 4))\n nest_type = ''\n if p_type == 'object':\n nest_type = po['$ref']\n elif p_type == 'array':\n nest_type = po['items']['$ref']\n if nest_type != '':\n nest_tmpl = tmpl_model(def_obj, nest_type, is_req, prefix=prop).strip('\\n')\n ret = strcat(ret, indent(nest_tmpl, 4))\n return ret\n\n\ndef tmpl_ctrl(groups_obj: {}, def_obj: {}) -> str:\n def parse_method_info(route: str, method: str, obj: {}) -> str:\n # -> GET - Summary\n tmpl = METHOD_INFO_TEMPLATE.format(\n method=method.upper(),\n route=route,\n summary=obj['summary'],\n description=f'({obj[\"description\"]})' if 'description' in obj else ''\n ).strip(' ')\n\n req = ''\n resp = ''\n # Req Param\n if 'parameters' in obj:\n req = strcat(req, f'+ Request Parameter', 1)\n for idx, param in enumerate(obj['parameters']):\n p_name, p_in, p_desc = param['name'], param['in'], param['description']\n if 'type' in param:\n p_type = param['type']\n elif 'schema' in param:\n nest_type = tmpl_model(def_obj, param['schema']['$ref'], True)\n if nest_type != '':\n req = strcat(req, indent(nest_type, 4), 1 if idx == 0 else 0)\n continue\n else:\n p_type = 'unknown'\n p_req = 'required' if param['required'] else 'not required'\n p_def = f' (default: {param[\"default\"]})' if 'default' in param else ''\n if 'allowEmptyValue' in param:\n p_empty = ' (allow empty)' if param['allowEmptyValue'] else ' (not empty)'\n else:\n p_empty = ''\n req_param = f'+ `{p_in}` : `{p_name}` ({p_type}) {p_req} - {p_desc}{p_empty}{p_def}'\n req = strcat(req, indent(req_param, 4), 1 if idx == 0 else 0)\n if 'enum' in param:\n req = strcat(req, indent(f'+ enum: {param[\"enum\"]}', 8))\n\n # Resp 200\n if 'responses' in obj:\n codes = [int(c) for c in obj['responses'].keys()]\n codes = [str(c) for c in sorted(codes)]\n for code in codes:\n resp_obj = obj['responses'][code]\n # Resp Desc\n if 'description' in resp_obj:\n resp = strcat(resp, f'+ Response {code}', 1)\n resp_desc = '+ ' + resp_obj['description']\n resp_desc = indent(resp_desc, 4)\n resp = strcat(resp, resp_desc, 1)\n # Resp Header\n if 'headers' in resp_obj:\n headers_obj = {k: v for k, v in resp_obj['headers'].items() if k != 'Content-Type'}\n if len(headers_obj) > 0:\n resp = strcat(resp, f'+ Response {code} Header', 1)\n for header, header_obj in headers_obj.items():\n resp_header = f'+ `{header}` ({header_obj[\"type\"]})'\n resp_header = indent(resp_header, 4)\n resp = strcat(resp, resp_header, 1)\n # Resp Body\n if 'schema' in resp_obj:\n resp = strcat(resp, f'+ Response {code} Body', 1)\n nest_type = tmpl_model(def_obj, resp_obj['schema']['$ref'], False)\n if nest_type != '':\n resp = strcat(resp, indent(nest_type, 4))\n tmpl = strcat(tmpl, req, 1)\n tmpl = strcat(tmpl, resp, 1)\n return tmpl\n\n def parse_method_demo(method: str, obj: {}) -> str:\n # -> ### Summary [GET]\n tmpl = METHOD_DEMO_TEMPLATE.format(\n summary=obj['summary'],\n method=method.upper()\n )\n req_codes = list(obj['requests'].keys()) if 'requests' in obj else []\n resp_codes = list(obj['responses'].keys()) if 'responses' in obj else []\n codes = [int(c) for c in req_codes + resp_codes]\n codes = [str(c) for c in sorted(set(codes))]\n for code in codes:\n req = ''\n resp = ''\n # Request 200\n if 'requests' in obj and code in obj['requests']:\n req = strcat(req, f'+ Request {code}', 1)\n req_obj = obj['requests'][code]\n # Header\n if 'headers' in req_obj:\n req = strcat(req, indent('+ Headers', 4), 1)\n for idx, (header, header_obj) in enumerate(req_obj['headers'].items()):\n req_header = f'{header}: {header_obj[\"description\"]}'\n req_header = indent(req_header, 12)\n req = strcat(req, req_header, 1 if idx == 0 else 0)\n # Body\n if 'examples' in req_obj:\n req = strcat(req, indent('+ Body', 4), 1)\n req_body = pretty_json(req_obj['examples']['application/json'])\n req_body = indent(req_body, 12)\n req = strcat(req, req_body, 1)\n\n # Response 200\n if 'responses' in obj and code in obj['responses']:\n resp = strcat(resp, f'+ Response {code}', 1)\n resp_obj = obj['responses'][code]\n # Header\n if 'headers' in resp_obj:\n resp = strcat(resp, indent('+ Headers', 4), 1)\n for header, header_obj in resp_obj['headers'].items():\n resp_header = f'{header}: {header_obj[\"description\"]}'\n resp_header = indent(resp_header, 12)\n resp = strcat(resp, resp_header, 1)\n # Body\n if 'examples' in resp_obj:\n resp = strcat(resp, indent('+ Body', 4), 1)\n resp_body = pretty_json(resp_obj['examples']['application/json'])\n resp_body = indent(resp_body, 12)\n resp = strcat(resp, resp_body, 1)\n tmpl = strcat(tmpl, req, 1)\n tmpl = strcat(tmpl, resp, 1)\n return tmpl\n\n def parse_route(route: str, route_obj: {}) -> str:\n \"\"\"\n parse at '/v1/xxx': {'get': {xxx}}\n \"\"\"\n method_infos = ''\n method_demos = ''\n for method, method_obj in route_obj.items():\n method_info = parse_method_info(route, method, method_obj)\n method_demo = parse_method_demo(method, method_obj)\n method_infos = strcat(method_infos, method_info, 1)\n method_demos = strcat(method_demos, method_demo, 1)\n ret = ''\n ret = strcat(ret, method_infos, 1)\n ret = strcat(ret, method_demos, 1)\n return ret\n\n out = ''\n for group, group_obj in groups_obj.items():\n # -> # Group\n routes = ''\n for route, route_obj in group_obj.items():\n # -> ## Route [xxx]\n summary = [method_obj['summary'] for method_obj in route_obj.values()]\n summary = ' & '.join(summary)\n methods = parse_route(route, route_obj)\n tmpl = ROUTE_TEMPLATE.format(\n summary=summary,\n route=route,\n methods=methods\n )\n routes = strcat(routes, tmpl, 1)\n\n tmpl = GROUP_TEMPLATE.format(\n group=group,\n routes=routes\n )\n out = strcat(out, tmpl, 1)\n return out\n\n\ndef run(yaml_name, apib_output):\n # noinspection PyBroadException\n try:\n print(f'> Reading {yaml_name}...')\n content = open(yaml_name, 'r', encoding='utf-8').read()\n except:\n print(f'Error: failed to open file {yaml_name}.')\n sys.exit(1)\n\n spec = yaml.load(content, Loader=yaml.FullLoader)\n\n # !!\n apib = tmpl_main(spec)\n groups_obj = prehandle_paths(spec['paths'])\n apib = strcat(apib, tmpl_ctrl(groups_obj, spec['definitions']), 1)\n\n apib_len = len(apib)\n while True:\n apib = apib.replace('\\n\\n\\n', '\\n\\n')\n if apib_len != len(apib):\n apib_len = len(apib)\n else:\n break\n apib += '\\n'\n\n # noinspection PyBroadException\n try:\n print(f'> Saving {apib_output}...')\n with open(apib_output, 'w', encoding='utf-8') as f:\n f.write(apib)\n except Exception as e:\n print(f'Error: failed to save file {apib_output}.{e}')\n sys.exit(1)\n\n\nclass Apib:\n\n def __init__(self, args):\n run(args.yaml_output, args.apib_output)\n","sub_path":"apib.py","file_name":"apib.py","file_ext":"py","file_size_in_byte":14029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"204828501","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 28 23:39:32 2019\n\n@author: WEIMIN ZHOU\n\"\"\"\n\nN = 100\n\ntotal = 0\ncur = 1.0\nfor i in range(1, N+1):\n cur /= i\n total += cur\n\nprint(total)\n\n","sub_path":"factorial.py","file_name":"factorial.py","file_ext":"py","file_size_in_byte":189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"260665216","text":"import json\nfrom os import listdir\n\ndef json_final_shape():\n with open(\"config/teachers_list.txt\", \"r\") as f:\n teachers_list = f.readlines()\n dirs = listdir(\"class_files\")\n for dir in dirs:\n files = listdir(\"class_files/{}\".format(dir))\n for file in files:\n with open(\"class_files/{}/{}\".format(dir, file), \"r\", encoding=\"utf8\") as f:\n dictionary = dict(json.load(f))\n replacement_list_final = []\n for key in dictionary.keys():\n if key.count(\"_\"):\n group = key[2:]\n replacement_subdict = {\"Lesson\": key[0], \"Group\": group}\n else:\n replacement_subdict = {\"Lesson\": key}\n replacement_content = str(dictionary[key])\n if replacement_content.count(\"\\n\") == 1:\n replacement_subdict[\"Description\"] = dictionary[key][:-1]\n replacement_list_final.append(replacement_subdict)\n elif replacement_content.count(\"\\n\") == 2:\n new_line_char_index = replacement_content.index(\"\\n\")\n description = replacement_content[new_line_char_index+1:-1]\n if description + \"\\n\" in teachers_list:\n replacement_subdict[\"Teacher\"] = description\n else:\n replacement_subdict[\"Description\"] = description\n replacement_list_final.append(replacement_subdict)\n else:\n new_line_char_index = replacement_content.index(\"\\n\")\n description = replacement_content[new_line_char_index+1:-1]\n new_line_char_index = replacement_content.index(\"\\n\", new_line_char_index+1)\n teacher = replacement_content[new_line_char_index+1:-1]\n replacement_subdict[\"Description\"] = description\n replacement_subdict[\"Teacher\"] = teacher\n replacement_list_final.append(replacement_subdict)\n with open(\"class_files/{}/{}\".format(dir, file), \"w\", encoding=\"utf8\") as fw:\n json.dump(replacement_list_final, fw, indent=4, ensure_ascii=False)\n","sub_path":"data/json_parser.py","file_name":"json_parser.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"615501137","text":"# -*- coding: utf-8 -*-\n\n# -----------------------------------------------\n# インポート\n# -----------------------------------------------\nimport pygame\nfrom pygame.locals import *\nimport sys\nfrom obj.dango import Dango\nfrom obj.star import Star\nfrom obj.stars import Stars\nfrom obj.score import Score\nfrom obj.bg import BG\n\n# -----------------------------------------------\n# 定義\n# -----------------------------------------------\n# ダンゴムシスピード\nds_up = -5\nds_down = 10\n\n# ダンゴムシ初期位置\n(x, y) = (100, 200)\n\n# -----------------------------------------------\n# 星集めクラス\n# -----------------------------------------------\nclass GetStar():\n def __init__(self, screen):\n # メイン画面\n self.screen = screen\n\n # 終了フラグ\n self.finished = False\n\n # 背景\n self.bg = BG(screen)\n\n # スコア表示\n self.score = Score(screen)\n\n # ダンゴ虫\n self.dango = Dango(screen, x, y)\n\n # 星\n self.stars = Stars(screen, self.dango, self.score)\n\n # BGM\n pygame.mixer.music.load('bgm/4 On The Floor 05.wav')\n pygame.mixer.music.set_volume(0.5)\n pygame.mixer.music.play(-1)\n\n def Update(self):\n # Returnキー押している間ダンゴムシが丸まって下降\n pressed = pygame.key.get_pressed()\n if pressed[K_RETURN]:\n self.dango.SetForm(True)\n if self.dango.rect.bottom <= self.screen.get_height():\n self.dango.rect.move_ip(0, ds_down)\n else:\n self.dango.SetForm(False)\n if self.dango.rect.top >= 0 : \n self.dango.rect.move_ip(0, ds_up)\n\n # スペースキーで戻る\n if pressed[K_SPACE]:\n self.finished = True\n\n # 終了判定\n if pressed[K_ESCAPE]:\n pygame.quit()\n sys.exit(0)\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit(0)\n\n def Draw(self):\n # 表示更新\n pygame.display.update()\n pygame.time.wait(30)\n self.screen.fill((255, 255, 255))\n self.bg.Update()\n self.stars.Update()\n self.dango.Update()\n self.score.Update()\n\n# -----------------------------------------------\n# 単体テスト\n# -----------------------------------------------\nif __name__ == '__main__':\n # 初期化\n pygame.init()\n pygame.mixer.init()\n\n # 画面生成\n pygame.display.set_mode((800, 600), 0, 32)\n screen = pygame.display.get_surface()\n pygame.display.set_caption('Get Star')\n\n gs = GetStar(screen)\n\n while True:\n gs.Update()\n gs.Draw()","sub_path":"get_star.py","file_name":"get_star.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"31981608","text":"#\n# Effects\n#\n# Basic mode for general effects and control of game items (lamps, coils, etc.)\n# Loaded in startup, so also operational in Attract mode\n#\n__author__=\"Pieter\"\n__date__ =\"$10 Sep 2012 20:36:37 PM$\"\n\n\nimport procgame\nfrom procgame import *\n\n#game_path = config.value_for_key_path('game_path')\n#dmd_path = game_path +\"dmd/\"\n\nclass Effects(game.Mode):\n\n def __init__(self, game):\n super(Effects, self).__init__(game, 4)\n\n# Lamp effects\n\n def drive_lamp_schedule(self, lamp_name, schedule=0x0f0f0f0f, cycle_seconds=0, now=True):\n self.game.lamps[lamp_name].schedule(schedule=schedule, cycle_seconds=cycle_seconds, now=now)\n\n def drive_lamp(self, lamp_name, style='on',time=2):\n if style == 'slow':\n self.game.lamps[lamp_name].schedule(schedule=0x00ff00ff, cycle_seconds=0, now=True)\n elif style == 'medium':\n self.game.lamps[lamp_name].schedule(schedule=0x0f0f0f0f, cycle_seconds=0, now=True)\n elif style == 'fast':\n self.game.lamps[lamp_name].schedule(schedule=0x55555555, cycle_seconds=0, now=True)\n elif style == 'superfast':\n self.game.lamps[lamp_name].schedule(schedule=0x99999999, cycle_seconds=0, now=True)\n elif style == 'on':\n self.game.lamps[lamp_name].enable()\n elif style == 'off':\n self.game.lamps[lamp_name].disable()\n # also cancel any pending delays\n self.cancel_delayed(lamp_name+'_medium')\n self.cancel_delayed(lamp_name+'_fast')\n self.cancel_delayed(lamp_name+'_superfast')\n elif style == 'smarton':\n self.game.lamps[lamp_name].schedule(schedule=0xaaaaaaaa, cycle_seconds=0, now=True)\n self.delay(name=lamp_name+'_on', event_type=None, delay=0.6, handler=self.game.lamps[lamp_name].enable)\n elif style == 'smartoff':\n self.game.lamps[lamp_name].schedule(schedule=0xaaaaaaaa, cycle_seconds=0, now=True)\n self.delay(name=lamp_name+'_off', event_type=None, delay=0.6, handler=self.game.lamps[lamp_name].disable)\n elif style == 'timeout':\n self.game.lamps[lamp_name].schedule(schedule=0x0f0f0f0f, cycle_seconds=0, now=True)\n if time>10:\n self.delay(name=lamp_name+'_medium', event_type=None, delay=time-10, handler=self.drive_medium, param=lamp_name)\n if time>5:\n self.delay(name=lamp_name+'_fast', event_type=None, delay=time-5, handler=self.drive_fast, param=lamp_name)\n if time>1:\n self.delay(name=lamp_name+'_superfast', event_type=None, delay=time-1, handler=self.drive_super_fast, param=lamp_name)\n self.delay(name=lamp_name+'_off', event_type=None, delay=time, handler=self.game.lamps[lamp_name].disable)\n\n def drive_super_fast(self, lamp_name):\n self.game.lamps[lamp_name].schedule(schedule=0x99999999, cycle_seconds=0, now=True)\n\n def drive_fast(self, lamp_name):\n self.game.lamps[lamp_name].schedule(schedule=0x55555555, cycle_seconds=0, now=True)\n\n def drive_medium(self, lamp_name):\n self.game.lamps[lamp_name].schedule(schedule=0x0f0f0f0f, cycle_seconds=0, now=True)\n\n def clear_all_lamps(self):\n for lamp in self.game.lamps:\n lamp.disable()\n\n def update_ramp_lamps(self):\n # called from ramp_move to update lamps after change in rampstatus\n # add call to lamp update function for specific mode\n self.game.base_game_mode.missions_modes.update_ramp_lamps()\n self.game.base_game_mode.generalplay.update_ramp_lamps()\n\n# Flashers + GI effects\n\n def drive_flasher(self, flasher_name, style='off',seconds_on=0):\n if style == 'slow':\n self.game.coils[flasher_name].schedule(schedule=0x0000FFFF, cycle_seconds=seconds_on, now=True)\n elif style == 'medium':\n self.game.coils[flasher_name].schedule(schedule=0x00FF00FF, cycle_seconds=seconds_on, now=True)\n elif style == 'fast':\n self.game.coils[flasher_name].schedule(schedule=0x0F0F0F0F, cycle_seconds=seconds_on, now=True)\n elif style == 'off':\n self.game.coils[flasher_name].disable()\n\n def all_flashers_off(self):\n self.game.coils.workshopFlash.disable()\n self.game.coils.showroomFlash.disable()\n self.game.coils.Llightningbolt.disable()\n self.game.coils.Rlightningbolt.disable()\n\n def gi_on(self):\n self.game.coils.GIrelay.disable()\n\n def gi_off(self):\n self.game.coils.GIrelay.enable()\n\n def gi_blinking(self, schedule=0x0f0f0f0f, cycle_seconds=1, now=True):\n self.game.coils.GIrelay.schedule(schedule=schedule, cycle_seconds=cycle_seconds, now=now)\n\n# AC-Select coils\n\n def raise_droptarget(self):\n if self.check_droptarget() == False:\n self.game.coils.ACselect.pulse(60)\n self.game.coils.bikesFlash_dropTarget.pulse(60)\n self.drive_lamp('spotLetter','on')\n\n def check_droptarget(self):\n if self.game.switches.dropTarget.is_active():\n self.droptarget_up = False;\n self.drive_lamp('spotLetter','off')\n print(\"Droptarget= Down\")\n elif self.game.switches.dropTarget.is_inactive():\n self.droptarget_up = True;\n self.drive_lamp('spotLetter','on')\n print(\"Droptarget= Up\")\n return self.droptarget_up\n\n# Ball control\n\n def flippers(self, flip_on=True):\n if flip_on:\n self.game.coils.flipperEnable.enable()\n else:\n self.game.coils.flipperEnable.disable()\n\n def release_stuck_balls(self):\n #left eject\n if self.game.switches.Leject.is_active():\n self.game.coils.Leject.pulse(20)\n\n #center eject\n if self.game.switches.Ceject.is_active():\n self.game.coils.Ceject.pulse(20)\n\n #upper left kicker\n if self.game.switches.upperLkicker.is_active():\n self.game.coils.ACselect.pulse(35)\n self.game.coils.rearFlash_upLeftkicker.pulse(30)\n\n #outhole\n if self.game.switches.outhole.is_active():\n self.game.coils.outhole.pulse(30)\n\n def eject_ball(self, location='all', ball_save=False):\n #left eject\n if location == 'all' or location == 'Leject':\n if self.game.switches.Leject.is_active():\n self.game.coils.workshopFlash.schedule(schedule=0x33333333, cycle_seconds=1, now=True)\n self.delay(name='search_leject', event_type=None, delay=0.8, handler=self.search_leject)\n #self.game.coils.Leject.pulse(30)\n\n #center eject\n if location == 'all' or location == 'Ceject':\n if self.game.switches.Ceject.is_active():\n self.game.coils.showroomFlash.schedule(schedule=0x33333333, cycle_seconds=1, now=True)\n self.delay(name='search_ceject', event_type=None, delay=0.8, handler=self.search_ceject)\n #self.game.coils.Ceject.pulse(30)\n if ball_save:\n self.game.ball_save.start(num_balls_to_save=1, time=2, now=True, allow_multiple_saves=False)\n #self.game.ball_save.add(add_time=2, allow_multiple_saves=False)\n\n #upper left kicker\n if location == 'all' or location == 'upperLkicker':\n if self.game.switches.upperLkicker.is_active():\n self.game.coils.ACselect.pulse(35)\n self.game.coils.rearFlash_upLeftkicker.pulse(30)\n\n def ball_search(self):\n self.delay(name='search_leject', event_type=None, delay=0.4, handler=self.search_leject)\n self.delay(name='search_ceject', event_type=None, delay=0.8, handler=self.search_ceject)\n self.delay(name='search_upleftkicker', event_type=None, delay=1.2, handler=self.search_upleftkicker)\n self.delay(name='search_rampup', event_type=None, delay=1.6, handler=self.search_rampup)\n self.delay(name='search_outhole', event_type=None, delay=2.0, handler=self.search_outhole)\n\n def search_leject(self):\n self.game.coils.Leject.pulse(20)\n\n def search_ceject(self):\n self.game.coils.Ceject.pulse(15)\n\n def search_upleftkicker(self):\n self.game.coils.ACselect.pulse(40)\n self.game.coils.rearFlash_upLeftkicker.pulse(30)\n\n def search_rampup(self):\n self.game.coils.ACselect.pulse(60)\n self.game.coils.knocker_rampUp.pulse(50)\n\n def search_outhole(self):\n self.game.coils.outhole.pulse(40)\n\n","sub_path":"effects.py","file_name":"effects.py","file_ext":"py","file_size_in_byte":9081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"605575434","text":"# 백준 2156 포도주 서식\n# DP\nimport sys\ninput = sys.stdin.readline\n\nn = int(input()) # 테스트케이스\nw = [0] \nfor i in range(n): \n w.append(int(input())) # 포도주의 양\ndp = [0] \n \ndp.append(w[1])\nif n > 1:\n dp.append((w[1] + w[2]))\n\nfor i in range(3, n+1):\n dp.append(max(dp[i-1], dp[i-3]+w[i-1]+w[i], dp[i-2]+w[i]))\nprint(dp[n])","sub_path":"2156.py","file_name":"2156.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"269861412","text":"from __future__ import division # Wihtout this, the star is effed up.\nimport turtle\nnPoint = turtle.Turtle()\n\ndef star(t, n):\n for i in range(n):\n t.forward(100)\n t.left(180 - 180/n)\n \ndef main():\n wn = turtle.Screen()\n \n star(nPoint, 50)\n\n wn.exitonclick()\n\nif __name__ == \"__main__\":\n main()","sub_path":"misc/ip/section_4/exercises/custom_points.py","file_name":"custom_points.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"341270980","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.font_manager import FontProperties\n\n\nfont = FontProperties(fname=r\"C:\\Windows\\Fonts\\STHUPO.TTF\", size=14)\nstudents = pd.read_excel('temp/Students.xlsx')\n# print(students)\nstudents.sort_values(by='score', inplace=True, ascending=False)\n# students.plot.bar(x='student', y='score', color='red', title='2nd Exam Score')\nplt.bar(students.student, students.score, width=0.5)\nplt.xticks(students.student, rotation='90')\n\nplt.title('期中考成绩', FontProperties=font)\nplt.xlabel('姓名', FontProperties=font)\nplt.ylabel('分数', FontProperties=font)\nplt.tight_layout()\nplt.show()\n","sub_path":"009狀圖1列.py","file_name":"009狀圖1列.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"322270969","text":"\"\"\"\nExercise 1\n\nWrite a function called most_frequent that takes a string and prints the\nletters in decreasing order of frequency. Find text samples from several\ndifferent languages and see how letter frequency varies between languages.\nCompare your results with the tables at\nhttp://en.wikipedia.org/wiki/Letter_frequencies.\n\nSolution:\nhttp://thinkpython2.com/code/most_frequent.py.\n\"\"\"\n\n\ndef frequency(t):\n t = t.lower().replace(\" \", \"\")\n\n freq = dict()\n\n for i in t:\n if i in freq:\n freq[i] += 1\n else:\n freq[i] = 1\n\n return freq\n\n\nif __name__ == '__main__':\n test_string = \"Hello, world\"\n\n hist = frequency(test_string)\n\n sort_hist = sorted(hist.items(), key=lambda kv: kv[1], reverse=True)\n\n new_string = \"\"\n for key, value in sort_hist:\n new_string += key * value\n\n for i in new_string:\n print(i)\n","sub_path":"ch12/ex1-most_frequent.py","file_name":"ex1-most_frequent.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"478034427","text":"import json\n\nimport requests\n\nfrom plan.models import LocationCache\nfrom plan.utils.debug import print_message\n\nrouter = 'https://router.project-osrm.org/{action}'\n\n\ndef calculate_distance(route):\n print_message('calculate distance')\n request_router(route)\n print_message('calculated')\n\n\ndef request_router(route):\n orders = route.orders.filter(location__is_valid=True)\n if orders.count() == 0:\n return\n previous = None\n\n # first\n first_order = orders.first()\n distance, duration = process_location(route.start_location, first_order.location)\n first_order.distance = distance\n first_order.duration = duration\n first_order.save()\n # orders\n for order in orders:\n if previous is None:\n previous = order\n continue\n distance, duration = process_location(previous.location, order.location)\n order.distance = distance\n order.duration = duration\n order.save()\n previous = order\n\n # last\n last_order = orders.last()\n distance, duration = process_location(last_order.location, route.end_location)\n route.distance = distance\n route.duration = duration\n route.save()\n\n\ndef process_location(location_from, location_to):\n distance = 0\n duration = 0\n if location_from.latitude != location_to.latitude or location_from.longitude != location_to.longitude:\n cache = get_location_cache(location_from, location_to)\n distance = cache.distance\n duration = cache.duration\n return distance, duration\n\n\ndef get_location_cache(location_from, location_to):\n if location_from.is_valid is False or location_to.is_valid is False:\n return None\n cache = LocationCache.objects.filter(from_latitude=location_from.latitude, from_longitude=location_from.longitude,\n to_latitude=location_to.latitude, to_longitude=location_to.longitude)\n if cache.count() > 0:\n return cache[0]\n return request_viaroute(location_from, location_to)\n\n\ndef request_viaroute(location_from, location_to):\n params = {\n 'headers': {\n 'User-Agent': 'Planndit',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n }\n }\n data = {\n 'loc': [\n str(location_from.latitude) + ',' + str(location_from.longitude),\n str(location_to.latitude) + ',' + str(location_to.longitude)\n ],\n }\n raw_response = requests.get(router.format(action='viaroute'), data, **params)\n response = json.loads(raw_response.text)\n distance, duration = parse_response(response)\n cache = LocationCache.objects.create(from_latitude=location_from.latitude, from_longitude=location_from.longitude,\n to_latitude=location_to.latitude, to_longitude=location_to.longitude,\n distance=distance, duration=duration)\n return cache\n\n\ndef parse_response(response):\n summary = response['route_summary']\n distance = summary.get('total_distance', 0)\n duration = summary.get('total_time', 0)\n return distance, duration\n","sub_path":"plan/externals/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":3162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"148065355","text":"import pandas as pd\nimport re\nimport numpy as np\nfrom utils import data_path\nimport os\n\n\ndef is_same_Chinese(first_word, second_word):\n min_len = min(len(first_word), len(second_word))\n\n first_word_chinese = sorted([char for char in first_word if '\\u4e00' <= char <= '\\u9fff'])\n second_word_chinese = sorted([char for char in second_word if '\\u4e00' <= char <= '\\u9fff'])\n\n # 如果两个实体的中文部分相同,且各自至少包含一个中文字符,则返回true\n if first_word_chinese == second_word_chinese and len(first_word_chinese) > 0 and len(second_word_chinese) > 0:\n return True\n else:\n return False\n\n\ndef post_process(submit_data):\n id_add = []\n id_min = []\n for index, item in submit_data.iterrows():\n entity = item['entity'].split(';')\n for i in entity:\n if 'P2P' in i and len(i) < 6 and item['negative'] == 1 and i in item['key_entity']:\n id_min.append([i, item['id']])\n if '*' not in i and '(' not in i and ')' not in i and '?' not in i and len(i) > 1:\n result_add = re.search(i + '[^(。|,)]{1,10}(被裁定|被强制执行|被曝|自担保)', item['text'])\n result_min = re.search(i + '[^(。|,)]{1,10}(信誉十分好|逾期降低|符合国家规定|逾期率.*低至)', item['text'])\n if result_min is not None and i in item['key_entity']:\n id_min.append([i, item['id']])\n if result_add is not None:\n if item['negative'] == 0:\n flag = True\n for add_index in range(len(id_add)):\n add_str, add_id = id_add[add_index]\n if item['id'] == add_id:\n if i in add_str:\n flag = False\n continue\n elif add_str in i:\n flag = False\n id_add[add_index][0] = i\n if flag:\n id_add.append([i, item['id']])\n\n for item in id_add:\n # print(item[1])\n neg_pos = submit_data.columns.tolist().index('negative')\n key_entity_pos = submit_data.columns.tolist().index('key_entity')\n submit_data.iloc[submit_data[submit_data['id'] == item[1]].index.item(), neg_pos] = 1\n submit_data.iloc[submit_data[submit_data['id'] == item[1]].index.item(), key_entity_pos] = item[0]\n\n for item in id_min:\n # print(item[1])\n neg_pos = submit_data.columns.tolist().index('negative')\n key_entity_pos = submit_data.columns.tolist().index('key_entity')\n key_entity = submit_data.iloc[submit_data[submit_data['id'] == item[1]].index.item(), key_entity_pos].split(';')\n key_entity.remove(item[0])\n if len(key_entity) == 0:\n submit_data.iloc[submit_data[submit_data['id'] == item[1]].index.item(), neg_pos] = 0\n submit_data.iloc[submit_data[submit_data['id'] == item[1]].index.item(), key_entity_pos] = np.nan\n else:\n submit_data.iloc[submit_data[submit_data['id'] == item[1]].index.item(), key_entity_pos] = ';'.join(key_entity)\n\n return submit_data\n\n\nif __name__ == '__main__':\n train_path = os.path.join(data_path, \"preprocess\", \"Train_Data_round2.csv\")\n test_path = os.path.join(data_path, \"preprocess\", \"Test_Data_round2.csv\")\n train_data = pd.read_csv(train_path)\n test_data = pd.read_csv(test_path)\n model_predict_result = pd.read_csv(os.path.join(data_path, \"submit\", \"fuxian_replace_post.csv\"))\n merge_data = test_data.merge(model_predict_result, left_on='id', right_on='id')\n\n for index, cur_row in merge_data.iterrows():\n if type(cur_row['entity']) == float:\n continue\n if type(cur_row['key_entity']) == float:\n continue\n\n entity_list = list(set(cur_row['entity'].split(';')))\n if '' in entity_list:\n entity_list.remove('')\n\n key_entity_list = list(set(cur_row['key_entity'].split(';')))\n if '' in key_entity_list:\n key_entity_list.remove('')\n\n final_key_entity_list = key_entity_list.copy()\n\n # 两重for循环,相当于形成(entity_outter, entity_inner) 实体对\n for i, key_entity_outter in enumerate(key_entity_list):\n for j, key_entity_inner in enumerate(key_entity_list):\n if i == j:\n continue\n\n # 如果两个实体只是相差英文大小写,则将不在文本中的实体删掉\n if key_entity_outter.lower() == key_entity_inner.lower():\n if key_entity_outter in cur_row['text'] and key_entity_inner not in cur_row['text']:\n final_key_entity_list.remove(key_entity_inner)\n\n # # 如果两个entity的汉字部分一样\n if is_same_Chinese(key_entity_inner, key_entity_outter):\n # 如果其中一个包含?或者空格,则将另一个实体删掉\n if '?' in key_entity_inner or ' ' in key_entity_inner:\n final_key_entity_list.remove(key_entity_outter)\n\n for i, entity_outter in enumerate(entity_list):\n for j, entity_inner in enumerate(entity_list):\n if i == j:\n continue\n if is_same_Chinese(entity_inner, entity_outter):\n if '?' in entity_inner and entity_outter in final_key_entity_list:\n final_key_entity_list.remove(entity_outter)\n final_key_entity_list.append(entity_inner)\n\n merge_data.loc[index:index, 'key_entity'] = ';'.join(final_key_entity_list)\n\n submit_data = post_process(merge_data)\n submit_data.to_csv(os.path.join(data_path, \"submit\", \"fuxian_replace_post_v2.csv\"),\n columns=['id', 'negative', 'key_entity'], index=False)\n","sub_path":"post_process.py","file_name":"post_process.py","file_ext":"py","file_size_in_byte":6014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"599451016","text":"import csv\r\nimport matplotlib.pyplot as plt \r\nimport numpy as np \r\nfrom mpl_toolkits.mplot3d import axes3d\r\n\r\nperokok= []\r\nwith open('Persentase Perokok RI.csv', 'r') as data:\r\n reader = csv.DictReader(data)\r\n for i in reader:\r\n perokok.append(dict(i))\r\nprov = []\r\nt_15 = []\r\nt_16= []\r\nfor i in perokok:\r\n prov.append('{}'.format(i['Provinsi']))\r\n t_15.append(float(i['2015']))\r\n t_16.append(float(i['2016']))\r\n\r\n\r\n\r\nx = []\r\nfor i1 in range(len(prov)):\r\n x.append(i1)\r\ny1 = np.repeat(1, len(t_15))\r\ny2 = np.repeat(3, len(t_15))\r\n\r\nx1 = []\r\nfor i1 in range(0, len(prov)):\r\n x1.append(i1)\r\n\r\nz = np.zeros(len(prov))\r\ndx = np.zeros(len(prov))\r\ndy = np.ones(len(prov))\r\ntick1 = np.arange(len(prov))\r\n\r\n\r\n\r\nplt.figure(\"Presentase Perokok Indonesia per Provinsi\")\r\nplt.style.use('seaborn-ticks')\r\n\r\nax = plt.subplot(111,projection='3d')\r\nax.bar3d(x, y1, z, dx, dy, t_15, color='lightblue')\r\nax.bar3d(x1, y2, z, dx, dy, t_16, color='lightyellow')\r\n\r\nplt.xticks(tick1, prov)\r\nplt.yticks([1.5,3.5],[2015,2016])\r\nplt.xticks(rotation=90)\r\nplt.show()","sub_path":"%tase_perokok_RI.py","file_name":"%tase_perokok_RI.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"281898365","text":"# ライブラリのインポート\nimport cv2\n\n# 画像の読み込み\nimage = cv2.imread(\"/home/pi/デスクトップ/opencv/face.jpg\")\n\n# カスケードファイルの指定\ncasceade_file = \"/home/pi/デスクトップ/opencv/haarcascade_frontalface_alt.xml\"\n\n# カスケードファイルの読み込み\ncascade = cv2.CascadeClassifier(casceade_file)\n\n# 矩形に変更して表示をリスト化\nface_list = cascade.detectMultiScale(image)\n\n# 顔を囲う枠の色を指定\ncolor = (0, 0, 255)\n\n# 顔を認識した箇所に枠を描画する処理\nif len(face_list) > 0:\n for face in face_list:\n x, y, w, h = face\n cv2.rectangle(image, (x,y), (x+w, y+h), color, thickness=2)\nelse:\n print(\"顔が認識できませんでした。\")\n\n# 顔認識した画像を表示する処理\ncv2.imshow('Frame',image)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"Python_IoT_sample/chapter8/chapter8.1.py","file_name":"chapter8.1.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"172827655","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Philipp Temminghoff\n\"\"\"\n\n\nfrom qtpy import QtCore, QtWidgets\n\nfrom prettyqt import widgets\nfrom prettyqt.utils import bidict\n\nALLOWED_AREAS = bidict(all=QtCore.Qt.AllDockWidgetAreas,\n left=QtCore.Qt.LeftDockWidgetArea,\n right=QtCore.Qt.RightDockWidgetArea,\n top=QtCore.Qt.TopDockWidgetArea,\n bottom=QtCore.Qt.BottomDockWidgetArea)\n\n\nQtWidgets.QDockWidget.__bases__ = (widgets.Widget,)\n\n\nclass DockWidget(QtWidgets.QDockWidget):\n \"\"\"\n Customized DockWidget class\n contains a custom TitleBar with maximise button\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n name = kwargs.pop(\"name\", None)\n title = kwargs.pop(\"title\", None)\n super().__init__(*args, **kwargs)\n if name:\n self.id = name\n if title:\n self.title = title\n self.set_allowed_areas(\"all\")\n\n def set_widget(self, widget):\n self.setWidget(widget)\n\n def set_allowed_areas(self, area):\n self.setAllowedAreas(ALLOWED_AREAS[area])\n\n def setup_title_bar(self):\n title_bar = widgets.Widget()\n layout = widgets.BoxLayout(\"horizontal\")\n layout.set_margin(0)\n layout.set_alignment(\"right\")\n title_bar.set_layout(layout)\n maximise_button = widgets.PushButton()\n layout += maximise_button\n maximise_button.set_style_icon(\"maximise\")\n maximise_button.clicked.connect(self.maximise)\n close_button = widgets.PushButton()\n close_button.set_style_icon(\"close\")\n layout += close_button\n close_button.clicked.connect(self.close)\n self.setTitleBarWidget(title_bar)\n\n def maximise(self):\n if not self.isFloating():\n self.setFloating(True)\n if not self.isMaximized():\n self.showMaximized()\n else:\n self.showMinimized()\n\n\nif __name__ == \"__main__\":\n app = widgets.app()\n win = widgets.MainWindow()\n dock_widget = DockWidget(name=\"aa\", title=\"Test\")\n dock_widget.setup_title_bar()\n win.add_dockwidget(dock_widget, \"left\")\n win.show()\n app.exec_()\n","sub_path":"prettyqt/widgets/dockwidget.py","file_name":"dockwidget.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"110264326","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 4 16:43:12 2019\n\n@author: w\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport datetime\nfrom Data.get_data import read_price\n\ndef mapping(tickers, delta_s, tickers_pl, \\\n init_cash, trans_dates, trans_prices, shares, residual_cashs, \\\n freq='D'): \n #freq: T-trading date, D-Daily, W-Weekly, M-Monthly\n # t=0\n d = delta_s.index[0]\n mapping_date = np.array(d)\n cash = init_cash\n mapping_cash = np.array(cash) \n s = np.zeros(len(tickers))\n mapping_shares = np.array(s) \n c = np.zeros(len(tickers)) \n pre_t_date = delta_s.index[0] + datetime.timedelta(days=-1) \n for e in range(len(tickers)):\n while pre_t_date.date() not in tickers_pl[tickers[e]].index.date:\n pre_t_date = pre_t_date + datetime.timedelta(days=-1)\n p = read_price(pre_t_date, tickers[e], tickers_pl[tickers[e]])\n c[e] = p.Close \n mapping_closes = np.array(c)\n w = np.zeros(len(tickers)) \n mapping_weights = np.array(w)\n v = 0.0\n mapping_value = np.array(v)\n # t>=1\n if freq == 'D':\n start_date = delta_s.index[0]\n end_date = tickers_pl[tickers[0]].index[-1]\n range_date = pd.date_range(start=start_date, end=end_date, freq='D')\n elif freq == 'T':\n range_date = trans_dates\n else:\n range_date = trans_dates\n t = 0\n for d in range_date:\n if datetime.datetime.weekday(d)<=4:\n if d == trans_dates[t]:\n s = shares[t]\n cash = residual_cashs[t]\n if t < len(trans_dates)-1:\n t = t + 1\n mapping_date = np.vstack([mapping_date, d])\n mapping_cash = np.vstack([mapping_cash, cash])\n mapping_shares = np.vstack([mapping_shares, s])\n for e in range(len(tickers)):\n if d.date() in tickers_pl[tickers[e]].index.date:\n p = read_price(d, tickers[e], tickers_pl[tickers[e]])\n c[e] = p.Close\n mapping_closes = np.vstack([mapping_closes, c])\n v = sum(s*c)\n mapping_value = np.vstack([mapping_value, v])\n for e in range(len(tickers)):\n w[e] = s[e]*c[e]/v\n mapping_weights = np.vstack([mapping_weights,w])\n return mapping_date, mapping_shares, mapping_weights, mapping_closes, mapping_cash, mapping_value\n \ndef get_portfolio(tickers, mapping_date, \\\n mapping_closes, mapping_cash, mapping_value):\n portfolio = pd.DataFrame(data=mapping_closes, columns=tickers)\n portfolio['Date'] = mapping_date\n portfolio['Value'] = mapping_value\n portfolio['Cash'] = mapping_cash\n portfolio['NAV'] = portfolio['Value'] + portfolio['Cash']\n portfolio.set_index(\"Date\", inplace=True)\n portfolio = portfolio.drop(['Value', 'Cash'], axis=1)\n return portfolio\n\ndef get_pd(tickers, mapping_date, mapping_data):\n df = pd.DataFrame(data=mapping_data, columns=tickers)\n df['Date'] = mapping_date\n df.set_index(\"Date\", inplace=True)\n return df\n \ndef get_performance(portfolio):\n annual_r = np.zeros(len(portfolio.columns))\n annual_std = np.zeros(len(portfolio.columns))\n total_r = np.zeros(len(portfolio.columns))\n sharpe_ratio = np.zeros(len(portfolio.columns))\n max_loss = np.zeros(len(portfolio.columns))\n for e in range(len(portfolio.columns)):\n p = portfolio[portfolio.columns[e]]\n #r = _calc_r(p)\n total_r[e] = _calc_total_r(p)\n annual_r[e] = _calc_annual_r(p)\n annual_std[e] = _calc_annual_std(p) \n sharpe_ratio[e] = _calc_sharpe_ratio(annual_r[e], annual_std[e])\n max_loss[e] = _calc_max_loss(p)\n return annual_r, annual_std, total_r, sharpe_ratio, max_loss\n \n# return at t \ndef _calc_r(p):\n r = p.pct_change()\n r.fillna(0.0, inplace=True)\n return r\n\n# annual return\ndef _calc_annual_r(p, annual_factor=365):\n total_r = p.iloc[-1] / p.iloc[0] - 1\n days = (p.index[-1] - p.index[0]).days\n annual_r = (1+total_r)**(annual_factor/days) - 1\n return annual_r\n'''\ndef _calc_annual_r(r, annual_factor=360):\n days = (r.index[-1] - r.index[0]).days\n annual_r = (1+r.mean())**(len(r)*annual_factor/days) - 1\n return annual_r\n'''\n\n# annual std\ndef _calc_annual_std(p, annual_factor=365):\n r = p.pct_change()\n r.fillna(0.0, inplace=True)\n days = (p.index[-1] - p.index[0]).days\n r = (1+r)**(len(p)/days) - 1\n annual_std = r.std()*(annual_factor**0.5)\n return annual_std\n'''\ndef _calc_annual_std(r, annual_factor=360):\n days = (r.index[-1] - r.index[0]).days\n annual_std = r.std()*((len(r)*annual_factor/days)**0.5)\n return annual_std\n'''\n\n# total return\ndef _calc_total_r(p):\n total_r = p.iloc[-1] / p.iloc[0] - 1\n return total_r\n\n# sharpe ratio\ndef _calc_sharpe_ratio(annual_r, annual_std, risk_free = 0.0):\n sharpe_ratio = (annual_r-risk_free)/annual_std\n return sharpe_ratio\n\n# max loss\ndef _calc_max_loss(p): \n m = 0.0\n for t in range(1,len(p)):\n d = (min(p[t:len(p)]) / p[t-1]) - 1\n if m>d:\n m=d\n max_loss = m\n return max_loss","sub_path":"Reporting/results.py","file_name":"results.py","file_ext":"py","file_size_in_byte":5173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"341549830","text":"def diviseur(n):\n d=[1]\n for i in range(2,int(n**0.5)):\n if n%i==0:\n d.append(i)\n d.append(n//i)\n return d\n\ndef somme(d):\n sum=0\n for i in d:\n sum+=i\n return sum\n\ndef prob21():\n amicable=[]\n sum1=sum2=0\n for i in range(10000):\n sum1=somme(diviseur(i))\n sum2=somme(diviseur(sum1))\n if sum2==i and sum1!=sum2:\n amicable.append(i)\n return somme(amicable)\n\nprint(prob21())","sub_path":"Project Euler/probleme21.py","file_name":"probleme21.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"336226895","text":"import FWCore.ParameterSet.Config as cms\n\ngeneralAndHiPixelTracks = cms.EDProducer('generalAndHiPixelTracks',\n genTrackSrc = cms.InputTag(\"generalTracks\"),\n pixTrackSrc = cms.InputTag(\"hiConformalPixelTracks\"),\n vertexSrc = cms.InputTag(\"offlinePrimaryVertices\"),\n centralitySrc = cms.InputTag(\"centralityBin\",\"HFtowers\"),\n mvaSrc = cms.InputTag('generalTracks','MVAValues'),\n cutWidth = cms.double(0.2),\n trkRes = cms.double(0.02),\n qualityString = cms.string(\"highPurity\"),\n dxyErrMax = cms.double(3.0),\n dzErrMax = cms.double(3.0),\n ptErrMax = cms.double(0.1),\n nhitsMin = cms.int32(0),\n chi2nMax = cms.double(0.18),\n chi2nMaxPixel = cms.double(9999.0),\n dzErrMaxPixel = cms.double(3.0),\n dxyErrMaxPixel = cms.double(3.0)\n) \n","sub_path":"generalAndHiPixelTracks/python/MergingPixAndGenProducer2022Run_cfi.py","file_name":"MergingPixAndGenProducer2022Run_cfi.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"530915827","text":"from unittest import TestCase\nfrom unittest.mock import MagicMock\nfrom ikcms.forms.validators import *\nfrom ikcms.forms import exceptions\n\n\nclass RequiredTestCase(TestCase):\n def test_is_required(self):\n field = MagicMock()\n field.required = True\n field.required_error = 'Field is required'\n validator = Required(field)\n for value in ['', [], {}, None]:\n with self.assertRaises(exceptions.ValidationError) as ctx:\n validator(value)\n exc = ctx.exception\n self.assertEqual(exc.kwargs['error'], field.required_error)\n\n def test_is_not_required(self):\n field = MagicMock()\n field.required = False\n field.required_error = 'Field is required'\n validator = Required(field)\n for value in ['', [], {}, None]:\n validator(value)\n\n\nclass RegexTestCase(TestCase):\n def test_regex(self):\n field = MagicMock()\n field.regex = r'\\d{4}-\\d{2}-\\d{2}'\n field.regex_error = 'Field does not match regex'\n validator = Regex(field)\n with self.assertRaises(exceptions.ValidationError) as ctx:\n validator('invalid')\n self.assertEqual(ctx.exception.kwargs['error'], field.regex_error)\n validator('2016-06-15')\n\n\nclass LenTestCase(TestCase):\n def test_len(self):\n field = MagicMock()\n field.min_len = 1\n field.max_len = 10\n field.min_len_error = 'Minimum length error'\n field.max_len_error = 'Maximum length error'\n validator = Len(field)\n validator(list(range(1)))\n validator(list(range(5)))\n validator(list(range(10)))\n with self.assertRaises(exceptions.ValidationError) as ctx:\n validator(list(range(0)))\n self.assertEqual(ctx.exception.kwargs['error'], field.min_len_error)\n with self.assertRaises(exceptions.ValidationError) as ctx:\n validator(list(range(11)))\n self.assertEqual(ctx.exception.kwargs['error'], field.max_len_error)\n\n\nclass RangeTestCase(TestCase):\n def test_range(self):\n field = MagicMock()\n field.min_value = 1\n field.max_value = 10\n field.min_value_error = 'Minimum value error'\n field.max_value_error = 'Maximum value error'\n validator = Range(field)\n validator(1)\n validator(5)\n validator(10)\n with self.assertRaises(exceptions.ValidationError) as ctx:\n validator(0)\n self.assertEqual(ctx.exception.kwargs['error'], field.min_value_error)\n with self.assertRaises(exceptions.ValidationError) as ctx:\n validator(11)\n self.assertEqual(ctx.exception.kwargs['error'], field.max_value_error)\n","sub_path":"tests/ikcms/forms/test_validators.py","file_name":"test_validators.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"574312998","text":"\"\"\"\nThe Python standard library's 'calendar' module allows you to \nrender a calendar to your terminal.\nhttps://docs.python.org/3.6/library/calendar.html\n\nWrite a program that accepts user input of the form\n `calendar.py month [year]`\nand does the following:\n - If the user doesn't specify any input, your program should \n print the calendar for the current month. The 'datetime'\n module may be helpful for this.\n - If the user specifies one argument, assume they passed in a\n month and render the calendar for that month of the current year.\n - If the user specifies two arguments, assume they passed in\n both the month and the year. Render the calendar for that \n month and year.\n - Otherwise, print a usage statement to the terminal indicating\n the format that your program expects arguments to be given.\n Then exit the program.\n\"\"\"\n\nimport sys\nimport calendar\nfrom datetime import datetime\n\n\ndate = datetime.now()\n\ncal = input(\"Choose a month number from 1-12 then add a space \\\n and ,if you would like, then choose a year --e.g-- 4 1992: \")\ncal = cal.split()\n\nif len(cal) == 0:\n print(calendar.month(date.year, date.month))\nelif len(cal) == 1 and (int(cal[0]) <= 12):\n month = int(cal[0])\n print(calendar.month(date.year, month))\nelif len(cal) == 2 and (int(cal[0]) <= 12) and (len(cal[1]) == 4):\n month, year = (int(x) for x in cal)\n print(calendar.month(year, month))\nelse:\n print('Please enter the month in the form of 1 - 12 and, if you like, then the year in the form of YYYY.')","sub_path":"src/14_cal.py","file_name":"14_cal.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"530210894","text":"'''\n Copyright (C) 2019 Stefan V. Pantazi (svpantazi@gmail.com) \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 http://www.gnu.org/licenses/.\n'''\nfrom pymongo import MongoClient\nfrom pymongo.errors import ConnectionFailure,AutoReconnect\nimport gridfs\n\nclass MiniEMRMongo:\n client=None\n db=None\n\n @classmethod\n def connect(cls,uri=\"mongodb://127.0.0.1:27017\"):\n #Connect to MongoDB\n cls.client = MongoClient(uri)\n try:\n #cls.client.admin.command('ismaster')\n #cls.client.admin.command('serverStatus')\n cls.db=cls.client.mini_emr\n print('Connected to MongoDb server')\n except AutoReconnect:\n print(\"Reconnecting server not available\")\n except ConnectionFailure:\n print(\"MongoDb server not available\")\n\n @classmethod\n def disconnect(cls):\n #clear database object\n cls.client.close()\n cls.db=None \n print('Disconnected from MongoDb server')\n\n @classmethod\n def uploadGridFSFile(cls,fname,**kwargs1):\n fs = gridfs.GridFS(cls.db)\n if fs.exists(filename=fname): \n print(\"GridFS file exists:\",fname)\n else:\n f=open(fname,\"br\") #b - for binary file! \n with fs.new_file(filename=fname,kwargs=kwargs1) as new_gridfs_file: \n new_gridfs_file.write(f)\n oid=new_gridfs_file._id\n new_gridfs_file.close() \n f.close() \n return oid\n\n @classmethod\n def downloadGridFSFile(cls,fileOId):\n fs = gridfs.GridFS(cls.db)\n with fs.get(fileOId) as gridfs_file:\n print('Found gridfs file to download ',gridfs_file._id) \n file_data=gridfs_file.read()\n gridfs_file.close()\n return file_data\n","sub_path":"jon_p1/modINFO74000/emr_db.py","file_name":"emr_db.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"594847245","text":"import sys\ninput = sys.stdin.readline\n\n\ndef manacher(string):\n n = len(string)\n a = [0] * n # i번째 문자를 중심으로 하는 가장 긴 팰린드롬 반지름 크기.\n c = 0 # 중심점(center) 초기화\n r = 0 # 시작점에서 가장 먼 반경(펠린드롬 끝나는 인덱스중 가장 큰 값.)\n \n for now in range(n):\n # i번째 문자가 now 아래쪽에 있는 문자를 중심으로 하는 팰린드롬 범위 밖의 문자라는 뜻.\n # 때문에 now 이전에 얻은 정보를 재활용하지 못하고 i를 기준으로 초기화시켜 재계산함.\n if r < now:\n a[now] = 0\n # i번째 문자가 i미만의 문자를 중심으로 하는 팰린드롬에 속한다면?\n # 1. i를 중심으로 하는 가장 긴 팰린드롬이 기존 최장 팰린드롬인 c를 중심으로 하는 가장 긴 팰린드롬에 완전히 속하는 경우 -> i의 c점에 대한 대칭점 now'을 기준으로 하는 펠린드롬은 i를 기준으로 하는 팰린드롬과 완전한 대칭. a[now]=a[now']인데 p[now']은 이전에 구해놓았기 때문에 연산 안해도됨.\n # 2. i를 중심으로 하는 가장 긴 팰린드롬이 c를 중심으로 한느 가장 긴 팰린드롬에 일부만 포함된느 경우 -> 초기 반지름 a[now] = ((c+a[c])-now)가 보장이됨(가장 긴 펠린드롬의 오른쪽 한계로부터 i만큼 왼쪽으로 줄인 반지름에서 (c+a[c])-now+1부터 비교 시작)\n # 3. i를 중심으로 한느 가장 긴 팰린드롬이 c < i인 c를 중심으로 하는 가장 긴 팰린드롬과 겹치는 경우. (c의 날개와 i의 날개가 동일지점인 경우)\n # 역시 case 2처럼 a[now] = ((c+a[c])-now)만큼의 반지름이 보장이 됨. 그 이후로 부터 비교하면 됨. now'은 (2*c)-i이므로 now'의 날개와 r-i값중 더 작은 곳을 보장받고 움직이면 됨.\n else:\n a[now] = min(a[(2*c) - now], r - now)\n\n # i번째 인덱스 기준 가장 긴 펠린드롬 반지름을 펼쳤을 시 0~len(s)의 범위 안에 존재해야하며\n # i기준 a[now](반지름)만큼 펼친 그 양옆문자도 같으면?(-1.+1인덱스가 같으면)\n # a[now]+1(반지름 확장)\n while(now-a[now]-1>=0 and now+a[now]+1 < n and string[now-a[now]-1] == string[now+a[now]+1]):\n a[now] = a[now] + 1\n # 시작점에서 가장 먼 반경인 now + a[now]가 기존 최장 반지름 길이 r보다 크므로\n # r초기화, 중심점 c는 현재 최장 펠린드롬의 중심점인 i로 초기화.\n # 결국 r,c는 현 시점에서 가장 먼 팰린드롬의 날개값(가장 멀리갈때 초기화됨.)\n # a[now]가 0이어도 r보다 i가 커지면 갱신됨.\n if (r < now + a[now]):\n r = now + a[now]\n c = now\n return max(a)\n\ns = input().rstrip()\nprint(manacher('#' + '#'.join(s)+'#'))","sub_path":"13275가장 긴 팰린드롬 부분 문자열.py.py","file_name":"13275가장 긴 팰린드롬 부분 문자열.py.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"169564492","text":"import chess\nimport math\ninf = math.inf\n'''\nConventions used:\nturn - 1 implies white, 0 implies black -- board.turn \ngamePhase - 0 opening, 1 middlegame, 2 endgame\n'''\n\nmaterial_values = {\n chess.PAWN: 1,\n chess.KNIGHT: 3,\n chess.BISHOP: 3.5,\n chess.ROOK: 5,\n chess.QUEEN: 9,\n chess.KING: 50\n}\n\npieceSquareWhitePawn = [\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0.05, 0.05, 0.1, -0.2, -0.2, 0.1, 0.1, 0.05,\n 0.05, 0.05, -0.2, 0, 0, -0.1, 0.025, 0.05,\n 0, -0.1, 0, 0.2, 0.2, 0.1, -0.1, 0,\n 0.05, 0.05, 0.1, 0.25, 0.25, 0.1, 0.05, 0.05,\n 0.1, 0.1, 0.2, 0.3, 0.3, 0.2, 0.1, 0.1,\n 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5,\n 0, 0, 0, 0, 0, 0, 0, 0 \n]\npieceSquareWhiteKnight = [\n -0.5, -0.4, -0.3, -0.3, -0.3, -0.3, -0.4, -0.5,\n -0.4, -0.2, 0, 0, 0, 0, -0.2, -0.4,\n -0.3, 0, 0.1, 0.15, 0.15, 0.1, 0, -0.3,\n -0.3, 0.05, 0.15, 0.2, 0.2, 0.15, 0.05, -0.3, \n -0.3, 0, 0.15, 0.2, 0.2, 0.15, 0, -0.3,\n -0.3, 0.05, 0.10, 0.15, 0.15, 0.10, 0.05, -0.3,\n -0.4, -0.2, 0, 0.05, 0.05, 0, -0.2, -0.4,\n -0.5, -0.4, -0.3, -0.3, -0.3, -0.3, -0.4, -0.5\n]\n\npieceSquareWhiteBishop = [\n -0.2, -0.1, -0.1, -0.1, -0.1, -0.1, -0.1, -0.2,\n -0.1, 0.05, 0, 0, 0, 0, 0.05, -0.1,\n -0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, -0.1,\n -0.1, 0, 0.1, 0.1, 0.1, 0.1, 0, -0.1,\n -0.1, 0.05, 0.05, 0.1, 0.1, 0.05, 0.05, -0.1,\n -0.1, 0, 0.05, 0.1, 0.1, 0.05, 0, -0.1,\n -0.1, 0, 0, 0, 0, 0, 0, -0.1,\n -0.2, -0.1, -0.1, -0.1, -0.1, -0.1, -0.1, -0.2\n]\npieceSquareWhiteRook = [\n 0, 0, 0, 0.05, 0.05, 0, 0, 0,\n -0.05, 0, 0, 0, 0, 0, 0, -0.05,\n -0.05, 0, 0, 0, 0, 0, 0, -0.05,\n -0.05, 0, 0, 0, 0, 0, 0, -0.05,\n -0.05, 0, 0, 0, 0, 0, 0, -0.05,\n -0.05, 0, 0, 0, 0, 0, 0, -0.05,\n -0.05, 0, 0, 0, 0, 0, 0, -0.05,\n 0.05, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.05\n]\n\npieceSquareWhiteQueen = [\n -0.2, -0.1, -0.1, -0.05, -0.05, -0.1, -0.1, -0.2,\n -0.1, 0, 0, 0, 0, 0, 0, -0.1,\n -0.1, 0, 0.05, 0.05, 0.05, 0.05, 0, -0.1,\n -0.05, 0, 0.05, 0.05, 0.05, 0.05, 0, -0.05,\n 0, 0, 0.05, 0.05, 0.05, 0.05, 0, -0.05,\n -0.1, 0.05, 0.05, 0.05, 0.05, 0.05, 0, -0.1,\n -0.1, 0, 0.05, 0, 0, 0, 0, -0.1,\n -0.2, -0.1, -0.1, -0.05, -0.05, -0.1, -0.1, -0.2 \n]\n\npieceSquareWhiteKing = [\n 0.2, 0.3, 0.1, 0, 0, 0.1, 0.3, 0.2,\n 0.2, 0.2, 0, 0, 0, 0, 0.2, 0.2,\n -0.1, -0.2, -0.2, -0.2, -0.2, -0.2, -0.2, -0.1,\n -0.2, -0.3, -0.3, -0.4, -0.4, -0.3, -0.3, -0.2,\n -0.3, -0.4, -0.4, -0.5, -0.5, -0.4, -0.4, -0.3,\n -0.3, -0.4, -0.4, -0.5, -0.5, -0.4, -0.4, -0.3,\n -0.3, -0.4, -0.4, -0.5, -0.5, -0.4, -0.4, -0.3,\n -0.3, -0.4, -0.4, -0.5, -0.5, -0.4, -0.4, -0.3\n]\n\npieceSquareBlackPawn = list(reversed(pieceSquareWhitePawn))\npieceSquareBlackKnight = list(reversed(pieceSquareWhiteKnight))\npieceSquareBlackBishop = list(reversed(pieceSquareWhiteBishop))\npieceSquareBlackRook = list(reversed(pieceSquareWhiteRook))\npieceSquareBlackQueen = list(reversed(pieceSquareWhiteQueen))\npieceSquareBlackKing = list(reversed(pieceSquareWhiteKing))\n\n\ndef pieceSquareValue(square, piece, gamePhase):\n if piece.piece_type == chess.PAWN:\n if piece.color == chess.WHITE:\n return pieceSquareWhitePawn[square]\n else:\n return pieceSquareBlackPawn[square]\n elif piece.piece_type == chess.BISHOP:\n if piece.color == chess.WHITE:\n return pieceSquareWhiteBishop[square]\n else:\n return pieceSquareBlackBishop[square]\n elif piece.piece_type == chess.KNIGHT:\n if piece.color == chess.WHITE:\n return pieceSquareWhiteKnight[square]\n else:\n return pieceSquareBlackKnight[square]\n elif piece.piece_type == chess.ROOK:\n if piece.color == chess.WHITE:\n return pieceSquareWhiteRook[square]\n else:\n return pieceSquareBlackRook[square]\n elif piece.piece_type == chess.QUEEN:\n if piece.color == chess.WHITE:\n return pieceSquareWhiteQueen[square]\n else:\n return pieceSquareBlackQueen[square]\n else:\n if piece.color == chess.WHITE:\n return pieceSquareWhiteKing[square]\n else:\n return pieceSquareBlackKing[square]\n\n\ndef pieceCount(board):\n #(p, P, n, N, b, B, r, R, q, Q) \n count = (0,0,0,0,0,0,0,0,0,0)\n for square in chess.SQUARES:\n piece = board.piece_at(square)\n return count\ndef evaluateMaterial(board):\n if(board.is_game_over()):\n if board.outcome().result() == \"1-0\":\n return (inf)\n elif board.outcome().result() == \"0-1\":\n return -(inf)\n else:\n return 0\n white_eval, black_eval = (0.0, 0.0)\n for square in chess.SQUARES:\n piece = board.piece_at(square)\n #print(square)\n if(not(piece is None)):\n if piece.color == chess.WHITE:\n white_eval+= (material_values[piece.piece_type]+pieceSquareValue(square, piece, 0))\n else:\n black_eval+=(material_values[piece.piece_type]+pieceSquareValue(square, piece, 0))\n return white_eval - black_eval\n\n\ndef eval(board):\n white_eval = 0\n black_eval = 0\n return evaluateMaterial(board)\n\ndef bestMoveOrder(board: chess.Board):\n legalMoves = (board.legal_moves)\n def comparator(move):\n board.push(move)\n evaluation = eval(board)\n board.pop()\n return evaluation\n bestMoves = sorted(legalMoves, key = comparator, reverse = board.turn==chess.WHITE)\n return list(bestMoves)\n\ndef alphaBetaPruning(board:chess.Board, depth, alpha=(-inf), beta=(+inf)):\n turn = board.turn\n if(board.is_game_over()):\n if board.outcome().result() == \"1-0\":\n return (inf)\n elif board.outcome().result() == \"0-1\":\n return -(inf)\n else:\n return 0\n if(depth == 0):\n return eval(board)\n \n if(turn):\n legal = bestMoveOrder(board)\n max_eval = -(inf)\n for move in legal:\n board.push(move)\n max_eval = max(max_eval, alphaBetaPruning(board, depth-1, alpha, beta))\n board.pop()\n if max_eval >=alpha:\n alpha = max_eval\n if beta <=alpha:\n return max_eval\n return max_eval\n else:\n legal = bestMoveOrder(board)\n min_eval = (inf)\n for move in legal:\n board.push(move)\n min_eval = min(min_eval, alphaBetaPruning(board, depth-1, alpha, beta))\n board.pop()\n if min_eval <= beta:\n beta = min_eval\n if beta <=alpha:\n return min_eval\n return min_eval\n\ndef search(depth, board):\n turn = board.turn\n if turn:\n best_eval = -(inf)\n else:\n best_eval = (inf)\n legal = bestMoveOrder(board)\n best_move = legal[0]\n #print(\"at depth \" + str(depth) + \", \" + str(legal))\n for move in legal:\n board.push(move)\n current_eval = alphaBetaPruning(board, depth-1)\n board.pop()\n if((turn and best_eval<=current_eval) or (not turn and best_eval>=current_eval)):\n best_eval = current_eval\n best_move = move\n return (best_move, best_eval)\n\n","sub_path":"main_v1.py","file_name":"main_v1.py","file_ext":"py","file_size_in_byte":7136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"63517594","text":"import hashlib\nimport time\nfrom test_module.db.r_db import db\n\n\nclass Auth(object):\n def __init__(self):\n\n self.user = 'a'\n self.pswd = 'a'\n\n def login(self, user, pswd):\n if user == self.user and pswd == self.pswd:\n #user = db_get_user\n hash = hashlib.md5(str(time.time()).encode()).hexdigest()\n db.set('session:' + hash, user)\n db.expire('session:' + hash, 60)\n return hash\n else:\n time.sleep(1)\n return None\n\n def check(self, hash):\n user = db.get('session:' + hash)\n t = time.time()\n if not user:\n return False\n # elif t > session['time']:\n # return False\n else:\n db.expire('session:' + hash, 600)\n return user\n\n def logout(self, hash):\n pass\n\n\nauth = Auth()\n","sub_path":"test_module/auth/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"343309963","text":"import errno\nimport logging\nimport os\nimport platform\n\nlogger = logging.getLogger(__name__)\n\n\nclass System:\n @staticmethod\n def hardlink(source, link_name):\n os.link(source, link_name)\n\n @staticmethod\n def symlink(source, link_name):\n os.symlink(source, link_name)\n\n @staticmethod\n def _reflink_darwin(src, dst):\n import ctypes\n\n def _cdll(name):\n return ctypes.CDLL(name, use_errno=True)\n\n LIBC = \"libc.dylib\"\n LIBC_FALLBACK = \"/usr/lib/libSystem.dylib\"\n try:\n clib = _cdll(LIBC)\n except OSError as exc:\n logger.debug(\n \"unable to access '{}' (errno '{}'). \"\n \"Falling back to '{}'.\".format(LIBC, exc.errno, LIBC_FALLBACK)\n )\n if exc.errno != errno.ENOENT:\n raise\n # NOTE: trying to bypass System Integrity Protection (SIP)\n clib = _cdll(LIBC_FALLBACK)\n\n if not hasattr(clib, \"clonefile\"):\n raise OSError(\n errno.ENOTSUP,\n \"'clonefile' not supported by the standard library\",\n )\n\n clonefile = clib.clonefile\n clonefile.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int]\n clonefile.restype = ctypes.c_int\n\n ret = clonefile(\n ctypes.c_char_p(os.fsencode(src)),\n ctypes.c_char_p(os.fsencode(dst)),\n ctypes.c_int(0),\n )\n if ret:\n err = ctypes.get_errno()\n msg = os.strerror(err)\n raise OSError(err, msg)\n\n @staticmethod\n def _reflink_linux(src, dst):\n import fcntl # pylint: disable=import-error\n\n from funcy import suppress\n\n FICLONE = 0x40049409\n\n try:\n with open(src, \"rb\") as s, open(dst, \"wb+\") as d:\n fcntl.ioctl(d.fileno(), FICLONE, s.fileno())\n except OSError:\n with suppress(OSError):\n os.unlink(dst)\n raise\n\n @staticmethod\n def reflink(source, link_name):\n from dvc.utils.fs import umask\n\n source, link_name = os.fspath(source), os.fspath(link_name)\n\n system = platform.system()\n if system == \"Darwin\":\n System._reflink_darwin(source, link_name)\n elif system == \"Linux\":\n System._reflink_linux(source, link_name)\n else:\n raise OSError(\n errno.ENOTSUP,\n f\"reflink is not supported on '{system}'\",\n )\n\n # NOTE: reflink has a new inode, but has the same mode as the src,\n # so we need to chmod it to look like a normal copy.\n os.chmod(link_name, 0o666 & ~umask)\n\n @staticmethod\n def inode(path):\n return os.lstat(path).st_ino\n\n @staticmethod\n def is_symlink(path):\n return os.path.islink(path)\n\n @staticmethod\n def is_hardlink(path):\n return os.stat(path).st_nlink > 1\n","sub_path":"dvc/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":2932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"285333588","text":"'''\nrefer to:\nhttps://www.jb51.net/article/135366.htm\nhttps://blog.csdn.net/zhangziju/article/details/79754652\nhttps://www.jianshu.com/p/ed57ee1056ab\nhttps://segmentfault.com/a/1190000015735549\n\n> python card/sift.py data/1.jpg && see warp.jpg\n'''\n\nimport cv2,numpy\nimport numpy as np\nfrom PIL import Image, ImageDraw, ImageFont\nfrom sklearn.cluster import DBSCAN\n\ncard_template_image_path=\"card.jpg\"\nimg_tpl = cv2.imread(card_template_image_path)\nH,W,_ = img_tpl.shape\nprint(\"加载模板身份证:宽{},高{}\".format(W,H))\n\nkey_pos={\n\t'姓':[[45,60],[65,75]],\n\t'名':[[80,60],[95,75]],\n\t'性':[[45,107],[63,123]],\n\t'别':[[78,109],[96,126]],\n\t'民':[[191,109],[205,125]],\n\t'族':[[222,109],[238,126]],\n\t'出':[[46,156],[62,173]],\n\t'生':[[78,158],[95,174]],\n\t'年':[[189,157],[204,173]],\n\t'月':[[253,156],[264,172]],\n\t'日':[[310,155],[325,175]],\n\t'住':[[45,210],[65,225]],\n\t'址':[[79,208],[96,225]],\n\t'公':[[47,335],[65,354]],\n\t'民':[[70,335],[87,350]],\n\t'身':[[91,335],[105,350]],\n\t'份':[[111,335],[151,350]],\n\t'证':[[132,335],[170,350]],\n\t'号':[[156,335],[190,350]],\n\t'左上':[[0,0],[20,20]],\n\t'右上':[[615,0],[635,20]],\n\t'左下':[[0,379],[20,399]],\n\t'右上':[[615,379],[635,399]]\n}\n\ndef distance(pt1,pt2):\n\tdelta_x = pt1[0] - pt2[0]\n\tdelta_y = pt1[1] - pt2[1]\n\treturn np.sqrt(delta_x*delta_x + delta_y*delta_y)\n\n# 中心(重心)函数\ndef center(points):\n\tx_coords = [p[0] for p in points]\n\ty_coords = [p[1] for p in points]\n\t_len = len(points)\n\tcentroid_x = sum(x_coords)/_len\n\tcentroid_y = sum(y_coords)/_len\n\treturn (int(centroid_x), int(centroid_y))\n\n# 过滤匹配点,source点必须要在这些mark的范围之内\ndef filter(p):\n\n\t# 遍历所有的关键点\n\tfor i, (k, v) in enumerate(key_pos.items()):\n\t\t# 如果关键点在我们规定的范围之内,我们就找到一个\n\t\tif v[0][0] < p[0] and p[0] < v[1][0] and \\\n\t\t v[0][1] < p[1] and p[1] < v[1][1]:\n\n\t\t\tprint(\"关键点匹配:\",k)\n\t\t\treturn True,k\n\n\treturn False,None\n\n# 过滤掉不在一块的点\ndef filter_dbscan(points):\n\tdbscan = DBSCAN(eps=20,min_samples=5) \t# eps是半径,min_samples是最少几个点\n\tlabels = dbscan.fit_predict(points)\t\t# 得到的是[0 1 1 0 -1 -1 2 2]是分类,-1是异常点把\n\tprint(\"dbscan 聚类结果:\",labels)\n\treturn [points[i] for i in labels if i != -1] # 我觉得,0是最近的一类???\n\n\t# # 找出最大的一类\n\t# clazz = set(labels)\n\t# found_cls = -100\n\t# max_num = 0\n\t# for cls in clazz:\n\t# \tcount = sum(1 for c in labels if c==cls)\n\t# \tprint(cls,\":\",count)\n\t# \tif count>max_num:\n\t# \t\tfound_cls = cls\n\t# \t\tmax_num = count\n\t# print(\"最大类别是:\",found_cls)\n #\n\t# # 不是最大的类,都挑出来准备删除\n\t# deleted_points = [points[i] for i in labels if i!=found_cls ]\n #\n\t# # 彻底删除\n\t# print(\"要删除的点\",deleted_points)\n\t# for dp in deleted_points:\n\t# \tif dp in points: points.remove(dp)\n\t# print(\"00000000000000\")\n\t# print(points)\n\ndef parse(dst_image_path):\n\tsift = cv2.xfeatures2d.SIFT_create()\n\t\n\tgray_tpl= cv2.cvtColor(img_tpl,cv2.COLOR_BGR2GRAY)\n\tkp_tpl, des_tpl = sift.detectAndCompute(gray_tpl, None) # des是描述子\n\n\t# 目标图片\n\timg_dst = cv2.imread(dst_image_path)\n\timg_origin = img_dst.copy()\n\tgray_dst= cv2.cvtColor(img_dst,cv2.COLOR_BGR2GRAY)\n\tkp_dst, des_dst = sift.detectAndCompute(gray_dst, None) # des是描述子\n\n\t# BFMatcher解决匹配\n\t# bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n\t# matches = bf.match(des_tpl, des_dst)\n\n\t# Brute-Force匹配非常简单,首先在第一幅图像中选取一个关键点然后依次与第二幅图像的每个关键点进行(描述符)距离测试,最后返回距离最近的关键点.\n\t# (https://segmentfault.com/a/1190000015735549)\n\tbf = cv2.BFMatcher()#normType=None,crossCheck=True)\n\t# BFMatcher.match()和BFMatcher.knnMatch(), 第一个返回最佳匹配, 第二种方法返回k个最佳匹配,其中k由用户指定.\n\tmatches = bf.knnMatch(des_tpl, des_dst, k=2)\n\tprint(\"一个匹配点数:\", len(matches))\n\t# matches = sorted(matches, key=lambda x: x[0].distance)\n\t# matches = matches[:10]\n\t# 调整ratio\n\n\tgood = []\n\tstat = {}\n\tpoints=[]\n\t# 返回的match的2个点,如果2个点差不多近,才确定这个点,不知道为何要这样做\n\tfor m, n in matches: # m我觉得是k=2导致的,反回了俩\n\t\tif m.distance < 0.8 * n.distance:\n\t\t\ti = m.queryIdx # queryIdx是目标图点\n\t\t\tj = m.trainIdx # trainIdx是模板图点\n\t\t\ttpl_pt = kp_tpl[i].pt\n\t\t\tdst_pt = (int(kp_dst[j].pt[0]),int(kp_dst[j].pt[1]))\n\t\t\tok,word = filter(tpl_pt)\n\t\t\tif ok:\n\t\t\t\tgood.append([m])\n\t\t\t\tif stat.get(word,None) is None: stat[word]={'points':[],'center':None}\n\t\t\t\tstat[word]['points'].append(dst_pt)\n\t\t\t\tpoints.append(dst_pt)\n\n\tfiltered_points = points#filter_dbscan(points)\n\n\tcenter_point = center(filtered_points)\n\n\timg3 = cv2.drawMatchesKnn(img_tpl, kp_tpl, img_dst, kp_dst, good, None, flags=2)\n\tcv2.imwrite(\"debug/sift.jpg\",img3)\n\n\tprint(filtered_points)\n\tfor p in filtered_points: cv2.circle(img_origin,p,radius=2,color=(255,0,0),thickness=-1)\n\tcv2.circle(img_origin,center_point,radius=300,color=(0,0,255),thickness=3)\n\tcv2.imwrite(\"debug/center.jpg\",img_origin)\n\nif __name__==\"__main__\":\n\timport sys,os\n\n\timagePath = sys.argv[1]\n\tif not os.path.exists(imagePath):print(\"图片不存在\")\n\n\tparse(imagePath)","sub_path":"card/sift2.py","file_name":"sift2.py","file_ext":"py","file_size_in_byte":5308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"16319221","text":"import os\nfrom firebase.firebase import FirebaseAuthentication\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_bcrypt import Bcrypt\nfrom flask_wtf.csrf import CSRFProtect\nfrom flask import Flask\nfrom flask_login import LoginManager, UserMixin\nfrom firebase import firebase\n\napp = Flask(__name__) # Create flask application\napp.config['SECRET_KEY'] = str(os.environ.get('FLASK_SECRET_KEY')) # Set secret key\napp.config['SQLALCHEMY_DATABASE_URI'] = str(os.environ.get('SQLITE_URL')) # Set SQLite database url\nfirebase = firebase.FirebaseApplication(str(os.environ.get('FIREBASE_URL'))) # Connect to firebase\nauthentication = FirebaseAuthentication(str(os.environ.get('DATABASE_SECRET')),\n str(os.environ.get('APP_ACCOUNT')),\n extra={'uid': str(os.environ.get('USER_ID'))}) # Authenticate to firebase\nfirebase.authentication = authentication # Initialize authentication\ndb = SQLAlchemy(app) # Initialize SQLAlchemy for managing SQLite database\nbcrypt = Bcrypt(app) # Initialize Bcrypt module. Used for password hashing\nlogin_manager = LoginManager() # Create LoginManager instance\nlogin_manager.init_app(app) # Initialize LoginManager. Used for managing user authentication\ncsrf = CSRFProtect(app) # Initialize CSRF protection\n\n\nclass Users(UserMixin, db.Model):\n # Create database table\n id = db.Column(db.Integer, primary_key=True) # Primary key\n username = db.Column(db.String(50), unique=True, nullable=False) # Username field\n password = db.Column(db.String(80), nullable=False) # Password field\n admin_role = db.Column(db.Boolean,\n default=False) # Field for admin role. If it is set on TRUE, the corresponding account has admin rights\n\n\n@login_manager.user_loader\ndef load_user(id):\n \"\"\"This function is required by LoginManager module and returns user identified by id\"\"\"\n return Users.query.get(int(id))\n\n\nfrom Implementation.accounts import accounts\nfrom Implementation.controls import controls\nfrom Implementation.main import main\n\napp.register_blueprint(accounts) # Include accounts blueprint\napp.register_blueprint(controls) # Include controls blueprint\napp.register_blueprint(main) # Include main blueprint\n\nif __name__ == \"__main__\":\n app.run(debug=True) # Start application\n","sub_path":"Cod/WebApplication/Implementation/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"176027677","text":"'''\nGiven an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.\n\nExample 1:\n\nInput: intervals = [[1,3],[2,6],[8,10],[15,18]]\nOutput: [[1,6],[8,10],[15,18]]\nExplanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].\nExample 2:\n\nInput: intervals = [[1,4],[4,5]]\nOutput: [[1,5]]\nExplanation: Intervals [1,4] and [4,5] are considered overlapping.\n \n\nConstraints:\n\n1 <= intervals.length <= 104\nintervals[i].length == 2\n0 <= starti <= endi <= 104\n'''\n\nfrom typing import List\nimport unittest\n\ndef merge_intervals(intervals:List[List[int]]) -> List[List[int]]:\n if intervals is None or len(intervals) < 2:\n return intervals\n sorted_intervals = sorted(intervals)\n result = []\n curr = sorted_intervals[0]\n for i in range(1, len(sorted_intervals)):\n interval = sorted_intervals[i]\n if interval[0] <= curr[1]:\n curr[1] = max(curr[1], interval[1])\n else:\n result.append(curr)\n curr = interval\n\n result.append(curr)\n return result\n\nclass Tests(unittest.TestCase):\n def test_ex1(self):\n intervals = [[1,3],[2,6],[8,10],[15,18]]\n result = merge_intervals(intervals)\n self.assertEqual([[1,6],[8,10],[15,18]], result)\n\nif __name__ == \"__main__\":\n unittest.main(verbosity = 2)","sub_path":"sorting/merge_interval.py","file_name":"merge_interval.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"298511630","text":"#!/usr/bin/env python3\n\n\"\"\"\nIn this example, we are given an array of numbers.\nThe task is to find the largest product of 3 numbers.\n\"\"\"\n\ndef largest_product_3(array):\n\n bottom_2 = [float(\"inf\")] * 2\n top_3 = [float(\"-inf\")] * 3\n\n for integer in array:\n if integer < bottom_2[1]:\n bottom_2.append(integer).sort().pop()\n if integer > top_3[0]:\n top_3.append(integer).sort().pop(0)\n\n smallest = bottom_2[0]\n smallest_2nd = bottom_2[1]\n\n largest = top_3[2]\n largest_2nd = top_3[1]\n largest_3rd = top_3[0]\n \n return max(largest*smallest*smallest_2nd, largest*largest_2nd*largest_3rd)\n","sub_path":"python/udemy_python1/largest_product_3.py","file_name":"largest_product_3.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"293752868","text":"# This is a region plugin for Galaxy Charts and New Frontier, created by the System Plugin Creator Tool\n\n########## GENERAL REGION INFORMATION ##########\n\nName = \"DS9FX Kurill\"\nControllingEmpire = \"Dominion\"\nSectorNumber = 469\nImagePath = \"\"\nType = \"Single\"\nLocation = [-41200, -28000]\nOnlyInQB = 0\nOnlyMult = 0\nIgnoreRDF = 1\nSystemsFiles = [\"Systems.DS9FXKurill.DS9FXKurill1\"]\nDescription = \"A Star - System. Some rumors say it would be the homeworld of the Vorta.\"\n","sub_path":"scripts/Custom/Systems/Regions/DS9FXKurill.py","file_name":"DS9FXKurill.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"36963304","text":"# tasks.py\nimport time\nfrom pyats.easypy import Task\n\n\ndef new_task(runtime, duration):\n return Task(testscript='arguments.py', runtime=runtime, duration=duration, interval=10)\n\n\ndef main(runtime):\n long_task = new_task(runtime, 30)\n tasks = [new_task(runtime, duration) for duration in range(0, 100, 10)]\n long_task.start()\n long_task.join()\n # start tasks in parallel\n for task in tasks:\n task.start()\n # wait for completion\n for task in tasks:\n if task.is_alive():\n task.wait()\n","sub_path":"training/pyats02/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"427882810","text":"from EREDef import ERE\nfrom Symbol import Symbol\nfrom Empty import Empty\n\n\nclass FSM:\n contents = {}\n match = set()\n\n\n @staticmethod\n def getFSM(input, events):\n return FSM(input, events)\n\n def __init__(self, input, events):\n self.start = input\n FSM.contents = {}\n FSM.match = set([])\n self.events = events\n self.number = {}\n self.count = 0\n self.generate(self.start)\n\n def generate(self, state):\n #recursively parse out state machines\n self.number[state] = \"s\" + str(self.count)\n self.count = self.count + 1\n trans = {}\n if state.containsEpsilon():\n self.match.add(state)\n self.contents[state] = trans\n for event in self.events:\n next = state.derive(event)\n if(next == Empty.getERE()):\n continue\n trans[event] = next\n if next in self.contents:\n continue\n self.generate(next)\n\n\n def printOut(self):\n print(\"s0 [\")\n self.printTransition(self.contents[self.start])\n print(\"]\")\n for state in self.contents:\n if state == self.start:\n continue\n print(self.number[state]+ \" [\")\n self.printTransition(self.contents[state])\n print(\"]\")\n if len(self.match) == 0:\n return\n print(\"alias match = \")\n for state in self.match:\n print(self.number[state] + \" \")\n print(\"end of matching states\")\n def printTransition(self, trans):\n for s in trans:\n print(\" \" + s.toString() + \" -> \" + self.number[trans[s]])","sub_path":"EREMachine/FSM.py","file_name":"FSM.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"9463894","text":"### programm to read the contents of recipe DATABA\nimport sqlite3\n\nrecipe_database = \"schoenegge_rezepte.db\"\n\ndef RecipeAmount():\n try:\n sqliteConnection = sqlite3.connect(recipe_database)\n cursor = sqliteConnection.cursor()\n\n cursor.execute(\"SELECT count(recipe_id) FROM sources_table\")\n recipe_amount = cursor.fetchone()[0]\n except sqlite3.Error as error:\n print(\"Error:\", error)\n finally:\n if (sqliteConnection):\n sqliteConnection.close()\n return recipe_amount\n\ndef RecipeNames():\n try:\n sqliteConnection = sqlite3.connect(recipe_database)\n cursor = sqliteConnection.cursor()\n\n cursor.execute(\"SELECT * FROM sources_table\")\n list = cursor.fetchall()\n except sqlite3.Error as error:\n print(\"Error:\", error)\n finally:\n if (sqliteConnection):\n sqliteConnection.close()\n return list\ndef showRecipe(id):\n try:\n sqliteConnection = sqlite3.connect(recipe_database)\n cursor = sqliteConnection.cursor()\n\n query = \"SELECT * FROM recipes_table WHERE recipe_id =?\"\n cursor.execute(query, [id])\n recipe_raw = cursor.fetchall()\n #print(recipe_raw)\n for line in recipe_raw:\n amount = None\n unit = None\n ingredient = None\n\n amount = line[0]\n #print(type(line[1]))\n if line[1] is not None:\n query = \"SELECT unit from units_table WHERE unit_id=?\"\n cursor.execute(query, [line[1]])\n unit = cursor.fetchall()[0][0]\n if line[2] is not None:\n query = \"SELECT ingredient from ingredients_table WHERE ingredient_id=?\"\n cursor.execute(query, [line[2]])\n ingredient = cursor.fetchall()[0][0]\n print(\"%s - %s - %s\" %(amount, unit, ingredient))\n except sqlite3.Error as error:\n print(\"Error:\", error)\n finally:\n if (sqliteConnection):\n sqliteConnection.close()\n #return list\nif __name__ == '__main__':\n recipe_list = RecipeNames()\n amount = len(recipe_list)\n print(\"there are %s Recipes\" %amount)\n id_list = [str(recipe_list[i][0]) for i in range(amount)]\n #print(id_list)\n for recipe in recipe_list:\n print(\"id:%s > %s\" %(recipe[0], recipe[1].replace(\"https://schönegge.de/index.php/wir-bieten/rezepte/\", \"\")))\n while True:\n request = input(\"\\nwhich recipe would you like to see? enter id! press any key to end!\\n>>\")\n if request in id_list:\n print(\"---showing recipe %s | %s---\"%(request, recipe_list[int(request)][1].replace(\"https://schönegge.de/index.php/wir-bieten/rezepte/\", \"\")))\n showRecipe(int(request))\n else:\n print(\"ending, bye!\")\n break\n","sub_path":"database_reader.py","file_name":"database_reader.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"218549173","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n# Though the following import is not directly being used, it is required\r\n# for 3D projection to work\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\nfrom sklearn.cluster import KMeans\r\nfrom sklearn.mixture import GaussianMixture\r\n\r\nfrom sklearn.metrics.cluster import normalized_mutual_info_score, adjusted_mutual_info_score\r\nfrom yellowbrick.cluster import KElbowVisualizer, SilhouetteVisualizer\r\n\r\nimport time\r\n\r\nfrom sklearn.datasets import load_digits\r\nfrom util import getCreditCardData, getWineData\r\nfrom sklearn.preprocessing import scale\r\n\r\nnp.random.seed(0)\r\n\r\ndef clustering(X, y, data_name):\r\n k_means_NMI = []\r\n k_means_AMI = []\r\n k_means_score = []\r\n gas_mix_NMI = []\r\n gas_mix_AMI = []\r\n gas_mix_score = []\r\n k_means_timing = []\r\n gas_mix_timing = []\r\n\r\n clusters = range(1, 25)\r\n # clusters = [1,2,4,8,16]\r\n\r\n viz = KElbowVisualizer(KMeans(random_state=0), k=clusters)\r\n viz.fit(X)\r\n viz.show(outpath='Figs/01_kmeans_cluster_{}_elbow.png'.format(data_name))\r\n bestK = viz.elbow_value_\r\n plt.clf()\r\n\r\n viz = SilhouetteVisualizer(KMeans(n_clusters=bestK, random_state=0))\r\n viz.fit(X)\r\n viz.show(outpath='Figs/01_kmeans_cluster_{}_silhouette.png'.format(data_name))\r\n plt.clf()\r\n\r\n k_means = KMeans(random_state=0)\r\n gas_mix = GaussianMixture(random_state=0)\r\n\r\n for i in clusters:\r\n # Cluster vs Features\r\n k_means.set_params(n_clusters=i)\r\n gas_mix.set_params(n_components=i)\r\n \r\n t1 = time.time()\r\n k_means.fit(X)\r\n t2 = time.time()\r\n gas_mix.fit(X)\r\n t3 = time.time()\r\n \r\n y_km = k_means.predict(X)\r\n y_gm = gas_mix.predict(X)\r\n\r\n k_means_NMI.append(normalized_mutual_info_score(y, y_km, average_method='arithmetic'))\r\n k_means_AMI.append(adjusted_mutual_info_score(y, y_km, average_method='arithmetic'))\r\n k_means_score.append(k_means.score(X))\r\n gas_mix_NMI.append(normalized_mutual_info_score(y, y_gm, average_method='arithmetic'))\r\n gas_mix_AMI.append(adjusted_mutual_info_score(y, y_gm, average_method='arithmetic'))\r\n gas_mix_score.append(gas_mix.score(X))\r\n k_means_timing.append(t2-t1)\r\n gas_mix_timing.append(t3-t2)\r\n\r\n df = pd.DataFrame()\r\n\r\n df.insert(loc=0, column='K-Means NMI', value=k_means_NMI)\r\n df.insert(loc=0, column='K-Means AMI', value=k_means_AMI)\r\n df.insert(loc=0, column='K-Means Score', value=k_means_score)\r\n df.insert(loc=0, column='Gaussian Mixture NMI', value=gas_mix_NMI)\r\n df.insert(loc=0, column='Gaussian Mixture AMI', value=gas_mix_AMI)\r\n df.insert(loc=0, column='Gaussian Mixture Score', value=gas_mix_score)\r\n df.insert(loc=0, column='K-Means Timing', value=k_means_timing)\r\n df.insert(loc=0, column='Gaussian Mixture Timing', value=gas_mix_timing)\r\n df.insert(loc=0, column='N Clusters', value=clusters)\r\n\r\n print(df.head())\r\n df.to_csv(path_or_buf='Figs/01_clustering_{}.csv'.format(data_name))\r\n\r\n\r\ndigits = load_digits()\r\nX, y = digits.data, digits.target\r\nclustering(scale(X), y, 'digits')\r\n\r\nX, y, data = getCreditCardData('./Data/ccdefault.xls')\r\nclustering(scale(X), y, 'credit')\r\n\r\n","sub_path":"01a_clustering.py","file_name":"01a_clustering.py","file_ext":"py","file_size_in_byte":3259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"463390972","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.http import HttpResponseForbidden, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom kexie_game.models import User\nimport requests\nimport hashlib\nimport redis\nimport time\nimport json\nimport uuid\n\nAPPID = \"wx6b9e0961249fab65\"\nSECRET = \"ab8fd7aa013524e798de9d200532f8c4\"\nTOKEN = \"laoganbunvzhuang\"\nr_belonging = redis.Redis(db=0) # OpenID-{item_id: count}\nr_ranking = redis.Redis(db=1)\n\n\nclass LockError(Exception):\n pass\n\n\nclass UnlockError(Exception):\n pass\n\n\ndef redis_lock(uid, temp_id):\n wait = 0\n while r_belonging.set(\"lock\" + uid, temp_id, nx=True, ex=10) is None:\n time.sleep(0.001)\n wait += 1\n if wait > 10000:\n return False\n return True\n\n\ndef redis_unlock(uid, temp_id):\n wait = 0\n while r_belonging.set(\"unlock\" + uid, temp_id, nx=True, ex=10) is None:\n time.sleep(0.001)\n wait += 1\n if wait > 10000:\n return False\n if r_belonging.get(\"lock\" + uid) == temp_id:\n r_belonging.delete(\"lock\" + uid, \"unlock\" + uid)\n else:\n r_belonging.delete(\"unlock\" + uid)\n return False\n return True\n\n\n@csrf_exempt\ndef login(request):\n if request.method == \"GET\":\n return HttpResponseForbidden()\n data = json.loads(request.body.decode('utf-8'))\n code = data.get(\"code\")\n r = requests.get(\"https://api.weixin.qq.com/sns/jscode2session?\",\n params={\"appid\": APPID, \"secret\": SECRET, \"js_code\": code, \"grant_type\": \"authorization_code\"})\n openid = r.json().get(\"openid\", None)\n if openid is None:\n return JsonResponse({\"status\": \"Error\", \"Error\": \"UnableGetOpenID\"})\n # 获取到OpenID\n u = User.objects.filter(openid=openid)\n is_first = not len(u)\n if not len(u):\n u = User.objects.create(openid=openid)\n else:\n u = u[0]\n if r_belonging.exists(openid):\n items = [{\"id\": key, \"count\": value} for key, value in r_belonging.hgetall(openid).items()]\n else:\n items = []\n return JsonResponse(\n {\"nickname\": u.nickname, \"img\": u.img, \"isBan\": u.isBan, \"items\": items, \"level\": u.level,\n \"history_items\": json.loads(u.history_items), \"openid\": openid, \"sign\": u.daily_sign, \"isFirst\": is_first})\n\n\n@csrf_exempt\ndef belongings_get(request):\n # 用户验证\n if request.method == \"GET\":\n return HttpResponseForbidden()\n data = json.loads(request.body.decode('utf-8'))\n openid = data.get(\"openid\")\n sign = data.get(\"sign\")\n nonce = data.get(\"nonce\")\n if sign != hashlib.md5(openid + TOKEN + nonce).hexdigest():\n return HttpResponseForbidden()\n # 获取信息\n if r_belonging.exists(openid):\n items = [{\"id\": key, \"count\": value} for key, value in r_belonging.hgetall(openid).items()]\n else:\n items = []\n u = User.objects.get(openid=openid)\n return JsonResponse({\"items\": items, \"Craftable\": json.loads(u.history_items)})\n\n\n@csrf_exempt\ndef sign_in(request):\n # 用户验证\n if request.method == \"GET\":\n return HttpResponseForbidden()\n data = json.loads(request.body.decode('utf-8'))\n openid = data.get(\"openid\")\n sign = data.get(\"sign\")\n nonce = data.get(\"nonce\")\n if sign != hashlib.md5(openid + TOKEN + nonce).hexdigest():\n return HttpResponseForbidden()\n # 获取信息\n u = User.objects.get(openid=openid)\n u.weekly_sign += 10 ** (6 - time.localtime(time.time()).tm_wday)\n u.daily_sign = True\n u.sign_count += 1\n u.save()\n return JsonResponse({\"weekly\": \"%07d\" % u.weekly_sign, \"sign_count\": u.sign_count, \"daily_sign\": u.daily_sign})\n\n\n@csrf_exempt\ndef ranking(request):\n key_list = r_ranking.keys()\n ranked_list = sorted([{\"score\": float(r_ranking.get(key)), \"nickname\": User.objects.get(openid=key).nickname}\n for key in key_list], key=lambda rank_item: -rank_item[\"score\"])\n return JsonResponse({\"users\": ranked_list})\n\n\n@csrf_exempt\ndef info(request):\n if request.method == \"GET\":\n return HttpResponseForbidden()\n data = json.loads(request.body.decode('utf-8'))\n openid = data.get(\"openid\")\n # 获取到OpenID后获取信息\n u = User.objects.get(openid=openid)\n if r_belonging.exists(openid):\n items = [{\"id\": key, \"count\": value} for key, value in r_belonging.hgetall(openid).items()]\n else:\n items = []\n return JsonResponse(\n {\"nickname\": u.nickname, \"img\": u.img, \"isBan\": u.isBan, \"items\": items, \"level\": u.level,\n \"history_items\": json.loads(u.history_items), \"openid\": openid, \"sign\": u.daily_sign})\n\n\ndef change_count(delta, item_id, openid, focus=False):\n \"\"\"\n 改变用户仓库内物品数量,种类\n :param int delta:\n :param str item_id:\n :param str openid:\n :param bool focus:\n :return:是否成功改变\n :rtype: bool\n :raises LockError:if redis is unable to lock, and waiting for more than 10 second.\n \"\"\"\n focus = True if delta > 0 and not focus else False\n temp_uuid = uuid.uuid4().__str__()\n if not redis_lock(str(openid), temp_uuid):\n raise LockError\n item_count = r_belonging.hget(openid, item_id)\n if item_count is None:\n item_count = 0\n else:\n item_count = int(float(item_count))\n if item_count + delta < 0 and not focus:\n if not redis_unlock(str(openid), temp_uuid):\n raise UnlockError\n return False\n total_count = 20000000 if item_count + delta > 20000000 else item_count + delta\n r_belonging.hset(openid, item_id, total_count)\n if not redis_unlock(str(openid), temp_uuid):\n raise UnlockError\n return True\n\n\ndef get_count(openid, item_id):\n # type: (int, str) -> int\n \"\"\"\n 获取UID用户仓库指定item_id物品内容个数\n :param int openid: 用户UID\n :param str item_id: 物品识别号ItemID\n :rtype: int\n :return: 数量\n \"\"\"\n item_count = r_belonging.hget(openid, item_id)\n if item_count is None:\n item_count = 0\n else:\n item_count = int(float(item_count))\n return item_count\n","sub_path":"kexie_game/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"534633975","text":"import math\nfrom tools import copy_tasks\nfrom operator import attrgetter\n\n\nclass LPT:\n \"\"\"\n LPT algorithms for parallel machines scheduling. The task goes to the first processor released.\n \"\"\"\n def __init__(self, proc_count: int = 2):\n self.processors = proc_count\n self.completed_tasks: list = []\n self.optimal_schedule_length = 0\n\n def run(self, tasks: list):\n tasks: list = sorted(copy_tasks(tasks), key=attrgetter('cpu_burst'), reverse=True)\n tasks = list(filter(lambda x: x.cpu_burst != 0, tasks))\n\n sum_tasks = sum([task.cpu_burst for task in tasks])\n self.optimal_schedule_length = math.ceil(sum_tasks / self.processors)\n\n loads = []\n for processor in range(self.processors):\n loads.append(0)\n self.completed_tasks.append([])\n\n for task in tasks:\n minloadproc = self._minloadproc(loads)\n self.completed_tasks[minloadproc].append(task)\n loads[minloadproc] += task.cpu_burst\n\n return self.completed_tasks\n\n @staticmethod\n def _minloadproc(loads):\n minload = min(loads)\n for proc, load in enumerate(loads):\n if load == minload:\n return proc\n\n @staticmethod\n def convert_tasks(tasks):\n return list([task.cpu_burst for task in tasks])\n\n def info(self):\n result = ['Алгоритм: LPT\\n', f'Длина оптимального расписания: {self.optimal_schedule_length}\\n']\n for tasks in self.completed_tasks:\n result.append(' '.join(list(map(str, [task.cpu_burst for task in tasks]))) + '\\n')\n\n return ''.join(result)\n","sub_path":"lab_2/LPT.py","file_name":"LPT.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"496885772","text":"\"\"\"\n参照\n・https://www.fxtrade-lab.com/10461\nダイバージェンス・・・価格は上昇しているがオシレーター系のウェーブは下降・・下げの前兆\nMACD特徴\n1 直近の値に重みを付けた平均移動線(実際の動きに近い)=EMAの差\n2 1~3か月の中長期的なスパン?\n3 比較的だましの影響を受けにくい\n\n相場の勢いを表す、上がる上昇、傾きなしストップ、下がる下降\n・欠点\nボックス相場に弱い\nり各ポイントが遅くなりやすい\nじり高じり安のそうばは信頼性が低い\n急激な変化に弱い\n数値的に売られすぎなどを出すのがむずい\n\nMACDのダイバージェンス現象・・・2つのMACDゴールデンクロス間で株価は下落しているがMACDは上昇しているとき、\n2回目のゴールデンクロスから大きく動く(逆もあり)\n\nMACD 買いタイミング\n1 ゴールデンクロス:MACDがシグナル(MACD(12,26,9)平均線)を下から上に突き抜けた時(0ラインより下)\n2 ゼロクロス:MACDが0を突き抜けた時(マイナス⇒プラス) MACDとそのシグナル両方\n3 MACD(12,26)日線がMACD(12,26,9)平均線とクロスしたタイミング\n4 ヒストグラムの反転に注目する\n注意\nMACD載せんが横ばいになってきたら(反転のタイミング?)\n# TODO\nMACDがゴールデンクロスしてそれに伴いRSIも上がっていている間は上昇するか\n「ストキャスティクス」と併用する\nダイバ���ジェンスを利用\nヒストグラムの反転利用\nゼロライン\n\"\"\"\n\n\nimport sys\nsys.path.append('../')\nfrom utils import * # libディレクトリ以下に設定した定数やutilクラスのインポート # 株価分析用に自作した関数をまとめたもの\nimport pandas as pd\n# メモリリーク問題を防ぐ\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nfrom math import ceil \nimport os\nfrom datetime import datetime # \"datetime\" オブジェクトによる時刻計算\nimport numpy as np\n# 1なら個別の株のMACDのグラフを生成\nplt_stock_macd = 1\n# save dir\nMACD_dir = \"./MACD\"\nsave_dir = MACD_dir + \"/MACD_up_toukei\"\nstock_macd_save_dir = MACD_dir + \"./MACD_stocks_graph\"\nif not os.path.isdir(MACD_dir):\n os.makedirs(MACD_dir)\nif not os.path.isdir(save_dir):\n os.makedirs(save_dir)\nif not os.path.isdir(stock_macd_save_dir):\n os.makedirs(stock_macd_save_dir)\n# 銘柄コードの読み込み\nstocks = get.topix500()\n\n## resultデータフレーム\nday = [1,3,5,10] # 〇日後に上昇しているかの〇を設定\ncol=[\"g_p_count\"] # ゴールデンクロスの総数\n# period = [[6,19,9],[8,17,9],[12,26,9]] # 移動平均の期間\nperiod = [[12,26,9]] # 移動平均の期間\nfor d in day:\n col.append(\"roc_d\"+str(d)+\"_plus\")\nresult = pd.DataFrame(data=0,index=range(len(period)),columns=col)\n# rocマップのデータフレーム\ncol=[]\nfor p in period:\n for d in day:\n col.append(\"roc_p\"+str(p)+\"_d\"+str(d))\nindex=[]\n# 分布図の設定(-40~40%を2%間隔)\nfor i in range(-42,42,2):\n if(i==40):\n index.append(str(i)+\"~\")\n elif(i==-42):\n index.append(\"~\"+str(i+2))\n else:\n index.append(str(i)+\"~\"+str(i+2))\nroc_map = pd.DataFrame(data=0,index=index,columns=col)\n\nfor code in stocks.code:\n # 用意した株価データの読み込み\n code = change_stock_code(code)\n # コードのprice情報を読み取る\n # date High Low Open Close Volume Adj Close\n read_data = get.price(code)\n \n for p in range(len(period)): \n data = read_data.copy()\n # MACDを計算\n # param date, 短期移動平均日数,長期移動平均日数, macdの平均移動日数\n # return macd,signal,hist がそれぞれdataに結合\n tech.macd(data, fastperiod=period[p][0], slowperiod=period[p][1], signalperiod=period[p][2])\n data[\"g_point\"] = False\n\n # ゴールデンクロスのタイミングを取得\n for i in range(len(data.index)-1):\n if(data.macd[i]data.signal[i+1]):\n data[\"g_point\"].iat[i+1] = True\n\n # ゴールデンクロス時の傾き/角度を算出\n data[\"macd_line\"] = np.nan\n data[\"signal_line\"] = np.nan\n data[\"macd_slop\"] = np.nan\n data[\"signal_slop\"] = np.nan\n data[\"line_deg\"] = np.nan\n for g in data.index[data.g_point]:\n # 2点間の直線を算出\n # data.macd[g] -> 7.7542 \n a1 = data.macd[g] - data.macd[len(data.Close[:g])-1-1]\n b1 = data.macd[g] - a1*len(data.Close[:g])\n data[\"macd_slop\"].at[g]=a1 \n a2 = data.signal[g] - data.signal[len(data.Close[:g])-1-1]\n b2 = data.signal[g] - a2*len(data.Close[:g])\n data[\"signal_slop\"].at[g]=a2\n data[\"line_deg\"].at[g] = np.rad2deg(np.arctan(abs((a1-a2)/(1+a1*a2))))\n #print(data)\n # plot用に直線データ追加\n # for i in range(7):\n # x = len(data.Close[:g])-1+i-3\n \n # data[\"macd_line\"].iat[x]= a1*x+b1\n # data[\"signal_line\"].iat[x]= a2*x+b2\n\n # 除くゴールデンクロスを選択 \n for g in data.index[data.g_point]:\n # 角度の条件設定\n if(data[\"line_deg\"].at[g] < 30):\n data[\"g_point\"].at[g] = False\n\n # 位置\n # if(data[\"macd\"].at[g] > -data[\"Close\"].at[g]*0.01):\n # data[\"g_point\"].at[g] = False\n\n # 〇日後に上昇しているか確認\n for g in data.index[data.g_point]:\n for d in day:\n # len(data.Close) = 値がある数(日数)、len(data.Close[:g] = 今何日目かみたいな\n # 何%あがったか下がったかをroc_d +dにいれる\n if(len(data.Close[:g])+d<=len(data.Close)):\n data.at[g,\"roc_d\"+str(d)] = (data.Close[len(data.Close[:g])+d-1]-data.Close[g])/data.Close[g]*100\n else:\n data.at[g,\"roc_d\"+str(d)] = (data.Close[-1]-data.Close[g])/data.Close[g]*100\n\n if(data.at[g,\"roc_d\"+str(d)]>0):\n data.at[g,\"roc_d\"+str(d)+\"_point\"] = 1\n else:\n data.at[g,\"roc_d\"+str(d)+\"_point\"] = 0\n # 分布に振り分け\n # 20が原点位置になる\n roc_index = 20+ceil(data.at[g,\"roc_d\"+str(d)]/2)\n if(roc_index<0):\n roc_index=0\n elif(roc_index>41):\n roc_index=41 \n roc_map.at[index[roc_index],\"roc_p\"+str(period[p])+\"_d\"+str(d)] += 1\n\n # 個別の銘柄のグラフとMACDのグラフを生成\n xlim=[\"20150101\",\"20220101\"]\n high = max(data[\"High\"])\n low = min(data[\"Low\"])\n macdHigh = np.nanmax(data[\"macd\"])\n macdLow = np.nanmin(data[\"macd\"])\n\n plot_starting_dtobject = datetime.strptime(xlim[0], \"%Y%m%d\") # datetime object of datetime module = dtobject\n plot_ending_dtobject = datetime.strptime(xlim[1], \"%Y%m%d\") \n plot_starting_time = datetime.timestamp(plot_starting_dtobject)\n plot_ending_time = datetime.timestamp(plot_starting_dtobject)\n if plt_stock_macd == 1:\n ymin, ymax = 0,100\n fig = plt.figure(figsize=[32, 4])\n ax1 = fig.add_subplot(211)\n ax2 = fig.add_subplot(212)\n #plt.subplots(figsize=(8.0, 6.0))\n #data.plot.line(style=['b.-'])\n #data.plot(subplots=True,figsize=[40, 4],y=['rsi','Close'],style=['b.-'],grid=True,xlim=xlim)\n ax1.plot(data[\"Close\"])\n ax1.set_ylabel('Close')\n ax1.vlines(data.index[data.g_point], low, high, colors='red', linestyle='dashed')\n ax1.set_xlim(plot_starting_dtobject, plot_ending_dtobject)\n ax2.vlines(data.index[data.g_point], macdLow, macdHigh, colors='red', linestyle='dashed')\n ax2.plot(data[\"macd\"])\n ax2.plot(data[\"signal\"])\n ax2.set_ylabel('MACD')\n \n ax2.set_xlim(plot_starting_dtobject, plot_ending_dtobject)\n fig.savefig( stock_macd_save_dir + \"/\" + code+'.png')\n plt.cla() # clear axis ################################################################################################################################# Python3 \n plt.clf() \n plt.close('all')\n # 上昇していたらカウンタを加算\n data.dropna(inplace=True)\n if(len(data.index[data.g_point])>0):\n result[\"g_p_count\"].iat[p] += len(data.index)\n for d in day:\n result[\"roc_d\"+str(d)+\"_plus\"].iat[p]+=sum(data[\"roc_d\"+str(d)+\"_point\"])\n # print(data) ここまでのデータ構造 [61 rows x 23 columns]\n # High Low Open Close Volume Adj Close macd signal hist g_point \n # macd_line signal_line macd_slop signal_slop line_deg roc_d1 roc_d1_point roc_d3 roc_d3_point \n # roc_d5 roc_d5_point roc_d10 roc_d10_point\n\n\n\n\n\n# 上昇した数をカウント/roc分布を画像出力\nfor p in range(len(period)):\n result[\"g_p_count\"].iat[p] = sum(roc_map.iloc[:,p*len(day)])\n for d in range(len(day)):\n result[\"roc_d\"+str(day[d])+\"_plus\"].iat[p]=sum(roc_map.iloc[21:,p*len(day)+d])\n\n # roc分布を画像出力\n fig = plt.figure(figsize=(16, 12))\n ax = fig.add_subplot(111)\n bar_list = ax.bar(roc_map.index,roc_map[\"roc_p\"+str(period[p])+\"_d\"+str(day[d])], width=1, color=\"#8ac6d1\")\n [bar_list[i].set_color(\"#ffb6b9\") for i in range(21)]\n ax.set_xticklabels(roc_map.index,rotation=90)\n ax.tick_params(labelsize=20)\n ax.grid(axis=\"y\",c=\"lightgray\")\n title = \"MACD (period=\"+str(period[p])+\", x day later=\"+str(day[d])+\")\"\n ax.set_title(title,fontsize=24)\n ax.set_xlabel(\"Rate of Change [%]\", fontsize=24)\n ax.set_ylabel(\"counts\", fontsize=24)\n win = round(result.at[p,\"roc_d\"+str(day[d])+\"_plus\"]/result.at[p,\"g_p_count\"]*100,1)\n fig.text(0.75,0.5,\"{:}%\".format(win),size=40,color=\"#7dc4d1\")\n fig.text(0.17,0.5,\"{:}%\".format(100-win),size=40,color=\"#ffa8ac\")\n fig.savefig(save_dir + \"/\" + title +\".png\", bbox_inches='tight')\n\nprint(result)\n","sub_path":"indicator/MACD_toukei.py","file_name":"MACD_toukei.py","file_ext":"py","file_size_in_byte":10583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"272508490","text":"\"\"\"\n4831. [파이썬 S/W 문제해결 기본] 1일차 - 전기버스\n\nA도시는 전기버스를 운행하려고 한다. 전기버스는 한번 충전으로 이동할 수 있는 정류장 수가 정해져 있어서, 중간에 충전기가 설치된 정류장을 만들기로 했다.\n\n버스는 0번에서 출발해 종점인 N번 정류장까지 이동하고, 한번 충전으로 최대한 이동할 수 있는 정류장 수 K가 정해져 있다.\n\n충전기가 설치된 M개의 정류장 번호가 주어질 때, 최소한 몇 번의 충전을 해야 종점에 도착할 수 있는지 출력하는 프로그램을 만드시오.\n\n만약 충전기 설치가 잘못되어 종점에 도착할 수 없는 경우는 0을 출력한다. 출발지에는 항상 충전기가 설치되어 있지만 충전횟수에는 포함하지 않는다.\n \n\nN 정류장 0 1 2 3 4 5 6 7 8 9 10\nM 충전기 o o o o o\n 충전횟수 1 2 3\nK : 한번 충전으로 갈수있는 최대 거리\n\nreturn 충전횟수 or 0\n\n다음은 K = 3, N = 10, M = 5, 충전기가 설치된 정류장이 1, 3, 5, 7, 9인 경우의 예이다.\n\n \n\n[입력]\n \n\n첫 줄에 노선 수 T가 주어진다. ( 1 ≤ T ≤ 50 )\n\n\n각 노선별로 K, N, M이 주어지고, 다음줄에 M개의 정류장 번호가 주어진다. ( 1 ≤ K, N, M ≤ 100 )\n \n\n[출력]\n\n\n#과 노선번호, 빈칸에 이어 최소 충전횟수 또는 0을 출력한다.\n\n\"\"\"\nimport sys\nsys.stdin = open('input.txt','r')\n\nT = int(input())\n\ndef ChargingCount(K, N, M, CP):\n life = K\n count = 0\n CPcount = 0\n\n # count sys\n for i in range(1,N):\n # 시작하면서 전진\n life -= 1\n \n # 충전소 o\n if i == CP[CPcount]:\n # 다음 충전소가 있는지 보고\n if CPcount+1 < M:\n # 다음 충전소까지 갈 수 없으면\n if life + i < CP[CPcount+1]:\n # 충전하고\n count += 1\n life = K\n # 다음 충전소 지정\n CPcount += 1\n # 다음 충전소까지 갈수 있으면\n else:\n # 다음 충전소 지정\n CPcount += 1\n # 다음 충전소가 없으면\n else:\n # 끝까지 갈 수 없으면 충전\n if life + i < N:\n count += 1\n life = K\n # 충전소 x\n else:\n # 다음 충전소가 있는지 보고\n if CPcount+1 < M:\n # 지나쳤으면 다음 충전소 지정\n if CP[CPcount] < i:\n CPcount += 1\n \n\n # 연료가 바닥났는데, 도착하지 못하면\n if life <= 0 and i != N:\n return 0\n return count\n \nfor i in range(1,T+1):\n K, N, M = map(int, input().split())\n ChargingPoint = list(map(int,input().split()))\n res = ChargingCount(K,N,M,ChargingPoint)\n print(f\"#{i} {res}\")","sub_path":"OnlineJudge/SWExpertAcademy/InterMediate/01/im1901154831.py","file_name":"im1901154831.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"395882974","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Author: Jordi Ballester (Eficent)\n# Copyright 2015 Eficent\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nfrom openerp.osv import osv\nfrom openerp.tools.translate import _\nfrom openerp.tools import float_round as round\n\n\nclass SaleOrderLine(osv.osv):\n _inherit = \"sale.order.line\"\n\n def _prepare_order_line_invoice_line_hook(self, cr, uid, line,\n account_id=False, context=None):\n\n if not account_id:\n if line.product_id:\n account_id = line.product_id.property_account_income.id\n if not account_id:\n account_id = line.product_id.\\\n categ_id.property_account_income_categ.id\n if not account_id:\n raise osv.except_osv(\n _('Error!'),\n _('Please define income account '\n 'for this product: \"%s\" (id:%d).') %\n (line.product_id.name, line.product_id.id,))\n else:\n prop = self.pool.get('ir.property').get(\n cr, uid, 'property_account_income_categ',\n 'product.category', context=context)\n account_id = prop and prop.id or False\n uosqty = self._get_line_qty(cr, uid, line, context=context)\n uos_id = self._get_line_uom(cr, uid, line, context=context)\n pu = 0.0\n if uosqty:\n pu = round(line.price_unit * line.product_uom_qty / uosqty,\n self.pool.get('decimal.precision').precision_get(\n cr, uid, 'Product Price'))\n fpos = line.order_id.fiscal_position or False\n account_id = self.pool.get('account.fiscal.position').\\\n map_account(cr, uid, fpos, account_id)\n if not account_id:\n raise osv.except_osv(\n _('Error!'),\n _('There is no Fiscal Position defined or '\n 'Income category account defined for '\n 'default properties of Product categories.'))\n res = {\n 'name': line.name,\n 'sequence': line.sequence,\n 'origin': line.order_id.name,\n 'account_id': account_id,\n 'price_unit': pu,\n 'quantity': uosqty,\n 'discount': line.discount,\n 'uos_id': uos_id,\n 'product_id': line.product_id.id or False,\n 'invoice_line_tax_id': [(6, 0, [x.id for x in line.tax_id])],\n 'account_analytic_id': (line.order_id.project_id and\n line.order_id.project_id.id or False),\n }\n return res\n\n def _prepare_order_line_invoice_line(self, cr, uid, line,\n account_id=False, context=None):\n \"\"\" Add Hook \"\"\"\n res = {}\n if not line.invoiced:\n # HOOK\n res = self._prepare_order_line_invoice_line_hook(\n cr, uid, line, account_id=account_id, context=context)\n # --\n return res\n","sub_path":"sale_order_line_prepare_order_line_invoice_line_hooks/models/sale.py","file_name":"sale.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"632557821","text":"one = [1]\nnin = [89]\npath = []\ncount = 0\nmax = 10000000\nfor i in range(1, 600):\n if i in one or i in nin:\n continue\n else:\n cur = i\n path = []\n while not (cur in one or cur in nin):\n path.append(cur)\n cur = sum(list(map(lambda x: int(x) ** 2, str(cur))))\n if cur in one:\n for num in path:\n one.append(num)\n if cur in nin:\n for num in path:\n nin.append(num)\n\nfor i in range(1, max):\n next = sum(list(map(lambda x: int(x) ** 2, str(i))))\n if next in nin:\n count += 1\n\nprint(count)\n","sub_path":"Python/ProjectEuler/92.py","file_name":"92.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"463939577","text":"from database import Database\r\nfrom tkinter.messagebox import *\r\nfrom tkinter import *\r\nfrom tkinter import ttk\r\nclass SearchHouseInfo(object):\r\n def __init__(self,tree_view):\r\n self.tree_view=tree_view\r\n \"\"\"主界面基本设置\"\"\"\r\n def createRoot(self):\r\n root = Tk()\r\n # 设置窗口大小和并将位置设置到屏幕中央\r\n screenwidth = root.winfo_screenwidth()\r\n screenheight = root.winfo_screenheight()\r\n width = 400\r\n high = 300\r\n root.geometry('%dx%d+%d+%d' % (width, high, (screenwidth - width) / 2, (screenheight - high) / 2))\r\n root.title('出租房屋信息查询')\r\n\r\n # 设置各个文本框的标签,并固定位置\r\n\r\n Label(root, text=\"户型\").place(relx=0.05, rely=0.08, relwidth=0.2)\r\n Label(root, text=\"房屋种类\").place(relx=0.5, rely=0.08, relwidth=0.2)\r\n Label(root, text=\"装修情况\").place(relx=0.05, rely=0.38, relwidth=0.2)\r\n Label(root, text=\"房屋情况\").place(relx=0.5, rely=0.38, relwidth=0.2)\r\n # Label(root, text=\"房屋地址\").place(relx=0.04, rely=0.58, relwidth=0.2)\r\n #下拉列表\r\n comvalueHous_type = StringVar() # 窗体自带的文本,新建一个值\r\n comboxlistHous_type = ttk.Combobox(root, textvariable=comvalueHous_type)\r\n comboxlistHous_type[\"values\"] = (\"三室一厅\", \"两室一厅\", \"一室一厅\",\"单间\",\"独门独院\",\"其他\")\r\n comboxlistHous_type.place(relx=0.7, rely=0.08, relwidth=0.2) # 初始化\r\n comboxlistHous_type.current(0)#默认第一个\r\n\r\n\r\n comvaluecus_type = StringVar() # 窗体自带的文本,新建一个值\r\n comboxlistcus_type = ttk.Combobox(root, textvariable=comvaluecus_type)\r\n comboxlistcus_type[\"values\"] = (\"楼房\", \"平房\", \"其他\")\r\n comboxlistcus_type.place(relx=0.25, rely=0.08, relwidth=0.2) # 初始化\r\n comboxlistcus_type.current(0)\r\n\r\n\r\n comvalueren_situatione = StringVar() # 窗体自带的文本,新建一个值\r\n comboxlistren_situation = ttk.Combobox(root, textvariable=comvalueren_situatione)\r\n comboxlistren_situation[\"values\"] = (\"高档装修\", \"中档装修\", \"简单装修\",\"无装修\")\r\n comboxlistren_situation.place(relx=0.25, rely=0.38,relwidth=0.2) # 初始化\r\n comboxlistren_situation.current(0)\r\n\r\n\r\n comvaluehous_situation = StringVar() # 窗体自带的文本,新建一个值\r\n comboxlisthous_situation = ttk.Combobox(root, textvariable=comvaluehous_situation)\r\n comboxlisthous_situation[\"values\"] = (\"已出租\", \"未出租\")\r\n comboxlisthous_situation.place(relx=0.7, rely=0.38,relwidth=0.2) # 初始化\r\n comboxlisthous_situation.current(0)\r\n\r\n # 此处如果默认,直接写死了\r\n # # 设置各个文本框内容所对应的变量\r\n # self.cus_type = comboxlistcus_type.get()\r\n # self.hous_type = comboxlistHous_type.get()\r\n # self.ren_situation = comboxlistren_situation.get()\r\n # self.hous_situation = comboxlisthous_situation.get()\r\n\r\n #插入与取消\r\n Button(root, text=\"查询\",command=lambda: self.searchInfo(comboxlistcus_type.get(),comboxlistHous_type.get(),comboxlistren_situation.get(),comboxlisthous_situation.get())).place(relx=0.3, rely=0.78, width=80)\r\n Button(root, text=\"取消\",command=lambda: self.callback(root)).place(relx=0.7, rely=0.78, width=80)\r\n\r\n\r\n # 捕获关闭按钮\r\n root.protocol(\"WM_DELETE_WINDOW\", lambda: self.callback(root))\r\n # 事件循环\r\n root.mainloop()\r\n\r\n def callback(self, root):\r\n \"\"\"退出时的询问\"\"\"\r\n if askokcancel(\"询问\", \"是否关闭该窗口?\"):\r\n root.destroy()\r\n\r\n def searchInfo(self, cus_type, hous_type, ren_situation,\r\n hous_situation):\r\n \"\"\"查询信息\"\"\"\r\n print(cus_type,hous_type,ren_situation,hous_situation)\r\n #print(self.cus_type, self.hous_type, self.ren_situation, self.hous_situation)\r\n db = Database()\r\n x = self.tree_view.get_children()\r\n for item in x:\r\n self.tree_view.delete(item)\r\n # print(cus_id, cus_name, cus_price, cus_type, hous_area, hous_type, cus_cell,\r\n # ren_situation, hous_address, hous_situation)\r\n try:\r\n # 该sql语句筛选出你模糊查询的各种数据(可以组合)\r\n sql = f'''select * from RentingHouseInfo where cus_type= '{cus_type}'\r\n and hous_type ='{hous_type}' and ren_situation = '{ren_situation}' and hous_situation = '{hous_situation}'\r\n '''\r\n # 只有文本框内有有效数据时才执行该语句\r\n if db.prepare(sql):\r\n db.update()\r\n showinfo(\"提示\", \"已完成查询\")\r\n student_tuple = db.cursor.fetchall()\r\n for item in student_tuple:\r\n self.tree_view.insert('', 'end', values=item)\r\n else:\r\n showerror(\"查询失败\", \"未查询到该类型房屋信息\")\r\n except ValueError:\r\n showerror(\"查询失败\", \"重新查询\")\r\n db.close()","sub_path":"house/searchRentInfo.py","file_name":"searchRentInfo.py","file_ext":"py","file_size_in_byte":5243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"123743733","text":"l = []\nx = 0\nn = 0\nsomx = 0\nsomy = 0\nsomc = 0\n# insetir os dados\nwhile True:\n x = x + 1\n a = float(input(\"Digite X%d: \" % x))\n if a == 0:\n break\n b = float(input(\"Digite Y%d: \" % x))\n l.append([a, b])\n n = n + 1\nprint(l)\n# começar repetição\nfor e in l:\n #soma dos X\n somx = somx + e[0]\n #soma dos Y\n somy = somy + e[1]\n# media de x\nmedx = somx/n\n# media de Y\nmedy = somy/n\nfor e in l:\n somc = somc + (e[0] - medx)*(e[1] - medy)\ncov = somc/n\n\nprint(somx)\nprint(somy)\nprint(medx)\nprint(medy)\nprint(cov)\n","sub_path":"for4.py","file_name":"for4.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"589790052","text":"\nimport os\nimport pandas as pd\n\nfrom transformations import (my_va_transform, my_size_transform, transform_currency,\n my_wc_transform, my_proof_transform)\n\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nread_dir = os.path.join(dir_path, '..', 'data_source')\nsave_dir = os.path.join(dir_path, '..', 'data_transformed')\n\n\ndef transform_data():\n # transform va price list\n va_df = pd.read_csv(os.path.join(read_dir, 'va_prices.csv'), skiprows=1)\n va_df.columns = va_df.columns.str.lower()\n va_df = va_df[va_df.description.str.contains('WHISKEY') | va_df.description.str.contains('WHISKY')]\n\n va_df['alt_brand'] = va_df['brand'].map(lambda x: my_va_transform(x))\n va_df['oz'] = va_df['size'].map(lambda x: my_size_transform(x))\n va_df['alt_price'] = va_df['price'].str.replace('$', '')\n va_df['alt_age'] = va_df['age'].str.replace('YR', '')\n\n # transform reddit whiskey archive\n w_archive = pd.read_csv(os.path.join(read_dir, 'reddit_archive.csv'),\n names=['timestamp', 'whisky_name', 'reviewer_username', 'link',\n 'rating', 'style', 'bottle_price', 'review_date'],\n skiprows=1,\n parse_dates=['timestamp', 'review_date'])\n w_archive['rating'] = pd.to_numeric(w_archive['rating'], errors='coerce')\n w_archive['timestamp'] = pd.to_datetime(w_archive['timestamp'], errors='coerce')\n w_archive['review_date'] = pd.to_datetime(w_archive['review_date'], errors='coerce')\n w_archive['whisky_name'] = w_archive.whisky_name.str.lower()\n w_archive['style'] = w_archive['style'].str.lower()\n w_archive['alt_brand'] = w_archive['whisky_name'].map(lambda x: my_va_transform(x))\n w_archive['alt_bottle_price'] = w_archive['bottle_price'].map(lambda x: transform_currency(x))\n\n # transform whiskey critic\n wc_df = pd.read_csv(os.path.join(read_dir, 'metacritic.csv'))\n wc_df.columns = wc_df.columns.str.lower().str.replace(' ', '_')\n wc_df['alt_brand'] = wc_df['whisky'].map(lambda x: my_va_transform(x))\n wc_df['alt_brand'] = wc_df['alt_brand'].map(lambda x: my_wc_transform(x))\n\n # transform proof66:\n proof_df = pd.read_csv(os.path.join(read_dir, 'proof66.csv'))\n proof_df.columns = proof_df.columns.str.lower().str.replace(' ', '_')\n proof_df['alt_brand'] = proof_df['name'].map(lambda x: my_va_transform(x))\n proof_df['alt_brand'] = proof_df['alt_brand'].map(lambda x: my_proof_transform(x))\n\n va_df.to_csv(os.path.join(save_dir, 'va_prices.csv'), index=False)\n w_archive.to_csv(os.path.join(save_dir, 'reddit_archive.csv'), index=False)\n wc_df.to_csv(os.path.join(save_dir, 'meta_critic.csv'), index=False)\n proof_df.to_csv(os.path.join(save_dir, 'proof66.csv'), index=False)\n\nif __name__ == '__main__':\n\n #download_data()\n transform_data()\n","sub_path":"data_get/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"654256736","text":"import sys\n\ndef flattenEnd(number, index):\n\tfor i in range(index, len(number)):\n\t\tnumber[i] = number[i-1]\n\ndef nextNonDecreasing(number):\n\tfor i in range(1, len(number)):\n\t\tif number[i] < number[i-1]:\n\t\t\tflattenEnd(number, i)\n\n\treturn number\n\ndef containsDouble(number):\n\tif number[0] == number[1] and number[1] != number[2]:\n\t\treturn True\n\n\tif number[-1] == number[-2] and number[-2] != number[-3]:\n\t\treturn True\n\n\tfor i in range(2, len(number)-1):\n\t\tif number[i] == number[i-1] and number[i] != number[i-2] and number[i] != number[i+1]:\n\t\t\treturn True\n\n\treturn False\n\ndef lessThanEqual(number1, number2):\n\ttemp1 = int(\"\".join(number1))\n\ttemp2 = int(\"\".join(number2))\n\n\treturn temp1 <= temp2\n\ndef intToNumber(integer):\n\treturn list(str(integer))\n\ndef increment(number):\n\treturn intToNumber(int(\"\".join(number))+1)\n\nif __name__ == \"__main__\":\n\tif len(sys.argv) != 2:\n\t\tprint(\"Usage: python3 problem_7.py [filename]\")\n\t\texit(1)\n\n\tfilename = sys.argv[1]\n\tf = open(filename, \"r\")\n\n\tlow, high = f.read().strip(\"\\n\").split(\"-\")\n\tlow = list(low)\n\thigh = list(high)\n\n\tcount = 0\n\tnumber = nextNonDecreasing(low)\n\twhile lessThanEqual(number, high):\n\t\tif containsDouble(number):\n\t\t\tcount += 1\n\n\t\tnumber = nextNonDecreasing(increment(number))\n\n\tprint(count)\n","sub_path":"part8/problem_7.py","file_name":"problem_7.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"501074201","text":"#get company\ncompany = filter_values.get('company') or get_defaults()['company']\n\n#get company letter head\nl_head = sql(\"select letter_head from `tabCompany` where name='%s'\" % company)\nl_head = l_head and l_head[0][0] or ''\n\n# Posting date, fiscal year and year start date\n#-----------------------------------------------\nif not filter_values.get('posting_date') or not filter_values.get('posting_date1'):\n msgprint(\"Please enter From Date and To Date\")\n raise Exception\nelse:\n from_date = filter_values['posting_date']\n to_date = filter_values['posting_date1']\n\nysd, from_date_year = sql(\"select year_start_date, name from `tabFiscal Year` where %s between year_start_date and date_add(year_start_date,interval 1 year)\",from_date)[0]\n\n\n# define columns\n#---------------\ncol = []\ncol.append(['Date','Date','80px',''])\ncol.append(['Detail','Text','475px',''])\ncol.append(['Debit','Currency','75px',''])\ncol.append(['Credit','Currency','75px',''])\n\nfor c in col:\n colnames.append(c[0])\n coltypes.append(c[1])\n colwidths.append(c[2])\n coloptions.append(c[3])\n col_idx[c[0]] = len(colnames)\n\n\ntotal_debit, total_credit, total_opening, total_diff = 0,0,0,0\n\n#total query\nq = query.split('WHERE')[1].split('LIMIT')\nif len(q) > 2:\n query_where_clause = 'LIMIT'.join(q[:-1])\nelse:\n query_where_clause = q[0]\n\ntot = sql('select sum(`tabGL Entry`.debit),sum(`tabGL Entry`.credit) from `tabGL Entry`, tabAccount where %s' % query_where_clause)\n\nfor t in tot:\n total_debit += t and flt(t[0]) or 0\n total_credit += t and flt(t[1]) or 0\n\ntotal_diff = total_debit - total_credit\n\n# opening\naccount = filter_values.get('account')\nif account:\n acc_det = sql(\"select debit_or_credit, is_pl_account, lft, rgt, group_or_ledger from tabAccount where name = '%s'\" % account)\n opening_bal = get_obj('GL Control').get_as_on_balance(account, from_date_year, add_days(from_date, -1), acc_det[0][0], acc_det[0][2], acc_det[0][3])[2]\n if acc_det[0][0] == 'Credit':\n opening_bal = -1*opening_bal\n \n\nout = []\ncount = 0\nfor r in res:\n count +=1\n det = r[1].split('~~~')\n if from_export == 1:\n a = \"Account: \" + det[0] + NEWLINE + det[1] + NEWLINE + \"Against: \" + det[2] + NEWLINE + \"Voucher No: \" + det[4]\n else:\n a = \"Account: \" + det[0]+ \"\" + NEWLINE + \"
\" +det[1]+ \"
Against: \" + det[2] + \"
Voucher No: \" + det[4] + \"
\"\n r[1] = a\n out.append(r)\n\nif total_debit != 0 or total_credit != 0:\n # Total debit/credit\n t_row = ['' for i in range(len(colnames))]\n t_row[1] = 'Total'\n t_row[col_idx['Debit']-1] = total_debit \n t_row[col_idx['Credit']-1] = total_credit \n out.append(t_row)\n \n # opening\n if account:\n t_row = ['' for i in range(len(colnames))]\n t_row[1] = 'Opening Balance on '+ from_date\n t_row[col_idx['Debit']-1] = opening_bal\n out.append(t_row)\n \n # diffrence (dr-cr)\n t_row = ['' for i in range(len(colnames))]\n t_row[1] = 'Total(Dr-Cr)'\n t_row[col_idx['Debit']-1] = total_diff \n out.append(t_row)\n\n # closing\n if account:\n t_row = ['' for i in range(len(colnames))]\n t_row[1] = 'Closing Balance on ' + to_date\n t_row[col_idx['Debit']-1] = flt(opening_bal) + flt(total_diff )\n out.append(t_row)\n \n# Print Format\nmyheader = \"\"\"\n\n
\"\"\"+l_head+\"\"\"
\n

%(acc)s

\n
Ledger Between %(fdt)s and %(tdt)s

\n\n \"\"\" % {'acc':account,\n 'fdt':from_date,\n 'tdt':to_date}\n \npage_template = myheader+\"
%(table)s
\"","sub_path":"accounts/search_criteria/creditors_ledger/creditors_ledger.py","file_name":"creditors_ledger.py","file_ext":"py","file_size_in_byte":3719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"562880117","text":"from SensorBase import SensorBase\n\nclass NullSensor(SensorBase):\n\tdef __init__(self, sensor):\n\t\tsuper(NullSensor, self).__init__(sensor)\n\t\n\tdef read(self):\n\t\tdata = {self.Temperature_F: 0,\n\t\t\t\tself.Humidity_Percent: 0,\n\t\t\t\tself.Dewpoint_F: 0,\n\t\t\t\tself.BarometricPressure_inchesHg: 0,\n\t\t\t\tself.RelativeLight_Percent: 0,\n\t\t\t\tself.WindSpeed_mph: 0,\n\t\t\t\tself.WindDirection_degrees: 0,\n\t\t\t\tself.Rainfall_inches: 0,\n\t\t\t\tself.BatteryLevel_volts: 0}\n\t\t\n\t\tsuper(NullSensor, self)._save(data)","sub_path":"sensorlib/NullSensor.py","file_name":"NullSensor.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"578773454","text":"\"\"\"\nUnits tests for propertyestimator.protocols.miscellaneous\n\"\"\"\nimport operator\nimport random\nimport tempfile\nfrom functools import reduce\n\nimport pytest\n\nfrom propertyestimator import unit\nfrom propertyestimator.backends import ComputeResources\nfrom propertyestimator.properties import ParameterGradient, ParameterGradientKey\nfrom propertyestimator.protocols.miscellaneous import AddValues, FilterSubstanceByRole, SubtractValues, MultiplyValue, \\\n DivideValue, WeightByMoleFraction\nfrom propertyestimator.substances import Substance\nfrom propertyestimator.utils.exceptions import PropertyEstimatorException\nfrom propertyestimator.utils.quantities import EstimatedQuantity\n\n\n@pytest.mark.parametrize(\"values\", [\n [random.randint(1, 10) for _ in range(10)],\n [random.random() for _ in range(10)],\n [random.random() * unit.kelvin for _ in range(10)],\n [EstimatedQuantity(random.random() * unit.kelvin, random.random() * unit.kelvin, f'{x}') for x in range(10)],\n [ParameterGradient(ParameterGradientKey('a', 'b', 'c'), random.random() * unit.kelvin) for x in range(10)]\n])\ndef test_add_values_protocol(values):\n\n with tempfile.TemporaryDirectory() as temporary_directory:\n\n add_quantities = AddValues('add')\n add_quantities.values = values\n\n result = add_quantities.execute(temporary_directory, ComputeResources())\n\n assert not isinstance(result, PropertyEstimatorException)\n assert add_quantities.result == reduce(operator.add, values)\n\n\n@pytest.mark.parametrize(\"values\", [\n [random.randint(1, 10) for _ in range(2)],\n [random.random() for _ in range(2)],\n [random.random() * unit.kelvin for _ in range(2)],\n [EstimatedQuantity(random.random() * unit.kelvin, random.random() * unit.kelvin, f'{x}') for x in range(2)],\n [ParameterGradient(ParameterGradientKey('a', 'b', 'c'), random.random() * unit.kelvin) for x in range(2)]\n])\ndef test_subtract_values_protocol(values):\n\n with tempfile.TemporaryDirectory() as temporary_directory:\n\n sub_quantities = SubtractValues('sub')\n sub_quantities.value_b = values[1]\n sub_quantities.value_a = values[0]\n\n result = sub_quantities.execute(temporary_directory, ComputeResources())\n\n assert not isinstance(result, PropertyEstimatorException)\n assert sub_quantities.result == values[1] - values[0]\n\n\n@pytest.mark.parametrize(\"value\", [\n random.randint(1, 10),\n random.random(),\n random.random() * unit.kelvin,\n EstimatedQuantity(random.random() * unit.kelvin, random.random() * unit.kelvin, 'a'),\n ParameterGradient(ParameterGradientKey('a', 'b', 'c'), random.random() * unit.kelvin)\n])\n@pytest.mark.parametrize(\"multiplier\", [\n random.randint(1, 10),\n random.random()\n])\ndef test_multiply_values_protocol(value, multiplier):\n\n with tempfile.TemporaryDirectory() as temporary_directory:\n\n multiply_quantities = MultiplyValue('multiply')\n multiply_quantities.value = value\n multiply_quantities.multiplier = multiplier\n\n result = multiply_quantities.execute(temporary_directory, ComputeResources())\n\n assert not isinstance(result, PropertyEstimatorException)\n assert multiply_quantities.result == value * multiplier\n\n\n@pytest.mark.parametrize(\"value\", [\n random.randint(1, 10),\n random.random(),\n random.random() * unit.kelvin,\n EstimatedQuantity(random.random() * unit.kelvin, random.random() * unit.kelvin, 'a'),\n ParameterGradient(ParameterGradientKey('a', 'b', 'c'), random.random() * unit.kelvin)\n])\n@pytest.mark.parametrize(\"divisor\", [\n random.randint(1, 10),\n random.random()\n])\ndef test_divide_values_protocol(value, divisor):\n\n with tempfile.TemporaryDirectory() as temporary_directory:\n\n divide_quantities = DivideValue('divide')\n divide_quantities.value = value\n divide_quantities.divisor = divisor\n\n result = divide_quantities.execute(temporary_directory, ComputeResources())\n\n assert not isinstance(result, PropertyEstimatorException)\n assert divide_quantities.result == value / divisor\n\n\n@pytest.mark.parametrize(\"component_smiles\", ['C', 'CC', 'CCC'])\n@pytest.mark.parametrize(\"value\", [\n random.randint(1, 10),\n random.random(),\n random.random() * unit.kelvin,\n EstimatedQuantity(random.random() * unit.kelvin, random.random() * unit.kelvin, 'a'),\n ParameterGradient(ParameterGradientKey('a', 'b', 'c'), random.random() * unit.kelvin)\n])\ndef test_weight_by_mole_fraction_protocol(component_smiles, value):\n\n full_substance = Substance.from_components('C', 'CC', 'CCC')\n component = Substance.from_components(component_smiles)\n\n mole_fraction = next(iter(full_substance.get_amounts(component_smiles))).value\n\n with tempfile.TemporaryDirectory() as temporary_directory:\n\n weight_protocol = WeightByMoleFraction('weight')\n weight_protocol.value = value\n weight_protocol.full_substance = full_substance\n weight_protocol.component = component\n\n result = weight_protocol.execute(temporary_directory, ComputeResources())\n\n assert not isinstance(result, PropertyEstimatorException)\n assert weight_protocol.weighted_value == value * mole_fraction\n\n\n@pytest.mark.parametrize(\"filter_role\", [Substance.ComponentRole.Solute,\n Substance.ComponentRole.Solvent,\n Substance.ComponentRole.Ligand,\n Substance.ComponentRole.Receptor])\ndef test_substance_filtering_protocol(filter_role):\n \"\"\"Tests that the protocol to filter substances by\n role correctly works.\"\"\"\n\n def create_substance():\n test_substance = Substance()\n\n test_substance.add_component(Substance.Component('C', role=Substance.ComponentRole.Solute),\n Substance.ExactAmount(1))\n\n test_substance.add_component(Substance.Component('CC', role=Substance.ComponentRole.Ligand),\n Substance.ExactAmount(1))\n\n test_substance.add_component(Substance.Component('CCC', role=Substance.ComponentRole.Receptor),\n Substance.ExactAmount(1))\n\n test_substance.add_component(Substance.Component('O', role=Substance.ComponentRole.Solvent),\n Substance.MoleFraction(1.0))\n\n return test_substance\n\n filter_protocol = FilterSubstanceByRole('filter_protocol')\n filter_protocol.input_substance = create_substance()\n\n filter_protocol.component_role = filter_role\n filter_protocol.execute('', ComputeResources())\n\n assert len(filter_protocol.filtered_substance.components) == 1\n assert filter_protocol.filtered_substance.components[0].role == filter_role\n","sub_path":"propertyestimator/tests/test_protocols/test_miscellaneous.py","file_name":"test_miscellaneous.py","file_ext":"py","file_size_in_byte":6783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"164754567","text":"#!/usr/bin/env python3\n\n#-*- coding: UTF-8 -*-\n#------------------------------\n# @Version : 1.0\n# @Author : Zeng**\n# @Time : 22-03-10\n# @Language : Python3.6\n# @Function : network_1\n#------------------------------\n\n\"\"\"\n创建 TCP 客户端\n\"\"\"\n\n###########################\t\n# TCP 时间戳服务器客户端代码;\n###########################\n\nimport socket\n\nHOST = 'localhost'\nPORT = 21567\nBUFSIZ = 1024\nADDR = (HOST, PORT)\n\ntcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ntcpCliSock.connect(ADDR)\n\nwhile True:\n\tdata = input('> ')\n\tif not data:\n\t\tbreak\n\ttcpCliSock.send(data.encode('utf-8'))\n\tdata = tcpCliSock.recv(BUFSIZ)\n\tif not data:\n\t\tbreak\n\tprint(data.encode('utf-8'))\n\t\ntcpCliSock.close()\n\n\n\n\n\n\n","sub_path":"python_core_3/网络编程/network_tcp_client.py","file_name":"network_tcp_client.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"316785517","text":"import time\n\nimport machine\nimport uasyncio\n# import const\nfrom lib.uasyncio.websocket.server import WSReader, WSWriter\n\n\ndef log(*args, **kwargs):\n print(*args, **kwargs)\n\n\nclass WriterPool:\n writers = {}\n\n @classmethod\n def register(cls, writer):\n uid = len(cls.writers)\n cls.writers[uid] = writer\n return uid\n\n @classmethod\n def unregister(cls, uid):\n del cls.writers[uid]\n\n @classmethod\n async def write(cls, msg):\n for w in cls.writers:\n await cls.writers[w].awrite(msg)\n log(\"Sent message {} to {}\".format(msg, w))\n\n\nclass DeviceHandler:\n HOME_POSITION = 0\n MIN_POSITION = 0\n MAX_POSITION = 1334930\n TRIGGER_PADDING = 25\n BATCH_SIZE = 100\n\n DIR_CW = 1\n DIR_CCW = -1\n\n BROADCAST_INTERVAL = 100\n\n position = HOME_POSITION\n\n steps = 0\n step_dir = DIR_CW\n\n pin_dir = machine.Pin(13, machine.Pin.OUT) # D7\n pin_step = machine.Pin(15, machine.Pin.OUT) # D8\n\n sensor_triggered = False\n trigger_position = (MAX_POSITION - TRIGGER_PADDING, MIN_POSITION + TRIGGER_PADDING)\n\n OP_IDLE = 0\n OP_GO = 1\n OP_ROT = 2\n OP_RESET = 3\n OP_RESET_STAGE_2 = 4\n\n operation = OP_IDLE\n\n @classmethod\n def setup_irq(cls):\n pin_sensor = machine.Pin(6, machine.Pin.IN) # GPIO 12 / D6\n\n # pin_sensor.irq(trigger=machine.Pin.IRQ_RISING, handler=cls.sensor_trigger_enter_handler)\n\n @classmethod\n async def main(cls):\n\n send_in = cls.BROADCAST_INTERVAL\n\n while 1:\n if cls.sensor_triggered:\n cls.position_cal()\n\n if cls.steps > 0:\n\n if cls.steps > 2 * cls.BATCH_SIZE:\n steps = cls.BATCH_SIZE\n else:\n steps = cls.steps\n\n cls.steps -= steps\n cls.position += cls.step_dir * steps\n\n cls.position = cls.normalize(cls.position)\n if cls.position < 0:\n cls.position += cls.MAX_POSITION\n if cls.position > cls.MAX_POSITION:\n cls.position -= cls.MAX_POSITION\n\n cls.batch_step(steps)\n\n await uasyncio.sleep_ms(1)\n elif cls.operation == cls.OP_RESET:\n cls.reset(cls.OP_RESET_STAGE_2)\n else:\n cls.operation = cls.OP_IDLE\n await uasyncio.sleep_ms(20)\n\n if send_in > 0:\n send_in -= 1\n else:\n send_in = cls.BROADCAST_INTERVAL\n await cls.send_status()\n\n @classmethod\n def batch_step(cls, batch_size):\n for i in range(0, batch_size):\n time.sleep_us(50)\n cls.pin_step.value(0)\n time.sleep_us(50)\n cls.pin_step.value(1)\n\n @classmethod\n def set_target(cls, target):\n if target > cls.MAX_POSITION or target < cls.HOME_POSITION:\n return\n\n position = cls.position\n cls.operation = cls.OP_GO\n\n cw_dist, ccw_dist = cls.dist(position, target)\n\n if cw_dist <= ccw_dist:\n cls.steps = cw_dist\n cls.step_dir = cls.DIR_CW\n else:\n cls.steps = ccw_dist\n cls.step_dir = cls.DIR_CCW\n\n cls.pin_dir.value(1 if cls.step_dir == cls.DIR_CW else 0)\n\n @classmethod\n def park(cls):\n cls.set_target(cls.HOME_POSITION)\n\n @classmethod\n def full_rotate(cls, dir=DIR_CW):\n cls.step_dir = dir\n cls.steps = cls.MAX_POSITION - cls.MIN_POSITION\n cls.operation = cls.OP_ROT\n\n @classmethod\n def reset(cls, stage=OP_RESET):\n if stage == cls.OP_RESET:\n cls.step_dir = cls.DIR_CCW\n cls.steps = cls.TRIGGER_PADDING * 1\n cls.operation = cls.OP_RESET\n\n if stage == cls.OP_RESET_STAGE_2:\n cls.step_dir = cls.DIR_CW\n cls.steps = cls.MAX_POSITION - cls.MIN_POSITION\n cls.operation = cls.OP_RESET_STAGE_2\n\n @classmethod\n async def send_status(cls):\n dir = \"cw\" if cls.step_dir == cls.DIR_CW else \"ccw\"\n if cls.position == cls.HOME_POSITION and cls.operation == cls.OP_IDLE:\n status = \"parked\"\n elif cls.operation == cls.OP_IDLE:\n status = \"idle\"\n elif cls.operation in (cls.OP_RESET, cls.OP_RESET_STAGE_2,):\n status = \"reset\"\n elif cls.operation == cls.OP_ROT:\n status = \"rotate\"\n else:\n status = \"go\"\n\n status = (\n \"{\"\n + '\"position\": {}, \"direction\": \"{}\", \"status\": \"{}\"\\}'.format(\n cls.position, dir, status\n )\n + \"}\"\n )\n await WriterPool.write(status)\n\n @classmethod\n def sensor_trigger_enter_handler(cls):\n cls.sensor_triggered = True\n\n @classmethod\n def position_cal(cls):\n dir_index = 1 if cls.step_dir == 1 else 0\n target = cls.normalize(cls.position + (cls.step_dir * cls.steps))\n\n cal_position = cls.trigger_position[dir_index]\n\n cls.position = cal_position\n\n if cls.operation == cls.OP_RESET_STAGE_2:\n cls.park()\n else:\n cls.set_target(target)\n\n cls.sensor_triggered = False\n\n @classmethod\n def dist(cls, position, target):\n cw_dist = target - position\n if cw_dist < cls.MIN_POSITION:\n cw_dist += cls.MAX_POSITION\n\n ccw_dist = cls.MAX_POSITION - cw_dist\n\n return cw_dist, ccw_dist\n\n @classmethod\n def normalize(cls, position):\n if position < 0:\n return position + cls.MAX_POSITION\n if position > cls.MAX_POSITION:\n return position - cls.MAX_POSITION\n return position\n\n\nasync def conn_handler(reader, writer):\n # Consume GET line\n await reader.readline()\n\n ws_reader = await WSReader(reader, writer)\n ws_writer = WSWriter(reader, writer)\n\n uid = WriterPool.register(ws_writer)\n\n while 1:\n l = await ws_reader.read(1024)\n\n log(\"Got message {}\".format(l))\n\n if not l:\n log(\"Disconnecting\")\n break\n\n if l.startswith(\"pos:\"):\n DeviceHandler.set_target(int(l[4:]))\n\n elif l.startswith(\"home\"):\n DeviceHandler.park()\n\n elif l.startswith(\"reset\"):\n DeviceHandler.reset()\n\n elif l.startswith(\"rot:ccw\"):\n DeviceHandler.full_rotate(DeviceHandler.DIR_CCW)\n\n elif l.startswith(\"rot\"):\n DeviceHandler.full_rotate(DeviceHandler.DIR_CW)\n\n WriterPool.unregister(uid)\n\n\ndef start_dome():\n machine.freq(160000000)\n\n loop = uasyncio.get_event_loop()\n loop.create_task(DeviceHandler.main())\n loop.create_task(uasyncio.start_server(conn_handler, \"0.0.0.0\", 8081))\n loop.run_forever()\n loop.close()\n","sub_path":"contrib/dome/app/dome.py","file_name":"dome.py","file_ext":"py","file_size_in_byte":6796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"270942053","text":"# -*- coding: utf-8 -*-\n\nimport requests\nimport json\nimport cv2\nimport numpy as np\nimport time \nimport argparse\n\ndef main():\n start = time.time()\n\n id = {}\n requestsURL = 'http://127.0.0.1:5000/mcs'\n response = requests.get(requestsURL,params=id)\n if len(response.text) == 0:\n res = 'ERROR: return is nan'\n else:\n res = json.loads(response.text)\n #ret = json.dumps(res, indent=2)\n #print(res)\n return res\n\ndef view():\n bord_size_w = 3840\n bord_size_h = 2160\n fps = 3\n access_time = 1/5\n \n bord_size = (bord_size_h, bord_size_w, 3)\n while(1):\n try:\n white_bord = np.full(bord_size, 255, np.uint8)\n ret = main()\n persons = ret[\"Persons\"]\n for person in persons:\n eye = person[\"eye\"].split(\",\")\n eye_x, eye_y = eye[:2]\n eye_x, eye_y = float(eye_x), float(eye_y)\n eye_x, eye_y = (eye_x/(-2.0))+0.5, (eye_y/(-2.0))+0.5\n disp_eye_x, disp_eye_y = int(bord_size_w*eye_x), int(bord_size_h*eye_y)\n cv2.circle(white_bord, (disp_eye_x, disp_eye_y), bord_size_h//5, (0,0,255), -1)\n\n gender = person[\"gender\"]\n age = str(person[\"age\"])[0:4]\n distance = str(person[\"distance\"])[0:4]\n disp_gender_x, disp_gender_y = disp_eye_x - 100, disp_eye_y - 100\n disp_age_x, disp_age_y = disp_gender_x, disp_gender_y + 100\n disp_distance_x, disp_distance_y = disp_age_x, disp_age_y + 100\n font_collor = (0,0,0)\n font_size = 100//30\n font_thickness = 10\n\n cv2.putText(white_bord, gender, (disp_gender_x, disp_gender_y ), cv2.FONT_HERSHEY_SIMPLEX, font_size, font_collor, font_thickness)\n cv2.putText(white_bord, 'age:' + age, (disp_age_x, disp_age_y), cv2.FONT_HERSHEY_SIMPLEX, font_size, font_collor, font_thickness)\n cv2.putText(white_bord, 'dst:' + distance, (disp_distance_x, disp_distance_y), cv2.FONT_HERSHEY_SIMPLEX, font_size, font_collor, font_thickness)\n\n print(eye_x,eye_y)\n cv2.imshow('show',white_bord)\n print()\n time.sleep(access_time)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n \n except:\n white_bord = np.full(bord_size, 255, np.uint8)\n cv2.imshow('show',white_bord)\n time.sleep(access_time)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n pass\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--dType', type=str, default='Custom', help=\n 'you can select \\'68points\\', \\'single68points\\',\\n \\\n \\'AgeGender\\', \\'Expressions\\',\\n \\\n \\'Descriptors\\', and \\'Custom\\'.\\n \\\n Default is \\'Custom\\''\n )\n parser.add_argument('--imgFile', type=str, default='../images/bbt1.jpg', help='Default is \\'../images/bbt1.jpg\\'')\n parser.add_argument('--portNum', type=int, default=50007, help='Default is 3030')\n args = parser.parse_args()\n\n dType = args.dType\n imgFile = args.imgFile\n portNum = args.portNum\n\n view()\n #ret = main()\n #print(type(ret))\n\n","sub_path":"dev_script_0.1/api-viewer_50inch.py","file_name":"api-viewer_50inch.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"2474181","text":"\"\"\"empty message\n\nRevision ID: 397cba89d209\nRevises: \nCreate Date: 2018-03-16 19:42:58.188818\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '397cba89d209'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('user_profile',\n sa.Column('userid', sa.Integer(), nullable=False),\n sa.Column('username', sa.String(length=80), nullable=True),\n sa.Column('firstname', sa.String(length=80), nullable=True),\n sa.Column('lastname', sa.String(length=80), nullable=True),\n sa.Column('gender', sa.String(length=10), nullable=True),\n sa.Column('biography', sa.String(length=255), nullable=True),\n sa.Column('photo', sa.String(length=80), nullable=True),\n sa.Column('created_on', sa.String(length=20), nullable=True),\n sa.PrimaryKeyConstraint('userid'),\n sa.UniqueConstraint('username')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('user_profile')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/397cba89d209_.py","file_name":"397cba89d209_.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"5918128","text":"import random\r\n\r\n\r\ndef yy(trainingTimes):\r\n\r\n\r\n y3 = [1, 0, 1, 0, 1, 0, 0]\r\n\r\n y4 = [1, 1, 0, 1, 1, 0, 0]\r\n\r\n y5 = [1, 1, 1, 1, 1, 0, 0]\r\n\r\n y6 = [1, 1, 1, 1, 1, 1, 0]\r\n\r\n\r\n if trainingTimes == 3:\r\n\r\n y = y3\r\n\r\n if trainingTimes == 4:\r\n\r\n y = y4\r\n\r\n if trainingTimes == 5:\r\n\r\n y = y5\r\n\r\n if trainingTimes == 6:\r\n\r\n y = y6\r\n\r\n\r\n return y\r\n\r\n\r\ndef week(dict, exercise, rest, a, b, x, restDayList, randRest, trainingTimes):\r\n\r\n\r\n\r\n if randRest == \"no\":\r\n\r\n y = yy(trainingTimes)\r\n\r\n for i in range(0, len(y)):\r\n\r\n\r\n if y[i] == 1:\r\n\r\n dict[a] = exercise[x]\r\n\r\n x += 1\r\n\r\n if x >= 3:\r\n\r\n x = 0\r\n\r\n\r\n else:\r\n\r\n dict[a] = rest[0]\r\n\r\n\r\n a += 1\r\n\r\n\r\n else:\r\n\r\n\r\n for i in range(a, b + 1):\r\n\r\n\r\n if i in restDayList:\r\n\r\n dict[i] = rest[0]\r\n\r\n\r\n else:\r\n\r\n dict[i] = exercise[x]\r\n\r\n x += 1\r\n\r\n if x >= 3:\r\n\r\n x = 0\r\n\r\n\r\n\r\n return dict, x\r\n\r\n\r\n\r\ndef Pass(dict, rest, a, b, x, addRestDayList):\r\n\r\n\r\n for i in range(a, b + 1):\r\n\r\n\r\n if i in addRestDayList:\r\n\r\n dict[i] = rest[0]\r\n\r\n print(\"aRD-rest\")\r\n\r\n\r\n\r\n return dict, x\r\n\r\n\r\n\r\ndef RandomAndOptimize(dict, exercise, rest, a, b, x, randRest, restDayList, addRestDayList, trainingTimes):\r\n\r\n uusi = False\r\n\r\n\r\n\r\n if addRestDayList[0] == \"\":\r\n\r\n addRestDayListLength = 0\r\n\r\n else:\r\n\r\n addRestDayListLength = len(addRestDayList)\r\n\r\n\r\n\r\n\r\n if addRestDayList[0] != \"\":\r\n\r\n # mikäli yksikään lisätyistä ei ole jo valmiiksi restDayListissä, niin pitää tehdä uusi\r\n for i in addRestDayList:\r\n\r\n if i not in restDayList:\r\n\r\n uusi = True\r\n\r\n if uusi == True:\r\n\r\n restDayList = randomizeFunction(a, b, trainingTimes, addRestDayList)\r\n\r\n print(restDayList)\r\n\r\n\r\n\r\n if (7 - trainingTimes - addRestDayListLength) < 0:\r\n\r\n # randomilla että mistä treenistä alotetaan, -1 kun len = yhen liian iso\r\n\r\n x = random.randint(0, len(exercise)-1)\r\n\r\n #jotta treenien järjestys ei muutu, TÄMÄNHÄN PITÄISI muuttua kun tehdään jatkuvasti mutta olkoon näin nyt\r\n if (7 - trainingTimes - addRestDayListLength) > 0:\r\n\r\n x = 0\r\n\r\n dict, x = week(dict, exercise, rest, a, b, x, restDayList, randRest, trainingTimes)\r\n\r\n\r\n\r\n return dict, x\r\n\r\n\r\n\r\n\r\ndef weekOptimize(dict, exercise, rest, a, b, x, restDayList):\r\n\r\n\r\n for i in range(a, b + 1):\r\n\r\n\r\n if i in restDayList:\r\n\r\n dict[i] = rest[0]\r\n\r\n else:\r\n\r\n dict[i] = exercise[x]\r\n\r\n x += 1\r\n\r\n if x >= 3:\r\n\r\n x = 0\r\n\r\n\r\n\r\n\r\n return dict, x\r\n\r\n\r\n\r\n\r\ndef rdlFunction(y, a, b, restDayList, addRestDayList):\r\n\r\n\r\n z = 0\r\n\r\n\r\n for i in range(a, b + 1):\r\n\r\n if i in addRestDayList:\r\n\r\n restDayList.append(i)\r\n\r\n elif y[z] == 0:\r\n\r\n restDayList.append(i)\r\n\r\n z += 1\r\n\r\n else:\r\n\r\n z += 1\r\n\r\n\r\n\r\n\r\n return restDayList\r\n\r\n\r\n\r\n\r\n\r\ndef Optimize(dict, exercise, rest, a, b, x, randRest, restDayList, addRestDayList, trainingTimes):\r\n\r\n print(restDayList)\r\n\r\n print(\"opt\")\r\n\r\n\r\n if addRestDayList[0] == \"\":\r\n\r\n addRestDayListLength = 0\r\n\r\n else:\r\n\r\n addRestDayListLength = len(addRestDayList)\r\n\r\n y = yy(trainingTimes)\r\n\r\n\r\n print(y)\r\n\r\n\r\n if trainingTimes == 3:\r\n\r\n\r\n if addRestDayListLength == 1:\r\n\r\n\r\n restDayList = rdlFunction(y, a, b, restDayList, addRestDayList)\r\n\r\n\r\n\r\n\r\n elif addRestDayListLength == 2:\r\n\r\n restDayList = rdlFunction(y, a, b, restDayList, addRestDayList)\r\n\r\n\r\n\r\n\r\n elif addRestDayListLength == 3:\r\n\r\n\r\n y[1] = 1\r\n\r\n restDayList = rdlFunction(y, a, b, restDayList, addRestDayList)\r\n\r\n\r\n\r\n\r\n\r\n elif addRestDayListLength == 4:\r\n\r\n\r\n restDayList = addRestDayList\r\n\r\n\r\n\r\n else:\r\n\r\n x = random.randint(0, 2)\r\n\r\n restDayList = addRestDayList\r\n\r\n\r\n\r\n\r\n dict, x = weekOptimize(dict, exercise, rest, a, b, x, restDayList)\r\n\r\n\r\n\r\n if trainingTimes == 4:\r\n\r\n\r\n if addRestDayListLength == 1:\r\n\r\n\r\n restDayList = rdlFunction(y, a, b, restDayList, addRestDayList)\r\n\r\n\r\n elif addRestDayListLength == 2:\r\n\r\n\r\n restDayList = rdlFunction(y, a, b, restDayList, addRestDayList)\r\n\r\n\r\n elif addRestDayListLength == 3:\r\n\r\n restDayList = addRestDayList\r\n\r\n\r\n else:\r\n\r\n x = random.randint(0, 2)\r\n\r\n restDayList = addRestDayList\r\n\r\n\r\n dict, x = weekOptimize(dict, exercise, rest, a, b, x, restDayList)\r\n\r\n\r\n if trainingTimes == 5:\r\n\r\n\r\n if addRestDayListLength == 1:\r\n\r\n restDayList = rdlFunction(y, a, b, restDayList, addRestDayList)\r\n\r\n\r\n elif addRestDayListLength == 2:\r\n\r\n restDayList = addRestDayList\r\n\r\n\r\n else:\r\n\r\n x = random.randint(0, 2)\r\n\r\n restDayList = addRestDayList\r\n\r\n\r\n\r\n dict, x = weekOptimize(dict, exercise, rest, a, b, x, restDayList)\r\n\r\n\r\n\r\n if trainingTimes == 6:\r\n\r\n if addRestDayListLength == 1:\r\n\r\n restDayList = addRestDayList\r\n\r\n\r\n else:\r\n\r\n x = random.randint(0, 2)\r\n\r\n restDayList = addRestDayList\r\n\r\n\r\n dict, x = weekOptimize(dict, exercise, rest, a, b, x, restDayList)\r\n\r\n\r\n return dict, x\r\n\r\n\r\n\r\n\r\ndef randomizeFunction(a, b, trainingTimes, addRestDayList):\r\n\r\n restDayList = []\r\n\r\n\r\n if addRestDayList[0] == \"\":\r\n\r\n addRestDayListLength = 0\r\n\r\n else:\r\n\r\n addRestDayListLength = len(addRestDayList)\r\n\r\n\r\n for i in addRestDayList:\r\n\r\n restDayList.append(i)\r\n\r\n\r\n\r\n for i in range(0, 7 - trainingTimes - addRestDayListLength):\r\n\r\n randInt = random.randint(a, b)\r\n\r\n print(randInt, \"1-try\")\r\n\r\n\r\n while randInt in restDayList:\r\n\r\n randInt = random.randint(a, b)\r\n\r\n print(randInt, \"2-try\")\r\n\r\n\r\n restDayList.append(randInt)\r\n\r\n\r\n\r\n restDayList.sort()\r\n\r\n\r\n #vältetään neljän lepopäivän tuleminen\r\n x = restDayList[0]\r\n\r\n if x + 1 in restDayList and x + 2 in restDayList and x + 3 in restDayList:\r\n\r\n\r\n while True:\r\n\r\n\r\n randInt = random.randint(a, b)\r\n\r\n print(randInt, \"4S-try\")\r\n\r\n if randInt not in restDayList:\r\n\r\n\r\n #jotta added päivä ei lähde pois\r\n for i in range(0, len(restDayList)):\r\n\r\n if restDayList[i] not in addRestDayList:\r\n\r\n restDayList[i] = randInt\r\n\r\n break\r\n\r\n break\r\n\r\n\r\n\r\n restDayList.sort()\r\n\r\n\r\n return restDayList\r\n\r\n\r\n\r\ndef main():\r\n\r\n dict = {}\r\n\r\n a = 1\r\n b = 7\r\n x = 0\r\n\r\n addRestDayList = [\"\"]\r\n\r\n restDayList = []\r\n\r\n exercise = [\"Push\", \"Pull\", \"Legs\"]\r\n\r\n rest = [\" \"]\r\n\r\n\r\n optimize = input(\"Do you want to optimize the workout?(yes/no): \")\r\n\r\n\r\n trainingTimes = int(input(\"How many times you want to train per week?(yes/no): \"))\r\n\r\n\r\n randRest = input(\"Do you want to randomize your training and resting days?(yes/no): \")\r\n\r\n\r\n\r\n while b <= 7:\r\n\r\n\r\n\r\n if randRest == \"yes\":\r\n\r\n\r\n restDayList = randomizeFunction(a, b, trainingTimes, addRestDayList)\r\n\r\n print(restDayList)\r\n\r\n\r\n dict, x = week(dict, exercise, rest, a, b, x, restDayList, randRest, trainingTimes)\r\n\r\n\r\n print(dict)\r\n\r\n\r\n addRestDayList = input(\"Give additional rest days in between \" +\r\n str(a) + \" to \" + str(b) + \": \").split(\",\")\r\n\r\n\r\n #string ---> int\r\n if addRestDayList[0] != \"\":\r\n\r\n for i in range(0, len(addRestDayList)):\r\n\r\n addRestDayList[i] = int(addRestDayList[i])\r\n\r\n print(addRestDayList)\r\n\r\n\r\n\r\n\r\n\r\n if optimize == \"no\":\r\n\r\n dict, x = Pass(dict, rest, a, b, x, addRestDayList)\r\n\r\n\r\n\r\n\r\n if optimize == \"yes\":\r\n\r\n dict, x = RandomAndOptimize(dict, exercise, rest, a, b, x,\r\n randRest, restDayList, addRestDayList, trainingTimes)\r\n\r\n\r\n else:\r\n\r\n\r\n dict, x = week(dict, exercise, rest, a, b, x, restDayList, randRest, trainingTimes)\r\n\r\n print(dict)\r\n\r\n addRestDayList = input(\"Give additional rest days in between \" +\r\n str(a) + \" to \" + str(b) + \" (X,Y...): \").split(\",\")\r\n\r\n # string ---> int\r\n if addRestDayList[0] != \"\":\r\n\r\n for i in range(0, len(addRestDayList)):\r\n\r\n addRestDayList[i] = int(addRestDayList[i])\r\n\r\n\r\n if optimize == \"no\":\r\n\r\n dict, x = Pass(dict, rest, a, b, x, addRestDayList)\r\n\r\n\r\n if optimize == \"yes\":\r\n\r\n dict, x = Optimize(dict, exercise, rest, a, b, x,\r\n randRest, restDayList, addRestDayList, trainingTimes)\r\n\r\n\r\n\r\n print(dict)\r\n\r\n\r\n\r\n a += 7\r\n\r\n b += 7\r\n\r\n\r\nmain()","sub_path":"Three-Pronged/Push-Pull-Legs/Push-Pull-Legs.py","file_name":"Push-Pull-Legs.py","file_ext":"py","file_size_in_byte":9423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"520761950","text":"#new:当前对象创建的时候就会调用:\n#init方法:对象创建完毕之后会调用init方法,给对象添加属性及其初始化\n#创建对象调用两个方法,先调用new,new调用完毕之后,表示对象创建完成\n#然后调用init方法实例化\nclass Student(object):\n def __new__(cls,*args,**kwargs):\n\n print(\"创建了对象\")\n print(args,kwargs)\n #返回父类的new方法(调用类父类的方法)\n #new方法必须返回(相当于创建对象)\n return object.__new__(cls)\n\n #对象没有创建(初始化呢)\n def __init__(self,name,age,sex):\n\n self.name = name\n self.age = age\n #默认给对象添加属性\n print(\"初始化\")\n\n#模块 (线程)(异常)\n\nstu = Student(\"张三\",10,\"男\")\n\n#单例:设计模式,常用的设计模式\n\n#在应用中,不管创建多少次对象,都是一个对象\nclass Person(object):\n\n #私有属性\n __instance = None\n #创建对象\n def __new__(cls, *args, **kwargs):\n #第一次创建对象\n if cls.__instance == None:\n #创建对象\n print(\"创建对象\")\n #把创建的对象给类属性\n #object.__new__(cls)(调用类父类的方法)\n #相当于创建对象成功(instance是否为None)\n #创建出来的当前对象\n cls.__instance = object.__new__(cls)\n #如果__instance有值,直接返回__instance(第一次创建的对象)\n return cls.__instance\n def __init__(self,name,age):\n print(\"初始化\")\n\n#p1和p2是同一个对象\np1 = Person(\"zhangsan\",10)\n\np2 = Person(\"lisi\",20)\nprint(p1,p2)","sub_path":"python_basic/day07/06-new方法和单例.py","file_name":"06-new方法和单例.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"132081930","text":"import pickle\nimport copy\nimport itertools\n\nimport numpy as np\n\nimport events.events\nimport events.eventsequence\n\nevent_label_event_class_mapping = {\n 1: events.events.BallHitsBatEvent(time=None, player=None),\n 2: events.events.BallHitsTableEvent(time=None, player=None),\n 3: events.events.UnknownEvent(time=None)\n}\n\n\nclass Classification(object):\n \"\"\"The Classification as we receive it from the classifier.\"\"\"\n\n def __init__(self, labels, probabilities):\n super(Classification, self).__init__()\n self._labels = labels\n self._probabilities = probabilities\n\n def __repr__(self):\n return \"%s(%r)\" % (self.__class__, self.__dict__)\n\n @property\n def number_of_events(self):\n return len(self._labels)\n\n @property\n def number_of_labels(self):\n return self._probabilities.shape[1]\n\n @property\n def possible_labels(self):\n return np.array(list(range(self.number_of_labels)))\n\n def possible_event_sequences(self):\n label_sequences = self._possible_label_sequences()\n event_sequences = []\n\n for (probability, label_sequence) in label_sequences:\n event_sequence = events.eventsequence.EventSequence.from_list(\n label_sequence,\n event_label_event_class_mapping\n )\n event_sequences.append((probability, event_sequence))\n return event_sequences\n\n def _possible_label_sequences(self):\n labels = self._idx_to_label(self.possible_labels)\n possible_label_sequences = itertools.combinations_with_replacement(labels, self.number_of_events)\n label_sequences_with_probability = [\n (self.probability_of_sequence(np.array(label_sequence)), np.array(label_sequence))\n for label_sequence\n in possible_label_sequences\n ]\n label_sequences_with_probability.sort(key=lambda tup: tup[0], reverse=True)\n return label_sequences_with_probability[0:10]\n\n def _label_to_idx(self, labels):\n return copy.deepcopy(labels) - 1\n\n def _idx_to_label(self, labels):\n return copy.deepcopy(labels) + 1\n\n def probability_of_sequence(self, label_sequence):\n indices = self._label_to_idx(label_sequence)\n probabilities = self._probabilities[range(self.number_of_events), indices]\n return np.product(probabilities)\n\n @classmethod\n def form_file(cls, input_file):\n with open(input_file, 'rb') as file_handle:\n labels = pickle.load(file_handle)\n probabilities = pickle.load(file_handle)\n return Classification(labels=labels, probabilities=probabilities)","sub_path":"event_parsing/classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"147655391","text":"import os\nfrom flask_marshmallow import Marshmallow\nfrom flask_jwt_extended import JWTManager\n\njwt = JWTManager()\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\ndef config_init(app):\n \n # Database\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \\\n os.path.join(basedir, 'db.sqlite')\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n app.config['SECRET_KEY'] = '5eCReT'\n jwt.init_app(app)\n \n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"18131209","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 24 20:55:58 2019\n\n@author: mut, dd\n\nit combines the Dataframe from the Experiment with the\nFeatures from the Saved Features from the Model and save it in to\na csv datatable.\n\n\"\"\"\n\nimport sys\nimport pickle\nimport keras as ks\nimport tensorflow as tf\nfrom keras.utils import to_categorical\nfrom keras import models\nfrom keras import layers\nimport os\n#import exp_library as ex\nimport pandas as pd\nimport numpy as np\n\nfrom modules.library import get_img_paths,get_feature_paths,memory_usage,get_csv_paths\nfrom modules.library import getsize\n\nfrom time import time\nfrom keras.applications.inception_v3 import preprocess_input\nfrom modules.generators import ImageSequence\n\nimport json\n\nfrom os import listdir\nfrom os.path import isfile, join\n\n#fevea ist 1 Grad\nfovea = 15\n\n\nwith open(\"../input_file.json\") as data_file:\n config = json.load(data_file)\n \n \nDEFAULT_EYE_FIXATION_DAT = config[\"MEMORY\"]\nDEFAULT_IMAGE_DIRECTORY = 'mem_images/'\n\n\n\nDEFAULT_IMAGE_FEATURES_DIRECTORY = \"/mnt/data/DATA/dataset/FEATURES/saved_features_from_pictures/inception/\"\n\n#feature_data_dir =\"/mnt/data/mendel_moved/data/saved_features_from_pictures/color_lowpass.pickle\"\n\n#experiment data tables\nMEMORY = config[\"MEMORY\"]\nSEARCH = config[\"SEARCH\"]\n\n#input images paths for different imagetypes\nMEMORY_COLOR = config[\"MEMORY_COLOR\"]\nMEMORY_GRAYSCALE = config[\"MEMORY_GRAYSCALE\"]\nSEARCH_COLOR = config[\"SEARCH_COLOR\"]\nSEARCH_GRAYSCALE = config[\"SEARCH_GRAYSCALE\"]\n\n\n\nIMAGE_DIRECTORY = \"\"\nIMAGE_FEATURES_DIRECTORY = \"\"\n\nall_data_uncleared = pd.read_table(\n DEFAULT_EYE_FIXATION_DAT,encoding = \"ISO-8859-1\")\n\nall_data = all_data_uncleared.loc[\n (all_data_uncleared[\"fixposx\"] >= fovea) &\n (all_data_uncleared[\"fixposx\"] <= 1024 - fovea) &\n (all_data_uncleared[\"fixposy\"] >= fovea) &\n (all_data_uncleared[\"fixposy\"] <= 768 - fovea) &\n (all_data_uncleared[\"fixinvalid\"] != 1) & \n (all_data_uncleared[\"sacinvalid\"] != 1)\n ]\n\n\ndata = pd.DataFrame()\n\n\n\nonlyfiles = [f for f in listdir(DEFAULT_IMAGE_FEATURES_DIRECTORY) if isfile(join(DEFAULT_IMAGE_FEATURES_DIRECTORY, f))]\n\n\nloaded_features = []\n\n\n\nfor i,file in enumerate(onlyfiles):\n loaded_features = pd.read_pickle(DEFAULT_IMAGE_FEATURES_DIRECTORY+file)\n \n\n\n for image_index in range(len(loaded_features)):\n print(\"image index: \", image_index)\n \n pic_id = loaded_features[image_index][\"pic_id\"]\n pic_type = loaded_features[image_index][\"type\"]\n image_shape = loaded_features[image_index][\"shape\"]\n \n print(\"file name\",file)\n print(\"pic id \", pic_id)\n \n if loaded_features[image_index][\"type\"] == \"color_original\":\n #masktype == 0 & maskregion == 0: Kontrollbedingung\n print(\"pic_type\", pic_type)\n selected_data = all_data.loc[ \n (all_data[\"imageid\"] == int(pic_id))&\n ((all_data[\"colorimages\"] == 1) )&\n ((all_data[\"masktype\"] == 0) | (all_data[\"masktype\"] == 1) \n | (all_data[\"masktype\"] == 2) ) &\n ((all_data[\"maskregion\"] == 0 ) | (all_data[\"maskregion\"] == 1 ) \n | (all_data[\"maskregion\"] == 2 ) )\n ,:] \n \n \n elif loaded_features[image_index][\"type\"] == \"color_high-pass\":\n #masktype == 0 & maskregion == 0: Kontrollbedingung\n #masktype == 2 & maskregion == 1: peripherer Hochpassfilter\n #masktype == 2 & maskregion == 2: zentraler Hochpassfilter\n print(\"pic_type\", pic_type)\n selected_data = all_data.loc[\n (all_data[\"imageid\"] == int(pic_id))&\n ((all_data[\"colorimages\"] == 1) )&\n ((all_data[\"masktype\"] == 0) | (all_data[\"masktype\"] == 2) ) &\n ((all_data[\"maskregion\"] == 0 ) | (all_data[\"maskregion\"] == 1 ) \n | (all_data[\"maskregion\"] == 2 ) )\n ,:] \n \n elif loaded_features[image_index][\"type\"] == \"color_low-pass\":\n #masktype == 0 & maskregion == 0: Kontrollbedingung\n #masktype == 1 & maskregion == 1: peripherer Tiefpassfilter\n #masktype == 1 & maskregion == 2: zentraler Tiefpassfilter\n print(\"pic_type\", pic_type)\n selected_data = all_data.loc[ \n (all_data[\"imageid\"] == int(pic_id))&\n ((all_data[\"colorimages\"] == 1) | (all_data[\"colorimages\"] == 1) )&\n ((all_data[\"masktype\"] == 0) | (all_data[\"masktype\"] == 1) ) &\n ((all_data[\"maskregion\"] == 0 ) | (all_data[\"maskregion\"] == 1 ) \n | (all_data[\"maskregion\"] == 2 ) )\n ,:] \n \n elif loaded_features[image_index][\"type\"] == \"greyscale_original\":\n #masktype == 0 & maskregion == 0: Kontrollbedingung\n print(\"pic_type\", pic_type)\n selected_data = all_data.loc[ (\n all_data[\"imageid\"] == int(pic_id))&\n ((all_data[\"colorimages\"] == 0) )&\n ((all_data[\"masktype\"] == 0) | (all_data[\"masktype\"] == 1)\n | (all_data[\"masktype\"] == 2) ) &\n ((all_data[\"maskregion\"] == 0 ) | (all_data[\"maskregion\"] == 1 )\n | (all_data[\"maskregion\"] == 2 ) )\n ,:] \n \n elif loaded_features[image_index][\"type\"] == \"greyscale_high-pass\":\n #masktype == 0 & maskregion == 0: Kontrollbedingung\n #masktype == 2 & maskregion == 1: peripherer Hochpassfilter\n #masktype == 2 & maskregion == 2: zentraler Hochpassfilter\n print(\"pic_type\", pic_type)\n selected_data = all_data.loc[ (\n all_data[\"imageid\"] == int(pic_id))&\n ((all_data[\"colorimages\"] == 1) | (all_data[\"colorimages\"] == 1) )&\n ((all_data[\"masktype\"] == 0) | (all_data[\"masktype\"] == 2) ) &\n ((all_data[\"maskregion\"] == 0 ) | (all_data[\"maskregion\"] == 1 ) \n | (all_data[\"maskregion\"] == 2 ) )\n ,:] \n \n elif loaded_features[image_index][\"type\"] == \"greyscale_low-pass\":\n #masktype == 0 & maskregion == 0: Kontrollbedingung\n #masktype == 1 & maskregion == 1: peripherer Tiefpassfilter\n #masktype == 1 & maskregion == 2: zentraler Tiefpassfilter\n print(\"pic_type\", pic_type)\n selected_data = all_data.loc[ (\n all_data[\"imageid\"] == int(pic_id))&\n ((all_data[\"colorimages\"] == 0) )&\n ((all_data[\"masktype\"] == 0) | (all_data[\"masktype\"] == 1)\n | (all_data[\"masktype\"] == 2) ) &\n ((all_data[\"maskregion\"] == 1 ) | (all_data[\"maskregion\"] == 0 )\n | (all_data[\"maskregion\"] == 2 ) )\n ,:] \n \n \n img_h, img_w = image_shape[0], image_shape[1]\n \n all_layers = pd.DataFrame()\n \n #get the layer activation and ad it with axis =1 example 256 + 256 +...+ 2048\n for layer in range(len(loaded_features[image_index]['features'])):\n \n #layershape\n part_h = loaded_features[image_index]['features'][layer][0].shape[0]\n part_w = loaded_features[image_index]['features'][layer][0].shape[1]\n \n #scale factors for the particular feature\n scale_h = img_h / part_h\n scale_w = img_w / part_w\n \n \n #auf feature skalierte fovea\n scaled_fovea_y = round(fovea / scale_h)\n scaled_fovea_x = round(fovea / scale_w)\n \n #auf feature skalierte Fixation\n scaled_fix_x = (selected_data[\"fixposx\"] / scale_w).astype(int)\n scaled_fix_y = (selected_data[\"fixposy\"] / scale_h).astype(int)\n \n \n \n #Bereiche der skalierten Fovea, die vom Features extrahiert werden\n scaled_fix_y0 = scaled_fix_y - scaled_fovea_y\n scaled_fix_y1 = scaled_fix_y + scaled_fovea_y + 1\n scaled_fix_x0 = scaled_fix_x - scaled_fovea_x\n scaled_fix_x1 = scaled_fix_x + scaled_fovea_x + 1\n \n \n \n #define np, leere list von array als Platzhalter für die Features\n fix_activations = np.array(\n np.zeros(\n shape=(\n selected_data.shape[0],\n loaded_features[image_index]['features'][layer][0].shape[2])))\n \n loaded_features[image_index]['features'][0].shape\n \n ##selected_data.shape\n #get the activations from each layer\n for fix in range(selected_data.shape[0]):\n fix_activations[fix,:] = loaded_features[\n image_index]['features'][layer][0][ \n scaled_fix_y0.iloc[fix]:scaled_fix_y1.iloc[fix],\n scaled_fix_x0.iloc[fix]:scaled_fix_x1.iloc[fix], \n :].mean(axis=(0,1))\n \n \n \n #save the activations in Dataframe\n #jede Layer wird auf axis 1 zusätzlich geadded\n all_layers = pd.concat([all_layers,\n pd.DataFrame(fix_activations)], \n axis=1)\n #debug\n selected_data.shape\n all_layers.shape\n \n \n #um die die Daten zu konkatinieren muss die Index geresetet werden\n selected_data = selected_data.reset_index()\n all_layers = all_layers.reset_index()\n \n all_layers_16 = all_layers.astype(\"float16\")\n all_layers_16[\"index\"] = all_layers_16.index.astype(\"uint8\")\n\n \n #the selected experimental data is concatinated with features\n data_16 = pd.concat([selected_data, all_layers_16], \n axis=1,\n ignore_index=False) \n \n \n print('16 Memory used:', memory_usage(data_16), 'Mb')\n \n #data_16.to_pickle(\"saved/\"+str(pic_type)+\"/Output_\"+str(pic_type)+\"_picture_\"+str(pic_id)+\".h5\")\n data_16.to_csv(\"saved/\"+str(pic_type)+\"/Output_\"+str(pic_type)+\"_picture_\"+str(pic_id)+\".csv\")\n \n\n\n#Loaded_Result_1 = pd.read_pickle(\"saved/\"+str(pic_type)+\"/Output_\"+str(pic_type)+\"_picture_\"+str(pic_id)+\".h5\")\n\n \n \n#Überprüft wie viele grow die Spalte ist\n#for i in range(50):\n# Loaded_Result = pd.read_pickle(\"saved/Output_\"+str(i+1)+\".h5\")\n# print(i,\" \",data.shape)\n# shape = Loaded_Result.shape[0]\n# summe = summe + shape\n#print(summe)\n# \n\n","sub_path":"feature_analyse_project/getfeatures_from_images.py","file_name":"getfeatures_from_images.py","file_ext":"py","file_size_in_byte":10850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"246154677","text":"from django import forms\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.core.mail import EmailMessage\nfrom django.db.models import Q\nfrom django.forms import ModelForm\nfrom django.template.loader import render_to_string\n\nfrom arcutils.ldap import escape, ldapsearch\n\nfrom .models import Item, Location, Category, Status, Action\n\n\ndef check_ldap(username):\n \"\"\"Check LDAP to ensure a user name exists.\"\"\"\n q = escape(username)\n search = '(uid={q}*)'.format(q=q)\n results = ldapsearch(search)\n return bool(results)\n\n\ndef create_user(first_name, last_name, email):\n \"\"\"Create a new user, ensuring their username is unique.\"\"\"\n user_model = get_user_model()\n\n i = 0\n username_template = '{first_name}_{last_name}{i}'\n username = username_template.format(**locals())\n while user_model.objects.filter(username=username).exists():\n i += 1\n username = username_template.format(**locals())\n\n user = user_model.objects.create(\n first_name=first_name,\n last_name=last_name,\n email=email,\n username=username,\n is_active=False,\n is_staff=False)\n\n return user\n\n\nclass AdminActionForm(forms.Form):\n\n \"\"\"Form used on the admin-action page.\"\"\"\n\n action_choice = forms.ModelChoiceField(queryset=Action.objects.all(), empty_label=None)\n note = forms.CharField(widget=forms.Textarea, required=False)\n first_name = forms.CharField(required=False)\n last_name = forms.CharField(required=False)\n email = forms.EmailField(required=False)\n\n def __init__(self, *args, current_user, **kwargs):\n self.user = current_user\n super(AdminActionForm, self).__init__(*args, **kwargs)\n\n if not self.user.is_staff:\n # Don't allow lab attendants to select an action since they\n # are only allowed to return items. This is enforced in the\n # clean() method.\n self.fields.pop('action_choice')\n\n def checkout_email(self, item):\n \"\"\"Send an email to all the admins when a valuable item is checked out.\"\"\"\n subject = 'Valuable item checked out'\n to = settings.ITS.CHECKOUT_EMAIL_TO\n from_email = settings.DEFAULT_FROM_EMAIL\n\n ctx = {\n 'found_on': str(item.found_on),\n 'possible_owner': item.possible_owner,\n 'returned_by': str(item.last_status.performed_by),\n 'returned_to': str(item.returned_to),\n 'found_in': item.location.name,\n 'category': item.category.name,\n 'description': item.description\n }\n\n message = render_to_string('items/emails/checkout.txt', ctx)\n\n EmailMessage(subject, message, to=to, from_email=from_email).send()\n\n def clean(self):\n cleaned_data = super().clean()\n\n if self.user.is_staff:\n # Staff must select an action.\n action_choice = cleaned_data.get('action_choice')\n else:\n # Lab attendants may only return items.\n action_choice = Action.objects.get(machine_name=Action.RETURNED)\n\n self.cleaned_data['action_choice'] = action_choice\n action = action_choice.machine_name if action_choice else None\n\n note = cleaned_data.get('note')\n first_name = cleaned_data.get('first_name')\n last_name = cleaned_data.get('last_name')\n email = cleaned_data.get('email')\n\n if action == Action.RETURNED:\n if not first_name:\n self.add_error('first_name', 'First name required.')\n if not last_name:\n self.add_error('last_name', 'Last name required.')\n if not email:\n self.add_error('email', 'Email required.')\n\n if action == Action.OTHER:\n if not note:\n self.add_error('note', 'Note required when choosing action of type Other.')\n\n return cleaned_data\n\n def save(self, *args, item_pk, current_user, **kwargs):\n \"\"\"If an item is being returned, create a new user for the\n person the item is being returned to if they don't already\n exist. Then send an email to the staff mailing list if the item\n is valuable.\n\n If an item is being set to checked in, set it's returned_to\n field to None.\n\n \"\"\"\n item = Item.objects.get(pk=item_pk)\n action_choice = self.cleaned_data['action_choice']\n first_name = self.cleaned_data.get('first_name')\n last_name = self.cleaned_data.get('last_name')\n email = self.cleaned_data.get('email')\n Status.objects.create(\n item=item, action_taken=action_choice, note=self.cleaned_data['note'],\n performed_by=current_user)\n\n # If they chose to change status to checked in we need to make sure to\n # set the returned_to field to None\n if action_choice.machine_name == Action.CHECKED_IN:\n item.returned_to = None\n elif action_choice.machine_name == Action.RETURNED:\n user_model = get_user_model()\n returned_user = user_model.objects.filter(\n first_name__iexact=first_name,\n last_name__iexact=last_name,\n email__iexact=email\n ).first()\n if returned_user is None:\n returned_user = create_user(first_name, last_name, email)\n item.returned_to = returned_user\n if item.is_valuable:\n self.checkout_email(item)\n\n item.save()\n return item\n\n\nclass AdminItemFilterForm(forms.Form):\n\n \"\"\"Administrative item filter form for the admin item list page.\"\"\"\n\n sort_choices = (\n ('-pk', 'Found most recently'),\n ('pk', 'Found least recently'),\n ('location', 'Location'),\n ('category', 'Category'),\n ('description', 'Description'),\n ('possible_owner', 'Possible owner'),\n )\n\n admin_item_choices = (\n ('active', 'Active'),\n ('archived', 'Archived only'),\n ('valuable', 'Valuable only'),\n )\n\n location = forms.ModelChoiceField(queryset=Location.objects.all(), required=False)\n category = forms.ModelChoiceField(queryset=Category.objects.all(), required=False)\n sort_by = forms.ChoiceField(choices=sort_choices, required=False)\n items = forms.ChoiceField(\n choices=admin_item_choices, required=False, initial=admin_item_choices[0][0])\n keyword_or_last_name = forms.CharField(max_length=50, required=False)\n\n def filter(self):\n filters = {}\n valid = self.is_valid()\n\n if valid:\n items = self.cleaned_data.get('items')\n\n if items == 'active':\n # Show unarchived only and both valuable & not valuable\n filters['is_archived'] = False\n elif items == 'archived':\n # Show archived only and both valuable & not valuable\n filters['is_archived'] = True\n elif items == 'valuable':\n # Show valuable only and both archived & not archived\n filters['is_valuable'] = True\n\n location = self.cleaned_data.get('location')\n if location:\n filters['location'] = self.cleaned_data['location']\n\n category = self.cleaned_data.get('category')\n if category:\n filters['category'] = self.cleaned_data['category']\n\n search_term = self.cleaned_data.get('keyword_or_last_name')\n if search_term:\n keyword_filter = (\n Q(description__icontains=search_term) |\n Q(possible_owner__last_name__icontains=search_term)\n )\n else:\n keyword_filter = None\n else:\n filters['is_archived'] = False\n keyword_filter = None\n\n item_list = Item.objects.filter(**filters)\n\n if keyword_filter:\n item_list = item_list.filter(keyword_filter)\n\n if valid:\n order_by = self.cleaned_data.get('sort_by') or '-pk'\n else:\n order_by = '-pk'\n\n item_list = item_list.order_by(order_by, '-is_archived')\n\n return item_list\n\n\nclass ItemFilterForm(AdminItemFilterForm):\n\n \"\"\"Item filter form for the regular item list page.\"\"\"\n\n item_choices = (\n ('active', 'Active'),\n ('valuable', 'Valuable only'),\n )\n\n items = forms.ChoiceField(choices=item_choices, required=False, initial=item_choices[0][0])\n\n def filter(self):\n \"\"\"Update filter so lab attendants can only see items with CHECKED_IN status.\"\"\"\n item_list = super(ItemFilterForm, self).filter()\n item_list = item_list.filter(laststatus__machine_name=Action.CHECKED_IN)\n return item_list\n\n\nclass ItemArchiveForm(forms.Form):\n\n \"\"\"Item archiving form used on the administrative item listing page.\"\"\"\n\n def __init__(self, *args, item_list, **kwargs):\n \"\"\"Setup a pre-filled checkbox, based on the item's current archived status.\"\"\"\n super(ItemArchiveForm, self).__init__(*args, **kwargs)\n\n self.item_list = item_list\n for item in item_list:\n field = forms.BooleanField(\n initial=item.is_archived, required=False,\n widget=forms.CheckboxInput(attrs={'class': 'checkbox_archive'}))\n self.fields['archive-%d' % item.pk] = field\n\n def __iter__(self):\n \"\"\"when iterating over this form, add archive-item.pk to each item.\"\"\"\n for item in self.item_list:\n yield item, self['archive-%d' % item.pk]\n\n def save(self):\n \"\"\"If an item is in the list, swap the items archived status.\"\"\"\n changed = False\n\n for item in self.item_list:\n is_archived = self.cleaned_data.get(\"archive-%d\" % item.pk)\n\n if item.is_archived is not is_archived:\n item.is_archived = is_archived\n item.save()\n changed = True\n\n return changed\n\n\nclass CheckInForm(ModelForm):\n\n class Meta:\n model = Item\n fields = ('location', 'category', 'description', 'is_valuable')\n\n username = forms.CharField(\n required=False, label='Odin username',\n help_text='Start typing a username for suggestions')\n possible_owner_found = forms.BooleanField(required=False)\n first_name = forms.CharField(required=False)\n last_name = forms.CharField(required=False)\n email = forms.EmailField(required=False)\n\n def checkin_email(self, item):\n \"\"\"Send an email to all the admins when a valuable item is checked in.\"\"\"\n subject = 'Valuable item checked in'\n to = settings.ITS.CHECKIN_EMAIL_TO\n from_email = settings.DEFAULT_FROM_EMAIL\n message = render_to_string('items/emails/checkin.txt', {'item': item})\n EmailMessage(subject, message, to=to, from_email=from_email).send()\n\n def user_checkin_email(self, item, possible_owner):\n \"\"\"Send an email to a possible owner when an item they own is checked in.\"\"\"\n subject = 'An item belonging to you was found'\n to = [possible_owner.email]\n from_email = settings.DEFAULT_FROM_EMAIL\n if item.category.machine_name == Category.USB:\n template = 'items/emails/user_checkin_usb.txt'\n elif item.category.machine_name == Category.ID:\n template = 'items/emails/user_checkin_id.txt'\n else:\n template = 'items/emails/user_checkin_all_other.txt'\n message = render_to_string(template, {'item': item})\n EmailMessage(subject, message, to=to, from_email=from_email).send()\n\n def clean(self):\n cleaned_data = super(CheckInForm, self).clean()\n if cleaned_data.get('possible_owner_found'):\n if not cleaned_data.get('first_name'):\n self.add_error('first_name', 'First name required')\n if not cleaned_data.get('last_name'):\n self.add_error('last_name', 'Last name required')\n if not cleaned_data.get('email'):\n self.add_error('email', 'Email required')\n username = cleaned_data.get('username')\n if username and not check_ldap(username):\n self.add_error(\n 'username', 'Invalid username; enter a valid username or leave blank')\n return cleaned_data\n\n def save(self, *args, current_user, **kwargs):\n user_first_name = self.cleaned_data['first_name']\n user_last_name = self.cleaned_data['last_name']\n user_email = self.cleaned_data['email']\n\n # If an owner was found we need to record them as an owner. This\n # may require that a new user is created.\n if self.cleaned_data.get('possible_owner_found'):\n user_model = get_user_model()\n checkin_user = user_model.objects.filter(\n first_name__iexact=user_first_name,\n last_name__iexact=user_last_name,\n email__iexact=user_email\n ).first()\n if checkin_user is None:\n checkin_user = create_user(user_first_name, user_last_name, user_email)\n self.instance.possible_owner = checkin_user\n\n item = super(CheckInForm, self).save(*args, **kwargs)\n new_action = Action.objects.get(machine_name=Action.CHECKED_IN)\n Status.objects.create(\n item=item, action_taken=new_action, note='Initial check-in', performed_by=current_user)\n\n if self.cleaned_data['possible_owner_found']:\n self.user_checkin_email(item, checkin_user)\n\n if self.cleaned_data['is_valuable']:\n self.checkin_email(item)\n\n return item\n","sub_path":"lostandfound/items/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":13638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"584298505","text":"from flask import Flask, request, render_template\nimport pyodbc\n\nconn = pyodbc.connect('DRIVER={FreeTDS};SERVER=localhost;PORT=1433;UID=sa;PWD=Virtual1234;DATABASE'\n '=Restaurant;UseNTLMv2=yes;TDS_Version=8.0;Trusted_Domain=domain.local;')\n\napp = Flask(__name__)\n\nuser_data = {\n 'Name': ''\n}\n\n\n@app.route('/')\ndef home():\n return render_template('index.html', user_data=user_data)\n\n\n@app.route('/register', methods=['POST'])\ndef register():\n cursor = conn.cursor()\n username = request.form['Username']\n cursor.execute(\"select dbo.CheckUsernameExists(?)\", username)\n res = cursor.fetchone()\n if res[0]:\n return \"Username already exists\"\n email = request.form['Email']\n cursor.execute(\"select dbo.CheckEmailExists(?)\", email)\n res = cursor.fetchone()\n if res[0]:\n return \"Email already exists\"\n cursor.execute(\"exec dbo.Register ?, ?, ?, ?\", (username, email, request.form['Password'], request.form['Address']))\n res = cursor.fetchone()\n if res[1] == username:\n global user_data\n user_data['Name'] = res[1]\n return \"OK\"\n else:\n return \"Registration failed\"\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n username = request.form['username']\n cursor = conn.cursor()\n cursor.execute(\"select dbo.Login(?, ?)\", (username, request.form['password']))\n res = cursor.fetchone()\n if res[0]:\n global user_data\n user_data['Name'] = username\n return render_template('login.html', user_data=user_data)\n else:\n return \"Wrong credentials\"\n else:\n return render_template('login.html', user_data=user_data)\n\n\n@app.route('/items', methods=['GET'])\ndef items():\n cursor = conn.cursor()\n cursor.execute(\"select * from dbo.Items\")\n return render_template('items.html', data=cursor, user_data=user_data)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port='5000')","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"164273398","text":"qtd_vezes = int(input())\nlista_valores = []\n\nwhile qtd_vezes > 0:\n n_uns = (int(input()) - 1)\n lista = [1, ]\n\n while len(lista) <= n_uns:\n \n if lista[-1] == 1:\n lista.append(-1)\n else:\n lista.append(1)\n\n lista_valores.append(sum(lista))\n qtd_vezes = qtd_vezes - 1\n\nfor i in lista_valores:\n print(i)\n","sub_path":"desafio_1866.py","file_name":"desafio_1866.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"125747500","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 25 15:10:30 2021\r\n\r\n@author: nandini.ananthan\r\n\"\"\"\r\n\r\nT = [73, 74, 75, 71, 69, 72, 76, 73]\r\nOP = [1, 1, 4, 2, 1, 1, 0, 0]\r\n\r\nclass Solution:\r\n def dailyTemperatures(self, T: List[int]) -> List[int]:\r\n res = [0] * len(T)\r\n stack = [len(T) - 1]\r\n \r\n for i in range(len(T)-2, -1, -1):\r\n while stack and T[i] >= T[stack[-1]]:\r\n stack.pop()\r\n if stack:\r\n res[i] = (stack[-1] - i)\r\n else:\r\n res[i] = 0\r\n stack.append(i)\r\n return res \r\n \r\n \r\n \r\n \r\n ","sub_path":"Data Structures/Array/739. Daily Temperatures.py","file_name":"739. Daily Temperatures.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"62351463","text":"from bs4 import BeautifulSoup\nimport pandas as pd\nimport re\nimport requests\n\n\n#response = requests.get('https://www.residentadvisor.net/events/1246651')\n\n#soup = BeautifulSoup(response.content, 'html.parser')\n\n# text_file = open('ra_2a.txt', 'w')\n# text_file.write(soup.prettify())\n\n#links = soup.find_all('a')\n\ndef _get_event_ids():\n \"\"\"Get list of events.\"\"\"\n\n events_df = pd.DataFrame()\n\n response = requests.get('https://www.residentadvisor.net/events/us/newyork/week/2019-05-19')\n soup = BeautifulSoup(response.content, 'html.parser')\n links = soup.find_all('a')\n\n for link in links:\n event_link = link.get('href')\n\n if event_link:\n x = re.findall('/events/[0-9]+(? 0:\n return\n\n days = [Day.MONDAY, Day.TUESDAY, Day.WEDNESDAY, Day.THURSDAY, Day.FRIDAY, Day.SATURDAY, Day.SUNDAY]\n\n for day in days:\n Day.objects.create(name=day)\n\n\ndef create_campus(post=False):\n data = {\n 'name': 'North Campus'\n }\n\n if post:\n return data\n\n return Campus.objects.create(**data)\n\n\ndef create_semester(post=False):\n campus = create_campus()\n start = datetime(2018, 5, 20, 0, 0, 0)\n end = start + timedelta(days=130)\n data = {\n 'name': 'Semester ' + str(randint(1, 2)),\n 'campus': campus,\n 'start': timezone.make_aware(start),\n 'end': timezone.make_aware(end),\n }\n\n if post:\n data['campus'] = campus.id\n data['start'] = data['start'].isoformat()\n data['end'] = data['start'].isoformat()\n return data\n\n return Semester.objects.create(**data)\n\n\ndef create_subject(post=False):\n # curframe = inspect.currentframe()\n # calframe = inspect.getouterframes(curframe, 2)\n # print('Calling by', calframe[1][3], '...')\n subject_list = [\n {'name': 'Chinese', 'code': 'CHN', 'selective': False},\n {'name': 'Math', 'code': 'MTH', 'selective': False},\n {'name': 'Music', 'code': 'MUS', 'selective': False},\n {'name': 'English', 'code': 'ENG', 'selective': False},\n {'name': 'Arts', 'code': 'ART', 'selective': False},\n ]\n lucky = None\n for subject in subject_list:\n if Subject.objects.filter(name=subject['name']).count() == 0:\n lucky = subject\n\n if not lucky:\n lucky = {\n 'name': faker.name(),\n 'code': faker.ean8(),\n 'selective': False,\n }\n\n data = {\n 'name': lucky['name'],\n 'code': lucky['code'],\n 'selective': lucky['selective']\n }\n\n if post:\n return data\n\n return Subject.objects.create(**data)\n\n\ndef create_teacher(subject, post=False):\n genders = [Teacher.MALE, Teacher.FEMALE]\n\n staff_code = ''.join([str(randint(0, 9)) for x in range(10)])\n data = {\n 'name': faker.name(),\n 'grade': randint(1, 6),\n 'gender': genders[randint(0, 1)],\n 'staff_code': staff_code,\n 'age': randint(20, 80),\n 'phone': faker.phone_number(),\n 'subject': subject,\n }\n if post:\n data['subject'] = subject.id\n return data\n\n return Teacher.objects.create(**data)\n\n\ndef create_grade(post=False):\n data = {\n 'name': faker.name()\n }\n if post:\n return data\n\n return Grade.objects.create(**data)\n\n\ndef create_course(semester, grade, post=False):\n subjects = Subject.objects.all()\n subject = choice(subjects)\n\n code = randint(100, 500)\n data = {\n 'code': code,\n 'title': choice([\"语文\", \"数学\", \"英语\", \"物理\", \"化学\", \"政治\", \"体育\", \"音乐\"]) + str(code),\n 'description': faker.sentences(nb=1),\n 'subject': subject,\n 'hours': 90,\n 'semester': semester,\n 'grade': grade,\n }\n\n if post:\n data['subject'] = subject.id\n data['semester'] = semester.id\n data['grade'] = grade.id\n return data\n\n return Course.objects.create(**data)\n\n\ndef create_building(post=False):\n data = {\n 'name': faker.name(),\n 'campus': create_campus(),\n }\n\n if post:\n data['campus'] = data['campus'].id\n return data\n\n return Building.objects.create(**data)\n\n\ndef create_classroom(building, post=False):\n data = {\n 'name': faker.name(),\n 'sequence': randint(100, 500),\n 'available': True,\n 'building': building,\n }\n\n if post:\n data['building'] = data['building'].id\n return data\n\n return Classroom.objects.create(**data)\n\n\ndef create_classrooms(building, number=50):\n for i in range(number):\n create_classroom(building)\n\n\ndef populate_subjects_table(nsubjects=5):\n return [create_subject() for i in range(nsubjects)]\n\n\ndef populate_grades_table(ngrades=6):\n return [create_grade() for i in range(ngrades)]\n\n\ndef populate_courses_table(semester, ncourses):\n grades = Grade.objects.all()\n return [create_course(semester, choice(grades)) for i in range(ncourses)]\n\n\ndef populate_teachers_table(nteachers=50):\n subjects = Subject.objects.all()\n return [create_teacher(subject=choice(subjects)) for i in range(nteachers)]\n\n\ndef populate_class_days(semester, grade):\n populate_days_table()\n\n next_date = semester.start\n total = (semester.end - semester.start).days\n\n for i in range(total):\n weekday_number = int(next_date.strftime('%w'))\n if 0 < weekday_number < 6: # not Saturday(6) and Sunday(0)\n morning_start = next_date + timedelta(hours=8)\n morning_end = morning_start + timedelta(hours=4)\n afternoon_start = morning_end + timedelta(hours=2)\n afternoon_end = afternoon_start + timedelta(hours=3)\n class_day = ClassDay.objects.create(\n semester=semester,\n grade=grade,\n date=next_date,\n max_nclass=7,\n num_arranged=0,\n num_available=7,\n morning_start=morning_start,\n morning_end=morning_end,\n afternoon_start=afternoon_start,\n afternoon_end=afternoon_end,\n )\n DailySchedule.objects.create(day=Day.objects.get(name=next_date.strftime('%a')),\n weekly_schedule=WeeklySchedule.objects.create(semester=semester,\n week_number=10))\n # print('Class day created:', class_day)\n populate_available_sequence(class_day)\n next_date = next_date + timedelta(days=1)\n\n\ndef populate_classroom_available_sequences(semester, classes_per_day):\n next_date = semester.start\n total = (semester.end - semester.start).days\n classrooms = Classroom.objects.all()\n for i in range(total):\n weekday_number = int(next_date.strftime('%w'))\n if 0 < weekday_number < 6: # not Saturday(6) and Sunday(0)\n for classroom in classrooms:\n for j in range(1, classes_per_day + 1):\n classroom_sequence = ClassroomAvailableSequence.objects.create(\n date=next_date,\n classroom=classroom,\n sequence=j,\n )\n # print(classroom_sequence)\n next_date += timedelta(days=1)\n\n\ndef populate_teachers_available_sequences(semester, classes_per_day):\n next_date = semester.start\n total = (semester.end - semester.start).days\n teachers = Teacher.objects.all()\n for i in range(total):\n weekday_number = int(next_date.strftime('%w'))\n if 0 < weekday_number < 6: # not Saturday(6) and Sunday(0)\n for teacher in teachers:\n for j in range(1, classes_per_day + 1):\n teacher_available_sequence = TeacherAvailableSequence.objects.create(\n date=next_date,\n teacher=teacher,\n sequence=j,\n )\n # print(classroom_sequence)\n next_date += timedelta(days=1)\n\n\ndef populate_available_sequence(class_day):\n for i in range(1, class_day.max_nclass + 1):\n available_sequence = ClassdayAvailableSequence.objects.create(\n class_day=class_day,\n sequence=i,\n )\n # print(available_sequence)\n\n\ndef populate_course_teacher_table():\n courses = Course.objects.all()\n teachers = Teacher.objects.all()\n\n correlations = []\n for course in courses:\n correlations.append(CourseTeacher.objects.create(course=course, teacher=choice(teachers)))\n\n return correlations\n\n\ndef initiate_fake_data_for_class_arrangements(settings):\n building = create_building()\n create_classrooms(building, settings['nclassrooms'])\n semester = create_semester()\n populate_classroom_available_sequences(semester=semester, classes_per_day=settings['classes_per_day'])\n populate_subjects_table(settings['nsubjects'])\n grades = populate_grades_table(settings['ngrades'])\n for grade in grades:\n populate_class_days(semester, grade=grade)\n populate_courses_table(ncourses=settings['ncourses'], semester=semester)\n populate_teachers_table(settings['nteachers'])\n populate_course_teacher_table()\n populate_teachers_available_sequences(semester, classes_per_day=settings['classes_per_day'])\n\n\ndef create_weekly_schedule(semester, post=False):\n start = semester.start\n end = semester.end\n days = (end - start).days\n\n data = {\n 'week_number': randint(1, days),\n 'semester': semester,\n }\n\n if post:\n data['semester'] = data['semester'].id\n return data\n\n return WeeklySchedule.objects.create(**data)\n\n\ndef create_daily_schedule(semester, post=False):\n populate_days_table()\n data = {\n 'day': Day.objects.order_by('?').first(),\n 'weekly_schedule': create_weekly_schedule(semester=semester),\n }\n\n if post:\n data['weekly_schedule'] = data['weekly_schedule'].id\n return data\n\n return DailySchedule.objects.create(**data)\n\n\ndef create_arranged_class(semester, grade, post=False, data=None):\n populate_class_days(semester, grade)\n if not data:\n class_days = ClassDay.objects.filter(semester=semester)\n class_day = choice(class_days)\n random_start = class_day.morning_start\n random_end = random_start + timedelta(hours=2)\n course = create_course(semester, grade)\n subject = course.subject\n data = {\n 'start': random_start,\n 'end': random_end,\n 'teacher': create_teacher(subject),\n 'course': course,\n 'daily_schedule': create_daily_schedule(semester=course.semester),\n 'classroom': create_classroom(building=create_building()),\n 'sequence': randint(1, 7),\n 'class_day': class_day,\n }\n\n if post:\n data['teacher'] = data['teacher'].id\n data['course'] = data['course'].id\n data['daily_schedule'] = data['daily_schedule'].id\n data['classroom'] = data['classroom'].id\n data['start'] = data['start'].strftime('%Y-%m-%d %H:%M:%S')\n data['end'] = data['end'].strftime('%Y-%m-%d %H:%M:%S')\n data['class_day'] = data['class_day'].id\n # print('Arranged Class Data:', data)\n return data\n\n return ArrangedClass.objects.create(**data)\n\n","sub_path":"arrangements/tests/common/createresource.py","file_name":"createresource.py","file_ext":"py","file_size_in_byte":11235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"241755422","text":"from typing import Optional, Type\n\nimport habitat\nfrom habitat import Config, Dataset\nfrom habitat_baselines.common.baseline_registry import baseline_registry\n\n\ndef get_env_class(env_name: str) -> Type[habitat.RLEnv]:\n r\"\"\"Return environment class based on name.\n\n Args:\n env_name: name of the environment.\n\n Returns:\n Type[habitat.RLEnv]: env class.\n \"\"\"\n return baseline_registry.get_env(env_name)\n\n\n@baseline_registry.register_env(name=\"NavRLEnv\")\nclass CustomObjectNavEnv(habitat.RLEnv):\n def __init__(self, config: Config, dataset: Optional[Dataset] = None):\n self._rl_config = config.RL\n self._core_env_config = config.habitat_cfg\n self._reward_measure_name = self._rl_config.REWARD_MEASURE\n self._success_measure_name = self._rl_config.SUCCESS_MEASURE\n\n self._previous_measure = None\n self._previous_action = None\n super().__init__(self._core_env_config, dataset)\n\n def reset(self):\n self._previous_action = None\n observations = super().reset()\n self._previous_measure = self._env.get_metrics()[\n self._reward_measure_name\n ]\n return observations\n\n def step(self, *args, **kwargs):\n self._previous_action = kwargs[\"action\"]\n return super().step(*args, **kwargs)\n\n def get_reward_range(self):\n return (\n self._rl_config.SLACK_REWARD - 1.0,\n self._rl_config.SUCCESS_REWARD + 1.0,\n )\n\n def get_reward(self, observations):\n reward = self._rl_config.SLACK_REWARD\n\n current_measure = self._env.get_metrics()[self._reward_measure_name]\n\n reward += self._previous_measure - current_measure\n self._previous_measure = current_measure\n\n if self._episode_success():\n reward += self._rl_config.SUCCESS_REWARD\n\n return reward\n\n def _episode_success(self):\n return self._env.get_metrics()[self._success_measure_name]\n\n def get_done(self, observations):\n done = False\n if self._env.episode_over or self._episode_success():\n done = True\n return done\n\n def get_info(self, observations):\n return self.habitat_env.get_metrics()","sub_path":"envs/habitat_utils/object_nav_env.py","file_name":"object_nav_env.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"563763048","text":"from itertools import groupby\n\ndef mean(numbers):\n return sum(numbers) / n\n\n\ndef mode(numbers):\n occurrences = {x: 0 for x in numbers}\n for x in range(n):\n if numbers[x] in occurrences:\n occurrences[numbers[x]] = occurrences[numbers[x]] + 1\n\n max_value_occurrence = 0\n max_value = []\n\n for i, j in occurrences.items():\n if j >= max_value_occurrence:\n max_value_occurrence = j\n max_value.append(i)\n return min(max_value)\n\n\ndef mode2(numbers):\n mode_number = 0\n for i, j in groupby(numbers):\n if len(list(j)) > mode_number:\n mode_number = i\n print(mode_number)\n\n\ndef median(numbers):\n numbers.sort()\n x = numbers[int(n/2)]\n y = numbers[int((n - 1)/2)]\n return (x + y)/2.0\n\n\ndef start():\n global n\n n = int(input())\n elements = input()\n split = list(map(int, (val for val in elements.split() if val.isdigit())))\n return split\n\n\nif __name__ == '__main__':\n x = start()\n\n value = \"{:.1f}\"\n print(value.format(mean(x)))\n print(value.format(median(x)))\n print(mode(x))\n print(mode2(x))\n\n","sub_path":"out/target/production/HackerRankSolution/PythonVersion/Day0_MeanMedianMode.py","file_name":"Day0_MeanMedianMode.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"131284125","text":"from dataclasses import Field, dataclass, fields\nfrom typing import Optional\n\nimport pytest\n\nfrom jsondataclass.exceptions import MissingDefaultValueError\nfrom jsondataclass.field import _METADATA_KEY, JsonField, jsonfield\nfrom jsondataclass.serializers import DefaultSerializer\n\n\ndef test_jsonfield_creation():\n field = jsonfield()\n assert isinstance(field, Field)\n\n\ndef test_jsonfield_serialized_name():\n field = jsonfield(serialized_name=\"field1\")\n assert field.metadata[_METADATA_KEY].serialized_name == \"field1\"\n\n\ndef test_jsonfield_serializer_class():\n field = jsonfield(serializer_class=DefaultSerializer)\n assert field.metadata[_METADATA_KEY].serializer_class == DefaultSerializer\n\n\ndef test_jsonfield_serializer_args():\n field = jsonfield(serializer_args=[1, 2, 3])\n assert field.metadata[_METADATA_KEY].serializer_args == [1, 2, 3]\n\n\ndef test_jsonfield_serializer_kwargs():\n field = jsonfield(serializer_kwargs={\"a\": 1, \"b\": 2})\n assert field.metadata[_METADATA_KEY].serializer_kwargs == {\"a\": 1, \"b\": 2}\n\n\ndef test_field_default_value():\n @dataclass\n class Foo:\n a: Optional[str]\n b: str = \"b\"\n c: str = jsonfield(default=\"c\")\n d: str = jsonfield(default_factory=lambda: \"d\")\n\n field_a = JsonField(fields(Foo)[0])\n field_b = JsonField(fields(Foo)[1])\n field_c = JsonField(fields(Foo)[2])\n field_d = JsonField(fields(Foo)[3])\n assert field_a.default_value is None\n assert field_b.default_value == \"b\"\n assert field_c.default_value == \"c\"\n assert field_d.default_value == \"d\"\n\n\ndef test_field_missing_default_value():\n @dataclass\n class Foo:\n a: str\n\n field = JsonField(fields(Foo)[0])\n\n with pytest.raises(MissingDefaultValueError):\n field.default_value\n","sub_path":"tests/test_field.py","file_name":"test_field.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"55534179","text":"class Solution:\n def findPairs(self, nums: List[int], k: int) -> int:\n if k < 0: return 0\n nums_set, pairs_set, count = set(), set(), 0\n \n for i, num in enumerate(nums):\n pair1, pair2 = [num-k, num], [num+k, num]\n pair1.sort()\n pair2.sort()\n if num-k in nums_set and not (pair1[0], pair1[1]) in pairs_set:\n count += 1\n pairs_set.add((pair1[0], pair1[1]))\n if num+k in nums_set and not (pair2[0], pair2[1]) in pairs_set:\n count += 1\n pairs_set.add((pair2[0], pair2[1]))\n nums_set.add(num)\n return count\n","sub_path":"python/532_K-diffPairsInArray.py","file_name":"532_K-diffPairsInArray.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"358852087","text":"\"\"\"empty message\n\nRevision ID: 82ecd2830bc9\nRevises: 34dcdb7a7d9d\nCreate Date: 2021-10-10 02:24:44.064437\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '82ecd2830bc9'\ndown_revision = '34dcdb7a7d9d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('projects', sa.Column('video_src', sa.String(length=100), nullable=True))\n op.add_column('projects', sa.Column('image_src', sa.String(length=100), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('projects', 'image_src')\n op.drop_column('projects', 'video_src')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/20211010_022444_.py","file_name":"20211010_022444_.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"245669821","text":"#! /usr/bin/env python\n# coding=utf-8\n# Copyright (c) 2019 Uber Technologies, 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# ==============================================================================\nimport argparse\nimport os\nimport random\nimport string\nimport uuid\n\nimport numpy as np\nimport yaml\nimport soundfile as sf\nfrom skimage.io import imsave\n\nfrom ludwig.utils.data_utils import save_csv\nfrom ludwig.constants import VECTOR\nfrom ludwig.utils.h3_util import components_to_h3\nfrom ludwig.utils.misc import get_from_registry\n\nletters = string.ascii_letters\n\nDATETIME_FORMATS = {\n '%m-%d-%Y': '{m:02d}-{d:02d}-{Y:04d}',\n '%m-%d-%Y %H:%M:%S': '{m:02d}-{d:02d}-{Y:04d} {H:02d}:{M:02d}:{S:02d}',\n '%m/%d/%Y': '{m:02d}/{d:02d}/{Y:04d}',\n '%m/%d/%Y %H:%M:%S': '{m:02d}/{d:02d}/{Y:04d} {H:02d}:{M:02d}:{S:02d}',\n '%m-%d-%y': '{m:02d}-{d:02d}-{y:02d}',\n '%m-%d-%y %H:%M:%S': '{m:02d}-{d:02d}-{y:02d} {H:02d}:{M:02d}:{S:02d}',\n '%m/%d/%y': '{m:02d}/{d:02d}/{y:02d}',\n '%m/%d/%y %H:%M:%S': '{m:02d}/{d:02d}/{y:02d} {H:02d}:{M:02d}:{S:02d}',\n '%d-%m-%Y': '{d:02d}-{m:02d}-{Y:04d}',\n '%d-%m-%Y %H:%M:%S': '{d:02d}-{m:02d}-{Y:04d} {H:02d}:{M:02d}:{S:02d}',\n '%d/%m/%Y': '{d:02d}/{m:02d}/{Y:04d}',\n '%d/%m/%Y %H:%M:%S': '{d:02d}/{m:02d}/{Y:04d} {H:02d}:{M:02d}:{S:02d}',\n '%d-%m-%y': '{d:02d}-{m:02d}-{y:02d}',\n '%d-%m-%y %H:%M:%S': '{d:02d}-{m:02d}-{y:02d} {H:02d}:{M:02d}:{S:02d}',\n '%d/%m/%y': '{d:02d}/{m:02d}/{y:02d}',\n '%d/%m/%y %H:%M:%S': '{d:02d}/{m:02d}/{y:02d} {H:02d}:{M:02d}:{S:02d}',\n '%y-%m-%d': '{y:02d}-{m:02d}-{d:02d}',\n '%y-%m-%d %H:%M:%S': '{y:02d}-{m:02d}-{d:02d} {H:02d}:{M:02d}:{S:02d}',\n '%y/%m/%d': '{y:02d}/{m:02d}/{d:02d}',\n '%y/%m/%d %H:%M:%S': '{y:02d}/{m:02d}/{d:02d} {H:02d}:{M:02d}:{S:02d}',\n '%Y-%m-%d': '{Y:04d}-{m:02d}-{d:02d}',\n '%Y-%m-%d %H:%M:%S': '{Y:04d}-{m:02d}-{d:02d} {H:02d}:{M:02d}:{S:02d}',\n '%Y/%m/%d': '{Y:04d}/{m:02d}/{d:02d}',\n '%Y/%m/%d %H:%M:%S': '{Y:04d}/{m:02d}/{d:02d} {H:02d}:{M:02d}:{S:02d}',\n '%y-%d-%m': '{y:02d}-{d:02d}-{m:02d}',\n '%y-%d-%m %H:%M:%S': '{y:02d}-{d:02d}-{m:02d} {H:02d}:{M:02d}:{S:02d}',\n '%y/%d/%m': '{y:02d}/{d:02d}/{m:02d}',\n '%y/%d/%m %H:%M:%S': '{y:02d}/{d:02d}/{m:02d} {H:02d}:{M:02d}:{S:02d}',\n '%Y-%d-%m': '{Y:04d}-{d:02d}-{m:02d}',\n '%Y-%d-%m %H:%M:%S': '{Y:04d}-{d:02d}-{m:02d} {H:02d}:{M:02d}:{S:02d}',\n '%Y/%d/%m': '{Y:04d}/{d:02d}/{m:02d}',\n '%Y/%d/%m %H:%M:%S': '{Y:04d}/{d:02d}/{m:02d} {H:02d}:{M:02d}:{S:02d}'\n}\n\n\ndef generate_string(length):\n sequence = []\n for _ in range(length):\n sequence.append(random.choice(letters))\n return ''.join(sequence)\n\n\ndef build_vocab(size):\n vocab = []\n for _ in range(size):\n vocab.append(generate_string(random.randint(2, 10)))\n return vocab\n\n\ndef return_none(feature):\n return None\n\n\ndef assign_vocab(feature):\n feature['idx2str'] = build_vocab(feature['vocab_size'])\n\n\ndef build_feature_parameters(features):\n feature_parameters = {}\n for feature in features:\n fearure_builder_function = get_from_registry(\n feature['type'],\n parameters_builders_registry\n )\n\n feature_parameters[feature['name']] = fearure_builder_function(feature)\n return feature_parameters\n\n\nparameters_builders_registry = {\n 'category': assign_vocab,\n 'text': assign_vocab,\n 'numerical': return_none,\n 'binary': return_none,\n 'set': assign_vocab,\n 'bag': assign_vocab,\n 'sequence': assign_vocab,\n 'timeseries': return_none,\n 'image': return_none,\n 'audio': return_none,\n 'date': return_none,\n 'h3': return_none,\n VECTOR: return_none\n}\n\n\ndef build_synthetic_dataset(dataset_size, features):\n build_feature_parameters(features)\n header = []\n for feature in features:\n header.append(feature['name'])\n\n yield header\n for _ in range(dataset_size):\n yield generate_datapoint(features)\n\n\ndef generate_datapoint(features):\n datapoint = []\n for feature in features:\n if ('cycle' in feature and feature['cycle'] is True and\n feature['type'] in cyclers_registry):\n cycler_function = cyclers_registry[feature['type']]\n feature_value = cycler_function(feature)\n else:\n generator_function = get_from_registry(\n feature['type'],\n generators_registry\n )\n feature_value = generator_function(feature)\n datapoint.append(feature_value)\n return datapoint\n\n\ndef generate_category(feature):\n return random.choice(feature['idx2str'])\n\n\ndef generate_text(feature):\n text = []\n for _ in range(random.randint(feature['max_len'] -\n int(feature['max_len'] * 0.2),\n feature['max_len'])):\n text.append(random.choice(feature['idx2str']))\n return ' '.join(text)\n\n\ndef generate_numerical(feature):\n return random.uniform(\n feature['min'] if 'min' in feature else 0,\n feature['max'] if 'max' in feature else 1\n )\n\n\ndef generate_binary(feature):\n p = feature['prob'] if 'prob' in feature else 0.5\n return np.random.choice([True, False], p=[p, 1 - p])\n\n\ndef generate_sequence(feature):\n length = feature['max_len']\n if 'min_len' in feature:\n length = random.randint(feature['min_len'], feature['max_len'])\n\n sequence = [random.choice(feature['idx2str']) for _ in range(length)]\n\n return ' '.join(sequence)\n\n\ndef generate_set(feature):\n elems = []\n for _ in range(random.randint(0, feature['max_len'])):\n elems.append(random.choice(feature['idx2str']))\n return ' '.join(list(set(elems)))\n\n\ndef generate_bag(feature):\n elems = []\n for _ in range(random.randint(0, feature['max_len'])):\n elems.append(random.choice(feature['idx2str']))\n return ' '.join(elems)\n\n\ndef generate_timeseries(feature):\n series = []\n for _ in range(feature['max_len']):\n series.append(\n str(\n random.uniform(\n feature['min'] if 'min' in feature else 0,\n feature['max'] if 'max' in feature else 1\n )\n )\n )\n return ' '.join(series)\n\n\ndef generate_audio(feature):\n audio_length = feature['preprocessing']['audio_file_length_limit_in_s']\n audio_dest_folder = feature['audio_dest_folder']\n sampling_rate = 16000\n num_samples = int(audio_length * sampling_rate)\n audio = np.sin(np.arange(num_samples)/100 * 2 * np.pi) * 2 * (np.random.random(num_samples) - 0.5)\n audio_filename = uuid.uuid4().hex[:10].upper() + '.wav'\n\n try:\n if not os.path.exists(audio_dest_folder):\n os.mkdir(audio_dest_folder)\n\n audio_dest_path = os.path.join(audio_dest_folder, audio_filename)\n sf.write(audio_dest_path, audio, sampling_rate)\n\n except IOError as e:\n raise IOError('Unable to create a folder for audio or save audio to disk.'\n '{0}'.format(e))\n\n return audio_dest_path\n\n\ndef generate_image(feature):\n # Read num_channels, width, height\n num_channels = feature['preprocessing']['num_channels']\n width = feature['preprocessing']['width']\n height = feature['preprocessing']['height']\n image_dest_folder = feature['destination_folder']\n\n if width <= 0 or height <= 0 or num_channels < 1:\n raise ValueError('Invalid arguments for generating images')\n\n # Create a Random Image\n if num_channels == 1:\n img = np.random.rand(width, height) * 255\n else:\n img = np.random.rand(width, height, num_channels) * 255.0\n\n # Generate a unique random filename\n image_filename = uuid.uuid4().hex[:10].upper() + '.jpg'\n\n # Save the image to disk either in a specified location/new folder\n try:\n if not os.path.exists(image_dest_folder):\n os.mkdir(image_dest_folder)\n\n image_dest_path = os.path.join(image_dest_folder, image_filename)\n imsave(image_dest_path, img.astype('uint8'))\n\n except IOError as e:\n raise IOError('Unable to create a folder for images/save image to disk.'\n '{0}'.format(e))\n\n return image_dest_path\n\n\ndef generate_datetime(feature):\n \"\"\"picking a format among different types.\n If no format is specified, the first one is used.\n \"\"\"\n if 'datetime_format' in feature:\n datetime_generation_format = DATETIME_FORMATS[\n feature['datetime_format']\n ]\n elif ('preprocessing' in feature and\n 'datetime_format' in feature['preprocessing']):\n datetime_generation_format = DATETIME_FORMATS[\n feature['preprocessing']['datetime_format']\n ]\n else:\n datetime_generation_format = DATETIME_FORMATS[0]\n\n y = random.randint(1, 99)\n Y = random.randint(1, 9999)\n m = random.randint(1, 12)\n d = random.randint(1, 28)\n H = random.randint(1, 12)\n M = random.randint(1, 59)\n S = random.randint(1, 59)\n\n return datetime_generation_format.format(y=y, Y=Y, m=m, d=d, H=H, M=M, S=S)\n\n\ndef generate_h3(feature):\n resolution = random.randint(0, 15) # valid values [0, 15]\n h3_components = {\n 'mode': 1, # we can avoid testing other modes\n 'edge': 0, # only used in other modes\n 'resolution': resolution,\n 'base_cell': random.randint(0, 121), # valid values [0, 121]\n # valid values [0, 7]\n 'cells': [random.randint(0, 7) for _ in range(resolution)]\n }\n\n return components_to_h3(h3_components)\n\n\ndef generate_vector(feature):\n # Space delimited string with floating point numbers\n return ' '.join(\n [str(100 * random.random()) for _ in range(feature['vector_size'])]\n )\n\n\ngenerators_registry = {\n 'category': generate_category,\n 'text': generate_sequence,\n 'numerical': generate_numerical,\n 'binary': generate_binary,\n 'set': generate_set,\n 'bag': generate_bag,\n 'sequence': generate_sequence,\n 'timeseries': generate_timeseries,\n 'image': generate_image,\n 'audio': generate_audio,\n 'h3': generate_h3,\n 'date': generate_datetime,\n VECTOR: generate_vector\n\n}\n\ncategory_cycle = 0\n\n\ndef cycle_category(feature):\n global category_cycle\n if category_cycle >= len(feature['idx2str']):\n category_cycle = 0\n category = feature['idx2str'][category_cycle]\n category_cycle += 1\n return category\n\n\nbinary_cycle = False\n\n\ndef cycle_binary(feature):\n global binary_cycle\n if binary_cycle:\n binary_cycle = False\n return True\n else:\n binary_cycle = True\n return False\n\n\ncyclers_registry = {\n 'category': cycle_category,\n 'binary': cycle_binary\n}\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='This script generates a synthetic dataset.')\n parser.add_argument('csv_file_path', help='output csv file path')\n parser.add_argument(\n '-d',\n '--dataset_size',\n help='size of the dataset',\n type=int,\n default=100\n )\n parser.add_argument(\n '-f',\n '--features',\n default='[\\\n {name: text_1, type: text, vocab_size: 20, max_len: 20}, \\\n {name: text_2, type: text, vocab_size: 20, max_len: 20}, \\\n {name: category_1, type: category, vocab_size: 10}, \\\n {name: category_2, type: category, vocab_size: 15}, \\\n {name: numerical_1, type: numerical}, \\\n {name: numerical_2, type: numerical}, \\\n {name: binary_1, type: binary}, \\\n {name: binary_2, type: binary}, \\\n {name: set_1, type: set, vocab_size: 20, max_len: 20}, \\\n {name: set_2, type: set, vocab_size: 20, max_len: 20}, \\\n {name: bag_1, type: bag, vocab_size: 20, max_len: 10}, \\\n {name: bag_2, type: bag, vocab_size: 20, max_len: 10}, \\\n {name: sequence_1, type: sequence, vocab_size: 20, max_len: 20}, \\\n {name: sequence_2, type: sequence, vocab_size: 20, max_len: 20}, \\\n {name: timeseries_1, type: timeseries, max_len: 20}, \\\n {name: timeseries_2, type: timeseries, max_len: 20}, \\\n ]',\n type=yaml.safe_load, help='dataset features'\n )\n args = parser.parse_args()\n\n dataset = build_synthetic_dataset(args.dataset_size, args.features)\n save_csv(args.csv_file_path, dataset)\n","sub_path":"ludwig/data/dataset_synthesyzer.py","file_name":"dataset_synthesyzer.py","file_ext":"py","file_size_in_byte":12829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"396445948","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 14 18:04:48 2020\n\n@author: Quang\n\"\"\"\n\nimport numpy as np\nimport cv2\nimport time\nimport os\nfrom utils import anonymize_face_simple, anonymize_face_pixelate\n\n# define the confidence of face detectopm as 0.5\nCONFIDENCE = 0.5\n\ndef resize_with_ratio(image, width):\n h,w = image.shape[:2]\n ratio = w/h\n image_resize = cv2.resize(image,(width,int(width/ratio)))\n return image_resize\n\n# Load the serialized face detector model from disk\nprint(\"[INFO] loading the face detector model...\")\nprototxtPath = \"./face_detector/deploy.prototxt\"\nweightsPath = \"./face_detector/res10_300x300_ssd_iter_140000.caffemodel\"\n\nnet = cv2.dnn.readNet(prototxtPath,weightsPath)\nprint(\"[INFO]Load model successfully...\")\n\ncap = cv2.VideoCapture(\"Taylor_ed.mp4\")\ntime.sleep(2.0)\n\nwriter = cv2.VideoWriter(\"processed_blured_face.mp4\",cv2.VideoWriter_fourcc(*'DIVX'),24,(1980,371))\n\nwhile True: \n # read and resize frame\n ret, frame = cap.read()\n \n if not ret:\n break\n \n frame = resize_with_ratio(frame,width=660)\n frame_gaussian = frame.copy()\n frame_blocks = frame.copy()\n \n # grab the dimensions of the frame and then construct \n # a blob from it\n h,w = frame.shape[:2]\n blob = cv2.dnn.blobFromImage(frame, 1.0, (300,300),\n (104.0, 177.0, 123.0))\n \n # pass the blob through the network and obtain the face\n # detections \n net.setInput(blob)\n detections = net.forward()\n \n # Loop over the detections\n \n for i in range(0, detections.shape[2]):\n # extract the confidence (i.e: probability) associated \n # with the detection\n \n confidence = detections[0,0,i,2]\n \n # filter out weak detections by ensureing the confidence is \n # greater than the minimum confidence\n \n if confidence > CONFIDENCE:\n # compute the (x,y) coordinates of the bounding box for \n # the objects\n box = detections[0,0,i,3:7] * np.array([w,h,w,h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n \n # extract the face ROI\n face = frame[startY:endY,startX:endX] \n \n # applying \"simple\" face bluring method\n face_blur_gaussian = anonymize_face_simple(face,factor=3.0)\n \n # applying \"pixelated\" face anonymization method\n face_blur_blocks = anonymize_face_pixelate(face,blocks=3)\n \n # replace the blurred face in the output image\n frame_gaussian[startY:endY, startX:endX] = face_blur_gaussian\n cv2.putText(frame_gaussian,\n (\"Face blurring with Gasussian technique\"),\n (20,h-20),cv2.FONT_HERSHEY_COMPLEX, 0.7, (0,0,255),2)\n \n frame_blocks[startY:endY, startX:endX] = face_blur_blocks\n cv2.putText(frame_blocks,\n (\"Face blurring with Pixelated technique\"),\n (20,h-20),cv2.FONT_HERSHEY_COMPLEX, 0.7, (0,0,255),2)\n \n # show the result\n horizontal_stacked_frame = np.concatenate((frame, frame_gaussian,frame_blocks),axis=1) \n writer.write(horizontal_stacked_frame)\n cv2.imshow(\"Face blur with Gaussian/Blocks\", horizontal_stacked_frame)\n \n k = cv2.waitKey(1) & 0xFF\n \n # press Esc to quit\n if k == 27:\n break \n \n\ncap.release()\nwriter.release()\ncv2.destroyAllWindows()","sub_path":"Face_bluring/face_bluring.py","file_name":"face_bluring.py","file_ext":"py","file_size_in_byte":3479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"285097097","text":"# -*- encoding: utf-8 -*-\n#\n# Copyright © 2021 Mergify SAS\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.\nimport dataclasses\nimport typing\n\nfrom mergify_engine import context\nfrom mergify_engine import exceptions\nfrom mergify_engine import github_types\nfrom mergify_engine import gitter\nfrom mergify_engine.dashboard import user_tokens\nfrom mergify_engine.dashboard.subscription import Features\n\n\n@dataclasses.dataclass\nclass SquashFailure(Exception):\n reason: str\n\n\n@dataclasses.dataclass\nclass SquashNeedRetry(exceptions.EngineNeedRetry):\n message: str\n\n\nasync def _do_squash(\n ctxt: context.Context, user: user_tokens.UserTokensUser, squash_message: str\n) -> None:\n\n head_branch = ctxt.pull[\"head\"][\"ref\"]\n base_branch = ctxt.pull[\"base\"][\"ref\"]\n tmp_branch = \"squashed-head-branch\"\n\n git = gitter.Gitter(ctxt.log)\n\n try:\n await git.init()\n\n if ctxt.subscription.has_feature(Features.BOT_ACCOUNT):\n await git.configure(user[\"name\"] or user[\"login\"], user[\"email\"])\n else:\n await git.configure()\n\n await git.setup_remote(\n \"origin\", ctxt.pull[\"head\"][\"repo\"], user[\"oauth_access_token\"], \"\"\n )\n await git.setup_remote(\n \"upstream\", ctxt.pull[\"base\"][\"repo\"], user[\"oauth_access_token\"], \"\"\n )\n\n await git(\"fetch\", \"--quiet\", \"origin\", head_branch)\n await git(\"fetch\", \"--quiet\", \"upstream\", base_branch)\n await git(\"checkout\", \"-q\", \"-b\", tmp_branch, f\"upstream/{base_branch}\")\n\n await git(\"merge\", \"--squash\", \"--no-edit\", f\"origin/{head_branch}\")\n await git(\"commit\", \"-m\", squash_message)\n\n await git(\n \"push\",\n \"--verbose\",\n \"origin\",\n f\"{tmp_branch}:{head_branch}\",\n \"--force-with-lease\",\n )\n\n expected_sha = (await git(\"log\", \"-1\", \"--format=%H\")).strip()\n # NOTE(sileht): We store this for dismissal action\n # FIXME(sileht): use a more generic name for the key\n await ctxt.redis.setex(f\"branch-update-{expected_sha}\", 60 * 60, expected_sha)\n except gitter.GitMergifyNamespaceConflict as e:\n raise SquashFailure(\n \"`Mergify uses `mergify/...` namespace for creating temporary branches. \"\n \"A branch of your repository is conflicting with this namespace\\n\"\n f\"```\\n{e.output}\\n```\\n\"\n )\n except gitter.GitAuthenticationFailure:\n raise\n except gitter.GitErrorRetriable as e:\n raise SquashNeedRetry(\n f\"Git reported the following error:\\n```\\n{e.output}\\n```\\n\"\n )\n except gitter.GitFatalError as e:\n raise SquashFailure(\n f\"Git reported the following error:\\n```\\n{e.output}\\n```\\n\"\n )\n except gitter.GitError as e:\n ctxt.log.error(\n \"squash failed\",\n output=e.output,\n returncode=e.returncode,\n exc_info=True,\n )\n raise SquashFailure(\"\")\n except Exception: # pragma: no cover\n ctxt.log.error(\"squash failed\", exc_info=True)\n raise SquashFailure(\"\")\n finally:\n await git.cleanup()\n\n\nasync def squash(\n ctxt: context.Context,\n message: str,\n bot_account: typing.Optional[github_types.GitHubLogin] = None,\n) -> None:\n\n if ctxt.pull[\"commits\"] <= 1:\n return\n\n try:\n users = await user_tokens.UserTokens.select_users_for(ctxt, bot_account)\n except user_tokens.UserTokensUserNotFound as e:\n raise SquashFailure(f\"Unable to squash: {e.reason}\")\n\n for user in users:\n try:\n await _do_squash(ctxt, user, message)\n except gitter.GitAuthenticationFailure as e:\n ctxt.log.info(\n \"authentification failure, will retry another token: %s\",\n e,\n login=user[\"login\"],\n )\n else:\n return\n\n ctxt.log.warning(\"unable to squash pull request: no tokens are valid\")\n\n if ctxt.pull_from_fork and ctxt.pull[\"base\"][\"repo\"][\"private\"]:\n raise SquashFailure(\n \"Squashing a branch for a forked private repository is not supported by GitHub\"\n )\n\n raise SquashFailure(\"No oauth valid tokens\")\n","sub_path":"mergify_engine/squash_pull.py","file_name":"squash_pull.py","file_ext":"py","file_size_in_byte":4718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"177637436","text":"import numpy as np\nimport pandas as pd\n\nimport bert\nimport utils\n\nmodel = None\n\n\ndef get_model():\n global model\n model = bert.BertToSingleLayerNeuralNetwork(config=bert.ModelConfig)\n model.version = \"final\"\n model.build(processors=[utils.replace_latex_math_with, utils.to_corpus, utils.lemmatize_sentence])\n model.load(\"model\")\n\n\ndef get_res(abstract):\n global labels\n global model\n labels = np.array(\n [\"Computer Science\", \"Physics\", \"Mathematics\", \"Statistics\", \"Quantitative Biology\", \"Quantitative Finance\"])\n data = pd.DataFrame({\"text\": [abstract]})\n y_pred = model.predict(data[\"text\"])[0]\n print(\"y_pred:\", y_pred)\n top_labels = (y_pred > 0.5).astype(int)\n selected_labels = labels[np.where(top_labels == 1)]\n response = {\n \"status\": 200, \"body\": {\n \"abstract\": abstract,\n \"labels\": selected_labels.tolist(),\n \"classification\": top_labels,\n \"confidenceScores\": {\n \"Computer\": float(y_pred[np.where(labels == \"Computer Science\")][0]),\n \"Physics\": float(y_pred[np.where(labels == \"Physics\")][0]),\n \"Maths\": float(y_pred[np.where(labels == \"Mathematics\")][0]),\n \"Statistics\": float(y_pred[np.where(labels == \"Statistics\")][0]),\n \"Biology\": float(y_pred[np.where(labels == \"Quantitative Biology\")][0]),\n \"Finance\": float(y_pred[np.where(labels == \"Quantitative Finance\")][0])\n }}}\n return response\n\n\ndef main(abstract):\n # get_model()\n result = get_res(abstract)\n body = result['body']\n return body\n\n\nget_model()\n","sub_path":"serving.py","file_name":"serving.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"590842446","text":"import httplib2 as http\r\nimport json\r\nimport logging\r\nimport startup\r\nimport os\r\nimport click\r\nimport sys\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\nlogging.basicConfig(level=logging.DEBUG)\r\ntry:\r\n from urlparse import urlparse\r\nexcept ImportError:\r\n from urllib.parse import urlparse\r\n\r\n# part of the code taken from the https://www.genenames.org/help/rest/#!/#tocAnchor-1-1\r\ndef downloading_from_API(hgnc_symbol):\r\n logging.info(\"The gene symbol under retreival is {}.\".format(hgnc_symbol))\r\n if os.path.exists(os.path.join(startup.data_path,hgnc_symbol+'.json')):\r\n logging.info(\"The information about the gene {} is already downloaded!\".format(hgnc_symbol))\r\n return None,None\r\n #sys.exit()\r\n else:\r\n headers = {'Accept': 'application/json'}\r\n uri = 'http://rest.genenames.org'\r\n path = '/fetch/symbol/{}'.format(hgnc_symbol)\r\n target = urlparse(uri+path)\r\n method = 'GET'\r\n body = ''\r\n h = http.Http()\r\n response, content = h.request(target.geturl(),method,body,headers)\r\n if response['status'] == '200':\r\n data = json.loads(content)\r\n if data['response']['docs'] == []:\r\n logging.warning(\"No Data fetched about the gene {}!\".format(hgnc_symbol))\r\n #sys.exit()\r\n else:\r\n logging.info(\"Data for the gene symbol {} retrieved\".format(hgnc_symbol))\r\n with open(os.path.join(startup.data_path,hgnc_symbol+'.json'),\"w\") as f:\r\n json.dump(data,f)\r\n logging.info(\"The data about the gene {} is written in the file {}.json.\".format(hgnc_symbol,hgnc_symbol))\r\n elif response['status'] != '200':\r\n logging.error(\"Data cannot be Retrieved and the status code is {}!\".format(response['status']))\r\n return data , uri+path\r\n\r\n\r\n\r\ndef extracting_identifiers(hgnc_symbol):\r\n identifier = {}\r\n data_from_api, link = downloading_from_API(hgnc_symbol)\r\n\r\n#data_from_api['response']['docs'][0]['hgnc_id'] if present else None using get method\r\n if data_from_api['response']['numFound']==1 :\r\n identifier[hgnc_symbol] = ((data_from_api['response']['docs'][0]).get(\"hgnc_id\",\"None\"),\r\n (data_from_api['response'] ['docs'][0]).get(\"ensembl_gene_id\",\"None\"),\r\n (data_from_api['response'] ['docs'][0]).get(\"uniprot_ids\",\"None\"))\r\n return identifier,link\r\n else:\r\n return None\r\n\r\n\r\n#print(extracting_identifiers(\"CREBBP\"))\r\n\r\n# start of the Click\r\n@click.group()\r\ndef main():\r\n pass\r\n@main.command()\r\n@click.option('-hgnc','--hgnc_symbol',help='Name of the HGNC symbol')\r\n\r\ndef info (hgnc_symbol=None) -> None:\r\n print(extracting_identifiers(hgnc_symbol))\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n\r\n# fulll correct","sub_path":"solutions/exercise05/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"337982226","text":"import sys\nimport numpy as np\nimport os\nsys.path.append(\"../../pygra\")\n\nimport geometry\nimport sculpt\n\ng = geometry.kagome_lattice()\n#g = geometry.honeycomb_lattice()\ng.has_sublattice = True\ng.sublattice = [-1,1,0]\nimport ribbon\n\ng = ribbon.bulk2ribbon(g,n=20)\nh = g.get_hamiltonian()\nms = [] # zeeman fields\nm1 = np.array([1.,0.,0.])\nm2 = np.array([-.5,np.sqrt(3.)/2.,0.])\nm3 = np.array([-.5,-np.sqrt(3.)/2.,0.])\nmm = 3.0\nfor (r,s) in zip(g.r,g.sublattice):\n if r[1]<0.0:\n if s==-1: ms.append(m1*mm)\n if s==1: ms.append(m2*mm)\n if s==0: ms.append(m3*mm)\n else: ms.append([0.,0.,0.])\n\n# swave\ndef fs(r):\n if r[1]>0.0: return 0.3\n else: return 0.0\nh.add_magnetism(ms)\nh.add_swave(fs)\nh.shift_fermi(fs)\nh.get_bands(operator=\"interface\")\nexit()\nmaf = []\n#for s in g.sublattice:\n# if s==-1:\nh.add_antiferromagnetism(0.5)\nh = h.get_bands()\n\n","sub_path":"examples/1d/kagome_frustration/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"471220246","text":"'''Base Class for Efflux Telemetry Data'''\nfrom abc import ABCMeta\nimport thread\nimport logging\nfrom logging.handlers import TimedRotatingFileHandler\nfrom os.path import expanduser\n\nimport requests\n\nimport efflux.logger as log\n\nlogger = log.get_logger(__name__)\n\n\ndef _handle_resp(resp, *args, **kwargs):\n if resp.status_code == 401:\n logger.error('Authorization failed!\\n%s', resp.json())\n thread.interrupt_main()\n\n\nclass Telemetry(object):\n '''Base Class for all types of Telemetry\n that can be ingested into Efflux.\n\n Currently, telemetry can be pushed to the\n Efflux API. Or for local testing and other\n development efforts, the telemetry can be\n written to rotating files in JSON format.\n '''\n\n __metaclass__ = ABCMeta\n\n def __init__(self, domain=None, token=None, mode='get'):\n '''Init ABC'''\n self.domain = domain\n self.token = token\n self.mode = mode.lower()\n self.base_params = {}\n if self.token is not None:\n self.base_params['token'] = self.token\n\n self.base_route = None\n self.data_logger = None\n self.send = self._get_sender()\n\n self._set_route()\n\n def _get_sender(self):\n if self.mode == 'get':\n return self._do_get\n elif self.mode == 'post':\n return self._do_post\n elif self.mode in ('file', 's3'):\n return self._write\n\n def set_logfile(self, path=expanduser('~'), interval=5, bucket=None,\n prefix=''):\n self.data_logger = logging.getLogger('telemetry_file_logger')\n self.data_logger.setLevel(logging.INFO)\n if not bucket:\n handler = TimedRotatingFileHandler(\n path,\n when='S',\n interval=interval * 60,\n backupCount=0\n )\n else:\n handler = log.S3Batch(\n path,\n bucket,\n prefix,\n when='S',\n interval=interval * 60)\n handler.setFormatter('')\n self.data_logger.addHandler(handler)\n\n def _set_route(self):\n '''Set the API base URI for this Object'''\n self.base_route = 'https://{}/api/telemetry'.format(self.domain)\n\n def _do_get(self,\n dest=None,\n data=None,\n headers=None):\n '''Define behavior for GET requests'''\n if not dest:\n logger.error('No HTTP endpoint available for GET')\n return None\n try:\n ret = requests.get(\n dest,\n params=data,\n headers=headers,\n hooks=dict(response=_handle_resp))\n try:\n return ret.status_code, ret.json()\n except ValueError:\n return ret.status_code, ret.text\n except requests.exceptions.RequestException:\n logger.exception('Could not complete GET request %s:%s',\n ret.status_code,\n ret.text)\n return None\n\n def _do_post(self,\n dest=None,\n data=None,\n headers=None):\n '''Define behavior for POST requests'''\n if not dest:\n logger.error('No HTTP endpoint available for POST')\n return None\n base_headers = {'x-auth-site-token': self.token}\n if headers is not None:\n base_headers.update(headers)\n\n try:\n ret = requests.post(\n dest,\n data=data,\n headers=base_headers,\n hooks=dict(response=_handle_resp))\n try:\n return ret.status_code, ret.json()\n except ValueError:\n return ret.status_code, ret.text\n except requests.exceptions.RequestException:\n logger.exception('Could not complete POST request %s:%s',\n ret.status_code,\n ret.text)\n return None\n\n def _write(self,\n dest=None,\n data=None):\n '''Define behavior for file write requests'''\n self.data_logger.info(data)\n\n def check_required_fields(self, in_array, check_array):\n '''Check that in_array is a subset of check_array'''\n return set(in_array) <= set(check_array)\n\n def set_namespace(self, ns, item):\n '''Append a namespace prefix to all keys in a dict'''\n for key in item.keys():\n item[ns + '_' + key] = item.pop(key)\n\n return item\n","sub_path":"efflux/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"41963982","text":"#-------------#\n\nMensaje_Bienvenida = \"Bienvenido al codigo\"\nMensaje_Mayor_Edad = \"Eres mayor de edad puedes seguir\"\nMensaje_Menor_Edad = \"Eres menor de edad no puedes seguir\"\nPregunta_edad = \"¿Cual es tu edad?: \"\n\n#------------------#\n\nprint(Mensaje_Bienvenida)\nedad = int(input(Pregunta_edad))\nIsmayor = edad >=18\nif (Ismayor):\n print(Mensaje_Mayor_Edad)\nelse:\n print(Mensaje_Menor_Edad)","sub_path":"clases/edad.py","file_name":"edad.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"438749727","text":"\"\"\"This file downloads the\nffmpeg binaries from google\ndrive and writes them at\nos.getcwd()\n\"\"\"\n\nimport requests\nimport zipfile\nimport os\nfrom os.path import join\nfrom pathlib import Path\n\n\nbase = os.getcwd()\n\nPath(base).mkdir(parents=True, exist_ok=True)\n\nffmpeg_url = (\n \"https://drive.google.com/uc?export=download&id=1HNKmdxYLpBfjg30EDFMuTXtfCFLkwvI9\"\n)\n\ntries = 0\nwhile True:\n tries += 1\n try:\n r = requests.get(ffmpeg_url)\n break\n except Exception as e:\n print(e)\n if tries > 5:\n break\n\nffmpeg_path = join(base, \"ffmpeg.exe\")\nwith open(ffmpeg_path, \"wb\") as fd:\n fd.write(r.content)\nprint(ffmpeg_path)\n","sub_path":"assets/windows_ffmpeg_downloader_at_cwd.py","file_name":"windows_ffmpeg_downloader_at_cwd.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"461230472","text":"import math\n\n'''\nhttps://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1985\n'''\n\nif __name__ == \"__main__\":\n N = int(input())\n for i in range(N):\n n, m = map(int, input().split())\n print(\"%d\" %(math.ceil((n-2)/3)*(math.ceil((m-2)/3))))\n","sub_path":"SearchingForNessy.py","file_name":"SearchingForNessy.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"203859889","text":"from multiprocessing import Process\nimport os\nimport time\n\n\ndef sun(name, age, **kwargs):\n for i in range(10):\n print('name=%s, age=%d, pid=%s' % (name, age, os.getpid()))\n print(kwargs)\n time.sleep(0.5)\n\n\nif __name__ == \"__main__\":\n print('father=%d' % os.getpid())\n p = Process(target=sun, args=('test_sun', 26), kwargs={'m': 26})\n print('sun will run')\n p.start()\n time.sleep(1)\n p.terminate()\n p.join()\n print('sun end')","sub_path":"07_older/04_multiprocessing.py","file_name":"04_multiprocessing.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"285606006","text":"from flask import Flask, request\nfrom flask_restplus import Namespace, Resource, Api, fields\nimport pymongo\nfrom bson import ObjectId\nfrom database import get_db\n\napi = Namespace('provinces', description='provinces related operations')\n\nuserPayload = api.model('userPayload', {\n \"nombre\" : fields.String\n})\n\nprovincesParser = api.parser()\nprovincesParser.add_argument(\n 'page', type=int, help='page number', location='head')\nprovincesParser.add_argument('pageSize', type=int,\n help='page size', location='head')\n\n@api.route('/')\nclass Provinces(Resource):\n @api.doc(parser=provincesParser)\n def get(self):\n db = get_db()\n args = request.args\n page = int(args['page'])\n pageSize = int(args['pageSize'])\n provinces = list(db[\"provincias\"].find({},{\"nombre\":1}).skip(\n page * pageSize).limit(pageSize))\n for province in provinces:\n province['_id'] = str(province['_id'])\n return {\"total\": db[\"provincias\"].count_documents({}), \"items\": provinces}, 200\n\n\n@api.route('/')\nclass Province(Resource):\n def get(self, id):\n db = get_db()\n res = db[\"provincias\"].find_one({\"_id\": ObjectId(id)})\n if res is None:\n return {\"id\": id}, 404\n res['_id'] = str(res['_id'])\n return res, 200\n","sub_path":"proyecto-2b/ProyectoGrupal2B/api/provincesController.py","file_name":"provincesController.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"574358657","text":"from camera_profiler import Profiler\nimport os\n\n# settings\nnum_cores = 4\npatch_radius = 10\n\n# import image\npath_input = \"/run/media/bjoern/daten/Programming/Raw_NLM_Denoise/images/Profiling_X_T20/200.RAF\"\n# path_input = \"/run/media/bjoern/daten/Programming/Raw_NLM_Denoise/images/Olympus_200_0.ORF\"\n# path_input = \"/run/media/bjoern/daten/Programming/Raw_NLM_Denoise/images/Profiling_D40/DSC_1577.NEF\"\ndir_output = \"/run/media/bjoern/daten/Programming/Raw_NLM_Denoise/images/results\"\noutput_parameters = os.path.join(dir_output, \"profile_T10_200.csv\")\n\n\nprofiler = Profiler(patch_radius, num_cores=num_cores)\n\nparameters = profiler.profile_camera(path_input, dir_output)\nprofiler.save_parameters(parameters, output_parameters)","sub_path":"profile_camera.py","file_name":"profile_camera.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"439152818","text":"# size = int(input('Enter Board size'))\r\n#\r\n# board = []\r\n# for i in range(size): # A for loop for row entries\r\n# a = []\r\n# for j in range(size): # A for loop for column entries\r\n# a.append(int(input()))\r\n# board.append(a)\r\n\r\n\r\nboard = [[],\r\n [],\r\n [],\r\n [],\r\n [],\r\n [],\r\n [],\r\n [],\r\n [], ]\r\n\r\n\r\ndef solve(b):\r\n find = find_empty(b)\r\n if not find:\r\n return True\r\n else:\r\n row, col = find\r\n\r\n for i in range(1, 10):\r\n if valid(b, i, (row, col)):\r\n b[row][col] = i\r\n\r\n if solve(b):\r\n return True\r\n\r\n b[row][col] = 0\r\n\r\n return False\r\n\r\n\r\ndef valid(b, num, pos):\r\n for i in range(len(b[0])):\r\n if b[pos[0]][i] == num and pos[1] != i:\r\n return False\r\n\r\n for i in range(len(b)):\r\n if b[i][pos[1]] == num and pos[0] != i:\r\n return False\r\n\r\n x0 = pos[1] // 3\r\n y0 = pos[0] // 3\r\n\r\n for i in range(y0 * 3, y0 * 3 + 3):\r\n for j in range(x0 * 3, x0 * 3 + 3):\r\n if b[i][j] == num and (i, j) != pos:\r\n return False\r\n\r\n return True\r\n\r\n\r\ndef print_board(b):\r\n for i in range(len(b)):\r\n if i % 3 == 0 and i != 0:\r\n print(\"- - - - - - - - - - - - - \")\r\n\r\n for j in range(len(b[0])):\r\n if j % 3 == 0 and j != 0:\r\n print(\" | \", end=\"\")\r\n\r\n if j == 8:\r\n print(b[i][j])\r\n else:\r\n print(str(b[i][j]) + \" \", end=\"\")\r\n\r\n\r\ndef find_empty(b):\r\n for i in range(len(b)):\r\n for j in range(len(b[0])):\r\n if b[i][j] == 0:\r\n return i, j\r\n\r\n return None\r\n\r\n\r\nprint_board(board)\r\nsolve(board)\r\nprint(\"\")\r\nprint(\"\")\r\nprint_board(board)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"584636416","text":"# Due to https://github.com/bazelbuild/bazel/issues/2757\n# Consumers have to specify all of the transitive dependencies recursively which is not a very nice UX and pretty error\n# prone, this defines a function which declares all the spectator dependencies so that any Bazel project needing to\n# depend on spectator can just load and call this function instead of re-declaring all dependencies.\n\n# There's no clear consensus for reusing transitive dependencies, most of the community names them in reverse fqdn\n# (though sometimes this may include the org name, sometimes just the repo name) and create a set of parameters\n# omit_xxx where xxx is the reverse fqdn of the dependency so that if the consumer happens to already have it, they can\n# omit_xxx = True when calling the dependency declaration function and reuse their version. See\n# https://github.com/google/nomulus/blob/master/java/google/registry/repositories.bzl and the corresponding\n# https://github.com/google/nomulus/blob/master/WORKSPACE. Discussion https://github.com/bazelbuild/bazel/issues/1952.\n#\n# New cmake_external style dependencies are referenced in a different way (e.g. \"//external:\") so in order to\n# provide a way for the consumer to use their own version of the dependency which is pulled in a different way\n# i.e. cmake_external vs Bazel native we provide configuration settings and select the name based on those.\n# Probably easier to eventually let consumers specify the names altogether.\n\nload(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n\ndef spectator_dependencies(\n omit_curl = False,\n omit_com_github_c_ares_c_ares = False,\n omit_boringssl = False,\n omit_net_zlib = False,\n omit_com_github_skarupke_flat_hash_map = False,\n omit_com_github_fmtlib_fmt = False,\n omit_org_exim_pcre = False,\n omit_com_github_tencent_rapidjson = False,\n omit_com_github_gabime_spdlog = False,\n omit_com_google_googletest = False):\n if not omit_curl:\n _curl()\n\n # Optional curl dependency used to fix https://stackoverflow.com/questions/9191668/error-longjmp-causes-uninitialized-stack-frame.\n if not omit_com_github_c_ares_c_ares:\n _com_github_c_ares_c_ares()\n\n # curl dependency.\n if not omit_boringssl:\n _boringssl()\n\n # curl dependency.\n if not omit_net_zlib:\n _net_zlib()\n\n if not omit_com_github_skarupke_flat_hash_map:\n _com_github_skarupke_flat_hash_map()\n\n if not omit_com_github_fmtlib_fmt:\n _com_github_fmtlib_fmt()\n\n if not omit_org_exim_pcre:\n _org_exim_pcre()\n\n if not omit_com_github_tencent_rapidjson:\n _com_github_tencent_rapidjson()\n\n if not omit_com_github_gabime_spdlog:\n _com_github_gabime_spdlog()\n\n if not omit_com_google_googletest:\n _com_google_googletest()\n\ndef _curl():\n # https://github.com/tensorflow/tensorflow/blob/master/tensorflow/workspace.bzl.\n http_archive(\n # Needs build file updates to build with reverse fqdn.\n name = \"curl\",\n build_file = \"@spectator//third_party:curl.BUILD\",\n sha256 = \"e9c37986337743f37fd14fe8737f246e97aec94b39d1b71e8a5973f72a9fc4f5\",\n strip_prefix = \"curl-7.60.0\",\n urls = [\n \"https://mirror.bazel.build/curl.haxx.se/download/curl-7.60.0.tar.gz\",\n \"https://curl.haxx.se/download/curl-7.60.0.tar.gz\",\n ],\n )\n\ndef _com_github_c_ares_c_ares():\n # https://github.com/grpc/grpc/blob/master/bazel/grpc_deps.bzl.\n http_archive(\n name = \"com_github_c_ares_c_ares\",\n build_file = \"@spectator//third_party:cares.BUILD\",\n sha256 = \"e8c2751ddc70fed9dc6f999acd92e232d5846f009ee1674f8aee81f19b2b915a\",\n strip_prefix = \"c-ares-e982924acee7f7313b4baa4ee5ec000c5e373c30\",\n url = \"https://github.com/c-ares/c-ares/archive/e982924acee7f7313b4baa4ee5ec000c5e373c30.tar.gz\",\n )\n\ndef _boringssl():\n # https://github.com/tensorflow/tensorflow/blob/master/tensorflow/workspace.bzl.\n http_archive(\n # Envoy uses short name, update when switch to reverse fqdn.\n name = \"boringssl\",\n sha256 = \"1188e29000013ed6517168600fc35a010d58c5d321846d6a6dfee74e4c788b45\",\n strip_prefix = \"boringssl-7f634429a04abc48e2eb041c81c5235816c96514\",\n urls = [\"https://github.com/google/boringssl/archive/7f634429a04abc48e2eb041c81c5235816c96514.tar.gz\"],\n )\n\ndef _net_zlib():\n # https://github.com/tensorflow/tensorflow/blob/master/tensorflow/workspace.bzl.\n http_archive(\n name = \"net_zlib\",\n build_file = \"@spectator//third_party:zlib.BUILD\",\n sha256 = \"c3e5e9fdd5004dcb542feda5ee4f0ff0744628baf8ed2dd5d66f8ca1197cb1a1\",\n strip_prefix = \"zlib-1.2.11\",\n urls = [\n \"https://mirror.bazel.build/zlib.net/zlib-1.2.11.tar.gz\",\n \"https://zlib.net/zlib-1.2.11.tar.gz\",\n ],\n )\n\ndef _com_github_skarupke_flat_hash_map():\n http_archive(\n name = \"com_github_skarupke_flat_hash_map\",\n build_file = \"@spectator//third_party:flat_hash_map.BUILD\",\n sha256 = \"513efb9c2f246b6df9fa16c5640618f09804b009e69c8f7bd18b3099a11203d5\",\n strip_prefix = \"flat_hash_map-2c4687431f978f02a3780e24b8b701d22aa32d9c\",\n urls = [\"https://github.com/skarupke/flat_hash_map/archive/2c4687431f978f02a3780e24b8b701d22aa32d9c.zip\"],\n )\n\ndef _com_github_fmtlib_fmt():\n # https://github.com/envoyproxy/envoy/blob/master/bazel/repository_locations.bzl.\n http_archive(\n name = \"com_github_fmtlib_fmt\",\n build_file = \"@spectator//third_party:fmtlib.BUILD\",\n sha256 = \"4c0741e10183f75d7d6f730b8708a99b329b2f942dad5a9da3385ab92bb4a15c\",\n strip_prefix = \"fmt-5.3.0\",\n urls = [\"https://github.com/fmtlib/fmt/releases/download/5.3.0/fmt-5.3.0.zip\"],\n )\n\ndef _org_exim_pcre():\n # https://github.com/tensorflow/tensorflow/blob/master/tensorflow/workspace.bzl.\n http_archive(\n name = \"org_exim_pcre\",\n build_file = \"@spectator//third_party:pcre.BUILD\",\n sha256 = \"69acbc2fbdefb955d42a4c606dfde800c2885711d2979e356c0636efde9ec3b5\",\n strip_prefix = \"pcre-8.42\",\n urls = [\n \"https://mirror.bazel.build/ftp.exim.org/pub/pcre/pcre-8.42.tar.gz\",\n \"http://ftp.exim.org/pub/pcre/pcre-8.42.tar.gz\",\n ],\n )\n\ndef _com_github_tencent_rapidjson():\n # https://github.com/envoyproxy/envoy/blob/master/bazel/repository_locations.bzl.\n http_archive(\n name = \"com_github_tencent_rapidjson\",\n build_file = \"@spectator//third_party:rapidjson.BUILD\",\n sha256 = \"bf7ced29704a1e696fbccf2a2b4ea068e7774fa37f6d7dd4039d0787f8bed98e\",\n strip_prefix = \"rapidjson-1.1.0\",\n urls = [\"https://github.com/Tencent/rapidjson/archive/v1.1.0.tar.gz\"],\n )\n\ndef _com_github_gabime_spdlog():\n # https://github.com/envoyproxy/envoy/blob/master/bazel/repository_locations.bzl.\n http_archive(\n name = \"com_github_gabime_spdlog\",\n build_file = \"@spectator//third_party:spdlog.BUILD\",\n sha256 = \"160845266e94db1d4922ef755637f6901266731c4cb3b30b45bf41efa0e6ab70\",\n strip_prefix = \"spdlog-1.3.1\",\n urls = [\"https://github.com/gabime/spdlog/archive/v1.3.1.tar.gz\"],\n )\n\ndef _com_google_googletest():\n # https://github.com/envoyproxy/envoy/blob/master/bazel/repository_locations.bzl.\n http_archive(\n name = \"com_google_googletest\",\n sha256 = \"a4cb4b0c3ebb191b798594aca674ad47eee255dcb4c26885cf7f49777703484f\",\n strip_prefix = \"googletest-release-1.8.1\",\n urls = [\"https://github.com/google/googletest/archive/release-1.8.1.tar.gz\"],\n )\n","sub_path":"dependencies.bzl","file_name":"dependencies.bzl","file_ext":"bzl","file_size_in_byte":7645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"397158165","text":"\n'''\nCreated on Feb 12, 2019\n\n@author: rravell\n'''\nfrom bellpolytope import BellPolytope\nimport cdd as cdd\nimport numpy as np\nimport itertools as it\nfrom _functools import reduce\nfrom ncpol2sdpa.sdp_relaxation import imap\nfrom linopttools import *\nimport qutip as qt\n\nif __name__ == '__main__':\n \n outputsAlice = [3,3,5]\n outputsBob = [3,3,4,5]\n \n aliceUnBlochVectors = [[1,0,0],[0,1,0]]\n aliceObservables = list(map(lambda bloch : createQubitObservable(bloch),aliceUnBlochVectors))\n aliceEffects = list(map(lambda qubitObservable : projectorsForQubitObservable(qubitObservable),aliceObservables))\n \n delta=0.01\n tetrahedronAlice = [[delta,0,1],[-delta,0,1],[0,delta,-1],[0,-delta,-1]]\n aliceEffects += [list(map(lambda bloch : \n effectForQubitPovm(1/4, createQubitObservable(bloch)),tetrahedronAlice))]\n \n \n bobUnBlochVectors = [[-1,-1,0],[-1,1,0]]\n bobObservables=list(map(lambda bloch : createQubitObservable(bloch),bobUnBlochVectors))\n bobEffects = list(map(lambda qubitObservable : projectorsForQubitObservable(qubitObservable),bobObservables))\n \n trineBob = [[0,0,-1],[-np.sqrt(3),0,1],[np.sqrt(3),0,1]]\n bobEffects += [list(map(lambda bloch : \n effectForQubitPovm(1/3, createQubitObservable(bloch)),trineBob))]\n \n tetrahedronBob = [[1,-delta,0],[1,delta,0],[-1,0,delta],[-1,0,-delta]]\n tetrahedronBob = tetrahedronAlice\n bobEffects += [list(map(lambda bloch : \n effectForQubitPovm(1/4, createQubitObservable(bloch)),tetrahedronBob))]\n \n aliceEffects = addEffectsForAbortOutcomes(aliceEffects,2)\n bobEffects = addEffectsForAbortOutcomes(bobEffects,2)\n \n psi=createMaxEntState(2)\n \n dist=computeDistributionFromStateAndEffects(psi,aliceEffects,bobEffects)\n\n matrixHRepresentation = createConstraintsMatrixForEfficiencyDual(outputsAlice, outputsBob) \n mat = cdd.Matrix(matrixHRepresentation, number_type='fraction')\n mat.obj_type = cdd.LPObjType.MAX\n mat.obj_func = tuple(np.concatenate(([0],dist)))\n \n lp = cdd.LinProg(mat)\n lp.solve()\n print(lp.status)\n print(lp.obj_value)\n print(\" \".join(\"{0}\".format(val) for val in lp.primal_solution))\n \n \n \n","sub_path":"src/chsh.py","file_name":"chsh.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"502788301","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport io\nimport time\nimport re\nimport zipfile\nimport sys\n\nfrom os import listdir, remove, mkdir\nfrom os.path import isfile, join, isdir, dirname\nfrom findtext import findAllIncorrectTexts\n\n\ndef concatenate_files(inputDirectory, outputFile):\n\t\n\tif not isdir(inputDirectory):\n\t\tif isfile(join(inputDirectory, 'zip')):\n\t\t\tprint('Extracting files ...')\n\t\t\tzipfile.ZipFile(join(inputDirectory, 'zip'), \"r\").extractall()\n\t\telse:\n\t\t\tprint('No files available. Program will now exit.')\n\t\t\tsys.exit()\n\n\tfile_list = [join(inputDirectory, f) for f in listdir(inputDirectory) if isfile(join(inputDirectory, f))]\n\n\trejected_files = findAllIncorrectTexts(inputDirectory)\n\tprint(\"\tNumber of incorrect texts found: %d\" % len(rejected_files))\n\tprint(\" \tThose texts are : \" + str(rejected_files))\n\n\tnb_files = 0\n\n\tif not isdir(dirname(outputFile)):\n\t\tmkdir(dirname(outputFile))\n\n\twith io.open(outputFile, 'w+', encoding='utf-8-sig') as output_file:\n\t\tfor file in file_list:\n\t\t\tif file not in (filepath for filepath in rejected_files):\n\t\t\t\twith io.open(file, 'r', encoding='utf-8-sig', errors='ignore') as input_file:\n\t\t\t\t\toutput_file.write(input_file.read())\n\t\t\t\t\tnb_files += 1\n\n\tprint(\"\tNumber of files loaded : %d\" %nb_files)\n\ndef clean_text(inputFile, outputFile, zip_files):\n\n\tlast_char = ''\n\n\topening_header = [u'Project Gutenberg', u'Project gutenberg', u'project gutenberg']\n\topening_footer = [u'END OF', u'End of']\n\n\tclosure_header = [u'START OF', u'Start of']\n\tclosure_footer = [u'subscribe']\n\n\tuseless_chars = [u'_']\n\n\tuseless_pattern = [re.compile(\"<.+>\"), re.compile(\"\")]\n\n\tskip_patterns = [u'=>', u'<=', u' ']\n\n\topening_chars = [u'(', u'[', u'{']\n\tclosure_chars = [u')', u']', u'}']\n\tflags_chars = [0, 0, 0]\n\tdont_write_char = 0\n\tdont_write_line = 0\n\tskip_line = 1\n\n\n\twith io.open(inputFile, 'r', encoding='utf-8-sig', errors='ignore') as input_file, io.open(outputFile, 'w', encoding='utf-8-sig') as output_file:\n\t\tfor line in input_file:\n\n\t\t\tif any(op_h in line for op_h in opening_header) or any(op_f in line for op_f in opening_footer):\n\t\t\t\tdont_write_line = 1\n\n\t\t\telif re.compile(\"Produced\").match(line):\n\t\t\t\tskip_line += 5\n\n\t\t\telif line.isupper() and not (any(op_c in line for op_c in opening_chars) or any(cl_c in line for cl_c in closure_chars)):\n\t\t\t\tskip_line += 1\n\n\t\t\telif not line.strip():\n\t\t\t\tskip_line += 1\n\n\t\t\telse:\n\t\t\t\tfor pattern in skip_patterns:\n\t\t\t\t\tif pattern in line and not any(op_c in line for op_c in opening_chars) and not any(cl_c in line for cl_c in closure_chars):\n\t\t\t\t\t\tskip_line += 1\n\t\t\t\t\t\tbreak\n\n\t\t\t\tfor pattern in useless_pattern:\n\t\t\t\t\tif pattern.search(line):\n\t\t\t\t\t\tline = re.sub(pattern, \"\", line)\n\t\t\t\n\n\t\t\tif dont_write_line == 0 and skip_line == 0:\n\t\t\t\tfor char in line:\n\t\t\t\t\tif not char in useless_chars:\n\t\t\t\t\t\t\n\t\t\t\t\t\tif char in opening_chars:\n\t\t\t\t\t\t\tflags_chars[opening_chars.index(char)] += 1\n\n\t\t\t\t\t\tif last_char == u'>':\n\t\t\t\t\t\t\tif char == u'>':\n\t\t\t\t\t\t\t\tchar = u' »'\n\t\t\t\t\t\t\telif not any(flag > 0 for flag in flags_chars):\n\t\t\t\t\t\t\t\toutput_file.write(u\">\")\n\n\t\t\t\t\t\telif char == u'>':\n\t\t\t\t\t\t\tdont_write_char = 1\n\n\t\t\t\t\t\tif last_char == u'<':\n\t\t\t\t\t\t\tif char == u'<':\n\t\t\t\t\t\t\t\tchar = u'« '\n\t\t\t\t\t\t\telif not any(flag > 0 for flag in flags_chars):\n\t\t\t\t\t\t\t\toutput_file.write(u\"<\")\n\n\t\t\t\t\t\telif char == u'<':\n\t\t\t\t\t\t\tdont_write_char = 1\n\n\t\t\t\t\t\tif last_char == u'-':\n\t\t\t\t\t\t\tif char == u'-':\n\t\t\t\t\t\t\t\tchar = u'— '\n\t\t\t\t\t\t\telif not any(flag > 0 for flag in flags_chars):\n\t\t\t\t\t\t\t\toutput_file.write(u\"-\")\n\n\t\t\t\t\t\telif char == u'-':\n\t\t\t\t\t\t\tdont_write_char = 1\n\n\t\t\t\t\t\tif all(flag == 0 for flag in flags_chars) and dont_write_char == 0:\n\t\t\t\t\t\t\toutput_file.write(char)\n\n\t\t\t\t\t\telif char in closure_chars:\n\t\t\t\t\t\t\tflags_chars[closure_chars.index(char)] -= 1\n\n\t\t\t\t\t\tdont_write_char = 0\n\t\t\t\t\t\tlast_char = char\n\n\t\t\telif any(cl_h in line for cl_h in closure_header) or any(cl_f in line for cl_f in closure_footer):\n\t\t\t\tdont_write_line = 0\n\t\t\t\n\t\t\tif skip_line > 0:\n\t\t\t\tskip_line -= 1\n\tif zip_files == True:\n\t\twith zipfile.ZipFile(outputFile[:-4] + \".zip\", \"w\", zipfile.ZIP_DEFLATED) as fzip:\n\t\t\tfzip.write(outputFile, arcname='input.txt')\n\nif __name__ == '__main__':\n\n\tparser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\tparser.add_argument('--nb_files', type=int, default=100, help='Number of files concatenated and cleaned by the cleaner')\n\tparser.add_argument('--in_dir', type=str, default='gutenberg', help='Directory in which the files are stored')\n\tparser.add_argument('--out_dir', type=str, default='data/french/input.txt', help='Directory in which the clean file will be stored')\n\tparser.add_argument('--name', type=str, default='input', help='Name of the file written by the cleaner')\n\n\targs = parser.parse_args()\n\n\tinpath = args.in_dir\n\toutpath = args.out_dir\n\ttmpath = args.name + '_tmp.txt'\n\n\tstart = time.time()\n\n\tconcatenateFiles(inpath, tmpath)\n\tcleanText(tmpath, outpath)\n\tremove(tmpath)","sub_path":"utils/clean_text.py","file_name":"clean_text.py","file_ext":"py","file_size_in_byte":4941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"410697838","text":"import numpy as np\nfrom pandas import DataFrame\nimport scipy as sc\n\nfrom .utils.crosstabs import (crosstab,\n crosstab_bayes_factor,\n crosstab_df,\n crosstab_odds_ratio,\n crosstab_ztest,\n get_top_bottom_indices,\n top_bottom_crosstab)\nfrom .utils.validate import (check_consistent_length,\n check_array,\n boolean_array)\n\n\ndef ztest(labels, results, threshold=None):\n \"\"\"\n Two-tailed z score for proportions\n\n Parameters\n ----------\n labels : array_like\n categorical labels for each corresponding value of `result` ie. M/F\n\n results : array_like\n binary decision values, if continuous values are supplied then\n the `threshold` must also be supplied to generate binary decisions\n\n threshold : numeric\n value dividing scores into True/False\n\n Returns\n -------\n z-score: float\n test statistic of two-tailed z-test\n z > 1.960 is signficant at p = .05\n z > 2.575 is significant at p = .01\n z > 3.100 is significant at p = .001\n \"\"\"\n\n check_consistent_length(labels, results)\n results = check_array(results)\n\n # convert the results to True/False\n results = boolean_array(results, threshold=threshold)\n # get crosstab for two groups\n ctab = top_bottom_crosstab(labels, results)\n\n zstat, pvalue = crosstab_ztest(ctab)\n return zstat, pvalue\n\n\ndef fisher_exact(labels, results, threshold=None):\n \"\"\"\n Returns odds ratio and p-value of Fisher's exact test\n Uses scipy.stats.fisher_exact, which only works for 2x2 contingency tables\n https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.fisher_exact.html\n\n Parameters\n ----------\n labels : array_like\n categorical labels for each corresponding value of `result` ie. M/F\n\n results : array_like\n binary decision values, if continuous values are supplied then\n the `threshold` must also be supplied to generate binary decisions\n\n threshold : numeric\n value dividing scores into True/False, where result>=threshold == True\n\n Returns\n -------\n oddsratio : float\n This is prior odds ratio and not a posterior estimate.\n pvalue : float\n P-value, the probability of obtaining a distribution at least\n as extreme as the one that was actually observed, assuming that\n the null hypothesis is true.\n \"\"\"\n\n check_consistent_length(labels, results)\n results = check_array(results)\n\n # convert the results to True/False\n results = boolean_array(results, threshold=threshold)\n # get crosstab for two groups\n ctab = top_bottom_crosstab(labels, results)\n\n oddsratio, pvalue = sc.stats.fisher_exact(ctab)\n return oddsratio, pvalue\n\n\ndef chi2(labels, results, threshold=None):\n \"\"\"\n Returns odds ratio and p-value of Chi-square test of independence\n Uses scipy.stats.chi2_contingency, using an Rx2 contingency table\n https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.chi2_contingency.html\n\n Parameters\n ----------\n labels : array_like\n categorical labels for each corresponding value of `result` ie. M/F\n\n results : array_like\n binary decision values, if continuous values are supplied then\n the `threshold` must also be supplied to generate binary decisions\n\n threshold : numeric\n value dividing scores into True/False, where result>=threshold == True\n\n Returns\n -------\n chi2_stat : float\n The test statistic.\n pvalue : float\n P-value, the probability of obtaining a distribution at least\n as extreme as the one that was actually observed, assuming that\n the null hypothesis is true.\n \"\"\"\n\n check_consistent_length(labels, results)\n results = check_array(results)\n\n # convert the results to True/False\n results = boolean_array(results, threshold=threshold)\n ctab = crosstab(labels, results)\n\n chi2_stat, pvalue = sc.stats.chi2_contingency(ctab)[:2]\n return chi2_stat, pvalue\n\n\ndef bayes_factor(labels, results, threshold=None,\n priors=None, top_bottom=True):\n \"\"\"\n Computes the analytical Bayes factor for an nx2 contingency table.\n If matrix is bigger than 2x2, calculates the bayes factor for the entire\n dataset unless top_bottom is set to True. Will always calculate odds ratio\n between largest and smallest diverging groups\n\n\n Adapted from Albert (2007) Bayesian Computation with R,\n 1st ed., pg 178:184\n\n Parameters\n ----------\n labels : array_like\n categorical labels for each corresponding value of `result` ie. M/F\n\n results : array_like\n binary decision values, if continuous values are supplied then\n the `threshold` must also be supplied to generate binary decisions\n\n threshold : numeric, optional\n value dividing scores into True/False, where result>=threshold == True\n\n priors : ndarray, optional, shape (n,2)\n e.g. uniform_prior = np.array([[1,1],[1,1]])\n\n\n Returns\n -------\n\n BF : float,\n bayes factor for the hypothesis of independence\n BF < 1 : support for a hypothesis of dependence\n 1 < BF < 3 : marginal support for independence\n 3 < BF < 20 : moderate support for independence\n 20 < BF < 150 : strong support for independence\n BF > 150 : very strong support for independence\n odds_ratio : float,\n odds ratio for the highest and lowest groups.\n\n Examples\n --------\n TODO : update examples with odds ratios\n\n >>> from biastesting.categorical import bf_ctabs\n >>> ctabs = np.array([[50,50],[50,50]]) # 1:1 hit/miss ratio\n >>> # assuming uniformity\n >>> uniform_prior = np.array([[1,1],[1,1]])\n >>> bf_ctabs(ctabs, uniform_prior) #all same leads to low BF (dependence)\n 0.26162148804907587\n\n >>> biased_prior = np.array([[5,10],[70,10]])\n >>> # all same given strong priors lowers BF (stronger proof of dependence)\n >>> bf_ctabs(ctabs, biased_prior)\n 0.016048077654948357\n\n >>> biased_ctab = np.array([[75,50],[25,50]])\n >>> # biased crosstabs against prior assumption of uniformity\n >>> # large BF (strong proof of independence)\n >>> bf_ctabs(biased_ctab, biased_prior)\n 202.95548692414306\n\n >>> # assuming a large prior bias in one direction\n >>> # conteracts a large observed dataset in the opposite direction\n >>> bf_ctabs(biased_ctab, biased_prior)\n 0.00012159518854984268\n \"\"\"\n check_consistent_length(labels, results)\n results = check_array(results)\n\n # convert the results to True/False\n results = boolean_array(results, threshold=threshold)\n ctab = crosstab_df(labels, results)\n\n if top_bottom:\n used_indices = list(get_top_bottom_indices(ctab))\n ctab = ctab.iloc[used_indices]\n\n else:\n used_indices = list(ctab.index)\n\n if priors:\n prior = DataFrame(priors)\n prior = prior.iloc[used_indices]\n prior = prior.values\n else:\n prior = np.ones(shape=ctab.shape)\n\n ctab = ctab.values\n\n BF = crosstab_bayes_factor(ctab, prior)\n oddsratio = crosstab_odds_ratio(ctab)\n\n return oddsratio, BF\n","sub_path":"auditai/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":7386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"70374949","text":"import FWCore.ParameterSet.Config as cms\n\nfrom Configuration.Generator.PythiaUEZ2starSettings_cfi import *\n\ngenerator = cms.EDFilter(\"Pythia6GeneratorFilter\",\n pythiaHepMCVerbosity = cms.untracked.bool(False),\n maxEventsToPrint = cms.untracked.int32(0),\n pythiaPylistVerbosity = cms.untracked.int32(1),\n filterEfficiency = cms.untracked.double(1.),\n crossSection = cms.untracked.double(0.0343),\n comEnergy = cms.double(13000.0),\n PythiaParameters = cms.PSet(\n pythiaUESettingsBlock,\n processParameters = cms.vstring(\n 'MSEL = 0 ! User defined process',\n 'MSUB(354) = 1 ! Heavy neutrino',\n 'MSTJ(41) = 2 ! Pythia QED bremsshtrahlung',\n 'PMAS(C9900024,1) = 2700. ! WR Mass',\n 'PMAS(C9900012,1) = 1350. ! nu_Re',\n 'PMAS(C9900014,1) = 1350. ! nu_Rmu',\n 'PMAS(C9900016,1) = 1350. ! nu_Rtau',\n '9900024:alloff',\n '9900024:onifany = 9900016'),\n parameterSets = cms.vstring('pythiaUESettings', 'processParameters')\n )\n)\n\nProductionFilterSequence = cms.Sequence(generator)\n","sub_path":"Configuration/GenProduction/python/ThirteenTeV/WRToNuTauToTauTau_M_2700_M_1350_TuneCUETP8M1_tauola_13TeV_pythia6_cfi.py","file_name":"WRToNuTauToTauTau_M_2700_M_1350_TuneCUETP8M1_tauola_13TeV_pythia6_cfi.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"250138872","text":"# import the required libraries\nimport numpy as np\nimport time\nimport random\nimport cPickle\nimport codecs\nimport collections\nimport os\nimport math\nimport json\nimport csv\nimport tensorflow as tf\nfrom six.moves import xrange\n\n# libraries required for visualisation:\nfrom IPython.display import SVG, display\nimport svgwrite # conda install -c omnia svgwrite=1.1.6\nimport PIL\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n# set numpy output to something sensible\nnp.set_printoptions(precision=8, edgeitems=6, linewidth=200, suppress=True)\ntf.logging.info(\"TensorFlow Version: %s\", tf.__version__)\n\n# import our command line tools\nfrom magenta.models.sketch_rnn.sketch_rnn_train import *\nfrom magenta.models.sketch_rnn.model import *\nfrom magenta.models.sketch_rnn.utils import *\nfrom magenta.models.sketch_rnn.rnn import *\n\n# little function that displays vector images and saves them to .svg\ndef draw_strokes(data, factor=0.2, svg_filename = '/tmp/sketch_rnn/svg/sample.svg'):\n tf.gfile.MakeDirs(os.path.dirname(svg_filename))\n min_x, max_x, min_y, max_y = get_bounds(data, factor)\n dims = (50 + max_x - min_x, 50 + max_y - min_y)\n dwg = svgwrite.Drawing(svg_filename, size=dims)\n dwg.add(dwg.rect(insert=(0, 0), size=dims,fill='white'))\n lift_pen = 1\n abs_x = 25 - min_x \n abs_y = 25 - min_y\n p = \"M%s,%s \" % (abs_x, abs_y)\n command = \"m\"\n for i in xrange(len(data)):\n if (lift_pen == 1):\n command = \"m\"\n elif (command != \"l\"):\n command = \"l\"\n else:\n command = \"\"\n x = float(data[i,0])/factor\n y = float(data[i,1])/factor\n lift_pen = data[i, 2]\n p += command+str(x)+\",\"+str(y)+\" \"\n the_color = \"black\"\n stroke_width = 1\n dwg.add(dwg.path(p).stroke(the_color,stroke_width).fill(\"none\"))\n dwg.save()\n display(SVG(dwg.tostring()))\n\n# generate a 2D grid of many vector drawings\ndef make_grid_svg(s_list, grid_space=10.0, grid_space_x=16.0):\n def get_start_and_end(x):\n x = np.array(x)\n x = x[:, 0:2]\n x_start = x[0]\n x_end = x.sum(axis=0)\n x = x.cumsum(axis=0)\n x_max = x.max(axis=0)\n x_min = x.min(axis=0)\n center_loc = (x_max+x_min)*0.5\n return x_start-center_loc, x_end\n x_pos = 0.0\n y_pos = 0.0\n result = [[x_pos, y_pos, 1]]\n for sample in s_list:\n s = sample[0]\n grid_loc = sample[1]\n grid_y = grid_loc[0]*grid_space+grid_space*0.5\n grid_x = grid_loc[1]*grid_space_x+grid_space_x*0.5\n start_loc, delta_pos = get_start_and_end(s)\n\n loc_x = start_loc[0]\n loc_y = start_loc[1]\n new_x_pos = grid_x+loc_x\n new_y_pos = grid_y+loc_y\n result.append([new_x_pos-x_pos, new_y_pos-y_pos, 0])\n\n result += s.tolist()\n result[-1][2] = 1\n x_pos = new_x_pos+delta_pos[0]\n y_pos = new_y_pos+delta_pos[1]\n return np.array(result)\n\ndef encode(sess, sample_model, eval_model, model,\n input_strokes):\n strokes = to_big_strokes(input_strokes).tolist()\n strokes.insert(0, [0, 0, 1, 0, 0])\n \n del strokes[126:]\n #if strokes[6][4] != 1.0:\n # print(strokes)\n \n seq_len = [len(input_strokes)]\n #draw_strokes(to_normal_strokes(np.array(strokes)))\n return sess.run(eval_model.batch_z, feed_dict={eval_model.input_data: [strokes], eval_model.sequence_lengths: seq_len})[0]\n\ndef decode(sess, sample_model, eval_model, model,\n z_input=None, draw_mode=True, temperature=0.1, factor=0.2):\n z = None\n if z_input is not None:\n z = [z_input]\n sample_strokes, m = sample(sess, sample_model, seq_len=eval_model.hps.max_seq_len, temperature=temperature, z=z)\n strokes = to_normal_strokes(sample_strokes)\n if draw_mode:\n draw_strokes(strokes, factor)\n return strokes\n\ndef main():\n \n data_dir = './image_full_npz'\n model_dir = './rnn_model_2'\n\n '''\n [train_set, valid_set, test_set, hps_model, eval_hps_model, sample_hps_model] = load_env(data_dir, model_dir)\n \n # construct the sketch-rnn model here:\n reset_graph()\n model = Model(hps_model)\n eval_model = Model(eval_hps_model, reuse=True)\n sample_model = Model(sample_hps_model, reuse=True)\n \n sess = tf.InteractiveSession()\n sess.run(tf.global_variables_initializer())\n \n # loads the weights from checkpoint into our model\n load_checkpoint(sess, model_dir)\n #load stroke\n while(1):\n stroke = test_set.random_sample()\n print(stroke)\n draw_strokes(stroke)\n z = encode(sess, sample_model, eval_model, model, stroke)\n\n data_dir = './image_full_npz'\n model_dir = './rnn_model_2'\n [train_set, valid_set, test_set, hps_model, eval_hps_model, sample_hps_model] = load_env(data_dir, model_dir)\n '''\n test = [[[ 14, -12, 0],\n [ 58, -24, 0],\n [ 58, -17, 0],\n [ 53, -5, 0],\n [ 49, 4, 1],\n [-229, 55, 0],\n [ 0, 10, 0],\n [ 11, 21, 0],\n [ 11, 9, 0],\n [ 20, 8, 0],\n [ 26, 5, 0],\n [ 77, 0, 0],\n [ 19, -4, 0],\n [ 16, -8, 0],\n [ 21, -34, 0],\n [ 24, -63, 1],\n [-108, 14, 0],\n [ -16, 4, 0],\n [ -14, 15, 0],\n [ -6, 26, 0],\n [ 2, 12, 0],\n [ 7, 10, 0],\n [ 31, 10, 0],\n [ 16, -1, 0],\n [ 13, -6, 0],\n [ 9, -10, 0],\n [ 4, -12, 0],\n [ -9, -24, 0],\n [ -25, -14, 1],\n [ -87, -4, 0],\n [ -41, -49, 1],\n [ 85, 31, 0],\n [ -9, -47, 1],\n [ 74, 37, 0],\n [ 11, -30, 0],\n [ 15, -25, 1]]]\n [hps_model, eval_hps_model, sample_hps_model] = load_model(model_dir)\n # construct the sketch-rnn model here:\n reset_graph()\n model = Model(hps_model)\n eval_model = Model(eval_hps_model, reuse=True)\n sample_model = Model(sample_hps_model, reuse=True)\n \n sess = tf.InteractiveSession()\n sess.run(tf.global_variables_initializer())\n \n # loads the weights from checkpoint into our model\n load_checkpoint(sess, model_dir)\n #load stroke\n test_set = DataLoader(\n test,\n batch_size=1,\n max_seq_length=125,\n random_scale_factor=0.0,\n augment_stroke_prob=0.0)\n normalizing_scale_factor = test_set.calculate_normalizing_scale_factor()\n test_set.normalize(normalizing_scale_factor)\n stroke = test_set.strokes[0]\n print(stroke)\n draw_strokes(stroke)\n z = encode(sess, sample_model, eval_model, model, stroke)\n print(z)\n z_means = np.load('z_means.npy')\n diff = np.zeros(5)\n for j in range(5):\n diff[j] = np.linalg.norm(z - z_means[j])\n name = ['eye', 'finger', 'foot', 'hand', 'leg']\n print(name[np.argmin(diff)])\n \n \n '''\n \n data_dir = './image_full_npz'\n model_dir = './rnn_model_2'\n [train_set, valid_set, test_set, hps_model, eval_hps_model, sample_hps_model] = load_env(data_dir, model_dir)\n \n # construct the sketch-rnn model here:\n reset_graph()\n model = Model(hps_model)\n eval_model = Model(eval_hps_model, reuse=True)\n sample_model = Model(sample_hps_model, reuse=True)\n \n sess = tf.InteractiveSession()\n sess.run(tf.global_variables_initializer())\n \n # loads the weights from checkpoint into our model\n load_checkpoint(sess, model_dir)\n \n csvfile = open('leg.csv', 'wb')\n csvwriter = csv.writer(csvfile, delimiter=',')\n for i in range(len(train_set.strokes)):\n if i%500 == 0:\n print(i)\n stroke = train_set.strokes[i]\n z = encode(sess, sample_model, eval_model, model, stroke)\n csvwriter.writerow(z)\n '''\n \nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n\n\n\n\n\n","sub_path":"load_model.py","file_name":"load_model.py","file_ext":"py","file_size_in_byte":7808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"129867471","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : Mon Apr 29 11:47:21 2019\n# @Author : JRP - Ruipeng Jia\n\nimport sys\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QIcon, QFont\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QWidget, \\\n QDesktopWidget, \\\n QFormLayout, QVBoxLayout, QHBoxLayout, \\\n QLineEdit, QTextEdit, QPushButton, QLabel, \\\n QCheckBox, QMessageBox, QDialogButtonBox, QGroupBox, QComboBox, QSpinBox\n\n\nclass MyDialog(QDialog):\n def __init__(self, frame):\n super().__init__()\n self.frame = frame\n\n self.ledit = QLineEdit()\n btn = QPushButton('Get', self)\n btn.clicked.connect(self.on_click)\n\n hbox = QHBoxLayout()\n hbox.addWidget(self.ledit)\n hbox.addWidget(btn)\n self.setLayout(hbox)\n\n self.setGeometry(400, 400, 350, 300)\n self.setWindowTitle('Simple')\n\n def on_click(self):\n text = self.ledit.text()\n self.frame.ledit.setText(text)\n\n\nclass MyWidget(QWidget):\n def __init__(self):\n super().__init__()\n self.dig = MyDialog(self)\n\n self.ledit = QLineEdit()\n btn = QPushButton('Dialog', self)\n btn.clicked.connect(self.on_click)\n\n hbox = QHBoxLayout()\n hbox.addWidget(self.ledit)\n hbox.addWidget(btn)\n self.setLayout(hbox)\n\n self.setGeometry(300, 300, 350, 300)\n self.setWindowTitle('Simple')\n self.show()\n\n def on_click(self):\n self.dig.show()\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n my_widget = MyWidget()\n sys.exit(app.exec_())\n","sub_path":"bin/template/src/jptqt/l53_pop_dialog.py","file_name":"l53_pop_dialog.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"279835890","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 getIntersectionNode(self, headA, headB):\n prevA, currA, countA, prevB, currB, countB = None, headA, 0, None, headB, 0\n while currA is not None: prevA, currA, countA = currA, currA.next, countA+1\n while currB is not None: prevB, currB, countB = currB, currB.next, countB+1\n if prevA is not prevB: return None\n currA, currB = headA, headB\n while currA is not currB:\n if countA - countB > 0: countA, currA = countA-1, currA.next\n elif countA - countB < 0: countB, currB = countB-1, currB.next\n else: currA, currB = currA.next, currB.next\n return currA","sub_path":"src/cgml/leetcode/facebook/linkedlist/_004_ll_intersection.py","file_name":"_004_ll_intersection.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"82499351","text":"import datetime\nfrom typing import Optional\n\nimport jwt\n\nfrom django.conf import settings\n\nfrom pitter.exceptions import AccessTokenInvalid\nfrom pitter.models import User\n\n\nclass JwtTokenAuth:\n @classmethod\n def check_token(cls, auth_type: str, token: str) -> Optional[dict]:\n if auth_type != 'Bearer':\n raise AccessTokenInvalid()\n\n try:\n decoded = jwt.decode(token.encode('utf-8'), settings.JWT_PUBLIC_KEY, algorithms=['RS256'])\n except Exception:\n raise AccessTokenInvalid()\n\n return decoded\n\n @classmethod\n def create_user_token(cls, user: User, exp: datetime.timedelta):\n jwt_payload = {\n 'user_id': user.id,\n 'exp': datetime.datetime.utcnow() + exp\n }\n\n return jwt.encode(\n jwt_payload,\n settings.JWT_PRIVATE_KEY,\n algorithm='RS256'\n ).decode('utf-8')\n","sub_path":"src/pitter/utils/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"514276568","text":"import requests\nimport json\nimport pandas as pd\n\ncsv = pd.read_csv('/home/ubuntu/ml/example.csv')\n\n\nfor ind, item in csv.iterrows():\n print(requests.post(url=\"http://demo131.delta.vkhackathon.com:8001/record/api\", data=json.dumps(\n {'text': u'на подарок', 'timestamp': item['local_datetime']}\n )))\n\n if ind == 5:\n break\n","sub_path":"mweb/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"243107888","text":"import matplotlib as mpl\nmpl.rcdefaults()\nmpl.rcParams.update(mpl.rc_params_from_file('meine-matplotlibrc'))\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.constants as const\nimport uncertainties.unumpy as unp\nfrom uncertainties import ufloat\nfrom uncertainties.unumpy import (\n nominal_values as noms,\n std_devs as stds,\n)\nimport Regression as reg\n\nfrom curve_fit import ucurve_fit\nfrom table import (\n make_table,\n make_full_table,\n make_composed_table,\n make_SI,\n write,\n)\n\n### Bestimmung der Dichte\n\nL1, kante1 = np.genfromtxt('Messwerte/Material1_laenge_seitenlaenge.txt', unpack=True)\ngewicht_stab1 = np.genfromtxt('Messwerte/Material1_gewicht.txt', unpack=True) #gram\ngewicht_stab1*=1e-3\nL1*=1e-2 #meter\nkante1*=1e-3 #meter\nL1_mittel = ufloat(np.mean(L1), np.std(L1))\nwrite('build/L1_mittel.tex', make_SI(L1[0], r'\\meter', figures=1))\nkante1_mittel = ufloat(np.mean(kante1), np.std(kante1))\nwrite('build/kante1_mittel.tex', make_SI(kante1_mittel*1e3,r'\\meter','e-3', figures=1))\nprint(kante1_mittel)\n\nrho1 = gewicht_stab1/(kante1_mittel**2 * L1_mittel) # m/V kg/m^3\nwrite('build/rho1.tex', make_SI(rho1, r'\\kilo\\gram\\per\\cubic\\meter', figures=1))\nprint('dichte')\nprint(rho1)\n\n\nL2, kante2 = np.genfromtxt('Messwerte/Material2_laenge_seitenlaenge.txt', unpack=True)\ngewicht_stab2 = np.genfromtxt('Messwerte/Material2_gewicht.txt', unpack=True) #gram\ngewicht_stab2*=1e-3\nL2*=1e-2 #meter\nkante2*=1e-3 #meter\nL2_mittel = ufloat(np.mean(L2), np.std(L2))\nwrite('build/L2_mittel.tex', make_SI(L2[0], r'\\meter', figures=1))\nkante2_mittel = ufloat(np.mean(kante2), np.std(kante2))\nwrite('build/kante2_mittel.tex', make_SI(kante2_mittel*1e3,r'\\meter','e-3', figures=1))\n\nrho2 = gewicht_stab2/(np.pi*((kante2_mittel/2)**2) * L2_mittel) # m/V kg/m^3\nwrite('build/rho2.tex', make_SI(rho2, r'\\kilo\\gram\\per\\cubic\\meter', figures=1))\nprint('dichte Alu')\nprint(rho2)\n\n\n\n\n\nL_1, masse_1 = np.genfromtxt('Messwerte/Material1_eingespannt_laenge_gewicht.txt', unpack=True) # cm #gram\nprint(L_1)\nL_1 *=1e-2 #meter\nmasse_1*=1e-3 #Kilogram\n\nD_o, D_m, x = np.genfromtxt('Messwerte/Material1_eingespannt.txt', unpack=True) #mm #mm #cm\nx*=1e-2 #meter\nD_o*=1e-3 #meter\nD_m*=1e-3 #meter\n\nD_x = D_o - D_m #meter\nx_achse = L_1*x**2 - ((x**3)/3) #meter\nprint(D_x)\n\nwrite('build/Material1_messdaten.tex', make_table([x[::-1]*1e3, D_o[::-1]*1e3, D_m[::-1]*1e3,D_x[::-1]*1e3, x_achse[::-1]*1e3], [2, 2, 2,2,2]))\nwrite('build/Material1_messdaten_texformat.tex', make_full_table(\n 'Messdaten Material 1.',\n 'table:Material1_messdaten',\n 'build/Material1_messdaten.tex',\n [], # Hier aufpassen: diese Zahlen bezeichnen diejenigen resultierenden Spaltennummern,\n# # die Multicolumns sein sollen\n [\n r'$x \\:/\\: \\si{\\milli\\meter}$',\n r'$D_\\text{ohne} \\:/\\: \\si{\\milli\\meter}$',\n r'$D_\\text{mit} \\:/\\: \\si{\\milli\\meter}$',\n r'$D_\\text{x} \\:/\\: \\si{\\milli\\meter}$',\n r'$L_1 x^2-\\frac{x^3}{3} \\:/\\: \\si{\\milli\\meter}$']))\n\n### Berechnung des E-moduls für Material1\n\nplt.plot(x_achse[::-1]*1e3,D_x[::-1]*1e3, 'rx', label='Messdaten')\nplt.ylabel(r'$U \\:/\\: \\si{\\volt}$')\nplt.xlabel(r'$t \\:/\\: \\si{\\milli\\second}$')\nplt.legend(loc='best')\nplt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)\n\nparams = ucurve_fit(reg.reg_linear, x_achse[::-1] , D_x[::-1])\nt_plot = np.linspace(0, 90, 2)\nplt.plot(t_plot, reg.reg_linear(t_plot, *noms(params)), 'b-', label='$Fit_\\t{1}$')\n\nplt.ylabel(r'$D(x) \\:/\\: \\si{\\milli\\meter}$')\nplt.xlabel(r'$L_1 x^2-\\frac{x^3}{3} \\:/\\: \\si{\\milli\\meter}$')\nplt.legend(loc='best')\nplt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)\nplt.savefig('build/Material1.pdf')\nplt.clf()\n\nprint('m und b')\nprint(params[0])\nprint(params[1])\n\n### Flächenträgheitsmoment\n\nI_eckig= kante1_mittel**4/12 #meter^4\nwrite('build/I_eckig.tex', make_SI(I_eckig*1e12, r'\\meter\\tothe{4}','e-12', figures=1))\nprint(I_eckig)\n##########################\n\nE_eckig=(9.81*masse_1)/(2*I_eckig*params[0]) #kilogram*(m*s^2)/m^4\nwrite('build/E_eckig.tex', make_SI(E_eckig*1e-9, r'\\newton\\per\\meter\\tothe{2}','e9', figures=1))\nprint('Elastizitätsmodul')\nprint(E_eckig)\n#Juhuuuu es ist Fe\n\n\n###################################\n#Material2\n###################################\n\nL_2, masse_2 = np.genfromtxt('Messwerte/Material2_eingespannt_laenge_gewicht.txt', unpack=True) # cm #gram\nL_2 *=1e-2 #meter\nmasse_2*=1e-3 #Kilogram\n\nD2_o, D2_m, x2 = np.genfromtxt('Messwerte/Material2_eingespannt.txt', unpack=True) #mm #mm #cm\nx2*=1e-2 #meter\nD2_o*=1e-3 #meter\nD2_m*=1e-3 #meter\n\nD2_x = D2_o - D2_m #meter\nx2_achse = L_2*x2**2 - ((x2**3)/3) #meter\nprint(D2_x)\n\n\nwrite('build/Material2_messdaten.tex', make_table([x2[::-1]*1e3, D2_o[::-1]*1e3, D2_m[::-1]*1e3,D2_x[::-1]*1e3, x2_achse[::-1]*1e3], [2, 2, 2,2,2]))\nwrite('build/Material2_messdaten_texformat.tex', make_full_table(\n 'Messdaten Material 2.',\n 'table:Material2_messdaten',\n 'build/Material2_messdaten.tex',\n [], # Hier aufpassen: diese Zahlen bezeichnen diejenigen resultierenden Spaltennummern,\n# # die Multicolumns sein sollen\n [\n r'$x \\:/\\: \\si{\\milli\\meter}$',\n r'$D_\\text{ohne} \\:/\\: \\si{\\milli\\meter}$',\n r'$D_\\text{mit} \\:/\\: \\si{\\milli\\meter}$',\n r'$D_\\text{x} \\:/\\: \\si{\\milli\\meter}$',\n r'$L_2 x^2-\\frac{x^3}{3} \\:/\\: \\si{\\milli\\meter}$']))\n\n### Berechnung des E-moduls für Material2\n\nplt.plot(x2_achse[::-1]*1e3,D2_x[::-1]*1e3, 'rx', label='Messdaten')\n\nplt.legend(loc='best')\nplt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)\n\nparams = ucurve_fit(reg.reg_linear, x2_achse[::-1] , D2_x[::-1])\nt_plot = np.linspace(0, 90, 2)\nplt.plot(t_plot, reg.reg_linear(t_plot, *noms(params)), 'b-', label='$Fit_\\t{2}$')\n\nplt.ylabel(r'$D(x) \\:/\\: \\si{\\milli\\meter}$')\nplt.xlabel(r'$L_2 x^2-\\frac{x^3}{3} \\:/\\: \\si{\\milli\\meter}$')\nplt.legend(loc='best')\nplt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)\nplt.savefig('build/material2.pdf')\nplt.clf()\nwrite('build/m2.tex', make_SI(params[0], r'1\\per\\milli\\meter\\tothe{2}',figures=1))\nprint('m und b')\nprint(params[0])\n\nprint(params[1])\n\n### Flächenträgheitsmoment\n\nI_rund= (kante2_mittel**4 * np.pi)/64 #meter^4\nwrite('build/I_rund.tex', make_SI(I_rund*1e12, r'\\meter\\tothe{4}','e-12',figures=1))\nprint('I_rund')\nprint(I_rund)\n##########################\n\nE_rund=(9.81*masse_2)/(2*I_rund*params[0]) #kilogram*(m*s^2)/m^4\nwrite('build/E_rund.tex', make_SI(E_rund*1e-9, r'\\newton\\per\\meter\\tothe{2}','e9', figures=1))\nprint('Elastizitätsmodul')\nprint(E_rund)\n\n\n#################################\n# Material1 beidseitig eigespannt\n#################################\n\nL_3, masse_3 = np.genfromtxt('Messwerte/Material1_zweifach_eingespannt_laenge_gewicht.txt', unpack=True) # cm #gram\nL_3 *=1e-2 #meter\nmasse_3*=1e-3 #Kilogram\n\nD3_o, D3_m, x3 = np.genfromtxt('Messwerte/Material1_zweifach_eingespannt_teil1.txt', unpack=True) #mm #mm #cm\nx3*=1e-2 #meter\nD3_o*=1e-3 #meter\nD3_m*=1e-3 #meter\n\nD3_x = D3_o - D3_m #meter\nx3_achse = 3*L_3**2*x3 - 4*x3**3 #meter\n\nwrite('build/Material3_messdaten.tex', make_table([x3*1e3, D3_o*1e3, D3_m*1e3,D3_x*1e3, x3_achse*1e3], [2, 2, 2,2,2]))\nwrite('build/Material3_messdaten_texformat.tex', make_full_table(\n 'Messdaten Material 1, beidseitig eingespannt.',\n 'table:Material3_messdaten',\n 'build/Material3_messdaten.tex',\n [], # Hier aufpassen: diese Zahlen bezeichnen diejenigen resultierenden Spaltennummern,\n# # die Multicolumns sein sollen\n [\n r'$x \\:/\\: \\si{\\milli\\meter}$',\n r'$D_\\text{ohne} \\:/\\: \\si{\\milli\\meter}$',\n r'$D_\\text{mit} \\:/\\: \\si{\\milli\\meter}$',\n r'$D_\\text{x} \\:/\\: \\si{\\milli\\meter}$',\n r'$L_1 x^2-\\frac{x^3}{3} \\:/\\: \\si{\\milli\\meter}$']))\n\n\nplt.plot(x3_achse*1e3,D3_x*1e3, 'rx', label='Messdaten')\n\n\nparams = ucurve_fit(reg.reg_linear, x3_achse , D3_x)\nt_plot = np.linspace(0, 180, 2)\nplt.plot(t_plot, reg.reg_linear(t_plot, *noms(params)), 'b-', label='$Fit_\\t{3}$')\n\nplt.ylabel(r'$D(x) \\:/\\: \\si{\\milli\\meter}$')\nplt.xlabel(r'$L_1 x^2-\\frac{x^3}{3} \\:/\\: \\si{\\milli\\meter}$')\nplt.legend(loc='best')\nplt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)\nplt.savefig('build/material3.pdf')\nplt.clf()\n\nwrite('build/m_teil1.tex', make_SI(params[0], r'1\\per\\meter\\tothe{2}','e-12',figures=1))\nE_teil_1=(9.81*masse_3)/(48*I_eckig*params[0])\nwrite('build/E_teil_1.tex', make_SI(E_teil_1*1e-9, r'\\newton\\per\\meter\\tothe{2}','e9', figures=1))\n\n\nD4_o, D4_m, x4 = np.genfromtxt('Messwerte/Material1_zweifach_eingespannt_teil2.txt', unpack=True) #mm #mm #cm\nx4*=1e-2 #meter\nD4_o*=1e-3 #meter\nD4_m*=1e-3 #meter\n\nD4_x = D4_o - D4_m #meter\nx4_achse = 4*(x4**3) - 12*L_3*(x4**2) + 9*(L_3**2)*x4 - L_3**3 #meter\n\nwrite('build/Material4_messdaten.tex', make_table([x4*1e3, D4_o*1e3, D4_m*1e3,D4_x*1e3, x4_achse*1e3], [2, 2, 2,2,2]))\nwrite('build/Material4_messdaten_texformat.tex', make_full_table(\n 'Messdaten Material 1, beidseitig eingespannt.',\n 'table:Material4_messdaten',\n 'build/Material4_messdaten.tex',\n [], # Hier aufpassen: diese Zahlen bezeichnen diejenigen resultierenden Spaltennummern,\n# # die Multicolumns sein sollen\n [\n r'$x \\:/\\: \\si{\\milli\\meter}$',\n r'$D_\\text{ohne} \\:/\\: \\si{\\milli\\meter}$',\n r'$D_\\text{mit} \\:/\\: \\si{\\milli\\meter}$',\n r'$D_\\text{x} \\:/\\: \\si{\\milli\\meter}$',\n r'$L_1 x^2-\\frac{x^3}{3} \\:/\\: \\si{\\milli\\meter}$']))\n\n\nplt.plot(x4_achse*1e3,D4_x*1e3, 'rx', label='Messdaten')\n\n\nparams = ucurve_fit(reg.reg_linear, x4_achse , D4_x)\nt_plot = np.linspace(0, 180, 2)\nplt.plot(t_plot, reg.reg_linear(t_plot, *noms(params)), 'b-', label='$Fit_\\t{4}$')\n\nplt.ylabel(r'$D(x) \\:/\\: \\si{\\milli\\meter}$')\nplt.xlabel(r'$L_1 x^2-\\frac{x^3}{3} \\:/\\: \\si{\\milli\\meter}$')\nplt.legend(loc='best')\nplt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)\nplt.savefig('build/material4.pdf')\nplt.clf()\n\nwrite('build/m_teil2.tex', make_SI(params[0], r'1\\per\\meter\\tothe{2}','e-12',figures=1))\n\n\nwrite('build/E_lit_1.tex', make_SI(196, r'\\newton\\per\\meter\\tothe{2}','e9', figures=1))\nwrite('build/E_lit_2.tex', make_SI(70, r'\\newton\\per\\meter\\tothe{2}','e9', figures=1))\n\n# x_achse = x_achse[::-1]\n## FREQUENZLY USED CODE\n#\n## IMPORT\n# t, U, U_err = np.genfromtxt('data.txt', unpack=True)\n# t *= 1e-3\n#\n#\n## ERRORS\n# R_unc = ufloat(R[0],R[2])\n# U = 1e3 * unp.uarray(U, U_err)\n# Rx_mean = np.mean(Rx) # Mittelwert und syst. Fehler\n# Rx_mean_err = MeanError(noms(Rx)) # Fehler des Mittelwertes\n#\n#\n## CURVE FIT\n# def f(t, a, b, c, d):\n# return a * np.sin(b * t + c) + d\n#\n# params = ucurve_fit(f, t, U, p0=[1, 1e3, 0, 0])\n# params = ucurve_fit(reg.reg_linear, x, y) # linearer Fit\n# params = ucurve_fit(reg.reg_quadratic, x, y) # quadratischer Fit\n# params = ucurve_fit(reg.reg_cubic, x, y) # kubischer Fit\n# a, b, c, d = params\n# write('build/loesung-a.tex', make_SI(a * 1e-3, r'\\kilo\\volt', figures=1)) # type in Anz. signifikanter Stellen\n# write('build/loesung-b.tex', make_SI(b * 1e-3, r'\\kilo\\hertz', figures=1))\n# write('build/loesung-c.tex', make_SI(c, r'', figures=1))\n# write('build/loesung-d.tex', make_SI(d * 1e-3, r'\\kilo\\volt', figures=2))\n#\n#\n## PLOTTING\n# t_plot = np.linspace(-0.5, 2 * np.pi + 0.5, 1000) * 1e-3\n# plt.clf\n### AUTOMATICLY CHOSING LIMITS WITH EXISTING ARRAY T1\n## t_plot = np.linspace(np.amin(T1), np.amax(T1), 100)\n## plt.xlim(t_plot[0]-1/np.size(T1)*(t_plot[-1]-t_plot[0]), t_plot[-1]+1/np.size(T1)*(t_plot[-1]-t_plot[0]))\n#\n# plt.plot(t_plot * 1e3, f(t_plot, *noms(params)) * 1e-3, 'b-', label='Fit')\n# plt.plot(t * 1e3, U * 1e3, 'rx', label='Messdaten')\n## plt.errorbar(B * 1e3, noms(y) * 1e5, fmt='rx', yerr=stds(y) * 1e5, label='Messdaten')\n## plt.xscale('log') # logarithmische x-Achse\n# plt.xlim(t_plot[0] * 1e3, t_plot[-1] * 1e3)\n# plt.xlabel(r'$t \\:/\\: \\si{\\milli\\second}$')\n# plt.ylabel(r'$U \\:/\\: \\si{\\kilo\\volt}$')\n# plt.legend(loc='best')\n# plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)\n# plt.savefig('build/loesung-plot.pdf')\n#\n#\n## WRITING TABLES\n# t1, t2 = np.array_split(t * 1e3, 2)\n# U1, U2 = np.array_split(U * 1e-3, 2)\n# write('build/loesung-table.tex', make_table([t1, U1, t2, U2], [3, None, 3, None])) # type in Nachkommastellen\n### ONLY ONE COLUMN IN A TABLE:\n## a=np.array([Wert_d[0]])\n## b=np.array([Rx_mean])\n## c=np.array([Rx_mean_err])\n## d=np.array([Lx_mean*1e3])\n## e=np.array([Lx_mean_err*1e3])\n## write('build/Tabelle_err_d.tex', make_table([a,b,c,d,e],[0, 1, 0, 1, 1]))\n## FULLTABLE\n# write('build/Tabelle_b_texformat.tex', make_full_table(\n# 'Messdaten Kapazitätsmessbrücke.',\n# 'table:A2',\n# 'build/Tabelle_b.tex',\n# [1,2,3,4,5], # Hier aufpassen: diese Zahlen bezeichnen diejenigen resultierenden Spaltennummern,\n## # die Multicolumns sein sollen\n# ['Wert',\n# r'$C_2 \\:/\\: \\si{\\nano\\farad}$',\n# r'$R_2 \\:/\\: \\si{\\ohm}$',\n# r'$R_3 / R_4$', '$R_x \\:/\\: \\si{\\ohm}$',\n# r'$C_x \\:/\\: \\si{\\nano\\farad}$']))\n\n# # Relative Fehler\n# RelFehler_G = (G_mess - G_lit) / G_lit\n# RelFehler_B = (B_mess - B_lit) / B_lit\n# write('build/RelFehler_G.tex', make_SI(RelFehler_G*100, r'\\percent', figures=1))\n# write('build/RelFehler_B.tex', make_SI(RelFehler_B*100, r'\\percent', figures=1))\n#\n#\n## ARRAY FUNCTIONS\n# np.amin(array) # Liefert den kleinsten Wert innerhalb eines Arrays\n# np.argmin(array) # Gibt mir den Index des Minimums eines Arrays zurück\n# np.amax(array) # Liefert den größten Wert innerhalb eines Arrays\n# np.argmax(array) # Gibt mir den Index des Maximums eines Arrays zurück\n#\n# a1,a2 = np.array_split(array, 2) # Array in zwei Hälften teilen\n# np.size(array) # Anzahl der Elemente eines Arrays ermitteln\n#\n#\n## DIFFERENT STUFF\n# R = const.physical_constants[\"molar gas constant\"] # Array of value, unit, error\n","sub_path":"WS15_16/103/PythonSkript.py","file_name":"PythonSkript.py","file_ext":"py","file_size_in_byte":13815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"3626522","text":"from mpi4py import MPI\r\nimport numpy as np\r\n\r\ncomm = MPI.COMM_WORLD\r\nrank = comm.Get_rank()\r\nsize = comm.Get_size()\r\n''' \r\n Approximation of the function f(x) using the extended trapezoid method, distributed on more processes.\r\n It is required to send the parameter of intervals to number of intervals + 1 because we require the rank 0 process\r\n to distribute the data and intervals to other processes using point to point blocking communication.\r\n \r\n\r\n Parameters\r\n ----------\r\n f : function\r\n Vectorized function of a single variable\r\n a , b : numbers\r\n Interval of integration [a,b]\r\n N : integer\r\n Number of sub intervals of [a,b]\r\n x : Array \r\n Return evenly spaced numbers over a specified interval. \r\n numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)\r\n N+1 points make N sub intervals\r\n arrayX : Array\r\n Converts array x into a dtype=np.float64.\r\n dx : float\r\n Lambda, calculates the required length of each array.\r\n k : Array\r\n Used to temporary store received date from other processes.\r\n T : Array\r\n Approximation of the function using sums of each result from the other processes.\r\n y : Array\r\n Inputs f into array y.\r\n a : Array\r\n Temporary array used to store intervals and their data.\r\n y_left : Array\r\n Left endpoints.\r\n y_right: Array\r\n Right endpoints.\r\n G : float\r\n Function used to calculate the approximation using the trapezoid method.\r\n Returns\r\n -------\r\n Array\r\n Approximation of the function of f(x) from a to b using the\r\n trapezoid rule with N sub intervals of equal length.\r\n'''\r\na = 0\r\nb = 6\r\nN = size-1\r\nf = np.square\r\nx = np.linspace(a, b, N+1)\r\narrayX = np.array(x, dtype=np.float64)\r\ndx = (b - a)/N\r\n\r\n\r\nif rank == 0:\r\n print(f(arrayX))\r\n k = np.zeros(1, dtype=np.float64)\r\n T = np.zeros(1, dtype=np.float64)\r\n for i in range(0, size-1):\r\n y = f(arrayX[i:i+2])\r\n print(f(arrayX[i:i+2]))\r\n comm.Send(y, dest=i+1)\r\n comm.Recv(k, source=i+1)\r\n T = T + k\r\n print(T)\r\n\r\n\r\nelif rank != 0:\r\n a = np.zeros(2, dtype=np.float64)\r\n comm.Recv(a, source=0)\r\n y_right = a[0:1] # right endpoint\r\n y_left = a[1:2] # left endpoint\r\n G = (dx / 2) * np.sum(y_right + y_left)\r\n comm.Send(G, dest=0)\r\nelse:\r\n exit()\r\n\r\n","sub_path":"projekat_procesi.py","file_name":"projekat_procesi.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"282203633","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 9 15:37:23 2021\n\n@author: Narmin Ghaffari Laleh\n\"\"\"\n\nimport utils.utils as utils\nimport torch.nn as nn\nimport numpy as np\nimport argparse\nimport torch\nimport os\nimport random\nfrom sklearn import preprocessing\nfrom sklearn import metrics\nfrom dataGenerator.dataset_generic import Generic_MIL_Dataset, Save_splits\nfrom utils.data_utils import SortClini_SlideTables\nfrom utils.core_utils import Accuracy_Logger\nfrom models.model_clam import CLAM_SB, CLAM_MB\nfrom models.model_mil import MIL_fc, MIL_fc_mc\nfrom utils.data_utils import Get_split_loader\nfrom tqdm import tqdm\nimport pandas as pd\nfrom eval.eval_Classic import CalculatePatientWiseAUC\n\n##############################################################################\n\nparser = argparse.ArgumentParser(description = 'Main Script to Run Training')\nparser.add_argument('--adressExp', type = str, default = r\"C:\\Users\\Administrator\\sciebo\\deepHistology\\labMembers\\Narmin\\Architecture Project\\RCC\\AACHEN_RCC_CLAM_TestFull.txt\", help = 'Adress to the experiment File')\nparser.add_argument('--modelAdr', type = str, default = r\"C:\\Users\\Administrator\\sciebo\\deepHistology\\labMembers\\Narmin\\Architecture Project\\RCC\\TCGA_RCC_CLAM_TrainFull_RCC_Subtype\\RESULTS\\s_0_checkpoint.pt\", help = 'Adress to the selected model')\nargs = parser.parse_args()\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(device)\n\n##############################################################################\n\nif __name__ == '__main__':\n \n \n args = utils.ReadExperimentFile(args, deploy = True)\n torch.cuda.set_device(args.gpuNo)\n random.seed(args.seed)\n\n targetLabels = args.target_labels\n args.feature_extract = False\n \n targetLabel = targetLabels[0]\n args.target_label = targetLabel \n args.projectFolder = utils.CreateProjectFolder(args.project_name, args.adressExp, targetLabel, args.model_name)\n\n if os.path.exists(args.projectFolder):\n #raise NameError('THis PROJECT IS ALREADY EXISTS!')\n print('This Project Already Exists!')\n else:\n os.mkdir(args.projectFolder) \n \n reportFile = open(os.path.join(args.projectFolder,'Report.txt'), 'a', encoding=\"utf-8\")\n \n reportFile.write('**********************************************************************'+ '\\n')\n reportFile.write('DEPLOYING...')\n reportFile.write('\\n' + '**********************************************************************'+ '\\n')\n targetLabels = args.target_labels\n \n \n print('\\nLoad the DataSet...') \n\n args.csvPath, labelList = SortClini_SlideTables(imagesPath = args.feat_dir, cliniTablePath = args.clini_dir, slideTablePath = args.slide_dir,\n label = args.target_label, outputPath = args.projectFolder, reportFile = reportFile, csvName = args.csv_name)\n\n\n labelsList = utils.CheckForTargetType(labelList)\n \n le = preprocessing.LabelEncoder()\n labelsList = le.fit_transform(labelsList)\n \n args.num_classes = len(set(labelsList))\n args.target_labelDict = dict(zip(le.classes_, range(len(le.classes_)))) \n\n \n print('\\nLoad the DataSet...') \n \n feat_dir = args.feat_dir[0]\n dataset = Generic_MIL_Dataset(csv_path = args.csvPath,\n data_dir = feat_dir,\n shuffle = False, \n seed = args.seed, \n print_info = True,\n label_dict = args.target_labelDict,\n patient_strat = True,\n label_col = args.target_label,\n ignore = [],\n normalize_targetNum = args.normalize_targetNum,\n normalize_method = 'DownSample',\n reportFile = reportFile)\n \n lf = 1.0 \n \n args.result = os.path.join(args.projectFolder, 'RESULTS')\n os.makedirs(args.result, exist_ok = True) \n args.split_dir = os.path.join(args.projectFolder, 'SPLITS')\n os.makedirs(args.split_dir, exist_ok=True)\n \n dataset.Create_splits(k = 1, val_num = [0] * args.num_classes, test_num = [0] * args.num_classes, label_frac = lf)\n i = 0\n dataset.Set_splits()\n descriptor_df = dataset.Test_split_gen(return_descriptor = True, reportFile = reportFile, fold = i)\n \n splits = dataset.Return_splits(from_id = True)\n Save_splits(split_datasets = splits, column_keys = ['train'], filename = os.path.join(args.split_dir, 'splits_{}.csv'.format(i))) \n descriptor_df.to_csv(os.path.join(args.split_dir, 'splits_{}_descriptor.csv'.format(i))) \n \n train_dataset, val_dataset, test_dataset = dataset.Return_splits(from_id = False, csv_path = args.split_dir + '//splits_{}.csv'.format(i), trainFull = True) \n \n datasets = (train_dataset, val_dataset, test_dataset)\n\n model_dict = {\"dropout\": args.drop_out, 'n_classes': args.num_classes}\n \n if args.model_size is not None and args.model_name != 'mil':\n model_dict.update({\"size_arg\": args.model_size})\n \n if args.model_name in ['clam_sb', 'clam_mb']:\n if args.subtyping:\n model_dict.update({'subtyping': True})\n \n if args.B > 0:\n model_dict.update({'k_sample': args.B})\n \n if args.inst_loss == 'svm':\n from topk import SmoothTop1SVM\n instance_loss_fn = SmoothTop1SVM(n_classes = 2)\n if device.type == 'cuda':\n instance_loss_fn = instance_loss_fn.cuda()\n else:\n instance_loss_fn = nn.CrossEntropyLoss()\n \n if args.model_name =='clam_sb':\n model = CLAM_SB(**model_dict, instance_loss_fn = instance_loss_fn)\n elif args.model_name == 'clam_mb':\n model = CLAM_MB(**model_dict, instance_loss_fn=instance_loss_fn)\n else:\n raise NotImplementedError\n \n else: # args.model_name == 'mil'\n if args.num_classes > 2:\n model = MIL_fc_mc(**model_dict)\n print('It is not there YET!')\n else:\n model = MIL_fc(**model_dict)\n \n model.relocate()\n model.load_state_dict(torch.load(args.modelAdr))\n model.to(device) \n \n acc_logger = Accuracy_Logger(n_classes = args.num_classes)\n model.eval()\n test_error = 0.\n\n test_loader = Get_split_loader(train_dataset, testing = args.testing)\n all_probs = np.zeros((len(test_loader), args.num_classes))\n all_labels = np.zeros(len(test_loader))\n\n slide_ids = test_loader.dataset.slide_data['slide_id']\n case_ids = test_loader.dataset.slide_data['case_id']\n patient_results = {}\n\n for batch_idx, (data, label, coord) in tqdm(enumerate(test_loader)):\n data, label = data.to(device), label.to(device)\n slide_id = slide_ids.iloc[batch_idx]\n case_id = case_ids.iloc[batch_idx]\n with torch.no_grad():\n logits, Y_prob, Y_hat, a_raw, results_dict = model(data)\n \n acc_logger.log(Y_hat, label)\n probs = Y_prob.cpu().numpy()\n all_probs[batch_idx] = probs\n all_labels[batch_idx] = label.item()\n tileScores = list(a_raw.cpu().detach().numpy())\n coords = list(coord[0].cpu().detach().numpy())\n \n patient_results.update({slide_id: {'case_id': case_id,'slide_id': slide_id, 'prob': probs, 'label': label.item(), 'tileScores' : tileScores, 'coords' : coords}})\n error = utils.calculate_error(Y_hat, label)\n test_error += error\n\n case_id_test = []\n slide_id_test = []\n labelList_test = []\n probs_test = {}\n tileScores = {} \n coords = {}\n for i_temp in range(args.num_classes):\n key = utils.get_key_from_value(args.target_labelDict, i_temp)\n probs_test[key] = []\n \n for item in list(patient_results.keys()):\n temp = patient_results[item]\n case_id_test.append(temp['case_id'])\n slide_id_test.append(temp['slide_id'])\n labelList_test.append(temp['label'])\n tileScores[temp['case_id']] = temp['tileScores']\n coords[temp['case_id']] = temp['coords']\n \n for i_temp in range(args.num_classes):\n key = utils.get_key_from_value(args.target_labelDict, i_temp)\n probs_test[key].append(temp['prob'][0, i_temp])\n \n probs_test = pd.DataFrame.from_dict(probs_test)\n tileScores = pd.DataFrame.from_dict(tileScores, orient='index')\n coords = pd.DataFrame.from_dict(coords, orient='index')\n \n df = pd.DataFrame(list(zip(case_id_test, slide_id_test, labelList_test)), columns =['patientID', 'X', 'y'])\n df = pd.concat([df, probs_test], axis = 1)\n df.to_csv(os.path.join(args.result, 'TEST_RESULT_FULL_SCORES_temp.csv'), index = False)\n \n tileScores.to_csv(os.path.join(args.result, 'TileScores.csv'), index = True)\n coords.to_csv(os.path.join(args.result, 'Coords.csv'), index = True)\n \n CalculatePatientWiseAUC(resultCSVPath = os.path.join(args.result, 'TEST_RESULT_FULL_SCORES_temp.csv'), uniquePatients = list(set(case_id_test)),\n target_labelDict = args.target_labelDict, resultFolder = args.result, counter = 'FULL', clamMil = True)\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n","sub_path":"Deploy_CLAM_MIL.py","file_name":"Deploy_CLAM_MIL.py","file_ext":"py","file_size_in_byte":9505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"639035313","text":"import logging\n\nfrom pygments import highlight\nfrom pygments.formatter import Formatter\nfrom pygments.lexers.dotnet import VbNetLexer\nfrom pygments.token import Token\n\nimport obfuscator.modifier.base\nimport obfuscator.msdocument\nfrom obfuscator.util import get_random_string_of_random_length\n\nLOG = logging.getLogger(__name__)\n\n\nclass RandomizeNames(obfuscator.modifier.base.Modifier):\n def run(self, doc: obfuscator.msdocument.MSDocument) -> None:\n doc.code = highlight(doc.code, VbNetLexer(), _RandomizeNamesFormatter())\n\n\ndef _get_or_create(i: str, dct: dict) -> str:\n if i not in dct:\n dct[i] = get_random_string_of_random_length()\n LOG.debug(\"Randomized {}.\".format(i))\n\n return dct[i]\n\n\ndef _blacklisted_functions(f):\n d = {}\n for name in f:\n d[name] = name\n return d\n\n\nclass _RandomizeNamesFormatter(Formatter):\n def __init__(self):\n self.names = _blacklisted_functions({\n \"AutoOpen\", \"Workbook_Open\", \"Shell\", \"Array\", \"LBound\", \"Auto_Open\", \"ActiveDocument\", \"Variables\", \"Chr\",\n \"UBound\", \"Err\", \"Raise\", \"vbObjectError\", \"Asc\", \"H40\", \"H10\", \"HF\", \"Dim\"\n })\n\n def format(self, tokensource, outfile):\n\n for ttype, value in tokensource:\n if ttype == Token.Name.Function:\n outfile.write(self._get_name(value))\n elif ttype == Token.Name:\n outfile.write(self._get_name(value))\n else:\n outfile.write(value)\n\n def _get_name(self, name: str) -> str:\n return _get_or_create(name, self.names)\n","sub_path":"obfuscator/modifier/functions_vars.py","file_name":"functions_vars.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"637954968","text":"from graia.saya import Saya, Channel\nfrom graia.saya.builtins.broadcast.schema import ListenerSchema\n\nfrom graia.application import GraiaMiraiApplication\nfrom graia.application.message.elements.internal import Plain, At, Quote\nfrom graia.application.event.messages import GroupMessage\nfrom graia.application.message.chain import MessageChain\nfrom graia.application.group import Group\nimport aiosonic\nimport json\n\nsaya = Saya.current()\nchannel = Channel.current()\n\n\n@channel.use(ListenerSchema(\n listening_events=[GroupMessage]\n))\nasync def nbnhhsh(message: MessageChain, app: GraiaMiraiApplication, group: Group):\n if message.asDisplay().startswith('nbnhhsh:') or message.asDisplay().startswith('nbnhhsh:'):\n text = message.asDisplay()[8:]\n await app.sendGroupMessage(group, MessageChain.create([\n Plain(text + \":\" + await guess(text))\n ]))\n\n\nasync def guess(text: str) -> str:\n client = aiosonic.HTTPClient()\n resp = await client.post(url='https://lab.magiconch.com/api/nbnhhsh/guess', json={'text': str(text)})\n tran = \"\"\n try:\n trans = json.loads(await resp.content())[0]['trans']\n except KeyError as e:\n print('可能暂时没有这个缩写!')\n print(e)\n await client.shutdown()\n for i in trans:\n if len(trans) == 1:\n tran = i\n break\n else:\n tran += i + \",\"\n return tran\n","sub_path":"unused/nbnhhsh.py","file_name":"nbnhhsh.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"444931807","text":"import socket\nimport time\nimport threading\nimport queue\nimport os\n\n\n# GRPC =================================================\nfrom concurrent import futures\n\nimport grpc\nimport standard_pb2\nimport standard_pb2_grpc\n# ======================================================\n\nDEFAULT_PORT = 23456\nDEFAULT_BUFFER_SIZE = 1024\nDEFAULT_IP_ADDRESS = \"127.0.1.1\"\nDEFAULT_PUBLIC_KEY = \"c144efbb-c793-4d57-b6ed-7ee40321656e\"\n_ONE_DAY_IN_SECONDS = 60 * 60 * 24\nDEFAULT_LOG_NUMBER = 0\n\n\nclass ServerNew(standard_pb2_grpc.StandardServicer):\n\n # Construtor - inicializa as configurações para estabelecer conexões sockets, cria as filas F1, F2 e F3 e o banco de dados (em memória -> dicionário do python)\n def __init__(self):\n\n # Cria o socket TCP/IP\n # self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n # Adquiri o hostname local\n # self.local_hostname = socket.gethostname()\n\n # Adquiri o fully qualified hostname\n # self.local_fqdn = socket.getfqdn()\n\n # Adquiri o endereco ip\n # self.ip_address = socket.gethostbyname(self.local_hostname)\n\n input_port = DEFAULT_PORT\n input_buffer_size = DEFAULT_BUFFER_SIZE\n self.timer = None\n self.time_between_snaps = 10\n\n # Tenta pegar as informações port, buffer_size de settings.txt - caso não exista ele cria um novo settings.txt com os valores fornecidos ou padrões para\n # port, buffer_size e ip_address\n try:\n with open(\"settings.txt\", 'r') as settings:\n i = 0\n for line in settings:\n if i == 0:\n self.port = int(line)\n elif i == 1:\n self.buffer_size = int(line)\n elif i == 2:\n #self.ip_address = line.split('\\n')[0]\n self.ip_address = line.rstrip()\n elif i == 3:\n self.public_key = line\n i += 1\n except IOError:\n with open(\"settings.txt\", \"w\") as settings:\n input_port = int(\n input(\"First run setup - which port to use (1024 < port < 65535)?\\n\"))\n if not (input_port > 1024 and input_port < 65535):\n print(\"Using %d instead.\" % DEFAULT_PORT)\n input_port = DEFAULT_PORT\n settings.write(str(input_port))\n input_buffer_size = int(\n input(\"Size for the buffer (at least 1024)?\\n\"))\n if not (input_buffer_size >= 1024):\n print(\"Using %d instead.\" % DEFAULT_BUFFER_SIZE)\n input_buffer_size = DEFAULT_BUFFER_SIZE\n settings.write(\"\\n\" + str(input_buffer_size))\n self.port = input_port\n self.buffer_size = input_buffer_size\n self.ip_address = DEFAULT_IP_ADDRESS\n self.public_key = DEFAULT_PUBLIC_KEY\n settings.write(\"\\n\" + str(self.ip_address))\n settings.write(\"\\n\" + self.public_key)\n else:\n pass\n\n try:\n with open(\"last_snap.txt\", \"r\") as last_snap:\n for line in last_snap:\n self.logNumber = int(line)\n except IOError:\n with open(\"last_snap.txt\", \"w\") as last_snap:\n last_snap.write(str(DEFAULT_LOG_NUMBER))\n self.logNumber = DEFAULT_LOG_NUMBER\n else:\n pass\n\n # Endereco do servidor\n # print(\"port: %s, buffer-size: %s\" % (self.port, self.buffer_size))\n self.server_address = self.ip_address + \":\" + str(self.port)\n # print(\"server_address = %s, %s\" % self.server_address)\n # Vincula a socket com a porta\n # self.sock.bind(self.server_address)\n\n # Coloca o servidor para escutar conexoes\n # self.sock.listen()\n\n self.event = threading.Event()\n\n self.recv_queue = queue.Queue(maxsize=-1)\n self.log_queue = queue.Queue(maxsize=-1)\n self.execution_queue = queue.Queue(maxsize=-1)\n self.chord_queue = queue.Queue(maxsize=-1)\n\n self.data_base = {}\n\n # Carrega o banco de dados na memória\n def loadDataBase(self):\n\n try:\n with open(\"snap.\" + str(self.logNumber) + \".txt\", \"r\") as file:\n for line in file:\n args = line.split(\" \")\n key = int(args[0])\n data = str(\" \".join(args[1:]))\n data = data.rstrip()\n self.data_base[key] = data\n except:\n pass\n\n try:\n\n with open(\"logfile.\" + str(self.logNumber) + \".txt\", 'r') as log:\n print(\"Restoring from log - \")\n for line in log:\n self.execute_command(True, line)\n print(\"Restored Sucessfuly!\\n\")\n\n except:\n pass\n\n # Recebe os comandos e o coloca em F1\n def recv_command(self, connection, client_address):\n\n print(\"\\nNew connection from %s\\n\" % str(client_address))\n\n while not self.event.is_set():\n data = connection.recv(self.buffer_size).decode()\n if not data:\n break\n self.recv_queue.put((connection, client_address, data))\n connection.close()\n\n # Recebe os comandos GRPC e o coloca em F1\n def recv_command_grpc(self, request, context):\n print(\"Method: %s\\n\" % str(context._rpc_event.call_details.method))\n if request and str(request.key) and (request.value or request.method == \"READ\" or request.method == \"DELETE\"):\n reply = standard_pb2.StandardReply()\n self.recv_queue.put((request, context, reply))\n # TODO: Fazer método que espera enquanto requisição não está pronta.\n while not reply.message:\n pass\n return reply\n else:\n return standard_pb2.StandardReply(message=\"ERROR: Req NOK.\\n\")\n\n # Pega os comandos de F1 e os transporta para F2 e F3\n def transport_command(self):\n\n while not self.event.is_set():\n if not self.recv_queue.empty():\n request, context, reply = self.recv_queue.get()\n self.log_queue.put((request, context))\n self.execution_queue.put((request, context, reply))\n\n # Escreve os comandos de F2 para um arquivo log\n def log_command(self):\n while not self.event.is_set():\n if not self.log_queue.empty():\n with open(\"logfile.\" + str(self.logNumber) + \".txt\", 'w') as log:\n request, _ = self.log_queue.get()\n if request.method != \"READ\":\n log.write(request.method + ' ' + str(request.key) +\n ' ' + str(request.value) + \"\\n\")\n log.flush()\n\n # Executa os comandos em F3 - utilizando das funções CRUD\n def execute_command(self, set_up=False, data=\"\"):\n\n while not self.event.is_set():\n if not self.execution_queue.empty() or set_up:\n if set_up == False:\n request, context, reply = self.execution_queue.get()\n data = str(request.method) + ' '\n data += str(request.key) + ' '\n data += str(request.value)\n\n query = data.split()\n user_command = query[0]\n key = int(query[1])\n user_data = \" \".join(map(str, query[2:])) if len(\n query) > 2 else \"\"\n\n response = \"\"\n server_info = \"\"\n\n # print(\"Comando: \" + user_command)\n if user_command == \"CREATE\":\n response = self.create(key, user_data)\n server_info = \"SERVER - CREATE\"\n\n elif user_command == \"READ\":\n response = self.read(key)\n server_info = \"SERVER - READ\"\n\n elif user_command == \"UPDATE\":\n response = self.update(key, user_data)\n server_info = \"SERVER - UPDATE\"\n\n elif user_command == \"DELETE\":\n response = self.delete(key)\n server_info = \"SERVER - DELETE\"\n\n else:\n response = \"%s not a valid command.\" % user_command\n\n if not set_up:\n server_info += \" (FROM ADDRESS %s)\\n\" % str(\n context._rpc_event.call_details.host)\n print(server_info + response)\n reply.message = response\n else:\n break\n\n # Função a ser chamada para iniciar o servidor - cria as threads e começa a receber conexões\n\n def updateLog(self):\n self.logNumber += 1\n try:\n with open(\"snap.\" + str(self.logNumber) + \".txt\", \"a\") as snap:\n for key in list(self.data_base.keys()):\n snap.write(str(key) + \" \" + self.data_base[key] + \"\\n\")\n snap.flush()\n if os.path.isfile(\"snap.\" + str(self.logNumber - 3) + \".txt\"):\n os.remove(\"snap.\" + str(self.logNumber - 3) + \".txt\")\n if os.path.isfile(\"last_snap.txt\"):\n os.remove(\"last_snap.txt\")\n try:\n with open(\"last_snap.txt\" , \"a\" ) as last_snap:\n last_snap.write(str(self.logNumber))\n except:\n pass\n except:\n pass\n\n if os.path.isfile(\"logfile.\" + str(self.logNumber - 3) + \".txt\"):\n os.remove(\"logfile.\" + str(self.logNumber - 3) + \".txt\")\n\n def snapStart(self):\n while not self.event.is_set():\n time.sleep(self.time_between_snaps)\n self.updateLog()\n \n \n \n \n def start(self):\n\n self.loadDataBase()\n\n transport_thread = threading.Thread(target=self.transport_command)\n transport_thread.setDaemon(True)\n transport_thread.start()\n\n log_thread = threading.Thread(target=self.log_command)\n log_thread.setDaemon(True)\n log_thread.start()\n\n execute_thread = threading.Thread(target=self.execute_command)\n execute_thread.setDaemon(True)\n execute_thread.start()\n\n snap_thread = threading.Thread(target=self.snapStart)\n snap_thread.setDaemon(True)\n snap_thread.start()\n\n # self.run()\n\n # Funções GRPC\n def Restart(self, request, context):\n if (request.public_key == self.public_key):\n print('Restarting server command.')\n self = ServerNew()\n self.start()\n return standard_pb2.StandardReply(message='OK - Restart.\\n')\n else:\n return standard_pb2.StandardReply(message='NOK - Restart.\\n')\n\n def Create(self, request, context):\n request.method = 'CREATE'\n return self.recv_command_grpc(request, context)\n\n def Read(self, request, context):\n request.method = 'READ'\n return self.recv_command_grpc(request, context)\n\n def Update(self, request, context):\n request.method = 'UPDATE'\n return self.recv_command_grpc(request, context)\n\n def Delete(self, request, context):\n request.method = 'DELETE'\n return self.recv_command_grpc(request, context)\n\n # Funções correspondentes ao CRUD\n def create(self, key, value):\n\n if not key in list(self.data_base.keys()):\n self.data_base[key] = value\n response = \"SUCESS: key: %d - value: <%s> created\\n\" % (\n key, self.data_base[key])\n else:\n response = \"ERROR: key already in the data base\\n\"\n\n return response\n\n def read(self, key):\n\n if key in list(self.data_base.keys()):\n response = (\"key: %d - value: <%s>\\n\" % (key, self.data_base[key]))\n else:\n response = \"ERROR: key doesnt exist in data base\\n\"\n\n return response\n\n def update(self, key, value):\n\n if key in list(self.data_base.keys()):\n self.data_base[key] = value\n response = \"SUCESS: key: %d - value: <%s> updated\\n\" % (\n key, self.data_base[key])\n else:\n response = \"ERROR: Key doesnt exist in data base\\n\"\n\n return response\n\n def delete(self, key):\n\n if key in list(self.data_base.keys()):\n response = \"SUCESS: key: %d - value: <%s> deleted\\n\" % (\n key, self.data_base[key])\n self.data_base.pop(key)\n else:\n response = \"ERROR: Key doesnt exist in data base\\n\"\n\n return response\n# ======================================================\n# Fim da classe Server ================================================================================================================\n\n\ndef onInit():\n server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))\n s = ServerNew()\n s.start()\n standard_pb2_grpc.add_StandardServicer_to_server(s, server)\n print(s.server_address)\n server.add_insecure_port(s.server_address)\n server.start()\n try:\n while True:\n time.sleep(_ONE_DAY_IN_SECONDS)\n except KeyboardInterrupt:\n server.stop(0)\n\n\nif __name__ == '__main__':\n onInit()\n","sub_path":"trabalho 2/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":13359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"479589952","text":"# These inheritance models are distinct from the official OMIM models of inheritance for variants\n# which are specified by GENETIC_MODELS (in variant_tags.py).\n# The following models are used while describing inheritance of genes in gene panels\n# It's a custom-compiled list of values\nGENE_CUSTOM_INHERITANCE_MODELS = (\n (\"AD\", \"Autosomal Dominant\"),\n (\"AR\", \"Autosomal recessive\"),\n (\"XL\", \"X Linked\"),\n (\"XD\", \"X Linked Dominant\"),\n (\"XR\", \"X Linked Recessive\"),\n (\"NA\", \"not available\"),\n (\"AD (imprinting)\", \"Autosomal Dominant (imprinting)\"),\n (\"digenic\", \"Digenic\"),\n (\"AEI\", \"Allelic expression imbalance\"),\n (\"other\", \"Other\"),\n)\n\nVALID_MODELS = (\"AR\", \"AD\", \"MT\", \"XD\", \"XR\", \"X\", \"Y\")\n\nINCOMPLETE_PENETRANCE_MAP = {\"unknown\": None, \"Complete\": None, \"Incomplete\": True}\n\nMODELS_MAP = {\n \"monoallelic_not_imprinted\": [\"AD\"],\n \"monoallelic_maternally_imprinted\": [\"AD\"],\n \"monoallelic_paternally_imprinted\": [\"AD\"],\n \"monoallelic\": [\"AD\"],\n \"biallelic\": [\"AR\"],\n \"monoallelic_and_biallelic\": [\"AD\", \"AR\"],\n \"monoallelic_and_more_severe_biallelic\": [\"AD\", \"AR\"],\n \"xlinked_biallelic\": [\"XR\"],\n \"xlinked_monoallelic\": [\"XD\"],\n \"mitochondrial\": [\"MT\"],\n \"unknown\": [],\n}\n\nPANEL_GENE_INFO_TRANSCRIPTS = [\n \"disease_associated_transcripts\",\n \"disease_associated_transcript\",\n \"transcripts\",\n]\n\nPANEL_GENE_INFO_MODELS = [\n \"genetic_disease_models\",\n \"genetic_disease_model\",\n \"inheritance_models\",\n \"genetic_inheritance_models\",\n]\n","sub_path":"scout/constants/gene_tags.py","file_name":"gene_tags.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"589339254","text":"from unittest import TestCase, mock\n\nimport ornitho\nfrom ornitho.model.family import Family\n\nornitho.consumer_key = \"ORNITHO_CONSUMER_KEY\"\nornitho.consumer_secret = \"ORNITHO_CONSUMER_SECRET\"\nornitho.user_email = \"ORNITHO_USER_EMAIL\"\nornitho.user_pw = \"ORNITHO_USER_PW\"\nornitho.api_base = \"ORNITHO_API_BASE\"\n\n\nclass TestFamily(TestCase):\n def setUp(self):\n self.family_json = {\n \"id\": \"1\",\n \"id_taxo_group\": \"1\",\n \"name\": \"BIRD_FAMILY_GAVIIDAE\",\n \"latin_name\": \"Gaviidae\",\n \"generic\": \"0\",\n }\n self.family = Family.create_from_ornitho_json(self.family_json)\n\n def test_id_taxo_group(self):\n self.assertEqual(\n int(self.family_json[\"id_taxo_group\"]), self.family.id_taxo_group\n )\n\n def test_name(self):\n self.assertEqual(self.family_json[\"name\"], self.family.name)\n\n def test_latin_name(self):\n self.assertEqual(self.family_json[\"latin_name\"], self.family.latin_name)\n\n def test_generic(self):\n self.assertEqual(\n False if self.family_json[\"generic\"] == \"0\" else True, self.family.generic\n )\n\n @mock.patch(\"ornitho.model.family.TaxonomicGroup\")\n def test_taxo_group(self, mock_taxo_group):\n mock_taxo_group.get.return_value = \"Taxonomic Group retrieved\"\n taxo_group = self.family.taxo_group\n mock_taxo_group.get.assert_called_with(self.family.id_taxo_group)\n self.assertEqual(taxo_group, \"Taxonomic Group retrieved\")\n","sub_path":"tests/model/test_family.py","file_name":"test_family.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"111732248","text":"from optparse import OptionParser\nimport numpy as np\n\ndef main():\n parser=OptionParser()\n parser.add_option('--out',dest='out',default='/srv/scratch/oursu/test/test_edge_jaccard')\n parser.add_option('--matrices',dest='ms',default='/srv/scratch/oursu/test/test_chr21.beta0.5.npy,/srv/scratch/oursu/test/test_chr21.beta0.5.npy',help='Comma delimited, .npy files, nodes should be aligned')\n parser.add_option('--thresh',dest='thresh',default='0.1')\n opts,args=parser.parse_args()\n\n thresh=float(opts.thresh)\n matrices=opts.ms.split(',')\n m1=np.load(matrices[0])\n m2=np.load(matrices[1])\n\n m1_bin=1*(m1>=thresh)\n m2_bin=1*(m1>=thresh)\n m1_e=np.count_nonzero(m1_bin)\n m2_e=np.count_nonzero(m2_bin)\n m1m2=np.multiply(m1_bin,m2_bin)\n m1m2_e=np.count_nonzero(m1m2)\n\n edges_union=m1_e+m2_e-m1m2_e\n edges_intersect=m1m2_e\n \n edge_jaccard=float(edges_intersect/edges_union)\n\n out=open(opts.out,'w')\n out.write('Edges_1\\tEdges_2\\tEdges_union\\tEdges_intersect\\tEdges_Jaccard\\n')\n out.write(str(m1_e)+'\\t'+str(m2_e)+'\\t'+str(edges_union)+'\\t'+str(edges_intersect)+'\\t'+str(edge_jaccard)+'\\n')\n out.close()\n\nmain()\n","sub_path":"3Dutils/edge_jaccard.py","file_name":"edge_jaccard.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"349657546","text":"import math\nfrom collections import namedtuple\nfrom enum import Enum\nimport re\n\nclass Direction(Enum):\n UP = 1\n DOWN = 2\n LEFT = 3\n RIGHT = 4\n\n @property\n def isHorizontal(self):\n return self is Direction.LEFT or self is Direction.RIGHT\n\n @property\n def isPositive(self):\n return self is Direction.UP or self is Direction.RIGHT\n\n @staticmethod\n def FromString(direction):\n if direction is 'U':\n return Direction.UP\n elif direction is 'D':\n return Direction.DOWN\n elif direction is 'L':\n return Direction.LEFT\n else:\n return Direction.RIGHT\n\nclass Instruction():\n Regex = re.compile(r\"([a-z]+\\d+)\", re.I)\n SplitRegex = re.compile(r\"([a-z]+)(\\d+)\", re.I)\n\n def __init__(self, encoded):\n parsed = Instruction.SplitRegex.match(encoded).groups()\n self.direction = Direction.FromString(parsed[0])\n self.distance = int(parsed[1])\n\n @staticmethod\n def ListFromRaw(raw):\n return [Instruction(rawI) for rawI in Instruction.Regex.findall(raw)]\n \nclass Point():\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def add(self, otherPoint):\n newX = self.x + otherPoint.x\n newY = self.y + otherPoint.y\n return Point(newX, newY)\n\n def multiply(self, factor):\n newX = self.x * factor\n newY = self.y * factor\n return Point(newX, newY)\n\n def distanceToPoint(self, otherPoint):\n # Manhattan Distance\n deltaX = abs(self.x - otherPoint.x)\n deltaY = abs(self.y - otherPoint.y)\n return (deltaX + deltaY)\n\n def __eq__(self, obj):\n return self.x is obj.x and self.y is obj.y\n\nclass WireSegment():\n def __init__(self, startPoint, endPoint):\n self.startPoint = startPoint\n self.endPoint = endPoint\n\n @property\n def deltaX(self):\n return self.startPoint.x - self.endPoint.x\n pass\n\n @property\n def maxX(self):\n return max(self.startPoint.x, self.endPoint.x)\n\n @property\n def maxY(self):\n return max(self.startPoint.y, self.endPoint.y)\n\n @property\n def minX(self):\n return min(self.startPoint.x, self.endPoint.x)\n\n @property\n def minY(self):\n return min(self.startPoint.y, self.endPoint.y)\n\n @property\n def isHorizontal(self):\n return abs(self.deltaX) > 0\n\n def intersects(self, otherWire):\n if (self.isHorizontal != otherWire.isHorizontal):\n verticalWire = otherWire if self.isHorizontal else self\n horizontalWire = self if self.isHorizontal else otherWire\n\n if (verticalWire.maxY >= horizontalWire.maxY\n and verticalWire.minY <= horizontalWire.maxY\n and horizontalWire.maxX >= verticalWire.maxX\n and horizontalWire.minX <= verticalWire.maxX):\n return (True, Point(verticalWire.maxX, horizontalWire.maxY))\n else:\n return (False, None)\n # check that the wire are in different directions\n # check that they cross ( eg start/end above and below)\n pass\n #return (true, Point(intersection))\n elif (self.startPoint == otherWire.endPoint\n or self.startPoint == otherWire.startPoint):\n return (True, self.startPoint)\n elif (self.endPoint == otherWire.startPoint \n or self.endPoint == otherWire.endPoint):\n return (True, self.endPoint)\n else:\n return (False, None)\n\n @staticmethod\n def FromInstruction(startPoint, instruction):\n distanceFactor = instruction.distance if instruction.direction.isPositive else -instruction.distance\n unitVector = Point(1,0) if instruction.direction.isHorizontal else Point(0,1)\n vector = unitVector.multiply(distanceFactor)\n endPoint = startPoint.add(vector)\n return WireSegment(startPoint, endPoint)\n\n## PART 1\nwith open('source.txt') as f:\n puzzleData=f.read()\n\norigin = Point(0,0)\n\ntestData = \"R8,U5,L5,D3\\nU7,R6,D4,L4\"\n\nwires = puzzleData.splitlines()\nwireSegments = []\nfor wire in wires:\n segments = []\n allInstructions = Instruction.ListFromRaw(wire)\n startPoint = origin\n latestPoint = origin\n for instruction in allInstructions:\n segment = WireSegment.FromInstruction(latestPoint, instruction)\n latestPoint = segment.endPoint\n segments.append(segment)\n wireSegments.append(segments)\n\nwire1Segments = wireSegments[0]\nwire2Segments = wireSegments[1]\n\nintersections = []\nfor segment_1 in wire1Segments:\n for segment_2 in wire2Segments:\n res, pt = segment_1.intersects(segment_2)\n if(res):\n if (pt.distanceToPoint(origin) > 0):\n intersections.append((pt, pt.distanceToPoint(origin)))\n\nprint(min(intersec[1] for intersec in intersections))\n\n## PART 2\n# Find closest in terms of wire length.","sub_path":"3/puzzle.py","file_name":"puzzle.py","file_ext":"py","file_size_in_byte":4937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"324484541","text":"#!/usr/bin/python\n\nimport argparse\nimport json\nfrom os import listdir\nfrom os import path\nfrom parse import parse_file\nimport plotly\nfrom plotly.graph_objs import Scatter, Layout\nimport random\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"res_path_conv\", help=\"path to directory with test results\")\nparser.add_argument(\"res_path_def\", help=\"path to directory with test results\")\nparser.add_argument(\"output_name\", help=\"name of output 'html' file with plot\")\nargs = parser.parse_args()\n\ndef add_key_if_need(data, key, axis=False):\n if key not in data:\n if axis:\n data.update({key: {'x': [], 'y': []}})\n else:\n data.update({key: {}})\n\n return data[key]\n\ndef group_and_parse_files_by_scenario(dir_path):\n files = [f for f in listdir(dir_path)\n if (path.isfile('/'.join([dir_path, f])) and\n f.endswith('.json'))]\n scenarios = {}\n for f in files:\n # scenario name should be in format: -.json\n name = f.split('-')[0]\n count = f.split('-')[1].split('.')[0]\n content = parse_file('/'.join([dir_path, f]))\n s_data = add_key_if_need(scenarios, name)\n for action in content:\n s_action = add_key_if_need(s_data, action)\n s_count = add_key_if_need(s_action, count)\n s_count.update(content[action])\n\n return scenarios\n\n# Data stored format is:\n# full_data -> scenario_name -> action -> scenario-count(engine_num) ->\n# -> res_num -> time of action\n\n# do it per action\n# the format is: eng_num: {x: [res_num], y: [time]}\n# or: res_num: {x: [eng_num], y: [time]}\ndef get_x_y_data(action_data, fixed='eng_num'):\n # fixed can be equals 'eng_num' or 'res_num'\n whole_data = {}\n if fixed == 'eng_num':\n for eng_num in action_data:\n res = add_key_if_need(whole_data, float(eng_num), axis=True)\n for res_num in action_data[eng_num]:\n res['x'].append(res_num)\n res['y'].append(action_data[eng_num][res_num])\n elif fixed == 'res_num':\n for eng_num in action_data:\n for res_num in action_data[eng_num]:\n res = add_key_if_need(whole_data, res_num, axis=True)\n res['x'].append(float(eng_num))\n res['y'].append(action_data[eng_num][res_num])\n\n # sort x/y pairs by x\n for pairs in whole_data.itervalues():\n (x , y) = zip(*sorted(zip(pairs['x'], pairs['y']),\n key=lambda pair: pair[0]))\n pairs['x'] = list(x)\n pairs['y'] = list(y)\n\n\n return whole_data\n\ndef build_trace(pairs, action):\n colors = {\n 'r': random.randrange(0, 255),\n 'g': random.randrange(0, 255),\n 'b': random.randrange(0, 255)\n }\n trace = Scatter(\n x = pairs['x'],\n y = pairs['y'],\n name = action,\n line = dict(\n color = ('rgb(%(r)s, %(g)s, %(b)s)' % colors),\n width = 4\n )\n )\n return trace\n\n\ndef draw_graphs_by_groups(traces, action, scenario, fixed='eng_num'):\n title = ('Comparison default and convergence engines for <%s> with '\n 'scenario (%s)' % (action, scenario))\n\n if fixed == 'eng_num':\n x_title = 'Resources invovment in action'\n elif fixed == 'res_num':\n x_title = 'Heat Engines'\n\n layout = dict(title = title,\n xaxis = dict(title = 'Num of %s' % x_title),\n yaxis = dict(title = 'Average time for operation'),\n )\n fig = dict(data=traces, layout=layout)\n\n filename = '-'.join([action, scenario])\n if not filename.endswith('html'):\n filename = '.'.join([filename, 'html'])\n # offline\n plotly.offline.plot(fig, filename=filename)\n # online\n #plotly.iplot(fig, filename='styled-line')\n\n\ndef main():\n data_conv = group_and_parse_files_by_scenario(args.res_path_conv)\n data_def = group_and_parse_files_by_scenario(args.res_path_def)\n # we need to remove this data, because this sceanrio does\n # only create and delete, so data for update is empty\n data_conv['nested_test_resource.yaml'].pop('heat.update_stack')\n data_def['nested_test_resource.yaml'].pop('heat.update_stack')\n\n if data_conv.keys() != data_def.keys():\n raise ValueError('Scenarios should be eqal for both directories')\n\n for scenario in data_conv:\n for action in data_conv[scenario]:\n # we have different executions with different numbers of resources\n # only for this scenario\n if scenario == 'increasing_resources.yaml':\n xy_conv = get_x_y_data(data_conv[scenario][action])\n xy_def = get_x_y_data(data_def[scenario][action])\n else:\n xy_conv = get_x_y_data(data_conv[scenario][action],\n fixed='res_num')\n xy_def = get_x_y_data(data_def[scenario][action],\n fixed='res_num')\n traces_conv = []\n for eng_num, pairs in xy_conv.iteritems():\n trace_name = '='.join(['conv_eng_works', str(eng_num)])\n traces_conv.append(build_trace(pairs, trace_name))\n traces_def = []\n for eng_num, pairs in xy_def.iteritems():\n trace_name = '='.join(['def_eng_works', str(eng_num)])\n traces_def.append(build_trace(pairs, trace_name))\n draw_graphs_by_groups(traces_conv+traces_def, action, scenario)\n\n# traces = build_traces(data)\n\nmain()\n","sub_path":"draw_plots.py","file_name":"draw_plots.py","file_ext":"py","file_size_in_byte":5558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"293386644","text":"revenue = int(input(\"Ваша выручка?\"))\r\ncost = int(input(\"Ваши издержки?\"))\r\nrev_cost = revenue - cost\r\nif rev_cost > 0:\r\n print('Ваша прибыль ', (rev_cost))\r\n print('Рентабельность выручки', round(rev_cost/revenue, 2))\r\n personal = int(input(\"Сколько людей на вас работает?\"))\r\n print('Прибыль на одного сотрудника ', round(rev_cost/personal, 2))\r\nelse:\r\n print('Вашы убытки ', (abs(rev_cost)))","sub_path":"lesson1.5.py","file_name":"lesson1.5.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"516146110","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.13-x86_64/egg/adlib/learners/retraining.py\n# Compiled at: 2018-07-20 16:00:09\n# Size of source mod 2**32: 4486 bytes\nfrom adlib.learners.learner import Learner\nfrom typing import Dict, List\nfrom data_reader.dataset import EmailDataset\nfrom data_reader.binary_input import Instance\nfrom adlib.learners.models.sklearner import Model\nimport numpy as np\nfrom data_reader.operations import fv_equals\n\nclass Retraining(Learner):\n\n def __init__(self, base_model=None, training_instances=None, attack_alg=None):\n Learner.__init__(self)\n self.model = Model(base_model)\n self.attack_alg = attack_alg\n self.adv_params = None\n self.attacker = None\n self.set_training_instances(training_instances)\n self.iterations = 5\n\n def set_params(self, params: Dict):\n if 'attack_alg' in params.keys():\n self.attack_alg = params['attack_alg']\n else:\n if 'attacker' in params.keys():\n self.attacker = params['attacker']\n if params['adv_params'] is not None:\n self.adv_params = params['adv_params']\n if 'iterations' in params.keys() and 'iterations' is not None:\n self.iterations = params['iterations']\n\n def get_available_params(self) -> Dict:\n params = {'attacker':self.attacker, 'adv_params':self.adv_params, \n 'iterations':self.iterations}\n return params\n\n def train(self):\n \"\"\"\n This is implemented according to Algorithm 1 in Central Rettraining Framework\n for Scalable Adversarial Classification. This will iterate between computing\n a classifier and adding the adversarial instances to the training data that evade\n the previously computed classifier.\n :return: None\n \"\"\"\n self.model.train(self.training_instances)\n iteration = self.iterations\n self.attacker = self.attack_alg()\n self.attacker.set_params(self.adv_params)\n self.attacker.set_adversarial_params(self.model, self.training_instances)\n malicious_instances = [x for x in self.training_instances if self.model.predict(x) == 1]\n augmented_instances = self.training_instances\n while iteration != 0:\n print('iteration: {}'.format(iteration))\n new = []\n transformed_instances = self.attacker.attack(malicious_instances)\n for instance in transformed_instances:\n in_list = False\n for idx, old_instance in enumerate(augmented_instances):\n if fv_equals(old_instance.get_feature_vector(), instance.get_feature_vector()):\n in_list = True\n\n if not in_list:\n new.append(instance)\n augmented_instances.append(Instance(label=1, feature_vector=(instance.get_feature_vector())))\n\n self.model.train(augmented_instances)\n malicious_instances = [x for x in augmented_instances if self.model.predict(x) == 1]\n iteration -= 1\n if new is None:\n break\n\n def decision_function(self, instances):\n return self.model.decision_function_(instances)\n\n def predict(self, instances):\n \"\"\"\n\n :param instances: matrix of instances shape (num_instances, num_feautres_per_instance)\n :return: list of labels (int)\n \"\"\"\n return self.model.predict(instances)\n\n def predict_proba(self, instances):\n return self.model.predict_proba(instances)\n\n def get_weight(self):\n print('weight shape in retraining: {}'.format(self.model.learner.coef_[0].T.shape))\n return self.model.learner.coef_[0].T\n\n def get_constant(self):\n return self.model.learner.intercept_","sub_path":"pycfiles/adlib-1.2.1-py3.7/retraining.cpython-37.py","file_name":"retraining.cpython-37.py","file_ext":"py","file_size_in_byte":3935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"393552313","text":"import os\nimport csv\nimport numpy as np\nimport seaborn as sns\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nnum_class=10\n\nnum=1\ncorrect=0\ntotal=0\n\naccum = np.zeros((10,10), dtype=float)\n\nwhile True:\n file='snaps_cnn8/snapshot_'+str(num)+'.csv'\n if os.path.exists(file) :\n data=np.loadtxt(file, dtype=int)\n\n accum += data\n\n for n in range(data.shape[0]):\n for k in range(data.shape[1]):\n total += data[n,k]\n if n==k:\n correct += data[n,k]\n else:\n break\n num += 1\n \nctotal=np.sum(accum, axis=1, keepdims=True)\nresult = np.divide(accum, ctotal)\nplt.figure\nsns.heatmap(result, cmap='Blues')\nplt.savefig('plot.png')\n","sub_path":"utils/heatmap.py","file_name":"heatmap.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"99533181","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/python\n\nimport pygame\nimport math\nimport numpy\nimport time\n\nimport Properties\n\n\ndef rot(point, ang, center):\n# ang es un porcentaje, va entre 0 y 1 (se podría pasar)\n a = numpy.matrix(point)\n c = numpy.matrix(center)\n #~ R = numpy.matrix([[math.cos(2 * math.pi * ang), -math.sin(2 * math.pi * ang)], \n # [2 * math.pi * math.sin(ang), math.cos(2 * math.pi * ang)]])\n R = numpy.matrix([[math.cos(2 * math.pi * ang), math.sin(2 * math.pi * ang)], \n [math.sin(-2 * math.pi * ang), math.cos(2 * math.pi * ang)]])\n res = tuple((((a-c)*R)+c).tolist()[0])\n return res\n\nclass ClockHand(pygame.sprite.DirtySprite):\n running = False\n def __init__(self):\n pygame.sprite.DirtySprite.__init__(self)\n self.screen = pygame.display.get_surface() \n #~ self.image_orig = pygame.image.load(\"./images/hand.png\").convert_alpha()\n self.image = pygame.Surface((400,400), pygame.SRCALPHA) # per-pixel alpha\n self.rect = self.image.get_rect()\n self.rect.center = self.screen.get_rect().center\n (self.x_c,self.y_c) = (self.rect.width/2, self.rect.height/2)\n\n self.base_points = { \"a0\": (self.x_c-6, self.y_c-180),\n \"a1\": (self.x_c+6, self.y_c-180),\n \"a2\": (self.x_c+6, self.y_c+10),\n \"a3\": (self.x_c-6, self.y_c+10)\n } \n\n self.next_points = []\n\n# self.start()\n# self.rotate_image()\n \n def start(self):\n #~ import pdb; pdb.set_trace()\n self.rotate = 0.0;\n self.init_time = time.time()\n self.already_init = False\n \n self.tic()\n self.draw()\n self.running = True\n \n def stop(self):\n self.running = False\n \n def tic(self):\n if self.running:\n self.rotate_image()\n \n return (self.rotate < 1) \n \n def rotate_f(self):\n pts = self.base_points.values()\n self.next_points = []\n for i in range(0, len(pts)):\n self.next_points.append(rot(pts[i], self.rotate, (self.x_c,self.y_c)))\n \n #~ print self.next_points\n \n def draw(self):\n self.image.fill((255,255,255,0))\n self.rotate_f()\n pygame.draw.polygon(self.image, (0,50,250), self.next_points)\n pygame.draw.aalines(self.image, (0,50,250), True, self.next_points, 1)\n\n def rotate_image(self):\n if not self.already_init:\n self.init_time = time.time()\n self.already_init = True\n \n delta = time.time() - self.init_time\n \n delta = min(1.0,delta/2.0)\n self.rotate = delta\n self.draw()\n\n \n #~ pass\n #~ self.image = pygame.transform.rotozoom(self.image_orig, self.rotate, 1.0)\n #~ self.rect = self.image.get_rect() \n #~ self.rect.center = (Properties.SCREEN_RES[0]/2, Properties.SCREEN_RES[1]/2)\n #~ \n #~ self.rotate += -5\n \n\nclass Clock(pygame.sprite.DirtySprite): \n def __init__(self):\n pygame.sprite.DirtySprite.__init__(self)\n self.image = pygame.image.load(\"./images/circle.png\").convert_alpha()\n self.rect = self.image.get_rect()\n \n #~ self.rect.center = (400,300)\n self.rect.center = (Properties.SCREEN_RES[0]/2, Properties.SCREEN_RES[1]/2)\n\n\n \n","sub_path":"avioncito/src/inc/Clock.py","file_name":"Clock.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"106164703","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseNotFound, HttpResponseBadRequest\n\nfrom oauth2app.oauth2app.authorize import Authorizer, MissingRedirectURI, AuthorizationException\nfrom oauth2app.oauth2app.models import Client\nfrom oauth2app.oauth2app.consts import TOKEN, CODE\n\nfrom . import models\nfrom . import forms\n\n\ndef front(request):\n \"\"\"List all clients in the front page.\"\"\"\n apps = models.App.objects.all().select_related()\n installed_apps = []\n if request.user.is_authenticated():\n installed_apps = [a.client.app for a in request.user.accesstoken_set.all().prefetch_related()]\n\n return render(request, \"front.html\", {'apps': apps, 'installed_apps': installed_apps})\n\n\n@login_required\ndef app(request, app_id):\n \"\"\"Display details of an app.\"\"\"\n app = get_object_or_404(models.App, pk=app_id)\n installed = False\n if app.client.accesstoken_set.filter(user__username='super').exists():\n installed = True\n\n return render(request, \"app.html\", {'app': app, 'installed': installed})\n\n\n@login_required\ndef register_app(request):\n if request.method == 'GET':\n return render(request, \"register_app.html\",\n {'form': forms.AppRegistrationForm()})\n if request.method == 'POST':\n form = forms.AppRegistrationForm(data=request.POST)\n if form.is_valid():\n app = form.save(commit=False)\n app.owner = request.user\n app.client = Client.objects.create(\n name=app.name, user=app.owner,\n description=app.description,\n redirect_uri=form.cleaned_data['redirect_uri'])\n app.save()\n request.session['register_app_success'] = app.id\n return redirect(reverse(\"register_app_success\"))\n else:\n return render(request, \"register_app.html\",\n {'form': form})\n\n\n@login_required\ndef register_app_success(request):\n app_id = request.session.get('register_app_success', None)\n if app_id:\n del request.session['register_app_success']\n app = models.App.objects.get(pk=app_id)\n\n return render(request, \"register_app_success.html\",\n {'app': app})\n else:\n return HttpResponseNotFound()\n\n\n@login_required\ndef install_app(request):\n apps = set(models.App.objects.all().select_related())\n installed_apps = set([a.client.app for a in request.user.accesstoken_set.all().prefetch_related()])\n apps = apps - installed_apps\n return render(request, 'install_app.html', {'apps': apps})\n\n\n@login_required\ndef authorize(request):\n\n authorizer = Authorizer(response_type=TOKEN) # allow direct creation of token\n try:\n authorizer.validate(request)\n except MissingRedirectURI:\n return redirect(\"/oauth2/missing_redirect_uri\")\n except AuthorizationException:\n # The request is malformed or invalid. Automatically\n # redirects to the provided redirect URL.\n\n # The OAuth2App likes to redirect to redirect_uri but in our case\n # AuthorizationException should never happen since we create the link\n # that leads a user to this view. So we should log this and make note\n # that an malformed request has been made.\n # return authorizer.error_redirect()\n return HttpResponseBadRequest()\n\n if request.method == 'GET':\n data = {\n \"client\": authorizer.client,\n \"app\": authorizer.client.app,\n \"access_ranges\": authorizer.access_ranges,\n \"action\": '/oauth2/authorize?%s' % authorizer.query_string,\n \"method\": 'POST'\n }\n return render(request, 'authorize.html', data)\n\n elif request.method == 'POST':\n if request.POST.get(\"connect\") == \"Yes\":\n return authorizer.grant_redirect()\n else:\n # The OAuth2App likes to redirect to redirect_uri but\n # we will simply intercept the request and send user back to\n # home page\n # return authorizer.error_redirect()\n return redirect(reverse(\"front\"))\n\n return redirect(reverse(\"front\"))\n\n\n@login_required\ndef authorize_code(request):\n\n authorizer = Authorizer(response_type=CODE)\n try:\n authorizer.validate(request)\n except MissingRedirectURI:\n return redirect(\"/oauth2/missing_redirect_uri\")\n except AuthorizationException:\n # The request is malformed or invalid. Automatically\n # redirects to the provided redirect URL.\n\n # The OAuth2App likes to redirect to redirect_uri but in our case\n # AuthorizationException should never happen since we create the link\n # that leads a user to this view. So we should log this and make note\n # that an malformed request has been made.\n # return authorizer.error_redirect()\n return HttpResponseBadRequest()\n\n if request.method == 'GET':\n data = {\n \"client\": authorizer.client,\n \"app\": authorizer.client.app,\n \"access_ranges\": authorizer.access_ranges,\n \"action\": '/oauth2/authorize-code?%s' % authorizer.query_string,\n \"method\": 'POST'\n }\n return render(request, 'authorize.html', data)\n\n elif request.method == 'POST':\n if request.POST.get(\"connect\") == \"Yes\":\n return authorizer.grant_redirect()\n else:\n # The OAuth2App likes to redirect to redirect_uri but\n # we will simply intercept the request and send user back to\n # home page\n # return authorizer.error_redirect()\n return redirect(reverse(\"front\"))\n\n return redirect(reverse(\"front\"))\n\n\n@login_required\ndef revoke_app(request, app_id):\n app = get_object_or_404(models.App, pk=app_id)\n if not app.client.accesstoken_set.filter(user=request.user).exists():\n return redirect(reverse('front'))\n\n if request.method == 'GET':\n return render(request, 'revoke_app.html', {'app': app})\n elif request.method == 'POST':\n if request.POST.get('consent') == 'Yes':\n access_token = app.client.accesstoken_set.get(user=request.user)\n access_token.delete()\n return redirect(reverse('front'))\n\n\ndef missing_redirect_uri(request):\n pass\n","sub_path":"oauth2_server/oauth2_server/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"364343079","text":"import unittest\nimport time\n\nfrom scanpointgenerator import LineGenerator, CompoundGenerator\n\nfrom malcolm.core import Process, Part, call_with_params, \\\n Context, ResponseError, AlarmStatus, AlarmSeverity, method_takes, \\\n method_also_takes, REQUIRED\nfrom malcolm.modules.scanning.parts import RunnableChildPart\nfrom malcolm.modules.demo.blocks import ticker_block\nfrom malcolm.compat import OrderedDict\nfrom malcolm.modules.scanning.controllers import \\\n RunnableController, RunnableStates\nfrom malcolm.modules.builtin.vmetas import StringMeta\n\n\nclass TestRunnableStates(unittest.TestCase):\n\n def setUp(self):\n self.o = RunnableStates()\n\n def test_init(self):\n expected = OrderedDict()\n expected['Resetting'] = {\"Ready\", \"Fault\", \"Disabling\"}\n expected['Ready'] = {\"Configuring\", \"Aborting\", 'Saving', \"Fault\",\n \"Disabling\", \"Loading\"}\n expected['Saving'] = {'Fault', 'Ready', 'Disabling'}\n expected['Loading'] = {'Disabling', 'Fault', 'Ready'}\n expected['Configuring'] = {\"Armed\", \"Aborting\", \"Fault\", \"Disabling\"}\n expected['Armed'] = {\"Seeking\", \"Aborting\", \"Running\",\n \"Fault\", \"Disabling\", \"Resetting\"}\n expected['Running'] = {\"PostRun\", \"Seeking\", \"Aborting\", \"Fault\",\n \"Disabling\"}\n expected['PostRun'] = {\"Ready\", \"Armed\", \"Aborting\", \"Fault\",\n \"Disabling\"}\n expected['Seeking'] = {\"Armed\", \"Paused\", \"Aborting\", \"Fault\",\n \"Disabling\"}\n expected['Paused'] = {\"Seeking\", \"Running\", \"Aborting\", \"Fault\",\n \"Disabling\"}\n expected['Aborting'] = {\"Aborted\", \"Fault\", \"Disabling\"}\n expected['Aborted'] = {\"Resetting\", \"Fault\", \"Disabling\"}\n expected['Fault'] = {\"Resetting\", \"Disabling\"}\n expected['Disabling'] = {\"Disabled\", \"Fault\"}\n expected['Disabled'] = {\"Resetting\"}\n assert self.o._allowed == expected\n possible_states = [\n 'Ready', 'Resetting', 'Saving', 'Loading', 'Configuring', 'Armed',\n 'Running', 'Seeking', 'PostRun', 'Paused', 'Aborting', 'Aborted',\n 'Fault', 'Disabling', 'Disabled']\n assert self.o.possible_states == possible_states\n\n\nclass TestRunnableController(unittest.TestCase):\n def setUp(self):\n self.p = Process('process1')\n self.context = Context(self.p)\n\n # Make a ticker_block block to act as our child\n self.c_child = call_with_params(\n ticker_block, self.p, mri=\"childBlock\", configDir=\"/tmp\")\n self.b_child = self.context.block_view(\"childBlock\")\n\n # Make an empty part for our parent\n part1 = Part(\"part1\")\n\n # Make a RunnableChildPart to control the ticker_block\n part2 = call_with_params(\n RunnableChildPart, mri='childBlock', name='part2')\n\n # create a root block for the RunnableController block to reside in\n self.c = call_with_params(RunnableController, self.p, [part1, part2],\n mri='mainBlock', configDir=\"/tmp\",\n axesToMove=[\"x\"])\n self.p.add_controller('mainBlock', self.c)\n self.b = self.context.block_view(\"mainBlock\")\n self.ss = self.c.stateSet\n\n # start the process off\n self.checkState(self.ss.DISABLED)\n self.p.start()\n self.checkState(self.ss.READY)\n\n def tearDown(self):\n self.p.stop(timeout=1)\n\n def checkState(self, state, child=True, parent=True):\n if child:\n assert self.c_child.state.value == state\n if parent:\n assert self.c.state.value == state\n\n def checkSteps(self, configured, completed, total):\n assert self.b.configuredSteps.value == configured\n assert self.b.completedSteps.value == completed\n assert self.b.totalSteps.value == total\n assert self.b_child.configuredSteps.value == configured\n assert self.b_child.completedSteps.value == completed\n assert self.b_child.totalSteps.value == total\n\n def test_init(self):\n assert self.c.completed_steps.value == 0\n assert self.c.configured_steps.value == 0\n assert self.c.total_steps.value == 0\n assert self.c.axes_to_move.value == (\"x\",)\n assert list(self.b.configure.takes.elements) == \\\n [\"generator\", \"axesToMove\", \"exceptionStep\"]\n\n def test_reset(self):\n self.c.disable()\n self.checkState(self.ss.DISABLED)\n self.c.reset()\n self.checkState(self.ss.READY)\n\n def test_set_axes_to_move(self):\n self.c.set_axes_to_move(['y'])\n assert self.c.axes_to_move.value == ('y',)\n\n def test_modify_child(self):\n # Save an initial setting for the child\n self.b_child.save(\"init_child\")\n assert self.b_child.modified.value is False\n x = self.context.block_view(\"COUNTERX\")\n x.counter.put_value(31)\n # x counter now at 31, child should be modified\n assert x.counter.value == 31\n assert self.b_child.modified.value is True\n assert self.b_child.modified.alarm.severity == AlarmSeverity.MINOR_ALARM\n assert self.b_child.modified.alarm.status == AlarmStatus.CONF_STATUS\n assert self.b_child.modified.alarm.message == \\\n \"x.counter.value = 31.0 not 0.0\"\n self.prepare_half_run()\n self.b.run()\n # x counter now at 2, child should be modified by us\n assert self.b_child.modified.value is True\n assert self.b_child.modified.alarm.severity == AlarmSeverity.NO_ALARM\n assert self.b_child.modified.alarm.status == AlarmStatus.CONF_STATUS\n assert self.b_child.modified.alarm.message == \\\n \"(We modified) x.counter.value = 2.0 not 0.0\"\n assert x.counter.value == 2.0\n x.counter.put_value(0.0)\n # x counter now at 0, child should be unmodified\n assert x.counter.value == 0\n assert self.b_child.modified.alarm.message == \"\"\n assert self.b_child.modified.value is False\n\n def test_modify_parent(self):\n # Save an initial setting for child and parent\n self.b_child.save(\"init_child\")\n self.b.save(\"init_parent\")\n # Change a value and save as a new child setting\n x = self.context.block_view(\"COUNTERX\")\n x.counter.put_value(31)\n self.b_child.save(\"new_child\")\n assert self.b_child.modified.value is False\n assert self.b.modified.value is True\n assert self.b.modified.alarm.severity == AlarmSeverity.MINOR_ALARM\n assert self.b.modified.alarm.status == AlarmStatus.CONF_STATUS\n assert self.b.modified.alarm.message == \\\n \"part2.design.value = 'new_child' not 'init_child'\"\n # Do a configure, and check we get set back\n self.prepare_half_run()\n assert self.b_child.design.value == \"init_child\"\n assert self.b_child.modified.value is False\n assert self.b.modified.value is False\n\n def test_validate(self):\n line1 = LineGenerator('y', 'mm', 0, 2, 3)\n line2 = LineGenerator('x', 'mm', 0, 2, 2)\n compound = CompoundGenerator([line1, line2], [], [])\n actual = self.b.validate(generator=compound, axesToMove=['x'])\n assert actual[\"generator\"].to_dict() == compound.to_dict()\n assert actual[\"axesToMove\"] == ('x',)\n\n def prepare_half_run(self, duration=0.01, exception=0):\n line1 = LineGenerator('y', 'mm', 0, 2, 3)\n line2 = LineGenerator('x', 'mm', 0, 2, 2)\n compound = CompoundGenerator([line1, line2], [], [], duration)\n self.b.configure(\n generator=compound, axesToMove=['x'], exceptionStep=exception)\n\n def test_configure_run(self):\n self.prepare_half_run()\n self.checkSteps(2, 0, 6)\n self.checkState(self.ss.ARMED)\n\n self.b.run()\n self.checkState(self.ss.ARMED)\n self.checkSteps(4, 2, 6)\n\n self.b.run()\n self.checkState(self.ss.ARMED)\n self.checkSteps(6, 4, 6)\n\n self.b.run()\n self.checkState(self.ss.READY)\n\n def test_abort(self):\n self.prepare_half_run()\n self.b.run()\n self.b.abort()\n self.checkState(self.ss.ABORTED)\n\n def test_pause_seek_resume(self):\n self.prepare_half_run()\n self.checkSteps(configured=2, completed=0, total=6)\n self.b.run()\n self.checkState(self.ss.ARMED)\n self.checkSteps(4, 2, 6)\n self.b.pause(completedSteps=1)\n self.checkState(self.ss.ARMED)\n self.checkSteps(2, 1, 6)\n self.b.run()\n self.checkSteps(4, 2, 6)\n self.b.completedSteps.put_value(5)\n self.checkSteps(6, 5, 6)\n self.b.run()\n self.checkState(self.ss.READY)\n\n def test_resume_in_run(self):\n self.prepare_half_run(duration=0.5)\n f = self.b.run_async()\n self.context.sleep(0.95)\n self.b.pause()\n self.checkState(self.ss.PAUSED)\n self.checkSteps(2, 1, 6)\n self.b.resume()\n # Parent should be running, child won't have got request yet\n then = time.time()\n self.checkState(self.ss.RUNNING, child=False)\n self.context.wait_all_futures(f, timeout=2)\n now = time.time()\n self.checkState(self.ss.ARMED)\n self.checkSteps(4, 2, 6)\n # This test fails on Travis sometimes, looks like the docker container\n # just gets starved\n #self.assertAlmostEqual(now - then, 0.5, delta=0.1)\n\n def test_run_exception(self):\n self.prepare_half_run(exception=1)\n with self.assertRaises(ResponseError):\n self.b.run()\n self.checkState(self.ss.FAULT)\n\n def test_run_stop(self):\n self.prepare_half_run(duration=0.1)\n f = self.b.run_async()\n self.context.sleep(0.1)\n self.b.abort()\n with self.assertRaises(ResponseError):\n f.result()\n self.checkState(self.ss.ABORTED)\n\n\nclass PartTester1(Part):\n\n @RunnableController.Configure\n @method_takes(\n \"size\", StringMeta(\"Size of the thing\"), REQUIRED)\n def configure(self, params):\n pass\n\n\nclass PartTester2(Part):\n\n def configure(self):\n pass\n\n\nclass PartTester3(Part):\n\n @RunnableController.Configure\n def configure(self):\n pass\n\n\nclass PartTester4(Part):\n\n @RunnableController.Configure\n @method_takes()\n def configure(self):\n pass\n\n\nclass RunnableControllerTester(RunnableController):\n\n def __init__(self, process, parts, params):\n super(RunnableControllerTester, self).__init__(process, parts, params)\n\n self.add_part(PartTester1(\"1\"))\n self.add_part(PartTester2(\"2\"))\n\n\nclass TestRunnableControllerCollectsAllParams(unittest.TestCase):\n\n def setUp(self):\n self.p = Process('process1')\n self.context = Context(self.p)\n\n def tearDown(self):\n self.p.stop(timeout=1)\n\n def test_no_hook_passes(self):\n # create a root block for the RunnableController block to reside in\n self.c = call_with_params(RunnableController, self.p,\n [PartTester1(\"1\"), PartTester2(\"2\")],\n mri='mainBlock', configDir=\"/tmp\",\n axesToMove=[\"x\"])\n self.p.add_controller('mainBlock', self.c)\n self.b = self.context.block_view(\"mainBlock\")\n\n # start the process off\n self.p.start()\n\n takes = list(self.b.configure.takes.elements)\n self.assertEqual(takes, [\"size\", \"generator\", \"axesToMove\"])\n\n def test_hook_fails(self):\n # create a root block for the RunnableController block to reside in\n self.c = call_with_params(RunnableController, self.p,\n [PartTester1(\"1\"), PartTester3(\"2\")],\n mri='mainBlock', configDir=\"/tmp\",\n axesToMove=[\"x\"])\n self.p.add_controller('mainBlock', self.c)\n self.b = self.context.block_view(\"mainBlock\")\n\n # start the process off\n self.p.start()\n\n takes = list(self.b.configure.takes.elements)\n self.assertEqual(takes, [\"size\", \"generator\", \"axesToMove\"])\n\n def test_hook_plus_method_takes_nothing_passes(self):\n # create a root block for the RunnableController block to reside in\n self.c = call_with_params(RunnableController, self.p,\n [PartTester1(\"1\"), PartTester4(\"2\")],\n mri='mainBlock', configDir=\"/tmp\",\n axesToMove=[\"x\"])\n self.p.add_controller('mainBlock', self.c)\n self.b = self.context.block_view(\"mainBlock\")\n\n # start the process off\n self.p.start()\n\n takes = list(self.b.configure.takes.elements)\n self.assertEqual(takes, [\"size\", \"generator\", \"axesToMove\"])\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n","sub_path":"tests/test_modules/test_scanning/test_runnablecontroller.py","file_name":"test_runnablecontroller.py","file_ext":"py","file_size_in_byte":13002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"517491412","text":"#!/usr/bin/python3.8\n\n\"\"\"\nCreated on Tue May 25 13:00:39 2021\n\n@author: Javier de la Peña\n\nCode to \n\nCommunications are based on ROS (Robot Operating Sytem)\n\nInputs: LiDAR pointcloud [x, y ,z, intensity, sweep]\nOutputs: Most relevant obstacles of the environment in the form of 3D bounding boxes with their associated velocity\n\"\"\"\n\n# General use imports\nimport os\nimport time\nimport sys\nimport copy\nimport json\nimport argparse\nimport glob\nfrom pathlib import Path\n\n# ROS imports\nimport rospy\nfrom sensor_msgs.msg import PointCloud2, PointField, Image, CameraInfo\nfrom nav_msgs.msg import Odometry\nfrom std_msgs.msg import Float64, Float32, Header, Bool\nfrom message_filters import TimeSynchronizer, Subscriber, ApproximateTimeSynchronizer\nfrom visualization_msgs.msg import Marker, MarkerArray\nfrom t4ac_msgs.msg import Bounding_Box_3D, Bounding_Box_3D_list\n\n# Math and geometry imports\nimport torch\nimport math\nimport numpy as np\nfrom pyquaternion import Quaternion\n\n# Auxiliar functions/classes imports\nfrom modules.auxiliar_functions_multihead import get_bounding_box_3d, marker_bb, marker_arrow, filter_predictions, relative2absolute_velocity\nfrom modules.auxiliar_functions import euler_from_quaternion\nfrom modules.processor_ros_nuscenes import Processor_ROS_nuScenes\n\n# Config PointCloud processor\n\nCONFIG_PATH = rospy.get_param(\"/t4ac/perception/detection/lidar/t4ac_openpcdet_ros/t4ac_openpcdet_ros_node/config_path\")\nMODEL_PATH = rospy.get_param(\"t4ac/perception/detection/lidar/t4ac_openpcdet_ros/t4ac_openpcdet_ros_node/model_path\")\n\nclass OpenPCDet_ROS():\n \"\"\"\n \"\"\"\n def __init__(self):\n\n # PointCloud processor\n\n self.processor = Processor_ROS_nuScenes(CONFIG_PATH, MODEL_PATH)\n self.processor.initilize_network()\n\n # ROS Subscribers\n\n input_odometry_topic = rospy.get_param(\"/t4ac/perception/detection/lidar/t4ac_openpcdet_ros/t4ac_openpcdet_ros_node/sub_input_odometry\")\n self.sub_input_odometry = rospy.Subscriber(input_odometry_topic, Odometry, self.ros_odometry_callback, queue_size=1)\n\n input_pointcloud_topic = rospy.get_param(\"/t4ac/perception/detection/lidar/t4ac_openpcdet_ros/t4ac_openpcdet_ros_node/sub_input_pointcloud\")\n self.sub_input_pointcloud = rospy.Subscriber(input_pointcloud_topic, PointCloud2, self.ros_lidar_callback, queue_size=1, buff_size=2**24)\n\n # ROS Publishers\n\n # pub_pcl2 = rospy.Publisher(\"/carla/ego_vehicle/pcl2_used\", PointCloud2, queue_size=20)\n \n lidar_3D_obstacles_topic = rospy.get_param(\"/t4ac/perception/detection/lidar/t4ac_openpcdet_ros/t4ac_openpcdet_ros_node/pub_3D_lidar_obstacles\")\n self.pub_lidar_3D_obstacles = rospy.Publisher(lidar_3D_obstacles_topic, Bounding_Box_3D_list, queue_size=10)\n\n lidar_3D_obstacles_markers_topic = rospy.get_param(\"/t4ac/perception/detection/lidar/t4ac_openpcdet_ros/t4ac_openpcdet_ros_node/pub_3D_lidar_obstacles_markers\")\n self.pub_lidar_3D_obstacles_markers = rospy.Publisher(lidar_3D_obstacles_markers_topic, MarkerArray, queue_size=10)\n\n lidar_3D_obstacles_velocities_markers_topic = rospy.get_param(\"/t4ac/perception/detection/lidar/t4ac_openpcdet_ros/t4ac_openpcdet_ros_node/pub_3D_lidar_obstacles_velocities_markers\")\n self.pub_lidar_3D_obstacles_velocities_markers = rospy.Publisher(lidar_3D_obstacles_velocities_markers_topic, MarkerArray, queue_size=10)\n\n self.laser_frame = rospy.get_param('/t4ac/frames/laser')\n self.header = None\n\n # Aux Functions\n\n def publish_obstacles(self, boxes, scores, labels):\n \"\"\"\n \"\"\"\n\n bounding_box_3d_list = Bounding_Box_3D_list()\n bounding_box_3d_list.header.stamp = self.header.stamp\n bounding_box_3d_list.header.frame_id = self.header.frame_id\n\n obstacles_marker_array = MarkerArray()\n velocities_marker_array = MarkerArray()\n i = j = 0\n\n for box, score, label in zip(boxes, scores, labels):\n \n box_marker = marker_bb(self.header,box,label,i,corners=False)\n obstacles_marker_array.markers.append(box_marker)\n i += 1\n\n arrow_marker = marker_arrow(self.header,box,label,j)\n velocities_marker_array.markers.append(arrow_marker)\n j += 1\n\n bounding_box_3d = get_bounding_box_3d(box,score,label)\n bounding_box_3d_list.bounding_box_3d_list.append(bounding_box_3d)\n\n self.pub_lidar_3D_obstacles.publish(bounding_box_3d_list)\n self.pub_lidar_3D_obstacles_markers.publish(obstacles_marker_array)\n self.pub_lidar_3D_obstacles_velocities_markers.publish(velocities_marker_array)\n\n # ROS callbacks\n\n def ros_odometry_callback(self,odom_msg):\n \"\"\"\n \"\"\"\n\n quaternion = []\n quaternion.append(odom_msg.pose.pose.orientation.x)\n quaternion.append(odom_msg.pose.pose.orientation.y)\n quaternion.append(odom_msg.pose.pose.orientation.z)\n quaternion.append(odom_msg.pose.pose.orientation.w)\n _,_,self.ego_vehicle_yaw = euler_from_quaternion(*quaternion)\n \n if not self.processor.odom_flag:\n self.processor.previous_ego_odometry = odom_msg\n self.processor.odom_flag = True\n else:\n self.processor.current_ego_odometry = odom_msg\n\n delta_t = self.processor.current_ego_odometry.header.stamp.to_sec() - self.processor.previous_ego_odometry.header.stamp.to_sec()\n \n desp_x_global = self.processor.current_ego_odometry.pose.pose.position.x - self.processor.previous_ego_odometry.pose.pose.position.x\n desp_y_global = self.processor.current_ego_odometry.pose.pose.position.y - self.processor.previous_ego_odometry.pose.pose.position.y\n self.ego_vel_x_global = desp_x_global/delta_t\n self.vel_y_global = desp_y_global/delta_t\n\n desp_x_local = desp_x_global*math.cos(self.ego_vehicle_yaw)+desp_y_global*math.sin(self.ego_vehicle_yaw)\n desp_y_local = desp_x_global*(-math.sin(self.ego_vehicle_yaw))+desp_y_global*math.cos(self.ego_vehicle_yaw)\n\n self.ego_vel_x_local = desp_x_local/delta_t\n self.ego_vel_y_local = desp_y_local/delta_t\n\n self.processor.previous_ego_odometry = self.processor.current_ego_odometry\n\n def ros_lidar_callback(self,point_cloud_msg):\n \"\"\"\n \"\"\"\n\n self.header = point_cloud_msg.header\n\n self.processor.new_pcl(point_cloud_msg)\n pred_dicts = self.processor.inference()\n\n pred_boxes, pred_scores, pred_labels = filter_predictions(pred_dicts, True)\n \n if self.processor.current_ego_odometry != None and len(pred_boxes) != 0:\n # pred_boxes = relative2absolute_velocity(pred_boxes, self.ego_vel_x_local, self.ego_vel_y_local)\n pred_boxes = relative2absolute_velocity(pred_boxes, self.processor.current_ego_odometry)\n\n # print(pred_boxes)\n # print(pred_scores)\n # print(pred_labels)\n\n self.publish_obstacles(pred_boxes, pred_scores, pred_labels)\n\ndef main():\n # Node name\n\n node_name = rospy.get_param(\"/t4ac/perception/detection/lidar/t4ac_openpcdet_ros/t4ac_openpcdet_ros_node/node_name\")\n rospy.init_node(node_name, anonymous=True)\n \n OpenPCDet_ROS()\n\n try:\n rospy.spin()\n except KeyboardInterruput:\n rospy.loginfo(\"Shutting down OpenPCDet ROS module\")\n\nif __name__ == '__main__':\n print(\"[+] PCDet ros_node has started.\") \n main()","sub_path":"src/t4ac_openpcdet_pp_mh_ros_node.py","file_name":"t4ac_openpcdet_pp_mh_ros_node.py","file_ext":"py","file_size_in_byte":7471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"507534644","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n\n path(\"\", views.index, name=\"index\"),\n path(\"login\", views.login_view, name=\"login\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"newuser\", views.newuser_view, name=\"newuser\"),\n path(\"testrun/\", views.testrun_view, name=\"testrun\"),\n path(\"testcase/\", views.testCase_view, name=\"testcase\"),\n path(\"export/xls/\", views.report_view, name=\"report\")\n\n ]","sub_path":"manualtest/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"302975073","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\n/*\n// This file is part of VELA-CLARA-Software. //\n//------------------------------------------------------------------------------------//\n// VELA-CLARA-Software 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// VELA-CLARA-Controllers 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 VELA-CLARA-Software. If not, see . //\n//\n// Author: DJS\n// Last edit: 03-07-2018\n// FileName: monitor_hub.py\n// Description: The hardware_control_hub, creates and holds all CATAP hardware controllers,\n// they get passed to where they are needed\n//\n//*/\n'''\nfrom src.data import config\nfrom src.data import rf_conditioning_logger\nfrom PyQt4.QtCore import QTimer\nfrom PyQt4.QtCore import QObject\nfrom src.data import config\nfrom src.data import rf_conditioning_logger\nfrom src.data.rf_conditioning_data import rf_conditioning_data\nfrom src.controllers.hardware_control_hub import hardware_control_hub\nimport numbers\n\n\n\nclass monitor(QObject):\n \"\"\"\n # DJS Sept 2017\n #\n # spike monitor\n #\n #\n # inherits from monitor base class\n # It relies on timers to automatically get new signal values\n # process them, then sets a flag in the passed stat_dict\n # when the state of the signal changes\n # from 'good' to 'bad'\n # these states are always tied to the state of the cooldown through the\n # property 'in_cooldown' and only emitted when the cooldown state changes\n #\n # Assuming connecting the interface to a pv has worked:\n # it has a timer that gets and checks the signal signal\n # a spike is defined as:\n # self._latest_value > self.spike_delta + self._mean_level\n # if the signal has not spiked, it appends the new value to\n # value_history and sets _mean_level\n # if the signal 'spikes' it sets 'bad' and the\n # object enters a cooldown state\n # there are two cooldown states: 'timed' and 'level'\n # 'timed' waits cooldown_time ms and then sets 'good'\n # 'level' emits good when the vacuum returns\n # to spike_decay_level*_mean_level then sets 'good'\n # after cooldown the monitor returns to checking new signal values\n # for a spike and updating the history buffer and mean\n #\n # base-class\n \"\"\"\n def __init__(self,\n update_time=100,\n cooldown_time=5000,\n timed_cooldown=False,\n level_cooldown=True,\n no_cooldown=False):\n QObject.__init__(self)\n self.timed_cooldown = timed_cooldown\n self.level_cooldown = level_cooldown\n self.no_cooldown = no_cooldown\n self.update_time = update_time\n self.cool_down_time = cooldown_time\n # this class has a number of timers:\n self.timer = QTimer() # used for getting data\n self.cooldown_timer = QTimer() # used for a TIMED cooldown\n # owns a config and logging class\n self.config = config.config()\n self.config_data = self.config.raw_config_data\n self.logger = rf_conditioning_logger.rf_conditioning_logger()\n self.llrf_type = self.config_data[self.config.RF_STRUCTURE]\n\n # the data class\n self.data = rf_conditioning_data()\n self.values = rf_conditioning_data.values\n\n # CATAP hardware controllers, these live here and are passed to where they are needed\n self.hardware = hardware_control_hub()\n #\n if timed_cooldown:\n self.set_timed_cooldown()\n if level_cooldown:\n self.set_level_cooldown()\n if no_cooldown:\n self.set_no_cooldown()\n\n # flag for general state of the monitor, eg True if initialised and passed sanity checks\n self.set_success = False\n\n def alarm(self, alarm):\n print('alarm ' + alarm)\n \"\"\"\n maybe pyttsx3 ??? \n https://stackoverflow.com/questions/30612298/text-to-speech-tts-module-that-works-under-python-3\n what general text to speak should we use??? \n \"\"\"\n # subprocess.call('espeak -ven+f5 ' + alarm)\n # base.alarm_process.stdin.write('espeak -ven+f5 ' + alarm )\n # p = subprocess.Popen('espeak '+alarm, shell=True)\n\n def start(self):\n self.check()\n print(__name__ + ' starting monitoring, update time = ' + str(self.update_time))\n self.timer.timeout.connect(self.check)\n self.timer.start(self.update_time)\n\n # a timed cooldown will set not ibnn_cooldown = false a set time after an event\n def set_timed_cooldown(self):\n self.timed_cooldown = True\n self.level_cooldown = False\n self.no_cooldown = False\n\n # a timed cooldown will set not ibnn_cooldown = false a set time after an event\n def set_level_cooldown(self):\n self.timed_cooldown = False\n self.level_cooldown = True\n self.no_cooldown = False\n\n def set_no_cooldown(self):\n self.timed_cooldown = False\n self.level_cooldown = True\n self.no_cooldown = False\n\n # you should probably overload this in child class\n def cooldown_function(self):\n self.logger.message(__name__ + ' monitor function called, cool down ended')\n self.incool_down = False\n\n def set_cooldown_mode(self, mode):\n if mode == 'LEVEL': # MAGIC_STRING\n self.set_level_cooldown()\n elif mode == 'TIMED': # MAGIC_STRING\n self.set_timed_cooldown()\n elif mode == 'LEVEL_NO_SPIKE': # MAGIC_STRING\n self.set_no_cooldown()\n else:\n self.set_level_cooldown()\n\n def sanity_checks(self, items):\n \"\"\"\n general a sanity checking funciton that just checks if items are numbers\n :param items: objects to check\n :return: tru if all ojects are numbers ...\n \"\"\"\n self.set_success = True # dangerous setting this to true temporarily >> ?? (in generla it\n # must be)\n i = 0\n for item in items:\n if not isinstance(item, numbers.Real):\n self.logger.message(__name__ + ' item {} failed sanity check'.format(i))\n i += 1\n self.set_success = False\n return self.set_success\n\n","sub_path":"Apps/RF_Conditioner/v2/src/monitors/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":7127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"520322723","text":"import hashlib\n\n#https://www.stat.berkeley.edu/~stark/Java/Html/sha256Rand.htm\n#https://people.csail.mit.edu/rivest/sampler.py\n\nseed = 123\nmaxValue = 1000\nnumbersToSample = 10\n\nfor currentSampleNumber in range(1,numbersToSample + 1):\n h = hashlib.sha256((str(seed) + \",\" + str(currentSampleNumber)).encode()).hexdigest()\n print(\"currentSampleNumber = \", currentSampleNumber)\n print(\"h = \", h)\n n = int(h, 16) % maxValue + 1\n print(\"n = \", n)\n","sub_path":"PRNGSHA256.py","file_name":"PRNGSHA256.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"375227028","text":"from django.shortcuts import render,redirect\nfrom django.views import View\nfrom .models import Category,Product\n\nfrom django.db.models import Q\n\nfrom django.core.paginator import Paginator \n\nclass ProductView(View):\n\n def get(self, request, *args, **kwargs):\n \n if \"search\" in request.GET:\n\n if request.GET[\"search\"] == \"\" or request.GET[\"search\"].isspace():\n return redirect(\"shopping:index\")\n\n search = request.GET[\"search\"].replace(\" \",\" \")\n search_list = search.split(\" \")\n\n query = Q()\n for word in search_list:\n query &= Q(name__contains=word)\n\n #.order_byメソッドで並び替えしないと、paginatorでWARNINGが出る。\n data = Product.objects.filter(query).order_by(\"id\")\n else:\n data = Product.objects.all().order_by(\"id\")\n\n\n #===========ここからページネーション処理================\n paginator = Paginator(data,1)\n\n if \"page\" in request.GET:\n data = paginator.get_page(request.GET[\"page\"])\n else:\n data = paginator.get_page(1)\n\n context = { \"data\":data }\n\n return render(request,\"shopping/index.html\",context)\n\n def post(self, request, *args, **kwargs):\n \n return redirect(\"shopping:index\")\n \nindex = ProductView.as_view()\n","sub_path":"shopping/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"485292990","text":"# -*- coding:utf-8 -*-\n\n\n# Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.\n#\n# You may return the answer in any order.\n#\n#  \n# Example 1:\n#\n#\n# Input: n = 4, k = 2\n# Output:\n# [\n# [2,4],\n# [3,4],\n# [2,3],\n# [1,2],\n# [1,3],\n# [1,4],\n# ]\n#\n#\n# Example 2:\n#\n#\n# Input: n = 1, k = 1\n# Output: [[1]]\n#\n#\n#  \n# Constraints:\n#\n#\n# \t1 <= n <= 20\n# \t1 <= k <= n\n#\n#\n\n\nclass Solution(object):\n def combine(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: List[List[int]]\n \"\"\"\n comb = [i for i in range (1,k+1)]\n R = [comb]\n while comb[0]!=n-k+1:\n comb=copy.deepcopy(comb)\n for i in range (1,k+1):\n if comb[-i]122: # lowercase letters\r\n cipherASCII.append(x+steps-26)\r\n else:\r\n cipherASCII.append(x+steps)\r\n elif x in range(65,91): # uppercase letters\r\n if x+steps>90:\r\n cipherASCII.append(x+steps-26)\r\n else:\r\n cipherASCII.append(x+steps)\r\n elif x in range(48,58): # numeric values\r\n if x+(steps%10)>57:\r\n cipherASCII.append(47+((steps%10)-(57-x)))\r\n else:\r\n cipherASCII.append(x+(steps%10))\r\n else:\r\n cipherASCII.append(x)\r\n \r\n # coverting the ASCII values of the cipherASCII (rotated) \r\n # into their corresponding characters as the ciphertext\r\n cipher = ''.join(map(chr,cipherASCII))\r\n #print(cipher)\r\n return cipher\r\n\r\n# decryption function that takes the ciphertext and the number of steps originally rotated\r\n# the step count also remain None (if not explicitly passed by user) - which triggers a brute force from step values -26 to +26\r\n# returns the plaintext based on the given step count or all possible results in case of bruteforce\r\ndef decrypt(cipher,steps=None):\r\n \r\n # list with the ASCII values of the ciphertext\r\n cipherASCII = [ord(char) for char in cipher]\r\n plainASCII = []\r\n\r\n # if step count is given by user\r\n if steps:\r\n # reverse rotating the ASCII values by 'steps' no. of steps\r\n \r\n for x in cipherASCII:\r\n if x in range(97,123):\r\n if x-steps<97: # lowercase letters\r\n plainASCII.append(123-(97-(x-steps)))\r\n else:\r\n plainASCII.append(x-steps)\r\n elif x in range(65,91): # uppercase letters\r\n if x-steps<65:\r\n plainASCII.append(91-(65-(x-steps)))\r\n else:\r\n plainASCII.append(x-steps)\r\n elif x in range(48,58): # numeric values\r\n if x-(steps%10)<48:\r\n plainASCII.append(58-(48-(x-(steps%10))))\r\n else:\r\n plainASCII.append(x-(steps%10))\r\n else:\r\n plainASCII.append(x)\r\n\r\n plain = ''.join(map(chr,plainASCII))\r\n #print(plain)\r\n return plain\r\n\r\n # if step count is not provided - bruteforce\r\n else:\r\n steps = -26 # initialising steps from -26\r\n for steps in range(26):\r\n plainASCII=[]\r\n for x in cipherASCII:\r\n if x in range(97,123):\r\n if x-steps<97: # lowercase letters\r\n plainASCII.append(123-(97-(x-steps)))\r\n else:\r\n plainASCII.append(x-steps)\r\n elif x in range(65,91): # uppercase letters\r\n if x-steps<65:\r\n plainASCII.append(91-(65-(x-steps)))\r\n else:\r\n plainASCII.append(x-steps)\r\n elif x in range(48,58): # numeric values\r\n if x-(steps%10)<48:\r\n plainASCII.append(58-(48-(x-(steps%10))))\r\n else:\r\n plainASCII.append(x-(steps%10))\r\n else:\r\n plainASCII.append(x)\r\n\r\n plain = ''.join(map(chr,plainASCII))\r\n # prints all possible combinations for rotation steps -26 to +26\r\n print('{}[!]{} ROT{} \\t:{}{}{}'.format(color.GREEN,color.END,str(steps),color.RED,plain,color.END))\r\n steps+=1\r\n return\r\n\r\n# preparatory function for encryption that takes in the \r\n# plaintext and step counts from user and calls the encrypting function with those values\r\n# returns the ciphertext as returned from encryption function along with the step count given by user\r\ndef enc(plain):\r\n\r\n # taking input for the number of steps to rotate\r\n # int between -26 to +26 (with or without the signs allowed)\r\n try:\r\n steps = int(input('{}[?]{} Enter the number of steps to rotate (+x or -x): '.format(color.BLUE,color.END)))\r\n # checking if the given input is within the valid range\r\n if steps not in range(-26,27):\r\n raise ValueError()\r\n # calling the encrypt function with the plaintext and steps to rotate \r\n ciphertext = encrypt(plain, steps)\r\n\r\n # catching and handling ValueError to end gracefully\r\n except ValueError:\r\n print('{}[-]{} Please enter a number between 1-26 with + or - sign'.format(color.RED,color.END))\r\n quit()\r\n\r\n return ciphertext,steps\r\n\r\n# preparatory function for decryption that takes in the \r\n# ciphertext and step counts (if given) from user and calls the encrypting function with those values\r\n# returns the ciphertext as returned from encryption function along with the step count given by user - for known step count\r\n# returns None,None to caller function as bruteforce results are displayed by the decrypting function - for bruteforce\r\ndef dec(cipher):\r\n\r\n steps = None\r\n # taking input for the number of steps to reverse rotate\r\n # int between -26 to +26 (with or without the signs allowed)\r\n # this is the original number of steps as used during encryption\r\n try:\r\n steps = int(input('{}[?]{} Enter the number of steps rotated during encryption \\n{}[!]{} Leave empty to try bruteforce (+x or -x): '.format(color.BLUE,color.END,color.CYAN,color.END)))\r\n\r\n # checking if the given input is within the valid range\r\n if steps not in range(-26,27):\r\n raise ValueError()\r\n # calling the encrypt function with the plaintext and steps to rotate \r\n plaintext = decrypt(cipher=cipher, steps=steps)\r\n\r\n # catching and handling ValueError to end gracefully\r\n except ValueError:\r\n if not steps: \r\n decrypt(cipher=cipher,steps=steps)\r\n else:\r\n print('{}[-]{} Please enter a number between 1-26 with + or - sign'.format(color.RED,color.END))\r\n quit()\r\n\r\n finally:\r\n if steps:\r\n return plaintext,steps\r\n else:\r\n return None,None\r\n\r\n\r\ndef parsefile(filename):\r\n message = ''\r\n try:\r\n with open(filename) as f:\r\n for line in f:\r\n message+=line\r\n except FileNotFoundError:\r\n print('{}[-] File not found{}\\n{}[!] Please make sure the file with the filename exists in the current working directory{}'.format(color.RED,color.END,color.YELLOW,color.END))\r\n quit()\r\n return message\r\n\r\ndef run():\r\n try:\r\n clear()\r\n # prompt for choice of action\r\n choice = input('{}[?]{} Encrypt or Decrypt? [e/d] : '.format(color.BLUE,color.END))\r\n if choice == 'e' or choice == 'E':\r\n # whether to load a file for the plaintext or type it from the console\r\n filechoice = input('{}[?]{} Load from a file? [y/N] : '.format(color.BLUE,color.END)).lower()\r\n if filechoice != 'y':\r\n pt = input('{}[?]{} Enter the Plaintext : '.format(color.BLUE,color.END)) # plaintext input\r\n else:\r\n filename = input('{}[?]{} Enter the filename: '.format(color.BLUE,color.END))\r\n pt = parsefile(filename)\r\n ciphertext,steps = enc(pt) # calling the enc() function with the input\r\n print('{}[+]{} The Ciphertext with {}{}{} steps is : {}{}{}'.format(color.GREEN,color.END,color.YELLOW,steps,color.END,color.RED,ciphertext,color.END))\r\n elif choice == 'd' or choice == 'D':\r\n # whether to load a file for the plaintext or type it from the console\r\n filechoice = input('{}[?]{} Load from a file? [y/N] : '.format(color.BLUE,color.END)).lower()\r\n if filechoice != 'y':\r\n ct = input('{}[?]{} Enter the Ciphertext : '.format(color.BLUE,color.END)) # ciphertext input\r\n else:\r\n filename = input('{}[?]{} Enter the filename: '.format(color.BLUE,color.END))\r\n ct = parsefile(filename)\r\n plaintext,steps = dec(ct) # calling dec() function with the input\r\n if steps: # if not bruteforce - then only print results\r\n print('{}[+]{} The Plaintext with {}{}{} steps is : {}{}{}'.format(color.GREEN,color.END,color.YELLOW,steps,color.END,color.RED,plaintext,color.END))\r\n else:\r\n print('{}[!]{} The bruteforce attack completed successfully!'.format(color.GREEN,color.END))\r\n else:\r\n print('{}[-] Please provide a valid coice of action{}'.format(color.RED,color.END))\r\n quit()\r\n except KeyboardInterrupt:\r\n print('\\n{}[!] Exiting...{}'.format(color.RED,color.END))\r\n\r\n# main driver function\r\n# parses arguments \r\n# prompts the user for necessary inputs if arguments not provided \r\ndef main():\r\n try:\r\n clear()\r\n \r\n # script description\r\n parser = argparse.ArgumentParser(description='Rotational Encryption & Decryption')\r\n # encryption group option (single option --encrypt)\r\n enc_group = parser.add_argument_group('Encryption Options')\r\n enc_group.add_argument('-e','--encrypt', help='Encrypt a given Plaintext', default=False, action='store_true')\r\n # decryption group options (--decrypt and --brute)\r\n dec_group = parser.add_argument_group('Decryption Options')\r\n dec_group.add_argument('-d','--decrypt', help='Decrypt a given Ciphertext', default=False, action='store_true')\r\n dec_group.add_argument('-B','--brute', help='Bruteforce decryption (to be used only with -d, --decrypt)', default=False, action='store_true')\r\n # file option - whether to load from a file\r\n parser.add_argument('-f','--file', help='Load the Plaintext/ Ciphertext from a file', default=False, action='store_true')\r\n # message (either plain or cipher) - handled later on based on options\r\n parser.add_argument('TEXT', help='Plaintext or Ciphertext (based on mode)')\r\n\r\n try: # if all options and positional argument (TEXT) provided\r\n args = parser.parse_args() \r\n except: # if positional argument TEXT not provided - prompts user with necessary options\r\n # prompt for choice of action\r\n choice = input('{}[?]{} Encrypt or Decrypt? [e/d] : '.format(color.BLUE,color.END))\r\n if choice == 'e' or choice == 'E':\r\n # whether to load a file for the plaintext or type it from the console\r\n filechoice = input('{}[?]{} Load from a file? [y/N] : '.format(color.BLUE,color.END)).lower()\r\n if filechoice != 'y':\r\n pt = input('{}[?]{} Enter the Plaintext : '.format(color.BLUE,color.END)) # plaintext input\r\n else:\r\n filename = input('{}[?]{} Enter the filename: '.format(color.BLUE,color.END))\r\n pt = parsefile(filename)\r\n ciphertext,steps = enc(pt) # calling the enc() function with the input\r\n print('{}[+]{} The Ciphertext with {}{}{} steps is : {}{}{}'.format(color.GREEN,color.END,color.YELLOW,steps,color.END,color.RED,ciphertext,color.END))\r\n elif choice == 'd' or choice == 'D':\r\n # whether to load a file for the plaintext or type it from the console\r\n filechoice = input('{}[?]{} Load from a file? [y/N] : '.format(color.BLUE,color.END)).lower()\r\n if filechoice != 'y':\r\n ct = input('{}[?]{} Enter the Ciphertext : '.format(color.BLUE,color.END)) # ciphertext input\r\n else:\r\n filename = input('{}[?]{} Enter the filename: '.format(color.BLUE,color.END))\r\n ct = parsefile(filename)\r\n plaintext,steps = dec(ct) # calling dec() function with the input\r\n if steps: # if not bruteforce - then only print results\r\n print('{}[+]{} The Plaintext with {}{}{} steps is : {}{}{}'.format(color.GREEN,color.END,color.YELLOW,steps,color.END,color.RED,plaintext,color.END))\r\n else:\r\n print('{}[!]{} The bruteforce attack completed successfully!'.format(color.GREEN,color.END))\r\n else:\r\n print('{}[-] Please provide a valid coice of action{}'.format(color.RED,color.END))\r\n quit()\r\n\r\n # parsing command line argumets (provided the necvessary ones are given)\r\n if args.encrypt: # if encrypt flag is on\r\n if args.decrypt: # decrypt flag should be off\r\n print('{}[-] Please select only one option among Encrypt or Decrypt at a time{}'.format(color.RED,color.END))\r\n quit()\r\n if args.brute: # bruteforce flag should be off\r\n print('{}[-] Bruteforce can only be used during Decryption{}'.format(color.RED,color.END))\r\n quit()\r\n else: # good to go - call enc() function and display result\r\n if args.file:\r\n pt = parsefile(args.TEXT)\r\n ciphertext,steps = enc(pt)\r\n print('{}[+]{} The Ciphertext with {}{}{} steps is : {}{}{}'.format(color.GREEN,color.END,color.YELLOW,steps,color.END,color.RED,ciphertext,color.END))\r\n else:\r\n ciphertext,steps = enc(args.TEXT)\r\n print('{}[+]{} The Ciphertext with {}{}{} steps is : {}{}{}'.format(color.GREEN,color.END,color.YELLOW,steps,color.END,color.RED,ciphertext,color.END))\r\n\r\n elif args.decrypt: # if decrypt flag is on\r\n if args.brute: # if bruteforce option is also on\r\n if args.file:\r\n ct = parsefile(args.TEXT)\r\n decrypt(ct,None)\r\n else:\r\n decrypt(args.TEXT,None) # call decrypt function directly - steps not required\r\n else: # no bruteforce - steps known\r\n if args.file:\r\n ct = parsefile(args.TEXT)\r\n plaintext,steps = dec(ct)\r\n if steps:\r\n print('{}[+]{} The Plaintext with {}{}{} steps is : {}{}{}'.format(color.GREEN,color.END,color.YELLOW,steps,color.END,color.RED,plaintext,color.END))\r\n else:\r\n print('{}[!]{} The bruteforce attack completed successfully!'.format(color.GREEN,color.END))\r\n else:\r\n plaintext,steps = dec(args.TEXT) # call dec() function and display result\r\n if steps:\r\n print('{}[+]{} The Plaintext with {}{}{} steps is : {}{}{}'.format(color.GREEN,color.END,color.YELLOW,steps,color.END,color.RED,plaintext,color.END))\r\n else:\r\n print('{}[!]{} The bruteforce attack completed successfully!'.format(color.GREEN,color.END))\r\n\r\n # if no arguments are provided except for positional (TEXT)\r\n else:\r\n print('{}[-] At least one of Encryption or Decryption action is required{}'.format(color.RED,color.END))\r\n\r\n except KeyboardInterrupt:\r\n print('\\n{}[!] Exiting...{}'.format(color.RED,color.END))\r\n quit()\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n","sub_path":"shift.py","file_name":"shift.py","file_ext":"py","file_size_in_byte":16359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"495668374","text":"import sys, re, datetime, pickle\nfrom walt.common.constants import WALT_SERVER_TCP_PORT\nfrom walt.common.tcp import read_pickle, write_pickle, client_sock_file, \\\n Requests\nfrom plumbum import cli\nfrom walt.client.application import WalTCategoryApplication, WalTApplication\nfrom walt.client.config import conf\nfrom walt.client.link import ClientToServerLink\nfrom walt.client.tools import confirm\nfrom walt.client.timeout import start_timeout, stop_timeout, timeout_reached, cli_timeout_switch\n\nDATE_FORMAT_STRING= '%Y-%m-%d %H:%M:%S'\nDATE_FORMAT_STRING_HUMAN= '--
::'\nDATE_FORMAT_STRING_EXAMPLE= '2015-09-28 15:16:39'\n\nDEFAULT_FORMAT_STRING= \\\n '{timestamp:%H:%M:%S.%f} {sender}.{stream} -> {line}'\n\nSECONDS_PER_UNIT = {'s':1, 'm':60, 'h':3600, 'd':86400}\nNUM_LOGS_CONFIRM_TRESHOLD = 1000\n\nMSG_INVALID_CHECKPOINT_NAME=\"\"\"\\\nInvalid checkpoint name:\n* Only alnum and dash(-) characters are allowed.\n* dash(-) is not allowed as the 1st character.\n\"\"\"\n\ndef isatty():\n return sys.stdout.isatty() and sys.stdin.isatty()\n\ndef validate_checkpoint_name(name):\n return re.match('^[a-zA-Z0-9]+[a-zA-Z0-9\\-]+$', name)\n\ndef compute_relative_date(server_time, rel_date):\n try:\n delay = datetime.timedelta(\n seconds = int(rel_date[1:-1]) * \\\n SECONDS_PER_UNIT[rel_date[-1]])\n except:\n print(\"Invalid relative date. Should be: -[dhms] (e.g. '-6h' for 'six hours ago')\")\n sys.exit(1)\n return pickle.dumps(server_time - delay)\n\nclass LogsFlowFromServer(object):\n def __init__(self, walt_server_host):\n self.f = client_sock_file(walt_server_host, WALT_SERVER_TCP_PORT)\n def read_log_record(self):\n return read_pickle(self.f)\n def request_log_dump(self, **kwargs):\n Requests.send_id(self.f, Requests.REQ_DUMP_LOGS)\n write_pickle(kwargs, self.f)\n def close(self):\n self.f.close()\n\nclass WalTLog(WalTCategoryApplication):\n \"\"\"management of logs\"\"\"\n pass\n\nclass WalTLogShowOrWait(WalTApplication):\n \"\"\"Implements options and features common to \"show\" and \"wait\" subcommands\"\"\"\n format_string = cli.SwitchAttr(\n \"--format\",\n str,\n argname = 'LOG_FORMAT',\n default = DEFAULT_FORMAT_STRING,\n help= \"\"\"format used to print logs (see walt help show log-format)\"\"\")\n set_of_nodes = cli.SwitchAttr(\n \"--nodes\",\n str,\n argname = 'SET_OF_NODES',\n default = 'my-nodes',\n help= \"\"\"targeted nodes (see walt help show node-terminology)\"\"\")\n streams = cli.SwitchAttr(\n \"--streams\",\n str,\n argname = 'STREAMS_REGEXP',\n default = None,\n help= \"\"\"selected log streams (as a regular expr.)\"\"\")\n\n @staticmethod\n def analyse_history_range(server, history_range):\n server_time = pickle.loads(server.get_pickled_time())\n MALFORMED=(False,)\n try:\n if history_range.lower() == 'none':\n return True, None\n elif history_range.lower() == 'full':\n return True, (None, None)\n parts = history_range.split(':')\n if len(parts) != 2:\n return MALFORMED\n history = []\n for part in parts:\n if part == '':\n history.append(None)\n elif part.startswith('-'):\n rel_date = compute_relative_date(server_time, part)\n history.append(rel_date)\n elif validate_checkpoint_name(part):\n cptime = server.get_pickled_checkpoint_time(part)\n if cptime == None:\n return MALFORMED\n history.append(cptime)\n else:\n return MALFORMED\n if history[0] and history[1]:\n if pickle.loads(history[0]) > pickle.loads(history[1]):\n print('Issue with the HISTORY_RANGE specified: ' + \\\n 'the starting point is newer than the ending point.')\n return MALFORMED\n return True, tuple(history)\n except Exception as e:\n return MALFORMED\n\n @staticmethod\n def verify_regexps(*regexps):\n for regexp in regexps:\n if regexp is None:\n continue\n try:\n re.compile(regexp)\n except:\n print('Invalid regular expression: %s.' % regexp)\n return False\n return True\n\n @staticmethod\n def start_streaming(format_string, history_range, realtime, senders, streams,\n logline_regexp, stop_test, timeout = -1):\n conn = LogsFlowFromServer(conf['server'])\n conn.request_log_dump( history = history_range,\n realtime = realtime,\n senders = senders,\n streams = streams,\n logline_regexp = logline_regexp)\n if timeout > 0:\n start_timeout(timeout)\n while True:\n try:\n record = conn.read_log_record()\n # sigalarm is caught by pickle, it will just abort the read\n # and record will be None.\n # Since we cannot get a TimeoutException, we check with timeout_reached().\n if timeout > 0 and timeout_reached():\n print('Timeout was reached.')\n break\n if record == None:\n break\n print(format_string.format(**record))\n sys.stdout.flush()\n if stop_test is not None and stop_test(**record):\n break\n except KeyboardInterrupt:\n print()\n break\n except Exception as e:\n print('Could not display the log record.')\n print('Verify your format string.')\n break\n if timeout > 0:\n stop_timeout()\n\n@WalTLog.subcommand(\"show\")\nclass WalTLogShow(WalTLogShowOrWait):\n \"\"\"Dump logs on standard output\"\"\"\n realtime = cli.Flag(\n \"--realtime\",\n default = False,\n help= \"\"\"enable realtime mode (see walt help show log-realtime)\"\"\")\n history_range = cli.SwitchAttr(\n \"--history\",\n str,\n argname = 'HISTORY_RANGE',\n default = 'none',\n help= \"\"\"history range to be retrieved (see walt help show log-history)\"\"\")\n\n def main(self, logline_regexp = None):\n if self.realtime == False and self.history_range == 'none':\n print('You must specify at least 1 of the options --realtime and --history.')\n print(\"See 'walt help show log-realtime' and 'walt help show log-history' for more info.\")\n return\n if not WalTLogShowOrWait.verify_regexps(self.streams, logline_regexp):\n return\n with ClientToServerLink() as server:\n senders = server.parse_set_of_nodes(self.set_of_nodes)\n if senders == None:\n return\n range_analysis = WalTLogShowOrWait.analyse_history_range(server, self.history_range)\n if not range_analysis[0]:\n print('''Invalid HISTORY_RANGE. See 'walt help show log-history' for more info.''')\n return\n history_range = range_analysis[1]\n # Note : if a regular expression is specified, we do not bother computing the number\n # of log records, because this computation would be too expensive, and the number of\n # matching lines is probably low.\n if history_range and logline_regexp is None and isatty():\n num_logs = server.count_logs(history = history_range, senders = senders, streams = self.streams)\n if num_logs > NUM_LOGS_CONFIRM_TRESHOLD:\n print('This will display approximately %d log records from history.' % num_logs)\n if not confirm():\n return\n WalTLogShowOrWait.start_streaming(self.format_string, history_range, self.realtime,\n senders, self.streams, logline_regexp, None)\n\n@WalTLog.subcommand(\"add-checkpoint\")\nclass WalTLogAddCheckpoint(WalTApplication):\n \"\"\"Record a checkpoint (reference point in time)\"\"\"\n date = cli.SwitchAttr(\"--date\", str, default=None,\n help=\"specify date (see walt help show log-checkpoint)\")\n def main(self, checkpoint_name):\n with ClientToServerLink() as server:\n if self.date:\n if self.date.startswith('-'):\n server_time = pickle.loads(server.get_pickled_time())\n self.date = compute_relative_date(server_time, self.date)\n else:\n try:\n self.date = pickle.dumps(datetime.datetime.strptime(\\\n self.date, DATE_FORMAT_STRING))\n except:\n print('Could not parse the date specified.')\n print('Expected format is: %s' % DATE_FORMAT_STRING_HUMAN)\n print('Example: %s' % DATE_FORMAT_STRING_EXAMPLE)\n return\n if not validate_checkpoint_name(checkpoint_name):\n sys.stderr.write(MSG_INVALID_CHECKPOINT_NAME)\n return\n server.add_checkpoint(checkpoint_name, self.date)\n\n@WalTLog.subcommand(\"remove-checkpoint\")\nclass WalTLogRemoveCheckpoint(WalTApplication):\n \"\"\"Remove a checkpoint\"\"\"\n def main(self, checkpoint_name):\n with ClientToServerLink() as server:\n server.remove_checkpoint(checkpoint_name)\n\n@WalTLog.subcommand(\"list-checkpoints\")\nclass WalTLogListCheckpoints(WalTApplication):\n \"\"\"List checkpoints\"\"\"\n def main(self):\n with ClientToServerLink() as server:\n server.list_checkpoints()\n\n@WalTLog.subcommand(\"wait\")\nclass WalTLogWait(WalTLogShowOrWait):\n \"\"\"Wait for a given log line\"\"\"\n mode = cli.SwitchAttr(\n \"--mode\",\n cli.Set(\"ALL\", \"ANY\", case_sensitive = False),\n argname = 'MODE',\n default = 'ANY',\n help= \"\"\"specify mode (see walt help show log-wait)\"\"\")\n time_margin = cli.SwitchAttr(\n \"--time-margin\",\n int,\n argname = 'SECONDS',\n default = 0,\n help= \"\"\"also look in recent past logs if they matched\"\"\")\n timeout = cli_timeout_switch()\n\n def main(self, logline_regexp):\n if not WalTLogShowOrWait.verify_regexps(self.streams, logline_regexp):\n return\n with ClientToServerLink() as server:\n senders = server.parse_set_of_nodes(self.set_of_nodes)\n if senders == None:\n return\n if self.time_margin != 0:\n history_range = '-%ds:' % self.time_margin\n range_analysis = WalTLogShowOrWait.analyse_history_range(server, history_range)\n history_range = range_analysis[1]\n else:\n history_range = None\n if self.mode == 'ANY':\n # as soon as a logline matches, we stop\n def stop_test(**record):\n return True\n else:\n # we stop when all nodes have emitted a matching logline\n missing_senders = set(senders)\n def stop_test(**record):\n missing_senders.discard(record['sender'])\n if len(missing_senders) == 0:\n return True # yes, we should stop\n else:\n return False # no, we are not done yet\n WalTLogShowOrWait.start_streaming(self.format_string, history_range, True,\n senders, self.streams, logline_regexp, stop_test, self.timeout)\n","sub_path":"client/walt/client/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":12149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"598614863","text":"\"\"\"\nBranch-and-bound solver implementation.\n\nCopyright by Gabriel A. Hackebeil (gabe.hackebeil@gmail.com).\n\"\"\"\nimport sys\nimport time\n\nfrom pybnb.common import (minimize,\n maximize,\n QueueStrategy,\n TerminationCondition,\n SolutionStatus)\nfrom pybnb.problem import (_SolveInfo,\n _SimpleSolveInfoCollector,\n _ProblemWithSolveInfoCollection)\nfrom pybnb.misc import (MPI_InterruptHandler,\n time_format,\n as_stream,\n get_simple_logger)\nfrom pybnb.node import Node\nfrom pybnb.convergence_checker import (_default_scale,\n ConvergenceChecker)\nfrom pybnb.dispatcher_proxy import DispatcherProxy\nfrom pybnb.dispatcher import (DispatcherLocal,\n DispatcherDistributed,\n DispatcherQueueData)\n\ntry:\n import mpi4py\nexcept ImportError: #pragma:nocover\n pass\n\nimport six\n\nclass _notset(object):\n pass\n\nclass SolverResults(object):\n \"\"\"Stores the results of a branch-and-bound solve.\n\n Attributes\n ----------\n solution_status : :class:`SolutionStatus `\n The solution status. This attribute is comparable\n with strings as well as attributes of the\n :class:`SolutionStatus `\n enum.\n\n Example\n -------\n\n >>> import pybnb\n >>> results = pybnb.SolverResults()\n >>> results.solution_status = pybnb.SolutionStatus.optimal\n >>> assert results.solution_status == \"optimal\"\n >>> assert results.solution_status == pybnb.SolutionStatus.optimal\n >>> assert results.solution_status.value == \"optimal\"\n\n termination_condition : :class:`TerminationCondition `\n The solve termination condition, as\n determined by the dispatcher. This attribute is comparable\n with strings as well as attributes of the\n :class:`TerminationCondition `\n enum.\n\n Example\n -------\n\n >>> import pybnb\n >>> results = pybnb.SolverResults()\n >>> results.termination_condition = pybnb.TerminationCondition.optimality\n >>> assert results.termination_condition == \"optimality\"\n >>> assert results.termination_condition == pybnb.TerminationCondition.optimality\n >>> assert results.termination_condition.value == \"optimality\"\n\n objective : float\n The best objective found.\n bound : float\n The global optimality bound.\n absolute_gap : float\n The absolute gap between the objective and bound.\n relative_gap : float\n The relative gap between the objective and bound.\n nodes : float\n The total number of nodes processes by all workers.\n wall_time : float\n The process-local wall time (seconds). This is the\n only value on the results object that varies between\n processes.\n \"\"\"\n\n def __init__(self):\n self.solution_status = None\n self.termination_condition = None\n self.objective = None\n self.bound = None\n self.absolute_gap = None\n self.relative_gap = None\n self.nodes = None\n self.wall_time = None\n\n def pprint(self, stream=sys.stdout):\n \"\"\"Prints a nicely formatted representation of the\n results.\n\n Parameters\n ----------\n stream : file-like object or string, optional\n A file-like object or a filename where results\n should be written to. (default: ``sys.stdout``)\n \"\"\"\n with as_stream(stream) as stream:\n stream.write(\"solver results:\\n\")\n self.write(stream, prefix=\" - \", pretty=True)\n\n def write(self, stream, prefix=\"\", pretty=False):\n \"\"\"Writes results in YAML format to a stream or\n file.\n\n Parameters\n ----------\n stream : file-like object or string\n A file-like object or a filename where results\n should be written to.\n prefix : string, optional\n A string to use as a prefix for each line that\n is written. (default: '')\n pretty : bool, optional\n Indicates whether or not certain recognized\n attributes should be formatted for more\n human-readable output. (default: False)\n \"\"\"\n with as_stream(stream) as stream:\n attrs = vars(self)\n names = sorted(list(attrs.keys()))\n first = ('solution_status', 'termination_condition',\n 'objective', 'bound',\n 'absolute_gap', 'relative_gap',\n 'nodes', 'wall_time')\n for cnt, name in enumerate(first):\n if not hasattr(self, name):\n continue\n names.remove(name)\n val = getattr(self, name)\n if val is not None:\n if pretty:\n if name == 'wall_time':\n val = time_format(val, digits=2)\n elif name in ('objective','bound',\n 'absolute_gap','relative_gap'):\n val = \"%.7g\" % (val)\n if name in (\"solution_status\", \"termination_condition\"):\n val = val.value\n stream.write(prefix+'%s: %s\\n'\n % (name, val))\n for name in names:\n stream.write(prefix+'%s: %s\\n'\n % (name, getattr(self, name)))\n\n def __str__(self):\n \"\"\"Represents the results as a string.\"\"\"\n tmp = six.StringIO()\n self.pprint(stream=tmp)\n return tmp.getvalue()\n\nclass Solver(object):\n \"\"\"A branch-and-bound solver.\n\n Parameters\n ----------\n comm : ``mpi4py.MPI.Comm``, optional\n The MPI communicator to use. If unset, the\n mpi4py.MPI.COMM_WORLD communicator will be\n used. Setting this keyword to None will disable the\n use of MPI and avoid an attempted import of\n mpi4py.MPI (which avoids triggering a call to\n `MPI_Init()`).\n dispatcher_rank : int, optional\n The process with this rank will be designated as the\n dispatcher process. If MPI functionality is disabled\n (by setting comm=None), this keyword must be 0.\n (default: 0)\n \"\"\"\n\n def __init__(self,\n comm=_notset,\n dispatcher_rank=0):\n mpi = True\n if comm is None:\n mpi = False\n self._comm = None\n self._worker_flag = None\n self._dispatcher_flag = None\n self._disp = None\n self._time = None\n if mpi:\n import mpi4py.MPI\n assert mpi4py.MPI.Is_initialized()\n assert comm is not None\n if comm is _notset:\n comm = mpi4py.MPI.COMM_WORLD\n if (int(dispatcher_rank) != dispatcher_rank) or \\\n (dispatcher_rank < 0) or \\\n (dispatcher_rank >= comm.size):\n raise ValueError(\"The 'dispatcher_rank' keyword \"\n \"has been set to %s, which is not \"\n \"an available rank given the \"\n \"size of the MPI communicator (%d).\"\n % (dispatcher_rank, comm.size))\n self._comm = comm\n if comm.size > 1:\n dispatcher_rank = int(dispatcher_rank)\n if comm.rank == dispatcher_rank:\n self._disp = DispatcherDistributed(comm)\n self._worker_flag = False\n self._dispatcher_flag = True\n else:\n self._disp = DispatcherProxy(comm)\n self._worker_flag = True\n self._dispatcher_flag = False\n else:\n self._disp = DispatcherLocal()\n self._worker_flag = True\n self._dispatcher_flag = True\n self._time = mpi4py.MPI.Wtime\n else:\n if dispatcher_rank != 0:\n raise ValueError(\n \"MPI functionality has been disabled but \"\n \"the 'dispatcher_rank' keyword is set to \"\n \"something other than 0.\")\n assert self._comm is None\n self._disp = DispatcherLocal()\n self._worker_flag = True\n self._dispatcher_flag = True\n self._time = time.time\n assert self._worker_flag in (True, False)\n assert self._dispatcher_flag in (True, False)\n assert self._disp is not None\n assert self._time is not None\n self._solve_start = None\n self._wall_time = 0.0\n self._best_objective = None\n self._local_solve_info = _SolveInfo()\n self._global_solve_info = None\n\n def _reset_local_solve_stats(self):\n self._solve_start = None\n self._wall_time = 0.0\n self._best_objective = None\n self._local_solve_info.reset()\n self._global_solve_info = None\n\n def _check_update_best_objective(self,\n convergence_checker,\n new_objective):\n if convergence_checker.objective_improved(\n new_objective,\n self._best_objective):\n self._best_objective = new_objective\n return True\n else:\n return False\n\n def _fill_results(self, results, convergence_checker):\n if results.bound == convergence_checker.infeasible_objective:\n assert results.objective == \\\n convergence_checker.infeasible_objective, \\\n str(results.objective)\n results.solution_status = SolutionStatus.infeasible\n elif results.objective == \\\n convergence_checker.infeasible_objective:\n results.solution_status = SolutionStatus.unknown\n elif results.objective == \\\n convergence_checker.unbounded_objective:\n assert results.bound == \\\n convergence_checker.unbounded_objective, \\\n str(results.bound)\n results.solution_status = SolutionStatus.unbounded\n else:\n results.absolute_gap = convergence_checker.\\\n compute_absolute_gap(results.bound,\n results.objective)\n results.relative_gap = convergence_checker.\\\n compute_relative_gap(results.bound,\n results.objective)\n if convergence_checker.objective_is_optimal(\n results.objective,\n results.bound):\n results.solution_status = SolutionStatus.invalid\n if (convergence_checker.sense == minimize) and \\\n (results.bound <= results.objective):\n results.solution_status = SolutionStatus.optimal\n elif (convergence_checker.sense == maximize) and \\\n (results.bound >= results.objective):\n results.solution_status = SolutionStatus.optimal\n else:\n results.solution_status = SolutionStatus.feasible\n\n def _solve(self,\n problem,\n best_objective,\n disable_objective_call,\n convergence_checker,\n results):\n infeasible_objective = problem.infeasible_objective()\n assert infeasible_objective == \\\n convergence_checker.infeasible_objective\n unbounded_objective = problem.unbounded_objective()\n assert unbounded_objective == \\\n convergence_checker.unbounded_objective\n\n self._best_objective = best_objective\n children = ()\n bound = unbounded_objective\n if not isinstance(problem, _ProblemWithSolveInfoCollection):\n problem = _SimpleSolveInfoCollector(problem)\n problem.set_clock(self._time)\n problem.set_solve_info_object(self._local_solve_info)\n\n working_node = Node()\n assert working_node.tree_id is None\n # start the work loop\n while (1):\n update_start = self._time()\n stop, new_objective, data = \\\n self._disp.update(\n self._best_objective,\n bound,\n self._local_solve_info,\n children)\n update_stop = self._time()\n self._local_solve_info._increment_queue_stat(\n update_stop-update_start, 1)\n\n updated = self._check_update_best_objective(\n convergence_checker,\n new_objective)\n if updated and \\\n (self._best_objective != unbounded_objective):\n problem.notify_new_best_objective_received(\n self._best_objective)\n del updated\n\n children = []\n\n if stop:\n # make sure all processes have the exact same best\n # objective value (not just subject to tolerances)\n self._best_objective = new_objective\n break\n # load the new data into the working_node\n working_node._set_data(data)\n del new_objective\n del data\n self._local_solve_info._increment_explored_nodes_stat(1)\n\n bound = working_node.bound\n current_tree_id = working_node.tree_id\n current_tree_depth = working_node.tree_depth\n assert current_tree_id is not None\n assert current_tree_depth >= 0\n\n # we should not be receiving a node that\n # does not satisfy these assertions\n assert convergence_checker.eligible_for_queue(\n bound,\n self._best_objective)\n\n problem.load_state(working_node)\n\n new_bound = problem.bound()\n if convergence_checker.bound_worsened(new_bound, bound): #pragma:nocover\n self._disp.log_warning(\n \"WARNING: Bound became worse \"\n \"(old=%r, new=%r)\"\n % (bound, new_bound))\n working_node.bound = new_bound\n bound = new_bound\n\n if convergence_checker.eligible_for_queue(\n bound,\n self._best_objective):\n objective = working_node.objective\n if not disable_objective_call:\n objective = problem.objective()\n working_node.objective = objective\n if convergence_checker.best_bound(bound, objective) != objective: #pragma:nocover\n self._disp.log_warning(\n \"WARNING: Local node bound is worse \"\n \"than local node objective (bound=%r, \"\n \"objective=%r)\" % (bound, objective))\n updated = self._check_update_best_objective(\n convergence_checker,\n objective)\n if updated and \\\n (self._best_objective != unbounded_objective):\n problem.notify_new_best_objective(\n self._best_objective)\n del updated\n if (objective != unbounded_objective) and \\\n convergence_checker.eligible_for_queue(\n bound,\n self._best_objective) and \\\n convergence_checker.eligible_to_branch(\n bound,\n objective):\n clist = problem.branch(working_node)\n for child in clist:\n assert child.parent_tree_id == current_tree_id\n assert child.tree_id is None\n assert child.tree_depth >= current_tree_depth + 1\n assert child.objective == working_node.objective\n children.append(child._data)\n if convergence_checker.bound_worsened(child.bound, bound): #pragma:nocover\n self._disp.log_warning(\n \"WARNING: Bound on child node \"\n \"returned from branch method \"\n \"is worse than parent node \"\n \"(child=%r, parent=%r)\"\n % (child.bound, bound))\n\n assert len(data) == 3\n global_bound = data[0]\n termination_condition = data[1]\n global_solve_info = data[2]\n return (self._best_objective,\n global_bound,\n termination_condition,\n global_solve_info)\n\n #\n # Interface\n #\n\n @property\n def is_worker(self):\n \"\"\"Indicates if this process has been designated as\n a worker.\"\"\"\n return self._worker_flag\n\n @property\n def is_dispatcher(self):\n \"\"\"Indicates if this process has been designated as\n the dispatcher.\"\"\"\n return self._dispatcher_flag\n\n @property\n def comm(self):\n \"\"\"The full MPI communicator that includes the\n dispatcher and all workers. Will be None if MPI\n functionality has been disabled.\"\"\"\n return self._comm\n\n @property\n def worker_comm(self):\n \"\"\"The worker MPI communicator. Will be None on any\n processes for which :attr:`Solver.is_worker` is\n False, or if MPI functionality has been disabled.\"\"\"\n if (self._comm is None) or \\\n (self._comm.size == 1):\n return self._comm\n elif not self.is_dispatcher:\n return self._disp.worker_comm\n return None\n\n @property\n def worker_count(self):\n \"\"\"The number of worker processes associated with this solver.\"\"\"\n if (self._comm is None) or \\\n (self._comm.size == 1):\n return 1\n elif not self.is_dispatcher:\n return self._disp.worker_comm.size\n else:\n return len(self._disp.worker_ranks)\n\n def collect_worker_statistics(self):\n \"\"\"Collect individual worker statistics about the\n most recent solve.\n\n Returns\n -------\n dict\n A dictionary whose keys are the different\n statistics collected, where each entry is a list\n storing a value for each worker.\n \"\"\"\n import numpy\n stats = {}\n if (self.comm is not None) and \\\n (self.comm.size > 1):\n gathered = numpy.empty((self.worker_count, 12),\n dtype=float)\n if self.is_worker:\n assert self.worker_comm is not None\n assert not self.is_dispatcher\n solve_info = self._local_solve_info\n mine = numpy.array(\n [self._wall_time,\n solve_info.total_queue_time,\n solve_info.queue_call_count,\n solve_info.total_objective_time,\n solve_info.objective_call_count,\n solve_info.total_bound_time,\n solve_info.bound_call_count,\n solve_info.total_branch_time,\n solve_info.branch_call_count,\n solve_info.total_load_state_time,\n solve_info.load_state_call_count,\n solve_info.explored_nodes_count],\n dtype=float)\n assert len(mine) == gathered.shape[1]\n self.worker_comm.Allgather([mine, mpi4py.MPI.DOUBLE],\n [gathered, mpi4py.MPI.DOUBLE])\n if self.worker_comm.rank == 0:\n self.comm.Send([gathered, mpi4py.MPI.DOUBLE],\n self._disp.dispatcher_rank,\n tag=11112111)\n else:\n assert self.worker_comm is None\n assert self.is_dispatcher\n self.comm.Recv([gathered, mpi4py.MPI.DOUBLE],\n tag=11112111)\n gathered = gathered.T.tolist()\n stats['wall_time'] = gathered[0]\n stats['queue_time'] = gathered[1]\n stats['queue_call_count'] = gathered[2]\n stats['objective_time'] = gathered[3]\n stats['objective_call_count'] = gathered[4]\n stats['bound_time'] = gathered[5]\n stats['bound_call_count'] = gathered[6]\n stats['branch_time'] = gathered[7]\n stats['branch_call_count'] = gathered[8]\n stats['load_state_time'] = gathered[9]\n stats['load_state_call_count'] = gathered[10]\n stats['explored_nodes_count'] = gathered[11]\n else:\n assert self.is_worker\n assert self.is_dispatcher\n solve_info = self._local_solve_info\n stats['wall_time'] = [self._wall_time]\n stats['queue_time'] = [solve_info.total_queue_time]\n stats['queue_call_count'] = [solve_info.queue_call_count]\n stats['objective_time'] = \\\n [solve_info.total_objective_time]\n stats['objective_call_count'] = \\\n [solve_info.objective_call_count]\n stats['bound_time'] = \\\n [solve_info.total_bound_time]\n stats['bound_call_count'] = \\\n [solve_info.bound_call_count]\n stats['branch_time'] = \\\n [solve_info.total_branch_time]\n stats['branch_call_count'] = \\\n [solve_info.branch_call_count]\n stats['load_state_time'] = \\\n [solve_info.total_load_state_time]\n stats['load_state_call_count'] = \\\n [solve_info.load_state_call_count]\n stats['explored_nodes_count'] = \\\n [solve_info.explored_nodes_count]\n\n return stats\n\n def save_dispatcher_queue(self):\n \"\"\"Saves the dispatcher queue.\n\n Returns\n -------\n queue : :class:`pybnb.dispatcher.DispatcherQueueData` or None\n If this process is the dispatcher, this method\n will return an object storing any nodes\n currently in the dispatcher queue. If this\n process is not the dispatcher, this method will\n return None. The returned object can be used to\n reinitialize a solve (e.g., with different\n algorithms settings) by assigning it to the\n initialize_queue keyword of the\n :func:`Solver.solve` method.\n \"\"\"\n ret = None\n if self.is_dispatcher:\n ret = self._disp.save_dispatcher_queue()\n return ret\n\n def solve(self,\n problem,\n best_objective=None,\n disable_objective_call=False,\n absolute_gap=1e-8,\n relative_gap=1e-4,\n scale_function=_default_scale,\n queue_tolerance=0,\n branch_tolerance=0,\n comparison_tolerance=0,\n objective_stop=None,\n bound_stop=None,\n node_limit=None,\n time_limit=None,\n initialize_queue=None,\n queue_strategy=\"bound\",\n log_interval_seconds=1.0,\n log_new_incumbent=True,\n log=_notset):\n \"\"\"Solve a problem using branch-and-bound.\n\n Note\n ----\n Parameters for this function are treated differently\n depending on whether the process is a worker or\n dispatcher. For the serial case (no MPI), the single\n process is both a worker and a dispatcher. For the\n parallel case, exactly one process is a dispatcher\n and all processes are workers. A **(W)** in the\n parameter description indicates that it is only used\n by worker processes (ignored otherwise). A **(D)**\n in the parameter description indicates that it is\n only used by the dispatcher process (ignored\n otherwise). An **(A)** indicates that it is used by\n all processes, and it is assumed the same value is\n provided for each process; otherwise, the behavior\n is undefined.\n\n Parameters\n ----------\n problem : :class:`pybnb.Problem `\n An object defining a branch-and-bound problem.\n best_objective : float, optional\n Initializes the solve with an assumed best\n objective. This is the only option used by both\n worker and dispatcher processes that can be set\n to a different value on each process. The\n dispatcher will collect all values and use the\n best. (default: None)\n disable_objective_call : bool, optional\n **(W)** Disables requests for an objective value from\n subproblems. (default: False)\n absolute_gap : float, optional\n **(A)** The maximum absolute difference between\n the global bound and best objective for the\n problem to be considered solved to\n optimality. Setting to `None` will disable this\n optimality check. (default: 1e-8)\n relative_gap : float, optional\n **(A)** The maximum relative difference (absolute\n difference scaled by `max{1.0,|objective|}`)\n between the global bound and best objective for\n the problem to be considered solved to\n optimality. Setting to `None` will disable this\n optimality check. (default: 1e-4)\n scale_function : function, optional\n **(A)** A function with signature `f(bound,\n objective) -> float` that returns a positive\n scale factor used to convert the absolute\n difference between the bound and objective into\n a relative difference. The relative difference\n is compared with the `relative_gap` convergence\n tolerance to determine if the solver should\n terminate. The default is equivalent to\n `max{1.0,|objective|}`. Other examples one\n could use are `max{|bound|,|objective|}`,\n `(|bound|+|objective|)/2`, etc.\n queue_tolerance : float, optional\n **(A)** The absolute tolerance used when\n deciding if a node is eligible to enter the\n queue. The difference between the node bound and\n the incumbent objective must be greater than\n this value. The default setting of zero means\n that nodes whose bound is equal to the incumbent\n objective are not eligible to enter the\n queue. Setting this to larger values can be used\n to control the queue size, but it should be kept\n small enough to allow absolute and relative\n optimality tolerances to be met. This option can\n also be set to `None` to allow nodes with a\n bound equal to (but not greater than) the\n incumbent objective to enter the queue.\n (default: 0)\n branch_tolerance : float, optional\n **(A)** The absolute tolerance used when\n deciding if the computed objective and bound for\n a node are sufficiently different to branch into\n the node. The default value of zero means that\n branching will occur if the bound is not exactly\n equal to the objective. This option can be set\n to `None` to enable branching for nodes with a\n bound and objective that are exactly\n equal. (default: 0)\n comparison_tolerance : float, optional\n **(A)** The absolute tolerance used when\n deciding if two objective or bound values are\n sufficiently different to be considered improved\n or worsened. This tolerance controls when the\n solver considers a new incumbent objective to be\n found. It also controls when warnings are output\n about bounds becoming worse on child\n nodes. Setting this to larger values can be used\n to avoid the above solver actions due to\n insignificant numerical differences, but it is\n better to deal with these numerical issues by\n rounding numbers to a reliable precision before\n returning them from the problem methods.\n (default: 0)\n objective_stop : float, optional\n **(A)** If provided, the solve will terminate\n when a feasible objective is found that is at\n least as good as the specified value, and the\n termination_condition flag on the results object\n will be set to \"objective_limit\". If this value\n is infinite, the solve will terminate as soon as\n a finite objective is found. (default: None)\n bound_stop : float, optional\n **(A)** If provided, the solve will terminate\n when the global bound on the objective is at\n least as good as the specified value, and the\n termination_condition flag on the results object\n will be set to \"objective_limit\". If this value\n is infinite, the solve will terminate as soon as\n a finite bound is found. (default: None)\n node_limit : int, optional\n **(D)** If provided, the solve will begin to\n terminate once this many nodes have been served\n from the dispatcher queue, and the\n termination_condition flag on the results object\n will be set to \"node_limit\". (default: None)\n time_limit : float, optional\n **(D)** If provided, the solve will begin to\n terminate once this amount of time has passed,\n and the termination_condition flag on the\n results object will be set to \"time_limit\". Note\n that the solve may run for an arbitrarily longer\n amount of time, depending how long worker\n processes spend completing their final\n task. (default: None)\n initialize_queue : :class:`pybnb.dispatcher.DispatcherQueueData`, optional\n **(D)** Initializes the dispatcher queue with\n that remaining from a previous solve (obtained\n by calling :func:`Solver.save_dispatcher_queue`\n after the solve). If left as None, the queue\n will be initialized with a single root node\n created by calling :func:`problem.save_state\n `.\n (default: None)\n queue_strategy : :class:`QueueStrategy `\n **(D)** Sets the strategy for prioritizing nodes\n in the central dispatcher queue. See the\n :class:`QueueStrategy\n ` enum for the list\n of acceptable values. This keyword can be\n assigned one of the enumeration attributes or an\n equivalent string name. (default: \"bound\")\n log_interval_seconds : float, optional\n **(D)** The approximate time (in seconds)\n between solver log updates. More time may pass\n between log updates if no updates have been\n received from worker processes, and less time\n may pass if a new incumbent objective is\n found. (default: 1.0)\n log_new_incumbent : bool\n **(D)** Controls whether updates to the best\n objective are logged immediately (overriding the\n log interval). Setting this to false can be\n useful when frequent updates to the incumbent\n are expected and the additional logging slows\n down the dispatcher. (default: True)\n log : logging.Logger, optional\n **(D)** A log object where solver output should\n be sent. The default value causes all output to\n be streamed to the console. Setting to None\n disables all output.\n\n Returns\n -------\n results : :class:`SolverResults`\n An object storing information about the solve.\n \"\"\"\n self._reset_local_solve_stats()\n self._solve_start = self._time()\n\n assert (initialize_queue is None) or \\\n (self.is_dispatcher)\n\n if best_objective is None:\n best_objective = problem.infeasible_objective()\n\n results = SolverResults()\n convergence_checker = ConvergenceChecker(\n problem.sense(),\n absolute_gap=absolute_gap,\n relative_gap=relative_gap,\n scale_function=scale_function,\n queue_tolerance=queue_tolerance,\n branch_tolerance=branch_tolerance,\n comparison_tolerance=comparison_tolerance,\n objective_stop=objective_stop,\n bound_stop=bound_stop)\n problem.notify_solve_begins(self.comm,\n self.worker_comm,\n convergence_checker)\n root = Node()\n root.queue_priority = 0\n problem.save_state(root)\n try:\n if self.is_dispatcher:\n if initialize_queue is None:\n root.bound = problem.unbounded_objective()\n root.objective = best_objective\n assert root.tree_id is None\n Node._insert_tree_id(root._data, 0)\n initialize_queue = DispatcherQueueData(\n nodes=[Node(data_=root._data.copy())],\n next_tree_id=1)\n if log is _notset:\n log = get_simple_logger()\n if type(queue_strategy) is \\\n QueueStrategy:\n queue_strategy = \\\n queue_strategy.value\n self._disp.initialize(\n best_objective,\n initialize_queue,\n queue_strategy,\n convergence_checker,\n node_limit,\n time_limit,\n log,\n log_interval_seconds,\n log_new_incumbent)\n if not self.is_worker:\n def handler(signum, frame): #pragma:nocover\n self._disp.log_warning(\n \"Solve interrupted by user. \"\n \"Waiting for current worker \"\n \"jobs to complete before \"\n \"terminating the solve.\")\n self._disp.termination_condition = \\\n TerminationCondition.interrupted\n with MPI_InterruptHandler(handler):\n tmp = self._disp.serve()\n else:\n def handler(signum, frame): #pragma:nocover\n if self.is_dispatcher:\n self._disp.log_warning(\n \"Solve interrupted by user. \"\n \"Waiting for current worker \"\n \"jobs to complete before \"\n \"terminating the solve.\")\n self._disp.termination_condition = \\\n TerminationCondition.interrupted\n with MPI_InterruptHandler(handler):\n tmp = self._solve(problem,\n best_objective,\n disable_objective_call,\n convergence_checker,\n results)\n if not self.is_dispatcher:\n self._disp.clear_cache()\n (results.objective,\n results.bound,\n results.termination_condition,\n self._global_solve_info) = tmp\n results.nodes = self._global_solve_info.explored_nodes_count\n self._fill_results(results, convergence_checker)\n except: #pragma:nocover\n sys.stderr.write(\"Exception caught: \"+str(sys.exc_info()[1])+\"\\n\")\n sys.stderr.write(\"Attempting to shut down, but this may hang.\\n\")\n sys.stderr.flush()\n raise\n finally:\n problem.load_state(root)\n self._wall_time = self._time() - self._solve_start\n results.wall_time = self._wall_time\n\n assert results.solution_status in SolutionStatus,\\\n str(results)\n assert results.termination_condition in TerminationCondition,\\\n str(results)\n\n problem.notify_solve_finished(self.comm,\n self.worker_comm,\n results)\n if self.is_dispatcher and \\\n (log is not None) and \\\n (not log.disabled):\n self._disp.log_info(\"\")\n if results.solution_status in (\"feasible\", \"optimal\"):\n agap = convergence_checker.compute_absolute_gap(\n results.bound,\n results.objective)\n rgap = convergence_checker.compute_relative_gap(\n results.bound,\n results.objective)\n if results.solution_status == \"feasible\":\n self._disp.log_info(\"Feasible solution found\")\n else:\n if (convergence_checker.absolute_gap is not None) and \\\n agap <= convergence_checker.absolute_gap:\n self._disp.log_info(\"Absolute optimality tolerance met\")\n if (convergence_checker.relative_gap is not None) and \\\n rgap <= convergence_checker.relative_gap:\n self._disp.log_info(\"Relative optimality tolerance met\")\n assert results.solution_status == \"optimal\"\n self._disp.log_info(\"Optimal solution found!\")\n elif results.solution_status == \"infeasible\":\n self._disp.log_info(\"Problem is infeasible\")\n elif results.solution_status == \"unbounded\":\n self._disp.log_info(\"Problem is unbounded\")\n elif results.solution_status == \"invalid\": #pragma:nocover\n self._disp.log_info(\"Problem is invalid\")\n else:\n assert results.solution_status == \"unknown\"\n self._disp.log_info(\"Status unknown\")\n self._disp.log_info(\"\")\n self._disp.log_info(str(results))\n\n return results\n\ndef summarize_worker_statistics(stats, stream=sys.stdout):\n \"\"\"Writes a summary of workers statistics to an\n output stream.\n\n Parameters\n ----------\n stats : dict\n A dictionary of worker statistics returned from\n a call to :func:`collect_worker_statistics`.\n stream : file-like object, or string, optional\n A file-like object or a filename where results\n should be written to. (default: ``sys.stdout``)\n \"\"\"\n import numpy\n wall_time = numpy.array(stats['wall_time'],\n dtype=float)\n queue_time = numpy.array(stats['queue_time'],\n dtype=float)\n queue_count = numpy.array(stats['queue_call_count'],\n dtype=int)\n objective_time = numpy.array(stats['objective_time'],\n dtype=float)\n objective_count = numpy.array(stats['objective_call_count'],\n dtype=int)\n bound_time = numpy.array(stats['bound_time'],\n dtype=float)\n bound_count = numpy.array(stats['bound_call_count'],\n dtype=int)\n branch_time = numpy.array(stats['branch_time'],\n dtype=float)\n branch_count = numpy.array(stats['branch_call_count'],\n dtype=int)\n load_state_time = numpy.array(stats['load_state_time'],\n dtype=float)\n load_state_count = numpy.array(stats['load_state_call_count'],\n dtype=int)\n explored_nodes_count = numpy.array(stats['explored_nodes_count'],\n dtype=int)\n work_time = wall_time - queue_time\n\n with as_stream(stream) as stream:\n stream.write(\"Number of Workers: %6d\\n\"\n % (len(wall_time)))\n div = max(1.0,numpy.mean(explored_nodes_count))\n numerator = numpy.max(explored_nodes_count) - \\\n numpy.min(explored_nodes_count)\n if explored_nodes_count.sum() == 0:\n stream.write(\"Load Imbalance: %6.2f%%\\n\"\n % (0.0))\n else:\n stream.write(\"Load Imbalance: %6.2f%%\\n\"\n % (numerator/div*100.0))\n stream.write(\" - min: %d\\n\" % (numpy.min(explored_nodes_count)))\n stream.write(\" - max: %d\\n\" % (numpy.max(explored_nodes_count)))\n stream.write(\"Average Worker Timing:\\n\")\n queue_count_str = \"%d\" % queue_count.sum()\n tmp = \"%\"+str(len(queue_count_str))+\"d\"\n bound_count_str = tmp % bound_count.sum()\n objective_count_str = tmp % objective_count.sum()\n branch_count_str = tmp % branch_count.sum()\n load_state_count_str = tmp % load_state_count.sum()\n div1 = numpy.copy(wall_time)\n div1[div1 == 0] = 1\n div2 = numpy.copy(queue_count)\n div2[div2 == 0] = 1\n stream.write(\" - queue: %6.2f%% [avg time: %8s, count: %s]\\n\"\n % (numpy.mean(queue_time/div1)*100.0,\n time_format(numpy.mean(queue_time/div2),\n align_unit=True),\n queue_count_str))\n div2 = numpy.copy(load_state_count)\n div2[div2==0] = 1\n stream.write(\" - load_state:%6.2f%% [avg time: %8s, count: %s]\\n\"\n % (numpy.mean((load_state_time/div1))*100.0,\n time_format(numpy.mean(load_state_time/div2),\n align_unit=True),\n load_state_count_str))\n div2 = numpy.copy(bound_count)\n div2[div2==0] = 1\n stream.write(\" - bound: %6.2f%% [avg time: %8s, count: %s]\\n\"\n % (numpy.mean((bound_time/div1))*100.0,\n time_format(numpy.mean(bound_time/div2),\n align_unit=True),\n bound_count_str))\n div2 = numpy.copy(objective_count)\n div2[div2==0] = 1\n stream.write(\" - objective: %6.2f%% [avg time: %8s, count: %s]\\n\"\n % (numpy.mean((objective_time/div1))*100.0,\n time_format(numpy.mean(objective_time/div2),\n align_unit=True),\n objective_count_str))\n div2 = numpy.copy(branch_count)\n div2[div2==0] = 1\n stream.write(\" - branch: %6.2f%% [avg time: %8s, count: %s]\\n\"\n % (numpy.mean((branch_time/div1))*100.0,\n time_format(numpy.mean(branch_time/div2),\n align_unit=True),\n branch_count_str))\n other_time = work_time - objective_time - bound_time - branch_time - load_state_time\n div2 = numpy.copy(queue_count)\n div2[div2 == 0] = 1\n stream.write(\" - other: %6.2f%% [avg time: %8s, count: %s]\\n\"\n % (numpy.mean(other_time/div1)*100.0,\n time_format(numpy.mean(other_time/div2),\n align_unit=True),\n queue_count_str))\n\n\ndef solve(problem,\n comm=_notset,\n dispatcher_rank=0,\n log_filename=None,\n results_filename=None,\n **kwds):\n \"\"\"Solves a branch-and-bound problem and returns the\n solution.\n\n Note\n ----\n This function also collects and summarizes runtime\n workload statistics, which may introduce additional\n overhead. This overhead can be avoided by directly\n instantiating a :class:`Solver` object and\n calling the :func:`Solver.solve` method.\n\n Parameters\n ----------\n problem : :class:`pybnb.Problem `\n An object that defines a branch-and-bound problem\n comm : ``mpi4py.MPI.Comm``, optional\n The MPI communicator to use. If unset, the\n mpi4py.MPI.COMM_WORLD communicator will be\n used. Setting this keyword to None will disable the\n use of MPI and avoid an attempted import of\n mpi4py.MPI (which avoids triggering a call to\n `MPI_Init()`).\n dispatcher_rank : int, optional\n The process with this rank will be designated the\n dispatcher process. If MPI functionality is disabled\n (by setting comm=None, or when comm.size==1), this\n keyword must be left at 0. (default: 0)\n log_filename : string, optional\n A filename where solver output should be sent in\n addition to console. This keyword will be ignored if\n the `log` keyword is set. (default: None)\n results_filename : string, optional\n Saves the solver results into a YAML-formatted file\n with the given name. (default: None)\n **kwds\n Additional keywords to be passed to\n :func:`Solver.solve`. See that method for additional\n keyword documentation.\n\n Returns\n -------\n results : :class:`SolverResults`\n An object storing information about the solve.\n \"\"\"\n\n opt = Solver(comm=comm,\n dispatcher_rank=dispatcher_rank)\n\n if (opt.is_dispatcher) and \\\n (\"log\" not in kwds) and \\\n (log_filename is not None):\n kwds[\"log\"] = get_simple_logger(\n filename=log_filename)\n\n results = opt.solve(problem, **kwds)\n\n stats = opt.collect_worker_statistics()\n if opt.is_dispatcher:\n tmp = six.StringIO()\n summarize_worker_statistics(stats, stream=tmp)\n opt._disp.log_info(tmp.getvalue())\n\n if opt.is_dispatcher and (results_filename is not None):\n results.write(results_filename)\n\n return results\n","sub_path":"src/pybnb/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":46725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"146836740","text":"#!/usr/bin/env python\n# coding=utf-8\nfrom __future__ import unicode_literals, absolute_import, print_function, division\n\n# sopel imports\nimport sopel.module\n\n# imports for system and OS access, directories\nimport os\nimport sys\n\n# imports based on THIS file\nmoduledir = os.path.dirname(__file__)\nshareddir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))\nsys.path.append(shareddir)\nfrom BotShared import *\n\n\n\n\n\n\ncomdict = {\n \"author\": \"deathbybandaid\",\n \"contributors\": [],\n \"description\": \"\",\n 'privs': ['admin', 'OP'],\n \"example\": \"\",\n \"exampleresponse\": \"\",\n }\n\n\n\"\"\"\nChange Directory\n\"\"\"\n\n\n@module.nickname_commands('cd')\n@module.thread(True)\ndef bot_command_hub(bot, trigger):\n\n botcom = botcom_nick(bot, trigger)\n\n # Bots block\n if bot_check_inlist(bot, botcom.instigator, [bot.nick]):\n return\n\n # does not apply to bots\n if \"altbots\" in bot.memory:\n if bot_check_inlist(bot, botcom.instigator, bot.memory[\"altbots\"].keys()):\n return\n\n if not bot_permissions_check(bot, botcom):\n return osd(bot, botcom.instigator, 'notice', \"I was unable to process this Bot Nick command due to privilege issues.\")\n\n validfolderoptions = ['..', 'reset']\n botcom.directory = get_nick_value(bot, botcom.instigator, 'temp', 'unsorted', 'current_admin_dir') or bot.memory[\"botdict\"][\"tempvals\"][\"bot_info\"][str(bot.nick)][\"directory_main\"]\n botcom = bot_list_directory(bot, botcom)\n\n for filename, filefoldertype in zip(botcom.directory_listing, botcom.filefoldertype):\n if filefoldertype == 'folder':\n validfolderoptions.append(filename)\n\n movepath = spicemanip.main(botcom.triggerargsarray, 0)\n if movepath not in validfolderoptions:\n if movepath in botcom.directory_listing and movepath not in validfolderoptions:\n osd(bot, botcom.channel_current, 'say', \"You can't Change Directory into a File!\")\n else:\n osd(bot, botcom.channel_current, 'say', \"Invalid Folder Path\")\n return\n\n if movepath == \"..\":\n movepath = os.path.dirname(botcom.directory)\n elif movepath == 'reset':\n movepath = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))\n else:\n movepath = os.path.join(botcom.directory, str(movepath+\"/\"))\n\n set_nick_value(bot, botcom.instigator, 'temp', 'unsorted', 'current_admin_dir', str(movepath))\n\n osd(bot, botcom.channel_current, 'say', \"Directory Changed to : \" + str(movepath))\n","sub_path":"Modules/BotCore/Nick_Commands/BotNick_CD.py","file_name":"BotNick_CD.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"17234993","text":"# Copyright 2017 The 'Scalable Private Learning with PATE' 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\n\"\"\"Plots graphs for the slide deck.\n\nA script in support of the PATE2 paper. The input is a file containing a numpy\narray of votes, one query per row, one class per column. Ex:\n 43, 1821, ..., 3\n 31, 16, ..., 0\n ...\n 0, 86, ..., 438\nThe output graphs are visualized using the TkAgg backend.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport os\nimport sys\n\nsys.path.append('..') # Main modules reside in the parent directory.\n\nfrom absl import app\nfrom absl import flags\nimport matplotlib\n\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top\nimport numpy as np\nimport core as pate\nimport random\n\nplt.style.use('ggplot')\n\nFLAGS = flags.FLAGS\nflags.DEFINE_string('counts_file', None, 'Counts file.')\nflags.DEFINE_string('figures_dir', '', 'Path where figures are written to.')\nflags.DEFINE_boolean('transparent', False, 'Set background to transparent.')\n\nflags.mark_flag_as_required('counts_file')\n\n\ndef setup_plot():\n fig, ax = plt.subplots()\n fig.set_figheight(4.5)\n fig.set_figwidth(4.7)\n\n if FLAGS.transparent:\n fig.patch.set_alpha(0)\n\n return fig, ax\n\n\ndef plot_rdp_curve_per_example(votes, sigmas):\n orders = np.linspace(1., 100., endpoint=True, num=1000)\n orders[0] = 1.001\n fig, ax = setup_plot()\n\n for i in range(votes.shape[0]):\n for sigma in sigmas:\n logq = pate.compute_logq_gaussian(votes[i,], sigma)\n rdp = pate.rdp_gaussian(logq, sigma, orders)\n ax.plot(\n orders,\n rdp,\n alpha=1.,\n label=r'Data-dependent bound, $\\sigma$={}'.format(int(sigma)),\n linewidth=5)\n\n for sigma in sigmas:\n ax.plot(\n orders,\n pate.rdp_data_independent_gaussian(sigma, orders),\n alpha=.3,\n label=r'Data-independent bound, $\\sigma$={}'.format(int(sigma)),\n linewidth=10)\n\n plt.xlim(xmin=1, xmax=100)\n plt.ylim(ymin=0)\n plt.xticks([1, 20, 40, 60, 80, 100])\n plt.yticks([0, .0025, .005, .0075, .01])\n plt.xlabel(r'Order $\\alpha$', fontsize=16)\n plt.ylabel(r'RDP value $\\varepsilon$ at $\\alpha$', fontsize=16)\n ax.tick_params(labelsize=14)\n\n plt.legend(loc=0, fontsize=13)\n plt.show()\n\n\ndef plot_rdp_of_sigma(v, order):\n sigmas = np.linspace(1., 1000., endpoint=True, num=1000)\n fig, ax = setup_plot()\n\n y = np.zeros(len(sigmas))\n\n for i, sigma in enumerate(sigmas):\n logq = pate.compute_logq_gaussian(v, sigma)\n y[i] = pate.rdp_gaussian(logq, sigma, order)\n\n ax.plot(sigmas, y, alpha=.8, linewidth=5)\n\n plt.xlim(xmin=1, xmax=1000)\n plt.ylim(ymin=0)\n # plt.yticks([0, .0004, .0008, .0012])\n ax.tick_params(labelleft='off')\n plt.xlabel(r'Noise $\\sigma$', fontsize=16)\n plt.ylabel(r'RDP at order $\\alpha={}$'.format(order), fontsize=16)\n ax.tick_params(labelsize=14)\n\n # plt.legend(loc=0, fontsize=13)\n plt.show()\n\n\ndef compute_rdp_curve(votes, threshold, sigma1, sigma2, orders,\n target_answered):\n rdp_cum = np.zeros(len(orders))\n answered = 0\n for i, v in enumerate(votes):\n v = sorted(v, reverse=True)\n q_step1 = math.exp(pate.compute_logpr_answered(threshold, sigma1, v))\n logq_step2 = pate.compute_logq_gaussian(v, sigma2)\n rdp = pate.rdp_gaussian(logq_step2, sigma2, orders)\n rdp_cum += q_step1 * rdp\n\n answered += q_step1\n if answered >= target_answered:\n print('Processed {} queries to answer {}.'.format(i, target_answered))\n return rdp_cum\n\n assert False, 'Never reached {} answered queries.'.format(target_answered)\n\n\ndef plot_rdp_total(votes, sigmas):\n orders = np.linspace(1., 100., endpoint=True, num=100)\n orders[0] = 1.1\n\n fig, ax = setup_plot()\n\n target_answered = 2000\n\n for sigma in sigmas:\n rdp = compute_rdp_curve(votes, 5000, 1000, sigma, orders, target_answered)\n ax.plot(\n orders,\n rdp,\n alpha=.8,\n label=r'Data-dependent bound, $\\sigma$={}'.format(int(sigma)),\n linewidth=5)\n\n # for sigma in sigmas:\n # ax.plot(\n # orders,\n # target_answered * pate.rdp_data_independent_gaussian(sigma, orders),\n # alpha=.3,\n # label=r'Data-independent bound, $\\sigma$={}'.format(int(sigma)),\n # linewidth=10)\n\n plt.xlim(xmin=1, xmax=100)\n plt.ylim(ymin=0)\n plt.xticks([1, 20, 40, 60, 80, 100])\n plt.yticks([0, .0005, .001, .0015, .002])\n\n plt.xlabel(r'Order $\\alpha$', fontsize=16)\n plt.ylabel(r'RDP value $\\varepsilon$ at $\\alpha$', fontsize=16)\n ax.tick_params(labelsize=14)\n\n plt.legend(loc=0, fontsize=13)\n plt.show()\n\n\ndef plot_data_ind_curve():\n fig, ax = setup_plot()\n\n orders = np.linspace(1., 10., endpoint=True, num=1000)\n orders[0] = 1.01\n\n ax.plot(\n orders,\n pate.rdp_data_independent_gaussian(1., orders),\n alpha=.5,\n color='gray',\n linewidth=10)\n\n # plt.yticks([])\n plt.xlim(xmin=1, xmax=10)\n plt.ylim(ymin=0)\n plt.xticks([1, 3, 5, 7, 9])\n ax.tick_params(labelsize=14)\n plt.show()\n\n\ndef plot_two_data_ind_curves():\n orders = np.linspace(1., 100., endpoint=True, num=1000)\n orders[0] = 1.001\n\n fig, ax = setup_plot()\n\n for sigma in [100, 150]:\n ax.plot(\n orders,\n pate.rdp_data_independent_gaussian(sigma, orders),\n alpha=.3,\n label=r'Data-independent bound, $\\sigma$={}'.format(int(sigma)),\n linewidth=10)\n\n plt.xlim(xmin=1, xmax=100)\n plt.ylim(ymin=0)\n plt.xticks([1, 20, 40, 60, 80, 100])\n plt.yticks([0, .0025, .005, .0075, .01])\n plt.xlabel(r'Order $\\alpha$', fontsize=16)\n plt.ylabel(r'RDP value $\\varepsilon$ at $\\alpha$', fontsize=16)\n ax.tick_params(labelsize=14)\n\n plt.legend(loc=0, fontsize=13)\n plt.show()\n\n\ndef scatter_plot(votes, threshold, sigma1, sigma2, order):\n fig, ax = setup_plot()\n x = []\n y = []\n for i, v in enumerate(votes):\n if threshold is not None and sigma1 is not None:\n q_step1 = math.exp(pate.compute_logpr_answered(threshold, sigma1, v))\n else:\n q_step1 = 1.\n if random.random() < q_step1:\n logq_step2 = pate.compute_logq_gaussian(v, sigma2)\n x.append(max(v))\n y.append(pate.rdp_gaussian(logq_step2, sigma2, order))\n\n print('Selected {} queries.'.format(len(x)))\n # Plot the data-independent curve:\n # data_ind = pate.rdp_data_independent_gaussian(sigma, order)\n # plt.plot([0, 5000], [data_ind, data_ind], color='tab:blue', linestyle='-', linewidth=2)\n ax.set_yscale('log')\n plt.xlim(xmin=0, xmax=5000)\n plt.ylim(ymin=1e-300, ymax=1)\n plt.yticks([1, 1e-100, 1e-200, 1e-300])\n plt.scatter(x, y, s=1, alpha=0.5)\n plt.ylabel(r'RDP at $\\alpha={}$'.format(order), fontsize=16)\n plt.xlabel(r'max count', fontsize=16)\n ax.tick_params(labelsize=14)\n plt.show()\n\n\ndef main(argv):\n del argv # Unused.\n fin_name = os.path.expanduser(FLAGS.counts_file)\n print('Reading raw votes from ' + fin_name)\n sys.stdout.flush()\n\n plot_data_ind_curve()\n plot_two_data_ind_curves()\n\n v1 = [2550, 2200, 250] # based on votes[2,]\n # v2 = [2600, 2200, 200] # based on votes[381,]\n plot_rdp_curve_per_example(np.array([v1]), (100., 150.))\n\n plot_rdp_of_sigma(np.array(v1), 20.)\n\n votes = np.load(fin_name)\n\n plot_rdp_total(votes[:12000, ], (100., 150.))\n scatter_plot(votes[:6000, ], None, None, 100, 20) # w/o thresholding\n scatter_plot(votes[:6000, ], 3500, 1500, 100, 20) # with thresholding\n\n\nif __name__ == '__main__':\n app.run(main)\n","sub_path":"research/pate_2018/ICLR2018/plots_for_slides.py","file_name":"plots_for_slides.py","file_ext":"py","file_size_in_byte":8028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"635790962","text":"from pandas import read_csv\nfrom pandas.tools.plotting import scatter_matrix\nfrom matplotlib import pyplot\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\n\nnames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']\ndataset = read_csv('iris.data', names=names)\nprint(dataset.shape)\nprint(dataset.describe())\nprint(dataset.groupby('class').size())\n\ndataset.plot(kind='box', subplots=True,\n\t\t\tlayout=(2,2),\n\t\t\tsharex=False, sharey=False)\n\npyplot.show()\ndataset.hist()\npyplot.show()\n\narray = dataset.values\nx = array[:, 0:4]\ny = array[:, 4]\n\nvalidation_size = 0.20\nx_train, x_validation, y_train, y_validation = train_test_split(x, y,\n\ttest_size=validation_size, random_state=7)\n\nmodels = []\nmodels.append(('LR', LogisticRegression()))\nmodels.append(('LDA', LinearDiscriminantAnalysis()))\nmodels.append(('KNN', KNeighborsClassifier()))\nmodels.append(('CART', DecisionTreeClassifier()))\nmodels.append(('NB', GaussianNB()))\nmodels.append(('SVM', SVC()))\n\nresults = []\nnames = []\nfor name, model in models:\n\tkfold = KFold(n_splits=10, random_state=7)\n\tcv_results = cross_val_score(model, x_train, y_train, cv=kfold)\n\tresults.append(cv_results)\n\tnames.append(name)\n\tprint(name, ':', cv_results.mean(), cv_results.std())\n\nfig = pyplot.figure()\nfig.suptitle('Algorithm Comparison')\nax = fig.add_subplot(111)\npyplot.boxplot(results)\nax.set_xticklabels(names)\npyplot.show()\n\nknn = KNeighborsClassifier()\nknn.fit(x_train, y_train)\npredictions = knn.predict(x_validation)\nprint(accuracy_score(y_validation, predictions))\nprint(confusion_matrix(y_validation, predictions))\nprint(classification_report(y_validation, predictions))\n\n","sub_path":"ML-Workshop/final_project.py","file_name":"final_project.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"2235577","text":"from odoo import fields, models, api, exceptions\nfrom datetime import datetime, timedelta\nimport pytz\nimport logging\n_logger = logging.getLogger(__name__)\n\n\ndef convert_string_to_datetime(datetimestring):\n # tests for appropriate format and converts to datetime\n timetest = datetimestring.split(' ')\n dash = True\n firsttest = timetest[0].split('-')\n if len(firsttest) == 1:\n # deljeni kosom crtom\n dash = False\n if len(timetest) > 1:\n secondtest = timetest[1].split(':')\n if len(secondtest) > 2:\n if dash:\n res = datetime.strptime(datetimestring, \"%Y-%m-%d %H:%M:%S\")\n else:\n res = datetime.strptime(datetimestring, \"%Y/%m/%d %H:%M:%S\")\n else:\n if dash:\n res = datetime.strptime(datetimestring, \"%Y-%m-%d %H:%M\")\n else:\n res = datetime.strptime(datetimestring, \"%Y/%m/%d %H:%M\")\n else:\n if dash:\n res = datetime.strptime(datetimestring, \"%Y-%m-%d\")\n else:\n res = datetime.strptime(datetimestring, \"%Y/%m/%d\")\n return res\n\nclass ContractTrafficAddContractWizard(models.TransientModel):\n _name = \"contract.traffic.add.contract.wizard\"\n\n dayfrom = fields.Datetime(readonly = True)\n dayto = fields.Datetime(readonly = True)\n contract_id = fields.Many2one('contract.detail', 'Tourism contract', \n domain=\"[('rel_vreme_pocetka', '>=', dayfrom), ('rel_vreme_pocetka', '<=',dayto ), ('state','in',('pending','odobren','open'))]\")\n contract_name = fields.Char('Name', related='contract_id.name')\n relation_name = fields.Char('Name', related='contract_id.rel_na_relaciji', readonly=True)\n pre_start_station = fields.Char('Pre start station', related='contract_id.rel_mesto_pocetka')\n pre_start_time = fields.Datetime('Pre start time', related='contract_id.rel_vreme_pocetka')\n start_station = fields.Char('Start station', related='contract_id.rel_mesto_postavljanja')\n start_time = fields.Datetime('Start time', related='contract_id.rel_vreme_postavljanja')\n end_station = fields.Char('Start station', related='contract_id.rel_mesto_zavrsetka')\n end_time = fields.Datetime('Start time', related='contract_id.rel_vreme_zavrsetka')\n waypoints_plan = fields.One2many('contract.turistic_traffic.departure.exactpoint', 'Waypoints',\n related='contract_id.plan_voznje')\n rel_broj_vozila = fields.Integer('Broj vozila', related='contract_id.rel_broj_vozila')\n\n @api.model\n def default_get(self, fields):\n rec = super(ContractTrafficAddContractWizard, self).default_get(fields)\n context = dict(self._context or {})\n day_id = context.get('active_id')\n dday = self.env['traffic.departure.day'].search([['id','=',day_id]])\n day = dday.date\n localtz = pytz.timezone('Europe/Belgrade')\n dayfrom = convert_string_to_datetime(day + \" 00:00:00\")\n dayto = convert_string_to_datetime(day + \" 23:59:59\")\n daylfrom = localtz.localize(dayfrom).astimezone(pytz.utc)\n daylto = localtz.localize(dayto).astimezone(pytz.utc)\n rec.update({\n 'dayfrom': datetime.strftime(daylfrom, '%Y-%m-%d %H:%M:%S'),\n 'dayto': datetime.strftime(daylto, '%Y-%m-%d %H:%M:%S'),\n })\n return rec\n\n @api.multi\n def action_create_block_from_contract(self):\n self.ensure_one()\n points = []\n start_datetime = datetime.strptime(self.contract_id.rel_vreme_pocetka, \"%Y-%m-%d %H:%M:%S\")\n for point in self.waypoints_plan:\n data = {}\n data['name'] = point.name\n data['platform'] = point.platform\n data['distance'] = point.distance\n data['cash_handover'] = point.cash_handover\n data['time_offset'] = point.time_offset\n data['wait_time'] = point.wait_time\n deltamin = point.relative_departure_time\n gotted = start_datetime + timedelta(minutes=deltamin)\n\n data['expected_datetime'] = gotted\n points.append([0, 0, data])\n blockdata = {}\n blockdata['description'] = self.contract_name + ' - ' + self.relation_name\n blockdata['block_type'] = 'tourism'\n blockdata['operating_unit_id'] = self._context['operating_unit_id']\n blockdata['exactpoint_ids'] = points\n blockdata['day'] = self._context['day_id']\n num_of_vehicles = self.rel_broj_vozila\n if num_of_vehicles > 1:\n strnum = str(num_of_vehicles)\n for i in xrange(1, num_of_vehicles + 1):\n blockdata['description'] = self.contract_name + ' - ' + self.relation_name + ' ' + str(i) + '/' + strnum\n resultblock = self.env['traffic.block.pattern.in.day'].with_context(mail_create_nosubscribe=True).create(blockdata)\n else:\n blockdata['description'] = self.contract_name + ' - ' + self.relation_name\n resultblock = self.env['traffic.block.pattern.in.day'].with_context(mail_create_nosubscribe=True).create(blockdata)\n\n\nclass ContractTrafficDepartureDay(models.Model):\n _inherit = 'traffic.departure.day'\n\n @api.multi\n def action_get_tourism_data(self):\n self.ensure_one()\n view = self.env.ref('contract_nix_turizam.add_contract_wizard', False)\n # contract_id = self.env['contract.traffic.add.contract.wizard'].create({'contract_id'})\n ctx = self.with_context(day_date=self.date, day_id=self.id, operating_unit_id=self.operating_unit_id.id)._context\n # ctx['day_date'] = self.date\n # ctx['day_id'] = self.id\n # ctx['operating_unit_id'] = self.operating_unit_id.id\n v = view.id\n return {\n 'name': \"Get data from contract\",\n 'type': 'ir.actions.act_window',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'contract.traffic.add.contract.wizard',\n # 'res_id': id,\n # 'domain': [('id', 'in', [id])],\n 'view_id': v,\n 'target': 'new',\n 'context': ctx,\n }\n","sub_path":"contract_nix_turizam/models/contract_traffic.py","file_name":"contract_traffic.py","file_ext":"py","file_size_in_byte":6135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"571024752","text":"from db import session\nfrom utils.util import uid\nfrom models.states_model import StatesModel\nfrom models.cities_model import CitiesModel\n\nfrom mappers.states_mapper import StatesMapper\nfrom mappers.cities_mapper import CitiesMapper\n\nimport datetime\n\nclass CitiesService:\n\n session_info = None\n\n def mapping(self, model, view):\n data = session.query(StatesModel).filter_by(stateName=view['stateName']).first()\n if data is not None:\n model.states = session.query(StatesModel).filter_by(id=data.id).first()\n else:\n model.states = StatesModel()\n model.states.id = uid()\n model.states.stateName = view['stateName']\n model.states.stateCode = view['stateCode']\n model.states.createdOn = datetime.datetime.now()\n model.states.updatedOn = datetime.datetime.now()\n if model.id is None:\n model.id = uid()\n model.stateId = model.states.id\n model.cityName = view['cityName']\n model.zipcode = view['zipcode']\n model.createdOn = datetime.datetime.now()\n\n model.updatedOn = datetime.datetime.now()\n CitiesMapper(model, view).model_mapping()\n StatesMapper(model.states, view.get('states')).model_mapping()\n\n\n def is_validate(self, model, is_new):\n\n query = session.query(CitiesModel) \\\n .filter((CitiesModel.cityName == model.cityName))\n data_list = query.all()\n if data_list:\n if is_new:\n print(\"true\")\n return False\n else:\n for item in data_list:\n print(\"item\", item)\n if item.id != model.id:\n print(\"item.id\", item.id)\n print(\"model.id\", model.id)\n return False\n return True\n def model(self, _id):\n if _id is not None:\n return session.query(CitiesModel).filter_by(id=_id).first()\n else:\n data = session.query(CitiesModel).all()\n return data\n\n def save(self, req_data):\n\n cities = None\n _id = req_data.get('id')\n if _id is not None:\n cities = self.model(_id)\n if cities is None:\n print(cities)\n cities = CitiesModel()\n print(cities)\n\n self.mapping(cities, req_data)\n if self.is_validate(cities, False if _id else True):\n session.add(cities)\n session.commit()\n return {'message': 'Saved Successfully', 'id': cities.id}\n else:\n raise Exception('Record already exists')\n\n def search(self, req_data):\n query = session.query(CitiesModel)\n if req_data and req_data.get('stateName') is not None:\n query = query.filter(CitiesModel.cityName.like('%'+req_data['cityName']+'%'))\n data_list = query.limit(9999).all()\n return data_list\n\n def delete(self, id):\n city = CitiesModel.query.get(id)\n session.delete(city)\n session.commit()\n return {'message': 'deleted Successfully', 'id': id}","sub_path":"src/services/cities_service.py","file_name":"cities_service.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"616984145","text":"import os\nimport PyPDF2 as pdf2\n\n\n# Step 1:\n# Find all PDF files\n# store the names in a list\npdfFiles = []\nfor filename in os.listdir('.'): # os.listdir() takes targets dir as arg\n if filename.endswith('.pdf'):\n pdfFiles.append(filename)\n\npdfFiles.sort(key = str.lower)\n\npdfWriter = pdf2.PdfFileWriter()\n\n\n# Loop through all the pdf files\nfor filename in pdfFiles:\n pdfFileObj = open(filename, 'rb')\n pdfReader = pdf2.PdfFileReader(pdfFileObj)\n\n\n# loop through all the pages except 1st\nfor pageNum in range(1, pdfReader.numPages):\n pageObj = pdfReader.getPage(pageNum)\n pdfWriter.addPage(pageObj)\n\n\n# save the resulting pdf to a file\npdfOutput = open('allminutes.pdf', 'wb')\npdfWriter.write(pdfOutput)\npdfOutput.close()\n\n","sub_path":"project/manipulating-docs/combine_pdfs.py","file_name":"combine_pdfs.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"474484273","text":"# Wade Polo 3/10/14\n# Starting out with Python pg. 154 #8\n# Software Sales\n# Determines the discount on large orders of software\n\ndef main():\n amountPurchased = float(input('Enter the number of software packages that you are purchasing: '))\n\n if amountPurchased >= 10 and amountPurchased <= 19:\n twentyDiscount(amountPurchased)\n elif amountPurchased >= 20 and amountPurchased <= 49:\n thirtyDiscount(amountPurchased)\n elif amountPurchased >= 50 and amountPurchased <= 99:\n fortyDiscount(amountPurchased)\n elif amountPurchased >= 100:\n fiftyDiscount(amountPurchased)\n else:\n print('You did not receive a discount on this purchase')\n print('The total of your purchase is ','$',format((amountPurchased * 99),'.2f'),sep='')\n\ndef twentyDiscount(amountPurchased):\n discount = ((amountPurchased * 99) * 0.2)\n print('You have received a 20% discount on this purchase for a savings of ','$',format(discount,'.2f'),sep='')\n print('The total of your purchase is ','$',format((amountPurchased * 99 - discount),'.2f'),sep='')\n\ndef thirtyDiscount(amountPurchased):\n discount = ((amountPurchased * 99) * 0.3)\n print('You have received a 30% discount on this purchase for a savings of ','$',format(discount,'.2f'),sep='')\n print('The total of your purchase is ','$',format((amountPurchased * 99 - discount),'.2f'),sep='')\n\ndef fortyDiscount(amountPurchased):\n discount = ((amountPurchased * 99) * 0.4)\n print('You have received a 40% discount on this purchase for a savings of ','$',format(discount,'.2f'),sep='')\n print('The total of your purchase is ','$',format((amountPurchased * 99 - discount),'.2f'),sep='')\n\ndef fiftyDiscount(amountPurchased):\n discount = ((amountPurchased * 99) * 0.5)\n print('You have received a 50% discount on this purchase for a savings of ','$',format(discount,'.2f'),sep='')\n print('The total of your purchase is ','$',format((amountPurchased * 99 - discount),'.2f'),sep='')\n\n\nmain()\n","sub_path":"SoftwareSales.py","file_name":"SoftwareSales.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"306049760","text":"def numStatistic(n):\n strNum=\" \".join(str(n)).split(\" \")\n dictNum = dict()\n for i in strNum:\n if i in dictNum:\n dictNum[i] +=1\n else:\n dictNum[i] = 1\n return dictNum\ngetNum = input()\nrealNum = eval(getNum)\ndoubleNum = realNum*2\norigindic = numStatistic(realNum)\ndoubledic = numStatistic(doubleNum)\nif origindic==doubledic:\n print(\"Yes\")\nelse:\n print(\"No\")\nprint(doubleNum)\n","sub_path":"daily_test/PTA_SelfTest_4.py","file_name":"PTA_SelfTest_4.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"252531355","text":"def find_max(arr):\n max = arr[0]\n for i in range(1, len(arr)):\n if arr[i] > max:\n max = arr[i]\n return max\n\ndef nums_sequence(sequence):\n # Input is sequence of nums ending by zero, zero isn't considered\n # The result is 4 sequences\n # 1 is all negative nums in sequince replaced by their abs\n # 2 all odd numbers replaced by max num\n # 3 all nums are substracted on 2\n # 4 all negatives replaced by zero\n result = [[], [], [], []]\n for i in range(0, len(sequence)-1):\n # First\n if sequence[i] < 0:\n result[0].append(abs(sequence[i]))\n else:\n result[0].append(sequence[i])\n #Second\n if sequence[i] % 2 == 0:\n result[1].append(find_max(sequence))\n else:\n result[1].append(sequence[i])\n #Third\n result[2].append(sequence[i] - 2)\n #Fourth\n if sequence[i] < 0:\n result[3].append(0)\n else:\n result[3].append(sequence[i])\n return result\n\nsequences = nums_sequence([1, 2, 3, 0])\nfor i in range(0, len(sequences)):\n print(str(i+1)+ \") \" + str(sequences[i]))\n","sub_path":"Задачи/nums_sequence.py","file_name":"nums_sequence.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"552142483","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom caffe2.python import (core, dyndep, workspace)\n\nfrom hypothesis import assume, given\nimport caffe2.python.hypothesis_test_util as hu\nimport hypothesis.strategies as st\nimport numpy as np\nfrom caffe2.proto import caffe2_pb2\n\n# Import our ops.\ndyndep.InitOpsLibrary('build/libbilinear_op.so')\n\nclass TestBilinear(hu.HypothesisTestCase):\n\n ''' Test GPU '''\n @given(B = st.integers(1, 24),\n C = st.integers(3, 128),\n H = st.integers(7,40),\n W = st.integers(7,40),\n **hu.gcs_gpu_only)\n def test_summarize_columns_gpu(self, B,C,H,W, gc, dc):\n self.run_it(B, C, H,W, gc,dc)\n\n ''' Test CPU '''\n @given(B = st.integers(1, 12),\n C = st.integers(3, 32),\n H = st.integers(10,40),\n W = st.integers(10,40),\n **hu.gcs_cpu_only)\n def test_bilinear_cpu(self, B,C,H,W, gc, dc):\n self.run_it(B, C, H,W, gc,dc)\n\n\n def run_it(self, B,C,H,W, gc,dc):\n def gold_standard(fa,fb):\n #outer = np.zeros([B,C,C,H*W], dtype=np.float32)\n fa = fa.reshape([B,C,H*W])\n fb = fb.reshape([B,C,H*W])\n #xx = xx.transpose(\n '''\n outer = np.zeros([B,H*W,C,C], dtype=np.float32)\n for b in range(B):\n for hw in range(H*W):\n outer[b,hw] = np.outer(fa[b,:,hw], fb[b,:,hw])\n #outer[b,hw] = np.ones([C,C])\n\n pooled = np.zeros([B, C,C])\n\n for b in range(B):\n for hw in range(H*W):\n pooled[b] += outer[b,hw] / (H*W)\n '''\n pooled = np.zeros([B,C,C])\n for b in range(B):\n for hw in range(H*W):\n pooled[b] += np.outer(fa[b,:,hw], fb[b,:,hw]) / (H*W)\n\n #return pooled.reshape([B,C*C]), outer.transpose(0,2,3,1)\n return pooled.reshape([B,C*C]),\n\n\n\n fa = np.random.randn(B,C,H,W).astype(np.float32)\n fb = np.random.randn(B,C,H,W).astype(np.float32)\n\n op = core.CreateOperator(\"BilinearPooling\",\n ['fa','fb'],\n #['bp_out', 'bp_saved_outer']\n ['bp_out']\n )\n\n self.assertReferenceChecks(\n device_option = gc,\n op = op,\n inputs = [fa,fb],\n reference=gold_standard\n )\n\n\nimport unittest\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"pysrc/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"139024760","text":"from typing import Any, Dict\n\nfrom girder_client import GirderClient\nfrom girder_worker.app import app\nfrom girder_worker.task import Task\nfrom girder_worker.utils import JobManager\n\nfrom dive_utils.constants import PublishedMarker\nfrom dive_utils.models import PublicDataSummary, SummaryItemSchema, Track\n\n\ndef summarize_annotations(\n datasetId: str, trackData: Dict[str, Any], summary: Dict[str, SummaryItemSchema]\n):\n for trackdict in trackData.values():\n track = Track(**trackdict)\n for name, _ in track.confidencePairs:\n if name in summary:\n summary[name].found_in = list(set(summary[name].found_in + [datasetId]))\n summary[name].total_tracks += 1\n summary[name].total_detections += len(track.features)\n else:\n summary[name] = SummaryItemSchema(\n value=name,\n total_tracks=1,\n total_detections=len(track.features),\n found_in=[datasetId],\n )\n\n\n@app.task(bind=True, acks_late=True)\ndef generate_summary(self: Task):\n manager: JobManager = self.job_manager\n gc: GirderClient = self.girder_client\n\n limit = 50\n offset = 0\n total = int(\n gc.get(\n 'viame/datasets',\n parameters={'limit': 1, PublishedMarker: True},\n jsonResp=False,\n ).headers['girder-total-count']\n )\n print(limit, offset, total)\n\n summary: Dict[str, SummaryItemSchema] = {}\n while offset < total:\n page = gc.get(\n 'viame/datasets',\n parameters={\n 'limit': limit,\n 'offset': offset,\n PublishedMarker: True,\n },\n )\n offset += limit\n for dataset in page:\n summarize_annotations(\n dataset['_id'],\n gc.get('viame_detection', parameters={'folderId': dataset['_id']}),\n summary,\n )\n print(summary)\n gc.post(\n 'viame_summary',\n data=PublicDataSummary(label_summary_items=list(summary.values())).json(),\n )\n","sub_path":"server/dive_tasks/summary.py","file_name":"summary.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"390882718","text":"from flask import request\nfrom flask_restful import Resource\nfrom .constants import *\nimport requests\nimport json\n\nfrom api_emulator.utils import create_path, create_object\n\nfrom api_emulator.redfish.Manager_api import ManagerCollectionAPI\n\nimport logging\n\nconfig = {}\n\nINTERNAL_ERROR = 500\n\n\n# EventListener does not have a Collection API\n\nclass EventProcessor(Resource):\n def __init__(self):\n logging.info('Event Listener init called')\n self.root = PATHS['Root']\n\n def fetchResource(self, obj_id, obj_root, host, port):\n\n resource_endpoint = f\"{host}:{port}/{obj_id}\"\n logging.info(f\"fetch: {resource_endpoint}\")\n response = requests.get(resource_endpoint)\n\n if response.status_code == 200:\n redfish_obj = response.json()\n\n obj_path = \"\".join(redfish_obj['@odata.id'].split('/redfish/v1/'))\n file_path = create_path(self.root, obj_path)\n create_object(redfish_obj, [], [], file_path)\n\n if 'Collection' in redfish_obj['@odata.type']:\n logging.info(f\"Found collection {redfish_obj['@odata.type']}\")\n EventProcessor.recursiveFetch(self, {'Members': redfish_obj['Members']}, obj_root, host, port)\n\n def recursiveFetch(self, obj_dict, obj_root, host, port):\n logging.info(f\"dict: {obj_dict}, obj_root:{obj_root}\")\n if obj_root is None or not obj_root or type(obj_dict) is not dict:\n return\n\n for key, value in obj_dict.items():\n logging.info(f\"checking k:{key}, v:{value}\")\n if key == 'Links': # Do not explore Links for now\n logging.info(f\"returning k:{key}, v:{value}\")\n continue\n elif key == '@odata.id' and obj_root in value and obj_root != value:\n logging.info(f\"fetch k:{key}, v:{value}\")\n EventProcessor.fetchResource(self, value, obj_root, host, port)\n\n if type(value) == dict:\n EventProcessor.recursiveFetch(self, value, obj_root, host, port)\n elif type(value) == list:\n for element in value:\n EventProcessor.recursiveFetch(self, element, obj_root, host, port)\n\n def ManagerCreated(self):\n logging.info(\"ManagerCreated method called\")\n config = json.loads(request.data)\n for event in config['Events']:\n host = event['MessageArgs'][0]\n port = event['MessageArgs'][1]\n response = requests.get(f\"{host}:{port}/{event['OriginOfCondition']['@odata.id']}\")\n if response.status_code == 200:\n redfish_obj = response.json()\n\n request.data = json.dumps(redfish_obj, indent=2).encode('utf-8')\n # Update ManagerCollection before fetching the resource subtree\n ManagerCollectionAPI.post(self)\n EventProcessor.recursiveFetch(self, redfish_obj, redfish_obj['@odata.id'], host, port)\n\n\ndef handle_events(res):\n config = json.loads(request.data)\n for event in config['Events']:\n ###\n # Each MessageId identifies the name of the handler that will be used to process the event\n # For instance an event json with MessageId as following will be handled by the function ConnectionCreated\n # {\n # ...\n # 'MessageId': 'Manager.1.0.ManagerCreated'\n # ...\n # }\n ###\n handlerfunc = getattr(EventProcessor, event['MessageId'].split(\".\")[-1])\n handlerfunc(res)\n\n\n# EventListener API\nclass EventListenerAPI(Resource):\n def __init__(self, **kwargs):\n logging.info('Event Listener init called')\n self.root = PATHS['Root']\n self.auth = kwargs['auth']\n\n # HTTP GET\n def get(self):\n logging.info('Event Listener get called')\n return {}\n\n # HTTP POST Collection\n def post(self):\n logging.info('Event Listener post called')\n if request.data:\n config = json.loads(request.data)\n logging.info(f\"Received request json: {config}\")\n handle_events(self)\n\n return {}\n\n # HTTP PUT Collection\n def put(self):\n logging.info('Event Listener put called')\n","sub_path":"api_emulator/redfish/EventListener_api.py","file_name":"EventListener_api.py","file_ext":"py","file_size_in_byte":4194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"466376028","text":"def unix_time():\n from utime import time\n SECONDS_IN_30_YEARS = 946684800\n return time() + SECONDS_IN_30_YEARS\n\ndef check_drinking_notification_required(last_drinking_timestamp_sec, last_notification_timestamp_sec, required_drinking_frequency_sec):\n now_timestamp_sec = unix_time()\n\n if now_timestamp_sec - last_drinking_timestamp_sec < required_drinking_frequency_sec:\n return False\n\n if now_timestamp_sec - last_notification_timestamp_sec < required_drinking_frequency_sec:\n return False\n\n return True\n\ndef sync_ntp(network_wrapper):\n from utime import sleep\n from ntptime import settime\n\n while not network_wrapper.connect_wifi():\n print(\"No connection, retrying\")\n sleep(1)\n\n while True:\n try:\n settime()\n break\n except:\n sleep(1)\n\n","sub_path":"src/outputs/time_utils.py","file_name":"time_utils.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"138620100","text":"#! /usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# __author__ = \"Q1mi\"\r\n# Email: master@liwenzhou.com\r\n\r\n\r\n\"\"\"\r\n\r\n\"\"\"\r\n\r\n\r\nclass MsgPrint(object):\r\n\r\n\t@staticmethod\r\n\tdef error(msg, exit_flag=True):\r\n\t\tmsg = \"\\033[31;1mError:\\033[0m{}\".format(msg)\r\n\t\tprint(msg)\r\n\r\n\t\tif exit_flag:\r\n\t\t\texit()\r\n","sub_path":"Stark/Arya/Needle/core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"148991536","text":"import VCS_main\nimport argparse\n\nparser = argparse.ArgumentParser(description=\"Parser for gitbit VCS commands.\")\nparser.add_argument(\"opcode\", type=str, help=\"Choose an opcode that suits the wanted operation.\"\n \" for example: commit, push, init.\")\nparser.add_argument(\"-o\", \"--opcode_args\", type=str, help=\"Optional arguments for certian functions.\")\n\n\ndef main():\n args = parser.parse_args()\n if args.opcode == \"commit\":\n VCS_main.handle_commit()\n elif args.opcode == \"init\":\n VCS_main.handle_init()\n elif args.opcode == \"delete\":\n VCS_main.handle_delete()\n elif args.opcode == \"push\":\n VCS_main.handle_push()\n elif args.opcode == \"pull\":\n VCS_main.handle_pull()\n elif args.opcode == \"clone\":\n VCS_main.handle_clone()\n elif args.opcode == \"add\":\n VCS_main.handle_add(args.opcode_args)\n elif args.opcode == \"preview\":\n VCS_main.handle_preview(args.opcode_args)\n elif args.opcode == \"status\":\n VCS_main.handle_status()\n\n else:\n print(f\"{args.opcode} is not a legal command.\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"gitbit.py","file_name":"gitbit.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"551796855","text":"import sys\n\nfrom PyQt5.QtWidgets import QApplication,\\\n QAction, qApp, QMainWindow\n\n\"\"\"\nJust a skeleton of a menu. Will not be used.\n\"\"\"\n\nclass Menu(QMainWindow):\n def __init__(self):\n super().__init__()\n\n # Create Menu bar\n bar = self.menuBar()\n\n # Create Root Menu\n file = bar.addMenu(\"File\")\n edit = bar.addMenu(\"Edit\")\n\n # Create Actions for menus\n save_action = QAction(\"&Save\", self)\n save_action.setShortcut(\"Ctrl+S\")\n\n new_action = QAction(\"&New\", self)\n new_action.setShortcut(\"Ctrl+N\")\n\n quit_action = QAction(\"&Quit\", self)\n quit_action.setShortcut(\"Ctrl+Q\")\n\n find_action = QAction(\"Find\", self)\n\n replace_action = QAction(\"Replace\", self)\n\n # Add Actions to menus\n file.addAction(new_action)\n file.addAction(save_action)\n file.addAction(quit_action)\n\n find_menu = edit.addMenu(\"Find\")\n find_menu.addAction(find_action)\n find_menu.addAction(replace_action)\n\n # Events\n quit_action.triggered.connect(self.quit_trigger)\n file.triggered.connect(self.selected)\n\n self.setWindowTitle(\"Menu\")\n self.resize(600, 800)\n\n self.show()\n\n def quit_trigger(self):\n qApp.quit()\n\n def selected(self, q):\n print(q.text() + \" selected\")\n\n\napp = QApplication(sys.argv)\nmenus = Menu()\nsys.exit(app.exec_())\n","sub_path":"Python/StandaloneExercises/PyQtNotepad/menubar.py","file_name":"menubar.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"320921986","text":"\ngst_str = (\"nvarguscamerasrc ! video/x-raw(memory:NVMM), width=(int)480, height=(int)360, format=(string)NV12, framerate=(fraction)60/1 ! nvvidconv flip-method=0 ! video/x-raw, width=(int)480, height=(int)360, format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)BGR ! appsink\")\n#gst_str = (\"nvarguscamerasrc ! video/x-raw(memory:NVMM), width=(int)640, height=(int)480, format=(string)NV12, framerate=(fraction)60/1 ! nvvidconv flip-method=0 ! video/x-raw, width=(int)640, height=(int)480, format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)BGR ! appsink\")\n#480 360\nimport cv2\nimport numpy as np\nimport lane_detection\nimport time\nfrom OpenCV_Utils import *\nimport motorDef\n\ndef Video(): #openpath\n openpath = gst_str\n cap = cv2.VideoCapture(openpath)\n time.sleep(2)\n if cap.isOpened():\n print(\"Video Opened\")\n else:\n print(\"Video Not Opened\")\n print(\"Program Abort\")\n exit()\n fps = 60 \n #fps = cap.get(cv2.CAP_PROP_FPS)\n width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n fourcc = int(cap.get(cv2.CAP_PROP_FOURCC))\n #fourcc = cv2.VideoWriter_fourcc('m','p','4','v') with *.mp4 save\n\n cv2.namedWindow(\"Input\", cv2.WINDOW_GUI_EXPANDED)\n\n while cap.isOpened():\n # Capture frame-by-frame\n# start_time = time.time()\n ret, frame = cap.read()\n #frame = cv2.resize(frame, dsize=(224, 224), interpolation=cv2.INTER_AREA)\n if ret:\n# lane_detect = lane_detection.LaneDetectImg(frame)\n \n try:\n #canny\n #canny_edge = lane_detection.LaneDetectImg_canny(frame)\n #cv2.imshow(\"canny\", canny_edge)\n \n lane_detect = lane_detection.LaneDetectImg(frame)\n cv2.imshow(\"input\", lane_detect)\n #cv2.waitKey(0)\n \n except:\n frame = lane_detection.centerAim(frame)\n cv2.imshow(\"input\", frame)\n \n #lane_detect = lineFitting(frame)\n # Display the resulting frame\n #cv2.imshow(\"Input\", lane_detect)\n #cv2.imshow(\"test\", linecv)\n \n else:\n break\n # waitKey(int(1000.0/fps)) for matching fps of video\n# end_time2 = time.time()\n# print(\"time1 :\", end_time2 - start_time)\n \n if cv2.waitKey(int(1000.0/fps)) & 0xFF == ord('q'):\n motorDef.real_stop() #motor stop\n break\n# end_time = time.time()\n# print(\"delay :\", end_time - start_time)\n # When everything done, release the capture\n cap.release()\n\n cv2.destroyAllWindows()\n return\n \nif __name__==\"__main__\":\n #Video(gst_str)\n Video()\n","sub_path":"scripts/jetbot_camera.py","file_name":"jetbot_camera.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"536119043","text":"#!py -3\r\n\r\nfrom sys import stderr, stdin, stdout\r\n\r\ndef main():\r\n \"\"\"\r\n The first line of the input gives the number of test cases, T. T test cases follow.\r\n \r\n Each test case consists of two lines.\r\n \r\n The first line of a test case contains a single integer N, the total number of kids in the class.\r\n\r\n The second line of a test case contains N integers F1, F2, ..., FN, where Fi is the student ID number of the BFF of the kid with student ID i. \r\n \r\n \r\n \"\"\"\r\n \r\n for i in range(int(input())):\r\n \r\n ## INPUT ##\r\n n = int(input())\r\n # f = list(map(int, input().strip().split()))\r\n f = [int(x) - 1 for x in input().strip().split()]\r\n # stupid 1-indexing.\r\n assert len(f) == n\r\n \r\n ## OUTPUT ##\r\n \r\n ans = solve(f)\r\n \r\n ## PRINT ##\r\n\r\n print(\"Case #%d:\" % (i+1), ans)\r\n\r\n\r\n#return: biggest circle.\r\ndef solve(f):\r\n \"\"\"\r\n Limits\r\n\r\n 1 = T = 100.\r\n 1 = Fi = N, for all i.\r\n Fi ? i, for all i. (No kid is their own BFF.)\r\n\r\n Small dataset\r\n 3 = N = 10.\r\n Large dataset\r\n 3 = N = 1000.\r\n\r\n \"\"\"\r\n # Need to be able to know:\r\n # For each kid, who their BFF is. (This is `f`.)\r\n # For each kid, who BFFs them.\r\n \r\n # graph[k] := list[]\r\n graph = bucketize(f)\r\n \r\n # Two ways of adding to the circle:\r\n # 1. Cycle. This takes up the whole circle.\r\n # 2. Chain: Two kids who are mutual BFf, and then a chain off of each of them (possibly nonempty).\r\n # a -> b -> c <-> d <- e <- f\r\n \r\n # Each child is either a straggler, or in a cycle.\r\n \r\n \r\n # Well, the length is what matters.\r\n # so these return ints, despite naming.s\r\n cycles, stragglers = divvy(graph)\r\n \r\n kchain = biggest_chain(cycles, stragglers, graph)\r\n #kchain first because kcycle is destructive.\r\n kcycle = biggest_cycle(cycles)\r\n \r\n print(file=stderr)\r\n print(\"Friends:\", *f, file=stderr)\r\n print(\"Cycles, chains:\", kcycle, kchain, file=stderr)\r\n \r\n return max(kcycle, kchain)\r\n\r\n\r\ndef divvy(g):\r\n \"\"\"\r\n Divides graph up into cycles and stragglers.\r\n \"\"\"\r\n \r\n graph = dict(enumerate(map(set, g)))\r\n \r\n ## Isolate stragglers. ##\r\n \r\n # Find no-incoming-edges.\r\n lonely = set(k for k, b in graph.items() if not b)\r\n all_lonely = lonely\r\n while lonely and graph:\r\n newgraph = []\r\n newlonely = []\r\n for k, b in graph.items():\r\n b -= lonely\r\n if b:\r\n newgraph.append((k, b))\r\n else:\r\n newlonely.append(k)\r\n graph, lonely = dict(newgraph), set(newlonely)\r\n all_lonely |= lonely\r\n \r\n assert all(len(v) == 1 for v in graph.values())\r\n g1 = {k: v.pop() for k, v in graph.items()}\r\n \r\n return g1, all_lonely\r\n\r\n\r\n\r\ndef biggest_cycle(cycles):\r\n def trace(v):\r\n c = 0 #i off-by-one'd here ._.\r\n while v is not None:\r\n v = cycles.pop(v, None)\r\n c += 1\r\n return c\r\n \r\n best = 0\r\n while cycles:\r\n best = max(best, trace(cycles.popitem()[1]))\r\n \r\n return best\r\n\r\n\r\n#\r\ndef biggest_chain(cycles, stragglers, graph):\r\n # Find two-cycles.\r\n loops = set()\r\n # Pick pairs where k0 < k1.\r\n for k, v in cycles.items():\r\n if cycles[v] == k:\r\n if k > v:\r\n k,v = v,k\r\n loops.add((k,v))\r\n \r\n # longest chain for this kid\r\n def longest_of(k, k0):\r\n q = (k,)\r\n depth = 0 # this kid\r\n while q:\r\n q = [kj for ki in q\r\n for kj in graph[ki]\r\n if kj != k0]\r\n # there shouldn't be any other cycles.\r\n depth += 1\r\n \r\n return depth\r\n \r\n return sum(\r\n (longest_of(k0, k1) + longest_of(k1, k0)\r\n for k0, k1 in loops),\r\n )\r\n \r\n \r\n\r\n\r\ndef bucketize(f):\r\n buckets = [[] for _ in range(len(f))]\r\n \r\n for i, k in enumerate(f):\r\n buckets[k].append(i)\r\n \r\n return buckets\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n","sub_path":"solutions_5631572862566400_0/Python/Franklinquestionmark/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":4203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"300099571","text":"from PyPDF2 import PdfFileMerger\nimport os\n\nos.chdir(\"/Users/matthew/Documents/PDFs\")\n\nprint(\"Please enter a list of PDFs.\")\n\nPDFs = input().split(\",\")\n\nmerger = PdfFileMerger()\n\nfor pdf in PDFs:\n merger.append(pdf)\n\nmerger.write('result.pdf')\n\n\n\n","sub_path":"Merge_PDFs.py","file_name":"Merge_PDFs.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"147017413","text":"import os\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n ('Chide.it', 'developers@chide.it'),\n)\n\nROOT = os.path.dirname(os.path.realpath(__file__))\n\nMANAGERS = ADMINS\n\nTIME_ZONE = 'America/Chicago'\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\nUSE_I18N = False\nUSE_L10N = False\n\nMEDIA_ROOT = '%s/media/' % ROOT\nMEDIA_URL = '/media/'\n\nADMIN_MEDIA_PREFIX = '/admin/media/'\n\nSECRET_KEY = 'thisisasecret'\n\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n)\n\nROOT_URLCONF = 'chide.urls'\n\nTEMPLATE_DIRS = (\n '%s/templates/' % ROOT,\n)\n\nINSTALLED_APPS = (\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'gunicorn',\n)\n\ntry:\n\tfrom settings_local import *\nexcept ImportError:\n\tpass\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"182002693","text":"import trafaret as t\n\nfrom datarobot.models.api_object import APIObject\nfrom datarobot.utils import encode_utf8_if_py2\n\n\nclass FeatureAssociationMatrixDetails(APIObject):\n \"\"\"\n Plotting details for a pair of passed features present in the feature association matrix.\n\n .. note::\n Projects created prior to v2.17 are not supported by this feature.\n\n Attributes\n ----------\n project_id : str\n Id of the project that contains the requested associations.\n chart_type : str\n Which type of plotting the pair of features gets in the UI.\n e.g. 'HORIZONTAL_BOX', 'VERTICAL_BOX', 'SCATTER' or 'CONTINGENCY'\n values : list\n The data triplets for pairwise plotting e.g.\n {\"values\": [[460.0, 428.5, 0.001], [1679.3, 259.0, 0.001], ...]\n The first entry of each list is a value of feature1, the second entry of each list is a\n value of feature2, and the third is the relative frequency of the pair of datapoints in the\n sample.\n features : list\n A list of the requested features, [feature1, feature2]\n types : list\n The type of `feature1` and `feature2`. Possible values: \"CATEGORICAL\", \"NUMERIC\"\n featurelist_id : str\n Id of the feature list to lookup FAM details for.\n \"\"\"\n\n _path = \"projects/{}/featureAssociationMatrixDetails/\"\n _converter = t.Dict(\n {\n t.Key(\"chart_type\"): t.String(),\n t.Key(\"values\"): t.List(t.Tuple(t.Any(), t.Any(), t.Float())),\n t.Key(\"features\"): t.List(t.String()),\n t.Key(\"types\"): t.List(t.String()),\n }\n )\n\n def __init__(\n self,\n project_id=None,\n chart_type=None,\n values=None,\n features=None,\n types=None,\n featurelist_id=None,\n ):\n self.project_id = project_id\n self.chart_type = chart_type\n self.values = values\n self.features = features\n self.types = types\n self.featurelist_id = featurelist_id\n\n def __repr__(self):\n return encode_utf8_if_py2(\n u\"{}(project_id={}, chart_type={}, values={}, features={}, types={})\".format(\n self.__class__.__name__,\n self.project_id,\n self.chart_type,\n self.values,\n self.features,\n self.types,\n )\n )\n\n @classmethod\n def get(cls, project_id, feature1, feature2, featurelist_id=None):\n \"\"\"\n Get a sample of the actual values used to measure the association between a pair of features\n\n .. versionadded:: v2.17\n\n Parameters\n ----------\n project_id : str\n Id of the project of interest.\n feature1 : str\n Feature name for the first feature of interest.\n feature2 : str\n Feature name for the second feature of interest.\n featurelist_id : str\n Optional, the feature list to lookup FAM data for. By default, depending on the type of\n the project \"Informative Features\" or \"Timeseries Informative Features\" list will be\n used.\n\n Returns\n --------\n FeatureAssociationMatrixDetails\n The feature association plotting for provided pair of features.\n \"\"\"\n url = cls._path.format(project_id)\n params = {\"feature1\": feature1, \"feature2\": feature2}\n if featurelist_id:\n params[\"featurelistId\"] = featurelist_id\n response = cls._client.get(url, params=params)\n fam_details = cls.from_server_data(response.json())\n fam_details.project_id = project_id\n fam_details.featurelist_id = featurelist_id\n return fam_details\n\n def to_dict(self):\n return {\n \"chart_type\": self.chart_type,\n \"values\": self.values,\n \"features\": self.features,\n \"types\": self.types,\n }\n","sub_path":"datarobot/models/feature_association_matrix/feature_association_matrix_details.py","file_name":"feature_association_matrix_details.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"617066560","text":"# Copyright 2020, 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\"\"\"Runs federated training on various tasks using a generalized form of FedAvg.\n\nSpecifically, we create (according to flags) an iterative processes that allows\nfor client and server learning rate schedules, as well as various client and\nserver optimization methods. For more details on the learning rate scheduling\nand optimization methods, see `shared/optimizer_utils.py`. For details on the\niterative process, see `shared/fed_avg_schedule.py`.\n\"\"\"\n\nimport collections\nimport os.path\nfrom typing import Callable\n\nfrom absl import app\nfrom absl import flags\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\nfrom optimization.cifar100 import federated_cifar100\nfrom optimization.emnist import federated_emnist\nfrom optimization.emnist_ae import federated_emnist_ae\nfrom optimization.shakespeare import federated_shakespeare\nfrom optimization.shared import fed_avg_schedule\nfrom optimization.shared import optimizer_utils\nfrom optimization.shared import training_specs\nfrom optimization.stackoverflow import federated_stackoverflow\nfrom optimization.stackoverflow_lr import federated_stackoverflow_lr\nfrom utils import training_loop\nfrom utils import utils_impl\n\n_SUPPORTED_TASKS = [\n 'cifar100', 'emnist_cr', 'emnist_ae', 'shakespeare', 'stackoverflow_nwp',\n 'stackoverflow_lr'\n]\n\nwith utils_impl.record_hparam_flags() as optimizer_flags:\n # Defining optimizer flags\n optimizer_utils.define_optimizer_flags('client')\n optimizer_utils.define_optimizer_flags('server')\n optimizer_utils.define_lr_schedule_flags('client')\n optimizer_utils.define_lr_schedule_flags('server')\n\nwith utils_impl.record_hparam_flags() as shared_flags:\n # Federated training hyperparameters\n flags.DEFINE_integer('client_epochs_per_round', 1,\n 'Number of epochs in the client to take per round.')\n flags.DEFINE_integer('client_batch_size', 20, 'Batch size on the clients.')\n flags.DEFINE_integer('clients_per_round', 10,\n 'How many clients to sample per round.')\n flags.DEFINE_integer('client_datasets_random_seed', 1,\n 'Random seed for client sampling.')\n\n # Training loop configuration\n flags.DEFINE_string(\n 'experiment_name', None, 'The name of this experiment. Will be append to '\n '--root_output_dir to separate experiment results.')\n flags.mark_flag_as_required('experiment_name')\n flags.DEFINE_string('root_output_dir', '/tmp/fed_opt/',\n 'Root directory for writing experiment output.')\n flags.DEFINE_integer('total_rounds', 200, 'Number of total training rounds.')\n flags.DEFINE_integer(\n 'rounds_per_eval', 1,\n 'How often to evaluate the global model on the validation dataset.')\n flags.DEFINE_integer('rounds_per_checkpoint', 50,\n 'How often to checkpoint the global model.')\n\nwith utils_impl.record_hparam_flags() as task_flags:\n # Task specification\n flags.DEFINE_enum('task', None, _SUPPORTED_TASKS,\n 'Which task to perform federated training on.')\n\nwith utils_impl.record_hparam_flags() as cifar100_flags:\n # CIFAR-100 flags\n flags.DEFINE_integer('cifar100_crop_size', 24, 'The height and width of '\n 'images after preprocessing.')\n flags.DEFINE_bool(\n 'cifar100_distort_train_images', True, 'If set to True, '\n 'train images will be randomly cropped. Otherwise, all '\n 'images will simply be resized.')\n\nwith utils_impl.record_hparam_flags() as emnist_cr_flags:\n # EMNIST CR flags\n flags.DEFINE_enum(\n 'emnist_cr_model', 'cnn', ['cnn', '2nn'], 'Which model to '\n 'use. This can be a convolutional model (cnn) or a two '\n 'hidden-layer densely connected network (2nn).')\n\nwith utils_impl.record_hparam_flags() as shakespeare_flags:\n # Shakespeare flags\n flags.DEFINE_integer(\n 'shakespeare_sequence_length', 80,\n 'Length of character sequences to use for the RNN model.')\n\nwith utils_impl.record_hparam_flags() as so_nwp_flags:\n # Stack Overflow NWP flags\n flags.DEFINE_integer('so_nwp_vocab_size', 10000, 'Size of vocab to use.')\n flags.DEFINE_integer('so_nwp_num_oov_buckets', 1,\n 'Number of out of vocabulary buckets.')\n flags.DEFINE_integer('so_nwp_sequence_length', 20,\n 'Max sequence length to use.')\n flags.DEFINE_integer('so_nwp_max_elements_per_user', 1000, 'Max number of '\n 'training sentences to use per user.')\n flags.DEFINE_integer(\n 'so_nwp_num_validation_examples', 10000, 'Number of examples '\n 'to use from test set for per-round validation.')\n\nwith utils_impl.record_hparam_flags() as so_lr_flags:\n # Stack Overflow LR flags\n flags.DEFINE_integer('so_lr_vocab_tokens_size', 10000,\n 'Vocab tokens size used.')\n flags.DEFINE_integer('so_lr_vocab_tags_size', 500, 'Vocab tags size used.')\n flags.DEFINE_integer(\n 'so_lr_num_validation_examples', 10000, 'Number of examples '\n 'to use from test set for per-round validation.')\n flags.DEFINE_integer('so_lr_max_elements_per_user', 1000,\n 'Max number of training '\n 'sentences to use per user.')\n\nwith utils_impl.record_hparam_flags() as dp_flags:\n # Differential privacy flags\n flags.DEFINE_float(\n 'clip', None, 'Clip value for fixed clipping or initial clip for '\n 'adaptive clipping. If None, no clipping is used.')\n flags.DEFINE_float('noise_multiplier', None,\n 'Noise multiplier. If None, non-DP aggregator is used.')\n flags.DEFINE_float(\n 'adaptive_clip_learning_rate', None, 'Adaptive clip learning rate. If '\n 'None, clip adaptation is not used.')\n flags.DEFINE_float('target_unclipped_quantile', 0.5,\n 'Target unclipped quantile.')\n flags.DEFINE_boolean('uniform_weighting', False,\n 'Whether to weigh clients uniformly.')\n\n# adding adaptive lr and making it compatible with the other options will take some time\n# I need to do quicker things first if I can\n#with utils_impl.record_hparam_flags() as callback_flags:\n# flags.DEFINE_float(\n# 'client_decay_factor', 0.1, 'Amount to decay the client learning rate '\n# 'upon reaching a plateau.')\n# flags.DEFINE_float(\n# 'server_decay_factor', 0.9, 'Amount to decay the server learning rate '\n# 'upon reaching a plateau.')\n# flags.DEFINE_float(\n# 'min_delta', 1e-4, 'Minimum delta for improvement in the learning rate '\n# 'callbacks.')\n# flags.DEFINE_integer(\n# 'window_size', 100, 'Number of rounds to take a moving average over when '\n# 'estimating the training loss in learning rate callbacks.')\n# flags.DEFINE_integer(\n# 'patience', 100, 'Number of rounds of non-improvement before decaying the'\n# 'learning rate.')\n# flags.DEFINE_float('min_lr', 0.0, 'The minimum learning rate.')\n\n # Compression hyperparameters.\nwith utils.impl.record_hparam_flags() as compression_flags:\n flags.DEFINE_boolean('use_compression', True,\n 'Whether to use compression code path.')\n flags.DEFINE_integer(\n 'broadcast_quantization_bits', 8,\n 'Number of quantization bits for server to client '\n 'compression.')\n flags.DEFINE_integer(\n 'aggregation_quantization_bits', 8,\n 'Number of quantization bits for client to server '\n 'compression.')\n flags.DEFINE_boolean('use_sparsity_in_aggregation', True,\n 'Whether to add sparsity to the aggregation. This will '\n 'only be used for client to server compression.')\nFLAGS = flags.FLAGS\n\nTASK_FLAGS = collections.OrderedDict(\n cifar100=cifar100_flags,\n emnist_cr=emnist_cr_flags,\n shakespeare=shakespeare_flags,\n stackoverflow_nwp=so_nwp_flags,\n stackoverflow_lr=so_lr_flags)\n\n\ndef _write_hparam_flags():\n \"\"\"Creates an ordered dictionary of hyperparameter flags and writes to CSV.\"\"\"\n hparam_dict = utils_impl.lookup_flag_values(shared_flags)\n\n # Update with optimizer flags corresponding to the chosen optimizers.\n opt_flag_dict = utils_impl.lookup_flag_values(optimizer_flags)\n opt_flag_dict = optimizer_utils.remove_unused_flags('client', opt_flag_dict)\n opt_flag_dict = optimizer_utils.remove_unused_flags('server', opt_flag_dict)\n hparam_dict.update(opt_flag_dict)\n\n # Update with task-specific flags.\n task_name = FLAGS.task\n if task_name in TASK_FLAGS:\n task_hparam_dict = utils_impl.lookup_flag_values(TASK_FLAGS[task_name])\n hparam_dict.update(task_hparam_dict)\n\n results_dir = os.path.join(FLAGS.root_output_dir, 'results',\n FLAGS.experiment_name)\n utils_impl.create_directory_if_not_exists(results_dir)\n hparam_file = os.path.join(results_dir, 'hparams.csv')\n utils_impl.atomic_write_series_to_csv(hparam_dict, hparam_file)\n\n\ndef main(argv):\n if len(argv) > 1:\n raise app.UsageError('Expected no command-line arguments, '\n 'got: {}'.format(argv))\n\n client_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('client')\n server_optimizer_fn = optimizer_utils.create_optimizer_fn_from_flags('server')\n\n client_lr_schedule = optimizer_utils.create_lr_schedule_from_flags('client')\n server_lr_schedule = optimizer_utils.create_lr_schedule_from_flags('server')\n\n task_spec = training_specs.TaskSpec(\n iterative_process_builder=iterative_process_builder,\n client_epochs_per_round=FLAGS.client_epochs_per_round,\n client_batch_size=FLAGS.client_batch_size,\n clients_per_round=FLAGS.clients_per_round,\n client_datasets_random_seed=FLAGS.client_datasets_random_seed)\n \n\n\n if FLAGS.task == 'cifar100':\n runner_spec = federated_cifar100.configure_training(\n task_spec,\n crop_size=FLAGS.cifar100_crop_size,\n distort_train_images=FLAGS.cifar100_distort_train_images)\n elif FLAGS.task == 'emnist_cr':\n runner_spec = federated_emnist.configure_training(\n task_spec, model=FLAGS.emnist_cr_model)\n elif FLAGS.task == 'emnist_ae':\n runner_spec = federated_emnist_ae.configure_training(task_spec)\n elif FLAGS.task == 'shakespeare':\n runner_spec = federated_shakespeare.configure_training(\n task_spec, sequence_length=FLAGS.shakespeare_sequence_length)\n elif FLAGS.task == 'stackoverflow_nwp':\n runner_spec = federated_stackoverflow.configure_training(\n task_spec,\n vocab_size=FLAGS.so_nwp_vocab_size,\n num_oov_buckets=FLAGS.so_nwp_num_oov_buckets,\n sequence_length=FLAGS.so_nwp_sequence_length,\n max_elements_per_user=FLAGS.so_nwp_max_elements_per_user,\n num_validation_examples=FLAGS.so_nwp_num_validation_examples)\n elif FLAGS.task == 'stackoverflow_lr':\n runner_spec = federated_stackoverflow_lr.configure_training(\n task_spec,\n vocab_tokens_size=FLAGS.so_lr_vocab_tokens_size,\n vocab_tags_size=FLAGS.so_lr_vocab_tags_size,\n max_elements_per_user=FLAGS.so_lr_max_elements_per_user,\n num_validation_examples=FLAGS.so_lr_num_validation_examples)\n else:\n raise ValueError(\n '--task flag {} is not supported, must be one of {}.'.format(\n FLAGS.task, _SUPPORTED_TASKS))\n\n _write_hparam_flags()\n\n\n training_loop.run(\n iterative_process=runner_spec.iterative_process,\n client_datasets_fn=runner_spec.client_datasets_fn,\n validation_fn=runner_spec.validation_fn,\n test_fn=runner_spec.test_fn,\n total_rounds=FLAGS.total_rounds,\n experiment_name=FLAGS.experiment_name,\n root_output_dir=FLAGS.root_output_dir,\n rounds_per_eval=FLAGS.rounds_per_eval,\n rounds_per_checkpoint=FLAGS.rounds_per_checkpoint)\n\n\nif __name__ == '__main__':\n app.run(main)\n","sub_path":"trainers/federated.py","file_name":"federated.py","file_ext":"py","file_size_in_byte":12238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"167863360","text":"import json\nimport pathlib\nimport time\nfrom typing import List, Optional, Dict\n\nimport git\nimport numpy as np\nimport tensorflow as tf\n\nimport lab.colors as colors\nfrom lab import tf_util, util\nfrom lab.commenter import Commenter\nfrom lab.lab import Lab\nfrom lab.logger import Logger\n\ncommenter = Commenter(\n comment_start='\"\"\"',\n comment_end='\"\"\"',\n add_start='```trial',\n add_end='```'\n)\n\n\nclass ExperimentInfo:\n \"\"\"\n ## Experiment Information\n\n This class keeps track of paths.\n \"\"\"\n\n def __init__(self, lab: Lab, name: str):\n \"\"\"\n ### Initialize\n \"\"\"\n self.name = name\n self.experiment_path = lab.experiments / name\n self.checkpoint_path = self.experiment_path / \"checkpoints\"\n self.npy_path = self.experiment_path / \"npy\"\n self.model_file = self.checkpoint_path / 'model'\n\n self.summary_path = self.experiment_path / \"log\"\n self.screenshots_path = self.experiment_path / 'screenshots'\n self.trials_log_file = self.experiment_path / \"trials.yaml\"\n\n def exists(self) -> bool:\n \"\"\"\n ### Check is this experiment results exists\n \"\"\"\n p = pathlib.Path(self.summary_path)\n return p.exists()\n\n\ndef _struct_time_to_time(t: time.struct_time):\n return f\"{t.tm_hour :02}:{t.tm_min :02}:{t.tm_sec :02}\"\n\n\ndef _struct_time_to_date(t: time.struct_time):\n return f\"{t.tm_year :04}-{t.tm_mon :02}-{t.tm_mday :02}\"\n\n\nclass Trial:\n \"\"\"\n # Trial 🏃‍\n\n Every trial in an experiment has same configs.\n It's just multiple runs.\n\n A new trial will replace checkpoints and TensorBoard summaries\n or previous trials, you should make a copy if needed.\n The performance log in `trials.yaml` is not replaced.\n\n You should run new trials after bug fixes or to see performance is\n consistent.\n\n If you want to try different configs, create multiple experiments.\n \"\"\"\n\n progress: List[Dict[str, str]]\n\n def __init__(self, *,\n python_file: str,\n trial_date: str,\n trial_time: str,\n comment: str,\n commit: str or None = None,\n commit_message: str or None = None,\n is_dirty: bool = True,\n start_step: int = 0,\n progress=None):\n self.commit = commit\n self.is_dirty = is_dirty\n self.python_file = python_file\n self.trial_date = trial_date\n self.trial_time = trial_time\n self.comment = comment\n self.commit_message = commit_message\n self.start_step = start_step\n if progress is None:\n self.progress = []\n else:\n self.progress = progress\n\n @classmethod\n def new_trial(cls, *,\n python_file: str,\n trial_time: time.struct_time,\n comment: str):\n \"\"\"\n ## Create a new trial\n \"\"\"\n return cls(python_file=python_file,\n trial_date=_struct_time_to_date(trial_time),\n trial_time=_struct_time_to_time(trial_time),\n comment=comment)\n\n @classmethod\n def from_dict(cls, data: Dict[str, any]):\n \"\"\"\n ## Create a new trial from a dictionary\n \"\"\"\n return cls(**data)\n\n def to_dict(self):\n \"\"\"\n ## Convert trial to a dictionary for saving\n \"\"\"\n return dict(\n python_file=self.python_file,\n trial_date=self.trial_date,\n trial_time=self.trial_time,\n comment=self.comment,\n commit=self.commit,\n commit_message=self.commit_message,\n is_dirty=self.is_dirty,\n start_step=self.start_step,\n progress=self.progress\n )\n\n def pretty_print(self) -> List[str]:\n \"\"\"\n ## 🎨 Pretty print trial for the python file header\n \"\"\"\n\n # Trial information\n commit_status = \"[dirty]\" if self.is_dirty else \"[clean]\"\n res = [\n f\"{self.trial_date} {self.trial_time}\",\n self.comment,\n f\"[{commit_status}]: {self.commit_message}\",\n f\"start_step: {self.start_step}\"\n ]\n\n # Stop if no progress is available\n if len(self.progress) == 0:\n return res\n\n res.append('')\n\n # Print progress table\n lens = {}\n for k, v in self.progress[0].items():\n lens[k] = max(len(k), len(v))\n\n line = []\n for k, v in self.progress[0].items():\n line.append(' ' * (lens[k] - len(k)) + k)\n line = '| ' + ' | '.join(line) + ' |'\n res.append('-' * len(line))\n res.append(line)\n res.append('-' * len(line))\n\n for p in self.progress:\n line = [' ' * (lens[k] - len(str(v))) + str(v) for k, v in p.items()]\n line = '| ' + ' | '.join(line) + ' |'\n res.append(line)\n\n res.append('-' * len(line))\n\n return res\n\n def __str__(self):\n return f\"Trial(comment=\\\"{self.comment}\\\",\" \\\n f\" commit=\\\"{self.commit_message}\\\",\" \\\n f\" date={self.trial_date}, time={self.trial_time}\"\n\n def __repr__(self):\n return self.__str__()\n\n def set_progress(self, progress: Dict[str, str], is_add: bool):\n \"\"\"\n ## Add or update progress\n \"\"\"\n if is_add:\n self.progress.append(progress)\n else:\n self.progress[-1] = progress\n\n\nclass Experiment:\n \"\"\"\n ## Experiment\n\n Each experiment has different configurations or algorithms.\n An experiment can have multiple trials.\n \"\"\"\n\n __variables: Optional[List[tf.Variable]]\n\n def __init__(self, *,\n lab: Lab,\n name: str,\n python_file: str,\n comment: str,\n check_repo_dirty: bool = True):\n \"\"\"\n ### Create the experiment\n\n :param lab: reference to current lab\n :param name: name of the experiment\n :param python_file: `__file__` that invokes this. This is stored in\n the experiments list.\n :param comment: a short description of the experiment\n :param check_repo_dirty: whether not to start the experiment if\n there are uncommitted changes.\n\n The experiments log keeps track of `python_file`, `name`, `comment` as\n well as the git commit.\n\n Experiment maintains the locations of checkpoints, logs, etc.\n \"\"\"\n\n self.__variables = None\n self.info = ExperimentInfo(lab, name)\n\n self.logger = Logger()\n self.check_repo_dirty = check_repo_dirty\n\n self.lab = lab\n\n if not tf.gfile.Exists(str(self.info.experiment_path)):\n tf.gfile.MakeDirs(str(self.info.experiment_path))\n\n self.trial = Trial.new_trial(\n python_file=python_file,\n trial_time=time.localtime(),\n comment=comment)\n\n repo = git.Repo(self.lab.path)\n\n self.trial.commit = repo.active_branch.commit.hexsha\n self.trial.commit_message = repo.active_branch.commit.message.strip()\n self.trial.is_dirty = repo.is_dirty()\n\n def print_info_and_check_repo(self):\n \"\"\"\n ## 🖨 Print the experiment info and check git repo status\n \"\"\"\n self.logger.log_color([\n (self.info.name, colors.Style.bold)\n ])\n self.logger.log_color([\n (\"\\t\", None),\n (self.trial.comment, colors.BrightColor.cyan)\n ])\n self.logger.log_color([\n (\"\\t\", None),\n (\"[dirty]\" if self.trial.is_dirty else \"[clean]\", None),\n (\": \", None),\n (f\"\\\"{self.trial.commit_message.strip()}\\\"\", colors.BrightColor.orange)\n ])\n\n # Exit if git repository is dirty\n if self.check_repo_dirty and self.trial.is_dirty:\n self.logger.log(\"Cannot trial an experiment with uncommitted changes. \",\n new_line=False)\n self.logger.log(\"[FAIL]\", color=colors.BrightColor.red)\n exit(1)\n\n @util.deprecated(\"Use load_checkpoint_numpy\")\n def load_checkpoint(self, session: tf.Session):\n \"\"\"\n ## Load latest TensorFlow checkpoint\n\n **Use numpy array saving.**\n\n It's simpler and you can easily load subsets of\n variable.\n Or even manually swap variables between experiments with just\n file copies to try things out.\n \"\"\"\n if not _load_checkpoint(session, str(self.info.checkpoint_path)):\n tf_util.init_variables(session)\n return False\n else:\n return True\n\n @util.deprecated(\"Use save_checkpoint_numpy\")\n def save_checkpoint(self, session: tf.Session, global_step: int):\n \"\"\"\n ## Save TensorFlow checkpoint\n\n Use numpy array saving.\n \"\"\"\n _delete_old_checkpoints(str(self.info.checkpoint_path))\n _save_checkpoint(session, str(self.info.checkpoint_path),\n str(self.info.model_file), global_step)\n\n def load_checkpoint_numpy(self,\n session: tf.Session):\n \"\"\"\n ## Load model as a set of numpy arrays\n \"\"\"\n\n checkpoints_path = pathlib.Path(self.info.checkpoint_path)\n max_step = -1\n for c in checkpoints_path.iterdir():\n max_step = max(max_step, int(c.name))\n\n if max_step < 0:\n return False\n\n checkpoint_path = checkpoints_path / str(max_step)\n\n with open(str(checkpoint_path / \"info.json\"), \"r\") as f:\n files = json.loads(f.readline())\n\n # Load each variable\n for variable in self.__variables:\n file_name = files[variable.name]\n value = np.load(str(checkpoint_path / file_name))\n ph = tf.placeholder(value.dtype,\n shape=value.shape,\n name=f\"{tf_util.strip_variable_name(variable.name)}_ph\")\n\n assign_op = tf.assign(variable, ph)\n session.run(assign_op, feed_dict={ph: value})\n\n return True\n\n def save_checkpoint_numpy(self,\n session: tf.Session,\n global_step: int):\n \"\"\"\n ## Save model as a set of numpy arrays\n \"\"\"\n\n checkpoints_path = pathlib.Path(self.info.checkpoint_path)\n if not checkpoints_path.exists():\n checkpoints_path.mkdir()\n\n checkpoint_path = checkpoints_path / str(global_step)\n assert not checkpoint_path.exists()\n\n checkpoint_path.mkdir()\n\n values = session.run(self.__variables)\n\n # Save each variable\n files = {}\n for variable, value in zip(self.__variables, values):\n file_name = tf_util.variable_name_to_file_name(\n tf_util.strip_variable_name(variable.name))\n file_name = f\"{file_name}.npy\"\n files[variable.name] = file_name\n\n np.save(str(checkpoint_path / file_name), value)\n\n # Save header\n with open(str(checkpoint_path / \"info.json\"), \"w\") as f:\n f.write(json.dumps(files))\n\n # Delete old checkpoints\n for c in checkpoints_path.iterdir():\n if c.name != checkpoint_path.name:\n util.rm_tree(c)\n\n def save_npy(self, array: np.ndarray, name: str):\n \"\"\"\n ## Save a single numpy array\n\n This is used to save processed data\n \"\"\"\n tf.gfile.MkDir(str(self.info.npy_path))\n file_name = name + \".npy\"\n np.save(str(self.info.npy_path / file_name), array)\n\n def load_npy(self, name: str):\n \"\"\"\n ## Load a single numpy array\n\n This is used to save processed data\n \"\"\"\n file_name = name + \".npy\"\n return np.load(str(self.info.npy_path / file_name))\n\n def clear_checkpoints(self):\n \"\"\"\n ## Clear old checkpoints\n\n We run this when running a new fresh trial\n \"\"\"\n if tf.gfile.Exists(str(self.info.checkpoint_path)):\n tf.gfile.DeleteRecursively(str(self.info.checkpoint_path))\n\n def clear_summaries(self):\n \"\"\"\n ## Clear TensorBoard summaries\n\n We run this when running a new fresh trial\n \"\"\"\n if tf.gfile.Exists(str(self.info.summary_path)):\n tf.gfile.DeleteRecursively(str(self.info.summary_path))\n\n def create_writer(self, session: tf.Session):\n \"\"\"\n ## Create TensorFlow summary writer\n \"\"\"\n self.logger.writer = tf.summary.FileWriter(str(self.info.summary_path), session.graph)\n\n def clear_screenshots(self):\n \"\"\"\n ## Clear screenshots\n \"\"\"\n path = str(self.info.screenshots_path)\n if tf.gfile.Exists(path):\n tf.gfile.DeleteRecursively(path)\n\n tf.gfile.MkDir(path)\n\n def save_screenshot(self, img, file_name: str):\n \"\"\"\n ## Save screenshot\n\n Use this to save images\n \"\"\"\n img.save(str(self.info.screenshots_path / file_name))\n\n def set_variables(self, variables: List[tf.Variable]):\n \"\"\"\n ## Set variable for saving and loading\n \"\"\"\n self.__variables = variables\n\n def _log_trial(self, is_add: bool):\n \"\"\"\n ### Log trial\n\n This will add or update a trial in the `trials.yaml` file\n \"\"\"\n try:\n with open(str(self.info.trials_log_file), \"r\") as file:\n trials = util.yaml_load(file.read())\n except FileNotFoundError:\n trials = []\n\n if is_add:\n trials.append(self.trial.to_dict())\n else:\n trials[-1] = self.trial.to_dict()\n\n with open(str(self.info.trials_log_file), \"w\") as file:\n file.write(util.yaml_dump(trials))\n\n def _log_python_file(self):\n \"\"\"\n ### Add header to python source\n\n This will add or update trial information in python source file\n \"\"\"\n with open(self.trial.python_file, \"r\") as file:\n lines = file.read().splitlines()\n\n trial_print = self.trial.pretty_print()\n\n lines = commenter.update(lines, trial_print)\n code = '\\n'.join(lines)\n\n with open(self.trial.python_file, \"w\") as file:\n file.write(code)\n\n def save_progress(self, progress: Dict[str, str], is_add: bool):\n \"\"\"\n ## Save experiment progress\n \"\"\"\n self.trial.set_progress(progress, is_add)\n\n self._log_trial(is_add=False)\n self._log_python_file()\n\n def start(self, global_step: int, session: tf.Session):\n \"\"\"\n ## Start experiment\n\n Load a checkpoint or reset based on `global_step`.\n \"\"\"\n\n self.trial.start_step = global_step\n self._log_trial(is_add=True)\n self._log_python_file()\n\n if global_step > 0:\n # load checkpoint if we are starting from middle\n with self.logger.monitor(\"Loading checkpoint\") as m:\n if self.__variables is None:\n m.is_successful = self.load_checkpoint(session)\n else:\n m.is_successful = self.load_checkpoint_numpy(session)\n else:\n # initialize variables and clear summaries if we are starting from scratch\n with self.logger.monitor(\"Clearing summaries\"):\n self.clear_summaries()\n with self.logger.monitor(\"Clearing checkpoints\"):\n self.clear_checkpoints()\n with self.logger.monitor(\"Initializing variables\"):\n tf_util.init_variables(session)\n\n self.create_writer(session)\n\n\ndef _delete_old_checkpoints(checkpoint_path: str):\n \"\"\"\n #### Delete old TensorFlow checkpoints\n \"\"\"\n latest_checkpoint = tf.train.latest_checkpoint(checkpoint_path)\n if not latest_checkpoint:\n return\n\n checkpoint_path = pathlib.Path(checkpoint_path)\n for p in checkpoint_path.iterdir():\n if p.match(str(checkpoint_path / 'checkpoint')):\n continue\n elif p.match(latest_checkpoint + '*'):\n continue\n else:\n p.unlink()\n\n\ndef _load_checkpoint(session: tf.Session, checkpoint_path: str) -> bool:\n \"\"\"\n #### Load TensorFlow checkpoint\n \"\"\"\n latest_checkpoint = tf.train.latest_checkpoint(checkpoint_path)\n if latest_checkpoint is not None:\n saver = tf.train.Saver()\n saver.restore(session, latest_checkpoint)\n return True\n else:\n return False\n\n\ndef _save_checkpoint(session: tf.Session,\n checkpoint_path: str,\n model_file: str,\n global_step: int):\n \"\"\"\n #### Save TensorFlow checkpoint\n \"\"\"\n if not tf.gfile.Exists(checkpoint_path):\n tf.gfile.MakeDirs(checkpoint_path)\n saver = tf.train.Saver()\n saver.save(session, model_file, global_step=global_step)\n","sub_path":"lab/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":16972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"81457729","text":"\"\"\"\nModule for testing\n\"\"\"\n\nimport os.path\nfrom typing import List, Dict\n\nimport json_manager\nimport agents\n\n\ndef test_reply_agent(agent_function: \"agent's function to process input message\",\n test_file_name: str,\n test_output_file_name: str = 'test_output.json') -> None:\n \"\"\"\n Test agent that can give replies on text messages\n :param agent_function: agent to test\n :param test_file_name: file with test data\n :param test_output_file_name: file for writing testing output in\n :return: None\n \"\"\"\n if not (agent_function and test_file_name and test_output_file_name):\n return\n\n # read lines of text as messages\n with open(test_file_name, 'r', encoding='utf-8-sig') as test_file:\n messages = test_file.readlines()\n\n # list with dictionaries that contain message text and reply\n test_output: List[Dict[str, str]] = list()\n\n for message in messages:\n test_output.append({\"message\": message,\n \"reply\": agent_function(message)})\n\n json_manager.write(test_output, test_output_file_name)\n\n\nTEST_NUMBERS = [1, 0, 2]\n\nfor test_n in TEST_NUMBERS:\n for agent_f in [agents.CONVERSATION_CONTROLLER.proceed_input_message]:\n test_reply_agent(agent_f,\n os.path.join('data', 'tests', f'test{str(test_n)}.txt'),\n test_output_file_name=f'test_output_CONVERSATION_CONTROLLER_n_{str(test_n)}.txt')\n","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"501514595","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\nos.system('mkdir data')\nos.system('mkdir results')\nos.system('mkdir results/timeseries')\n\n#=====================================\n#incident wave\n#=====================================\nd0 = 0.2\nh0 = 0.07\n\nc = np.sqrt(9.81*(d0+h0))\nk = np.sqrt(0.75*h0/d0**3)\n\nt = np.linspace(-3.,6.,200)\nx = 0.\neta = h0*(np.cosh(k*(x-c*t)))**(-2)\n\netaL = np.vstack([t,eta]).T\nnp.savetxt('data/etaL.dat',etaL)\n\nplt.figure()\nplt.plot(etaL[:,0],etaL[:,1])\nplt.savefig('data/etaL.png')\n\n#=====================================\n#computational domain\n#=====================================\nn=100.\nx=np.linspace(0,10.,n)\ndx = np.diff(x)[0]\ny=np.linspace(-dx*5,dx*5,10)\nx,y=np.meshgrid(x,y,indexing='ij')\n\nz= -d0*np.ones(x.shape)\nh = d0*np.ones(x.shape)\nu = np.zeros(x.shape)\nv = np.zeros(x.shape)\n\nbatifiles=['data/gridX.dat','data/gridY.dat','data/gridZ.dat']\ninitqfiles=['data/inith.dat', 'data/initu.dat', 'data/initv.dat']\n\nnp.savetxt(batifiles[0],x)\nnp.savetxt(batifiles[1],y)\nnp.savetxt(batifiles[2],z)\nnp.savetxt(initqfiles[0],h)\nnp.savetxt(initqfiles[1],u)\nnp.savetxt(initqfiles[2],v)\n\nplt.figure(figsize=(8.,3.))\nplt.fill_between(x[:,0],z[:,0],z[:,0]+h[:,0],color='b')\n#plt.fill_between(x[:,0],0.*z[:,0],z[:,0],color='k')\nplt.tight_layout()\nplt.savefig('data/condicion_inicial.png',dpi=300)\n\n\n#=====================================\n#wave gauges\n#=====================================\nb=[[1,0.,0],\\\n [2,3.,0.],\\\n [3,6.,0.]]\nf=open('data/gauges.dat','w')\nf.write('%i\\n'%len(b))\nfor i in range(len(b)):\n s='%i %.18e %.18e\\n'%(b[i][0],b[i][1],b[i][2])\n f.write(s)\nf.close()\n\n#=====================================\n#input.dat parameters\n#=====================================\ncaso=999\ntinit=-3.0\ntfinal=20.0\ncfl=.45\nnxi=x.shape[0]\nneta=y.shape[1]\nbatiopt=1\ninitqopt=1\n\ndxi=1.\ndeta=1.\nL=1.\nH=1.\nU=1.\nbcxi0=4\nif bcxi0==4:\n GA1=1\n if GA1==9 or GA1==1:\n Nsenal1=etaL.shape[0]\nbcxiN=1\nbceta0=1\nbcetaN=1\ndit=-1\ndtout=0.5\nkappa=1e-5\nrktype=1\nlimtype=1\nfricopt=0\noutopt=1\noutdir='results/'\n\n#---------write to file\nf=open('data/input.dat','w')\nf.write('%i'%caso)\nf.write('\\n%.8f'%tinit)\nf.write('\\n%.8f'%tfinal)\nf.write('\\n%.8f'%cfl)\nf.write('\\n%i'%nxi)\nf.write('\\n%i'%neta)\nf.write('\\n%i'%batiopt)\nfor i in range(len(batifiles)):\n f.write('\\n%s'%batifiles[i])\nf.write('\\n%i'%initqopt)\nfor i in range(len(initqfiles)):\n f.write('\\n%s'%initqfiles[i])\nf.write('\\n%.8f'%dxi)\nf.write('\\n%.8f'%deta)\nf.write('\\n%.8f'%L)\nf.write('\\n%.8f'%H)\nf.write('\\n%.8f'%U)\nf.write('\\n%i'%bcxi0)\nif bcxi0==4:\n f.write('\\n%i'%GA1)\n if GA1==9 or GA1==1:\n f.write('\\n%i'%Nsenal1)\nf.write('\\n%i'%bcxiN)\nf.write('\\n%i'%bceta0)\nf.write('\\n%i'%bcetaN)\nf.write('\\n%i'%dit)\nif dit==-1:\n f.write('\\n%.3f'%dtout)\nf.write('\\n%3.20e'%kappa)\nf.write('\\n%i'%rktype)\nf.write('\\n%i'%limtype)\nf.write('\\n%i'%fricopt)\nf.write('\\n%i'%outopt)\nf.write('\\n%s\\n'%outdir)\nf.close()\n","sub_path":"tests/test3_solitarywave/setrun.py","file_name":"setrun.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"90240645","text":"from collections import namedtuple\n\nimport pygame as pg\nimport pytweening as tween\nfrom pygame.math import Vector2\n\nfrom data.input_output import load_mod_data_kwargs\nfrom model import TimeAccess, GameObject\nfrom mods import Mod, BOB_RANGE, BOB_PERIOD, BOB_SPEED, ModData\nfrom view import images\n\nBaseItemData = namedtuple('BaseItemData', ('mod_data', 'image_file'))\n\n\nclass ItemData(BaseItemData):\n def __new__(cls, mod_label: str, image_file: str) -> None:\n mod_data = ModData(**load_mod_data_kwargs(mod_label))\n\n return super().__new__(cls, mod_data, image_file)\n\n\nclass ItemObject(GameObject, TimeAccess):\n \"\"\"A bobbing in-game object that can be picked up.\"\"\"\n\n def __init__(self, mod: Mod, pos: Vector2) -> None:\n self._class_initialized()\n super().__init__(pos)\n\n mygroups = [self.groups.all_sprites, self.groups.items]\n pg.sprite.Sprite.__init__(self, mygroups)\n\n self._base_rect = self.image.get_rect().copy()\n\n self._mod = mod\n self._tween = tween.easeInOutSine\n self._step = 0.0\n self._bob_direction = 1\n self._bob_range = BOB_RANGE\n self._bob_period = BOB_PERIOD\n self._bob_speed = BOB_SPEED\n\n @property\n def mod(self) -> Mod:\n return self._mod\n\n def update(self) -> None:\n # bobbing motion\n offset = self._bob_offset()\n self.pos.y += offset * self._bob_direction\n self._step += self._bob_speed\n if self._step > self._bob_period:\n self._step = 0.0\n self._bob_direction *= -1\n\n def _bob_offset(self) -> float:\n offset = self._bob_range * (\n self._tween(self._step / self._bob_period) - 0.5)\n return offset\n\n @property\n def rect(self) -> pg.Rect:\n self._base_rect.center = self.pos\n return self._base_rect\n\n @property\n def image(self) -> pg.Surface:\n raise NotImplementedError\n\n\nclass ItemFromData(ItemObject):\n def __init__(self, item_data: ItemData, pos: Vector2) -> None:\n mod = Mod(item_data.mod_data)\n self._image_file = item_data.image_file\n super().__init__(mod, pos)\n\n @property\n def image(self) -> pg.Surface:\n return images.get_image(self._image_file)\n","sub_path":"src/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"95062983","text":"import pygame\nimport sys\n\nif len(sys.argv) != 4:\n print('')\n print('Error! Expects exactly 3 command line arguments:')\n print(' 1. the number of doors in the experiment')\n print(' 2. the input filename')\n print(' 3. the output filename')\n exit()\n\nnum_doors = int(sys.argv[1] )\ninput_filename = sys.argv[2] \noutput_filename = sys.argv[3] \n\nmax_width = 1024\n\ndata = []\nwith open(input_filename, 'r') as fp:\n for line in fp:\n line = line.strip()\n if line == '':\n continue\n line_parts = line.split()\n if len(line_parts) < 2 or line_parts[0] != '[DOORS]':\n continue\n info_parts = line_parts[1].split(',')\n door_taken = int(info_parts[0])\n door_needed = int(info_parts[1])\n data.append([door_taken, door_needed])\n\nrect_width = 4\nrect_height = 4\nsurf_width = rect_width * len(data)\nif surf_width > max_width:\n surf_width = max_width\nsurf_height = rect_height * num_doors \n\npygame.init()\n\nsurf = pygame.Surface((surf_width, surf_height))\nfor idx in range(len(data)):\n x = idx * rect_width\n if x >= surf_width: \n break\n door_taken, door_needed = data[idx]\n for i in range(num_doors):\n pygame.draw.rect(surf, (50,50,50), \n (x + (rect_width // 4), i * rect_height + (rect_height // 4),\n rect_width // 2, rect_height // 2))\n if door_taken == door_needed:\n pygame.draw.rect(surf, (100,225,50), \n (x, door_taken * rect_height, rect_width, rect_height))\n else:\n pygame.draw.rect(surf, (225,100,25), \n (x, door_taken * rect_height, rect_width, rect_height))\n pygame.draw.rect(surf, (50,100,225), \n (x, door_needed * rect_height, rect_width, rect_height))\n\n\npygame.image.save(surf, output_filename)\n\n","sub_path":"MABE2_extras/scripts/visualization/eval_doors.py","file_name":"eval_doors.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"579467132","text":"import asyncio\nimport websockets\nimport json\n\nimport time\nimport logging\nimport sys\n\nimport my_data\nfrom derebit_ws import DeribitWS\n\n\n\nclass BasisTradingBot:\n '''\n Идея бота в том чтобы торговать относительно basisа,\n т.е. например купить и продать два фьючерса с одним\n и тем же базовым активом, но разной датой экспирации.\n Например купить ETH-PERPETUAL (long),\n одновременно с этим продав ETH-7MAY21 (short), так чтобы\n между ними была разница 20долларов, а потом сделать обратную сделку,\n когда разница между ними станет 5 долларов. Таким образом\n маржа будет 15 долларов.\n\n Пока предназначен одновременно только для двух пар.\n\n '''\n # TODO: 1) обработка ошибок\n # 2) обработка случая если ордер при карытии уже исполнился, \n # 3) обработка случая, когда ордер исполнился частично,\n # 4) сделать ассинхроннное выполнение запросов, посмотреть\n # возмодные точки оптимизации\n # 5) добавить логирование в телеграм бота\n # 6) добавить отчёт о совершённых сделках\n # 7) надо придумать как борорться с проскальзыванием между проверками.\n # 8) надо аккуратно заканчивать работу программы, т.к. сейчас она обрывается посреди действия.\n \n def __init__(self, data, ws):\n self.data = data\n self.ws = ws\n self.current_orders = {} # {pair: [order_info]}\n self.current_positions = {} # {pair: [positions]}\n\n logging.basicConfig(level=logging.INFO, filename='application',\n format='%(asctime)s %(levelname)s: %(message)s' )\n self.log = logging.getLogger(__name__)\n self.log.info(\"\\n\\n====================================================================\")\n self.log.info(\"Starting application\")\n\n def put_order(self):\n # TODO: сделать обработку ошибок,\n # добавлять открытые ордера в список.\n # ? сделать структуру для ордеров\n\n self.log.info('In put_order')\n\n bid_base, ask_base, err = self.ws.get_bid_ask(self.data['pair_base'])\n self.log.info(f'End get bid ask prices for base, err = {err}')\n\n # bid_second, ask_second, err = self.ws.get_bid_ask(self.data['pair_second'])\n # self.log.info(f'End get bid ask prices for second, err = {err}')\n \n\n amount = self.data['amount_second']\n pair = self.data['pair_second']\n\n side = self.data['side_second']\n basis = self.data['basis']\n # min_price_step = 0.05\n # Т.к. я делаю post_only заявку, то можно указать любую цену, она попадёт в стакан.\n if side == 'buy':\n order_price = bid_base + basis\n self.log.info(f'Set limit order: pair={pair}, side={side}, price={order_price}, amount={amount}; pair_base={self.data[\"pair_base\"]}: price={bid_base}')\n elif side == 'sell':\n order_price = ask_base + basis\n self.log.info(f'Set limit order: pair={pair}, side={side}, price={order_price}, amount={amount}; pair_base={self.data[\"pair_base\"]}: price={ask_base}')\n\n post_only = True\n reduce_only = False\n response, err = self.ws.limit_order(pair, amount, side, order_price, post_only, reduce_only)\n self.log.info(f'Make order, err={err}')\n\n order_id = response['result']['order']['order_id']\n order_price = response['result']['order']['price']\n order_info = {\n \"order_id\": order_id, \"order_price\": order_price, \"filled_amount\": 0.\n }\n self.current_orders[pair] = order_info\n\n return err\n\n def market_base(self, amount):\n self.log.info('Start making market order')\n\n pair_base = self.data['pair_base']\n # amount = self.data['amount_base']\n side = self.data['side_base']\n\n response, err = self.ws.market_order(pair_base, amount, side)\n self.log.info(f'End making market order, err={err} \\n\\t\\t\\t\\t\\t\\t\\t\\t Trade DONE amount {amount} out of {self.data[\"amount_base\"]}')\n \n pair_second = self.data['pair_second']\n order_price = self.current_orders[pair_second]['order_price']\n price_base = response['result']['order']['average_price']\n side_second = self.data['side_second']\n self.log.info(f'basis={round(order_price - price_base, 2)}; {side} {pair_base}: price={price_base}; {side_second} {pair_second}: price={order_price};')\n\n # Т.к. по сути ордер один, то можно закрывать бота.\n print(f'Trade done amount {amount} out of {self.data[\"amount_base\"]}')\n print(f'basis={round(order_price - price_base, 2)}; {side} {pair_base}: price={price_base}; {side_second} {pair_second}: price={order_price};')\n \n # Если исполнился частично, надо продолжить работу бота.\n if amount < self.data['amount_base']:\n self.data['amount_base'] -= amount\n self.data['amount_second'] -= amount\n return False, err\n return True, err # Работа бота завершена.\n\n def cancel_order(self, order_info):\n self.log.info('In cancel_order')\n order_id, amount_done = order_info['order_id'], order_info['filled_amount']\n response, err = self.ws.cancel_order(order_id)\n self.log.info(f'End cancelling order, err = {err}')\n\n # Знчит ордер сполнился полностью.\n if err == 'error':\n self.log.info('In cancel_order order fully filled')\n is_trade, err = self.market_base(self.data['amount_base'])\n return is_trade, err\n\n # Значит ордер частично исполнился.\n pair_second = self.data['pair_second']\n filled_amount = response['result']['filled_amount']\n if filled_amount > 0:\n self.log.info(f'In cancel_order order filled_amount={filled_amount}')\n self.log.info(response['result'])\n if self.current_orders[pair_second]['filled_amount'] < filled_amount:\n amount = filled_amount - self.current_orders[pair_second]['filled_amount']\n self.current_orders[pair_second]['filled_amount'] = filled_amount\n is_trade, err = self.market_base(amount)\n return is_trade, err\n return False, err\n\n def check_order(self):\n '''\n Если ордер выполнился, то требуется сделать симметричную\n сделку на основной паре. Закончить программу.\n Если цена на основной фьючерс изменилась достаточно\n сильно, то требуется закрыть отрытый ордер и открыть новый.\n \n \n '''\n # TODO: надо добавить асинхронное выполнение запроса цены и запроса инфы об ордере.\n self.log.info('In check_order')\n\n pair_base = self.data['pair_base']\n pair_second = self.data['pair_second']\n amount = self.data['amount_base']\n side = self.data['side_base']\n\n order_info = self.current_orders[pair_second]\n order_id, amount_done = order_info['order_id'], order_info['filled_amount']\n order_price = order_info['order_price']\n\n # Проверяем ордер.\n res_order_state, base_bid_ask, second_bid_ask = self.ws.execute_funcs(\n self.ws.get_order_state_async(order_id),\n self.ws.get_bid_ask_async(self.data['pair_base']),\n self.ws.get_bid_ask_async(self.data['pair_second'])\n )\n response, err_order_state = res_order_state\n bid_base, ask_base, err_base = base_bid_ask\n bid_second, ask_second, err_second = second_bid_ask\n err = err_base\n\n # self.log.info('Start check order state')\n # response, err = self.ws.get_order_state_async(order_id)\n self.log.info(f'End check order state of order={order_id}, err = {err_order_state}')\n self.log.info(f'End get bid ask prices for base, err = {err_base}')\n self.log.info(f'End get bid ask prices for second, err = {err_second}')\n\n price_base = bid_base if side == 'sell' else ask_base\n # price_second = bid_second if side == 'buy' else ask_second\n price_second = bid_second if side == 'sell' else ask_second\n self.log.info(f'==== Current basis = {round(price_second - price_base, 2)}' \\\n + f', base price={price_base}, order price={order_price}, diff={round(order_price - price_base, 2)} =====')\n\n order_state = response['result']['order_state']\n filled_amount = response['result']['filled_amount']\n\n # Ордер выполнился. Надо выполнить по маркету основной фьючерс.\n if filled_amount > 0:\n self.log.info(f'In check_order order filled_amount={filled_amount} out of {self.data[\"amount_second\"]}')\n self.log.info(response['result'])\n if self.current_orders[pair_second]['filled_amount'] < filled_amount:\n amount = filled_amount - self.current_orders[pair_second]['filled_amount']\n self.current_orders[pair_second]['filled_amount'] = filled_amount\n is_trade, err = self.market_base(amount)\n return is_trade, err\n\n # Ордер не выполнился. Надо проверить, требуется ли его переставить.\n else:\n self.log.info('Start check for resseting order')\n\n # Разница цены, при которой надо переставить ордер.\n max_price_diff_up = self.data['max_price_diff_up'] # Переставлять оредр, если текущий базис больше заданного. (Надо ставить больше при вхождении в позицию)\n max_price_diff_down = self.data['max_price_diff_down'] # Переставлять ордер, если текущий базис снизился на данное значение. (Надо ставить больше при выходже из позиции)\n # Если разница достаточно большая, то надо закрыть ордер и открыть заново.\n expr = (order_price - price_base <= self.data['basis'] - max_price_diff_down) \\\n or (order_price - price_base >= self.data['basis'] + max_price_diff_up)\n if expr:\n self.log.info('Start resetting order')\n is_trade, err = self.cancel_order(order_info)\n if is_trade:\n return True, err\n\n err = self.put_order()\n self.log.info('End resetting order')\n\n self.log.info('End check for resseting order')\n\n self.log.info('End check_order \\n')\n\n return False, err\n\n def close_bot(self):\n self.log.info('\\n')\n self.log.info('In close bot')\n self.log.info('Start closing bot')\n\n pair_second = self.data['pair_second']\n order_info = self.current_orders[pair_second]\n err = self.cancel_order(order_info)\n\n self.log.info(f'End closing bot, err={err}')\n\n\n def make_trade(self):\n self.log.info(\"In make_trade\")\n # Начальный ордер.\n err = self.put_order()\n\n trade_done = False\n while not trade_done:\n # start_time = time.time()\n trade_done, err = self.check_order()\n # end_time = time.time()\n # print(f'Work time = {(end_time - start_time)} seconds')\n # time.sleep(3)\n\n\ndef main():\n client_id = my_data.client_id\n client_secret = my_data.client_secret\n ws = DeribitWS(client_id, client_secret, test=False)\n\n # basis = 90 # При открытии позиции\n basis = 50 # При закрытии позиции, кратный 0.05\n\n pair_base = 'ETH-25JUN21' # Закрываем по маркету, цена должна быть ниже\n pair_second = 'ETH-24SEP21' # Выставляем лимитный ордер\n\n # buy/sell\n # side_base = 'buy'\n # side_second = 'sell'\n\n side_base = 'sell'\n side_second = 'buy'\n\n max_price_diff_up = 1.2 # Переставлять оредр, если текущий базис больше заданного. (Надо ставить больше при вхождении в позицию)\n max_price_diff_down = 5\n\n # Размер ордера в USDT\n amount = 3\n amount_base = amount\n amount_second = amount\n\n data = {}\n data['basis'] = basis \n data['pair_base'] = pair_base\n data['pair_second'] = pair_second\n data['side_base'] = side_base\n data['side_second'] = side_second\n data['amount_base'] = amount_base\n data['amount_second'] = amount_second\n data['max_price_diff_up'] = max_price_diff_up\n data['max_price_diff_down'] = max_price_diff_down\n\n trading_bot = BasisTradingBot(data, ws)\n try:\n trading_bot.make_trade()\n print('Bot closed because trade done')\n except KeyboardInterrupt:\n trading_bot.close_bot()\n print('\\nBot closed by KeyboardInterrupt')\n sys.exit(0)\n\n\nif __name__ == '__main__':\n\n main()","sub_path":"buy_sell_bot_v0.py","file_name":"buy_sell_bot_v0.py","file_ext":"py","file_size_in_byte":14226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"643334958","text":"#import os\n#import urllib.request\n#cdfgj = urllib.request.urlopen('http://www.cdlr.gov.cn/detailnoright.aspx?id=96391')\n#print(cdfgj.read(300).decode('gb2312'))\n#print(cdfgj.reason)\nimport scrapy\nfrom items import DmozItem\nclass MySpider(scrapy.Spider):\n name = 'cdlr.gov.cn'\n allowed_domains = ['http://cdlr.gov.cn']\n start_urls = ['http://www.cdlr.gov.cn/detailnoright.aspx?id=96391']\n\n def parse(self,response):\n for sel in response.xpath('//tr/td'):\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 print(item)\n yield item\n# filename = response.url.split(\"/\")[-2]\n# print('filename')\n# with open(filename, 'wb') as f:\n# f.write(response.body)\n\n\n\n","sub_path":"project/exec.py","file_name":"exec.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"619738754","text":"import fire\nimport os\nimport statistics\nimport sys\n\nimport pandas as pd\nimport numpy as np\nfrom fairness import results\nfrom fairness.data.objects.list import DATASETS, get_dataset_names\nfrom fairness.data.objects.ProcessedData import ProcessedData, TAGS, TRAINING_PERCENT\nfrom fairness.algorithms.list import ALGORITHMS\nfrom fairness.metrics.list import get_metrics\nfrom fairness.benchmark import run_eval_alg, write_alg_results # rewritten: create_detailed_file\n\nimport results_writing_new # newly added\nimport warnings\n\nfrom fairness.algorithms.ParamGridSearch import ParamGridSearch\n\nNUM_TRIALS_DEFAULT = 10\n\n# TAGS = [\"original\", \"numerical\", \"numerical-binsensitive\", \"categorical-binsensitive\"]\n# TRAINING_PERCENT = 2.0 / 3.0\n\nclass BalancedProcessedData(ProcessedData):\n def __init__(self, data_obj):\n self.data = data_obj\n self.dfs = dict((k, pd.read_csv(self.data.get_filename(k)))\n for k in TAGS)\n self.splits = dict((k, []) for k in TAGS)\n self.has_splits = False\n self.balanced_splits = self.splits\n self.has_balanced_splits = False\n \n \n def get_protected_idx(self):\n pd.read_csv(self.data.get_filename(k))\n \n \n def create_balanced_train_test_splits(self, num):\n if self.has_balanced_splits:\n return self.balanced_splits\n \n # get all the variables to balanced over\n balance_attr = self.data.sensitive_attrs.copy()\n balance_attr.append(self.data.class_attr)\n\n # merge them all into a single variable\n sensitive_vals = self.dfs['original'][balance_attr].astype(str).apply(lambda x: '_'.join(x), axis=1).values\n\n sensitive_levels = pd.unique(sensitive_vals)\n \n \n for i in range(0, num):\n # we first shuffle a list of indices so that each subprocessed data\n # is split consistently\n \n\n # create empty lists for each portion\n train_fraction = np.asarray([])\n test_fraction = np.asarray([])\n\n for cur_sensitive in sensitive_levels:\n # randomly split each value of the protected class \n c_attr_idx = np.where(sensitive_vals == cur_sensitive)[0]\n np.random.shuffle(c_attr_idx)\n\n split_ix = int(len(c_attr_idx) * .8)\n train_fraction = list(np.concatenate([train_fraction,c_attr_idx[:split_ix]]))\n test_fraction = list( np.concatenate([test_fraction,c_attr_idx[split_ix:]]))\n\n # for cur_sensitive in sensitive_levels:\n # # randomly split each value of the protected class \n # c_attr_idx = np.where(sensitive_vals.values == cur_sensitive)[0]\n # np.random.shuffle(c_attr_idx)\n\n # split_ix = int(len(c_attr_idx) * TRAINING_PERCENT)\n # train_fraction = np.concatenate([train_fraction,c_attr_idx[:split_ix]])\n # test_fraction = np.concatenate([test_fraction,c_attr_idx[split_ix:]])\n # TODO if multiple balances, get list for each interesection and randomly split each of those\n # appned all trains together and all tests together\n \n \n for (k, v) in self.dfs.items():\n train = self.dfs[k].iloc[train_fraction]\n test = self.dfs[k].iloc[test_fraction]\n self.balanced_splits[k].append((train, test))\n\n print(self.balanced_splits.keys())\n \n self.has_balanced_splits = True\n return self.balanced_splits\n\ndef get_algorithm_names():\n result = [algorithm.get_name() for algorithm in ALGORITHMS]\n print(\"Available algorithms:\")\n for a in result:\n print(\" %s\" % a)\n return result\n\ndef create_detailed_file(filename, dataset, sensitive_dict, tag):\n return results_writing_new.NewResultsFile(filename, dataset, sensitive_dict, tag)\n\ndef run(num_trials = NUM_TRIALS_DEFAULT, dataset = get_dataset_names(),\n algorithm = get_algorithm_names()):\n algorithms_to_run = algorithm\n\n print(\"Datasets: '%s'\" % dataset)\n for dataset_obj in DATASETS:\n if not dataset_obj.get_dataset_name() in dataset:\n continue\n\n print(\"\\nEvaluating dataset:\" + dataset_obj.get_dataset_name())\n\n processed_dataset = BalancedProcessedData(dataset_obj)\n train_test_splits = processed_dataset.create_balanced_train_test_splits(num_trials)\n\n all_sensitive_attributes = dataset_obj.get_sensitive_attributes_with_joint()\n for sensitive in all_sensitive_attributes:\n\n print(\"Sensitive attribute:\" + sensitive)\n\n detailed_files = dict((k, create_detailed_file(\n dataset_obj.get_results_filename(sensitive, k),\n dataset_obj,\n processed_dataset.get_sensitive_values(k), k))\n for k in train_test_splits.keys())\n\n for algorithm in ALGORITHMS:\n if not algorithm.get_name() in algorithms_to_run:\n continue\n\n print(\" Algorithm: %s\" % algorithm.get_name())\n print(\" supported types: %s\" % algorithm.get_supported_data_types())\n if algorithm.__class__ is ParamGridSearch:\n param_files = \\\n dict((k, create_detailed_file(\n dataset_obj.get_param_results_filename(sensitive, k,\n algorithm.get_name()),\n dataset_obj, processed_dataset.get_sensitive_values(k), k))\n for k in train_test_splits.keys())\n for i in range(0, num_trials):\n for supported_tag in algorithm.get_supported_data_types():\n train, test = train_test_splits[supported_tag][i]\n try:\n params, results, param_results = \\\n run_eval_alg(algorithm, train, test, dataset_obj, processed_dataset,\n all_sensitive_attributes, sensitive, supported_tag)\n except Exception as e:\n import traceback\n traceback.print_exc(file=sys.stderr)\n print(\"Failed: %s\" % e, file=sys.stderr)\n else:\n write_alg_results(detailed_files[supported_tag],\n algorithm.get_name(), params, i, results)\n if algorithm.__class__ is ParamGridSearch:\n for params, results in param_results:\n write_alg_results(param_files[supported_tag],\n algorithm.get_name(), params, i, results)\n\n print(\"Results written to:\")\n for supported_tag in algorithm.get_supported_data_types():\n print(\" %s\" % dataset_obj.get_results_filename(sensitive, supported_tag))\n\n for detailed_file in detailed_files.values():\n detailed_file.close()\n\nif __name__ == '__main__': \n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\")\n run(dataset = ['ricci'])","sub_path":"balanced_splits_original.py","file_name":"balanced_splits_original.py","file_ext":"py","file_size_in_byte":7525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"633342556","text":"# -*- coding: utf-8 -*-\n\"\"\" \n@Time : 2020/12/8 15:37\n@Author : liufubin\n@FileName: test_login_api.py\n@description: 登录接口\n\"\"\"\nimport pytest\nimport requests\nimport time\nfrom public_method.request_method import RequestMethod\n\n\nclass TestLogin(object):\n @staticmethod\n def login():\n registry_time = time.time() # 获取当前时间时间戳\n get_session, getresponse = RequestMethod.request_get_method( # 调获取code接口,会在redis中生成code码\n 'http://mom-test.simuwang.com/momapi/v1/system/userMgt/'\n 'getSmsCode?mobile=13055866827®isterOrNot=false&t={}'\n .format(registry_time))\n print(getresponse)\n print(get_session)\n cookie_value = 'JSESSIONID={}'.format(get_session['JSESSIONID'])\n # for codes in range(1000, 9999, 1):\n body = {'mobile': '13055866827', 'code': 4568}\n url = 'http://mom-test.simuwang.com/momapi/api/sms/login'\n header = {\"Content-Type\": \"application/json\", \"Cookie\": cookie_value}\n response = requests.post(url=url, headers=header, data=body)\n print(response.json())\n\n\nif __name__ == '__main__':\n TestLogin.login()\n","sub_path":"test_case/custom_system/china_resource/test_login_api.py","file_name":"test_login_api.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"433239632","text":"#Creates a pdf of a user inputted Songsterr tab\nimport pdfkit\nimport requests\nimport json\n\n\n#Displays tab title and artist to user\ndef loop(data):\n\tprint('%-62s' '%s' % ('Tab Title:', 'Artist:'))\n\ti = 1\n\tfor song in data:\n\t\tdigits = len(str(i))\n\t\tif digits == 1:\n\t\t\tprint(str(i) + '.' + '%-60s' '%s' % (song['title'], song['artist']['nameWithoutThePrefix']))\n\t\tif digits == 2:\n\t\t\tprint(str(i) + '.' + '%-59s' '%s' % (song['title'], song['artist']['nameWithoutThePrefix']))\n\t\tif digits == 3:\n\t\t\tprint(str(i) + '.' + '%-58s' '%s' % (song['title'], song['artist']['nameWithoutThePrefix']))\n\t\ti += 1\n\n#prompts user to enter song index and returns song id\ndef getSongId(data):\n\tindex = int(input('Please enter the number of the tab you want: ')) - 1\n\tsongID = data[index]['id']\n\treturn songID\n\n#Prompts user to input song title and formulates requestURL \n#also gets request and stores request data in json format and returns it\ndef getUserRequest():\n\tsong = input('Please input the title of the song you would like the tab for: ')\n\trequestURL = 'http://www.songsterr.com/a/ra/songs.json?pattern=' + str(song)\n\tresponse = requests.get(requestURL)\n\tdata = response.json()\n\treturn data\n\n#Creates URL as string given a song ID and returns it\ndef createSongURL(id):\n\tsongURL = 'http://www.songsterr.com/a/wa/song?id=' + str(id)\n\treturn songURL\n\n\n\ndata = getUserRequest()\nloop(data)\nsongID = getSongId(data)\nsongURL = createSongURL(songID)\nprint('Loading tab...')\npdfkit.from_url(songURL, 'out.pdf')\nprint('')\n","sub_path":"SRInterpreter.py","file_name":"SRInterpreter.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"172977402","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nfrom bubble_sort import bubble_sort\nall_data=[3,4,1,7,10,14,16,15,89,23,57,21,50,56,1]\n\n\ndef data_gen(t=0):\n\treturn bubble_sort(all_data)\n\n\nfig, ax = plt.subplots()\nx=[i for i in range(1,len(all_data)+1)]\ny=all_data\n#data1=[[i,j] for i,j in zip(x,y)]\nsca1 = ax.scatter(x,y)\n#ax.grid()\n\t\ndef init():\n\tdata1=[[i,j] for i,j in zip(x,y)]\n\tsca1.set_offsets(data1)\n\treturn sca1\n\n\n\ndef run(data):\n # update the data\n\ty=data\n\tprint(y)\n\tsca1.set_offsets([[i,j] for i,j in zip(x,y)])\n\treturn sca1\n\nani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=1000,\n repeat=False, init_func=init)\nplt.show()\n\n\n\n\n","sub_path":"sorts/bubble_sort_plot.py","file_name":"bubble_sort_plot.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"280680673","text":"import cv2\nimport os\n\nclass process_unit:\n def __init__(self):\n self.video = None\n self.video_path = None\n if os.path.exists('./frames'):\n self.frame_path = './frames/'\n else:\n self.frame_path = None\n self.frames = []\n\n def read_video(self, path):\n self.video = cv2.VideoCapture(path)\n self.video_path = path\n\n def make_frames(self):\n if self.video is not None:\n success, image = self.video.read()\n count = 0\n self.frame_path = \"./frames/\"\n while success:\n success, image = self.video.read()\n cv2.imwrite(\"./frames/%d.jpg\" % count, image)\n count += 1\n print(\"count: %d\" % count)\n else:\n print('read video first!')\n\n def read_frames(self):\n if self.frame_path is not None:\n for (dirpath, dirnames, filenames) in os.walk(self.frame_path):\n filenames.sort(key=lambda x: int(os.path.splitext(x)[0]))\n for name in filenames:\n full_path = self.frame_path+name\n self.frames.append(full_path)\n break\n else:\n return\n\nif __name__ == '__main__':\n test = process_unit()\n test.read_video('./5.mp4')\n test.make_frames()","sub_path":"script/process_unit.py","file_name":"process_unit.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"328901896","text":"import time\n\n###########################\n# 工具类\n# 数据库常量信息\n#\n#\n##############################\n\nweibo_tbl=\"vt_info_niuren\"\nweibo_columes=\"id,name,createtime,content,source,headimg,contentimg\"\n\ntwitter_tbl=\"vt_info_niuren\"\ntwitter_columes=\"id,name,createtime,content,source\"\n\nkuaixun_tbl=\"vt_info_news\"\nkuaixun_columes=\"id,createtime,content,sourceurl,source\"\n\n\n\ntoutiao_tbl=\"vt_info_block_news\"\ntoutiao_columes=\"title,author,newstime,newsuri\"\n\nqukuaiwang_tbl=\"vt_info_block_news\"\nqukuaiwang_columes=\"title,author,newstime,newsuri,img,viewcount\"\n\n\n\nqukuaiwang_detail_tbl=\"vt_info_block_news_detail\"\nqukuaiwang_detail_columes=\"title,author,content,images\"\n# host='localhost'\n# user='root'\n# passwd=''\n# database='test'\n\nhost='120.79.34.242'\nuser='vt_dev'\npasswd='vt_dev__2018~*!#$'\ndatabase='virtualTrade'\n\n\ndef gettoday():\n return time.strftime('%Y-%m-%d', time.localtime())\n\n\nif __name__==\"__main__\":\n print(gettoday())\n\n\n\n\n","sub_path":"spiders/spiders/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"113327599","text":"import pysam\n\n# Class representing a reference genome build\nclass Reference(object):\n\n # Constructor\n def __init__(self, fastafile):\n self.ref_tabix = pysam.Fastafile(fastafile)\n\n # Read reference sequence of a given genomic region\n def read(self, *arg):\n if len(arg) == 3: chrom, start, end = arg[0], arg[1], arg[2]\n elif len(arg) == 1:\n chrom, pos = arg[0].split(':')\n if '-' in pos: [start, end] = pos.split('-')\n else: start, end = pos, pos\n else:\n return None\n chrom, start, end = str(chrom), int(start), int(end)\n\n goodchrom = chrom\n if not goodchrom in self.ref_tabix.references:\n goodchrom = 'chr' + chrom\n if not goodchrom in self.ref_tabix.references:\n if chrom == 'MT':\n goodchrom = 'chrM'\n if goodchrom not in self.ref_tabix.references:\n return None\n else:\n return None\n\n if end < start: return ''\n if start < 0: start = 1\n\n if pysam.__version__ in ['0.7.7', '0.7.8', '0.8.0']: last = self.ref_tabix.getReferenceLength(goodchrom)\n else: last = self.ref_tabix.get_reference_length(goodchrom)\n\n if end > last: end = last\n\n seq = self.ref_tabix.fetch(goodchrom, start - 1, end)\n return str(seq.upper().decode(\"utf-8\"))\n\n\n\n\n","sub_path":"compareensts_/reference.py","file_name":"reference.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"228200049","text":"class Solution(object):\n def shortestDistance(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n X,Y = len(grid), len(grid[0])\n reachCnt = [[0] * Y for _ in range(X)]\n totalDis = [[0] * Y for _ in range(X)]\n \n def isValid(x,y): return 0<=x \n# meaning that we will have a total of 7 bits, which each of these bits will inform the following function\n# if the user requested to see the specific data(described by that bit) on the output string.\n\ndef choose_output(x, y, z, r, az, reflectivity, time, output_flag):\n\n output_str = ''\n # means that bit is \"on\"\n if output_flag & 64 == 64:\n output_str = output_str + \"%12s\" % x\n # means that bit is \"on\"\n if output_flag & 32 == 32:\n output_str = output_str + \"%12s\" % y\n # means that bit is \"on\"\n if output_flag & 16 == 16:\n output_str = output_str + \"%12s\" % z\n # means that bit is \"on\"\n if output_flag & 8 == 8:\n output_str = output_str + \"%12s\" % r\n # means that bit is \"on\"\n if output_flag & 4 == 4:\n output_str = output_str + \"%12s\" % az\n # means that bit is \"on\"\n if output_flag & 2 == 2:\n output_str = output_str + \"%12s\" % reflectivity\n # means that bit is \"on\"\n if output_flag & 1 == 1:\n output_str = output_str + \"%20s\" % time\n output_str = output_str + '\\n'\n return output_str\n","sub_path":"code/choose_output.py","file_name":"choose_output.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"598737692","text":"''' A `Candlestick chart`_ based on stock price data. This example demonstrates\ncombining multiple glyphs.\n\n.. bokeh-example-metadata::\n :sampledata: stocks\n :apis: bokeh.plotting.figure.segment, bokeh.plotting.figure.vbar\n :keywords: candlestick\n\n.. _Candlestick chart: https://en.wikipedia.org/wiki/Candlestick_chart\n\n'''\nimport pandas as pd\n\nfrom bokeh.plotting import figure, show\nfrom bokeh.sampledata.stocks import MSFT\n\ndf = pd.DataFrame(MSFT)[60:120]\ndf[\"date\"] = pd.to_datetime(df[\"date\"])\n\ninc = df.close > df.open\ndec = df.open > df.close\nw = 16*60*60*1000 # milliseconds\n\nTOOLS = \"pan,wheel_zoom,box_zoom,reset,save\"\n\np = figure(x_axis_type=\"datetime\", tools=TOOLS, width=1000, height=400,\n title=\"MSFT Candlestick\", background_fill_color=\"#efefef\")\np.xaxis.major_label_orientation = 0.8 # radians\n\np.segment(df.date, df.high, df.date, df.low, color=\"black\")\n\np.vbar(df.date[dec], w, df.open[dec], df.close[dec], color=\"#eb3c40\")\np.vbar(df.date[inc], w, df.open[inc], df.close[inc], fill_color=\"white\",\n line_color=\"#49a3a3\", line_width=2)\n\nshow(p)\n","sub_path":"examples/topics/timeseries/candlestick.py","file_name":"candlestick.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"435114962","text":"import discord\nfrom discord import Server\nfrom discord import Client\nfrom discord.ext import commands\nfrom discord.ext.commands import Bot\nimport asyncio\n\nbot = commands.Bot(command_prefix='$')\nkey = open('testkey.txt').readline().rstrip('\\n')\nmessages = [\"$$a flcl\",\"$$a \",\"$$a mha\",\"https://osu.ppy.sh/beatmapsets/717528#osu/1515830\",\"https://osu.ppy.sh/beatmapsets/591442\",\"https://osu.ppy.sh/beatmapsets/1#osu/1\",\"$$v remo con || wan opo\",\"$$v a || yunosuke\",\"$$v s || lazy\",\"$$v a || sdnjsb\", \"$$v s || gjdgjksd\",\"$$v s || catlife\",\"$$v undead enemy\",\"$$v a || \",\"$$v s || \"]\nloopvalue = 0\n\n@bot.event\nasync def on_ready():\n print('Logged in as')\n print(bot.user.name)\n print(bot.user.id)\n print('-------')\n #\n #tests begin here\n #\n global chan\n chan = bot.get_channel('431806042377289739')\n\n@bot.event\nasync def on_message(message):\n global loopvalue\n if message.author.id != bot.user.id:\n if message.content == \"reset\":loopvalue=0\n else:\n await bot.send_message(chan, messages[loopvalue])\n loopvalue += 1\n await bot.process_commands(message)\n\n\n\nbot.run(key)\n","sub_path":"test-bot.py","file_name":"test-bot.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"487611927","text":"'''\nДаны длины сторон треугольника. Вычислите площадь треугольника.\n'''\nfrom math import sqrt\n\na = int(input('a: '))\nb = int(input('b: '))\nc = int(input('c: '))\n\np = (a + b + c) / 2\ns = sqrt(p * (p - a) * (p - b) * (p - c))\nprint(round(s, 3))","sub_path":"mccme/05-float/05-04.py","file_name":"05-04.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"74775909","text":"import copy\n\nimport torch\nimport torch.nn as nn\n\nfrom .attention import attention\nfrom .resnet import BasicBlock, ResNet\n\nmodel_urls = {\n \"resnet18\": \"https://download.pytorch.org/models/resnet18-5c106cde.pth\",\n \"resnet34\": \"https://download.pytorch.org/models/resnet34-333f7ec4.pth\",\n \"resnet50\": \"https://download.pytorch.org/models/resnet50-19c8e357.pth\",\n}\n\n\nclass ResAtt(ResNet):\n\n # def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,\n # groups=1, width_per_group=64, replace_stride_with_dilation=None,\n # norm_layer=None, in_channels=3):\n def __init__(self):\n super(ResAtt, self).__init__(\n block=BasicBlock, layers=[2, 2, 2, 2], in_channels=3, num_classes=1000\n )\n # state_dict = load_state_dict_from_url(model_urls['resnet18'])\n # self.load_state_dict(state_dict)\n\n self.att12 = attention(channels=64, block=BasicBlock, depth=2)\n self.att23 = attention(channels=128, block=BasicBlock, depth=1)\n self.att34 = attention(channels=256, block=BasicBlock, depth=0)\n # self.fc = nn.Linear(512, 7)\n\n # self.init_att()\n # self.init_mask()\n\n def init_att(self):\n self.att12._trunk1 = copy.deepcopy(self.layer1[1])\n self.att12._trunk2 = copy.deepcopy(self.layer1[1])\n\n self.att23._trunk1 = copy.deepcopy(self.layer2[1])\n self.att23._trunk2 = copy.deepcopy(self.layer2[1])\n\n self.att34._trunk1 = copy.deepcopy(self.layer3[1])\n self.att34._trunk2 = copy.deepcopy(self.layer3[1])\n\n def init_mask(self):\n self.att12._enc = copy.deepcopy(self.layer1[1])\n self.att12._dec = copy.deepcopy(self.layer1[1])\n\n self.att23._enc1 = copy.deepcopy(self.layer2[1])\n self.att23._enc2 = copy.deepcopy(self.layer2[1])\n self.att23._dec = copy.deepcopy(self.layer2[1])\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.att12(x)\n x = self.layer2(x)\n x = self.att23(x)\n x = self.layer3(x)\n x = self.att34(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = torch.flatten(x, 1)\n\n x = self.fc(x)\n return x\n\n\ndef resatt18(pretrained=True, progress=True, **kwargs):\n model = ResAtt()\n model.fc = nn.Linear(512, 7)\n return model\n","sub_path":"models/resatt.py","file_name":"resatt.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"634244218","text":"'''\nWrite a program to\n\n1. take min,max from user\n2. find all primes in the range\n3. find their sum and average\n4. repeat if user needs\n\n'''\n\nimport maths\nimport primes\nimport consoleutils\n\ndef main():\n run=True\n while run:\n min=consoleutils.read_int('min',2)\n max=consoleutils.read_int('max',100)\n primelist=primes.prime_range(min,max)\n tot=maths.sum(*primelist)\n avg=maths.average(*primelist)\n\n print('primes is range {}-{} are {}'.format(min,max,primelist))\n print('sum of all primes is {}'.format(tot))\n print('average of all primes is {}'.format(avg))\n\n run=consoleutils.read_bool('repeat','yes')\n\n\n\n \n\nmain()\n\n","sub_path":"module-demo-01/app-main-1.py","file_name":"app-main-1.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"53673027","text":"# 根据设备启动信息,通过pytest.main来收集并执行用例。\nimport os\n\nimport pytest\n\n\"\"\"\n参考连接地址:http://testingpai.com/article/1595507151237\nappium+pytest+allure+jenkins 如何实现多台手机连接\n本贴最后更新于 265 天前,其中的信息可能已经渤澥桑田\n使用 appium 可以实现 app 自动化测试,我们之前是连接一台手机去运行,如何同时连接多台手机呢?很多人可能想到的是多线程(threading)。\n今天分享一种比多线程更简单的方法,虽然不是多台手机同时运行,但可以连接多台手机依次运行,\n大致的运行方式是:001 号测试用例:A 手机,B 手机...,002 号测试用例:A 手机,B 手机...\n\n结语\npytest 中 fixture 的参数化虽然能够实现多台手机同时连接,但是运行并不是同时的,\n因为 request.param 读取参数列表是遍历读取的,所以造成了一个测试用例,手机 A 先执行,手机 B 后执行(假设 params=[\"手机 A\", \"手机 B\"]),\n要想真正做到多台手机同时运行,就要用到多线程\n\n\"\"\"\n\nreports_dir = './allure-report'\ndef run_cases(device):\n \"\"\"\n 参数:device为设备启动参数。在pytest.main当中,传递给--cmdopt选项。\n \"\"\"\n print([\"-s\", \"-v\", \"--cmdopt={}\".format(device)])\n reports_path = os.path.join(reports_dir,\"test_result_{}_{}.html\".format(device[\"caps\"][\"deviceName\"], device[\"port\"]))\n pytest.main([\"-s\", \"-v\",\n \"--cmdopt={}\".format(device),\n \"--html={}\".format(reports_path)])","sub_path":"main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"454092665","text":"import openpyxl\nimport datetime\nfrom datetime import date, timedelta\nfrom dateutil import parser\notchet = openpyxl.load_workbook('Zott - 14.05.xlsx')\nmoscow = openpyxl.load_workbook('Zott.xlsx')\nsaint_p = openpyxl.load_workbook('07.05-13.05.18_ZOTT_ОТЧЕТ _СПб.xlsx')\notchet_1 = openpyxl.load_workbook('Zott - 14.05 (копия).xlsx', data_only=True)\n\n\nvictoria_1 = otchet_1['Виктория']\nlenta_1 = otchet_1['Лента']\nglobus_1 = otchet_1['ГиперГлобус']\nkarusel_1 = otchet_1['Карусель']\nmetro_1 = otchet_1['Метро']\nperek_1 = otchet_1['Перекрёсток']\nokay_1 = otchet_1['Окей']\nlenta_s1 = otchet_1['Лента СПб']\nkarusel_s1 = otchet_1['Карусель СПб']\nmetro_s1 = otchet_1['Метро СПб']\nlime_s1 = otchet_1['Лайм СПб']\nspar_s1 = otchet_1['Спар СПб']\nokay_s1 = otchet_1['Окей СПб']\nauchan_reg1 = otchet_1['Ашан Регион']\nlenta_reg1 = otchet_1['Лента Регион']\nmetro_reg1 = otchet_1['Метро Регион']\n\n\n\nvictoria = otchet['Виктория']\nvictoria_m = moscow['Виктория']\nresult = otchet['Отчёт']\n\ntoday = date.today()\nfriday = date.today() - timedelta(3)\nresult.cell(row = 2, column = 3, value = today)\n#print(yesterday.strftime('%d.%m.%y'))\n#print(victoria.cell(row=26,column=13).value)\n\n\nfor i in range (2,28):\n victoria.cell(row=i, column = 13, value = victoria_m.cell(row=i, column=5).value.date())\n#lenta.cell(row=65, column=30, value='=COUNTIF(O3:O62'+',\"='+ yesterday.strftime('%d.%m.%y')+'\"')\n\nfor k in range (2,28):\n for m in range(15,26):\n victoria.cell(row=k, column=m, value=victoria_m.cell(row=k,column=m-8).value)\n victoria_1.cell(row=k, column=m, value=victoria_m.cell(row=k,column=m-8).value)\n\n\n\n#проверка комментов\n\nlenta = otchet['Лента']\nlenta_m = moscow['Лента']\n\nfor j in range (2,11):\n lenta.cell(row=j, column=13, value = lenta_m.cell(row=j, column=5).value.date())\n\nfor l in range (2,11):\n for a in range (15,22):\n lenta.cell(row=l, column=a, value = lenta_m.cell(row=l, column=a-8).value)\n lenta_1.cell(row=l, column=a, value = lenta_m.cell(row=l, column=a-8).value)\n\nglobus = otchet['ГиперГлобус']\nglobus_m = moscow['ГиперГлобус']\n\nfor b in range (2,8):\n globus.cell(row=b, column=13, value=globus_m.cell(row=b, column=5).value.date())\n\nfor c in range (2,8):\n for i in range (15,22):\n globus.cell(row=c, column=i, value=globus_m.cell(row=c, column=i-8).value)\n globus_1.cell(row=c, column=i, value=globus_m.cell(row=c, column=i-8).value)\n\n\nkarusel = otchet['Карусель']\nkarusel_m = moscow['Карусель']\n\nfor b in range (2,23):\n karusel.cell(row=b, column=12, value=karusel_m.cell(row=b, column=5).value.date())\n\nfor c in range (2,23):\n for i in range (14,26):\n karusel.cell(row=c, column=i, value=karusel_m.cell(row=c, column=i-7).value)\n karusel_1.cell(row=c, column=i, value=karusel_m.cell(row=c, column=i-7).value)\n\n\nmetro = otchet['Метро']\nmetro_m = moscow['Метро']\n\nfor b in range (2,20):\n metro.cell(row=b, column=13, value=metro_m.cell(row=b, column=5).value.date())\n\nfor c in range (2,20):\n for i in range (15,31):\n metro.cell(row=c, column=i, value=metro_m.cell(row=c, column=i-8).value)\n metro_1.cell(row=c, column=i, value=metro_m.cell(row=c, column=i-8).value)\n\n\nperek = otchet['Перекрёсток']\nperek_m = moscow['Перекрёсток']\n\nfor b in range (2,80):\n perek.cell(row=b, column=13, value=perek_m.cell(row=b, column=6).value.date())\n\nfor c in range (2,80):\n for i in range (15,21):\n perek.cell(row=c, column=i, value=perek_m.cell(row=c, column=i-8).value)\n perek_1.cell(row=c, column=i, value=perek_m.cell(row=c, column=i-8).value)\n\nokay = otchet['Окей']\nokay_m = moscow['Окей']\n\nfor b in range (2,11):\n okay.cell(row=b, column=13, value=okay_m.cell(row=b, column=5).value.date())\n\nfor c in range (2,11):\n for i in range (15,20):\n okay.cell(row=c, column=i, value=okay_m.cell(row=c, column=i-8).value)\n okay_1.cell(row=c, column=i, value=okay_m.cell(row=c, column=i-8).value)\n\n\nlentaspb = otchet['Лента СПб']\nlenta_s = saint_p['Лента СПб']\n\nfor i in range(2,30):\n lentaspb.cell(row=i, column = 13, value = friday)\n\nfor c in range (2,30):\n for i in range (15,22):\n lentaspb.cell(row=c, column=i, value=lenta_s.cell(row=c, column=i-1).value)\n\nkaruselspb = otchet['Карусель СПб']\nkarusel_s = saint_p['Карусель СПб']\n\nfor i in range(2,16):\n karuselspb.cell(row=i, column = 13, value = friday)\n\nfor c in range (2,16):\n for i in range (15,26):\n karuselspb.cell(row=c, column=i, value=karusel_s.cell(row=c, column=i-1).value)\n\nmetrospb = otchet['Метро СПб']\nmetro_s = saint_p['Метро СПб']\n\nfor i in range(2,5):\n metrospb.cell(row=i, column = 13, value = friday)\n\nfor c in range (2,5):\n for i in range (15,31):\n metrospb.cell(row=c, column=i, value=metro_s.cell(row=c, column=i-1).value)\n\nlime = otchet['Лайм СПб']\nlime_s = saint_p['Лайм СПб']\n\nfor i in range(2,13):\n lime.cell(row=i, column = 13, value = friday)\n\nfor c in range (2,13):\n for i in range (15,25):\n lime.cell(row=c, column=i, value=lime_s.cell(row=c, column=i-1).value)\n\nspar = otchet['Спар СПб']\nspar_s = saint_p['Спар СПб']\n\nfor i in range(2,18):\n spar.cell(row=i, column = 13, value = friday)\n\nfor c in range (2,18):\n for i in range (15,22):\n spar.cell(row=c, column=i, value=spar_s.cell(row=c, column=i-1).value)\n\nokayspb = otchet['Окей СПб']\nokay_s = saint_p['ОКЕЙ']\n\nfor i in range(2,23):\n okayspb.cell(row=i, column = 13, value = friday)\n\nfor c in range (2,23):\n for i in range (15,20):\n okayspb.cell(row=c, column=i, value=okay_s.cell(row=c, column=i+4).value)\n\nauchan = otchet['Ашан Регион']\nauchan_m = moscow['Ашан Регион']\n#print (auchan_m.cell(row=2, column=6).value)\n\nfor b in range (2,10):\n auchan.cell(row=b, column=13, value=auchan_m.cell(row=b, column=6).value.date())\n\nfor c in range (2,10):\n for i in range (15,24):\n auchan.cell(row=c, column=i, value=auchan_m.cell(row=c, column=i-7).value)\n\n\nlentaregion = otchet['Лента Регион']\nlenta_reg = moscow['Лента Регион']\n\nfor b in range (2,21):\n lentaregion.cell(row=b, column=13, value=lenta_reg.cell(row=b, column=6).value.date())\n\nfor c in range (2,21):\n for i in range (15,22):\n lentaregion.cell(row=c, column=i, value=lenta_reg.cell(row=c, column=i-7).value)\n\nmetroregion = otchet['Метро Регион']\nmetro_reg = moscow['Метро Регион']\n\nfor b in range (2,9):\n metroregion.cell(row=b, column=13, value=metro_reg.cell(row=b, column=7).value.date())\n\nfor c in range (2,9):\n for i in range (15,31):\n metroregion.cell(row=c, column=i, value=metro_reg.cell(row=c, column=i-6).value)\n\nfor i in range (2,28):\n count=0\n count1=0\n for j in range (15,26):\n if victoria_1.cell(row=i, column=j).value == 'х':\n count+=1\n victoria_1.cell(row=i, column=14, value=11-count)\n elif victoria_1.cell(row=i, column=j).value==1:\n count1+=1\n victoria_1.cell(row=i, column=26, value=count1)\n\nfor g in range (2,28):\n victoria_1.cell(row=g, column=27, value= victoria_1.cell(row=g, column=26).value / victoria_1.cell(row=g, column=14).value)\n\n\nfor i in range (2,28):\n victoria.cell(row=i, column=28, value= victoria_m.cell(row=i,column=20).value)\n\nfor j in range(2,28):\n if victoria.cell(row=j, column=28).value==None and victoria_1.cell(row=j, column=27).value<1:\n victoria.cell(row=j, column=28).value = 'Ожидается поставка с' + ' ' + str(today)\n\nfor i in range (2,11):\n count=0\n count1=0\n for j in range (15,22):\n if lenta_1.cell(row=i, column=j).value == 'х':\n count+=1\n lenta_1.cell(row=i, column=14, value=7-count)\n elif lenta_1.cell(row=i, column=j).value==1:\n count1+=1\n lenta_1.cell(row=i, column=22, value=count1)\n\nfor g in range (2,11):\n lenta_1.cell(row=g, column=23, value= lenta_1.cell(row=g, column=22).value / lenta_1.cell(row=g, column=14).value)\n\n\nfor i in range (2,11):\n lenta.cell(row=i, column=24, value= lenta_m.cell(row=i,column=16).value)\n\n\nfor j in range (2,11):\n if lenta.cell(row=j, column=24).value==None and lenta_1.cell(row=j, column=23).value<1:\n lenta.cell(row=j, column=24, value='Ожидается поставка с' + ' ' + str(today))\n\nfor i in range (2,8):\n count=0\n count1=0\n for j in range (15,22):\n if globus_1.cell(row=i, column=j).value == 'х':\n count+=1\n globus_1.cell(row=i, column=14, value=11-count)\n elif globus_1.cell(row=i, column=j).value==1:\n count1+=1\n globus_1.cell(row=i, column=22, value=count1)\n\nfor g in range (2,8):\n globus_1.cell(row=g, column=23, value= globus_1.cell(row=g, column=22).value / globus_1.cell(row=g, column=14).value)\n\nfor i in range (2,11):\n globus.cell(row=i, column=24, value= lenta_m.cell(row=i,column=16).value)\n\nfor i in range (2,8):\n if globus.cell(row=i, column=24).value==None and globus_1.cell(row=i, column=23).value<1:\n globus.cell(row=j, column=24, value='Ожидается поставка с' + ' ' + str(today))\n\nfor i in range (2,23):\n count=0\n count1=0\n for j in range (14,26):\n if karusel_1.cell(row=i, column=j).value == 'х':\n count+=1\n karusel_1.cell(row=i, column=13, value=12-count)\n elif karusel_1.cell(row=i, column=j).value==1:\n count1+=1\n karusel_1.cell(row=i, column=26, value=count1)\n\nfor g in range (2,23):\n karusel_1.cell(row=g, column=27, value= karusel_1.cell(row=g, column=26).value / karusel_1.cell(row=g, column=13).value)\n\nfor i in range (2,23):\n karusel.cell(row=i, column=28, value= lenta_m.cell(row=i,column=21).value)\n\nfor i in range (2,23):\n if karusel.cell(row=i, column=28).value==None and karusel_1.cell(row=i, column=27).value<1:\n karusel.cell(row=j, column=28, value='Ожидается поставка с' + ' ' + str(today))\n\nfor i in range (2,20):\n count=0\n count1=0\n for j in range (15,31):\n if metro_1.cell(row=i, column=j).value == 'х':\n count+=1\n metro_1.cell(row=i, column=14, value=16-count)\n elif metro_1.cell(row=i, column=j).value==1:\n count1+=1\n metro_1.cell(row=i, column=31, value=count1)\n\nfor g in range (2,20):\n metro_1.cell(row=g, column=32, value= metro_1.cell(row=g, column=31).value / metro_1.cell(row=g, column=14).value)\n\nfor i in range (2,20):\n metro.cell(row=i, column=33, value= lenta_m.cell(row=i,column=25).value)\n\nfor i in range (2,20):\n if metro.cell(row=i, column=33).value==None and metro_1.cell(row=i, column=32).value<1:\n metro.cell(row=j, column=33, value='Ожидается поставка с '+ str(today))\n\nfor i in range (2,80):\n count=0\n count1=0\n for j in range (15,21):\n if perek_1.cell(row=i, column=j).value == 'х':\n count+=1\n perek_1.cell(row=i, column=14, value=6-count)\n elif perek_1.cell(row=i, column=j).value==1:\n count1+=1\n perek_1.cell(row=i, column=21, value=count1)\n\nfor g in range (2,80):\n perek_1.cell(row=g, column=22, value= perek_1.cell(row=g, column=21).value / perek_1.cell(row=g, column=14).value)\n\nfor i in range (2,80):\n perek.cell(row=i, column=23, value= lenta_m.cell(row=i,column=15).value)\n\nfor i in range (2,80):\n if perek.cell(row=i, column=23).value==None and perek_1.cell(row=i, column=22).value<1:\n perek.cell(row=j, column=23, value='Ожидается поставка с '+ str(today))\n\nfor i in range (2,11):\n count=0\n count1=0\n for j in range (15,20):\n if okay_1.cell(row=i, column=j).value == 'х':\n count+=1\n okay_1.cell(row=i, column=14, value=5-count)\n elif okay_1.cell(row=i, column=j).value==1:\n count1+=1\n okay_1.cell(row=i, column=20, value=count1)\n\nfor g in range (2,11):\n okay_1.cell(row=g, column=21, value= okay_1.cell(row=g, column=20).value / okay_1.cell(row=g, column=14).value)\n\nfor i in range (2,11):\n okay.cell(row=i, column=22, value= lenta_m.cell(row=i,column=14).value)\n\n#print(okay_1.cell(row=2, column=21).value)\nfor i in range (2,11):\n if okay.cell(row=i, column=22).value==None and okay_1.cell(row=i, column=21).value<1:\n okay.cell(row=j, column=22, value='Ожидается поставка с '+ str(today))\n\nprint((victoria_1.cell(row=24, column=27).value))\n\n\n#print(lenta.cell(row=38, column=15).value.date())\notchet_1.save('test.xlsx')\notchet.save('zott' + str(today) + '.xlsx')\n\n#test_parser = parser.parse(lenta.cell(row=38, column=15).value, dayfirst=True)\n#print(test_parser)\n#lenta.cell(row=7, column =15, value = str(lenta.cell(row=7, column=15).value[1:]))\n\n#for l in range (3,30):\n# print(lenta_m.cell(row=l, column=7).value.strftime(\"%d.%m.%y\"))\n\n#print(type(lenta_m.cell(row=3, column=7).value))\n\n\n\n\n#dates_lenta_m=[]\n#for l in range (2,30):\n #dates_lenta_m+= datetime.strptime(lenta_m.cell(row=l, column=7).value.strftime(\"%d.%m.%Y\"),'%d.%m.%Y')\n #print(dates_lenta_m)\n","sub_path":"auto_zott.py","file_name":"auto_zott.py","file_ext":"py","file_size_in_byte":13414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"92594376","text":"import math\nimport logging\nfrom collections import Counter\n\ndef smooth_bleu_stats(hypothesis, reference):\n yield len(hypothesis)\n yield len(reference)\n for n in xrange(1, 5):\n s_ngrams = Counter(tuple(hypothesis[i:i+n]) for i in xrange(len(hypothesis)+1-n))\n r_ngrams = Counter(tuple(reference[i:i+n]) for i in xrange(len(reference)+1-n))\n yield sum((s_ngrams & r_ngrams).itervalues()) + 1\n yield max(len(hypothesis)+1-n, 0) + 1\n\n\ndef smooth_bleu(hypothesis, reference):\n stats = list(smooth_bleu_stats(hypothesis.split(), reference.split()))\n assert all(v != 0 for v in stats)\n (c, r) = stats[:2]\n log_bleu_prec = sum([math.log(float(x)/y) for x,y in zip(stats[2::2],stats[3::2])]) / 4.\n return math.exp(min([0, 1-float(r)/c]) + log_bleu_prec)\n\ntry:\n import meteor_api\n meteor_api.initVM(maxheap='2g')\nexcept ImportError:\n pass\n\nMETEOR_PARAPHRASE='/home/vchahune/projects/sp2013.11-731/hw4/meteor-1.4/data/paraphrase-en.gz'\nclass MeteorScorer:\n def __init__(self):\n logging.info('Loading the METEOR English scorer')\n config = meteor_api.MeteorConfiguration()\n config.setLanguage('en')\n config.setParaFileURL(meteor_api.URL('file:'+METEOR_PARAPHRASE))\n self.meteor_scorer = meteor_api.MeteorScorer(config)\n\n def stats(self):\n return MeteorStats()\n\n def score(self, hypothesis, reference):\n return MeteorStats(self.meteor_scorer.getMeteorStats(hypothesis, reference))\n\n def update(self, stats):\n self.meteor_scorer.computeMetrics(stats.stats)\n\nclass MeteorStats:\n def __init__(self, stats=None):\n if not stats:\n self.stats = meteor_api.MeteorStats()\n else:\n self.stats = stats\n\n def __iadd__(self, other):\n self.stats.addStats(other.stats)\n return self\n\n @property\n def score(self):\n return self.stats.score\n\n def __repr__(self):\n return self.stats.toString()\n\nmeteor_scorer = None\ndef meteor(hypothesis, reference):\n global meteor_scorer\n if not meteor_scorer: meteor_scorer = MeteorScorer()\n return meteor_scorer.score(hypothesis, reference).score\n\nMETRICS = {'bleu': smooth_bleu, 'meteor': meteor}\n","sub_path":"hw4/src/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"651859501","text":"import datetime\nimport unittest\n\nfrom GedcomParser import parse_gedcom_file\n\n\nclass UpcomingAnniversariesTests(unittest.TestCase):\n \"\"\"\n Test Cases for U.S. 39\n \"\"\"\n\n def test_us_39(self):\n \"\"\"\n Validate that there are upcoming anniversaries for 2/21/2017 in this file.\n \"\"\"\n gedcom_data = parse_gedcom_file(\"./sampledata/us39testdata.ged\")\n families = gedcom_data[0]\n individuals = gedcom_data[1]\n data = []\n # Assert that this file contains upcoming anniversaries for febraury.\n today = datetime.datetime.strptime(\"02 21 2017\", '%m %d %Y')\n for fam_id in families:\n family = families[fam_id]\n result = family.anniversary_upcoming(individuals, today=today)\n if result:\n data.append(result)\n self.assertFalse(data == [])\n\n def test_us_39_neg(self):\n \"\"\"\n Validate that there are NO upcoming anniversaries for 12/21/2017 in this file.\n \"\"\"\n gedcom_data = parse_gedcom_file(\"./sampledata/us39testdata.ged\")\n families = gedcom_data[0]\n individuals = gedcom_data[1]\n data = []\n # Assert that this file contains NO upcoming anniversaries for december.\n today = datetime.datetime.strptime(\"12 21 2017\", '%m %d %Y')\n for fam_id in families:\n family = families[fam_id]\n result = family.anniversary_upcoming(individuals, today=today)\n if result:\n data.append(result)\n self.assertTrue(data == [])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/testUpcomingAnniversaries.py","file_name":"testUpcomingAnniversaries.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"268712518","text":"import decimal\nimport os, pickle, json, random\nimport pandas as pd\n\nwith open('data/city_ids.json', 'r') as f:\n jcity = json.load(f, parse_float = decimal.Decimal)\n for city in jcity:\n city_list = list(jcity.keys())\n \ndef city2page(name):\n path = f'data/pages/{name}'\n with open(path, 'rb') as fp:\n return pickle.load(fp)\n \nmylist = []\nfor i in range(0, len(city_list)):\n try:\n mylist.append(city2page(city_list[i]).text)\n print(\"I am working\")\n except:\n continue \n \ndf = pd.DataFrame({\n 'city': city_list[i],\n 'text': mylist[i]\n })\n\ndf = pd.to_csv(r'city-data1/itter_7_dyno/wiki_dataframe/wiki_df.csv')\n","sub_path":"data-collection-master/APIs/wiki_master/.ipynb_checkpoints/wiki_page_csv-checkpoint.py","file_name":"wiki_page_csv-checkpoint.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"633955062","text":"import pygame\n\nclass Effect(pygame.sprite.Sprite):\n \"\"\"This class is base class for effects.\n Animation is played from images list and destroyed itself.\n\n \"\"\"\n def __init__(self, game, pos, images, delay):\n \"\"\"__init__ method for Explosion class\n\n Args:\n game (): Integrate.Game class object.\n pos (tuple length 2): position of the player (x,y).\n images (): image list from sprites.\n delay (int): delay between animation images\n\n \"\"\"\n self.group = game.all_sprites\n pygame.sprite.Sprite.__init__(self)\n self.layer = 0\n self.group.add(self, layer=self.layer)\n self.game = game\n\n self.timer = 0\n self.frame = 0\n self.images = images\n self.image = self.images[0]\n self.rect = self.image.get_rect()\n self.rect.center = pos\n self.game = game\n self.pos = pos\n self.delay = delay\n self.end = False\n \n \n def update(self):\n \"\"\"Effect class method to update the effect.\n\n \"\"\"\n self.rect.center = self.pos\n now = pygame.time.get_ticks() \n if self.frame == len(self.images):\n self.kill()\n self.end = True\n if now - self.timer > self.delay:\n self.timer = now\n # print(\"Frame: \" +str(self.frame))\n # print(\"Images: \" + str(self.images))\n # print(\"Images and Frames: \" + str(self.images[self.frame]))\n self.image = self.images[self.frame]\n self.frame = self.frame + 1","sub_path":"effects/Effect.py","file_name":"Effect.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"202227889","text":"import sys\nimport cv2\nimport concurrent.futures\n\ndef white_clipping(path, outputPath, value):\n lower_value = value\n upper_value = 255\n lower_color_bounds = (lower_value, lower_value, lower_value)\n upper_color_bounds = (upper_value, upper_value, upper_value)\n \n image = cv2.imread(path)\n #cv2.imshow('frame',image)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n #cv2.imshow('gray',gray)\n mask = cv2.inRange(image,lower_color_bounds,upper_color_bounds )\n #cv2.imshow('mask',mask)\n mask_rgb = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)\n #cv2.imshow('mask_rgb',mask_rgb)\n image = image | mask_rgb\n #cv2.imshow('res',image)\n cv2.imwrite(outputPath, image)\n \n \n return True\n\n\ndef multiProcessing(input_path_array, output_path_array, value):\n\n value_array = [value] * len(input_path_array)\n with concurrent.futures.ProcessPoolExecutor() as executor:\n results = executor.map(white_clipping, input_path_array, output_path_array, value_array)\n return \"Success\"\n\ndef ConvertStringToStringArray(string): \n li = list(string.split(\",\")) \n return li \n\n\nif __name__ == \"__main__\":\n #path = ['E:\\\\4.Jpg', 'E:\\\\5.jpg']\n #outputpath = ['E:\\\\New Folder\\\\4.Jpg','E:\\\\New Folder\\\\5.Jpg']\n #value = 112\n #result = white_clipping(path, outputPath, value)\n\n path = sys.argv[1]\n outputpath = sys.argv[2]\n value= int(sys.argv[3])\n SorM = int(sys.argv[4])\n\n if SorM == 1:\n input_path_array = ConvertStringToStringArray(path)\n output_path_array = ConvertStringToStringArray(outputpath)\n\n result = multiProcessing(input_path_array, output_path_array, value) \n else:\n result = white_clipping(path,outputpath,value)\n print(result)\n\n","sub_path":"CameraControl/pyFiles/whiteClipping.py","file_name":"whiteClipping.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"621158308","text":"\"\"\"\nA lightweight runner that just sets up a model and runs one of its functions in a particular configuration.\n\nIntented for debugging/exploration/profiling use cases, where the test/measurement harness is overhead.\n\nDANGER: make sure to `python install.py` first or otherwise make sure the benchmark you are going to run\n has been installed. This script intentionally does not automate or enforce setup steps.\n\nWall time provided for sanity but is not a sane benchmark measurement.\n\"\"\"\nimport argparse\nimport time\nimport torch.autograd.profiler as profiler\n\nfrom torchbenchmark import list_models\n\nimport torch\n\ndef run_one_step(func):\n\n func()\n\n if args.device == \"cuda\":\n torch.cuda.synchronize()\n start_event = torch.cuda.Event(enable_timing=True)\n end_event = torch.cuda.Event(enable_timing=True)\n\n start_event.record()\n\n t0 = time.time()\n func()\n t1 = time.time()\n\n end_event.record()\n torch.cuda.synchronize()\n print(f\"Ran in {t1 - t0} seconds, gpu time {start_event.elapsed_time(end_event)}.\")\n\n else:\n\n t0 = time.time()\n func()\n t1 = time.time()\n\n print(f\"Ran in {t1 - t0} seconds.\")\n\n\ndef profile_one_step(func, nwarmup=3):\n for i in range(nwarmup):\n func()\n\n use_cuda = args.device == \"cuda\"\n\n with profiler.profile(record_shapes=True, use_cuda = use_cuda) as prof:\n func()\n\n print(prof.key_averages(group_by_input_shape=True).table(sort_by=\"cpu_time_total\", row_limit=30))\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(__doc__)\n parser.add_argument(\"model\", help=\"Full or partial name of a model to run. If partial, picks the first match.\")\n parser.add_argument(\"-d\", \"--device\", choices=[\"cpu\", \"cuda\"], default=\"cpu\", help=\"Which device to use.\")\n parser.add_argument(\"-m\", \"--mode\", choices=[\"eager\", \"jit\"], default=\"eager\", help=\"Which mode to run.\")\n parser.add_argument(\"-t\", \"--test\", choices=[\"eval\", \"train\"], default=\"eval\", help=\"Which test to run.\")\n parser.add_argument(\"--profile\", action=\"store_true\", help=\"Run the profiler around the function\")\n args = parser.parse_args()\n\n found = False\n for Model in list_models():\n if args.model.lower() in Model.name.lower():\n found = True\n break\n if found:\n print(f\"Running {args.test} method from {Model.name} on {args.device} in {args.mode} mode\")\n else:\n print(f\"Unable to find model matching {args.model}\")\n exit(-1)\n\n # build the model and get the chosen test method\n m = Model(device = args.device, jit = (args.mode == \"jit\"))\n test = getattr(m, args.test)\n\n if args.profile:\n profile_one_step(test)\n else:\n run_one_step(test)\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"640849856","text":"\"\"\"\n\n Copyright (C) 2016, Blackboard Inc.\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n following conditions are met:\n\n Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n disclaimer.\n\n Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n following disclaimer in the documentation and/or other materials provided with the distribution.\n\n Neither the name of Blackboard Inc. nor the names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY BLACKBOARD INC ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\n BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL BLACKBOARD INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\n\nfrom demo.BBDNCore.rest import *\n\n\nclass User():\n def __init__(self, target_url, token):\n self.target_url = target_url\n self.token = token\n self.users_Path = '/learn/api/public/v1/users' # create(POST)/get(GET)\n self.user_Path = '/learn/api/public/v1/users/externalId:'\n\n def execute(self, command, dsk, token):\n if \"create\" in command:\n print('[User:execute] : ' + command)\n self.createUser(dsk, token)\n elif \"read_all\" in command:\n print('[User:execute] : ' + command + \"not implemented on server\")\n # self.getUsers(token)\n elif \"read\" in command:\n print('[User:execute] : ' + command)\n self.getUser(token)\n elif \"update\" in command:\n print('[User:execute] : ' + command)\n self.updateUser(dsk, token)\n elif \"delete\" in command:\n print('[User:execute] : ' + command)\n self.deleteUser(token)\n\n def getUsers(self, token):\n print('[User:getUsers] token: ' + token)\n # \"Authorization: Bearer $token\"\n authStr = 'Bearer ' + token\n print('[User:getUsers] authStr: ' + authStr)\n session = requests.session()\n session.mount('https://', Tls1Adapter()) # remove for production\n print(\"[User:getUsers()] GET Request URL: https://\" + self.target_url + self.users_Path)\n print(\"[User:getUsers()] JSON Payload: NONE REQUIRED\")\n r = session.get(\"https://\" + self.target_url + self.users_Path, headers={'Authorization': authStr},\n verify=False)\n print(\"[User:getUsers()] STATUS CODE: \" + str(r.status_code))\n print(\"[User:getUsers()] RESPONSE:\")\n if r.text:\n res = json.loads(r.text)\n print(json.dumps(res, indent=4, separators=(',', ': ')))\n else:\n print(\"NONE\")\n\n def createUser(self, dsk, token):\n # \"Authorization: Bearer $token\"\n authStr = 'Bearer ' + token\n\n self.PAYLOAD = {\n \"externalId\": USEREXTERNALID,\n \"dataSourceId\": dsk, # self.dskExternalId, Supported soon.\n \"userName\": \"python_demo\",\n \"password\": \"python61\",\n \"availability\": {\n \"available\": \"Yes\"\n },\n \"name\": {\n \"given\": \"Python\",\n \"family\": \"Demo\",\n },\n \"contact\": {\n \"email\": \"no.one@ereh.won\",\n }\n }\n\n session = requests.session()\n session.mount('https://', Tls1Adapter()) # remove for production with commercial cert\n\n print(\"[User:createUser()] POST Request URL: https://\" + self.target_url + self.users_Path)\n print(\"[User:createUser()] JSON Payload: \" + json.dumps(self.PAYLOAD, indent=4, separators=(',', ': ')))\n r = session.post(\"https://\" + self.target_url + self.users_Path, data=json.dumps(self.PAYLOAD),\n headers={'Authorization': authStr, 'Content-Type': 'application/json'}, verify=False)\n print(\"[User:createUser()] STATUS CODE: \" + str(r.status_code))\n print(\"[User:createUser()] RESPONSE:\")\n if r.text:\n res = json.loads(r.text)\n print(json.dumps(res, indent=4, separators=(',', ': ')))\n else:\n print(\"NONE\")\n\n def getUser(self, token):\n print('[User:getUser()] token: ' + token)\n # \"Authorization: Bearer $token\"\n authStr = 'Bearer ' + token\n print('[User:getUser()] authStr: ' + authStr)\n session = requests.session()\n session.mount('https://', Tls1Adapter()) # remove for production\n\n print(\"[User:getUser()] GET Request URL: https://\" + self.target_url + self.user_Path + USEREXTERNALID)\n print(\"[User:getUser()] JSON Payload: NONE REQUIRED\")\n r = session.get(\"https://\" + self.target_url + self.user_Path + USEREXTERNALID,\n headers={'Authorization': authStr}, verify=False)\n\n print(\"[User:getUser()] STATUS CODE: \" + str(r.status_code))\n print(\"[User:getUser()] RESPONSE:\")\n if r.text:\n res = json.loads(r.text)\n print(json.dumps(res, indent=4, separators=(',', ': ')))\n else:\n print(\"NONE\")\n\n def updateUser(self, dsk, token):\n # \"Authorization: Bearer $token\"\n authStr = 'Bearer ' + token\n print(\"[User:updateUser()] USEREXTERNALID: \" + USEREXTERNALID)\n\n self.PAYLOAD = {\n \"externalId\": USEREXTERNALID,\n \"dataSourceId\": dsk, # self.dskExternalId, Supported soon.\n \"userName\": \"python_demo\",\n \"password\": \"python16\",\n \"availability\": {\n \"available\": \"Yes\"\n },\n \"name\": {\n \"given\": \"Python\",\n \"family\": \"BbDN\",\n \"middle\": \"Demo\",\n },\n \"contact\": {\n \"email\": \"no.one@ereh.won\",\n }\n }\n session = requests.session()\n session.mount('https://', Tls1Adapter()) # remove for production with commercial cert\n\n print(\"[User:updateUser()] PATCH Request URL: https://\" + self.target_url + self.user_Path + USEREXTERNALID)\n print(\"[User:updateUser()] JSON Payload: \" + json.dumps(self.PAYLOAD, indent=4, separators=(',', ': ')))\n r = session.patch(\"https://\" + self.target_url + self.user_Path + USEREXTERNALID, data=json.dumps(self.PAYLOAD),\n headers={'Authorization': authStr, 'Content-Type': 'application/json'}, verify=False)\n\n print(\"[User:updateUser()] STATUS CODE: \" + str(r.status_code))\n print(\"[User:updateUser()] RESPONSE:\")\n if r.text:\n res = json.loads(r.text)\n print(json.dumps(res, indent=4, separators=(',', ': ')))\n else:\n print(\"NONE\")\n\n def deleteUser(self, token):\n # \"Authorization: Bearer $token\"\n authStr = 'Bearer ' + token\n print(\"[User:deleteUser()] USEREXTERNALID: \" + USEREXTERNALID)\n\n session = requests.session()\n session.mount('https://', Tls1Adapter()) # remove for production with commercial cert\n\n print(\"[User:deleteUser()] DELETE Request URL: https://\" + self.target_url + self.user_Path + USEREXTERNALID)\n print(\"[User:deleteUser()] JSON Payload: NONE REQUIRED\")\n r = session.delete(\"https://\" + self.target_url + self.user_Path + USEREXTERNALID,\n headers={'Authorization': authStr}, verify=False)\n\n print(\"[User:deleteUser()] STATUS CODE: \" + str(r.status_code))\n print(\"[User:deleteUser()] RESPONSE:\")\n if r.text:\n res = json.loads(r.text)\n print(json.dumps(res, indent=4, separators=(',', ': ')))\n else:\n print(\"NONE\")\n","sub_path":"demo/old_examples/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":8383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"413225240","text":"#!/usr/bin/python\nimport common as co\nimport numpy as np\nimport os\nimport sys\n\n# pylint: disable=C0103\n\n# prefix = 'run_sph_2b_same_mask'\nprefix = os.path.basename(sys.argv[1].strip('/'))\nrun_path = os.path.join('./simulations_outputs/', prefix, prefix)\n\noutdir = os.path.join('./simulations_outputs/', prefix, 'full_covariance_spin0')\noutput_path = os.path.join(outdir, prefix)\n\nfigures_dir = os.path.join('./simulations_outputs/', prefix, 'figures')\nfigures_path = os.path.join(figures_dir, prefix)\n\noutdir_NKA = os.path.join('./simulations_outputs/', prefix, 'full_covariance')\noutput_path_NKA = os.path.join(outdir_NKA, prefix)\n\n##################\nells = np.loadtxt(run_path + '_ells.txt')\n\nlmax = (ells < 2*512).sum()\n\nCovSims_path = output_path_NKA + '_covSims_TTTEEE_short_0001-20000.npz'\nCovTh_path = output_path + '_covTh_TTTEEE_short_2bins_spin0.npz'\n\nCovSims_Full = np.load(CovSims_path)['arr_0']\nCovTh_Full = np.load(CovTh_path)['arr_0']\n\ncl_ar = np.load(run_path + '_cl_0001-20000.npz')['arr_0']\nCls = [0, 1, 2] * 2 # 0 for T, 1 for E and 2 for B\nCls_Bs_ar = []\n\nc = 0\nfor i, Cli in enumerate(Cls):\n for Clj in Cls[i:]:\n Cls_Bs_ar.append([Cli, Clj])\n\nCls_Bs_ar = np.array(Cls_Bs_ar)\ncl_ar_noBs = cl_ar[np.all(Cls_Bs_ar != 2, axis=1)]\n\ncl_for_C = np.concatenate(cl_ar_noBs[:, :, :lmax].swapaxes(1, 2)).T\nlbins_Full = np.concatenate([ells[:lmax]] * cl_ar_noBs.shape[0])\n\n##################\nfoutput = figures_path + '_Spin0'\nchi2_Full, corr_Full = co.do_all_checks(lbins_Full, cl_for_C, CovSims_Full,\n CovTh_Full, modes=\"All TTTEEE\",\n row_cov=False, foutput=foutput + '_TTTEEE_Full')\n\nnp.savez_compressed(output_path + '_chi2_sims_th_TTTEEE_short_Full_spin0.npz', chi2_Full)\nnp.savez_compressed(output_path + '_corr_sims_th_TTTEEE_short_Full_spin0.npz', corr_Full)\n","sub_path":"notebooks/run_sph_2b_do_all_checks_full_cov_general_spin0.py","file_name":"run_sph_2b_do_all_checks_full_cov_general_spin0.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"154634116","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n if not lists or len(lists) == 0:\n return None\n\n while len(lists) > 1:\n mergedList = []\n for i in range(0, len(lists), 2):\n l1 = lists[i]\n #might be out of range bc incrementing i twice\n l2 = lists[i + 1] if (i + 1) < len(lists) else None\n mergedList.append(self.mergeTwoLists(l1, l2))\n lists = mergedList\n return lists[0]\n\n def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n dummy = ListNode(0)\n current = dummy\n while l1 and l2:\n if l1.val < l2.val:\n current.next = l1\n l1 = l1.next\n else:\n current.next = l2\n l2 = l2.next\n current = current.next\n if l1:\n current.next = l1\n elif l2:\n current.next = l2\n return dummy.next","sub_path":"leetcode/merge_k_sorted_lists_23.py","file_name":"merge_k_sorted_lists_23.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"332872031","text":"################################################################################\n#\n# (C) Copyright 2013 Hewlett-Packard Development Company, L.P.\n#\n################################################################################\n\n################################################################################\n# File Name : pcs_udw.py\n#\n# Release Notes:\n#\n# ----- Jul/23/2012 - Terry Fritz ------------------------------------------\n# - First release!\n#\n# ------------------------------------------------------------------------------\n#\n################################################################################\n\nfrom salutil import logger\nimport os\nimport sys\nimport time\nfrom printercx import ConnectException\nfrom printercx import deviceConnection\n\n#===============================================================================\nclass PCSudwException(Exception):\n \"\"\"Exception class used to raise exceptions for calling function\n\n \"\"\"\n #---------------------------------------------------------------------------\n def __init__(self, message, Errors=[]):\n \"\"\"Constructor for exception class\n\n \"\"\"\n\n # Call the base class constructor with the parameters it needs\n Exception.__init__(self, message)\n\n self.Errors = Errors\n\n #---------------------------------------------------------------------------\n def getErrors(self):\n \"\"\"Returns the error from this exception\n\n \"\"\"\n return self.Errors\n\n#===============================================================================\nclass PCSudw(object):\n \"\"\" This class wraps the deviceConnection.udw() functionality with some useful features.\n\n This class provides the following features:\n - It keeps track of errors seen in successive calls to PCSuds.udw() and allows\n access to the list of all errors seen since object instantiation.\n - It allows for 3 types of expected return values from a udw command:\n 1) The return value to match a specific value\n Supply PCSudw.udw with expectedValue=\n 2) The return value needs to be read from deviceConnection.udw(), but the\n return value doesn't matter.\n Supply PCSudw.udw with expectedValue=\"\" (empty string)\n 3) There is no return value for this udw command\n Supply PCSudw.udw with expectedValue=None\n - This class supplies a powerCycle() method, which issues the appropriate\n udw command to cause a power cycle (this is functions only for newer products)\n - This class keeps track of total udw commands issued and is available using the\n PCSudw.getTotalTestSteps() method.\n \"\"\"\n\n #---------------------------------------------------------------------------\n def __init__(self, quitOnFirstError=False, existingDeviceConnection=None):\n \"\"\"Constructor for PCSudw class\n\n Args:\n quitOnFirstError: Stops execution on first error if True\n existingDeviceConnection: This allows handing in an existing deviceConnection\n if one already exists.\n Raises:\n PCSudwException: if deviceConnection connection fails\n \"\"\"\n self.quitOnFirstError = quitOnFirstError\n if existingDeviceConnection == None or (not isinstance(existingDeviceConnection, deviceConnection)):\n logger.debug(\"Creating PCSudw new deviceConnection\")\n try:\n self.pcs = deviceConnection()\n except ConnectException as e:\n raise PCSudwException(\"PCSudw.__init__: %s\" % e)\n else:\n self.pcs = existingDeviceConnection\n logger.debug(\"Creating PCSudw with existing deviceConnection\")\n\n self.errorList = []\n self.testStep = 0\n\n #---------------------------------------------------------------------------\n def getDeviceConnection(self):\n \"\"\"Returns the deviceConnection instance being used to communicate with\n the printer.\n \"\"\"\n return self.pcs\n\n #---------------------------------------------------------------------------\n def resetConnection(self):\n \"\"\"Resets device connection settings\"\"\"\n return self.pcs.resetConnection()\n\n #---------------------------------------------------------------------------\n def getConnectionInfo(self):\n \"\"\"Returns the device connection information \"\"\"\n return self.pcs.getConnectionInfo()\n\n #---------------------------------------------------------------------------\n def getHost(self):\n \"\"\"Returns the host of the connection\"\"\"\n return self.pcs.getHost()\n\n #---------------------------------------------------------------------------\n def setPreferredChannel(self, channel):\n \"\"\"Sets the preferred USB connection channel\n\n Args:\n preferredChannel: The channel to request communication occur over. Either 'print' or 'rest'.\n \"\"\"\n return self.pcs.setPreferredChannel(channel)\n\n #---------------------------------------------------------------------------\n def getChannel(self):\n \"\"\"Returns the channel of the connection\"\"\"\n return self.pcs.getChannel()\n\n #---------------------------------------------------------------------------\n def udwVerify(self, commandString, expectedValue=None, commandCompletionDelay=0, timeoutFirstResponse=None, timeoutSubsequentResponses=None):\n \"\"\"Sends an underware command to the device\n\n Args:\n commandString -- The UDW command to sendn to device, including any\n needed parameters separated by spaces.\n expectedValue -- Three options:\n None : No expected value, and no read on PCS socket will occur\n '' : (Empty String) The return value is not important, but\n the return value will be read and returned from this function.\n : Any other string will be compared to the actual\n result (reading on PCS socket), and if results don't match,\n exit script with -1.\n commandCompletionDelay: For USB connections over the rest channel,\n it is sometimes necessary to force a delay between sending\n the udw command and reading the response. If this delay is not\n injected, the rest channel thinks there is no data to return,\n and the eventual data is returned for some follow-on command.\n Set this to a non-zero value to force a delay.\n timeoutFirstResponse: The socket timeout to wait for the first\n response from the socket.\n timeoutSubsequentResponses: The socket timeout to wait for the\n all responses after the first response. This is usually\n much less than 'timeoutFirstResponse'.\n Returns:\n the udw command response, if applicable\n Raises:\n PCSudwException: if communication error occurs\n \"\"\"\n returnValue = None\n self.testStep += 1\n\n if expectedValue == None:\n try:\n self.pcs.udw(commandString, False, commandCompletionDelay=commandCompletionDelay,\n timeoutFirstResponse=timeoutFirstResponse,\n timeoutSubsequentResponses=timeoutSubsequentResponses)\n except ConnectException as e:\n raise PCSudwException(\"PCSudw.udwVerify: %s\" % e)\n\n logger.info(\"SUCCESS:\\tResponse: \\t\\t<-\\t'%s'\", commandString)\n else:\n try:\n val = self.pcs.udw(commandString, commandCompletionDelay=commandCompletionDelay,\n timeoutFirstResponse=timeoutFirstResponse,\n timeoutSubsequentResponses=timeoutSubsequentResponses)\n except ConnectException as e:\n raise PCSudwException(\"PCSudw.udwVerify: %s\" % e)\n\n if expectedValue == '':\n logger.info(\"SUCCESS:\\tResponse: '%s' \\t<-\\t'%s'\", val, commandString)\n else:\n if val != expectedValue:\n logger.error(\"ERROR:\\t\\tResponse: '%s'\\t\\t\\t<-\\t'%s' != '%s'\", val, commandString, expectedValue)\n if self.quitOnFirstError:\n logger.error(\"#\\tExiting test because quitOnFirstError=True\")\n exit(-1)\n self.errorList.append({'testStep': self.testStep, 'type':'ERROR', 'command': commandString, 'expectedValue': expectedValue, 'actualValue': val})\n else:\n logger.info(\"SUCCESS:\\tResponse: '%s'\\t\\t\\t<-\\t'%s'\", val, commandString)\n returnValue = val\n\n return returnValue\n\n #---------------------------------------------------------------------------\n def udw(self, commandString, expectedValue=None, commandCompletionDelay=0, timeoutFirstResponse=None, timeoutSubsequentResponses=None):\n \"\"\"Deprecated method. Since this had the same name as deviceConnection.udw(), but with different parameters\n this was confusing. I changed the name of the udw() method to udwVerified(). It has the\n exact same implementation as before, just with a new name to imply different behavior\n than deviceConnection.udw().\n\n Raises:\n NotImplementedError: This method will always raise this exception since it is deprecated\n \"\"\"\n raise NotImplementedError(\"Deprecated method PCSudw.udw(). Use PCSudw.udwVerify() instead.\")\n\n #---------------------------------------------------------------------------\n def close(self):\n \"\"\"Closes all open socket connections\"\"\"\n return self.pcs.close()\n\n #---------------------------------------------------------------------------\n def file(self, filename, timeout=100, asynchronous=False):\n \"\"\"Sends a file to the printer over either print channel or port 9100, depending on connection type\n\n Args:\n filename: The full path of the file to send to the printer\n timeout: The maximum timeout to wait, in seconds, before considering the communication to be hung.\n Sending print files usually takes many seconds, and even minutes in some cases. Make sure\n this is set longer than the print file should reasonably take or else a premature termination\n will occur.\n asynchronous: If True, the print file is send on a separate thread, allowing this call to return\n almost immediately. False causes this method to wait until the print file has completely been\n sent.\n \"\"\"\n return self.pcs.file(filename, timeout, asynchronous)\n\n #---------------------------------------------------------------------------\n def powerCycle(self, maxWait=60):\n \"\"\"Power-cycle the device at 'host'\n\n Raises:\n PCSudwException: if communication error occurs\n \"\"\"\n return self.pcs.powerCycle(maxWait=maxWait)\n\n #---------------------------------------------------------------------------\n def getErrorList(self):\n \"\"\"Returns a list of any errors that occurred since object creation\n\n Returns:\n a list of dictionaries that describe the errors\n \"\"\"\n return self.errorList\n\n #---------------------------------------------------------------------------\n def getTotalTestSteps(self):\n \"\"\"Returns the number of udw commands sent since object creation\n\n Returns:\n the number of udw commands issued in total\n \"\"\"\n return self.testStep\n\n\n# Now take all classes and functions defined in this module and decorate them\nif logger.isEnabledFor(logger.DEBUG):\n from salutil.tracer import tracer\n _tracer = tracer(tracerOn=True, outputFun=logger.debug)\n _tracer.decorateModule(__name__)\n","sub_path":"PrinterControl/printercx/pcs_udw.py","file_name":"pcs_udw.py","file_ext":"py","file_size_in_byte":12042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"306655754","text":"# Import der benötigten Module\n# Bertiebssystemsanwendung und Dateizugriff\nimport os, pickle\n\n# Funktion zur Abspeicherung der Messdaten\ndef messe(verzeichnis):\n # Messwerte in eine temporäre Datei abspeichern\n befehl = \"python lspectrum.py > Messwerte_AktuellSP.txt\"\n os.system(befehl)\n # Messwerte aus der Datei lesen\n with open('Messwerte_AktuellSP.txt') as f:\n data = f.readline()[:-1]\n # Falls eine Messwerte-Datei existiert:\n if os.path.exists(verzeichnis+\"Messwerte.dat\"):\n # Datei zum (binären) Lesen öffnen\n h = open(verzeichnis+\"Messwerte.dat\",\"rb\")\n # Inhalt lesen\n messwerte = pickle.load(h)\n # Datei schließen\n h.close()\n # Bisherigen Messwerte ergänzen\n messwerte.append(data)\n messwerteneu = messwerte[:]\n # Datei zum (binären) Schreiben öffnen\n g = open(verzeichnis+\"Messwerte.dat\",\"wb\")\n # Datei mit den Messwerten überschreiben\n pickle.dump(messwerteneu,g)\n # Datei schließen\n g.close()\n # Andernfalls:\n else:\n # Neue Messwert-Liste erstellen\n messwerteneu = []\n # Durch die Messwerte ergänzen\n messwerteneu.append(data)\n # Messwerte-Datei zum (binären) Schreiben öffnen/erstellen\n g = open(verzeichnis+\"Messwerte.dat\",\"wb\")\n # Messwerte auf die Datei übertragen\n pickle.dump(messwerteneu,g)\n # Datei schließen\n g.close()\n","sub_path":"spektralsensornp.py","file_name":"spektralsensornp.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"473811334","text":"import sys\nimport os.path\n\n# There is a name clash with a module in Ansible named \"copy\":\ndeepcopy = __import__('copy').deepcopy\n\n# To be able to import wordpress_action_module\nsys.path.append(os.path.dirname(__file__))\n\nfrom wordpress_action_module import WordPressActionModule\n\n\nclass ActionModule(WordPressActionModule):\n def run(self, tmp=None, task_vars=None):\n \n self.result = super(ActionModule, self).run(tmp, task_vars)\n\n # Handling --check execution mode\n if task_vars['ansible_check_mode']:\n self.result['skipped'] = True\n return self.result\n\n # We only can do the job if plugin is installed\n if self._plugin_is_installed():\n\n self._set_protection_state()\n\n return self.result\n \n\n def _plugin_is_installed(self):\n \"\"\"\n Tells if the plugin is installed\n \"\"\"\n\n result = self._run_wp_cli_action(\"plugin list --format=csv\", update_result=False)\n\n for line in result['stdout_lines'][1:]:\n fields = line.split(',')\n if len(fields) < 2: continue\n\n if fields[0] == 'epfl-intranet': \n return True\n\n return False\n\n def _set_protection_state(self):\n \"\"\"\n Set correct protection state for plugin\n \"\"\"\n\n result = self._run_wp_cli_action(\"epfl intranet status\", update_result=False)\n\n if 'failed' in self.result: return\n\n # Getting parameters\n protection_enabled = self._task.args.get('protection_enabled').strip().lower() == 'yes'\n restrict_to_groups = str(self._task.args.get('restrict_to_groups')).strip()\n\n # If protection needs to be enabled\n if protection_enabled:\n\n # If protection is disabled or group restriction is not correct\n if 'is disabled' in result['stdout'] or (restrict_to_groups != \"\" and not result[\"stdout\"].endswith(restrict_to_groups)):\n\n # Creating restriction option\n restrict_to_groups_opt = \"--restrict-to-groups={}\".format(restrict_to_groups) if restrict_to_groups != \"\" else \"\"\n\n wpcli_command = \"epfl intranet enable-protection {}\".format(restrict_to_groups_opt)\n #self._update_result(self._run_wp_cli_action(wpcli_command))\n self._run_wp_cli_action(wpcli_command)\n \n # Protection needs to be disabled\n else:\n \n if 'is enabled' in result['stdout']:\n \n wpcli_command = \"epfl intranet disable-protection\"\n self._run_wp_cli_action(wpcli_command)\n","sub_path":"ansible/roles/wordpress-instance/action_plugins/wordpress_plugin_epfl_intranet.py","file_name":"wordpress_plugin_epfl_intranet.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"275313679","text":"# 텀 프로젝트\nimport sys\n# 백준에서 pypy3로 재귀호출리미트를 늘려주는 코드를 작성하지 않으면 런타임에러 발생\nsys.setrecursionlimit(111111)\n\ndef dfs(V):\n if check[V] == 2 or check[V] == -1:\n return\n check[V] += 1\n if check[lst[V]] != 2:\n dfs(lst[V])\n if check[V] < 2:\n check[V] = -1\n return\n\nT = int(input())\nfor _ in range(T):\n n = int(input())\n lst = list(map(int, input().split()))\n lst.insert(0, 0)\n check = [0]*(n+1)\n for i in range(1, n+1):\n if check[i] == 0:\n dfs(i)\n print(check.count(-1))","sub_path":"BOJ_Python/BOJ_9466.py","file_name":"BOJ_9466.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"244789834","text":"#!/usr/bin/env python\n#encoding: utf-8\nimport sys\nimport imp\nimp.reload(sys)\n# sys.setdefaultencoding('utf-8')\nsys.path.append(\"../\")\nimport config\nimport os\n\n\n\n# bert-as-service\n# https://github.com/hanxiao/bert-as-service\n# start service:\n\n# Base:\n# bert-serving-start -max_seq_len 100 -pooling_strategy NONE -model_dir /home/dejian/bert/uncased_L-12_H-768_A-12/ -num_worker=4\n\n\n# Large:\n# bert-serving-start -max_seq_len 100 -pooling_strategy NONE -model_dir /home/dejian/bert/uncased_L-24_H-1024_A-16/ -num_worker=4\n\n### bert-serving-start -pooling_strategy NONE -model_dir /home/dejian/bert/uncased_L-12_H-768_A-12/ -tuned_model_dir /home/dejian/pycharm_space/bert_linux/tmp/pdtb_output/ -num_worker=4\n\n\n\n# ''' sentense four eng'''\n# train_data_dir = config.DATA_PATH + \"/gen_my_four_sen/exp\"\ntrain_data_dir = config.DATA_PATH + \"/gen_my_four_sen/imp\"\n\n\n\n# # # CoNLL\n# train_data_dir = config.DATA_PATH + \"/conll/conll_imp\"\n# blind = False\n\n\n# train_data_dir = config.DATA_PATH + \"/ZH\"\n# blind = True\n\n\n# model = \"CNN\"\n# model = \"RNN\"\n# model = \"Attention_RNN1\"\n# model = \"Attention_RNN2\" # mine\nmodel = \"Attention_RNN3\"\n# model = \"Attention_RNN4\"\n# model = \"Attention_RNN5\"\nshare_rep_weights = False\nbidirectional = False\ncell_type = \"BasicLSTM\"\n# cell_type = \"TreeLSTM\"\nhidden_size = 50\nnum_layers = 1\ndropout_keep_prob = 0.5\nl2_reg_lambda = 0.0\nlearning_rate = 0.001\nbatch_size = 64\nnum_epochs = 20\nevaluate_every = 10\n\ncmd = \"python train_bert_task2.py\" \\\n + \" --train_data_dir %s\" % train_data_dir \\\n + \" --model %s\" % model \\\n + \" --share_rep_weights %s\" % share_rep_weights \\\n + \" --bidirectional %s\" % bidirectional \\\n + \" --cell_type %s\" % cell_type \\\n + \" --hidden_size %s\" % hidden_size \\\n + \" --num_layers %s\" % num_layers \\\n + \" --dropout_keep_prob %s\" % dropout_keep_prob \\\n + \" --l2_reg_lambda %s\" % l2_reg_lambda \\\n + \" --learning_rate %s\" % learning_rate \\\n + \" --batch_size %s\" % batch_size \\\n + \" --num_epochs %s\" % num_epochs \\\n + \" --evaluate_every %s\" % evaluate_every \\\n\n\n# + \" --blind %s\" % blind \\\n# + \" --dataset_type %s\" % dataset_type \\\n# + \" --level1_sense %s\" % level1_type \\\n\nprint(cmd)\nos.system(cmd)\n\n\n\n\n","sub_path":"bert_trainer/run_bert_task2.py","file_name":"run_bert_task2.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"519263401","text":"class Solution:\n def fastPower(self, a, n, b): # 递归求快速幂,求a的n次幂\n if (n == 1): # n等于1时,幂为a\n return a\n temp = self.fastPower(a, n // 2, b) % b\n return (1 if n % 2 == 0 else a) * temp * temp % 3 # 如果n是奇数,就会舍去一个a,所以要补上\n\nif __name__ == '__main__':\n solution = Solution()\n print(solution.fastPower(2, 31, 3))","sub_path":"Python算法指南/6_快速幂.py","file_name":"6_快速幂.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"193341502","text":"'''\nQuestion: Given a two dimensional matrix print inside out (spiral order)\n'''\n\n\ndef PrintMatrix(Table):\n for row in range(0,len(Table)):\n for col in range(0,len(Table[row])):\n print(\"%d\" % (Table[row][col]),end=\" \")\n print(\"\")\n\n\n#References\n#1. http://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/\n#2. http://stackoverflow.com/questions/726756/print-two-dimensional-array-in-spiral-order\ndef SpiralBind(rowEnd,colEnd,table):\n rowStart = 0\n colStart = 0\n result = []\n while (rowStart < rowEnd and colStart < colEnd):\n #top row\n for i in range(colStart,colEnd):\n result.append(table[rowStart][i])\n rowStart +=1\n #right most col\n for i in range(rowStart,rowEnd):\n result.append(table[i][rowEnd-1])\n colEnd -=1\n #last row\n if(rowStart < rowEnd):\n for i in range(colStart,colEnd)[::-1]:\n result.append(table[rowEnd-1][i])\n rowEnd -=1\n #left most col\n if(colStart < colEnd):\n for i in range(rowStart,rowEnd)[::-1]:\n result.append(table[i][colStart])\n colStart += 1\n return result\n \n \n\n\ntable = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]\nprint(\"2x2 matrix\")\nPrintMatrix(table)\n \nresult = SpiralBind(4,4,table)\nprint(\"\\nspiral bind ...\")\nprint(result)\nanswer = [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]\nassert result == answer, \"invalid!!!!\"","sub_path":"matrix-spiral-print.py","file_name":"matrix-spiral-print.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"306257870","text":"import os\nimport sys\n\nimport numpy as np\nfrom PIL import Image\nfrom numpy import random\nimport subprocess\nimport datetime\n\n\n#########################################################\n# parameters ############################################\n\n#directory of the ImageNet image files\n#sub-directories must correspond to the categories\nIMAGE_DIR = \"/home/kouichi/Data/Imagenet/images\"\n\n\n#########################################################\n# functions #############################################\n\ndef execute(cmd_str):\n cmd = cmd_str.split(' ')\n return subprocess.check_call(cmd)\n\n\ndef get_images_in_dir(dir_path, index=None):\n \n image_paths = []\n image_indices = []\n \n for image in os.listdir(dir_path):\n\n if len(image.split('.')) <= 1: # for the case image is directory\n continue\n\n path = os.path.join(dir_path, image)\n image_paths.append(path)\n if index is None:\n image_indices.append(image.split('__')[0])\n else:\n image_indices = [index] * len(image_paths)\n \n return image_paths, image_indices\n\n\ndef sampling_categories(index_list, n_samples = 20, index_must = []):\n \n remain_index = [i for i in index_list if i not in index_must]\n random.shuffle(remain_index)\n \n n_remain = n_samples - len(index_must)\n index_samples = sorted(index_must + remain_index[:n_remain])\n \n return index_samples\n\n\ndef sampling_images(index_samples, n_pics, index_dirname):\n\n image_paths = []\n image_indices = []\n \n sampling_dir = \"./sampling_images/\" + datetime.datetime.today().strftime(\"%Y%m%d-%H%M%S\")\n execute(\"mkdir -p {}\".format(sampling_dir))\n \n for i in index_samples:\n category_dir = os.path.join(IMAGE_DIR, index_dirname[i])\n image_list = os.listdir(category_dir)\n if len(image_list) == 0:\n continue\n random.shuffle(image_list)\n \n for image in image_list[:n_pics]:\n image_path = os.path.join(category_dir, image)\n copy_path = os.path.join(sampling_dir, \"{0}__{1}\".format(i, image))\n execute(\"cp {0} {1}\".format(image_path, copy_path))\n image_paths.append(copy_path)\n image_indices.append(i)\n \n return sampling_dir, image_paths, image_indices\n\n\n","sub_path":"modules/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"369392907","text":"\"\"\"\nUnifie les mots au pluriel et au féminin avec leur souche singulière et masculine.\nPour certains mots techniques, effectue une conversion du français à l'anglais quand\nc'est possible : biologique -> biologic.\n\"\"\"\n\nimport unicodedata\n\ndef strip_accents(s):\n return ''.join(c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn')\n\n\n# Mots qui peuvent être transformé en faux amis par les règles 'suffixes'\ndefaultInvariants = 'I sure due done one issue max use six its she may they sex user normal here que Ile Paris Rennes basé à mis poste ete dès tél ENS base gene Latex EST CET unix linux'\n\n# Mots dont le stem est irrégulier\ndefaultMap = {'ses': 'son',\n 'nos': 'notre',\n 'vos': 'votre',\n 'eaux': 'eau',\n 'ens': 'ENS',\n 'la': 'le',\n\n\n 'mais': 'but',\n 'dans': 'in',\n 'lorsque': 'when',\n 'pays': 'country',\n 'donné': 'data',\n 'dos': 'back',\n 'équipe': 'team',\n 'mois': 'mounth',\n }\n\n\n\n# Les opérations successivement effectuées sur chaque mot sont définies par des fonctions\n# Ces fonction yield chaque possibilité de transformation.\n# Entre chaque transformations, seuls les mots qui sont dans le dictionaire sont conservés.\ndef lower(w):\n if len(w) > 1 and not w.isupper():\n yield w.lower()\n\n\ndef stripSuffixes(suffixes):\n \"\"\"\n À partir d'une liste de paires (suffixe, remplacement), génère une fonction qui\n remplace le suffixe du mot.\n \"\"\"\n def go(w):\n lenw = len(w)\n if lenw < 2 or w[-1] == w[-2]: # less, see, etc\n return\n for suf, repl in suffixes:\n suflen = len(suf)\n if w.endswith(suf) and len(w) >= suflen + 2:\n yield w[:-suflen] + repl\n return go\n\n\nsingularize = stripSuffixes([ ('ies', 'y'),\n ('eaux', 'au'),\n ('aux' , 'al'),\n ('aux', 'ail'),\n ('s' , ''),\n ('x' , '')\n ])\n\nmasculinize = stripSuffixes([ ('elle', 'eau'),\n ('elle', 'el'),\n ('nne', 'n'),\n ('e' , ''),\n ])\n\ndef stripHyphen(w):\n yield w.replace('-', '')\n\n# French -> english\nfr2enSuffixes = stripSuffixes([ ('el', 'al'),\n ('ie', 'y'),\n ('ique', 'ic'),\n ])\n\ndef fr2en(w):\n if len(w) <= 3:\n return\n w = strip_accents(w)\n yield w\n yield from fr2enSuffixes(w)\n\n\ndefaultOps = [lower, singularize, masculinize, stripHyphen, fr2en]\n\n\n\nclass Stemmer:\n \"\"\" Stemmer basé sur un vocabulaire :\n Il établis une successions de candidats et essaye de continuer la simplification pour chaque\n candidats appartenant au vocabulaire.\n Il ne peut inventer de mots, mais il existe toujours la possibilité de faux amis.\n \"\"\"\n def __init__(self, vocab, ops=defaultOps, invariants=defaultInvariants, initmap=defaultMap):\n if type(invariants) == str:\n invariants = invariants.split()\n\n self.vocab = vocab\n self.termMap = initmap.copy()\n self.termMap.update({w:w for w in invariants})\n self.ops = ops\n\n\n def stem(self, w):\n termMap = self.termMap\n\n # Si le mot est déjà dans la table de transformation :\n shortcut = termMap.get(w)\n if shortcut is not None:\n return shortcut\n\n vocab = self.vocab\n\n origs = set()\n origs.add(w)\n\n # Pour chaque transformations\n for op in self.ops:\n # et pour chaque candidat généré\n for candidate in op(w):\n # On conserve le premier candidat présent dans le vocabulaire\n if candidate != w and candidate in vocab:\n origs.add(w)\n w = candidate\n break\n\n # Vérifie s'il existe un mot correspondant dans la table de transformation\n # C'est aussi une façon de stopper la conversion sur les stems invariants\n # (defaultInvariants) en stockant { word:word }\n shortcut = termMap.get(w)\n if shortcut is not None:\n w = shortcut\n break\n\n # Sauvegarde les transformation dans terMap pour une conversion plus rapide lors\n # de la prochaine rencontre avec le mot.\n for orig in origs:\n if orig in termMap:\n assert termMap[orig] != w\n else:\n termMap[orig] = w\n return w\n\n\n def printMapping(self):\n \"\"\"\n Affiche la correspondance entre les mot d'origine et le mots convertis.\n \"\"\"\n termMap = self.termMap\n vocab = self.vocab\n reverse = dict()\n for k,v in termMap.items():\n if k == v:\n continue\n reverse.setdefault(v, set()).add(k)\n\n reverse = list(reverse.items())\n if isinstance(vocab, dict):\n # Trie les transformations par nombre d'occurence des mots\n def totalOccurences(item):\n v, ks = item\n ks_occ = sum(vocab.get(k,0) for k in ks if k != v)\n v_occ = vocab.get(v,0)\n return ks_occ + v_occ\n reverse.sort(key=totalOccurences)\n for v, ks in reverse:\n ks = ' '.join('{}~{}'.format(k, vocab.get(k,0))\n for k in ks\n if k.lower() != v)\n if ks:\n print('{} -> {}~{}'.format(ks,v, vocab.get(v,0)))\n else:\n for v, ks in reverse:\n print('{} -> {}'.format(' '.join(ks), v))\n\n # Pour le pickling\n def __getstate__(self):\n return (self.vocab, self.termMap)\n\n def __setstate__(self, state):\n self.vocab, self.termMap = state\n","sub_path":"stemmer.py","file_name":"stemmer.py","file_ext":"py","file_size_in_byte":6181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"104422845","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# pylint: disable=unused-argument, no-self-use, line-too-long, protected-access, too-few-public-methods\nfrom knack.log import get_logger\n\nfrom azure.cli.core.aaz import has_value\nfrom azure.cli.core.aaz.utils import assign_aaz_list_arg\nfrom ._util import import_aaz_by_profile\n\n\nlogger = get_logger(__name__)\n\n\n_Nsg = import_aaz_by_profile(\"network.nsg\")\n_NsgRule = import_aaz_by_profile(\"network.nsg.rule\")\n\n\nclass NSGCreate(_Nsg.Create):\n def _output(self, *args, **kwargs):\n result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True)\n return {\"NewNSG\": result}\n\n\ndef _handle_plural_or_singular(args, plural_name, singular_name):\n values = getattr(args, plural_name)\n if not has_value(values):\n return\n\n setattr(args, plural_name, values if len(values) > 1 else None)\n setattr(args, singular_name, values[0] if len(values) == 1 else None)\n\n\nclass NSGRuleCreate(_NsgRule.Create):\n @classmethod\n def _build_arguments_schema(cls, *args, **kwargs):\n from azure.cli.core.aaz import AAZListArg, AAZResourceIdArg, AAZResourceIdArgFormat\n args_schema = super()._build_arguments_schema(*args, **kwargs)\n args_schema.priority._required = True\n args_schema.destination_asgs = AAZListArg(\n options=[\"--destination-asgs\"],\n arg_group=\"Destination\",\n help=\"Space-separated list of application security group names or IDs. Limited by backend server, \"\n \"temporarily this argument only supports one application security group name or ID.\",\n )\n args_schema.destination_asgs.Element = AAZResourceIdArg(\n fmt=AAZResourceIdArgFormat(\n template=\"/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.Network\"\n \"/applicationSecurityGroups/{}\",\n ),\n )\n args_schema.source_asgs = AAZListArg(\n options=[\"--source-asgs\"],\n arg_group=\"Source\",\n help=\"Space-separated list of application security group names or IDs. Limited by backend server, \"\n \"temporarily this argument only supports one application security group name or ID.\",\n )\n args_schema.source_asgs.Element = AAZResourceIdArg(\n fmt=AAZResourceIdArgFormat(\n template=\"/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.Network\"\n \"/applicationSecurityGroups/{}\",\n ),\n )\n # filter arguments\n args_schema.destination_address_prefix._registered = False\n args_schema.destination_application_security_groups._registered = False\n args_schema.destination_port_range._registered = False\n args_schema.source_address_prefix._registered = False\n args_schema.source_application_security_groups._registered = False\n args_schema.source_port_range._registered = False\n return args_schema\n\n def pre_operations(self):\n args = self.ctx.args\n _handle_plural_or_singular(args, \"destination_address_prefixes\", \"destination_address_prefix\")\n _handle_plural_or_singular(args, \"destination_port_ranges\", \"destination_port_range\")\n _handle_plural_or_singular(args, \"source_address_prefixes\", \"source_address_prefix\")\n _handle_plural_or_singular(args, \"source_port_ranges\", \"source_port_range\")\n # handle application security groups\n if has_value(args.destination_asgs):\n args.destination_application_security_groups = [{\"id\": asg_id} for asg_id in args.destination_asgs]\n if has_value(args.destination_address_prefix):\n args.destination_address_prefix = None\n if has_value(args.source_asgs):\n args.source_application_security_groups = [{\"id\": asg_id} for asg_id in args.source_asgs]\n if has_value(args.source_address_prefix):\n args.source_address_prefix = None\n\n\nclass NSGRuleUpdate(_NsgRule.Update):\n @classmethod\n def _build_arguments_schema(cls, *args, **kwargs):\n from azure.cli.core.aaz import AAZListArg, AAZResourceIdArg, AAZResourceIdArgFormat\n args_schema = super()._build_arguments_schema(*args, **kwargs)\n args_schema.destination_asgs = AAZListArg(\n options=[\"--destination-asgs\"],\n arg_group=\"Destination\",\n help=\"Space-separated list of application security group names or IDs. Limited by backend server, \"\n \"temporarily this argument only supports one application security group name or ID.\",\n nullable=True,\n )\n args_schema.destination_asgs.Element = AAZResourceIdArg(\n nullable=True,\n fmt=AAZResourceIdArgFormat(\n template=\"/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.Network\"\n \"/applicationSecurityGroups/{}\",\n ),\n )\n args_schema.source_asgs = AAZListArg(\n options=[\"--source-asgs\"],\n arg_group=\"Source\",\n help=\"Space-separated list of application security group names or IDs. Limited by backend server, \"\n \"temporarily this argument only supports one application security group name or ID.\",\n nullable=True,\n )\n args_schema.source_asgs.Element = AAZResourceIdArg(\n nullable=True,\n fmt=AAZResourceIdArgFormat(\n template=\"/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.Network\"\n \"/applicationSecurityGroups/{}\",\n ),\n )\n # filter arguments\n args_schema.destination_address_prefix._registered = False\n args_schema.destination_application_security_groups._registered = False\n args_schema.destination_port_range._registered = False\n args_schema.source_address_prefix._registered = False\n args_schema.source_application_security_groups._registered = False\n args_schema.source_port_range._registered = False\n return args_schema\n\n def pre_operations(self):\n args = self.ctx.args\n # handle application security groups\n args.destination_application_security_groups = assign_aaz_list_arg(\n args.destination_application_security_groups,\n args.destination_asgs,\n element_transformer=lambda _, asg_id: {\"id\": asg_id}\n )\n args.source_application_security_groups = assign_aaz_list_arg(\n args.source_application_security_groups,\n args.source_asgs,\n element_transformer=lambda _, asg_id: {\"id\": asg_id}\n )\n\n def pre_instance_update(self, instance):\n if instance.properties.sourceAddressPrefix:\n instance.properties.sourceAddressPrefixes = [instance.properties.sourceAddressPrefix]\n instance.properties.sourceAddressPrefix = None\n if instance.properties.destinationAddressPrefix:\n instance.properties.destinationAddressPrefixes = [instance.properties.destinationAddressPrefix]\n instance.properties.destinationAddressPrefix = None\n if instance.properties.sourcePortRange:\n instance.properties.sourcePortRanges = [instance.properties.sourcePortRange]\n instance.properties.sourcePortRange = None\n if instance.properties.destinationPortRange:\n instance.properties.destinationPortRanges = [instance.properties.destinationPortRange]\n instance.properties.destinationPortRange = None\n\n def post_instance_update(self, instance):\n if instance.properties.sourceAddressPrefixes and len(instance.properties.sourceAddressPrefixes) == 1:\n instance.properties.sourceAddressPrefix = instance.properties.sourceAddressPrefixes[0]\n instance.properties.sourceAddressPrefixes = None\n if instance.properties.destinationAddressPrefixes and len(instance.properties.destinationAddressPrefixes) == 1:\n instance.properties.destinationAddressPrefix = instance.properties.destinationAddressPrefixes[0]\n instance.properties.destinationAddressPrefixes = None\n if instance.properties.sourcePortRanges and len(instance.properties.sourcePortRanges) == 1:\n instance.properties.sourcePortRange = instance.properties.sourcePortRanges[0]\n instance.properties.sourcePortRanges = None\n if instance.properties.destinationPortRanges and len(instance.properties.destinationPortRanges) == 1:\n instance.properties.destinationPortRange = instance.properties.destinationPortRanges[0]\n instance.properties.destinationPortRanges = None\n\n\ndef list_nsg_rules(cmd, resource_group_name, network_security_group_name, include_default=False):\n Show = import_aaz_by_profile(\"network.nsg\").Show\n nsg = Show(cli_ctx=cmd.cli_ctx)(command_args={\n \"resource_group\": resource_group_name,\n \"name\": network_security_group_name\n })\n\n rules = nsg[\"securityRules\"]\n return rules + nsg[\"defaultSecurityRules\"] if include_default else rules\n","sub_path":"src/azure-cli/azure/cli/command_modules/network/azure_stack/profile_2018_03_01_hybrid/operations/nsg.py","file_name":"nsg.py","file_ext":"py","file_size_in_byte":9475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"24638235","text":"\"\"\"\n题目:画椭圆ellipse。 \n程序分析:无。\n\"\"\"\n\n# !/usr/bin/python\n# -*- coding: UTF-8 -*-\n# from tkinter import *\n# from tkinter.ttk import Combobox\n#\n# xin = Tk()\n# Label(xin,text = \"文件路径:\").grid(row=0,sticky=W)\n# Entry(xin).grid(row=0,column=1,sticky=E)\n# Button(xin,text=\"导入考勤文件\").grid(row=0,column=2,sticky=E)\n# Label(xin,text = \"员工姓名:\").grid(row=1,sticky=W)\n# Combobox(xin).grid(row=1,column=1,sticky=E)\n# Button(xin,text=\" 导出 \").grid(row=2,column=1,sticky=E)\n# xin.mainloop()\n\n\n\n\n# import tkinter as tk\n# from tkinter import ttk\n#\n# win = tk.Tk()\n# win.title(\"Python GUI\") # 添加标题\n#\n# ttk.Label(win, text=\"Chooes a number\").grid(column=1, row=0) # 添加一个标签,并将其列设置为1,行设置为0\n# ttk.Label(win, text=\"Enter a name:\").grid(column=0, row=0) # 设置其在界面中出现的位置 column代表列 row 代表行\n#\n# # button被点击之后会被执行\n# def clickMe(): # 当acction被点击时,该函数则生效\n# action.configure(text='Hello ' + name.get()) # 设置button显示的内容\n# action.configure(state='disabled') # 将按钮设置为灰色状态,不可使用状态\n#\n# # 按钮\n# action = ttk.Button(win, text=\"Click Me!\", command=clickMe) # 创建一个按钮, text:显示按钮上面显示的文字, command:当这个按钮被点击之后会调用command函数\n# action.grid(column=2, row=1) # 设置其在界面中出现的位置 column代表列 row 代表行\n#\n# # 文本框\n# name = tk.StringVar() # StringVar是Tk库内部定义的字符串变量类型,在这里用于管理部件上面的字符;不过一般用在按钮button上。改变StringVar,按钮上的文字也随之改变。\n# nameEntered = ttk.Entry(win, width=12, textvariable=name) # 创建一个文本框,定义长度为12个字符长度,并且将文本框中的内容绑定到上一句定义的name变量上,方便clickMe调用\n# nameEntered.grid(column=0, row=1) # 设置其在界面中出现的位置 column代表列 row 代表行\n# nameEntered.focus() # 当程序运行时,光标默认会出现在该文本框中\n#\n# # 创建一个下拉列表\n# number = tk.StringVar()\n# numberChosen = ttk.Combobox(win, width=12, textvariable=number)\n# numberChosen['values'] = (1, 2, 4, 42, 100) # 设置下拉列表的值\n# numberChosen.grid(column=1, row=1) # 设置其在界面中出现的位置 column代表列 row 代表行\n# numberChosen.current(0) # 设置下拉列表默认显示的值,0为 numberChosen['values'] 的下标值\n#\n# win.mainloop() # 当调用mainloop()时,窗口才会显示出来\n\n\n\n\nimport tkinter as tk\nfrom tkinter import ttk\n\nimport win32ui\n\n\nwin = tk.Tk()\nwin.title(\"员工考勤工具\") # 添加标题\npathtext = tk.StringVar()\nnumberChosen = ttk.Combobox(win, width=48, textvariable=tk.StringVar())\n\ndef exportFile():\n print(\"export\")\ndef importFile():\n dlg = win32ui.CreateFileDialog(1) # 1表示打开文件对话框\n dlg.SetOFNInitialDir('C:/Users/Public/Desktop') # 设置打开文件对话框中的初始显示目录\n dlg.DoModal()\n filename = dlg.GetPathName() # 获取选择的文件名称\n pathtext.set(filename)\n numberChosen['values'] = (\"张三\",\"李四\")\n\n\n\n\nttk.Label(win, text=\"文件路径\").grid(column=0, row=0)\nttk.Entry(win,width=50, textvariable=pathtext,state='readonly').grid(column=1,row=0)\nttk.Button(win,text=\"导入考勤文件\",command=importFile).grid(column=2,row=0)\n\nttk.Label(win, text=\"员工姓名\").grid(column=0, row=1)\n\nnumberChosen['values'] = ('1') # 设置下拉列表的值\nnumberChosen.grid(column=1, row=1) # 设置其在界面中出现的位置 column代表列 row 代表行\nnumberChosen.current(0) # 设置下拉列表默认显示的值,0为 numberChosen['values'] 的下标值\n\naction = ttk.Button(win, text=\"导出\", command=exportFile) # 创建一个按钮, text:显示按钮上面显示的文字, command:当这个按钮被点击之后会调用command函数\naction.grid(column=2, row=1) # 设置其在界面中出现的位置 column代表列 row 代表行\n\nwin.mainloop() # 当调用mainloop()时,窗口才会显示出来\n\n","sub_path":"test63.py","file_name":"test63.py","file_ext":"py","file_size_in_byte":4231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"266644499","text":"import yaml\nimport tikzplotlib\nimport glob\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\n\n\nDP = []\nC = []\nOGD = []\nW = {}\nB = {}\nL = {}\nbeta = {}\n\ncolors = {\n 'OGD': 'red',\n 'DPWRAP_OGD': 'green',\n 'CWRAP_OGD': 'orange',\n 'ADAGRAD': 'blue',\n 'ConversionConstrained_RewardDoubligNDGuess': 'deeppink'\n }\n\nlabel = {\n 'OGD': 'OGD',\n 'DPWRAP_OGD': 'CP-OGD',\n 'CWRAP_OGD': 'CS-OGD',\n 'ADAGRAD': 'Adagrad',\n 'ConversionConstrained_RewardDoubligNDGuess': 'CRDG'\n }\n\nmarker = {\n 'OGD': '.',\n 'DPWRAP_OGD': '>',\n 'CWRAP_OGD': '+',\n 'ADAGRAD': '*',\n 'ConversionConstrained_RewardDoubligNDGuess': 'p'\n }\n\nlinestyle = {\n 'OGD': 'solid',\n 'DPWRAP_OGD': 'dotted',\n 'CWRAP_OGD': 'dashed',\n 'ADAGRAD': 'dashdot',\n 'ConversionConstrained_RewardDoubligNDGuess': 'solid'\n }\n\nfor yaml_file in glob.glob('experiments2/FIN/*.yaml'):\n\n with open(yaml_file, 'r') as f:\n d = dict(yaml.load(f, Loader=yaml.FullLoader))\n\n if d['algo']['name'] != 'DPOGDMAX':\n base_np = os.path.splitext(os.path.basename(yaml_file))[0]+'.npz'\n np_file = os.path.join(os.path.dirname(yaml_file), base_np)\n data = dict(np.load(np_file))\n\n L_t = data['L_t'].T[0]\n L_def_t = data['LT_t'].T[0]\n # L_best = np.cumsum(data['best_loss_t'])\n b = 0.80\n u = 1.04\n ll = 0.96\n e_u = float(np.log(u)-np.log(ll))\n alpha = float(b/(43140*e_u))\n print(b)\n bdg = (1 + alpha)*L_def_t - L_t\n t = np.arange(1, len(L_t)+1)\n K = -np.log(ll)\n W_t = np.exp(-L_t+K*t)\n D2 = np.exp(-L_def_t+K*t)\n W[d['algo']['name']] = W_t\n B[d['algo']['name']] = W_t-D2*b\n L[d['algo']['name']] = L_t\n D = D2*b\n if d['algo']['name'] in ['COGD', 'DPOGD', 'DPOGDMAX']:\n beta[d['algo']['name']] = data['beta']\n\nplt.figure()\nfor k in W.keys():\n T = np.arange(1, len(W[k])+1)*d['checkpoints']\n idx = np.arange(1, len(T)+1, 100)\n T = T[idx]\n plt.plot(T, W[k][idx], color=colors[k], label=label[k], marker=marker[k], linestyle=linestyle[k], markevery=50, markersize=3)\nplt.xlabel(r\"$t$\")\nplt.ylabel(r\"$W_t$\")\n# plt.plot(T, D, label='def*b', color='blue')\n# plt.plot(T, D2, label='def', color='magenta')\n# plt.legend()\n# plt.grid(True)\n# plt.title('W')\nplt.show(block=False)\n\ntikzplotlib.save(\"teximgs/FIN_wealth.tex\")\n\nplt.figure()\nfor k in B.keys():\n T = np.arange(len(B[k]))*d['checkpoints']\n T = T[idx]\n plt.plot(T, B[k][idx], color=colors[k], label=label[k], marker=marker[k], linestyle=linestyle[k], markevery=50, markersize=3)\nplt.xlabel(r\"$t$\")\nplt.ylabel(r\"$P_t$\")\nplt.legend()\n# plt.grid(True)\nplt.show(block=False)\n\ntikzplotlib.save(\"teximgs/FIN_budget.tex\")\n\nplt.figure()\nfor k in beta.keys():\n T = np.arange(len(beta[k]))*d['checkpoints']\n plt.plot(T, beta[k], label=k, color=colors[k])\nplt.legend()\nplt.title('beta')\nplt.show()\n","sub_path":"FIN_plot.py","file_name":"FIN_plot.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"596629506","text":"from django.test import TestCase\nfrom .forms import FormFromPattern\n\n\nclass FormFromPatternTest(TestCase):\n def setUp(self):\n pattern = {\n \"id\": {\n \"caption\": \"Numer faktury\",\n \"hint\": \"np. 21\",\n \"type\": \"text\",\n \"order\": 1,\n \"check\": \"^[0-9]+$\"\n },\n \"items\": {\n \"caption\": \"Towary\",\n \"order\": 2,\n \"type\": [\n {\n \"price\": {\n \"caption\": \"Cena\",\n \"hint\": \"np. 21.00\",\n \"type\": \"text\",\n \"order\": 2,\n \"check\": \"^[0-9]+\\\\.[0-9][0-9]$\"\n },\n \"name\": {\n \"caption\": \"Nazwa towaru\",\n \"hint\": \"np. slodka bulka\",\n \"type\": \"text\",\n \"order\": 1,\n \"check\": \".+\"\n }\n }\n ]\n }\n }\n self.form = FormFromPattern(pattern, True)\n\n # def test_form_has_nested\n\n def test_caption_is_missing_in_field(self):\n self.assertRaises(KeyError, FormFromPattern, {\n \"id\": {\n \"hint\": \"np. 21\",\n \"type\": \"text\",\n \"order\": 1,\n \"check\": \"^[0-9]+$\"\n }\n }, True)\n\n def test_hint_is_missing_in_field(self):\n self.assertRaises(KeyError, FormFromPattern, {\n \"id\": {\n \"caption\": \"Numer faktury\",\n \"type\": \"text\",\n \"order\": 1,\n \"check\": \"^[0-9]+$\"\n }\n }, True)\n\n def test_type_is_missing_in_field(self):\n self.assertRaises(KeyError, FormFromPattern, {\n \"id\": {\n \"caption\": \"Numer faktury\",\n \"hint\": \"np. 21\",\n \"order\": 1,\n \"check\": \"^[0-9]+$\"\n }\n }, True)\n\n def test_order_is_missing_in_field(self):\n self.assertRaises(KeyError, FormFromPattern, {\n \"id\": {\n \"caption\": \"Numer faktury\",\n \"hint\": \"np. 21\",\n \"type\": \"text\",\n \"check\": \"^[0-9]+$\"\n }\n }, True)\n\n def test_check_is_missing_in_field(self):\n self.assertRaises(KeyError, FormFromPattern, {\n \"id\": {\n \"caption\": \"Numer faktury\",\n \"hint\": \"np. 21\",\n \"type\": \"text\",\n \"order\": 1\n }\n }, True)\n\n def test_form_raises_error_without_pattern_and_tags(self):\n with self.assertRaises(TypeError):\n FormFromPattern()\n\n\n","sub_path":"templado/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"116036799","text":"import keras.layers as KL\nimport keras.engine as KE\nimport tensorflow as tf\n\nfrom utils import utils, keras_util, tf_util\nfrom utils.pointnet_util import pointnet_sa_module_msg, pointnet_sa_module, pointnet_fp_module\n\nclass FeaturePointCloud(KE.Layer):\n\n def __init__(self, feature_map_size, config, **kwargs):\n \"\"\"\n\n :param rois: batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized\n coordinates\n :param image_features: [batch, num_rois, h, w, channels]\n :param depth_image: [batch, num_rois, h, w, 1]\n :return: [batch, num_rois, h*w, (x, y, z)], [batch, num_rois, h*w, channels]\n \"\"\"\n super(FeaturePointCloud, self).__init__(**kwargs)\n self.feature_map_size = feature_map_size\n self.config = config\n\n def call(self, inputs, **kwargs):\n def min_nonzero(tensor):\n \"\"\"\n computes the minimum value of a tensor not including values that are 0\n :param tensor:\n :return:\n \"\"\"\n mask = tf.greater(tensor, 0., name=\"depth_mask\")\n masked_tensor = tf.boolean_mask(tensor, mask)\n return tf.reduce_min(masked_tensor)\n # [batch, num_rois, (y1, x1, y2, x2)], [batch, num_rois, 24, 24, config.FEATURE_PYRAMIND_TOP_DOWN_SIZE]\n # [batch, num_rois, 24, 24, 1], [batch, 3, 3]\n rois, image_features, depth_image, intrinsic_matrices = inputs\n # [batch, num_rois, 1], [batch, num_rois, 1], [batch, num_rois, 1], [batch, num_rois, 1]\n y1, x1, y2, x2 = tf.split(rois, 4, axis=2)\n im_shape = tf.shape(image_features)\n # TODO: this works only as long as the rois have shape 24 x 24\n batch = self.config.IMAGES_PER_GPU\n num_rois = im_shape[1]\n h = tf.cast(self.feature_map_size[0], \"float32\")\n w = tf.cast(self.feature_map_size[1], \"float32\")\n channels = im_shape[4]\n # print_op = tf.print([batch, num_rois, h, w, channels])\n # with tf.control_dependencies([print_op]):\n # [width]\n x = tf.range(w)\n # [height]\n y = tf.range(h)\n # [h, w], [h, w]\n X, Y = tf.meshgrid(x, y)\n # [batch*h, w]; needs to be [batch, 1, h*w]\n X = tf.tile(X, [batch, 1], name=\"tiled_X\")\n X = tf.reshape(X, (batch, 1, -1), name=\"reshape_X\")\n # [batch, 1, h * w]\n # [1, h*w]\n Y = tf.tile(Y, [batch, 1], name=\"tiled_X\")\n Y = tf.reshape(Y, (batch, 1, -1), name=\"reshape_Y\")\n # [batch, 1, h * w]\n # [batch, num_rois, 1]\n height_pixel_scale = (y2 - y1) / h\n # [batch, num_rois, 1]\n width_pixel_scale = (x2 -x1) / w\n # expand_dims([batch, num_rois, 1] + [batch, num_rois, h*w]) =! [batch, num_rois, h*w, 1]\n z_im = tf.reshape(depth_image, (batch, num_rois, -1, 1), name=\"z_im\")\n y_im = tf.expand_dims(y1 + tf.linalg.matmul(height_pixel_scale, Y), axis=-1)\n # [batch, num_rois, h*w, 1] - [batch, 1, 1, 1] = [batch, num_rois, h*w, 1] -> subtract principal point\n y_im = (y_im * self.config.IMAGE_SHAPE[0] - tf.reshape(intrinsic_matrices[:, 1, 2], (batch, 1, 1, 1)))\n # [batch, num_rois, h*w, 1] * [batch, num_rois, h*w, 1] = [batch, num_rois, h*w, 1] -> get correct depth scaling\n y_im = y_im * z_im\n # [batch, num_rois, h*w, 1] / [batch, 1, 1, 1] = [batch, num_rois, h*w, 1] -> divide by focal length\n y_im = y_im / tf.reshape(intrinsic_matrices[:, 1, 1], (batch, 1, 1, 1))\n x_im = tf.expand_dims(x1 + tf.linalg.matmul(width_pixel_scale, X), axis=-1)\n # x_im = (x_im * self.config.IMAGE_SHAPE[1] - intrinsic_matrices[:, 0, 2]) * z_im / intrinsic_matrices[:, 0, 0]\n x_im = (x_im * self.config.IMAGE_SHAPE[1] - tf.reshape(intrinsic_matrices[:, 0, 2], (batch, 1, 1, 1)))\n # [batch, num_rois, h*w, 1] * [batch, num_rois, h*w, 1] = [batch, num_rois, h*w, 1] -> get correct depth scaling\n x_im = x_im * z_im\n # [batch, num_rois, h*w, 1] / [batch, 1, 1, 1] = [batch, num_rois, h*w, 1] -> divide by focal length\n x_im = x_im / tf.reshape(intrinsic_matrices[:, 0, 0], (batch, 1, 1, 1))\n # [batch, num_rois, h*w, 1]\n # filter out all elements which have z == 0 for the minimum value\n min_z = tf.reshape(utils.batch_slice([z_im], min_nonzero,\n self.config.IMAGES_PER_GPU,\n names=[\"min_nonzero_z\"]),\n (batch, 1, 1, 1))\n # rescales z to be between 0...1 for each batch, excluding the depth points == 0\n # reshapes z_im to [batch, num_rois*w*h], then takes then min/max along dimension 1\n # to result in an tensor of shape [batch]\n sub1 = tf.subtract(\n z_im,\n min_z\n )\n sub2 = tf.subtract(\n tf.reshape(\n tf.reduce_max(\n tf.reshape(z_im, (batch, -1)),\n axis=1),\n (batch, 1, 1, 1)),\n min_z\n )\n\n # z_im = tf.div(sub1, sub2)\n # [batch, num_rois, h*w, 3]\n\n positions = tf.concat([x_im, y_im, z_im], axis=-1, name=\"concat_positions\")\n positions = tf.reshape(positions, (batch, num_rois, -1, 3))\n # [batch, num_rois, h*w, config.FEATURE_PYRAMID_TOP_DOWN_SIZE]\n # print_op = tf.print([tf.shape(y_im), tf.shape(x_im), tf.shape(z_im), tf.shape(positions)])\n # with tf.control_dependencies([print_op]):\n features = tf.reshape(image_features, (batch, num_rois, -1, channels), name=\"reshape_features\")\n return [positions, features]\n\n def compute_output_shape(self, input_shape):\n rois_shape = input_shape[0]\n image_shape = input_shape[1]\n feature_maps = self.feature_map_size[0] * self.feature_map_size[1]\n output_shape = [(rois_shape[:2]) +(feature_maps, 3),\n image_shape[:2] + (feature_maps, image_shape[-1])]\n return output_shape\n\ndef build_PointNet_Keras_Graph(point_cloud_tensor, pool_size, train_bn,\n name, out_number, last_activation=\"linear\", vector_size=1024):\n # transform to [batch, num_rois, h*w(576), 6, 16]\n x = KL.TimeDistributed(KL.Conv2D(16, (1, 2), padding=\"valid\"),\n name=f\"mrcnn_pointnet_{name}_conv1\")(point_cloud_tensor)\n x = KL.TimeDistributed(KL.BatchNormalization(),\n name=f'mrcnn_pointnet_{name}_bn1')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n # transform to [batch, num_rois, h*w(576), 4, 32]\n x = KL.TimeDistributed(KL.Conv2D(32, (1, 3), padding=\"valid\"),\n name=f\"mrcnn_pointnet_{name}_conv2\")(x)\n x = KL.TimeDistributed(KL.BatchNormalization(),\n name=f'mrcnn_pointnet_{name}_bn2')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n # transform to [batch, num_rois, h*w(576), 1, 64]\n x = KL.TimeDistributed(KL.Conv2D(64, (1, 4), padding=\"valid\"),\n name=f\"mrcnn_pointnet_{name}_conv3\")(x)\n x = KL.TimeDistributed(KL.BatchNormalization(),\n name=f'mrcnn_pointnet_{name}_bn3')(x, training=train_bn)\n\n x = KL.Activation('relu')(x)\n # transform to [batch, num_rois, h*w(576), 1, 256]\n x = KL.TimeDistributed(KL.Conv2D(256, (1, 1), padding=\"valid\"),\n name=f\"mrcnn_pointnet_{name}_conv4\")(x)\n x = KL.TimeDistributed(KL.BatchNormalization(),\n name=f'mrcnn_pointnet_{name}_bn4')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n # transform to [batch, num_rois, h*w(576), 1, vector_size]\n x = KL.TimeDistributed(KL.Conv2D(vector_size, (1, 1), padding=\"valid\"),\n name=f\"mrcnn_pointnet_{name}_conv5\")(x)\n x = KL.TimeDistributed(KL.BatchNormalization(),\n name=f'mrcnn_pointnet_{name}_bn5')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n # transform to [batch, num_rois, 1, 1, vector_size]\n x = KL.TimeDistributed(KL.MaxPool2D((pool_size * pool_size, 1), padding=\"valid\"),\n name=f\"mrcnn_{name}_sym_max_pool\")(x)\n # transform to [batch, num_rois, vector_size]\n x = KL.Lambda(lambda y: tf.squeeze(y, axis=[2, 3]))(x)\n # transform to [batch, num_rois, 256]\n x = KL.TimeDistributed(KL.Dense(256),\n name=f\"mrcnn_pointnet_{name}_fc1\")(x)\n x = KL.TimeDistributed(KL.BatchNormalization(),\n name=f'mrcnn_pointnet_{name}_bn6')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n # transform to [batch, num_rois, 128]\n x = KL.TimeDistributed(KL.Dense(128),\n name=f\"mrcnn_pointnet_{name}_fc2\")(x)\n x = KL.TimeDistributed(KL.BatchNormalization(),\n name=f'mrcnn_pointnet_{name}_bn7')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n # [batch, num_rois, out_number]\n x = KL.TimeDistributed(KL.Dense(out_number, activation=last_activation),\n name=f\"mrcnn_pointnet_{name}_fc3\")(x)\n return x\n\nclass CalcRotMatrix(KL.Layer):\n def __init__(self, config, **kwargs):\n super(CalcRotMatrix, self).__init__(**kwargs)\n self.batch_shape = [config.BATCH_SIZE,\n config.TRAIN_ROIS_PER_IMAGE,\n config.NUM_CLASSES]\n def call(self, inputs, **kwargs):\n \"\"\"\n Transformes a Matrix with 2 out of 3 column vectors of a rotation matrix available\n From:\n https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d/476311#476311\n :param inputs: [batch, num_rois, 3, 2, num_classes]\n :param kwargs:\n :return:\n \"\"\"\n # transpose to [batch, num_rois, num_classes, 2, 3]\n inputs = tf.transpose(inputs, [0, 1, 4, 3, 2], \"transpose_inputs\")\n # split the column vectors; [batch, num_rois, num_classes, 3]\n a, b = tf.split(inputs, 2, axis=3, name=\"split_inputs\")\n a = tf.squeeze(a, axis=3, name=\"squeeze_a\")\n b = tf.squeeze(b, axis=3, name=\"squeeze_b\")\n # calculate the norm of the vectors\n a_norm = tf.sqrt(tf.reduce_sum(tf.square(a), axis=3, keepdims=True) + 1e-8, name=\"a_norm\")\n b_norm = tf.sqrt(tf.reduce_sum(tf.square(b), axis=3, keepdims=True) + 1e-8, name=\"b_norm\")\n # transfrom them into unit vectors\n a = a / a_norm\n b = b / b_norm\n # [batch, num_rois, num_classes, 1]\n # dot product of the last dimensions (3-vectors); cosine of angle\n c = tf.squeeze(\n tf.matmul(\n tf.expand_dims(a, -1), tf.expand_dims(b, -1),\n transpose_a=True),\n axis=-1)\n v = tf.linalg.cross(a, b)\n v_1 = v[:, :, :, 0]\n v_2 = v[:, :, :, 1]\n v_3 = v[:, :, :, 2]\n zero_element = tf.zeros_like(v_1)\n # skew-symmetric cross-product matrix of v; [batch, num_rois, num_classes, 9]\n skew_symmetric_v = tf.stack([zero_element, -v_3, v_2, v_3, zero_element,\n -v_1, -v_2, v_1, zero_element], axis=-1)\n # reshape to [batch, num_rois, num_classes, 3, 3]\n skew_symmetric_v = tf.reshape(skew_symmetric_v, self.batch_shape + [3, 3])\n identity_matrix = tf.eye(3, batch_shape=self.batch_shape)\n # the factor is 0 iff cos(a, b) = -1, i.e. when they point in opposite directions\n # [batch, num_rois, num_classes, 1]\n factor = tf.div_no_nan(tf.ones_like(c), 1 + c)\n # broadcast to [batch, num_rois, num_classes, 3, 3] for multiplication\n factor = tf.broadcast_to(tf.expand_dims(factor, -1), skew_symmetric_v.shape)\n rot = identity_matrix + skew_symmetric_v + tf.multiply(tf.matmul(skew_symmetric_v, skew_symmetric_v), factor)\n\n # [batch, num_rois, num_classes, 3, 3] --> [batch, num_rois, 3, 3, num_classes]\n # TODO: check if this is correct\n rot = tf.transpose(rot, [0, 1, 3, 4, 2])\n return rot\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], 3, 3, input_shape[-1])\n\ndef build_fpn_pointnet_pose_graph(rois, feature_maps, depth_image, image_meta, intrinsic_matrices,\n config, pool_size=18, train_bn=True):\n \"\"\"Builds the computation graph of the pose estimation head of Feature Pyramid Network.\n\n rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized\n coordinates.\n feature_maps: List of feature maps from different layers of the pyramid,\n [P2, P3, P4, P5]. Each has a different resolution.\n image_meta: [batch, (meta data)] Image details. See compose_image_meta()\n intrinsic_matrices: [batch, 3, 3] Intrinsic Matrix of the camera batch was taken with\n train_bn: Boolean. Train or freeze Batch Norm layers\n\n Returns: Trans [[batch, num_rois, 3, 1, num_classes]\n \"\"\"\n # TODO: as it seems, TRAIN_ROIS_PER_IMAGE (200) becomes DETECTION_MAX_INSTANCES (100) for inference\n # ROIAlign returning [batch, num_rois, 24, 24, channels] so that in the end a 4x4 matrix\n # is predicted for every class\n x, d = keras_util.PyramidROIAlign([pool_size, pool_size], depth_image=depth_image,\n name=\"roi_align_pointnet_pose\")([rois, image_meta] + feature_maps)\n # pcl_list = [batch, num_rois, h*w(576), (xq, y, z)], feature_list = [batch, num_rois, h*w, channels]\n # TODO: add masking from the previous branch; i.e. use predicted object masks here\n pcl_list, feature_list = FeaturePointCloud((pool_size, pool_size), config,\n name=\"FeaturePointCloud\")([rois, x, d, intrinsic_matrices])\n # transfrom to [batch, num_rois, h*w, (x, y, z), 1]\n pcl_list = KL.Lambda(lambda y: tf.expand_dims(y, -1), name=\"expand_pcl_list\")(pcl_list)\n # expand to [batch, num_rois, h*w, channels, 1]\n feature_list = KL.Lambda(lambda y: tf.expand_dims(y, -1), name=\"expand_feature_list\")(feature_list)\n # transform to [batch, num_rois, h*w, 4, 1]\n feature_list = KL.TimeDistributed(KL.Conv2D(1, (1, int(config.TOP_DOWN_PYRAMID_SIZE / 4)),\n padding=\"valid\",\n strides=(1, int(config.TOP_DOWN_PYRAMID_SIZE / 4))),\n name=\"mrcnn_pose_feature_conv\")(feature_list)\n feature_list = KL.TimeDistributed(KL.BatchNormalization(),\n name='mrcnn_pose_feature_bn')(feature_list, training=train_bn)\n feature_list = KL.Activation('relu')(feature_list)\n # merge to [batch, num_rois, h*w(576), 7, 1]\n # print_op = tf.print([tf.shape(feature_list), tf.shape(pcl_list)])\n concat_point_cloud = KL.Lambda(lambda y: tf.concat([y[0], y[1]], axis=-2),\n name=\"point_cloud_repr_concat\")([pcl_list, feature_list])\n if config.POSE_ESTIMATION_METHOD is \"pointnet2\":\n concat_point_cloud = build_PointNet2_Feature_Graph(concat_point_cloud,\n train_bn, 0.5)\n trans = build_PointNet2_Regr_Graph(concat_point_cloud, pool_size, train_bn, \"trans\",\n 3 * config.NUM_CLASSES)\n rot = build_PointNet2_Regr_Graph(concat_point_cloud, pool_size, train_bn, \"rot\",\n 9 * config.NUM_CLASSES, last_activation=\"tanh\")\n else:\n trans = build_PointNet_Keras_Graph(concat_point_cloud, pool_size, train_bn, \"trans\",\n 3 * config.NUM_CLASSES,\n vector_size=config.POINTNET_VECTOR_SIZE)\n rot = build_PointNet_Keras_Graph(concat_point_cloud, pool_size, train_bn, \"rot\",\n 9 * config.NUM_CLASSES, last_activation=\"tanh\",\n vector_size=config.POINTNET_VECTOR_SIZE)\n # transform to [batch, num_rois, 3, 1, num_classes]\n trans = KL.Reshape((config.TRAIN_ROIS_PER_IMAGE,\n 3, 1, config.NUM_CLASSES), name=\"trans_reshape\")(trans)\n # [batch, num_rois, 3, 2, num_classes]\n rot = KL.Reshape((config.TRAIN_ROIS_PER_IMAGE,\n 3, 3, config.NUM_CLASSES), name=\"rot_reshape\")(rot)\n # [batch, num_rois, 3, 3, num_classes]; uses orthogonality of rotation matrices to calc\n # the third column vector\n # rot = CalcRotMatrix(name=\"CalcRotMatrix\", config=config)(rot)\n\n # print_op = tf.print([tf.shape(feature_list), tf.shape(pcl_list), tf.shape(point_cloud_repr),\n # tf.shape(x), tf.shape(shared), rot, trans])\n # with tf.control_dependencies([print_op]):\n # rot = KL.Lambda(lambda y: tf.identity(y), name=\"pose_identity_op\")(rot)\n return trans, rot\n\n########################################################################################################################\n# POINTNET++ #\n########################################################################################################################\n\nclass MultiScaleGroupingSetAbstractionLayer(KL.Layer):\n def __init__(self, npoint, radius_list, nsample_list,\n mlp_list, is_training, bn_decay, bn=True,\n use_xyz=True, use_nchw=False, **kwargs):\n super(MultiScaleGroupingSetAbstractionLayer, self).__init__(**kwargs)\n self.npoint = npoint\n self.radius_list = radius_list\n self.nsample_list = nsample_list\n self.mlp_list = mlp_list\n self.is_training = is_training\n self.bn_decay = bn_decay\n self.bn = bn\n self.use_xyz = use_xyz\n self.use_nchw = use_nchw\n\n def call(self, inputs, **kwargs):\n \"\"\"\n Set Abstraction with Multi-Scale Grouping\n :param inputs: [xyz, points]\n xyz: [batch, num_points, 3]\n points: [batch, num_points, channels]\n :param kwargs:\n :return: [new_xyz, new_points]\n new_xyz: [batch, npoint, 3]\n new_points: [batch, npoint, \\sum_k{mlp[k][-1]}]\n \"\"\"\n xyz = tf.slice(inputs, [0, 0, 0], [-1, -1, 3])\n points = tf.slice(inputs, [0, 0, 3], [-1, -1, -1])\n l_xyz, l_points = pointnet_sa_module_msg(xyz, points, npoint=self.npoint,\n radius_list=self.radius_list, nsample_list=self.nsample_list,\n mlp_list=self.mlp_list, is_training=self.is_training,\n bn_decay=self.bn_decay, bn=self.bn, use_xyz=self.use_xyz,\n use_nchw=self.use_nchw, scope=self.name)\n return tf.concat([l_xyz, l_points], axis=-1)\n\n def compute_output_shape(self, input_shape):\n batch = input_shape[0]\n channels = 0\n for l in self.mlp_list:\n channels += l[-1]\n return (batch, self.npoint, 3 + channels)\n\nclass SetAbstractionLayer(KL.Layer):\n def __init__(self, npoint, radius, nsample, mlp, mlp2,\n group_all, is_training, bn_decay, bn=True,\n pooling='max', knn=False, use_xyz=True,\n use_nchw=False, **kwargs):\n super(SetAbstractionLayer, self).__init__(**kwargs)\n self.npoint = npoint\n self.radius = radius\n self.nsample = nsample\n self.mlp = mlp\n self.mlp2 = mlp2\n self.group_all = group_all\n self.is_training = is_training\n self.bn_decay = bn_decay\n self.bn = bn\n self.pooling = pooling\n self.knn = knn\n self.use_xyz = use_xyz\n self.use_nchw = use_nchw\n\n def call(self, inputs, **kwargs):\n xyz = tf.slice(inputs, [0, 0, 0], [-1, -1, 3])\n points = tf.slice(inputs, [0, 0, 3], [-1, -1, -1])\n l_xyz, l_points, _ = pointnet_sa_module(xyz, points, npoint=self.npoint,\n radius=self.radius, nsample=self.nsample,\n mlp=self.mlp, mlp2=self.mlp2,\n group_all=self.group_all,\n is_training=self.is_training,\n bn_decay=self.bn_decay, scope=self.name,\n bn=self.bn, pooling=self.pooling,\n knn=self.knn, use_xyz=self.use_xyz,\n use_nchw=self.use_nchw)\n return tf.concat([l_xyz, l_points], axis=-1)\n\n def compute_output_shape(self, input_shape):\n batch = input_shape[0]\n channels = self.mlp2[-1] if self.mlp2 is not None else self.mlp[-1]\n return (batch, self.npoint, 3 + channels)\n\nclass FeaturePropagationLayer(KL.Layer):\n def __init__(self, mlp, is_training, bn_decay, bn=True, **kwargs):\n super(FeaturePropagationLayer, self).__init__(**kwargs)\n self.mlp = mlp\n self.is_training = is_training\n self.bn_decay = bn_decay\n self.bn = bn\n\n def call(self, inputs, **kwargs):\n xyz1 = tf.slice(inputs[0], [0, 0, 0, 0], [-1, -1, -1, 3])\n points1 = tf.slice(inputs[0], [0, 0, 0, 3], [-1, -1, -1, -1])\n xyz2 = tf.slice(inputs[1], [0, 0, 0, 0], [-1, -1, -1, 3])\n points2 = tf.slice(inputs[1], [0, 0, 0, 3], [-1, -1, -1, -1])\n num_rois = xyz1.get_shape()[1]\n points = []\n for i in range(num_rois):\n new_points = pointnet_fp_module(xyz1[:, i, :, :], xyz2[:, i, :, :], points1[:, i, :, :], points2[:, i, :, :],\n mlp=self.mlp, is_training=self.is_training,\n bn_decay=self.bn_decay, scope=self.name+f\"_{i}\", bn=self.bn)\n points.append(new_points)\n return tf.concat([xyz1, tf.stack(points, axis=1)], axis=-1)\n\n def compute_output_shape(self, input_shape):\n xyz1_shape = input_shape[0]\n return (xyz1_shape[0], xyz1_shape[1], xyz1_shape[2], 3 + self.mlp[-1])\n\n\ndef build_PointNet2_Feature_Graph(concat_points, is_training, bn_decay):\n # Set abstraction layers\n # [batch, num_rois, pool_size², 7, 1]\n concat_points = KL.Lambda(lambda y: tf.squeeze(y, axis=-1))(concat_points)\n # [batch, num_rois, 128, 323] = [batch, num_rois, 128, 3] + [batch, num_rois, 128, 320]\n l1_concat = KL.TimeDistributed(MultiScaleGroupingSetAbstractionLayer(128, [0.2, 0.4, 0.8],\n [32, 64, 128],\n [[32, 32, 64], [64, 64, 128], [64, 96, 128]],\n is_training, bn_decay,\n name='msg_layer1'))(concat_points)\n # [batch, num_rois, 32, 643] = [batch, num_rois, 32, 3] + [batch, num_rois, 32, 640]\n l2_concat = KL.TimeDistributed(MultiScaleGroupingSetAbstractionLayer(32, [0.4, 0.8, 1.6], [64, 64, 128],\n [[64, 64, 128], [128, 128, 256], [128, 128, 256]],\n is_training, bn_decay,\n name='msg_layer2'))(l1_concat)\n # [batch, num_rois, 1, 1027] = [batch, num_rois, 1, 3] + [batch, num_rois, 1, 1024]\n l3_concat = KL.TimeDistributed(SetAbstractionLayer(npoint=None, radius=None, nsample=None,\n mlp=[128, 256, 1024], mlp2=None, group_all=True,\n is_training=is_training, bn_decay=bn_decay,\n name='layer3'))(l2_concat)\n\n # Feature Propagation layers\n # l3_points = tf.concat([l3_points, tf.expand_dims(one_hot_vec, 1)], axis=2)\n # [batch, num_rois, 32, 131] = [batch, num_rois, 32, 3] + [batch, num_rois, 32, 128]\n l2_concat = FeaturePropagationLayer([128, 128], is_training, bn_decay,\n name='fa_layer1')([l2_concat, l3_concat])\n # [batch, num_rois, 128, 131] = [batch, num_rois, 128, 3] + [batch, num_rois, 128, 128]\n l1_concat = FeaturePropagationLayer([128, 128], is_training, bn_decay,\n name='fa_layer2')([l1_concat, l2_concat])\n # [batch, num_rois, pool_size², 131]\n l0_concat = FeaturePropagationLayer([128, 128], is_training, bn_decay,\n name='fa_layer3')([concat_points, l1_concat])\n # [batch, num_rois, pool_size², 128, 1]\n l0_points = KL.Lambda(lambda y: tf.expand_dims(tf.slice(y, [0, 0, 0, 3],\n [-1, -1, -1, -1]),\n axis=-1))(l0_concat)\n # FC layers\n # net = KL.TimeDistributed(KL.Lambda(lambda y: tf_util.conv1d(y, 128, 1, padding='VALID', bn=True,\n # is_training=is_training,\n # bn_decay=bn_decay), name='conv1d-fc1'))(l0_points)\n # net = KL.TimeDistributed(KL.Lambda(lambda y: tf_util.dropout(y, keep_prob=0.7,\n # is_training=is_training), name=\"dp1\"))(net)\n # logits = KL.TimeDistributed(KL.Lambda(lambda y: tf_util.conv1d(y, out_number, 1, padding='VALID',\n # activation_fn=None),\n # name=\"conv1d-fc2\"))(net)\n return l0_points\n\ndef build_PointNet2_Regr_Graph(point_cloud_tensor, pool_size, train_bn,\n name, out_number, last_activation=\"linear\"):\n # transform to [batch, num_rois, h*w(576), 1, 64]\n x = KL.TimeDistributed(KL.Conv2D(128, (1, 128), padding=\"valid\"),\n name=f\"mrcnn_pointnet_{name}_conv1\")(point_cloud_tensor)\n x = KL.TimeDistributed(KL.BatchNormalization(),\n name=f'mrcnn_pointnet_{name}_bn1')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n x = KL.TimeDistributed(KL.Conv2D(128, (1, 1), padding=\"valid\"),\n name=f\"mrcnn_pointnet_{name}_conv2\")(x)\n x = KL.TimeDistributed(KL.BatchNormalization(),\n name=f'mrcnn_pointnet_{name}_bn2')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n # transform to [batch, num_rois, h*w(576), 1, 256]\n x = KL.TimeDistributed(KL.Conv2D(256, (1, 1), padding=\"valid\"),\n name=f\"mrcnn_pointnet_{name}_conv4\")(x)\n x = KL.TimeDistributed(KL.BatchNormalization(),\n name=f'mrcnn_pointnet_{name}_bn4')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n # transform to [batch, num_rois, 1, 1, vector_size]\n x = KL.TimeDistributed(KL.MaxPool2D((pool_size * pool_size, 1), padding=\"valid\"),\n name=f\"mrcnn_{name}_sym_max_pool\")(x)\n # transform to [batch, num_rois, vector_size]\n x = KL.Lambda(lambda y: tf.squeeze(y, axis=[2, 3]))(x)\n # transform to [batch, num_rois, 256]\n x = KL.TimeDistributed(KL.Dense(256),\n name=f\"mrcnn_pointnet_{name}_fc1\")(x)\n x = KL.TimeDistributed(KL.BatchNormalization(),\n name=f'mrcnn_pointnet_{name}_bn6')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n # transform to [batch, num_rois, 128]\n x = KL.TimeDistributed(KL.Dense(128),\n name=f\"mrcnn_pointnet_{name}_fc2\")(x)\n x = KL.TimeDistributed(KL.BatchNormalization(),\n name=f'mrcnn_pointnet_{name}_bn7')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n # [batch, num_rois, out_number]\n x = KL.TimeDistributed(KL.Dense(out_number, activation=last_activation),\n name=f\"mrcnn_pointnet_{name}_fc3\")(x)\n return x","sub_path":"mrcnn/pointnet_pose_estimation.py","file_name":"pointnet_pose_estimation.py","file_ext":"py","file_size_in_byte":28220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"439630669","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\n\nfrom typing import TYPE_CHECKING\n\nfrom azure.mgmt.core import ARMPipelineClient\nfrom msrest import Deserializer, Serializer\n\nif TYPE_CHECKING:\n # pylint: disable=unused-import,ungrouped-imports\n from typing import Any, Optional\n\n from azure.core.credentials import TokenCredential\n\nfrom ._configuration import ProviderHubConfiguration\nfrom .operations import CustomRolloutsOperations\nfrom .operations import DefaultRolloutsOperations\nfrom .operations import ProviderHubOperationsMixin\nfrom .operations import NotificationRegistrationsOperations\nfrom .operations import Operations\nfrom .operations import ProviderRegistrationsOperations\nfrom .operations import ResourceTypeRegistrationsOperations\nfrom .operations import ResourceTypeRegistrationOperations\nfrom .operations import SkusOperations\nfrom . import models\n\n\nclass ProviderHub(ProviderHubOperationsMixin):\n \"\"\"Microsoft ProviderHub.\n\n :ivar custom_rollouts: CustomRolloutsOperations operations\n :vartype custom_rollouts: provider_hub.operations.CustomRolloutsOperations\n :ivar default_rollouts: DefaultRolloutsOperations operations\n :vartype default_rollouts: provider_hub.operations.DefaultRolloutsOperations\n :ivar providerhub_operations: ProviderHubOperationsMixin operations\n :vartype providerhub_operations: provider_hub.operations.ProviderHubOperationsMixin\n :ivar notification_registrations: NotificationRegistrationsOperations operations\n :vartype notification_registrations: provider_hub.operations.NotificationRegistrationsOperations\n :ivar operations: Operations operations\n :vartype operations: provider_hub.operations.Operations\n :ivar provider_registrations: ProviderRegistrationsOperations operations\n :vartype provider_registrations: provider_hub.operations.ProviderRegistrationsOperations\n :ivar resource_type_registrations: ResourceTypeRegistrationsOperations operations\n :vartype resource_type_registrations: provider_hub.operations.ResourceTypeRegistrationsOperations\n :ivar resource_type_registration: ResourceTypeRegistrationOperations operations\n :vartype resource_type_registration: provider_hub.operations.ResourceTypeRegistrationOperations\n :ivar skus: SkusOperations operations\n :vartype skus: provider_hub.operations.SkusOperations\n :param credential: Credential needed for the client to connect to Azure.\n :type credential: ~azure.core.credentials.TokenCredential\n :param subscription_id: The ID of the target subscription.\n :type subscription_id: str\n :param str base_url: Service URL\n :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n \"\"\"\n\n def __init__(\n self,\n credential, # type: \"TokenCredential\"\n subscription_id, # type: str\n base_url=None, # type: Optional[str]\n **kwargs # type: Any\n ):\n # type: (...) -> None\n if not base_url:\n base_url = 'https://management.azure.com'\n self._config = ProviderHubConfiguration(credential, subscription_id, **kwargs)\n self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs)\n\n client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}\n self._serialize = Serializer(client_models)\n self._deserialize = Deserializer(client_models)\n\n self.providerhub_operations = ProviderHubOperationsMixin(\n self._client, self._config, self._serialize, self._deserialize)\n self.custom_rollouts = CustomRolloutsOperations(\n self._client, self._config, self._serialize, self._deserialize)\n self.default_rollouts = DefaultRolloutsOperations(\n self._client, self._config, self._serialize, self._deserialize)\n self.notification_registrations = NotificationRegistrationsOperations(\n self._client, self._config, self._serialize, self._deserialize)\n self.operations = Operations(\n self._client, self._config, self._serialize, self._deserialize)\n self.provider_registrations = ProviderRegistrationsOperations(\n self._client, self._config, self._serialize, self._deserialize)\n self.resource_type_registrations = ResourceTypeRegistrationsOperations(\n self._client, self._config, self._serialize, self._deserialize)\n self.resource_type_registration = ResourceTypeRegistrationOperations(\n self._client, self._config, self._serialize, self._deserialize)\n self.skus = SkusOperations(\n self._client, self._config, self._serialize, self._deserialize)\n\n def close(self):\n # type: () -> None\n self._client.close()\n\n def __enter__(self):\n # type: () -> ProviderHub\n self._client.__enter__()\n return self\n\n def __exit__(self, *exc_details):\n # type: (Any) -> None\n self._client.__exit__(*exc_details)\n","sub_path":"src/providerhub/azext_providerhub/vendored_sdks/providerhub/_provider_hub.py","file_name":"_provider_hub.py","file_ext":"py","file_size_in_byte":5400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"620250176","text":"from Hash import TablaHash\n\nclass Database:\n \"\"\"\n @description Constructor, llamado por el método createDatabase(nombre: str) -> int\n @param nombre, debe cumplir con las reglas de identificadores de SQL\n @return\n 0 operación exitosa\n 1 error en la operación \n 2 base de datos existente\n \"\"\"\n def __init__(self, name):\n self.name = name\n self.tables = []\n\n \"\"\"\n alterDatabase(databaseNew) -> int\n @param databaseNew, nombre nuevo de la base de datos\n \"\"\"\n def setName(self, databaseNew):\n self.name = databaseNew\n\n def getName(self):\n return self.name\n\n def getTable(self, indice):\n return self.tables[indice]\n\n \"\"\"\n prototype method\n \"\"\"\n def buscarTable(self, name):\n if len(self.tables) != 0:\n for table in self.tables:\n if name == table.getName():\n #encontrada\n return self.tables.index(table)\n return None\n\n def dropTable(self, indice):\n try:\n self.tables.pop(indice)\n return 0\n except: \n return 1\n\n \"\"\"\n createTable(size(default), database, table, nCols) -> int\n \"\"\"\n def createTable(self, size, table, nCols):\n try:\n if self.buscarTable(table) != None:\n # print(\"Tabla existente\")\n return 3\n else:\n hashTable = TablaHash(size, table, nCols)\n self.tables.append(hashTable)\n return 0\n except: \n print(\"Error en la operación\")\n return 1\n \n def showTables(self):\n tables = []\n for table in self.tables:\n tables.append(table.getName())\n return tables\n\n def extractTable2(self,table):\n try:\n if self.buscarTable(table) != None:\n #print(\"Tabla existente\")\n index = self.buscarTable(table)\n table = self.tables[index] \n return table.printlistTbl()\n else:\n # print(\"Tabla NO existente\")\n return None\n except: \n # print(\"Error en la operación\")\n return None\n\n def extractRangeTable2(self,table,columnNumber,lower,upper):\n try:\n if self.buscarTable(table) != None:\n #print(\"Tabla existente\")\n index = self.buscarTable(table)\n table = self.tables[index] \n return table.imp1(columnNumber,lower,upper) ##Cambiar esto\n else:\n # print(\"Tabla NO existente\")\n return None\n except: \n # print(\"Error en la operación\")\n return None\n\n def alterAddPK(self, name, columns):\n try:\n if self.buscarTable(name) != None:\n index = self.buscarTable(name)\n table = self.tables[index]\n return table.alterAddPK(columns)\n else:\n # print(\"Tabla Inexistente\")\n return 3\n except: \n # print(\"Error en la operación\")\n return 1\n\n def alterTable(self, old, new):\n try:\n if self.buscarTable(old) != None:\n index = self.buscarTable(old)\n table = self.tables[index]\n tableNew = None\n\n if self.buscarTable(new) is not None:\n tableNew = self.tables[self.buscarTable(new)]\n\n if tableNew and tableNew.getName() == new:\n return 4\n else:\n table.setName(new)\n return 0\n else:\n return 3\n except: \n print(\"Error en la operación\")\n return 1\n\n def insert(self, name, register):\n try:\n if self.buscarTable(name) != None:\n index = self.buscarTable(name)\n table = self.tables[index]\n return table.insert(table, register)\n else:\n # print(\"Tabla Inexistente\")\n return 3\n except: \n # print(\"Error en la operación\")\n return 1\n\n def update(self, name, columns):\n try:\n if self.buscarTable(name) != None:\n index = self.buscarTable(name)\n table = self.tables[index]\n # return table.editar()\n else:\n # print(\"Tabla Inexistente\")\n return 3\n except: \n # print(\"Error en la operación\")\n return 1\n","sub_path":"storage/team10/lib/DataBase.py","file_name":"DataBase.py","file_ext":"py","file_size_in_byte":4640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"72176726","text":"#!/usr/bin/env python\nimport sys\nsys.path.append('.')\nfrom app import db\nfrom app import Questions\n\ndef load():\n question = Questions(None,sys.argv[1])\n # Insert a row of data\n db.session.add(question)\n # Save (commit) the changes\n db.session.commit()\n\nif __name__ == \"__main__\":\n load()\n","sub_path":"load_db.py","file_name":"load_db.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"117237154","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nfrom falkor import views\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url('', include('social.apps.django_app.urls', namespace='social')),\n url(r'^login$', views.login),\n url(r'^$', views.home),\n url(r'^logout/$', views.logout),\n \n url(r'^workspaces/$', views.workspaces),\n]\n","sub_path":"hub/falkor_project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"339191509","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\nimport config\nimport time\nimport os\n\nlog_dir = config.log_dir\n\nfp = None\nfp_refresh_time = None\n\n# check if log folder exists\nif not os.path.exists(log_dir):\n os.mkdir(log_dir)\n \ndef _refresh_fp():\n global fp\n global fp_refresh_time\n global log_dir\n \n # close\n if fp:\n fp.close()\n \n # get time\n time_ym = time.strftime('%y_%m')\n time_day = time.strftime('%d')\n \n # check folder\n dir_str = log_dir + '/' + time_ym\n if not os.path.exists(dir_str):\n os.mkdir(dir_str)\n \n # open file\n if fp == None:\n filename = dir_str + '/' + time_day + '.log' \n \n # check if file exists\n if not os.path.exists(filename):\n fp = open(filename, 'w')\n else:\n fp = open(filename, 'a')\n \n # refresh time\n fp_refresh_time = time_day\n\n\ndef write(string):\n global fp\n \n if config.log_en == False:\n return\n \n if fp == None or time.strftime('%d') != fp_refresh_time:\n _refresh_fp()\n \n time_str_in_log = time.strftime('%y-%m-%d %H:%M:%S ')\n \n # write\n fp.write(time_str_in_log + string + '\\n')\n fp.flush()\n \nif __name__ == '__main__':\n write('test_1')\n write('test_2')\n write('test_3')\n pass","sub_path":"osp_sai_2.1.8/system/apps/rpcapi/base/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"4670305","text":"import sublime\nimport sublime_plugin\nimport os.path\n\nclass OpenCommand(sublime_plugin.WindowCommand):\n\n def run(self):\n self.window.show_input_panel('Path:', '', self.open, None, None)\n\n def open(self, path):\n\n try:\n if not os.path.isfile(path):\n raise IOError1\n\n self.window.open_file(path)\n except:\n sublime.error_message('OpenFromPath Error: Could not open this file.')","sub_path":"OpenFromPath.py","file_name":"OpenFromPath.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"388090441","text":"from twilio.rest import Client\nimport threading\nfrom threading import Thread\n\n# Set values from twilio account\naccount_sid = \"AC**********\" # Found in Twilio dashboard\nauth_token = \"*************\" # Found in twilio dashboard\nclient = Client(account_sid, auth_token)\n\n\n\n#update with account info, all phone numbers have no spaces \ndef callout():\n\ttry:\n\t\tcall = client.calls.create(to =\"+1numbertocall\", \n \t\tfrom_=\"+a verified number\", \n \t\turl =\"http://webserver/with/twiml.xml\") #this is the webserver w/ twiml message\n\texcept:\n\t\tprint('Test Unsuccessful')\n\n\tprint('Call Executed to: ' + call.to_formatted)\n# Change conditions to alter call volume currently set to 3 calls\ni = 0\nwhile True:\n callout()\n i = i + 1\n if(i > 2):\n break","sub_path":"pycallsyou.py","file_name":"pycallsyou.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"9868784","text":"import pyflann\nimport scipy.io as sio\nimport numpy as np\nimport cv2 as cv\nimport time\n\nfrom util.synthetic_util import SyntheticUtil\nfrom util.iou_util import IouUtil\nfrom util.projective_camera import ProjectiveCamera\n\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--feature-type', required=True, type=str, default='deep', help='deep or HoG')\nparser.add_argument('--query-index', required=True, type=int, default=0, help='[0, 186)')\n\nargs = parser.parse_args()\nfeature_type = args.feature_type\nassert feature_type == 'deep' or feature_type == 'HoG'\nquery_index = args.query_index\nassert 0 <= query_index < 186\n\n\"\"\"\nEstimate an homogrpahy using edge images \n\"\"\"\n\n# Step 1: load data\n# database\nif feature_type == 'deep':\n data = sio.loadmat('../data/features/database_camera_feature.mat')\n database_features = data['features']\n database_cameras = data['cameras']\nelse:\n data = sio.loadmat('../data/features/database_camera_feature_HoG.mat')\n database_features = data['features']\n database_cameras = data['cameras']\n\n# testing edge image from two-GAN\nif feature_type == 'deep':\n data = sio.loadmat('../data/features/testset_feature.mat')\n edge_map = data['edge_map']\n test_features = data['features']\n test_features = np.transpose(test_features)\nelse:\n data = sio.loadmat('../data/features/testset_feature_HoG.mat')\n edge_map = data['edge_map']\n test_features = data['features']\n\n# World Cup soccer template\ndata = sio.loadmat('../data/worldcup2014.mat')\nmodel_points = data['points']\nmodel_line_index = data['line_segment_index']\n\ntemplate_h = 74 # yard, soccer template\ntemplate_w = 115\n\n\n# ground truth homography\ndata = sio.loadmat('../data/UoT_soccer/test.mat')\nannotation = data['annotation']\ngt_h = annotation[0][query_index][1] # ground truth\n\n\nstate_time = time.time()\n# Step 2: retrieve a camera using deep features\nflann = pyflann.FLANN()\nresult, _ = flann.nn(database_features, test_features[query_index], 1, algorithm=\"kdtree\", trees=8, checks=64)\nretrieved_index = result[0]\n\n\n\"\"\"\nRetrieval camera: get the nearest-neighbor camera from database\n\"\"\"\nretrieved_camera_data = database_cameras[retrieved_index]\n\nu, v, fl = retrieved_camera_data[0:3]\nrod_rot = retrieved_camera_data[3:6]\ncc = retrieved_camera_data[6:9]\n\nretrieved_camera = ProjectiveCamera(fl, u, v, cc, rod_rot)\n\nretrieved_h = IouUtil.template_to_image_homography_uot(retrieved_camera, template_h, template_w)\n\niou_1 = IouUtil.iou_on_template_uot(gt_h, retrieved_h)\nprint('retrieved homogrpahy IoU {:.3f}'.format(iou_1))\n\nretrieved_image = SyntheticUtil.camera_to_edge_image(retrieved_camera_data, model_points, model_line_index,\n im_h=720, im_w=1280, line_width=4)\n\nquery_image = edge_map[:,:,:,query_index]\n#cv.imshow('Edge image of query image', query_image)\n#cv.imshow('Edge image of retrieved camera', retrieved_image)\n#cv.waitKey(10000)\n\n\"\"\"\nRefine camera: refine camera pose using Lucas-Kanade algorithm \n\"\"\"\ndist_threshold = 50\nquery_dist = SyntheticUtil.distance_transform(query_image)\nretrieved_dist = SyntheticUtil.distance_transform(retrieved_image)\n\nquery_dist[query_dist > dist_threshold] = dist_threshold\nretrieved_dist[retrieved_dist > dist_threshold] = dist_threshold\n\n#cv.imshow('Distance image of query image', query_dist.astype(np.uint8))\n#cv.imshow('Distance image of retrieved camera', retrieved_dist.astype(np.uint8))\n#cv.waitKey(10000)\n\nh_retrieved_to_query = SyntheticUtil.find_transform(retrieved_dist, query_dist)\n\nrefined_h = h_retrieved_to_query@retrieved_h\niou_2 = IouUtil.iou_on_template_uot(gt_h, refined_h)\nprint('refined homogrpahy IoU {:.3f}'.format(iou_2))\nprint('takes time {:.3f} seconds'.format(time.time()-state_time))\n\n\n","sub_path":"python/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":3751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"372986519","text":"#!/usr/bin/python3\n\nimport tornado.web\nimport redis\nimport json\nimport time\nimport keys\nimport shunlu_config\n\ncharset = \"utf-8\"\n\n\nclass CreateOrdersService(object):\n def __init__(self):\n self.rds = redis.StrictRedis(shunlu_config.redis_ip, shunlu_config.redis_port)\n\n def saveOrder(self, data):\n order_id = -1\n if self.rds.exists(keys.newest_k):\n order_id = self.rds.get(keys.newest_k)\n self.rds.set(keys.newest_k, order_id+1)\n\n data[\"status\"] = 2\n data[\"worker_score\"] = 0\n data[\"master_score\"] = 0\n data[\"worker_phone\"] = \"\"\n data[\"master_name\"] = self.getUserNickName(data[\"master_id\"])\n data[\"create_time\"] = time.time()\n\n json_str = json.dumps(data)\n\n order_lock = keys.newest_k + str(order_id)\n pipe = self.rds.pipeline()\n\n _order_id = -1\n for i in range(3):\n try:\n pipe.watch(order_lock)\n pipe.set(order_lock,1)\n pipe.set(str(order_id) , order_dict)\n master_key = keys.master_k_prefix + str(user_id)\n pipe.sadd(master_key, order_id)\n pipe.sadd(keys.pending_orders_k, order_id)\n pipe.set(order_lock,0)\n pipe.execute()\n _order_id = order_id\n except Exception:\n print('save order failed!')\n continue\n return _order_id\n\n\n def getUserNickName(self, user_id):\n user_key = keys.user_k_prefix + str(user_id)\n user_name = (self.rds.hmget(user_key, \"user_name\")[0]).decode(charset)\n return user_name\n\n\n\nclass CreateOrdersHandler(tornado.web.RequestHandler):\n service = CreateOrdersService()\n\n def post(self):\n #worker_id = self.get_argument(\"worker_id\") #接单人id\n #master_id = self.get_argument(\"master_id\") #发单人id\n # FIXME: here should edit\n worker_id = str(1)\n master_id = str(1)\n print(self.request.body)\n source_location = self.get_argument(\"source_location\") #订单来源地\n order_type = self.get_argument(\"order_type\") #订单类型\n destination_location = self.get_argument(\"destination_location\") #订单送达目的地\n sending_start_time = self.get_argument(\"sending_start_time\") #订单开始时间\n sending_end_time = self.get_argument(\"sending_end_time\") #订单截止时间\n money = self.get_argument(\"money\") #订单金额\n package_weight = self.get_argument(\"package_weight\") #包裹重量\n note = self.get_argument(\"note\") #备注\n # owner_info = self.get_argument(\"owner_info\")#拥有者信息\n owner_name = self.get_argument(\"owner_name\")\n owner_phone = self.get_argument(\"owner_phone\")\n owner_number = self.get_argument(\"owner_number\")\n owner_info = {\n \"owner_name\": owner_name,\n \"owner_phone\": owner_phone,\n \"owner_number\": owner_number\n }\n\n data = {\"worker_id\" : str(worker_id),\n \"master_id\" : str(master_id),\n \"order_type\": int(order_type),\n \"source_location\": str(source_location),\n \"destination_location\":str(destination_location),\n \"sending_start_time\":int(sending_start_time),\n \"sending_end_time\":int(sending_end_time),\n \"money\":int(money),\n \"package_weight\":int(package_weight),\n \"owner_info\": owner_info,\n \"note\":str(note)}\n\n result_number = self.service.saveOrder(data)\n\n self.set_header(\"Content-Type\", \"text/plain; charset=UTF-8\")\n self.write(str(result_number))\n\n","sub_path":"CreateOrder.py","file_name":"CreateOrder.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"348195782","text":"# @Time : 2021/7/1 4:50 下午\n# @Author : Bais\n# @Email : 17343001493@163.com\n# @File : views_if.py\n\nfrom django.http import JsonResponse\nfrom sign.models import Event, Guest\nfrom django.db.utils import IntegrityError\nfrom django.core.exceptions import ValidationError, ObjectDoesNotExist\nfrom django.views.decorators.csrf import csrf_exempt\nimport time\nfrom tools import Verify\nfrom log import logger\n\n\n@csrf_exempt\ndef add_event(request): # 添加发布会接口\n eid = request.POST.get('eid', '')\n name = request.POST.get('name', '')\n limit = request.POST.get('limit', '')\n status = request.POST.get('status', '')\n address = request.POST.get('address', '')\n start_time = request.POST.get('start_time', '')\n if eid == '' or name == '' or limit == '' or address == '' or start_time == '':\n return JsonResponse({'status': 10021, \"msg\": \"必填不能为空\"})\n\n result = Event.objects.filter(id=eid)\n logger.info(result)\n if result:\n return JsonResponse({\"status\": 10022, \"msg\": \"event id already exists\"})\n\n result = Event.objects.filter(name=name)\n if result:\n return JsonResponse({\"status\": 10023, \"msg\": \"event name already exists\"})\n\n if status == \"\":\n status = 1\n try:\n Event.objects.create(id=eid, name=name, limit=limit, address=address, status=int(status), start_time=start_time)\n\n except ValidationError as e:\n error = \"start_time format error. It must be in YYYY-MM-DD HH:MM:SS format.\"\n return JsonResponse({\"status\": 10024, \"msg\": error})\n\n return JsonResponse({\"status\": 200, \"msg\": \"add event success\"})\n\n\n# 查询发布会接口\n@csrf_exempt\ndef get_event_list(request):\n global event\n eid = request.GET.get('eid', '')\n name = request.GET.get('name', '')\n\n if eid == '' and name == '':\n return JsonResponse({\"status\": 10021, \"msg\": \"必填参数不能为空\"})\n\n if eid != '':\n event = dict()\n\n try:\n result = Event.objects.get(id=eid)\n except ObjectDoesNotExist:\n return JsonResponse({\"status\": 10022, \"msg\": \"query result is empty!\"})\n\n event[\"name\"] = result.name\n event['limit'] = result.limit\n event['status'] = result.status\n event['address'] = result.address\n event['start_time'] = result.start_time\n return JsonResponse({\"status\": 200, \"msg\": \"success\", \"data\": event})\n\n if name != \"\":\n datas = list()\n results = Event.objects.filter(name__contains=name)\n if results:\n for ret in results:\n event = dict()\n event['name'] = ret.name\n event['limit'] = ret.limitc\n event['status'] = ret.status\n event['address'] = ret.address\n event['start_time'] = ret.start_time\n datas.append(event)\n return JsonResponse({\"status\": 200, \"msg\": \"success\", \"data\": datas})\n else:\n return JsonResponse({\"status\": 10022, \"msg\": \"query result is empty!\"})\n\n\n# 添加发布会嘉宾\n@csrf_exempt\ndef add_guest(request):\n eid = request.POST.get(\"eid\", '') # 关联发布会id\n realname = request.POST.get(\"realname\", '') # 嘉宾姓名\n phone = request.POST.get(\"phone\", '') # 嘉宾手机号\n email = request.POST.get(\"email\", '') # 嘉宾邮箱\n\n # 判断嘉宾关联的发布会、姓名和手机号均不能为空\n if eid == '' or realname == '' or phone == '':\n return JsonResponse({\"status\": 10021, \"msg\": \"必填参数不能为空!\"})\n\n # 校验参数合法性\n phone = Verify.verify_phone(phone) # 检验phone\n logger.info(phone)\n logger.info(realname)\n if not phone:\n return JsonResponse({\"status\": 10026, \"msg\": \"phone参数不合法!\"})\n\n realname = Verify.verify_str(realname) # 检验realname\n if not realname:\n return JsonResponse({\"status\": 10026, \"msg\": \"realname参数不合法!\"})\n\n email = Verify.verify_email(email) # 检验email\n if not email:\n return JsonResponse({\"status\": 10026, \"msg\": \"email参数不合法!\"})\n\n # 判断嘉宾关联的发布会是否存在\n result = Event.objects.filter(id=eid)\n if not result:\n return JsonResponse({\"status\": 10022, \"msg\": \"该发布会不存在\"})\n\n # 判断关联的发布会的状态是否为True\n result = Event.objects.get(id=eid).status\n if not result:\n return JsonResponse({\"status\": 10023, \"msg\": \"event status is not available\"})\n\n # try:\n # result = Guest.objects.get(realname=realname)\n # print(result)\n # except ObjectDoesNotExist:\n # return JsonResponse({\"status\": 10025, \"msg\": \"您还没添加嘉宾呦!\"})\n # print('可以继续运行程序')\n # pass\n result = Guest.objects.filter(realname=realname)\n if result:\n return JsonResponse({\"status\": 10024, \"msg\": \"该嘉宾已添加过,请勿重复添加!\"})\n logger.info(result)\n\n # 判断手机号是否重复\n result = Guest.objects.filter(phone=phone)\n if result:\n return JsonResponse({\"status\": 10027, \"msg\": \"phone 重复!\"})\n\n event_limit = Event.objects.get(id=eid).limit # 获取发布会限制人数\n guest_limit = Guest.objects.filter(event_id=eid) # 发布会已添加的嘉宾人数\n\n if len(guest_limit) >= event_limit: # 嘉宾数是否大于发布会限制人数\n return JsonResponse({\"status\": 10024, \"msg\": \"发布会添加人数已达上限!\"})\n\n event_time = Event.objects.get(id=eid).start_time\n etime = str(event_time).split(\".\")[0]\n timeArray = time.strptime(etime, \"%Y-%m-%d %H:%M:%S\")\n e_time = int(time.mktime(timeArray))\n\n now_time = str(time.time())\n ntime = now_time.split(\".\")[0]\n n_time = int(ntime)\n\n if n_time >= e_time: # 当前添加嘉宾的时间是否大于发布会开始的时间\n return JsonResponse({\"status\": 10025, \"msg\": \"发布会已经开始了..\"})\n try:\n Guest.objects.create(realname=realname, phone=int(phone), email=email, sign=0, event_id=int(eid))\n except IntegrityError:\n return JsonResponse({\"status\": 10026, \"msg\": \"The event guest phone number repeat!\"})\n\n return JsonResponse({\"status\": 200, \"msg\": \"add guest success!\"})\n","sub_path":"sign/views_if.py","file_name":"views_if.py","file_ext":"py","file_size_in_byte":6248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"469340250","text":"from django.conf.urls import url\nfrom django.views.generic import TemplateView\nfrom django.contrib.auth.decorators import login_required\n\nfrom . import views\n\nurlpatterns = [\n url(r'^learningcircles/$', views.LearningCircleListView.as_view(), name='api_learningcircles'),\n url(r'^learningcircles/successes/$', views.FinalReportListView.as_view(), name='api_learningcircles_successes'),\n url(r'^learningcircles/topics/$', views.LearningCircleTopicListView.as_view(), name='api_learningcircle_topics'),\n url(r'^learningcircles/cities/$', views.cities, name='api_learningcircles_cities'),\n url(r'^courses/$', views.CourseListView.as_view(), name='api_courses'),\n url(r'^courses/topics/$', views.CourseTopicListView.as_view(), name='api_course_topics'),\n url(r'^courses/languages/$', views.CourseLanguageListView.as_view(), name='api_course_languages'),\n url(r'^courses/detect-platform/$', views.detect_platform_from_url, name='api_course_detect_platform'),\n url(r'^signup/$', views.SignupView.as_view(), name='api_learningcircles_signup'),\n url(r'^learning-circle/$', views.LearningCircleCreateView.as_view(), name='api_learningcircles_create'),\n url(r'^learning-circle/(?P[\\d]+)/$', views.LearningCircleUpdateView.as_view(), name='api_learningcircles_update'),\n url(r'^landing-page-learning-circles/$', views.LandingPageLearningCirclesView.as_view(), name='api_learningcircles_meetings'),\n url(r'^landing-page-stats/$', views.LandingPageStatsView.as_view(), name='api_landing_page_stats'),\n url(r'^upload_image/$', views.ImageUploadView.as_view(), name='api_image_upload'),\n url(r'^learning-circles-map/$', views.LearningCirclesMapView.as_view(), name='api_learningcircles_map'),\n url(r'^instagram-feed/$', views.InstagramFeed.as_view(), name='api_instagram_feed'),\n url(r'^teams/$', views.TeamListView.as_view(), name='api_teams'),\n url(r'^teams/(?P[\\d]+)/$', views.TeamDetailView.as_view(), name='api_teams_detail'),\n url(r'^teams/(?P[\\d]+)/invitation-url/create/$', views.create_team_invitation_url, name='api_teams_create_invitation_url'),\n url(r'^teams/(?P[\\d]+)/invitation-url/delete/$', views.delete_team_invitation_url, name='api_teams_delete_invitation_url'),\n url(r'^teams/members/$', views.TeamMembershipListView.as_view(), name='api_team_memberships'),\n url(r'^teams/invitations/$', views.TeamInvitationListView.as_view(), name='api_team_invitations'),\n url(r'^facilitator/invitations/$', views.facilitator_invitation_notifications, name='api_facilitator_invitations'),\n url(r'^announcements/$', views.AnnouncementListView.as_view(), name='api_announcements')\n]\n","sub_path":"studygroups/api_urls.py","file_name":"api_urls.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"243669335","text":"\"\"\"\r\nPopup Suche für pystunden.\r\n\"\"\"\r\nfrom tkinter import *\r\nfrom tkinter.ttk import *\r\nfrom tkinter.simpledialog import Dialog\r\nimport datetime\r\nimport re\r\nimport os\r\n\r\n\r\nclass EintragSuchen(Dialog):\r\n \"\"\"\r\n Popupfenster Suche.\r\n \"\"\" \r\n def __init__(self, master=None):\r\n # Setzt result None\r\n self.result = None\r\n \r\n self.master = master\r\n if os.name == 'nt':\r\n self.master.iconbitmap(\"pystunden.ico\")\r\n self.master.title(\"Eintrag suchen\")\r\n \r\n self.l1 = Label(self.master, text=\"Startdatum (JJJJ-MM-TT):\", width=22, \r\n anchor=E)\r\n self.l1.grid(row=0, sticky=W+E, padx=5, pady=5)\r\n self.l2 = Label(self.master, text=\"Enddatum (JJJJ-MM-TT):\", width=22, \r\n anchor=E)\r\n self.l2.grid(row=3, sticky=W+E, padx=5, pady=5) \r\n \r\n self.l3 = Label(self.master, text=\"Projekt:\", width=22, anchor=E)\r\n self.l3.grid(row=6, sticky=W+E, padx=5, pady=5)\r\n \r\n \r\n self.startdatum_error = Label(self.master)\r\n self.startdatum_error.grid(row=0, column=1, padx=5, pady=5, sticky=W)\r\n self.startdatum = Entry(self.startdatum_error, width=20)\r\n self.startdatum.grid(row=0, column=0, padx=5, pady=5)\r\n\r\n self.searchstart = IntVar(self.master)\r\n self.searchstart.set(1) \r\n self.check_startdatum = Checkbutton(self.master, \r\n text=\"In Suche einbeziehen?\", \r\n variable=self.searchstart,\r\n onvalue=1, offvalue=0)\r\n self.check_startdatum.grid(row=1, column=1, padx=5, sticky=W)\r\n \r\n self.space1 = Label(self.master)\r\n self.space1.grid(row=2, column=1)\r\n \r\n self.enddatum_error = Label(self.master)\r\n self.enddatum_error.grid(row=3, column=1, padx=5, pady=5, sticky=W)\r\n self.enddatum = Entry(self.enddatum_error, width=20)\r\n self.enddatum.grid(row=0, column=0, padx=5, pady=5)\r\n\r\n self.searchend = IntVar(self.master)\r\n self.searchend.set(1) \r\n self.check_enddatum = Checkbutton(self.master, \r\n text=\"In Suche einbeziehen?\", \r\n variable=self.searchend,\r\n onvalue=1, offvalue=0)\r\n self.check_enddatum.grid(row=4, column=1, padx=5, sticky=W)\r\n\r\n self.space2 = Label(self.master)\r\n self.space2.grid(row=5, column=1)\r\n \r\n self.projekt_error = Label(self.master)\r\n self.projekt_error.grid(row=6, column=1, padx=5, pady=5, sticky=W)\r\n self.projekt = Entry(self.projekt_error, width=40)\r\n self.projekt.grid(row=0, column=0, padx=5, pady=5)\r\n\r\n self.searchprojekt = IntVar(self.master)\r\n self.searchprojekt.set(0) \r\n self.check_projekt = Checkbutton(self.master, \r\n text=\"In Suche einbeziehen?\", \r\n variable=self.searchprojekt,\r\n onvalue=1, offvalue=0)\r\n self.check_projekt.grid(row=7, column=1, padx=5, sticky=W)\r\n\r\n self.button = Button(self.master, text=\"Suchen\", width=20, \r\n command=self.save)\r\n self.button.grid(row=8, column=0, padx=5, pady=5) \r\n \r\n self.button = Button(self.master, text=\"Beenden\", width=20,\r\n command=self.master.destroy)\r\n self.button.grid(row=8, column=1, sticky=E, padx=5, pady=5) \r\n # Populiert Start- und Enddatum\r\n now = datetime.datetime.today()\r\n self.startdatum.insert(0, \"{}-{:02d}-01\".format(now.year, now.month)) \r\n self.enddatum.insert(0, \"{}-{:02d}-31\".format(now.year, now.month)) \r\n # Bindings\r\n self.master.bind(\"\", self.save)\r\n # Verhindert Größenänderungen\r\n self.master.update()\r\n self.master.minsize(self.master.winfo_width(), \r\n self.master.winfo_height())\r\n self.master.maxsize(self.master.winfo_width(), \r\n self.master.winfo_height()) \r\n\r\n def save(self, event=None):\r\n \"\"\"\r\n Validiert alle Eingaben und setzt die Variable result als Ergebnis.\r\n \"\"\"\r\n startdatum = self.startdatum.get()\r\n enddatum = self.enddatum.get()\r\n projekt = self.projekt.get()\r\n \r\n searchstart = self.searchstart.get()\r\n searchend = self.searchend.get()\r\n searchprojekt = self.searchprojekt.get()\r\n \r\n validated_startdatum = None\r\n validated_enddatum = None\r\n validated_projekt = None\r\n \r\n if searchprojekt:\r\n try:\r\n validated_projekt = self.validate_projekt(projekt)\r\n except:\r\n self.projekt_error[\"background\"] = \"red\"\r\n self.projekt.focus_set()\r\n else:\r\n validated_projekt = \"None\"\r\n\r\n if searchend:\r\n try:\r\n validated_enddatum = self.validate_datum(enddatum)\r\n except:\r\n self.enddatum_error[\"background\"] = \"red\"\r\n self.enddatum.focus_set()\r\n else:\r\n validated_enddatum = \"None\"\r\n\r\n if searchstart:\r\n try:\r\n validated_startdatum = self.validate_datum(startdatum)\r\n except:\r\n self.startdatum_error[\"background\"] = \"red\"\r\n self.startdatum.focus_set()\r\n else:\r\n validated_startdatum = \"None\"\r\n \r\n\r\n if validated_startdatum and searchstart:\r\n self.startdatum_error[\"background\"] = \"green\"\r\n \r\n if validated_enddatum and searchend :\r\n self.enddatum_error[\"background\"] = \"green\" \r\n\r\n if validated_projekt and searchprojekt: \r\n self.projekt_error[\"background\"] = \"green\"\r\n \r\n if validated_startdatum and validated_enddatum and validated_projekt:\r\n if validated_startdatum <= validated_enddatum:\r\n self.result = (validated_startdatum, validated_enddatum, \r\n validated_projekt) \r\n self.master.destroy()\r\n else:\r\n self.enddatum_error[\"background\"] = \"red\" \r\n self.startdatum_error[\"background\"] = \"red\"\r\n self.startdatum.focus_set()\r\n \r\n def validate_datum(self, datum):\r\n \"\"\"\r\n Valiediert das Start- und Enddatum im Format JJJJ-MM-TT\r\n \"\"\"\r\n datum_pattern = \\\r\n r\"^(19|20)\\d\\d([- /.])(0[1-9]|1[012])\\2(0[1-9]|[12][0-9]|3[01])$\"\r\n regex = re.compile(datum_pattern)\r\n valid_date = regex.match(datum)\r\n\r\n if valid_date:\r\n return datum\r\n else:\r\n raise ValueError\r\n\r\n def validate_projekt(self, projekt):\r\n \"\"\"\r\n Valiediert Projekt auf \"nicht leer\".\r\n \"\"\"\r\n if projekt.strip():\r\n return projekt\r\n else:\r\n raise ValueError\r\n","sub_path":"popup_suchen.py","file_name":"popup_suchen.py","file_ext":"py","file_size_in_byte":7305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"20658464","text":"from django.utils.six import string_types\n\nFALSEY_STRINGS = (\n '0',\n 'false',\n '',\n)\n\n\ndef is_truthy(x):\n if isinstance(x, string_types):\n return x.lower() not in FALSEY_STRINGS\n return bool(x)\n","sub_path":"dynamic_rest/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"169438162","text":"import tensorflow as tf\nimport numpy as np\n\ndef project_tracklet_out_of_dataset(tracks, tracklet):\n\tt = np.expand_dims(np.expand_dims(tracklet, axis=0), axis=-1)\n\ttnorm = np.sqrt(np.sum(t**2))\n\tt /= tnorm\n\tolaps = np.sum(tracks * t, axis=(2, 3), keepdims=True)\n\treturn tracks - t * olaps\n\n# def deep_dream\n\ndef project_conv_unit_out_of_dataset(tracks, conv_unit, strides, mode):\n\tif mode == 'valid':\n\t\tnum_x_strides = (tracks[0, 0].shape[0] - conv_unit.shape[0]) // strides[0]\n\t\tnum_y_strides = (tracks[0, 0].shape[1] - conv_unit.shape[1]) // strides[1]\n\telif mode == 'same':\n\t\tnum_x_strides = tracks[0, 0].shape[0] // strides[0]\n\t\tnum_y_strides = tracks[0, 0].shape[1] // strides[1]\n\n\tfor i in range(num_x_strides):\n\t\tfor j in range(num_y_strides):\n\t\t\ttracklet = np.expand_dims(np.zeros_like(tracks[0, 0]), axis=0)\n\n\t\t\ti_start = i*strides[0]\n\t\t\ti_end = min(i*strides[0] + conv_unit.shape[0], tracklet.shape[0])\n\n\t\t\tj_start = j*strides[1]\n\t\t\tj_end = min(j*strides[1] + conv_unit.shape[1], tracklet.shape[1])\n\n\t\t\ttracklet[i_start: i_end, j_start: j_end] = conv_unit[0,:i_end - i_start, :j_end - j_start]\n\t\t\ttracks = project_tracklet_out_of_dataset(tracks, tracklet)\n\n\treturn tracks","sub_path":"py_datatools/datatools/manipulations.py","file_name":"manipulations.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"543521506","text":"# Copyright REFITT Team 2019. All rights reserved.\n#\n# This program is free software: you can redistribute it and/or modify it under the\n# terms of the Apache License (v2.0) as published by the Apache Software Foundation.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT ANY\n# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n# PARTICULAR PURPOSE. See the Apache License for more details.\n#\n# You should have received a copy of the Apache License along with this program.\n# If not, see .\n\n\"\"\"\nRuntime configuration for REFITT.\n\nFiles:\n /etc/refitt.toml System\n ~/.refitt/config.toml User\n .refitt/config.toml Local\n\"\"\"\n\n\n# standard libs\nimport os\nimport functools\nimport logging\n\n# external libs\nfrom cmdkit.config import Namespace, Configuration, ConfigurationError # noqa: unused\nfrom streamkit.core import config as _streamkit\n\n\n# module level logger\nlog = logging.getLogger(__name__)\n\n\nCWD = os.getcwd()\nHOME = os.getenv('HOME')\nROOT = os.getuid() == 0\nSITE = 'system' if ROOT else 'user'\nPATH = Namespace({\n 'system': {\n 'lib': '/var/lib/refitt',\n 'log': '/var/log/refitt',\n 'run': '/var/run/refitt',\n 'config': '/etc/refitt.toml'},\n 'user': {\n 'lib': f'{HOME}/.refitt/lib',\n 'log': f'{HOME}/.refitt/log',\n 'run': f'{HOME}/.refitt/run',\n 'config': f'{HOME}/.refitt/config.toml'},\n 'local': {\n 'lib': f'{CWD}/.refitt/lib',\n 'log': f'{CWD}/.refitt/log',\n 'run': f'{CWD}/.refitt/run',\n 'config': f'{CWD}/.refitt/config.toml'},\n})\n\n\n# environment variables and configuration files are automatically\n# depth-first merged with defaults\nDEFAULT = Namespace({\n\n 'database': {\n 'backend': 'sqlite',\n 'database': ':memory:'\n },\n\n 'logging': {\n 'level': 'warning',\n 'format': '%(asctime)s %(hostname)s %(levelname)-8s [%(name)s] %(msg)s',\n 'datefmt': '%Y-%m-%d %H:%M:%S',\n 'stream': {\n 'enabled': False,\n 'batchsize': 10,\n 'timeout': 5\n }\n },\n\n 'api': {\n 'site': 'https://api.refitt.org',\n 'port': None,\n 'login': 'https://refitt.org/profile/api_credentials'\n },\n\n 'daemon': {\n 'port': 50000,\n 'key': '__REFITT__DAEMON__KEY__', # this should be overridden\n 'refresh': 10, # seconds to wait before issuing keep-alive to services\n 'timeout': 4, # seconds to wait before hard kill services on interrupt\n },\n\n 'plasma': {\n 'memory': 1_000_000, # 1 MB\n 'socket': ''\n }\n})\n\n\n@functools.lru_cache(maxsize=None)\ndef get_site(key: str = None) -> Namespace:\n \"\"\"\n Return the file-system structure based on `key`.\n Automatically creates directories if needed.\n \"\"\"\n site = PATH[SITE] if key is None else PATH[key]\n for folder in ['lib', 'log', 'run']:\n if not os.path.isdir(site[folder]):\n log.debug(f'creating directory {site[folder]}')\n os.makedirs(site[folder], exist_ok=True)\n return site\n\n\ndef get_config() -> Configuration:\n \"\"\"Load configuration.\"\"\"\n return Configuration.from_local(env=True,\n prefix='REFITT',\n default=DEFAULT,\n system=PATH.system.config,\n user=PATH.user.config,\n local=PATH.local.config)\n\n\n# single global instance\nconfig = get_config()\n\n\ndef update_config(site: str, data: dict) -> None:\n \"\"\"\n Extend the current configuration and commit it to disk.\n\n Args:\n site (str):\n Either \"local\", \"user\", or \"system\"\n data (dict):\n Sectioned mappable to update configuration file.\n\n Example:\n >>> update_config('user', {\n ... 'database': {\n ... 'user': 'ABC123'\n ... }\n ... })\n \"\"\"\n path = get_site(site).config\n new_config = Namespace.from_local(path, ignore_if_missing=True)\n new_config.update(data)\n new_config.to_local(path)\n\n\n# inject configuration back into streamkit library\n# this needs to happen before streamkit is imported anywhere\n_streamkit.config.extend(refitt=Namespace({\n 'database': config.database,\n 'logging': config.logging\n}))\n","sub_path":"refitt/core/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"246963492","text":"#1\r\na = [\"ウォーキング・デッド\",\"アントラージュ\",\"ザ・ソブラノズ\",\"ヴァンパイア・ダイアリーズ\"]\r\nfor name in a:\r\n print(name)\r\n\r\n#2\r\nfor i in range(25,51):\r\n print(i)\r\n\r\n#3\r\nfor i,j in enumerate(a):\r\n print(i,j)\r\n\r\n\r\n#4\r\nwhile True :\r\n a = input(\"1~9の中から数字を1つ入力してください。qで強制終了:\")\r\n a = set({a}) \r\n b = {\"1\",\"3\",\"5\"}\r\n z = {\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"}\r\n if a <= b:\r\n print(\"正解\")\r\n elif a <= z:\r\n print(\"不正解\")\r\n elif a == set(\"q\"):\r\n break\r\n else :\r\n print(\"数字を入力するか、qで終了します\")\r\n\r\n#4解答例\r\nnumbers = [11, 32, 33, 15, 1]\r\nwhile True:\r\n answer = input(\"Guess a number or type q to quit.\")\r\n if answer == \"q\": # 文字列以外を考えるため必要な文字列処理は先に済ませておく\r\n break\r\n try: \r\n answer = int(answer) #必要な文字列処理が終わったあとに文字列を整数に変換する。\r\n except ValueError:\r\n print(\"please type a number or q to quit.\")\r\n if answer in numbers:\r\n print(\"You guessed correctly!\")\r\n else:\r\n print(\"You guessed incorrectly!\")\r\n\r\n#5\r\na = [8,19,148,4]\r\nb = [9,1,33,83]\r\nz = []\r\nfor i in a:\r\n for j in b:\r\n # z = z.append(i*j) #コマンド・クエリ分離の原則に反するためNoneを返す\r\n z.append(i*j)\r\nprint(z) \r\n\r\n \r\n\r\n\r\n","sub_path":"chap07.py","file_name":"chap07.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"550873215","text":"# python3\n\nimport sys, threading\n\nsys.setrecursionlimit(10 ** 6) # max depth of recursion\nthreading.stack_size(2 ** 27) # new thread will get stack of such size\n\n\nclass TreeNode:\n def __init__(self, val=None):\n self.val = val\n self.left = None\n self.right = None\n self.parent = None\n self.leftBound = ()\n self.rightBound = ()\n\n\nclass TreeOrders:\n def __init__(self):\n self.root = None\n self.nodesOrder = []\n self.key = []\n self.n = None\n self.left = []\n self.right = []\n\n def read(self):\n self.n = int(input())\n self.key = [TreeNode() for i in range(self.n)]\n self.left = [0 for i in range(self.n)]\n self.right = [0 for i in range(self.n)]\n for i in range(self.n):\n [a, b, c] = map(int, input().split())\n self.key[i].val = a\n self.left[i] = b\n self.right[i] = c\n\n def find(self, data, root=None):\n if not root:\n root = self.root\n if data == root.val:\n return True, root\n elif data < root.val:\n # print(f'data({data}) < root({root.val})')\n if root.left:\n return self.find(data, root.left)\n else:\n return False, root\n elif data > root.val:\n # print(f'data({data}) > root({root.val})')\n if root.right:\n return self.find(data, root.right)\n else:\n return False, root\n\n def isBinaryTree(self):\n if self.n == 0:\n return True\n self.root = self.key[0]\n leftIndex = self.left[0]\n rightIndex = self.right[0]\n if leftIndex != -1:\n leftNode = self.key[leftIndex]\n if leftNode.val >= self.root.val:\n return False\n self.root.left = leftNode\n leftNode.leftBound = float('-inf'), leftNode.val\n leftNode.rightBound = leftNode.val, self.root.val\n self.nodesOrder.append(leftIndex)\n if rightIndex != -1:\n rightNode = self.key[rightIndex]\n if rightNode.val < self.root.val:\n return False\n self.root.right = rightNode\n rightNode.leftBound = self.root.val, rightNode.val\n rightNode.rightBound = rightNode.val, float('inf')\n self.nodesOrder.append(rightIndex)\n i = 0\n while i < self.n - 1:\n node = self.key[self.nodesOrder[i]]\n leftIndex = self.left[self.nodesOrder[i]]\n rightIndex = self.right[self.nodesOrder[i]]\n # print(f'self.nodesOrder[i] = {self.nodesOrder[i]} node = {node.val}; leftIndex = {leftIndex}; leftIndexVal = {self.key[leftIndex].val} rightIndex = {rightIndex} rightIndexVal = {self.key[rightIndex].val}')\n if leftIndex != -1:\n leftNode = self.key[leftIndex]\n # print(f'node = {node.val}; leftNode = {leftNode.val}; Bounds = {node.leftBound[0], node.leftBound[1]}')\n if node.leftBound[0] > leftNode.val or leftNode.val >= node.leftBound[1]:\n return False\n node.left = leftNode\n leftNode.leftBound = float('-inf'), leftNode.val\n leftNode.rightBound = leftNode.val, node.leftBound[1]\n self.nodesOrder.append(leftIndex)\n if rightIndex != -1:\n rightNode = self.key[rightIndex]\n # print(f'node = {node.val}; rightNode = {rightNode.val}; Bounds = {node.rightBound[0], node.rightBound[1]}')\n if node.rightBound[0] > rightNode.val or rightNode.val > node.rightBound[1]:\n return False\n node.right = rightNode\n rightNode.leftBound = node.rightBound[0], rightNode.val\n rightNode.rightBound = rightNode.val, float('inf')\n self.nodesOrder.append(rightIndex)\n i += 1\n return True\n\n\ndef main():\n tree = TreeOrders()\n tree.read()\n flag = tree.isBinaryTree()\n\n if flag:\n print(\"CORRECT\")\n else:\n print(\"INCORRECT\")\n\n\nthreading.Thread(target=main).start()\n","sub_path":"data-structures/week4_binary_search_trees/3_is_bst_advanced/is_bst_hard.py","file_name":"is_bst_hard.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"601650337","text":"from tkinter import *\n\nwindow = Tk()\n\ndef kg_to_other():\n got=en_KG.get()\n if got.isdigit():\n gram=float(got)*1000\n pounds=float(got)*2.20462\n ounces=float(got)*35.274\n else:\n gram=\"NOT a NUM\"\n pounds=\"NOT a NUM\"\n ounces=\"NOT a NUM\"\n t1_gram.insert(END,gram)\n t1_pounds.insert(END,pounds)\n t1_ounces.insert(END,ounces)\n\n\nt1_info=Text(window,height=1,width=8)\nt1_info.grid(row=0,column=0)\nt1_info.insert(END,\"Enter KG:\")\n\nen_KG=StringVar()\ne1=Entry(window,textvariable=en_KG)\ne1.grid(row=0,column=1)\n\nb1=Button(window,text=\"Convert\",command=kg_to_other)\nb1.grid(row=0,column=2)\n\n\nt1_info=Text(window,height=1,width=8)\nt1_info.grid(row=1,column=0)\nt1_info.insert(END,\"In Grams:\")\n\nt1_info=Text(window,height=1,width=8)\nt1_info.grid(row=1,column=1)\nt1_info.insert(END,\"In Pounds:\")\n\nt1_info=Text(window,height=1,width=8)\nt1_info.grid(row=1,column=2)\nt1_info.insert(END,\"In Ounces:\")\n\nt1_gram=Text(window,height=1,width=8)\nt1_gram.grid(row=2,column=0)\n\nt1_pounds=Text(window,height=1,width=8)\nt1_pounds.grid(row=2,column=1)\n\nt1_ounces=Text(window,height=1,width=8)\nt1_ounces.grid(row=2,column=2)\n\n\n\n\n\n\n\nwindow.mainloop()","sub_path":"gui/kilo_to_other.py","file_name":"kilo_to_other.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"607769257","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nfrom handler import AbstractHandler\nfrom module.infos.motor_info import MotorInfo\nfrom module.lidar_drive.transform_cloud_points import TrnasformCP\n\nfrom module.utils.linear_functions import *\nfrom module.utils.discreate_filter import DiscreateFilter\nfrom module.sliding_window.preprocessing import preprocessing_sliding_window\nfrom module.sliding_window.sliding_window import get_points_with_sliding_window, \\\n get_steering_angle_from_linear_function_curve, \\\n get_steering_angle_from_linear_function_curve2, \\\n get_steering_angle_from_linear_function_center, \\\n get_steering_angle_from_linear_function_center2\n\n\nclass SlidingWindowHandler(AbstractHandler):\n\n def __init__(self):\n # 슬라이딩 윈도우\n self.filter_deg = DiscreateFilter(f_cut=4000, freq=10000)\n\n # 장애물 회피\n self.tfcp = None\n self.filter_obs = DiscreateFilter(f_cut=1000, freq=10000)\n self.filter_obs_vel = DiscreateFilter(f_cut=2000, freq=10000)\n\n\n def handle(self, handler_info):\n frame = handler_info.image\n lidar_info = handler_info.lidar_info\n lidar_param = handler_info.lidar_param\n prev_speed = handler_info.prev_speed\n \n # 영상 전처리\n preprcessed_frame = preprocessing_sliding_window(frame)\n\n # 슬라이딩 윈도우를 통해 왼쪽/오른쪽 영역에서 검출된 차선의 점 추출\n choosen_left, choosen_right = get_points_with_sliding_window(preprcessed_frame)\n\n # 검출된 차선의 점에 맞는 2차함수 계산\n ret_left, linear_func_left = get_sliding_window_function(choosen_left)\n ret_right, linear_func_right = get_sliding_window_function(choosen_right)\n\n # 슬라이딩 윈도우로 motor_angle(steering_angle) 계산\n # 양쪽 차선이 있거나 직진의 형태일 경우, 중앙 차선으로 가도록 진행)\n if (ret_left and ret_right) \\\n or (ret_left and abs(linear_func_left.c)[1] < 0.1 and self.is_straight_line(linear_func_left, preprcessed_frame)) \\\n or (ret_right and abs(linear_func_right.c)[1] < 0.1 and self.is_straight_line(linear_func_right, preprcessed_frame)):\n motor_angle = self.get_steering_angle_center(preprcessed_frame, linear_func_left, linear_func_right)\n # motor_angle = self.get_steering_angle_center2(preprcessed_frame, linear_func_left, linear_func_right)\n # 한쪽 차선이 있을 경우, 커브 구간으로 생각하고 진행\n else:\n # motor_angle = self.get_steering_angle_curve(preprcessed_frame, linear_func_left, linear_func_right)\n motor_angle = self.get_steering_angle_curve2(preprcessed_frame, linear_func_left, linear_func_right)\n\n # 설정된 2차함수에 따라 angle 값을 새로 계산\n abs_motor_angle = max(0, get_linear_steering_angle2(abs(motor_angle)))\n\n # 앞에 장애물이 있는 경우\n if lidar_info:\n if self.tfcp is None:\n self.tfcp = TrnasformCP(lidar_param)\n self.tfcp.set_azimuth()\n\n cloud_r, cloud_al = self.tfcp.rm_spherical(lidar_info, 180)\n cartesian = self.tfcp.get_cartesian(cloud_r, cloud_al)\n camera_mks = self.tfcp.transform_to_ROI(cartesian)\n num_data, camera_mks_rm = self.tfcp.rm_cartesian(camera_mks)\n\n if num_data != 0:\n obs_angle, explain2, speed = self.tfcp.get_segment(preprcessed_frame, camera_mks_rm, linear_func_left, linear_func_right, prev_speed)\n obs_speed = self.filter_obs_vel.get_lpf(speed)[0]\n\n # angle 값 범위 조정 (-50 ~ 50)\n motor_angle += obs_angle # 장애물에 따른 angle 조정\n angle = np.clip(motor_angle, -50, 50)\n\n # 장애물에 따른 속도 고정\n # print(obs_angle, obs_speed, angle, speed)\n speed = obs_speed\n\n return MotorInfo(angle, speed), handler_info\n\n # angle 값 범위 조정 (-50 ~ 50)\n angle = np.clip(np.sign(motor_angle) * abs_motor_angle, -50, 50)\n\n # 설정된 2차함수에 따라, 해당 angle에 대한 speed 값을 새로 계산\n speed = get_linear_speed2(angle, 50)\n \n return MotorInfo(angle, speed), handler_info\n\n\n # 한쪽 차선이 있을 경우, 커브 구간으로 생각하고 진행\n def get_steering_angle_curve(self, frame, linear_func_left, linear_func_right):\n # 각 2차함수를 통해 steering angle 계산\n if linear_func_left:\n steering_angle = get_steering_angle_from_linear_function_curve(linear_func_left, frame, rel_x_ratio=1.2)\n elif linear_func_right:\n steering_angle = get_steering_angle_from_linear_function_curve(linear_func_right, frame, rel_x_ratio=0.8)\n else:\n steering_angle = self.filter_deg.prev_lpf\n\n # Low-pass filter를 적용한 steering angle 계산\n steering_angle = self.filter_deg.get_lpf(steering_angle)[0]\n\n \"\"\"\n Explain Matrix\n \"\"\"\n # vertical_line = np.zeros((explain1.shape[0], 5, 3), dtype=np.uint8)\n # explain_merge = np.hstack((explain2, vertical_line, explain1))\n # return steering_angle, explain_merge\n return steering_angle\n\n\n # 한쪽 차선이 있을 경우, 커브 구간으로 생각하고 진행\n def get_steering_angle_curve2(self, frame, linear_func_left, linear_func_right):\n # 각 2차함수를 통해 steering angle 계산\n if linear_func_left:\n steering_angle = get_steering_angle_from_linear_function_curve2(linear_func_left, frame)\n elif linear_func_right:\n steering_angle = get_steering_angle_from_linear_function_curve2(linear_func_right, frame)\n else:\n steering_angle = self.filter_deg.prev_lpf\n\n # Low-pass filter를 적용한 steering angle 계산\n steering_angle = self.filter_deg.get_lpf(steering_angle)[0]\n\n \"\"\"\n Explain Matrix\n \"\"\"\n # vertical_line = np.zeros((explain1.shape[0], 5, 3), dtype=np.uint8)\n # explain_merge = np.hstack((explain2, vertical_line, explain1))\n # return steering_angle, explain_merge\n return steering_angle\n\n\n # 양쪽 차선이 있을 경우, 중앙 차선으로 가도록 진행\n def get_steering_angle_center(self, frame, linear_func_left, linear_func_right):\n # 각 2차함수를 통해 steering angle 계산\n height, width = frame.shape[:2]\n \n # 직선 차선일 경우, 중앙차선으로 향하는 angle 계산\n steering_angle = get_steering_angle_from_linear_function_center(linear_func_left, linear_func_right, frame)\n\n # Low-pass filter를 적용한 steering angle 계산\n steering_angle = self.filter_deg.get_lpf(steering_angle)[0]\n\n \"\"\"\n Explain Matrix\n \"\"\"\n # vertical_line = np.zeros((explain1.shape[0], 5, 3), dtype=np.uint8)\n # explain_merge = np.hstack((explain2, vertical_line, explain1))\n # return steering_angle, explain_merge\n return steering_angle\n\n\n # 양쪽 차선이 있을 경우, 중앙 차선으로 가도록 진행\n def get_steering_angle_center2(self, frame, linear_func_left, linear_func_right, prev_speed=50):\n # 각 2차함수를 통해 steering angle 계산\n height, width = frame.shape[:2]\n \n # 직선 차선일 경우, 중앙차선으로 향하는 angle 계산\n steering_angle = get_steering_angle_from_linear_function_center2(linear_func_left, linear_func_right, frame, prev_speed=prev_speed)\n\n # Low-pass filter를 적용한 steering angle 계산\n steering_angle = self.filter_deg.get_lpf(steering_angle)[0]\n\n \"\"\"\n Explain Matrix\n \"\"\"\n # vertical_line = np.zeros((explain1.shape[0], 5, 3), dtype=np.uint8)\n # explain_merge = np.hstack((explain2, vertical_line, explain1))\n # return steering_angle, explain_merge\n return steering_angle\n\n\n def is_straight_line(self, func, frame):\n height, width = frame.shape[:2]\n \n f0 = func(0)\n f1 = func(height)\n\n grad1 = func.deriv()(0)\n grad2 = (f1 - f0) / (height - 0)\n\n grad_rad1 = np.arctan(grad1)\n grad_rad2 = np.arctan(grad2)\n\n grad_deg1 = np.degrees(grad_rad1)\n grad_deg2 = np.degrees(grad_rad2)\n\n if abs(grad_deg1 - grad_deg2) < 10:\n return True\n return False","sub_path":"soha_workspace/src/rally_3rd/src/handler/sliding_window_handler.py","file_name":"sliding_window_handler.py","file_ext":"py","file_size_in_byte":8755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"544230253","text":"import pytest\n\n\n@pytest.fixture\ndef base_url():\n url = 'https://api.openbrewerydb.org/breweries'\n return url\n\n@pytest.fixture()\ndef schema_id0():\n schema = {\n 'type': 'object',\n 'properties': {\n 'message': {'type': 'string',\n 'enum': [\"Couldn't find Brewery with 'id'=0\"]}\n },\n }\n return schema\n\n\n@pytest.fixture()\ndef schema_id1():\n schema = {\n 'type': 'object',\n 'properties': {\n 'id': {'type': 'integer',\n 'enum': [1]}\n },\n }\n return schema\n\n\n@pytest.fixture\ndef schema():\n schema = {\n 'type': 'object',\n 'properties': {\n \"id\": {'type': 'integer'},\n \"name\": {'type': 'string'},\n \"brewery_type\": {'type': 'string'},\n \"street\": {'type': 'string'},\n \"city\": {'type': 'string',\n 'enum': ['san_diego',\n 'amsterdam',\n 'new_york']},\n \"state\": {'type': 'string'},\n \"postal_code\": {'type': 'string'},\n \"country\": {'type': 'string'},\n \"longitude\": {'type': null},\n \"latitude\": {'type': null},\n \"phone\": {'type': 'string'},\n \"website_url\": {'type': 'string'},\n \"updated_at\": {'type': 'string'},\n \"tag_list\": []\n },\n }\n return schema\n\n","sub_path":"2_openbrewerydb_tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"500520513","text":"#!/usr/bin/env python\n\nclass Vertex(object):\n def __init__(self, label):\n self.label = label\n self.edges = [] # maybe not needed\n self.leader = self\n self.children = []\n self.size = 0\n\n def __repr__(self):\n return 'L: {}, chd: {}'.format(self.label, self.size)\n\n\nclass Edge(object):\n def __init__(self, head, tail, cost):\n self.head = head\n self.tail = tail\n self.cost = cost\n def __eq__(self, other):\n return self.cost == other.cost\n\ndef read_input(fname):\n \"\"\"\n Read input into an array of edges\n and total number of vertices\n \"\"\"\n with open(fname, 'r') as f:\n input_rows = f.read().splitlines()\n\n total_node_count = int(input_rows.pop(0))\n\n edges = []\n\n for edge in input_rows:\n [head, tail, cost] = edge.split()\n edges.append(Edge(head, tail, cost))\n # print('Head {}'.format(head))\n # print('Tail {}'.format(tail))\n # print('Cost {}'.format(cost))\n\n return [edges, total_node_count]\n\ndef digital_root(num):\n while num >= 10:\n num = (num % 10) + (num / 10)\n return num\n\ndef initialize_vertices(num):\n vertices = []\n for i in range (1, num + 1):\n vertices.append(Vertex(i))\n return vertices\n\ndef make_vertices_from(edges, total_vertices):\n \"\"\" Unclear if we need to do more \"\"\"\n vertices = initialize_vertices(total_vertices)\n return vertices\n\nif __name__ == '__main__':\n [edges, total_vertices] = read_input('resources/test')\n\n edges.sort(key=lambda x: x.cost) # sort the edges by cost\n\n vertices = make_vertices_from(edges, total_vertices)\n","sub_path":"algos_ii/kruskal.py","file_name":"kruskal.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"225651024","text":"from django.db.models import Q\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponse\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage, InvalidPage\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.contenttypes.models import ContentType\nfrom .models import ArticlePost\nfrom .forms import ArticlePostForm\nfrom users.models import User\nimport json\nimport logging\nimport markdown\nfrom comment.models import Comment\nfrom comment.forms import CommentForm\n\n\ndef articles_latest(request):\n \"\"\"\n 主页显示最新的三篇文章\n :param request:\n :return:/home/\n \"\"\"\n artcles = ArticlePost.objects.all().order_by('-id')\n count = ArticlePost.objects.all().count()\n types = ArticlePost.objects.values_list('article_type', flat=True)\n # distinct()无效,暂时先用以下方法代替\n unique_type = []\n for type in types:\n if type not in unique_type:\n unique_type.append(type)\n if count > 2:\n content = {'articles': [artcles[0], artcles[1], artcles[2]],\n 'types': unique_type}\n return render(request, 'home.html', content)\n elif count == 2:\n content = {'articles': [artcles[0], artcles[1]],\n 'types': unique_type}\n return render(request, 'home.html', content)\n else:\n content = {'articles': [artcles[0]],\n 'types': unique_type}\n return render(request, 'home.html', content)\n\n\ndef article_type(request, article_type):\n \"\"\"\n 类似主页,显示不同分类下的下最新的三篇文章\n :param request:\n :return: /home/type/类型\n \"\"\"\n article_list = ArticlePost.objects.filter(\n article_type__contains=article_type).order_by('-id')\n count = ArticlePost.objects.filter(\n article_type__contains=article_type).count()\n types = ArticlePost.objects.filter(\n article_type__contains=article_type).values_list('detail_type', flat=True)\n # distinct()无效,暂时先用以下方法代替\n unique_type = []\n for type in types:\n if type not in unique_type:\n unique_type.append(type)\n if count > 2:\n content = {'articles': [article_list[0], article_list[1], article_list[2]],\n 'types': unique_type,\n 'article_type': article_type}\n return render(request, 'article_type.html', content)\n elif count == 2:\n content = {'articles': [article_list[0], article_list[1]],\n 'types': unique_type,\n 'article_type': article_type}\n return render(request, 'article_type.html', content)\n elif count == 1:\n content = {'articles': [article_list[0]],\n 'types': unique_type,\n 'article_type': article_type}\n return render(request, 'article_type.html', content)\n else:\n return HttpResponse(\"There is not any article\")\n\n\ndef detail_type(request, article_type, detail_type):\n \"\"\"\n 类似主页,显示某一类型下最新的三篇文章\n :param request:\n :return: /home/type/类型/细分类型/\n \"\"\"\n article_list = ArticlePost.objects.filter(article_type__contains=article_type).filter(\n detail_type__contains=detail_type).order_by('-id')\n count = ArticlePost.objects.filter(article_type__contains=article_type).filter(\n detail_type__contains=detail_type).count()\n types = ArticlePost.objects.filter(\n article_type__contains=article_type).values_list('detail_type', flat=True)\n # distinct()无效,暂时先用以下方法代替\n unique_type = []\n for type in types:\n if type not in unique_type:\n unique_type.append(type)\n if count > 2:\n content = {'articles': [article_list[0], article_list[1], article_list[2]],\n 'types': unique_type,\n 'article_type': article_type,\n 'detail_type': detail_type}\n return render(request, 'detail_type.html', content)\n elif count == 2:\n content = {'articles': [article_list[0], article_list[1]],\n 'types': unique_type,\n 'article_type': article_type,\n 'detail_type': detail_type}\n return render(request, 'detail_type.html', content)\n else:\n content = {'articles': [article_list[0]],\n 'types': unique_type,\n 'article_type': article_type,\n 'detail_type': detail_type}\n return render(request, 'detail_type.html', content)\n\n\ndef article_detail(request, id):\n \"\"\"\n 显示文章详情\n :param request:\n :param id: 文章的id\n :return: /home/post/id/\n \"\"\"\n articlepost = get_object_or_404(ArticlePost, id=id)\n articlepost_content_type = ContentType.objects.get_for_model(articlepost)\n comments = Comment.objects.filter(\n content_type=articlepost_content_type, object_id=articlepost.pk,parent=None)\n\n types = ArticlePost.objects.filter(article_type__contains=articlepost.article_type).values_list('detail_type',flat=True)\n # distinct()无效,暂时先用以下方法代替,获取大类下面的每个小类\n unique_type = []\n for type in types:\n if type not in unique_type:\n unique_type.append(type)\n\n # 将markdown语法渲染成html格式\n articlepost.body = markdown.markdown(articlepost.body,\n extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ])\n data = {\"content_type\": articlepost_content_type.model,\n \"object_id\": articlepost.pk,\n \"reply_comment_id\":0,\n }\n print(data[\"content_type\"])\n context = {\"articlepost\": articlepost,\n \"types\": unique_type,\n \"comments\": comments.order_by(\"-comment_time\"),\n \"comment_form\": CommentForm(initial=data),\n }\n return render(request, 'post.html', context)\n\n\ndef about(request):\n \"\"\"\n 个人介绍\n :param request:\n :return: /home/about/\n \"\"\"\n return render(request, 'about.html')\n\n\ndef contact(request):\n \"\"\"\n 联系我\n :param request:\n :return: /home/contact/\n \"\"\"\n return render(request, \"contact.html\")\n\n\n@login_required(login_url='/accounts/login/')\ndef article_create(request):\n \"\"\"\n 写文章\n :param request:\n :return:\n \"\"\"\n if request.method == \"POST\":\n article_post_form = ArticlePostForm(data=request.POST)\n if article_post_form.is_valid():\n artcle_new = article_post_form.save(commit=False)\n artcle_new.author = User.objects.get(id=request.user.id)\n artcle_new.save()\n return redirect(\"home:articles_latest\")\n else:\n return HttpResponse(\"Error\")\n else:\n article_post_form = ArticlePostForm()\n context = {\"article_post_form\": article_post_form}\n return render(request, \"create.html\", context)\n\n\n@login_required(login_url='/accounts/login/')\ndef article_update(request, id):\n \"\"\"\n 修改文章\n :param request:\n :param id:\n :return:\n \"\"\"\n article = ArticlePost.objects.get(id=id)\n if request.method == \"POST\":\n article_post_form = ArticlePostForm(data=request.POST)\n if article_post_form.is_valid():\n article.title = request.POST['title']\n article.subtitle = request.POST['subtitle']\n article.article_type = request.POST['article_type']\n article.detail_type = request.POST['detail_type']\n article.body = request.POST['body']\n article.save()\n return redirect(\"home:post\", id=id)\n else:\n return HttpResponse(\"Error\")\n else:\n article_post_form = ArticlePostForm()\n context = {\"article\": article, \"article_post_form\": article_post_form}\n return render(request, \"update.html\", context)\n\n\ndef paginator_view(request):\n \"\"\"\n 所有文章分页显示\n :param request:\n :return:\n \"\"\"\n article_list = ArticlePost.objects.all().order_by(\"-id\")\n # 去除首页现实的最新的三条blog\n old_article = article_list[3:]\n # 每页现实5条\n paginator = Paginator(old_article, 5)\n if request.method == \"GET\":\n # 获取url中的page参数,首页不显示页数1\n page = request.GET.get(\"page\")\n try:\n articles_show = paginator.page(page)\n # 页码不是整数\n except PageNotAnInteger:\n # 页码不是整数返回第一页\n articles_show = paginator.page(1)\n except InvalidPage:\n # 找不到页数,返回提示\n return HttpResponse('找不到页面的内容')\n except EmptyPage:\n # 页数不在合法的页数范围内,返回最后一页\n articles_show = paginator.page(paginator.num_pages)\n content = {\"articles_show\": articles_show, }\n return render(request, \"paginator.html\", content)\n\n\ndef paginator_type(request, article_type):\n \"\"\"\n 不同类型文章分页显示\n :param request:\n :param article_type:\n :return:\n \"\"\"\n article_list = ArticlePost.objects.filter(\n article_type=article_type).order_by(\"-id\")\n # 去除首页现实的最新的三条blog\n old_article = article_list[3:]\n # 每页现实10条\n paginator = Paginator(old_article, 5)\n if request.method == \"GET\":\n # 获取url中的page参数,首页不显示页数1\n page = request.GET.get(\"page\")\n try:\n articles_show = paginator.page(page)\n # 页码不是整数\n except PageNotAnInteger:\n # 页码不是整数返回第一页\n articles_show = paginator.page(1)\n except InvalidPage:\n # 找不到页数,返回提示\n return HttpResponse('找不到页面的内容')\n except EmptyPage:\n # 页数不在合法的页数范围内,返回最后一页\n articles_show = paginator.page(paginator.num_pages)\n content = {\"articles_show\": articles_show, }\n return render(request, \"paginator.html\", content)\n\n\ndef paginator_detailtype(request, article_type, detail_type):\n \"\"\"\n 不同细分文章分页显示\n :param request:\n :param article_type:\n :return:\n \"\"\"\n article_list = ArticlePost.objects.filter(article_type=article_type).filter(\n detail_type=detail_type).order_by(\"-id\")\n # 去除首页现实的最新的三条blog\n old_article = article_list[3:]\n # 每页现实10条\n paginator = Paginator(old_article, 5)\n if request.method == \"GET\":\n # 获取url中的page参数,首页不显示页数1\n page = request.GET.get(\"page\")\n try:\n articles_show = paginator.page(page)\n # 页码不是整数\n except PageNotAnInteger:\n # 页码不是整数返回第一页\n articles_show = paginator.page(1)\n except InvalidPage:\n # 找不到页数,返回提示\n return HttpResponse('找不到页面的内容')\n except EmptyPage:\n # 页数不在合法的页数范围内,返回最后一页\n articles_show = paginator.page(paginator.num_pages)\n content = {\"articles_show\": articles_show, }\n return render(request, \"paginator.html\", content)\n\n\n@login_required(login_url='/accounts/login/')\ndef article_delete(request, id):\n \"\"\"\n 文章详情页删除按钮\n :param request:\n :param id:\n :return:\n \"\"\"\n article_deleted = ArticlePost.objects.get(id=id)\n article_deleted.delete()\n return redirect(\"home:articles_latest\")\n\n\ndef user_article(request, id):\n user = User.objects.get(id=id)\n author_article = ArticlePost.objects.filter(author=user).order_by(\"-id\")\n paginator = Paginator(author_article, 5)\n if request.method == \"GET\":\n # 获取url中的page参数,首页不显示页数1\n page = request.GET.get(\"page\")\n try:\n articles_show = paginator.page(page)\n # 页码不是整数\n except PageNotAnInteger:\n # 页码不是整数返回第一页\n articles_show = paginator.page(1)\n except InvalidPage:\n # 找不到页数,返回提示\n return HttpResponse('找不到页面的内容')\n except EmptyPage:\n # 页数不在合法的页数范围内,返回最后一页\n articles_show = paginator.page(paginator.num_pages)\n content = {\"articles_show\": articles_show, }\n return render(request, \"paginator.html\", content)\n\n\ndef article_search(request):\n if request.method == \"GET\":\n keywords = str(request.GET.get('keywords'))\n article_list = ArticlePost.objects.filter(\n Q(title__icontains=keywords) | Q(\n subtitle__icontains=keywords) | Q(body__icontains=keywords)\n ).order_by(\"-id\")\n if request.method == \"GET\":\n # 每页现实5条\n paginator = Paginator(article_list, 5)\n # 获取url中的page参数,首页不显示页数1\n page = request.GET.get(\"page\")\n try:\n articles_show = paginator.page(page)\n # 页码不是整数\n except PageNotAnInteger:\n # 页码不是整数返回第一页\n articles_show = paginator.page(1)\n except InvalidPage:\n # 找不到页数,返回提示\n return HttpResponse('找不到页面的内容')\n except EmptyPage:\n # 页数不在合法的页数范围内,返回最后一页\n articles_show = paginator.page(paginator.num_pages)\n content = {\"articles_show\": articles_show,\n \"keywords\": keywords}\n return render(request, \"search.html\", content)\n","sub_path":"blog/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"3375685","text":"import os\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport input_data\r\nimport model\r\nN_CLASSES = 2 # 2个输出神经元,[1,0] 或者 [0,1]猫和狗的概率\r\nIMG_W = 208 # resize图像,太大的话训练时间久\r\nIMG_H = 208\r\nBATCH_SIZE = 16\r\nCAPACITY = 2000\r\nMAX_STEP = 20000 # 一般大于10K\r\nlearning_rate = 0.0001 # 一般小于0.0001\r\ntrain_dir = './data/train/'\r\nlogs_train_dir = './logs/train/' #这个目录会自动生成\r\n\r\n # 获取图片和标签集\r\ntrain, train_label = input_data.get_files(train_dir)\r\n ## 生成批次\r\ntrain_batch,train_label_batch=input_data.get_batch(train,\r\n train_label,\r\n IMG_W,\r\n IMG_H,\r\n BATCH_SIZE,\r\n CAPACITY)\r\n#操作定义 进入模型\r\ntrain_logits = model.inference(train_batch, BATCH_SIZE, N_CLASSES)\r\n#获取loss\r\ntrain_loss = model.losses(train_logits, train_label_batch)\r\n#训练\r\ntrain_op = model.trainning(train_loss, learning_rate)\r\n#获取准确率\r\ntrain__acc = model.evaluation(train_logits, train_label_batch)\r\n# 合并summary\r\nsummary_op = tf.summary.merge_all() #这个是log汇总记录\r\n#产生一个会话\r\nsess = tf.Session()\r\n#产生一个writer来写log文件\r\ntrain_writer = tf.summary.FileWriter(logs_train_dir, sess.graph)\r\n #产生一个saver来存储训练好的模型\r\nsaver = tf.train.Saver()\r\n#所有节点初始化\r\nsess.run(tf.global_variables_initializer())\r\n\r\n#队列监控\r\ncoord = tf.train.Coordinator()\r\nthreads = tf.train.start_queue_runners(sess=sess, coord=coord)\r\n#进行batch的训练\r\ntry:\r\n #执行MAX_STEP步的训练,一步一个batch\r\n for step in np.arange(MAX_STEP):\r\n if coord.should_stop():\r\n break\r\n #启动以下操作节点,有个疑问,为什么train_logits在这里没有开启?\r\n _, tra_loss, tra_acc = sess.run([train_op, train_loss, train__acc])\r\n #每隔50步打印一次当前的loss以及acc,同时记录log,写入writer\r\n if step % 50 == 0:\r\n print('Step %d, train loss = %.2f, train accuracy = %.2f%%' %(step, tra_loss, tra_acc*100.0))\r\n summary_str = sess.run(summary_op)\r\n train_writer.add_summary(summary_str, step)\r\n #每隔2000步,保存一次训练好的模型\r\n if step % 2000 == 0 or (step + 1) == MAX_STEP:\r\n checkpoint_path = os.path.join(logs_train_dir, 'model.ckpt')\r\n saver.save(sess, checkpoint_path, global_step=step)\r\n\r\nexcept tf.errors.OutOfRangeError:\r\n print('Done training -- epoch limit reached')\r\nfinally:\r\n coord.request_stop()\r\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"461183682","text":"secret_word = input(\"Skriv inn det hemmelige ordet: \")\nattempts = int(input(\"Hvor mange forsøk får brukeren? \"))\nguesses = []\nprint(\"Det hemmelige ordet er\", len(secret_word) * \"*\")\ntotal_guesses = []\nguess = \"\"\n\nwhile True:\n total_guesses.append(guess)\n guess = input(\"Bokstav: \")\n if guess in total_guesses:\n print(\"Allerede gjettet, prøv igjen!\")\n\n else:\n if guess in secret_word:\n guesses.append(guess)\n if guess == \"\":\n break\n\n i = -1\n revealed_word = \"\"\n\n if guess in secret_word:\n for characters in secret_word:\n i += 1\n placement = False\n\n for c in range(len(guesses)):\n if guesses[c] == secret_word[i]:\n revealed_word += guesses[c]\n placement = True\n\n if placement == False:\n revealed_word += \"*\"\n\n print(\"Bokstaven er i ordet!\")\n print(revealed_word)\n\n if revealed_word == secret_word:\n print(\"Du vant! Ordet var\", secret_word)\n break\n else:\n print(\"Bokstaven\", guess, \"er ikke i ordet. Prøv igjen!\")\n attempts -= 1\n print(\"Du har\", attempts, \"forsøk igjen.\")\n\n if attempts <= 0:\n print(\"Du tapte!\")\n break","sub_path":"Øving 3/Hangman/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"139204123","text":"#!/bin/env python\n\n\"\"\"\n Module that search sounds in www.myinstants.com\n Author: Luiz Francisco Rodrigues da Silva \n\"\"\"\n\nimport re\nimport sys\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nBASE_URL = \"https://www.myinstants.com/{}\"\nSEARCH_URL = \"search/?name={}\"\n\nMP3_MATCH = re.compile(r\"play\\('(.*?)'\\)\")\n\ndef search_instants(query):\n \"\"\"Search instant\n Params:\n query: String to search\n \"\"\"\n query_string = \"+\".join(query) if isinstance(query, list) else query.replace(\" \", \"+\")\n url = BASE_URL.format(SEARCH_URL.format(query_string))\n\n req = requests.get(url)\n\n if req.status_code != 200:\n return {}\n\n soup = BeautifulSoup(req.text, \"html.parser\")\n response = []\n for div_obj in soup.find_all(\"div\", class_=\"instant\"):\n text = div_obj.find(\"a\", attrs={\"style\": \"text-decoration: underline; font-size: 14px;\"}).string\n mp3 = MP3_MATCH.search(div_obj.find(\"div\", class_=\"small-button\")[\"onmousedown\"]).group(1)\n url = BASE_URL.format(mp3)\n response.append({\"text\": text,\n \"url\": url})\n\n return response\n\ndef main():\n \"\"\"Main function\"\"\"\n try:\n response = search_instants(sys.argv[1:])\n except requests.exceptions.Timeout:\n print(\"Timeout\")\n response = []\n\n print(response)\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"myinstants.py","file_name":"myinstants.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"411539685","text":"import random\n\nfrom django.contrib.auth import get_user_model\nfrom django.core.management import BaseCommand\n\nfrom challenge.models import Challenge, Category, Score, Solve\nfrom team.models import Team\n\n\nclass Command(BaseCommand):\n\n def handle(self, *args, **options):\n print('Creating 10 categories...')\n for i in range(10):\n category = Category(name='category-' + str(i), display_order=i, contained_type='test',\n description='Category ' + str(i))\n category.save()\n\n print('Creating 100 challenges for each category...')\n for i in range(10):\n category = Category.objects.get(name='category-' + str(i))\n for j in range(50):\n challenge = Challenge(name='cat-' + str(i) + '-chal-' + str(j), category=category,\n description='An example challenge ' + str(j),\n flag_metadata={'flag': f'ractf{{{j}}}'}, author='dave', auto_unlock=True, score=j,\n challenge_metadata={})\n challenge.save()\n for j in range(50, 100, 2):\n challenge = Challenge(name='cat-' + str(i) + '-chal-' + str(j), category=category,\n description='An example challenge ' + str(j),\n flag_metadata={'flag': f'ractf{{{j}}}'}, author='dave', auto_unlock=True,\n score=j, challenge_metadata={})\n challenge2 = Challenge(name='cat-' + str(i) + '-chal-' + str(j + 1), category=category,\n description='An example challenge ' + str(j + 1),\n flag_metadata={'flag': f'ractf{{{j + 1}}}'}, author='dave', auto_unlock=False,\n score=j, challenge_metadata={})\n challenge2.save()\n challenge.save()\n challenge.unlocks.add(challenge2)\n\n print('Creating 20000 users with 10000 teams with 100 solves per team...')\n for i in range(10000):\n user = get_user_model()(username='user-' + str(i), email='user-' + str(i) + '@example.org')\n user.save()\n team = Team(name='team-' + str(i), password='password', owner=user)\n team.save()\n user2 = get_user_model()(username='user-' + str(i) + '-second', email='user-' + str(i) + '-second@example.org',\n team=team)\n user2.save()\n for j in range(50):\n challenge = Category.objects.get(name='category-' + str(j % 5))\\\n .category_challenges.get(name='cat-' + str(j % 5) + '-chal-' + str(j))\n points = random.randint(0, 1000)\n score = Score(team=team, reason='challenge', points=points, penalty=0, leaderboard=True)\n score.save()\n solve = Solve(team=team, solved_by=user, challenge=challenge, first_blood=challenge.first_blood is None,\n flag='ractf{}', score=score, correct=True)\n solve.save()\n user.points += points\n team.points += points\n user.leaderboard_points += points\n team.leaderboard_points += points\n for j in range(50):\n challenge = Category.objects.get(name='category-' + str(j % 5 + 5))\\\n .category_challenges.get(name='cat-' + str(j % 5 + 5) + '-chal-' + str(j))\n points = random.randint(0, 1000)\n score = Score(team=team, reason='challenge', points=points, penalty=0, leaderboard=True)\n score.save()\n solve = Solve(team=team, solved_by=user2, challenge=challenge,\n first_blood=challenge.first_blood is None, flag='ractf{}', score=score, correct=True)\n solve.save()\n user2.points += points\n team.points += points\n user.leaderboard_points += points\n team.leaderboard_points += points\n\n","sub_path":"src/ractf/management/commands/insert_mega_dummy_data.py","file_name":"insert_mega_dummy_data.py","file_ext":"py","file_size_in_byte":4160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"261178469","text":"\"\"\"empty message\n\nRevision ID: 5ddb88320031\nRevises: e58cdf3b10f9\nCreate Date: 2018-08-11 03:59:13.419187\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '5ddb88320031'\ndown_revision = 'e58cdf3b10f9'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('photos', 'cn_name')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('photos', sa.Column('cn_name', sa.VARCHAR(length=64), autoincrement=False, nullable=True))\n # ### end Alembic commands ###\n","sub_path":"app/migrations/versions/5ddb88320031_.py","file_name":"5ddb88320031_.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"308356185","text":"import yaml\nimport os\nimport subprocess\nimport pandas as pd\nimport numpy as np\nimport pdb\n\ndef firecalc(configlocation, room, layout, firstign):\n #Setting the location of config file, which holds settings\n configs = yaml.load(open(configlocation))\n #In that file, the 'firecalc' section is relevant for this code\n configuse = configs['firecalc']\n #Creating an array of times spaced by timestep that goes to simtime\n timelist = np.arange(0,configuse['simtime'], configuse['timestep'])\n #Importing item info as pandas df\n iteminfo = pd.read_csv(configuse['itemloc'],index_col='item')\n #Importing room specs as pandas df\n roominfo = pd.read_csv(configuse['roomloc'] \\\n + '/' + room + '.csv')\n\n \n\n #Need room surface area for flashover correlation\n surf_area = 2*roominfo['width'][0]*roominfo['length'][0] \\\n + 2*roominfo['width'][0]*roominfo['height'][0] \\\n + 2*roominfo['length'][0]*roominfo['height'][0]\n\n\n #Now calculate the required HRR that produces flashover\n Q_FO = 378*(1+.021*(surf_area/(roominfo['ventarea'][0]*\\\n roominfo['ventheight'][0]**.5)))\\\n *roominfo['ventarea'][0]*roominfo['ventheight'][0]**.5\n\n #If/when flashover occurs, the NaN is replaced with a time\n flashover = float('NaN')\n\n\n #construct an HRR dictionary holding curves for each item\n hrrdic = {}\n\n #Incluedes a draw for multiple curves if applicable\n for itemtype in iteminfo.index:\n hrrdic[itemtype] = np.loadtxt(configuse['itemhrrdataloc']\\\n +itemtype+ str(np.random.randint(0,iteminfo.numcurves[itemtype])) \\\n + '.csv',delimiter=',')\n\n \n\n #Retrieving a list of items in the room\n rawlayout= pd.read_csv(configuse['layoutloc'] \\\n + '/' + layout + '.csv')\n itemlist = rawlayout.item\n\n #Retriving the centroid to edge distance matrix for point source\n distmatrix = np.loadtxt(configuse['layoutloc'] \\\n + 'dist/' + layout + '.csv', delimiter=',')\n\n num_items = len(itemlist)\n\n #Firelist holds the time at which each item is ignited\n firelist = np.ones(num_items)*configuse['simtime']\n firelist[firstign] = 0\n\n #Creating a ist of accumulated FTP for each item\n FTP = np.zeros(num_items) #FTP for each item\n\n\n for t, time in enumerate(timelist):\n\n #The list of incident fluxes. Resets each time step\n incident_flux = np.zeros(num_items)\n #The current HRR of the total fire, resets at each time step\n HRR = 0\n\n for f,fire in enumerate(itemlist):\n #Add all fires' contribution to overall HRR\n #Negative times (unignited) are given zero in interp\n HRR = HRR + np.interp(time - firelist[f]\\\n ,hrrdic[fire][:,0],hrrdic[fire][:,1])\n\n\n\n #Check if flashover conditions are met\n if HRR > Q_FO and np.isnan(flashover):\n flashover = time\n #If anything hasn't ignited, it has now\n firelist[firelist==configuse['simtime']] = time\n\n for i,item in enumerate(itemlist):\n #Only executes if ith item hasn't ignited \n #AND fth item has ignited\n if item == 'HF':\n incident_flux[i] = incident_flux[i] \\\n + iteminfo.radfrac[fire]\\\n *np.interp(time - firelist[f]\\\n ,hrrdic[fire][:,0],hrrdic[fire][:,1]) \\\n /(4*np.pi*distmatrix[f][i]**2)\n print(incident_flux[i], i)\n if firelist[f] != configuse['simtime'] and\\\n firelist[i] == configuse['simtime']:\n\n #Use point source to find incident flux on ith item\n incident_flux[i] = incident_flux[i] \\\n + iteminfo.radfrac[fire]\\\n *np.interp(time - firelist[f]\\\n ,hrrdic[fire][:,0],hrrdic[fire][:,1]) \\\n /(4*np.pi*distmatrix[f][i]**2)\n\n\n #Then use FTP model\n if incident_flux[i] > iteminfo.qcrit[item]:\n FTP[i] = FTP[i] + (incident_flux[i]\\\n -iteminfo.qcrit[item])\\\n **iteminfo.n[item]*configuse['timestep']\n \n if FTP[i] > iteminfo.FTP[item]:\n firelist[i] = time\n return [flashover,firelist]\n\n \n \n","sub_path":"flashover/flashover.py","file_name":"flashover.py","file_ext":"py","file_size_in_byte":4438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"180084092","text":"# -*- coding: utf-8 -*-\n# ----------------------------------------------------------------------\n# Test telnet module\n# ----------------------------------------------------------------------\n# Copyright (C) 2007-2019 The NOC Project\n# See LICENSE for details\n# ----------------------------------------------------------------------\n\n\n# Third-party modules\nimport pytest\nfrom six import BytesIO\n\n# NOC modules\nfrom noc.core.script.cli.telnet import TelnetParser\n\n\n@pytest.mark.parametrize(\n \"scenario\",\n [\n # Feed, Expected, Sent Expected\n # Feed - parser input\n # Expected - expected parser output\n # Sent Expected - expected control sequence output\n # Empty feed\n [(b\"\", b\"\", b\"\")],\n # Plain text\n [(b\"Lorem ipsum\", b\"Lorem ipsum\", b\"\"), (b\"dolor sit amet\", b\"dolor sit amet\", b\"\")],\n # Escaped IAC\n [\n (b\"Lorem\\xff\\xff ipsum\", b\"Lorem\\xff ipsum\", b\"\"),\n (b\"dolor sit amet\", b\"dolor sit amet\", b\"\"),\n ],\n # Incomplete IAC\n [\n (b\"Lorem ipsum\\xff\", b\"Lorem ipsum\", b\"\"),\n (b\"\\xffdolor sit amet\", b\"\\xffdolor sit amet\", b\"\"),\n ],\n # Ignored commands\n [\n (b\"Lorem\\xff\\xf5 ipsum\", b\"Lorem ipsum\", b\"\"),\n (b\"Lorem\\xff\\xf6 ipsum\", b\"Lorem ipsum\", b\"\"),\n (b\"Lorem\\xff\", b\"Lorem\", b\"\"),\n (b\"\\xf5ipsum\", b\"ipsum\", b\"\"),\n ],\n # Accepted commands\n [\n # IAC DO ECHO -> IAC WILL ECHO\n (b\"\\xff\\xfd\\x01Lorem ipsum\", b\"Lorem ipsum\", b\"\\xff\\xfb\\x01\"),\n # IAC DO SGA -> IAC WILL SGA\n (b\"\\xff\\xfd\\x03Lorem ipsum\", b\"Lorem ipsum\", b\"\\xff\\xfb\\x03\"),\n ],\n # IAC DO\n [\n (b\"\\xff\\xfd\\x01\", b\"\", b\"\\xff\\xfb\\x01\"),\n (b\"\\xff\\xfd\\x02\", b\"\", b\"\\xff\\xfc\\x02\"),\n (b\"\\xff\\xfd\\x03\", b\"\", b\"\\xff\\xfb\\x03\"),\n (b\"\\xff\\xfd\\x04\", b\"\", b\"\\xff\\xfc\\x04\"),\n (b\"\\xff\\xfd\\x18\", b\"\", b\"\\xff\\xfb\\x18\"),\n # NAWS\n (b\"\\xff\\xfd\\x1f\", b\"\", b\"\\xff\\xfb\\x1f\\xff\\xfa\\x1f\\x00\\x80\\x00\\x80\\xff\\xf0\"),\n ],\n # IAC DONT\n [(b\"\\xff\\xfe\\x01Lorem\", b\"Lorem\", b\"\\xff\\xfc\\x01\")],\n # IAC WONT\n [(b\"\\xff\\xfc\\x01Lorem\", b\"Lorem\", b\"\\xff\\xfe\\x01\")],\n # IAC WILL\n [\n (b\"\\xff\\xfb\\x01\", b\"\", b\"\\xff\\xfd\\x01\"),\n (b\"\\xff\\xfb\\x02\", b\"\", b\"\\xff\\xfe\\x02\"),\n (b\"\\xff\\xfb\\x03\", b\"\", b\"\\xff\\xfd\\x03\"),\n (b\"\\xff\\xfb\\x04\", b\"\", b\"\\xff\\xfe\\x04\"),\n (b\"\\xff\\xfb\\x18\", b\"\", b\"\\xff\\xfd\\x18\"),\n ],\n # Invalid IAC\n [(b\"\\xff\\x00Lorem ipsum\", b\"orem ipsum\", b\"\")],\n # TTYPE\n [\n (b\"\\xff\\xfa\\x18\\x01\\xff\\xf0Lorem\", b\"Lorem\", b\"\\xff\\xfa\\x18\\x00XTERM\\xff\\xf0\"),\n (b\"\\xff\\xfa\\x18\", b\"\", b\"\"),\n (b\"\\x01\\xff\\xf0Lorem\", b\"Lorem\", b\"\\xff\\xfa\\x18\\x00XTERM\\xff\\xf0\"),\n ],\n ],\n)\ndef test_telnet_scenario(scenario):\n parser = TelnetParser()\n for feed, expected, sent_expected in scenario:\n writer = BytesIO()\n parser.set_writer(writer.write)\n data = parser.feed(feed)\n assert data == expected\n ctl = writer.getvalue()\n assert ctl == sent_expected\n\n\n@pytest.mark.parametrize(\n \"data,expected\",\n [\n (b\"\", b\"\"),\n (b\"12345\", b\"12345\"),\n (b\"\\xfe12345\", b\"\\xfe12345\"),\n (b\"\\xff12345\", b\"\\xff\\xff12345\"),\n (b\"123\\xff45\", b\"123\\xff\\xff45\"),\n (b\"12345\\xff\", b\"12345\\xff\\xff\"),\n ],\n)\ndef test_telnet_escape(data, expected):\n assert TelnetParser.escape(data) == expected\n\n\n@pytest.mark.parametrize(\"cmd, opt, expected\", [])\ndef test_telnet_iac_repr(cmd, opt, expected):\n assert TelnetParser.iac_repr(cmd, opt) == expected\n","sub_path":"tests/test_telnet.py","file_name":"test_telnet.py","file_ext":"py","file_size_in_byte":3760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"329915528","text":"from __future__ import generators\n\nimport sys\nimport logging\nfrom celery.tests.utils import unittest\nfrom tempfile import mktemp\nfrom celery.tests.utils import StringIO\n\ntry:\n from contextlib import contextmanager\nexcept ImportError:\n from celery.tests.utils import fallback_contextmanager as contextmanager\n\nfrom celery import log\nfrom celery.log import (setup_logger, setup_task_logger,\n get_default_logger, get_task_logger,\n redirect_stdouts_to_logger, LoggingProxy)\nfrom celery.tests.utils import override_stdouts, execute_context\nfrom celery.utils import gen_unique_id\nfrom celery.utils.compat import LoggerAdapter\nfrom celery.utils.compat import _CompatLoggerAdapter\n\n\ndef get_handlers(logger):\n if isinstance(logger, LoggerAdapter):\n return logger.logger.handlers\n return logger.handlers\n\n\ndef set_handlers(logger, new_handlers):\n if isinstance(logger, LoggerAdapter):\n logger.logger.handlers = new_handlers\n logger.handlers = new_handlers\n\n\n@contextmanager\ndef wrap_logger(logger, loglevel=logging.ERROR):\n old_handlers = get_handlers(logger)\n sio = StringIO()\n siohandler = logging.StreamHandler(sio)\n set_handlers(logger, [siohandler])\n\n yield sio\n\n set_handlers(logger, old_handlers)\n\n\nclass test_default_logger(unittest.TestCase):\n\n def setUp(self):\n self.setup_logger = setup_logger\n self.get_logger = get_default_logger\n log._setup = False\n\n def _assertLog(self, logger, logmsg, loglevel=logging.ERROR):\n\n def with_wrap_logger(sio):\n logger.log(loglevel, logmsg)\n return sio.getvalue().strip()\n\n context = wrap_logger(logger, loglevel=loglevel)\n execute_context(context, with_wrap_logger)\n\n def assertDidLogTrue(self, logger, logmsg, reason, loglevel=None):\n val = self._assertLog(logger, logmsg, loglevel=loglevel)\n return self.assertEqual(val, logmsg, reason)\n\n def assertDidLogFalse(self, logger, logmsg, reason, loglevel=None):\n val = self._assertLog(logger, logmsg, loglevel=loglevel)\n return self.assertFalse(val, reason)\n\n def test_setup_logger(self):\n logger = self.setup_logger(loglevel=logging.ERROR, logfile=None,\n root=False)\n set_handlers(logger, [])\n logger = self.setup_logger(loglevel=logging.ERROR, logfile=None,\n root=False)\n self.assertIs(get_handlers(logger)[0].stream, sys.__stderr__,\n \"setup_logger logs to stderr without logfile argument.\")\n self.assertDidLogFalse(logger, \"Logging something\",\n \"Logger doesn't info when loglevel is ERROR\",\n loglevel=logging.INFO)\n\n def test_setup_logger_no_handlers_stream(self):\n l = self.get_logger()\n set_handlers(l, [])\n\n def with_override_stdouts(outs):\n stdout, stderr = outs\n l = self.setup_logger(logfile=stderr, loglevel=logging.INFO,\n root=False)\n l.info(\"The quick brown fox...\")\n self.assertIn(\"The quick brown fox...\", stderr.getvalue())\n\n context = override_stdouts()\n execute_context(context, with_override_stdouts)\n\n def test_setup_logger_no_handlers_file(self):\n l = self.get_logger()\n set_handlers(l, [])\n tempfile = mktemp(suffix=\"unittest\", prefix=\"celery\")\n l = self.setup_logger(logfile=tempfile, loglevel=0, root=False)\n self.assertIsInstance(get_handlers(l)[0],\n logging.FileHandler)\n\n def test_redirect_stdouts(self):\n logger = self.setup_logger(loglevel=logging.ERROR, logfile=None,\n root=False)\n try:\n def with_wrap_logger(sio):\n redirect_stdouts_to_logger(logger, loglevel=logging.ERROR)\n logger.error(\"foo\")\n self.assertIn(\"foo\", sio.getvalue())\n\n context = wrap_logger(logger)\n execute_context(context, with_wrap_logger)\n finally:\n sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__\n\n def test_logging_proxy(self):\n logger = self.setup_logger(loglevel=logging.ERROR, logfile=None,\n root=False)\n\n def with_wrap_logger(sio):\n p = LoggingProxy(logger, loglevel=logging.ERROR)\n p.close()\n p.write(\"foo\")\n self.assertNotIn(\"foo\", sio.getvalue())\n p.closed = False\n p.write(\"foo\")\n self.assertIn(\"foo\", sio.getvalue())\n lines = [\"baz\", \"xuzzy\"]\n p.writelines(lines)\n for line in lines:\n self.assertIn(line, sio.getvalue())\n p.flush()\n p.close()\n self.assertFalse(p.isatty())\n self.assertIsNone(p.fileno())\n\n context = wrap_logger(logger)\n execute_context(context, with_wrap_logger)\n\n\nclass test_task_logger(test_default_logger):\n\n def setUp(self):\n self.setup_logger = setup_task_logger\n self.get_logger = get_task_logger\n\n\nclass MockLogger(logging.Logger):\n _records = None\n\n def __init__(self, *args, **kwargs):\n self._records = []\n logging.Logger.__init__(self, *args, **kwargs)\n\n def handle(self, record):\n self._records.append(record)\n\n def isEnabledFor(self, level):\n return True\n\n\nclass test_CompatLoggerAdapter(unittest.TestCase):\n levels = (\"debug\",\n \"info\",\n \"warn\", \"warning\",\n \"error\",\n \"fatal\", \"critical\")\n\n def setUp(self):\n self.logger, self.adapter = self.createAdapter()\n\n def createAdapter(self, name=None, extra={\"foo\": \"bar\"}):\n logger = MockLogger(name=name or gen_unique_id())\n return logger, _CompatLoggerAdapter(logger, extra)\n\n def test_levels(self):\n for level in self.levels:\n msg = \"foo bar %s\" % (level, )\n logger, adapter = self.createAdapter()\n getattr(adapter, level)(msg)\n self.assertEqual(logger._records[0].msg, msg)\n\n def test_exception(self):\n try:\n raise KeyError(\"foo\")\n except KeyError:\n self.adapter.exception(\"foo bar exception\")\n self.assertEqual(self.logger._records[0].msg, \"foo bar exception\")\n\n def test_setLevel(self):\n self.adapter.setLevel(logging.INFO)\n self.assertEqual(self.logger.level, logging.INFO)\n\n def test_process(self):\n msg, kwargs = self.adapter.process(\"foo bar baz\", {\"exc_info\": 1})\n self.assertDictEqual(kwargs, {\"exc_info\": 1,\n \"extra\": {\"foo\": \"bar\"}})\n\n def test_add_remove_handlers(self):\n handler = logging.StreamHandler()\n self.adapter.addHandler(handler)\n self.assertIs(self.logger.handlers[0], handler)\n self.adapter.removeHandler(handler)\n self.assertListEqual(self.logger.handlers, [])\n","sub_path":"celery/tests/test_log.py","file_name":"test_log.py","file_ext":"py","file_size_in_byte":7027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"625954886","text":"'''\nCore image processing tools.\n\nCopyright 2017, Voxel51, LLC\nvoxel51.com\n\nBrian Moore, brian@voxel51.com\n'''\nimport os\nfrom subprocess import Popen, PIPE\n\nimport cv2\nimport numpy as np\n\nimport utils\n\n\ndef read(path, flag=cv2.IMREAD_UNCHANGED):\n '''Reads image from path.'''\n return cv2.imread(path, flag)\n\n\ndef write(img, path):\n '''Writes image to file, creating the output directory if necessary.'''\n utils.ensure_dir(path)\n cv2.imwrite(path, img)\n\n\ndef resize(img, width=None, height=None, *args, **kwargs):\n '''Resizes the given image to the given width and height. At most one\n dimension can be None, in which case the aspect-preserving value is used.\n '''\n if height is None:\n height = int(round(img.shape[0] * (width * 1.0 / img.shape[1])))\n if width is None:\n width = int(round(img.shape[1] * (height * 1.0 / img.shape[0])))\n return cv2.resize(img, (width, height), *args, **kwargs)\n\n\ndef to_double(img):\n '''Converts img to a double precision image with values in [0, 1].'''\n return img.astype(np.float) / np.iinfo(img.dtype).max\n\n\ndef rasterize(vector_path, width):\n '''Renders a vector image as a raster image with the given width,\n in pixels.\n '''\n with utils.TempDir() as d:\n try:\n png_path = os.path.join(d, \"tmp.png\")\n Convert(\n in_opts=[\"-density\", \"1200\", \"-trim\"],\n out_opts=[\"-resize\", str(width)],\n ).run(vector_path, png_path)\n return read(png_path)\n except:\n # Fail gracefully\n return None\n\n # @todo why is it slightly blurry this way?\n # try:\n # out = Convert(\n # in_opts=[\"-density\", \"1200\", \"-trim\"],\n # out_opts=[\"-resize\", str(width)],\n # ).run(vector_path, \"png:-\")\n # return read(out)\n # except:\n # # Fail gracefully\n # return None\n\n\ndef overlay(im1, im2, x0=0, y0=0):\n '''Overlays im2 onto im1 at the specified coordinates.\n\n Args:\n im1: a numpy array of any type containing a non-transparent image\n im2: a numpy array of any type containing a possibly-transparent image\n (x0, y0): the top-left coordinate of im2 in im1 after overlaying, where\n (0, 0) corresponds to the top-left of im1. This coordinate may lie\n outside of im1, in which case some (even all) of im2 may be omitted\n\n Returns:\n a uint8 numpy array containing the final image\n '''\n im1 = to_double(im1)\n im2 = to_double(im2)\n h1, w1 = im1.shape[:2]\n h2, w2 = im2.shape[:2]\n\n # Active slice of im1\n y1t = np.clip(y0, 0, h1)\n y1b = np.clip(y0 + h2, 0, h1)\n x1l = np.clip(x0, 0, w1)\n x1r = np.clip(x0 + w2, 0, w1)\n y1 = slice(y1t, y1b)\n x1 = slice(x1l, x1r)\n\n # Active slice of im2\n y2t = np.clip(y1t - y0, 0, h2)\n y2b = y2t + y1b - y1t\n x2l = np.clip(x1l - x0, 0, w2)\n x2r = x2l + x1r - x1l\n y2 = slice(y2t, y2b)\n x2 = slice(x2l, x2r)\n\n if im2.shape[2] == 4:\n # Mix transparent image\n alpha = im2[y2, x2, 3][:, :, np.newaxis]\n im1[y1, x1, :] *= (1 - alpha)\n im1[y1, x1, :] += alpha * im2[y2, x2, :3]\n else:\n # Insert opaque image\n im1[y1, x1, :] = im2[y2, x2, :]\n\n return np.uint8(255 * im1)\n\n\ndef to_frame_size(frame_size=None, shape=None, img=None):\n '''Converts an image size representation to a (width, height) tuple.\n\n Pass *one* keyword argument to compute the frame size.\n\n Args:\n frame_size: the (width, height) of the image\n shape: the (height, width, ...) of the image, e.g. from img.shape\n img: the image itself\n\n Returns:\n (w, h): the width and height of the image\n\n Raises:\n TypeError: if none of the keyword arguments were passed\n '''\n if img is not None:\n shape = img.shape\n if shape is not None:\n return shape[1], shape[0]\n elif frame_size is not None:\n return frame_size\n else:\n raise TypeError(\"A valid keyword argument must be provided\")\n\n\nclass Convert(object):\n '''Interface for the ImageMagick convert binary.'''\n\n def __init__(\n self,\n executable=\"convert\",\n in_opts=None,\n out_opts=None,\n ):\n '''Constructs a convert command, minus the input/output paths.\n\n Args:\n executable: the system path to the convert binary\n in_opts: a list of input options for convert\n out_opts: a list of output options for convert\n '''\n self._executable = executable\n self._in_opts = in_opts or []\n self._out_opts = out_opts or []\n self._args = None\n self._p = None\n\n @property\n def cmd(self):\n '''The last executed convert command string, or None if run() has not\n yet been called.\n '''\n return \" \".join(self._args) if self._args else None\n\n def run(self, inpath, outpath):\n '''Run the convert binary with the specified input/outpath paths.\n\n Args:\n inpath: the input path\n outpath: the output path. Use \"-\" or a format like \"png:-\" to pipe\n output to STDOUT\n\n Returns:\n out: STDOUT of the convert binary\n\n Raises:\n ExecutableNotFoundError: if the convert binary cannot be found\n ExecutableRuntimeError: if the convert binary raises an error during\n execution\n '''\n self._args = (\n [self._executable] +\n self._in_opts + [inpath] +\n self._out_opts + [outpath]\n )\n\n try:\n self._p = Popen(self._args, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n except OSError as e:\n if e.errno == errno.ENOENT:\n raise utils.ExecutableNotFoundError(self._executable)\n else:\n raise\n\n out, err = self._p.communicate()\n if self._p.returncode != 0:\n raise utils.ExecutableRuntimeError(self.cmd, err)\n\n return out\n\n\nclass Length(object):\n '''Represents a length along a specified dimension of an image as a relative\n percentage or an absolute pixel count.\n '''\n\n def __init__(self, length_str, dim):\n '''Builds a Length object.\n\n Args:\n length_str: a string of the form '%' or 'px' describing\n a relative or absolute length, respectively\n dim: the dimension to measure length along\n '''\n self.dim = dim\n if length_str.endswith(\"%\"):\n self.relunits = True\n self.rellength = 0.01 * float(length_str[:-1])\n self.length = None\n elif length_str.endswith(\"px\"):\n self.relunits = False\n self.rellength = None\n self.length = int(length_str[:-2])\n else:\n raise TypeError(\n \"Expected '%%' or 'px', received '%s'\" %\n str(length_str))\n\n def render(self, frame_size=None, shape=None, img=None):\n '''Returns the length in pixels for the given frame size/shape/img.\n\n Pass any *one* of the keyword arguments to render the length.\n\n Args:\n frame_size: the (width, height) of the image\n shape: the (height, width, ...) of the image, e.g. from img.shape\n img: the image itself\n\n Raises:\n LengthError: if none of the keyword arguments were passed\n '''\n if img is not None:\n shape = img.shape\n elif frame_size is not None:\n shape = frame_size[::-1]\n elif shape is None:\n raise LengthError(\"One keyword argument must be provided\")\n\n if self.relunits:\n return int(round(self.rellength * shape[self.dim]))\n else:\n return self.length\n\n\nclass LengthError(Exception):\n pass\n\n\nclass Width(Length):\n '''Represents the width of an image as a relative percentage or an absolute\n pixel count.\n '''\n\n def __init__(self, width_str):\n '''Builds a Width object.\n\n Args:\n width_str: a string of the form '%' or 'px' describing\n a relative or absolute width, respectively\n '''\n super(Width, self).__init__(width_str, 1)\n\n\nclass Height(Length):\n '''Represents the height of an image as a relative percentage or an absolute\n pixel count.\n '''\n\n def __init__(self, height_str):\n '''Builds a Height object.\n\n Args:\n height_str: a string of the form '%' or 'px' describing\n a relative or absolute height, respectively\n '''\n super(Height, self).__init__(height_str, 0)\n\n\nclass Location(object):\n '''Represents a location in an image.'''\n\n # Valid loc strings\n TOP_LEFT = [\"top-left\", \"tl\"]\n TOP_RIGHT = [\"top-right\", \"tr\"]\n BOTTOM_RIGHT = [\"bottom-right\", \"br\"]\n BOTTOM_LEFT = [\"bottom-left\", \"bl\"]\n\n def __init__(self, loc):\n '''Constructs a Location object.\n\n Args:\n loc: a (case-insenstive) string specifying a location\n [\"top-left\", \"top-right\", \"bottom-right\", \"bottom-left\"]\n [\"tl\", \"tr\", \"br\", \"bl\"]\n '''\n self._loc = loc.lower()\n\n @property\n def is_top_left(self):\n '''True if the location is top left, otherwise False.'''\n return self._loc in self.TOP_LEFT\n\n @property\n def is_top_right(self):\n '''True if the location is top right, otherwise False.'''\n return self._loc in self.TOP_RIGHT\n\n @property\n def is_bottom_right(self):\n '''True if the location is bottom right, otherwise False.'''\n return self._loc in self.BOTTOM_RIGHT\n\n @property\n def is_bottom_left(self):\n '''True if the location is bottom left, otherwise False.'''\n return self._loc in self.BOTTOM_LEFT\n\n\ndef hex_to_rgb(value):\n '''Converts \"#rrbbgg\" to a (red, green, blue) tuple.'''\n value = value.lstrip('#')\n return tuple(int(value[i:i + 2], 16) for i in (0, 2, 4))\n\n\ndef hex_to_bgr(value):\n '''Converts \"#rrbbgg\" to a (blue, green, red) tuple.'''\n return hex_to_rgb(value)[::-1]\n\n\ndef rgb_to_hex(red, green, blue):\n '''Converts (red, green, blue) to a \"#rrbbgg\" string.'''\n return \"#%02x%02x%02x\" % (red, green, blue)\n\n\ndef bgr_to_hex(blue, green, red):\n '''Converts (blue, green, red) to a \"#rrbbgg\" string.'''\n return rgb_to_hex(red, green, blue)\n\n\ndef rgb_to_bgr(img):\n '''Converts an RGB image to a BGR image.'''\n return img[..., [2, 1, 0] + range(3, img.shape[2])]\n\n\ndef bgr_to_rgb(img):\n '''Converts a BGR image to an RGB image.'''\n return rgb_to_bgr(img) # this operation is symmetric\n\n","sub_path":"eta/core/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":10732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"608895168","text":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nfrom django.utils import timezone\n\nimport os\nimport numpy as np\nimport cv2 as cv\n\nfrom io import BufferedReader, BytesIO\nimport base64\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n# 启动Django项目时,会初始化该类,加载模型耗时较长但是加载完毕后该实例一直留在资源池中等待调用\n# 在此类中编写接口即可\n# 包括 根据图片识别,根据numpy组成的数组识别等\nclass Classifier:\n def __init__(self, model_dir, model_name, img_size=(160, 160)):\n self.img_size = img_size\n self.model_dir = model_dir\n self.model_name = model_name\n self.model = keras.models.load_model(BASE_DIR + model_dir + model_name)\n # 模型加载完毕后立即使用一次Model.predict初始化模型\n self.model.predict(np.zeros((1, 160, 160, 3)))\n\n # 读取标签映射\n self.label_names = []\n with open(BASE_DIR + model_dir + \"/label_mapping.txt\", encoding=\"utf-8\") as mappings:\n for mapping in mappings:\n mapping = mapping.strip(\"\\n\")\n print(\"[初始化]读取到 %s \" % mapping)\n self.label_names.append(mapping.split('\\t')[1])\n\n '''TODO:Init ImageDataGenerator \n self.dst_images_formatter = ImageDatagenerator()\n\n '''\n\n def predict_by_imgpath(self, path):\n test_images = []\n true_names = []\n for root, _, files in os.walk(path):\n for filename in files:\n img_name, img_ext = os.path.splitext(filename)\n if img_ext.lower() not in ['.jpg', '.jpeg', '.bmp', '.png']:\n break\n img = cv.imread(os.path.join(root, filename))\n img = cv.resize(img, self.img_size, cv.INTER_AREA)\n true_names.append(img_name)\n test_images.append(img)\n\n # 归一化 0~255 => -1~1\n test_images = np.array(test_images)\n test_images = test_images.astype(\"float32\") / 127.5 - 1\n\n predictions = self.model.predict(test_images)\n\n for i, prediction in enumerate(predictions):\n predicted_label = 0 if prediction[0] < 0 else 1\n print(\"[True Class] %s <= => %s [Predict result: %0.6f] \" % (\n true_names[i], self.label_names[predicted_label], prediction[0]))\n\n def predict_test(self):\n test_path = BASE_DIR + \"/core/NetModel/test\"\n self.predict_by_imgpath(test_path)\n\n # 用以单张预测\n def predict(self, img):\n predictions = self.model.predict(img)\n predicted_label = 0 if predictions[0] < 0 else 1\n\n print(timezone.now().strftime(\"[%d/%b/%Y %H:%M:%S] \") + \"[预测分类] %s | [置信度] %.6f\" % (\n self.label_names[predicted_label], predictions[0]))\n\n return self.label_names[predicted_label]\n\n def predict_by_bytes(self, file):\n img = self.preprocessBytesObject(file)\n return self.predict(img)\n\n def predict_by_b64str(self, file):\n img = self.preprocessb64str(file)\n return self.predict(img)\n\n # 预处理io.BytesIO类型对象的图片\n def preprocessBytesObject(self, file):\n if isinstance(file, BytesIO):\n img = []\n buf = BufferedReader(file).read()\n img = cv.imdecode(np.frombuffer(buf, np.uint8), cv.IMREAD_COLOR)\n img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n img = cv.resize(img, self.img_size, cv.INTER_AREA)\n\n # 处理为网络模型需求的输入\n img = np.array(img)\n img = img.astype(\"float32\") / 127.5 - 1\n img = np.expand_dims(img, axis=0)\n\n return img\n else:\n return None\n\n # 预处理base64编码过的图片\n def preprocessb64str(self, img_b64):\n img = str(img_b64).split(';base64,')[1]\n img = base64.b64decode(img)\n img = np.fromstring(img, np.uint8)\n img = cv.imdecode(img, cv.IMREAD_COLOR)\n\n img = np.array(img)\n img = img.astype(\"float32\") / 127.5 - 1\n img = np.expand_dims(img, axis=0)\n\n return img\n\n\nclassify_factory = Classifier(\"/core/NetModel/MobileNetV2/\", \"MobileNetV2_binary_fine.h5\")\n\nif __name__ == \"__main__\":\n test_path = BASE_DIR + \"/core/NetModel/test\"\n classify_factory.predict_by_imgpath(test_path)\n","sub_path":"core/Classifier.py","file_name":"Classifier.py","file_ext":"py","file_size_in_byte":4436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"595237749","text":"\"\"\" Utilities for working with models\n\n:Author: Jonathan Karr \n:Date: 2020-03-22\n:Copyright: 2020, Center for Reproducible Biomedical Modeling\n:License: MIT\n\"\"\"\n\nfrom .data_model import BiomodelFormat\nfrom .sbml import SbmlBiomodelReader\n\n__all__ = ['read_biomodel']\n\n\ndef read_biomodel(filename, format):\n \"\"\" Read a model from a file\n\n Args:\n filename (:obj:`str`): path to a file which defines a model\n format (:obj:`BiomodelFormat`): model format\n\n Returns:\n :obj:`dict`: model\n\n Raises:\n :obj:`NotImplementedError`: the format is not supported\n \"\"\"\n if format == BiomodelFormat.sbml:\n Reader = SbmlBiomodelReader\n else:\n raise NotImplementedError(\"Model format {} is not supported\".format(format.name))\n return Reader().run(filename)\n","sub_path":"Biosimulations_utils/biomodel/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"99762666","text":"import sys\n#from PyQt5.QtWidgets import *\n#from PyQt5.QAxContainer import *\n#from PyQt5.QtCore import *\nimport pandas as pd\nimport pymysql\nfrom sqlalchemy import create_engine\nimport datetime\nimport time\nimport numpy as np\n\ncon = pymysql.connect(host='db-mysql.cj5nhbnzm5ke.ap-northeast-2.rds.amazonaws.com', user='admin',password='adminroot',db='stockdb',charset='utf8')\nengine = create_engine(\"mysql+pymysql://admin:\"+\"adminroot\"+\"@db-mysql.cj5nhbnzm5ke.ap-northeast-2.rds.amazonaws.com/stockdb?charset=utf8\",encoding='utf-8')\nconn = engine.connect()\ncursor = con.cursor()\ncursor.execute(\"set names utf8\")\ncon.commit()\n\n\nsql = \"select code,name from code_list where market=0\"\ncursor.execute(sql)\ndata = cursor.fetchall()\ncode_list = list(data)\n\ncount=0\nmonth3_list = ['018500','002630','000970', '008110', '092440', '018500', '001720']\nmonth6_list = ['033250', '093240','001080','005390']\nmonth9_list = ['003610', '008870']\nmonth11_list = ['004310']\nempty_list = ['152550', '316140', '094800', '336370', '088980', '336260','330590', '099350', '021820', '096300', '099340']\n\n\n\n#momentum_3m_profitage rank\nselect_rank_percent_sql =\"\"\"\n select\n\t c.code,c.name, c.momentum_3m_profitage, round(((@rank-rank)/@rank)*100,2) as percent_rank \n from\n (select\n *,\n @prev:=@curr,\n @curr:=a.momentum_3m_profitage,\n @rank:=if(@prev = @curr, @rank, @rank +1) as rank\n from\n (select code, name,momentum_3m_profitage from rank_corp)as a,\n (select @curr:=null, @prev:=null,@rank:=0)as b\n order by momentum_3m_profitage asc) as c;\n \"\"\"\ncursor.execute(select_rank_percent_sql)\nrank_str = cursor.fetchall()\n\n\nfor i in range(len(rank_str)):\n code = rank_str[i][0]\n momentum_3m_profitage = rank_str[i][2]\n percent_rank = float(rank_str[i][3])\n percent_rank = round(percent_rank,2)\n\n \n if percent_rank >80:\n percent_rank_score = 1\n elif percent_rank >60:\n percent_rank_score = 2\n elif percent_rank >40:\n percent_rank_score = 3\n elif percent_rank >20:\n percent_rank_score = 4\n else:\n percent_rank_score = 5\n \n\n\n if code in empty_list:\n continue\n if code in month3_list:\n cur_date = '2019/03'\n update_sql = \"update rank_corp set momentum_3m_profitage_rank_percent=%s where code=%s and settle_date='%s'\"%(percent_rank,code,cur_date)\n update_rank_sql = \"update rank_corp set momentum_3m_profitage_rank=%s where code=%s and settle_date='%s'\"%(percent_rank_score,code,cur_date)\n elif code in month6_list:\n cur_date = '2019/06'\n update_sql = \"update rank_corp set momentum_3m_profitage_rank_percent=%s where code=%s and settle_date='%s'\"%(percent_rank,code,cur_date)\n update_rank_sql = \"update rank_corp set momentum_3m_profitage_rank=%s where code=%s and settle_date='%s'\"%(percent_rank_score,code,cur_date)\n elif code in month9_list:\n cur_date = '2019/09'\n update_sql = \"update rank_corp set momentum_3m_profitage_rank_percent=%s where code=%s and settle_date='%s'\"%(percent_rank,code,cur_date)\n update_rank_sql = \"update rank_corp set momentum_3m_profitage_rank=%s where code=%s and settle_date='%s'\"%(percent_rank_score,code,cur_date)\n elif code in month11_list:\n cur_date = '2019/11'\n update_sql = \"update rank_corp set momentum_3m_profitage_rank_percent=%s where code=%s and settle_date='%s'\"%(percent_rank,code,cur_date)\n update_rank_sql = \"update rank_corp set momentum_3m_profitage_rank=%s where code=%s and settle_date='%s'\"%(percent_rank_score,code,cur_date)\n else:\n cur_date = '2018/12'\n update_sql = \"update rank_corp set momentum_3m_profitage_rank_percent=%s where code=%s and settle_date='%s'\"%(percent_rank,code,cur_date)\n update_rank_sql = \"update rank_corp set momentum_3m_profitage_rank=%s where code=%s and settle_date='%s'\"%(percent_rank_score,code,cur_date)\n\n #print(update_sql)\n #print(update_rank_sql)\n cursor.execute(update_sql)\n #con.commit()\n cursor.execute(update_rank_sql)\n con.commit()\n\n count = count +1\n print(count)\n\ncon.close()","sub_path":"Frontend/db_create/rank_corp/ranking_data.py","file_name":"ranking_data.py","file_ext":"py","file_size_in_byte":4149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"82869809","text":"from tkinter import *\nfrom tkinter import filedialog\nfrom tkinter.ttk import Combobox\nfrom pytube import YouTube\n\n\nclass Downloader:\n\n def __init__(self) -> None:\n # creating window\n self.window: Tk = Tk()\n self.window.title(\"Youtube_Downloader\")\n self.window.resizable(0, 0)\n self.window.geometry('640x480+300+200')\n \n # Attribute representing download options\n self.resolutions: tuple = (\"144p\", \"360p\", \"480p\", \"720p\", \"1080p\", \"apenas audio\")\n \n # Attributes that receive the images and icons for the look\n self.img_logo: PhotoImage = PhotoImage(file=\"img/1x/youtube_logo_white.png\")\n self.img_file: PhotoImage = PhotoImage(file=\"img/file.png\")\n self.img_download: PhotoImage = PhotoImage(file=\"img/download.png\")\n \n # Logo frame\n self.frame: Frame = Frame(self.window, bg=\"#C9020C\")\n self.frame.pack(fill=\"x\")\n self.label_logo: Label = Label(self.frame, image=self.img_logo, bg=\"#C9020C\")\n self.label_logo.pack()\n \n # Frame that receives features for data entry\n self.frame2: Frame = Frame(self.window, pady=20)\n self.frame2.pack()\n \n self.label_insert: Label = Label(self.frame2, text=\" Insert link: \", font='arial 12')\n self.label_insert.pack(side='left')\n \n self.link: Entry = Entry(self.frame2, font=\"arial 12\", width=30)\n self.link.pack(side=\"left\")\n \n self.file_button: Button = Button(self.frame2, image=self.img_file, border=0, width=60, command=self.info_file)\n self.file_button.pack(side=\"left\")\n \n self.resolutions_options: Combobox = Combobox(self.frame2, values=self.resolutions, state=\"readonly\")\n self.resolutions_options.set(\"Escolha a resolução\")\n self.resolutions_options.pack(side=\"left\")\n \n # Frame where it will show the status of the file\n self.frame3: Frame = Frame(self.window, pady=30)\n self.frame3.pack()\n \n self.info: Listbox = Listbox(self.frame3, relief=\"flat\", width=55, height=40)\n self.info.pack(side=\"left\")\n \n self.button_download: Button = Button(self.frame3, image=self.img_download, border=0, width=70, command=self.download)\n self.button_download.pack(side=\"left\")\n \n self.window.mainloop()\n \n \n def info_file(self) -> None:\n \"\"\"\n Info_file receives the download link, gets the location where the video\n will be saved and writes in the download characteristics listbox\n \"\"\"\n self.info.delete(0, END)\n self.info.insert(1,\"»» YouTube Download Init\")\n try:\n self.info_video_()\n self.info.insert(1,55*\"=\")\n self.info.insert(1, f\"»» Title: {self.video_title}\")\n self.info.insert(2, f\"»» Author: {self.video_author}\")\n self.info.insert(3, f\"»» length: {self.video_lenght}\")\n self.info.insert(1, 55*\"=\")\n except:\n self.msg()\n \n def info_video_(self: object):\n self.video_info: YouTube = YouTube(self.link.get())\n self.video_author: YouTube = self.video_info.author\n self.video_title: YouTube = self.video_info.title\n self.video_lenght: YouTube = self.video_info.length\n self.file : filedialog = filedialog.askdirectory()\n \n def download(self: object) -> None:\n \"\"\"\n \"\"\"\n self.info.delete(0, END)\n try:\n if self.resolutions_options.get() == \"audio/mp3\":\n self.video_info.streams.get_audio_only().download(self.file)\n self.info.insert(1,\"»» DOWNLOAD CONCLUDED\")\n self.info.insert(1, f\"»» Title: {self.video_title}\")\n elif self.resolutions_options.get() == \"Escolha a resolução\":\n self.video_info.streams.get_highest_resolution().download(self.file)\n self.info.insert(1,\"»» DOWNLOAD CONCLUDED\")\n self.info.insert(1, f\"»» Title: {self.video_title}\")\n else:\n self.info.insert(1, f\"»» resolution: {self.resolutions_options.get()}\")\n self.video_info.streams.get_by_resolution(self.resolutions_options.get()).download(self.file)\n self.info.insert(1,\"»» DOWNLOAD CONCLUDED\")\n self.info.insert(1, f\"»» Title: {self.video_title}\")\n except:\n self.info.delete(0, END)\n self.info.insert(1,\"»» Something went wrong.\")\n self.info.insert(1,\"»» Verify the chosen folder.\")\n self.info.insert(1,\"»» Try changing resolutions.\")\n \n def msg(self: object) -> None:\n windom: Toplevel = Toplevel()\n windom.title(\"ERROR\")\n windom.resizable(0, 0)\n windom.geometry(\"300x200+300+200\")\n \n texto: Label = Label(windom, text = \"The link is not valid\", pady = 30)\n texto.pack()\n \n ok: Button = Button(windom, text = \"OK\", command = windom.destroy)\n ok.pack()\n \n \nDownloader()","sub_path":"downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":5111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"200186095","text":"############################################################################\n# Copyright 2018 Anthony Ma & Stanford 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\n##############################################################################\n# Imports\n##############################################################################\n\nimport datetime\nfrom multiprocessing import Process, Queue\nfrom vmd import * # Loads the static `molecule` object\n\nfrom .contact_utils import *\nfrom .aromatics import *\nfrom .hbonds import *\nfrom .salt_bridges import *\nfrom .pi_cation import *\nfrom .vanderwaals import *\n\n##############################################################################\n# Global Variables\n##############################################################################\nTRAJ_FRAG_SIZE = 100\nfull_name_dirs = {'hbbb': 'hydrogen_bonds/backbone_backbone_hydrogen_bonds',\n 'hbsb': 'hydrogen_bonds/sidechain_backbone_hydrogen_bonds',\n 'hbss': 'hydrogen_bonds/sidechain_sidechain_hydrogen_bonds',\n 'vdw': 'van_der_Waals',\n 'sb': 'salt_bridges',\n 'ts': 't_stacking',\n 'ps': 'pi_stacking',\n 'pc': 'pi_cation',\n 'wb': 'hydrogen_bonds/water_mediated_hydrogen_bonds',\n 'wb2': 'hydrogen_bonds/extended_water_mediated_hydrogen_bonds',\n 'lhb': 'ligand_hydrogen_bonds/hydrogen_bonds',\n 'hlb': 'ligand_hydrogen_bonds/backbone_hydrogen_bonds',\n 'hls': 'ligand_hydrogen_bonds/sidechain_hydrogen_bonds',\n 'lwb': 'ligand_hydrogen_bonds/water_mediated_hydrogen_bonds',\n 'lwb2': 'ligand_hydrogen_bonds/extended_water_mediated_hydrogen_bonds',\n }\n\n##############################################################################\n# Functions\n##############################################################################\n\n# Note: Trying to write directly to output and doing postprocessing after\n# May save a lot of memory instead of having massive arrays, but there is\n# also the IO time (which would happen anyways). Figure out best output\n# format and most efficient way to write to disk.\n\n\ndef compute_frame_contacts(traj_frag_molid, frag_idx, frame_idx, ITYPES, geom_criterion_values, solvent_resn, sele_id,\n ligand, index_to_label):\n \"\"\"\n Computes each of the specified non-covalent interaction type for a single frame\n\n Parameters\n ----------\n traj_frag_molid: int\n Identifier to simulation fragment in VMD\n frag_idx: int\n Trajectory fragment index for worker to keep track of\n frame_idx: int\n Frame number to query\n ITYPES: list\n Denotes the list of non-covalent interaction types to compute contacts for \n geom_criterion_values: dict\n Dictionary containing the cutoff values for all geometric criteria\n solvent_resn: string, default = TIP3\n Denotes the resname of solvent in simulation\n sele_id: string, default = None\n Compute contacts on subset of atom selection based on VMD query\n chain_id: string, default = None\n Specify chain of protein to perform computation on \n ligand: list of string, default = None\n Include ligand resname if computing contacts between ligand and binding pocket residues\n index_to_label: dict \n Maps VMD atom index to label \"chain:resname:resid:name:index\"\n {11205: \"A:ASP:114:CA:11205, ...}\n\n Returns\n -------\n frame_contacts: list of tuples, [(frame_index, atom1_label, atom2_label, itype), ...]\n\n \"\"\"\n # tic = datetime.datetime.now()\n\n # Extract geometric criterion\n SALT_BRIDGE_CUTOFF_DISTANCE = geom_criterion_values['SALT_BRIDGE_CUTOFF_DISTANCE']\n PI_CATION_CUTOFF_DISTANCE = geom_criterion_values['PI_CATION_CUTOFF_DISTANCE']\n PI_CATION_CUTOFF_ANGLE = geom_criterion_values['PI_CATION_CUTOFF_ANGLE']\n PI_STACK_CUTOFF_DISTANCE = geom_criterion_values['PI_STACK_CUTOFF_DISTANCE']\n PI_STACK_CUTOFF_ANGLE = geom_criterion_values['PI_STACK_CUTOFF_ANGLE']\n PI_STACK_PSI_ANGLE = geom_criterion_values['PI_STACK_PSI_ANGLE']\n T_STACK_CUTOFF_DISTANCE = geom_criterion_values['T_STACK_CUTOFF_DISTANCE']\n T_STACK_CUTOFF_ANGLE = geom_criterion_values['T_STACK_CUTOFF_ANGLE']\n T_STACK_PSI_ANGLE = geom_criterion_values['T_STACK_PSI_ANGLE']\n HBOND_CUTOFF_DISTANCE = geom_criterion_values['HBOND_CUTOFF_DISTANCE']\n HBOND_CUTOFF_ANGLE = geom_criterion_values['HBOND_CUTOFF_ANGLE']\n VDW_EPSILON = geom_criterion_values['VDW_EPSILON']\n VDW_RES_DIFF = geom_criterion_values['VDW_RES_DIFF']\n\n frame_contacts = []\n if \"sb\" in ITYPES:\n frame_contacts += compute_salt_bridges(traj_frag_molid, frame_idx, sele_id, SALT_BRIDGE_CUTOFF_DISTANCE)\n if \"pc\" in ITYPES:\n frame_contacts += compute_pi_cation(traj_frag_molid, frame_idx, index_to_label, sele_id, PI_CATION_CUTOFF_DISTANCE, PI_CATION_CUTOFF_ANGLE)\n if \"ps\" in ITYPES:\n frame_contacts += compute_pi_stacking(traj_frag_molid, frame_idx, index_to_label, sele_id, PI_STACK_CUTOFF_DISTANCE, PI_STACK_CUTOFF_ANGLE, PI_STACK_PSI_ANGLE)\n if \"ts\" in ITYPES:\n frame_contacts += compute_t_stacking(traj_frag_molid, frame_idx, index_to_label, sele_id, T_STACK_CUTOFF_DISTANCE, T_STACK_CUTOFF_ANGLE, T_STACK_PSI_ANGLE)\n if \"vdw\" in ITYPES:\n frame_contacts += compute_vanderwaals(traj_frag_molid, frame_idx, index_to_label, sele_id, ligand, VDW_EPSILON, VDW_RES_DIFF)\n if \"hb\" in ITYPES:\n frame_contacts += compute_hydrogen_bonds(traj_frag_molid, frame_idx, index_to_label, solvent_resn, sele_id, None, HBOND_CUTOFF_DISTANCE, HBOND_CUTOFF_ANGLE)\n if \"lhb\" in ITYPES:\n frame_contacts += compute_hydrogen_bonds(traj_frag_molid, frame_idx, index_to_label, solvent_resn, sele_id, ligand, HBOND_CUTOFF_DISTANCE, HBOND_CUTOFF_ANGLE)\n\n # toc = datetime.datetime.now()\n # print(\"Finished computing contacts for frame %d (frag %d) in %s s\" %\n # (frag_idx*100+frame_idx, frag_idx, (toc-tic).total_seconds()))\n return frame_contacts\n\n\ndef compute_fragment_contacts(frag_idx, beg_frame, end_frame, top, traj, output, itypes, geom_criterion_values, stride,\n solvent_resn, sele_id, ligand, index_to_label):\n \"\"\" \n Reads in a single trajectory fragment and calls compute_frame_contacts on each frame\n\n Parameters\n ----------\n frag_idx: int\n Trajectory fragment index for worker to keep track of\n beg_frame: int\n Start frame of trajectory fragment\n end_frame: int\n Last frame of trajectory fragment\n top: str\n Topology in .pdb or .mae format\n traj: str\n Trajectory in .nc or .dcd format\n output: str\n Path to file where results should be written\n itypes: list\n Denotes the list of non-covalent interaction types to compute contacts for \n geom_criterion_values: dict\n Dictionary containing the cutoff values for all geometric criteria\n stride: int, default = 1\n Frequency to skip frames in trajectory\n solvent_resn: string, default = TIP3\n Denotes the resname of solvent in simulation\n sele_id: string, default = None\n Compute contacts on subset of atom selection based on VMD query\n ligand: list of string, default = None\n Include ligand resname if computing contacts between ligand and binding pocket residues\n index_to_label: dict \n Maps VMD atom index to label \"chain:resname:resid:name:index\"\n {11205: \"A:ASP:114:CA:11205, ...}\n\n Return\n ------\n frag_idx: int \n\n fragment_contacts: list of tuples, [(frame_index, atom1_label, atom2_label, itype), ...]\n \"\"\"\n tic = datetime.datetime.now()\n traj_frag_molid = load_traj(top, traj, beg_frame, end_frame, stride)\n fragment_contacts = []\n\n # Compute contacts for each frame\n num_frag_frames = molecule.numframes(traj_frag_molid)\n for frame_idx in range(num_frag_frames):\n # if frame_idx > 1: break\n fragment_contacts += compute_frame_contacts(traj_frag_molid, frag_idx, frame_idx, itypes, geom_criterion_values,\n solvent_resn, sele_id, ligand, index_to_label)\n\n # Delete trajectory fragment to clear memory\n molecule.delete(traj_frag_molid)\n\n # Update frame-number so it's not relative to beg_frame\n for fc in fragment_contacts:\n fc[0] = beg_frame + (fc[0] * stride)\n\n toc = datetime.datetime.now()\n print(\"Finished computing contacts for fragment %d: %d frames from %d to %d by strides of %d taking %s s\" %\n (frag_idx, num_frag_frames, beg_frame, beg_frame + num_frag_frames * stride - 1, stride, (toc-tic).total_seconds()))\n # print(\"Finished computing contacts for fragment %d (frames %d to %d) in %s s\" %\n # (frag_idx,\n # frag_idx * TRAJ_FRAG_SIZE,\n # frag_idx * TRAJ_FRAG_SIZE + num_frag_frames - 1,\n # (toc-tic).total_seconds())\n # )\n\n # Write directly out to temporary output\n # print(\"Writing output to seperate files, one for each itype ...\")\n #\n # fd_map = {itype: open(OUTPUT + \"_\" + itype + \"_frag_\" + str(frag_idx) + \".txt\", 'w') for itype in contact_types}\n # for contact in fragment_contacts:\n # itype_key = contact[-1]\n # output_string = str(frag_idx) + \"\\t\" + \"\\t\".join(map(str, contact)) + \"\\n\"\n # fd_map[itype_key].write(output_string)\n #\n # for itype in fd_map:\n # fd_map[itype].close()\n #\n # return frag_idx, num_frag_frames - 1\n\n return fragment_contacts\n\n\ndef compute_fragment_contacts_helper(args):\n return compute_fragment_contacts(*args)\n\n\n# def stitch_fragment_contacts(itype, OUTPUT_DIR, frag_contact_files, frag_idx_to_length):\n# \"\"\"\n# Stitch together multiple fragments of non-covalent contacts into\n# single file and delete individual fragment files.\n#\n# Parameters\n# ----------\n# itype: Type of non-covalent contact\n# OUTPUT_DIR: string\n# Absolute path to output directory\n# frag_contact_files: list of strings\n# List of paths to fragment contact files\n# frag_idx_to_length: dict from int to int\n# Map the fragment index to length of fragment\n# \"\"\"\n# print(\"Stitching %s ...\" % (itype))\n# # stitched_filename = OUTPUT_DIR + \"/\" + itype + \".txt\"\n# # stitched_filename = OUTPUT_DIR + full_name_dirs[contact_type] + '/' + 'raw_frame_output.txt'\n# stitched_filename = OUTPUT_DIR + full_name_dirs[itype] + '/' + itype + '.txt'\n# fo = open(stitched_filename, 'w')\n#\n# num_frames = 0\n# for frag_contact_file in frag_contact_files:\n# frag_idx = int(frag_contact_file.split(\"/\")[-1].strip(\".txt\").split(\"_\")[2])\n# ffrag = open(frag_contact_file, 'r')\n# for line in ffrag:\n# linfo = line.split(\"\\t\")\n# frame_idx = int(linfo[1])\n# new_frame_idx = num_frames + frame_idx - 1\n# output_string = str(new_frame_idx) + \"\\t\" + \"\\t\".join(linfo[2:])\n# fo.write(output_string)\n# num_frames += frag_idx_to_length[frag_idx]\n# ffrag.close()\n# os.remove(frag_contact_file)\n#\n# fo.close()\n#\n# return stitched_filename\n\n\ndef compute_contacts(top, traj, output, itypes, geom_criterion_values, cores,\n beg, end, stride, solvent_resn, sele_id, ligand):\n \"\"\"\n Computes non-covalent contacts across the entire trajectory and writes them to `output`.\n\n Parameters\n ----------\n top: Topology\n In .pdb or .mae format\n traj: Trajectory\n In .nc or .dcd format\n output: string\n Absolute path to output file\n itypes: list\n Denotes the list of non-covalent interaction types to compute contacts for \n geom_criterion_values: dict\n Dictionary containing the cutoff values for all geometric criteria\n cores: int, default\n Number of CPU cores to parallelize over\n beg: int\n First frame to read\n end: int\n Last frame to read\n stride: int, default\n The number of frames to increment after each read frame\n solvent_resn: string, default = TIP3\n Denotes the resname of solvent in simulation\n sele_id: string, default = None\n Compute contacts on subset of atom selection based on VMD query\n ligand: list of string, default = None\n Include ligand resname if computing contacts between ligand and binding pocket residues\n \"\"\"\n contact_types = []\n for itype in itypes:\n if itype == \"hb\":\n contact_types += [\"hbbb\", \"hbsb\", \"hbss\", \"wb\", \"wb2\"]\n elif itype == \"lhb\":\n contact_types += [\"hls\", \"hlb\", \"lwb\", \"lwb2\"]\n else:\n contact_types += [itype]\n\n index_to_label = gen_index_to_atom_label(top, traj)\n sim_length = simulation_length(top, traj)\n\n beg = max(min(beg, sim_length-1), 0)\n end = min(max(end, beg), sim_length - 1)\n stride = max(1, stride)\n num_fragments = math.ceil((end - beg + 1) / (TRAJ_FRAG_SIZE * stride))\n\n # Generate input arguments for each trajectory piece\n inputqueue = Queue()\n print(\"Processing %s (frame %d to %d with stride of %d) as %d fragments\\n\" %\n (traj, beg, end, stride, num_fragments))\n\n for frag_idx, beg_frame in enumerate(range(beg, end + 1, TRAJ_FRAG_SIZE * stride)):\n end_frame = beg_frame + (TRAJ_FRAG_SIZE * stride) - 1\n # print(frag_idx, beg_frame, end_frame, stride)\n inputqueue.put((frag_idx, beg_frame, end_frame, top, traj, output, itypes, geom_criterion_values,\n stride, solvent_resn, sele_id, ligand, index_to_label))\n\n # Set up result queue for workers to transfer results to the consumer\n resultsqueue = Queue()\n\n # Set up and start worker processes\n num_workers = max(1, cores - 1)\n for _ in range(num_workers):\n inputqueue.put(\"DONE\") # Stops each worker process\n workers = [Process(target=contact_worker, args=(inputqueue, resultsqueue)) for _ in range(num_workers)]\n for w in workers:\n w.start()\n\n # Set up and start consumer process which takes contact results and saves them to output\n output_fd = open(output, \"w\")\n consumer = Process(target=contact_consumer, args=(resultsqueue, output_fd, sim_length, itypes, beg, end, stride))\n consumer.start()\n\n # Wait for everyone to finish\n for w in workers:\n w.join()\n resultsqueue.put(\"DONE\")\n consumer.join()\n\n\ndef contact_worker(inputqueue, resultsqueue):\n while True:\n args = inputqueue.get()\n if args == \"DONE\":\n return\n contacts = compute_fragment_contacts(*args)\n # print(args)\n resultsqueue.put(contacts)\n\n\ndef contact_consumer(resultsqueue, output_fd, sim_length, itypes, beg, end, stride):\n import heapq\n\n total_frames = math.ceil((end - beg + 1) / stride)\n output_fd.write(\"# total_frames:%d beg:%d end:%d stride:%d interaction_types:%s\\n\" %\n (total_frames, beg, end, stride, \",\".join(itypes)))\n output_fd.write(\"# Columns: frame, interaction_type, atom_1, atom_2[, atom_3[, atom_4]]\\n\")\n\n resultheap = []\n waiting_for_frame = beg\n\n while True:\n contacts = resultsqueue.get()\n if contacts == \"DONE\":\n output_fd.close()\n break\n\n # print(contacts)\n first_contact_frame = contacts[0][0]\n heapq.heappush(resultheap, (first_contact_frame, contacts))\n\n # If this is the contact frame we're waiting for, go ahead and write it\n while waiting_for_frame == first_contact_frame:\n _, contacts = heapq.heappop(resultheap)\n if resultheap:\n first_contact_frame = resultheap[0][0]\n\n # Strip VMD id, order atom 1 and 2\n for interaction in contacts:\n for a in range(2, len(interaction)):\n atom_str = interaction[a]\n interaction[a] = atom_str[0:atom_str.rfind(\":\")]\n\n # Sort atom 1 and 2 lexicographically\n if interaction[3] < interaction[2]:\n interaction[2], interaction[3] = interaction[3], interaction[2] # Swap\n\n contact_line_hash = set()\n for interaction in contacts:\n # Write to file\n waiting_for_frame = max(waiting_for_frame, interaction[0] + stride)\n interaction[0] = str(interaction[0])\n contact_line = \"\\t\".join(interaction)\n if contact_line not in contact_line_hash:\n output_fd.write(contact_line)\n output_fd.write(\"\\n\")\n contact_line_hash.add(contact_line)\n","sub_path":"contact_calc/compute_contacts.py","file_name":"compute_contacts.py","file_ext":"py","file_size_in_byte":17731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"567091665","text":"zen = [['The', 'Zen', 'of', 'Python,', 'by', 'Tim', 'Peters'],\n ['Beautiful', 'is', 'better', 'than', 'ugly.'],\n ['Explicit', 'is', 'better', 'than', 'implicit.']]\n\nwyrazy_dwa_znaki = []\n\n# tu napisz swoją pętlę\n\nprint()\nprint(\"Wyrazy z dwoma znakami:\", wyrazy_dwa_znaki)\n","sub_path":"zajęcia03/zadania/zadanie02_szablon.py","file_name":"zadanie02_szablon.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"546570739","text":"import numpy as np\nimport drawing\nfrom drawing import MAX_CHAR_LEN, MAX_STROKE_LEN\n\n\ndef load_data(path):\n samples = np.load(path, allow_pickle=True)\n return samples\n\n\ndef process_stroke(stroke):\n sps = stroke[:, -1]\n stroke[:, -1] = np.where(np.diff(np.insert(sps, 0, 0)) > 0.5, 1, 0)\n stroke = stroke[:MAX_STROKE_LEN]\n stroke = drawing.normalize(stroke)\n\n return stroke\n\n\ndef process_chars(chars):\n chars = chars.strip()\n if any(c not in drawing.alphabet for c in chars):\n return None\n chars = drawing.encode_ascii(chars)[:MAX_CHAR_LEN]\n return chars\n\n\ndef process_data(samples):\n strokes, chars = [], []\n for sample in samples:\n stroke = process_stroke(sample['stroke'][:, 0:-1])\n char = process_chars(sample['text'])\n if char is not None:\n strokes.append(stroke)\n chars.append(char)\n else:\n continue\n return strokes, chars\n\n\nif __name__ == \"__main__\":\n data = load_data('data/raw/all_data.npy')\n strokes, chars = process_data(data)\n\n x = np.zeros([len(strokes), drawing.MAX_STROKE_LEN, 3], dtype=np.float32)\n x_len = np.zeros([len(strokes)], dtype=np.int16)\n c = np.zeros([len(strokes), drawing.MAX_CHAR_LEN], dtype=np.int8)\n c_len = np.zeros([len(strokes)], dtype=np.int8)\n\n for i, (stroke, char) in enumerate(zip(strokes, chars)):\n x[i, :len(stroke), :] = stroke\n x_len[i] = len(stroke)\n\n c[i, :len(char)] = char\n c_len[i] = len(char)\n\n np.save('data/processed/x.npy', x)\n np.save('data/processed/x_len.npy', x_len)\n np.save('data/processed/c.npy', c)\n np.save('data/processed/c_len.npy', c_len)\n","sub_path":"prepare_synth_data.py","file_name":"prepare_synth_data.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"577041010","text":"#!/usr/bin/env python\nimport rospy\nfrom sensor_msgs.msg import LaserScan\nimport datetime\nimport sys\n#primer parametro distancia+cm \n#segundo parametro angulo inicio en grados\n#tercer parametro angulo fin en grados\n\nANGULO_FINAL=225\nANGULO_INICIO=-45\ndiferenciaInicio=0\ndiferenciaFin=0\ndef guardarDatosLaser(data):\n hoy = datetime.datetime.now().date()\n distancia=sys.argv[1]\n seq=str(data.header.seq)\n secs=str(data.header.seq)\n nsecs=str(data.header.stamp.nsecs)\n distancias=list(data.ranges)\n intensidades=list(data.intensities)\n if len(sys.argv)==4:\n diferenciaInicio=float(sys.argv[2])-ANGULO_INICIO\n diferenciaFin=ANGULO_FINAL-float(sys.argv[3])\n distancias=distancias[int(diferenciaInicio*2):541-int(diferenciaFin*2)]\n intensidades=intensidades[int(diferenciaInicio*2):541-int(diferenciaFin*2)]\n fichero = open ('DatosLaser'+str(hoy)+'_'+distancia+'.txt', 'a')\n #rospy.loginfo(\"Capturando datos secuencia %s\", str(data.header.seq))\n #secuencia escaneo,segundos, nanosegundos,tiempo de escaneo, arreglo de rangos , arreglo de intensidades\n fichero.write(seq+','+secs+','+nsecs+','+str(data.scan_time)+\",\"+distancias+','+intensidades+\"\\n\")\n fichero.close() \n\ndef listener():\n rospy.init_node('CapturadorDatosLaser', anonymous=True)\n rospy.Subscriber(\"scan\", LaserScan, guardarDatosLaser)\n rospy.spin()\n\nif __name__ == '__main__':\n listener()\n","sub_path":"src/Laser_LIDAR/src/CapturadorDatosLaserAngulos.py","file_name":"CapturadorDatosLaserAngulos.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"274071876","text":"from pynput import keyboard \r\nimport time\r\nfrom datetime import datetime\r\n#from run import analysis\r\n#from sendemail import send_p, send_a\r\n\r\n\r\n## print(hand['f'])\r\n\r\n\r\n\r\nglobal tame \r\nglobal cow \r\n\r\nhand = {\r\n \"a\": 'L', 'A': 'L',\r\n 'b': 'R', 'B': 'R',\r\n 'c': 'L', 'C': 'L',\r\n 'd': 'L', 'D': 'L',\r\n 'e': 'L', 'E': 'L',\r\n 'f': 'L', 'F': 'L',\r\n 'g': 'L', 'G': 'L',\r\n 'h': 'R', 'H': 'R',\r\n 'i': 'R', 'I': 'R',\r\n 'j': 'R', 'J': 'R',\r\n 'k': 'R', 'K': 'R',\r\n 'l': 'R', 'L': 'R',\r\n 'm': 'R', 'M': 'R',\r\n 'n': 'R', 'N': 'R',\r\n 'o': 'R', 'O': 'R',\r\n 'p': 'R', 'P': 'R',\r\n 'q': 'L', 'Q': 'L',\r\n 'r': 'L', 'R': 'L',\r\n 's': 'L', 'S': 'L',\r\n 't': 'L', 'T': 'L',\r\n 'u': 'R', 'U': 'R',\r\n 'v': 'L', 'V': 'L',\r\n 'w': 'L', 'W': 'L',\r\n 'x': 'L', 'X': 'L',\r\n 'y': 'R', 'Y': 'R',\r\n 'z': 'L', 'Z': 'L'\r\n\r\n }\r\n\r\ndef k_press():\r\n t = {\r\n 'UserKey': 'Patient1234',\r\n 'Date': datetime.today().strftime('%d-%m-%y').replace(\"-\", \"\"),\r\n 'Hand':\"\",\r\n 'Timestamp': datetime.today().strftime('%H:%M:%S'),\r\n 'time': time.time(),\r\n 'time_flight': time.time(),\r\n 'released': True,\r\n 'keys_pressed': 0,\r\n 'keys': []\r\n }\r\n\r\n global num\r\n num = 0 \r\n\r\n global lis\r\n lis = ['R']\r\n #global length\r\n #length = len(lis)\r\n\r\n global lat1\r\n global ma\r\n ma = [0,0]\r\n\r\n global caw\r\n caw = [0, 0, 0, 0]\r\n\r\n\r\n LOAD_THRESH = 0\r\n\r\n\r\n def load_to_csv(keys, fname='/Users/Sumeet/Desktop/CognitoMaster/presses.txt'):\r\n with open(fname, 'a') as f:\r\n for key_name, hold_time, release_time in keys:\r\n Date = datetime.today().strftime('%d-%m-%y').replace(\"-\", \"\")\r\n timestamp = datetime.today().strftime('%H:%M:%S')\r\n global id\r\n id = \"Patient1234\"\r\n ####manssss = str(manssss)\r\n ##man2 = \"{:0.4f}\".format(man2)\r\n ##man2 = str(man2)\r\n k = str(key_name)\r\n if '\\\\' in k:\r\n continue\r\n k = k.replace(\"'\", \"\")\r\n k = k.replace(\"Key.\", \"\")\r\n k = k.replace(')', 'parenleft')\r\n k = k.replace(',', 'comma')\r\n k = k.replace(':', 'colon')\r\n k = k.replace(';', 'semicolon')\r\n k = k.replace('.', 'period')\r\n k = k.replace('(', 'parenright')\r\n k = k.replace('?', 'question')\r\n k = k.replace('enter', 'Return')\r\n if k == 'shift':\r\n k = 'Shift_L'\r\n k = k.replace('shift_r', 'Shift_R')\r\n k = k.replace('backspace', 'BackSpace')\r\n x = \" \"\r\n ran = ma[-1]- ma[-2]\r\n ram = caw[-1] - caw[-2]\r\n m = (\"Patient1234\" + 6*x + Date + 2*x + timestamp + 4*x + cow + 7*x + \"{:<0.4f}\".format(hold_time) + 2*x + amazon + 6*x + str(\"{:<0.4f}\".format(ran)) + 2*x + str(\"{:<0.4f}\".format(ram)) + \"\\n. \")\r\n m = m.replace(\". Patient1234 \", \"Patient1234\")\r\n f.write(m)\r\n \r\n\r\n\r\n\r\n\r\n\r\n def on_press(key):\r\n hand = {\r\n \"a\": 'L', 'A': 'L',\r\n 'b': 'R', 'B': 'R',\r\n 'c': 'L', 'C': 'L',\r\n 'd': 'L', 'D': 'L',\r\n 'e': 'L', 'E': 'L',\r\n 'f': 'L', 'F': 'L',\r\n 'g': 'L', 'G': 'L',\r\n 'h': 'R', 'H': 'R',\r\n 'i': 'R', 'I': 'R',\r\n 'j': 'R', 'J': 'R',\r\n 'k': 'R', 'K': 'R',\r\n 'l': 'R', 'L': 'R',\r\n 'm': 'R', 'M': 'R',\r\n 'n': 'R', 'N': 'R',\r\n 'o': 'R', 'O': 'R',\r\n 'p': 'R', 'P': 'R',\r\n 'q': 'L', 'Q': 'L',\r\n 'r': 'L', 'R': 'L',\r\n 's': 'L', 'S': 'L',\r\n 't': 'L', 'T': 'L',\r\n 'u': 'R', 'U': 'R',\r\n 'v': 'L', 'V': 'L',\r\n 'w': 'L', 'W': 'L',\r\n 'x': 'L', 'X': 'L',\r\n 'y': 'R', 'Y': 'R',\r\n 'z': 'L', 'Z': 'L',\r\n 'Key.space': 'S', \r\n 'Key.esc': 'R'\r\n \r\n\r\n }\r\n lat1 = time.time()\r\n ma.append(lat1)\r\n print(ma[-1] - ma[-2])\r\n global cow3\r\n global num\r\n cow1 = str(key)\r\n cow2 = cow1.replace('\"', '')\r\n cow3 = cow2.replace(\"'\", \"\")\r\n \r\n if((cow3 in hand) or cow3 == 'Key.esc'):\r\n global cow \r\n cow = hand.get(cow3, \"\")\r\n lis.append(cow)\r\n print(lis)\r\n global amazon\r\n amazon = (lis[-2] + cow)\r\n print(amazon)\r\n #print(cow)\r\n global reee\r\n reee = True\r\n if t['released']:\r\n t['time'] = time.time()\r\n t['released'] = False\r\n print(f'{key} pressed after {time.time() - t[\"time_flight\"]}')\r\n global tame \r\n tame = t['Date'].replace(\"-\", \"\")\r\n #print(tame)\r\n else: \r\n pass\r\n reee = False\r\n global ama1\r\n ama1 = time.time()\r\n caw.append(ama1)\r\n \r\n \r\n \r\n\r\n def on_release(key):\r\n if(cow3 in hand or cow3 == 'Key.esc'):\r\n #print('{0} held for {1}s'.format(\r\n #key, time.time() - t['time']))\r\n t['released'] = True\r\n t['keys_pressed'] += 1\r\n if t['keys_pressed'] and reee:\r\n load_to_csv(t['keys'])\r\n t['keys'] = []\r\n else:\r\n pass\r\n id = \"Patient1234\"\r\n timestamp = datetime.today().strftime('%H:%M:%S')\r\n global hold_time\r\n hold_time = round(time.time() - t['time'], 4)\r\n t['keys'].append(\r\n (\r\n str(key),\r\n round(time.time() - t['time'], 4),\r\n round(time.time() - t['time_flight'], 4),\r\n )\r\n )\r\n if key == keyboard.Key.esc:\r\n # Stop listener\r\n return False\r\n else:\r\n pass\r\n global ama\r\n ama = time.time()\r\n caw.append(ama)\r\n\r\n with keyboard.Listener(\r\n on_press=on_press,\r\n on_release=on_release,\r\n ) as listener:\r\n listener.join()\r\n\r\nk_press()\r\n\r\n \r\n","sub_path":"keypress.py","file_name":"keypress.py","file_ext":"py","file_size_in_byte":6160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"506702313","text":"# -*- coding: utf-8 -*-\nimport os, sys\nimport time, datetime\n\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\nsys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../util'))\nimport loghelper\nimport db\n\n#logger\nloghelper.init_logger(\"user_abnormal_log2\", stream=True)\nlogger = loghelper.get_logger(\"user_abnormal_log2\")\n\n\ndef main():\n logger.info(\"cookie cnt > 50 in 60m\")\n ips = {}\n mongo = db.connect_mongo()\n logs = list(mongo.log.user_log.find({\"code\": 0, \"time\": {\"$gte\": datetime.datetime.utcnow() - datetime.timedelta(minutes=60)}}))\n for log in logs:\n ip = log.get(\"ip\")\n if ip is None:\n continue\n if ip.startswith(\"10.\"):\n continue\n\n user_cookie = log.get(\"userCookie\")\n if user_cookie is None:\n continue\n\n if ips.has_key(ip):\n if user_cookie not in ips[ip]:\n ips[ip].append(user_cookie)\n else:\n ips[ip] = [user_cookie]\n\n spider_ips = load_spider_ip()\n for k, v in ips.items():\n if len(v) > 50:\n bip = mongo.xiniudata.blackwhitelist.find_one({\"ip\" : k})\n if bip is None:\n if not spider_ips.has_key(k):\n logger.info(\"ip: %s, cookie cnt: %s\", k, len(v))\n mongo.xiniudata.blackwhitelist.insert_one({\"type\" : \"black\", \"ip\" : k, \"status\": \"Y\",\n \"createTime\": datetime.datetime.utcnow(),\n \"memo\": \"in 1 hour cookie cnt: %s\" % (len(v))})\n\n\ndef main2():\n logger.info(\"cookie cnt > 5 in 1m\")\n ips = {}\n ips_cnt = {}\n mongo = db.connect_mongo()\n logs = list(mongo.log.user_log.find({\"code\": 0, \"time\": {\"$gte\": datetime.datetime.utcnow() - datetime.timedelta(minutes=1)}}))\n for log in logs:\n ip = log.get(\"ip\")\n if ip is None:\n continue\n if ip.startswith(\"10.\"):\n continue\n\n user_cookie = log.get(\"userCookie\")\n if user_cookie is None:\n continue\n\n if ips.has_key(ip):\n if user_cookie not in ips[ip]:\n ips[ip].append(user_cookie)\n else:\n ips[ip] = [user_cookie]\n\n if ips_cnt.has_key(ip):\n ips_cnt[ip] += 1\n else:\n ips_cnt[ip] = 1\n\n spider_ips = load_spider_ip()\n for k, v in ips.items():\n if len(v) >= 5:\n bip = mongo.xiniudata.blackwhitelist.find_one({\"ip\" : k})\n if bip is None:\n if not spider_ips.has_key(k):\n total = ips_cnt[k]\n cnt = len(v)\n rate = (cnt+0.0) / total\n logger.info(\"ip: %s, cookie cnt: %s, total cnt:%s, rate: %s\", k, cnt, total, rate)\n if rate > 0.9 or cnt > 10:\n mongo.xiniudata.blackwhitelist.insert_one({\"type\" : \"black\", \"ip\" : k, \"status\": \"Y\",\n \"createTime\": datetime.datetime.utcnow(),\n \"memo\": \"in 1 minute cookie cnt: %s, total cnt:%s\" % (cnt, total)})\n\n\ndef load_spider_ip():\n ips = {}\n fp = open('spider_ip.txt')\n for line in fp.readlines():\n ip = line.strip()\n ips[ip] = 1\n return ips\n\n\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n p = sys.argv[1]\n if p == \"test\":\n main2()\n exit()\n\n while True:\n main2()\n time.sleep(10)","sub_path":"data/monitor/user_abnormal_log2.py","file_name":"user_abnormal_log2.py","file_ext":"py","file_size_in_byte":3577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"510415599","text":"import sys\nimport random\nimport os\nimport pandas as pd\nfrom PIL import Image\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torchvision.datasets as datasets\nfrom torch.utils.data import Dataset, DataLoader\nimport torchvision.models as models\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nfrom torch.autograd import Variable\nfrom torchvision.utils import save_image\ndevice = torch.device(\"cuda\")\n\ndef where(cond, x, y):\n \"\"\"\n code from :\n https://discuss.pytorch.org/t/how-can-i-do-the-operation-the-same-as-np-where/1329/8\n \"\"\"\n cond = cond.float()\n return (cond*x) + ((1-cond)*y)\n\n# 實作一個繼承 torch.utils.data.Dataset 的 Class 來讀取圖片\nclass Adverdataset(Dataset):\n def __init__(self, root, label, transforms):\n # 圖片所在的資料夾\n self.root = root\n # 由 main function 傳入的 label\n self.label = torch.from_numpy(label).long()\n # 由 Attacker 傳入的 transforms 將輸入的圖片轉換成符合預訓練模型的形式\n self.transforms = transforms\n # 圖片檔案名稱的 list\n self.fnames = []\n\n for i in range(200):\n self.fnames.append(\"{:03d}\".format(i))\n\n def __getitem__(self, idx):\n # 利用路徑讀取圖片\n img = Image.open(os.path.join(self.root, self.fnames[idx] + '.png'))\n # 將輸入的圖片轉換成符合預訓練模型的形式\n img = self.transforms(img)\n # 圖片相對應的 label\n label = self.label[idx]\n return img, label\n \n def __len__(self):\n # 由於已知這次的資料總共有 200 張圖片 所以回傳 200\n return 200\n \n\nclass Attacker:\n def __init__(self, img_dir, label, output_dir):\n # 讀入預訓練模型 vgg16\n self.model = models.densenet121(pretrained = True)\n self.model.to(device)\n self.model.eval()\n\n self.mean = [0.485, 0.456, 0.406]\n self.std = [0.229, 0.224, 0.225]\n # 把圖片 normalize 到 0~1 之間 mean 0 variance 1\n self.normalize = transforms.Normalize(self.mean, self.std, inplace=False)\n transform = transforms.Compose([ \n transforms.Resize((224, 224), interpolation=3),\n #transforms.Resize(224, (0.8, 1.0), (0.8, 1.2), interpolation=3),\n transforms.ToTensor(),\n self.normalize\n ])\n # 利用 Adverdataset 這個 class 讀取資料\n self.dataset = Adverdataset(img_dir, label, transform)\n self.output_dir = output_dir\n #self.dataset = Adverdataset('./data/images', label, transform)\n self.loader = torch.utils.data.DataLoader(\n self.dataset,\n batch_size = 1,\n shuffle = False)\n\n def fgsm_attack(self, image, epsilon, data_grad):\n # 找出 gradient 的方向\n sign_data_grad = data_grad.sign()\n # 將圖片加上 gradient 方向乘上 epsilon 的 noise\n perturbed_image = image + epsilon * sign_data_grad\n return perturbed_image\n \n def attack(self, epsilon):\n # 存下一些成功攻擊後的圖片 以便之後顯示\n adv_examples = []\n wrong, fail, success, linf = 0, 0, 0, 0\n for i, (data, target) in enumerate(self.loader):\n #print(i)\n data, target = data.to(device), target.to(device)\n # padding\n '''\n for j in range(3):\n for k in range(2):\n for l in range(224):\n data[0, j, k, l] = 0\n data[0, j, 224-k-1, l] = 0\n data[0, j, l, k] = 0\n data[0, j, l, 224-k-1] = 0\n '''\n data_raw = data;\n data_adv = Variable(data.data, requires_grad=True)\n # 將圖片丟入 model 進行測試 得出相對應的 class\n for step in range(20):\n output = self.model(data_adv)\n init_pred = output.max(1, keepdim=True)[1]\n\n # 如果 class 錯誤 就不進行攻擊\n #print(init_pred.item())\n #print(target.item())\n if init_pred.item() != target.item():\n #wrong += 1\n if step == 0:\n wrong += 1\n #print('WRONG')\n break\n \n # 如果 class 正確 就開始計算 gradient 進行 FGSM 攻擊\n loss = F.nll_loss(output, target)\n self.model.zero_grad()\n loss.backward()\n #print(data_raw.grad)\n data_grad = data_adv.grad.data\n data_adv = self.fgsm_attack(data_adv, epsilon, data_grad)\n \n # 再將加入 noise 的圖片丟入 model 進行測試 得出相對應的 class \n output = self.model(data_adv)\n self.model.zero_grad() \n data_adv = where(data_adv > data_raw+eps, data_raw+eps, data_adv)\n data_adv = where(data_adv < data_raw-eps, data_raw-eps, data_adv)\n #print(data_adv.min())\n #data_adv = torch.clamp(data_adv, -1, 1)\n #print(data_adv)\n if step < 19:\n #data_adv = where(data_adv > data+eps, data+eps, data_adv)\n #data_adv = where(data_adv < data-eps, data-eps, data_adv)\n data_adv = Variable(data_adv.data, requires_grad=True)\n \n final_pred = output.max(1, keepdim=True)[1]\n #print(final_pred)\n inv_normalize = transforms.Normalize(\n mean=[-0.485/0.229, -0.456/0.224, -0.406/0.225],\n std=[1/0.229, 1/0.224, 1/0.225]\n )\n inv_tensor = inv_normalize(data_adv.squeeze(0)) \n save_image(inv_tensor, self.output_dir +'/{:0>3d}.png'.format(i))\n \n if final_pred.item() == target.item():\n # 辨識結果還是正確 攻擊失敗\n fail += 1\n #print('FAIL')\n else:\n # 辨識結果失敗 攻擊成功\n success += 1\n #print('SUCCESS')\n \n if len(adv_examples) < 5:\n adv_ex = data_adv * torch.tensor(self.std, device = device).view(3, 1, 1) + torch.tensor(self.mean, device = device).view(3, 1, 1)\n adv_ex = adv_ex.squeeze().detach().cpu().numpy() \n data_raw = data_raw * torch.tensor(self.std, device = device).view(3, 1, 1) + torch.tensor(self.mean, device = device).view(3, 1, 1)\n data_raw = data_raw.squeeze().detach().cpu().numpy()\n adv_examples.append( (init_pred.item(), final_pred.item(), data_raw , adv_ex) ) \n final_acc = (wrong / (wrong + success + fail))\n #print(\"Epsilon: {}\\tTest Accuracy = {} / {} = {}\\n\".format(epsilon, wrong, len(self.loader), final_acc))\n return adv_examples, final_acc\n\nif __name__ == '__main__':\n\n # Set seed\n seed = 100\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.deterministic = True\n \n # 讀入圖片相對應的 label\n input_dir = sys.argv[1]\n output_dir = sys.argv[2]\n df = pd.read_csv(input_dir + \"/labels.csv\")\n df = df.loc[:, 'TrueLabel'].to_numpy()\n label_name = pd.read_csv(input_dir + \"/categories.csv\")\n label_name = label_name.loc[:, 'CategoryName'].to_numpy()\n # new 一個 Attacker class\n attacker = Attacker(output_dir, df, output_dir)\n # 要嘗試的 epsilon\n epsilons = [0.017]\n accuracies, examples = [], []\n\n # 進行攻擊 並存起正確率和攻擊成功的圖片\n for eps in epsilons:\n ex, acc = attacker.attack(eps)\n accuracies.append(acc)\n examples.append(ex)\n\n","sub_path":"hw6/main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":8045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"548632116","text":"import random #importujeme modul random\n\njmenaKluk = [\"Jakub\",\n\"Jan\",\n\"Adam\",\n\"Matyáš\",\n\"Tomáš\",\n\"Vojtěch\",\n\"Matěj\",\n\"Filip\",\n\"Ondřej\",\n\"Dominik\",\n\"Daniel\",\n\"Martin\",\n\"David\",\n\"Lukáš\",\n\"Marek\",\n\"Václav\",\n\"Antonín\",\n\"Jiří\",\n\"Kryštof\",\n\"Tobiáš\"] #databáze 20 nejoblíběnějších klučičích jmen za rok 2019\n\njmenaHolka = [\"Eliška\",\n\"Anna\",\n\"Sofie\",\n\"Ema\",\n\"Tereza\",\n\"Karolína\",\n\"Adéla\",\n\"Viktorie\",\n\"Natálie\",\n\"Kristýna\",\n\"Emma\",\n\"Julie\",\n\"Amalie\",\n\"Nela\",\n\"Anežka\",\n\"Marie\",\n\"Klára\",\n\"Laura\",\n\"Barbora\",\n\"Kateřina\"] #databáze 20 holčičích jmen za rok 2019\n\nprint(\"Dobrý den, asi budete mít dítě! Nevíte jak ho pojmenovat? Poradíme vám! Bude to kluk nebo holka?\") #dotaz\npohlavi = input() #odpověď\npohlavi = pohlavi.lower()\nif pohlavi == \"kluk\": #odpověď pokud uživatel bude mít kluka\n random.shuffle(jmenaKluk)\n print(\"Můžete svého syna pojemnovat třeba\", jmenaKluk[0])\n\nelif pohlavi == \"holka\": #odpověď pokud uživatel bude mít holku\n random.shuffle(jmenaHolka)\n print(\"Můžete svojí dceru pojmenovat třeba\", jmenaHolka[0])\nelse:\n print(pohlavi + \" není pohlaví. Pohlaví jsou přece jen 2.\") #odpověď pokud uživatel napíše něco jiného než holka/kluk, osobně si nemyslím že jsou jen 2 pohlaví je to vtípek\n","sub_path":"generátor dětského jména.py","file_name":"generátor dětského jména.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"83671270","text":"import requests\nimport os\n\ndef getPic(url):\n root=\"C:/users/rachel/desktop/\"\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 kv={'user-agent':'Moziila/5.0'}\n r=requests.get(url,headers=kv,timeout=30)\n with open(path,'wb') as f:\n f.write(r.content)\n print(\"文件成功保存\")\n else:\n print(\"文件已存在\")\n except:\n print(\"爬取失败\")\nif __name__==\"__main__\":\n url=\"https://zimg.zazhimall.com.cn/images/201811/source_img/7076_P_1542849040566.jpg\"\n getPic(url)","sub_path":"Template-picture.py","file_name":"Template-picture.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"39853996","text":"import numpy as np\n\n\nclass Layer:\n \"\"\"\n Base class for all layers.\n \"\"\"\n\n def __init__(self, input_shape: tuple, output_shape: tuple, activation: str = None, name: str = None):\n self.input_shape = input_shape\n self.output_shape = output_shape\n self.activation = activation\n self.weights = None\n self.bias = None\n self.name = name\n\n def forward(self, inputs: np.ndarray) -> np.ndarray:\n \"\"\"\n Forward pass of the layer.\n Args:\n inputs: input to the layer.\n Returns:\n output of the layer.\n \"\"\"\n raise NotImplementedError\n","sub_path":"layers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"58045154","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom layers.mha_layer import MultiHeadAttentionLayer\nfrom layers.NystromAttn import attn\nfrom layers.pff import PositionwiseFeedforwardLayer\n\n\nclass EncoderLayer(nn.Module):\n def __init__(self,\n hid_dim,\n head_dim,\n n_heads,\n n_landmarks,\n pf_dim,\n dropout):\n super().__init__()\n\n self.self_attn_layer_norm = nn.LayerNorm(hid_dim)\n self.ff_layer_norm = nn.LayerNorm(hid_dim)\n self.self_attention = attn\n self.positionwise_feedforward = PositionwiseFeedforwardLayer(hid_dim,\n pf_dim,\n dropout)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, src, src_mask):\n\n #src = [batch size, src len, hid dim]\n #src_mask = [batch size, src_len]\n\n #self attention\n _src = self.self_attention(src, src_mask)\n\n #dropout, residual connection and layer norm\n src = self.self_attn_layer_norm(src + self.dropout(_src))\n\n #src = [batch size, src len, hid dim]\n\n #positionwise feedforward\n _src = self.positionwise_feedforward(src)\n\n #dropout, residual and layer norm\n src = self.ff_layer_norm(src + self.dropout(_src))\n\n #src = [batch size, src len, hid dim]\n\n return src","sub_path":"layers/encoder_layer.py","file_name":"encoder_layer.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"52768641","text":"def kole(arr,w):\n A={}\n s=len(arr)\n for i in range(s):\n tmp=arr[i]\n \n temp=tmp[1]/tmp[0]\n\n \n A[i]=temp\n\n sorted (A.items())\n listofTuples = sorted(A.items() , key=lambda x: x[1]) \n print(listofTuples)\n size=len(A)\n res=0\n\n i=size-1 \n weight=0 \n while i>=0 :\n z=listofTuples[i][0]\n tmp=arr[z]\n print(arr[z])\n weight=weight+tmp[0]\n if weight<= w:\n res=res+tmp[1] \n i=i-1 \n\n print(res)\n\n\n\n\n\n\n\n\n\n\n\n\n\narr=[(5,10),(3,20),(8,25),(4,8)]\n#arr={5:10,3:20,8:25,4:8}\nw=13\nkole(arr,w)","sub_path":"knapsak.py","file_name":"knapsak.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"92274187","text":"#-*- coding: utf-8 -*-\nimport sys\nimport string\n\nCHAR_MAP = dict(zip(\n string.ascii_lowercase,\n string.ascii_lowercase[13:26] + string.ascii_lowercase[0:13]\n))\n\ndef rotate13_letter(letter):\n '''\n Return the 13-char rotation of a letter.\n '''\n do_upper = False\n if letter.isupper():\n do_upper = True\n letter = letter.lower()\n if letter not in CHAR_MAP:\n return letter\n else:\n letter = CHAR_MAP[letter]\n if do_upper:\n letter = letter.upper()\n return letter\n\nif __name__ == '__main__':\n for char in sys.argv[1]:\n sys.stdout.write(rotate13_letter(char))\n sys.stdout.write('\\n')","sub_path":"copiedFromOthers/rot13.py","file_name":"rot13.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"236062364","text":"#!/usr/bin/env vpython3\n# *-* coding: utf-8 *-*\nfrom certum import dllpath\nfrom lxml import etree\nimport PyKCS11 as PK11\nfrom cryptography import x509\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import serialization\n\nfrom endesive import xades, signer, hsm\n\n\n\nclass Signer(hsm.HSM):\n def certificate(self):\n self.login(\"profil bezpieczny\", \"9593\")\n keyid = [\n 0x5E,\n 0x9A,\n 0x33,\n 0x44,\n 0x8B,\n 0xC3,\n 0xA1,\n 0x35,\n 0x33,\n 0xC7,\n 0xC2,\n 0x02,\n 0xF6,\n 0x9B,\n 0xDE,\n 0x55,\n 0xFE,\n 0x83,\n 0x7B,\n 0xDE,\n ]\n # keyid = [0x3f, 0xa6, 0x63, 0xdb, 0x75, 0x97, 0x5d, 0xa6, 0xb0, 0x32, 0xef, 0x2d, 0xdc, 0xc4, 0x8d, 0xe8]\n keyid = bytes(keyid)\n try:\n pk11objects = self.session.findObjects(\n [(PK11.CKA_CLASS, PK11.CKO_CERTIFICATE)]\n )\n all_attributes = [\n # PK11.CKA_SUBJECT,\n PK11.CKA_VALUE,\n # PK11.CKA_ISSUER,\n # PK11.CKA_CERTIFICATE_CATEGORY,\n # PK11.CKA_END_DATE,\n PK11.CKA_ID,\n ]\n\n for pk11object in pk11objects:\n try:\n attributes = self.session.getAttributeValue(\n pk11object, all_attributes\n )\n except PK11.PyKCS11Error as e:\n continue\n\n attrDict = dict(list(zip(all_attributes, attributes)))\n cert = bytes(attrDict[PK11.CKA_VALUE])\n if keyid == bytes(attrDict[PK11.CKA_ID]):\n return keyid, cert\n finally:\n self.logout()\n return None, None\n\n def sign(self, keyid, data, mech):\n self.login(\"profil bezpieczny\", \"9593\")\n try:\n privKey = self.session.findObjects(\n [(PK11.CKA_CLASS, PK11.CKO_PRIVATE_KEY), (PK11.CKA_ID, keyid)]\n )[0]\n mech = getattr(PK11, \"CKM_%s_RSA_PKCS\" % mech.upper())\n sig = self.session.sign(privKey, data, PK11.Mechanism(mech, None))\n return bytes(sig)\n finally:\n self.logout()\n\n\ndef main():\n clshsm = Signer(dllpath)\n keyid, cert = clshsm.certificate()\n\n def signproc(tosign, algosig):\n return clshsm.sign(keyid, tosign, algosig)\n\n data = open(\"xml.xml\", \"rb\").read()\n cert = x509.load_der_x509_certificate(cert, backend=default_backend())\n certcontent = cert.public_bytes(serialization.Encoding.DER)\n\n for tspurl, tspcred in (\n (None, None),\n (\"http://public-qlts.certum.pl/qts-17\", None)\n ):\n cls = xades.BES()\n doc = cls.enveloping(\n \"dokument.xml\",\n data,\n \"application/xml\",\n cert,\n certcontent,\n signproc,\n False,\n False,\n False,\n tspurl,\n tspcred,\n )\n data = etree.tostring(doc, encoding=\"UTF-8\", xml_declaration=True, standalone=False)\n if tspurl is None:\n open(\"xml-hsm-certum-enveloping.xml\", \"wb\").write(data)\n else:\n open(\"xml-hsm-certum-enveloping-t.xml\", \"wb\").write(data)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"examples/xml-hsm-certum-enveloping.py","file_name":"xml-hsm-certum-enveloping.py","file_ext":"py","file_size_in_byte":3454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"404523874","text":"#!/usr/bin/python\n\nimport socket\nimport sys\n\nfrom IPv4 import IPv4\nfrom TCP import TCP\nfrom HTTP import HTTP\nfrom struct import *\nfrom io import StringIO\n\nTAB_1 = '\\t '\nTAB_2 = '\\t\\t '\nTAB_3 = '\\t\\t\\t '\n\nHTTP_PORT = 80\nMAX_PORTS = 65535\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\ntry:\n # Create the socket\n s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(3))\nexcept error:\n print(bcolors.FAIL + 'Socket could not be created.' + bcolors.ENDC)\n sys.exit()\n\nwhile True:\n # Accept a tcp packet\n packet, addr = s.recvfrom(MAX_PORTS)\n\n raw_data = packet[14:]\n ipv4 = IPv4(raw_data)\n tcp = TCP(ipv4.data)\n\n if (len(tcp.data) > 0):\n # For checking HTTP data\n http = HTTP(tcp.data)\n if tcp.src_port == HTTP_PORT or tcp.dest_port == HTTP_PORT:\n print(bcolors.OKGREEN + TAB_1 + 'TCP Segment:' + bcolors.ENDC)\n print(bcolors.OKGREEN + TAB_2 + 'Source Addr: {} {}, \\n {}Destination Addr: {} {}'.format(TAB_2, ipv4.src, TAB_2, TAB_1, ipv4.target))\n print(bcolors.OKGREEN + TAB_2 + 'Source Port: {} {}, \\n {}Destination Port: {} {}'.format(TAB_2, tcp.src_port, TAB_2, TAB_1, tcp.dest_port) + bcolors.ENDC)\n print(bcolors.OKGREEN + TAB_2 + 'Sequence: {} {}, \\n {}Acknowledgment: {} {} \\n'.format(TAB_2, tcp.sequence, TAB_2, TAB_1, tcp.acknowledgment) + bcolors.ENDC)\n try:\n if isinstance(http.data, str):\n print(bcolors.HEADER + 'HTTP Data:' + bcolors.ENDC)\n buf = StringIO(http.data)\n print(buf.read())\n else:\n print(bcolors.HEADER + 'HTTP Data:' + bcolors.ENDC)\n buf = StringIO(http.data.decode('utf-8'))\n print(http.data)\n\n except Exception as e:\n print(bcolors.FAIL + str(e) + bcolors.ENDC)","sub_path":"Intercept.py","file_name":"Intercept.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"242390355","text":"import FWCore.ParameterSet.Config as cms\n\nL1HPSPFTauProducerPuppi = cms.EDProducer(\"L1HPSPFTauProducer\",\n srcL1PFCands = cms.InputTag(\"l1pfCandidates:Puppi\"), \n srcL1PFJets = cms.InputTag(\"ak4PFL1PuppiCorrected\"), \n #srcL1Vertices = cms.InputTag(\"VertexProducer:l1vertextdr\"),\n srcL1Vertices = cms.InputTag(\"L1TkPrimaryVertex\"),\n useChargedPFCandSeeds = cms.bool(True), \n min_seedChargedPFCand_pt = cms.double(5.),\n max_seedChargedPFCand_eta = cms.double(2.4),\n max_seedChargedPFCand_dz = cms.double(1.e+3),\n usePFJetSeeds = cms.bool(True), \n min_seedPFJet_pt = cms.double(30.),\n max_seedPFJet_eta = cms.double(2.4),\n signalConeSize = cms.string(\"2.8/max(1., pt)\"),\n min_signalConeSize = cms.double(0.05),\n max_signalConeSize = cms.double(0.10),\n useStrips = cms.bool(True), \n stripSize_eta = cms.double(0.05),\n stripSize_phi = cms.double(0.20),\n isolationConeSize = cms.double(0.4),\n min_PFTau_pt = cms.double(20.),\n max_PFTau_eta = cms.double(2.4), \n min_leadChargedPFCand_pt = cms.double(1.),\n max_leadChargedPFCand_eta = cms.double(2.4),\n max_leadChargedPFCand_dz = cms.double(1.e+3),\n max_chargedIso = cms.double(1.e+3),\n max_chargedRelIso = cms.double(1.0),\n srcRho = cms.InputTag('kt6L1PFJetsNeutralsPuppi:rho'),\n #inputFileName_rhoCorr = cms.string(\"L1Trigger/Phase2L1Taus/data/rhoCorr.root\"),\n #histogramName_rhoCorr = cms.string(\"RhoCorrAnalyzerPuppi/neutralPFCandPt_vs_absEta\"),\n inputFileName_rhoCorr = cms.string(\"\"),\n histogramName_rhoCorr = cms.string(\"\"), \n deltaR_cleaning = cms.double(0.4),\n signalQualityCuts = cms.PSet(\n chargedHadron = cms.PSet(\n min_pt = cms.double(0.),\n max_dz = cms.double(1.e+3), \n ),\n neutralHadron = cms.PSet(\n min_pt = cms.double(0.)\n ), \n muon = cms.PSet(\n min_pt = cms.double(0.),\n max_dz = cms.double(1.e+3), \n ),\n electron = cms.PSet(\n min_pt = cms.double(0.),\n max_dz = cms.double(1.e+3), \n ), \n photon = cms.PSet(\n min_pt = cms.double(0.)\n ) \n ),\n isolationQualityCuts = cms.PSet(\n chargedHadron = cms.PSet(\n min_pt = cms.double(0.),\n max_dz = cms.double(1.e+3), \n ),\n neutralHadron = cms.PSet(\n min_pt = cms.double(0.)\n ), \n muon = cms.PSet(\n min_pt = cms.double(0.),\n max_dz = cms.double(1.e+3), \n ),\n electron = cms.PSet(\n min_pt = cms.double(0.),\n max_dz = cms.double(1.e+3), \n ), \n photon = cms.PSet(\n min_pt = cms.double(0.)\n ) \n ),\n applyPreselection = cms.bool(False), \n debug = cms.untracked.bool(False) \n)\n","sub_path":"python/L1HPSPFTauProducerPuppi_cfi.py","file_name":"L1HPSPFTauProducerPuppi_cfi.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"134571725","text":"import logging\nimport re\nfrom urllib.parse import quote\nfrom github3 import login\nfrom ..client import client\nfrom ..commands import always_command\nfrom ..config import get_config\n\n\nlogger = logging.getLogger(__name__)\ngithub = login(token=get_config(\"github.login.token\"))\nrepo = github.repository(get_config(\"github.repo.owner\"), get_config(\"github.repo.name\"))\ntree = tree = repo.tree(repo.branch(get_config(\"github.repo.branch\")).commit.sha).recurse()\n\n# Taken from https://github.com/d3athrow/vgstation13/blob/Bleeding-Edge/bot/plugins/GitHub.py\nREG_PATH = re.compile(r\"\\[([a-zA-Z\\-_/][a-zA-Z0-9\\- _/]*\\.[a-zA-Z]+)(#L\\d+(?:-L\\d+)?)?\\]\", re.I)\nREG_ISSUE = re.compile(r\"\\[#?([0-9]+)\\]\")\n\n@always_command()\nasync def issue(message):\n for match in REG_ISSUE.finditer(message.content):\n id = int(match.group(1))\n if id < 1000:\n continue\n\n issue = repo.issue(id)\n\n await client.send_message(message.channel, issue.html_url)\n \n\n for match in REG_PATH.finditer(message.content):\n path = match.group(1).lower()\n logger.info(path)\n length = -len(path)\n for hash in tree.tree:\n logger.debug(hash.path)\n if hash.path.lower()[length:] == path:\n logger.info(repo.html_url)\n logger.info(get_config(\"github.repo.branch\"))\n logger.info(quote(hash.path))\n logger.info(match.group(2))\n url = \"%s/blob/%s/%s\" % (repo.html_url, get_config(\"github.repo.branch\"), quote(hash.path)) + (match.group(2) or \"\")\n await client.send_message(message.channel, url)\n break;\n\ndef update():\n global tree\n repo.refresh()\n\n tree = repo.tree(repo.branch(get_config(\"github.repo.branch\")).commit.sha)\n tree.recurse()\n","sub_path":"MoMMI/Modules/issues.py","file_name":"issues.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"139640505","text":"from django.urls import path\nfrom . import views\nfrom django.contrib.auth import views as auth_views\n\n\napp_name = 'core' # here for namespacing of urls.\n\nurlpatterns = [\n path(\"\", views.home_page, name=\"home\"),\n path(\"search/data=++\", views.search_info, name=\"search_info\"),\n path(\"establishments/data=\", views.search_establishment, name=\"search_establishment\"),\n path(\"all-establishments/\", views.all_establishments, name=\"all_establishments\"),\n path(\"establishments/departments/data=+\", views.search_department, name=\"search_department\"),\n path(\"establishments/all-departments/\", views.all_departments, name=\"all_departments\"),\n path(\"test\", views.test, name=\"test\"),\n]","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"121793880","text":"#Tic Tac Toe \nimport random\n\ndef draw_board(board):\n print(' | |')\n print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])\n print(' | |')\n print('----------------')\n print(' | |')\n print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])\n print(' | |')\n print('----------------')\n print(' | |')\n print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])\n print(' | |')\n\ndef input_player_letter():\n letter = ' '\n while not (letter == 'X' or letter == 'O'):\n print('Do you want to be \"X\" or \"O\"?')\n letter = input().upper()\n if letter == 'X':\n return ['X', 'O']\n else:\n return ['O', 'X']\n\ndef who_goes_first():\n # flip coin to know goes first\n if random.randint(0, 1) == 0:\n return 'computer'\n else:\n return 'player'\n\ndef play_again():\n #returns TRUE if the response start with 'y' otherwise return FALSE\n print('Do you want to play again? (yes or no)')\n return input().lower().startswith('y')\n\ndef make_move(board, letter, move):\n board[move] = letter\n\ndef is_winner(board, letter):\n return ((board[7] == letter and board[8] == letter and board[9] == letter) or # across the top\n (board[4] == letter and board[5] == letter and board[6] == letter) or # across the middletter\n (board[1] == letter and board[2] == letter and board[3] == letter) or # across the boardttom\n (board[7] == letter and board[4] == letter and board[1] == letter) or # down the letterft side\n (board[8] == letter and board[5] == letter and board[2] == letter) or # down the middletter\n (board[9] == letter and board[6] == letter and board[3] == letter) or # down the right side\n (board[7] == letter and board[5] == letter and board[3] == letter) or # diagonal\n (board[9] == letter and board[5] == letter and board[1] == letter)) # diagonal\n\ndef get_board_copy(board):\n duplicated_board = []\n for i in board:\n duplicated_board.append(i)\n\n return duplicated_board\n\ndef is_a_space_free(board, move):\n return board[move] == ' '\n\ndef get_player_move(board):\n move = ' '\n while move not in '1 2 3 4 5 6 7 8 9'.split() or not is_a_space_free(board, int(move)):\n print('What s your next move? (1-9)')\n move = input()\n return int(move)\n\ndef choose_random_move_from_list(board, moves_list):\n possible_moves = []\n for i in moves_list:\n if is_a_space_free(board, i):\n possible_moves.append(i)\n if len(possible_moves) != 0:\n return random.choice(possible_moves)\n else:\n return None\n\ndef get_computer_move(board, computer_letter):\n if computer_letter == 'X':\n player_letter = 'O'\n else:\n player_letter = 'X'\n\n for i in range(1, 10):\n copy = get_board_copy(board)\n if is_a_space_free(copy, i):\n make_move(copy, computer_letter, i)\n if is_winner(copy, computer_letter):\n return i\n\n for i in range(1, 10):\n copy = get_board_copy(board)\n if is_a_space_free(copy, i):\n make_move(copy, player_letter, i)\n if is_winner(copy, player_letter):\n return i\n\n move = choose_random_move_from_list(board, [1, 3, 7, 9])\n if move != None:\n return move\n if is_a_space_free(board, 5):\n return 5\n return choose_random_move_from_list(board, [2, 4, 6, 8])\n\ndef is_board_full(board):\n for i in range(1, 10):\n if is_a_space_free(board, i):\n return False\n return True\n\nprint('Welcome to Tic Tac Toe Game!')\n\nwhile True:\n the_board = [' '] * 10\n player_letter, computer_letter = input_player_letter()\n turn = who_goes_first()\n print('The ' + turn + ' will go first.')\n is_game_playing = True\n\n while is_game_playing:\n if turn == 'player':\n draw_board(the_board)\n move = get_player_move(the_board)\n make_move(the_board, player_letter, move)\n\n if is_winner(the_board, player_letter):\n draw_board(the_board)\n print('Hooray! You have won the game!')\n is_game_playing = False\n else:\n if is_board_full(the_board):\n draw_board(the_board)\n print('The game is a tie!')\n break\n else:\n turn = 'computer'\n else:\n # computer's turn\n move = get_computer_move(the_board, computer_letter)\n make_move(the_board, computer_letter, move)\n if is_winner(the_board, computer_letter):\n draw_board(the_board)\n print('The computer has beaten you! You lose.')\n is_game_playing = False\n else:\n if is_board_full(the_board):\n draw_board(the_board)\n print('The game is a tie!')\n break\n else:\n turn = 'player'\n if not play_again():\n break","sub_path":"tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":4583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"519902196","text":"\nimport unittest\n\nimport os\nimport json\n\nfrom ReviewsParser import ReviewsParser\n\n\nclass TestReviewsParser(unittest.TestCase):\n\t\n#\tdef setUp(self):\t\n#\tdef tearDown(self):\n\t\n\tdef test_reviews(self):\n\t\tparser = ReviewsParser(os.path.join(os.path.dirname(__file__), \"data\", \"reviews_1.xml\"))\n\t\treviews = parser.parse()\n\t\tself.assertIs(type(reviews), list);\n\t\t\n\t\tfo = open(os.path.join(os.path.dirname(__file__), \"data\", \"reviews_1.json\"))\n\t\treviewsJson = json.load(fo)\n\t\t\n\t\tself.assertEquals(len(reviewsJson), len(reviews));\n\t\t\n\t\ti = 0\n\t\tfor review in reviews:\n\t\t\tself.assertEquals(review.author, reviewsJson[i][\"author\"])\n\t\t\tself.assertEquals(review.title, reviewsJson[i][\"title\"])\n\t\t\tself.assertEquals(review.rating, reviewsJson[i][\"rating\"])\n\t\t\tself.assertEquals(review.version, reviewsJson[i][\"version\"])\n\t\t\tself.assertEquals(review.date.strftime(\"%d.%m.%Y\"), reviewsJson[i][\"date\"])\n\t\t\t\n\t\t\ti += 1\n\n\nif __name__ == '__main__':\n\tunittest.main()","sub_path":"tests/TestReviewsParser.py","file_name":"TestReviewsParser.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"224600829","text":"# Imporat\nimport sys, os\nproject_root = os.path.abspath(os.path.dirname(__file__) + \"../../\")\t# get absolute path of moving directory up two levels from current\nsys.path.append(project_root)\t# append new path in the path attribute of the sys module\nimport numpy as np\nimport pickle\nimport timeit\t# check performance\nfrom dataset.mnist import load_mnist\n\n# Global Variables\n\n# Classes\n\n# Functions\ndef sigmoid(x):\n\treturn 1 / (1 + np.exp(-x))\n\ndef softmax(a):\n\tc = np.max(a)\n\texp_a = np.exp(a - c)\n\tsum_exp_a = np.sum(exp_a)\n\ty = exp_a / sum_exp_a\n\treturn y\n\ndef get_data():\n\t(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, flatten=True, one_hot_label=False)\n\treturn x_test, t_test\n\ndef init_network():\n\twith open(\"sample_weight.pkl\", 'rb') as f:\n\t\tnetwork = pickle.load(f)\n\treturn network\n\ndef predict(network, x): \t# forward propagation\n\tW1, W2, W3 = network['W1'], network['W2'], network['W3']\t# weight\n\tb1, b2, b3 = network['b1'], network['b2'], network['b3']\t# bias\n\n\ta1 = np.dot(x, W1) + b1\n\tz1 = sigmoid(a1)\t# activation\n\ta2 = np.dot(z1, W2) + b2\n\tz2 = sigmoid(a2)\t# activation\n\ta3 = np.dot(z2, W3) + b3\n\ty = softmax(a3)\t\t# identity function\n\treturn y\n\ndef main():\n\tx, t = get_data()\n\tnetwork = init_network()\n\tbatch_size = 100\n\taccuracy_cnt = 0\n\n\tstart = timeit.default_timer()\t# check performance\n\tfor i in range(0, len(x), batch_size):\n\t\tx_batch = x[i:i+batch_size]\n\t\ty_batch = predict(network, x_batch)\n\t\tp = np.argmax(y_batch, axis=1)\n\t\taccuracy_cnt += np.sum(p == t[i:i+batch_size])\n\tstop = timeit.default_timer()\t# check performance\n\tprint(\"=============================\")\n\tprint(\"Total elapsed time: \" + str(stop - start) + \" seconds\")\n\tprint(\"Accuracy:\" + str(float(accuracy_cnt) / len(x)))\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"02.ann/mnist/mnist_batch.py","file_name":"mnist_batch.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"140470641","text":"#!/usr/bin/env python3\n\n#######################\n#\n# FireEye API\n#\n# Copyright (c) 2015 United States Government/National Institutes of Health\n# Author: Aaron Gee-Clough\n# Modifications from original made by: Adam Trask, Marcus LaFerrera\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n#####################\n\nimport re\nimport json\nimport demjson\nimport requests\nimport lxml.etree\n\n\nclass ApiVersion110(object):\n\n valid_durations = ('1_hour', '2_hours', '6_hours',\n '12_hours', '24_hours', '48_hours')\n\n valid_info_levels = ('concise', 'normal', 'extended')\n\n valid_report_durations = ('pastWeek', 'pastMonth',\n 'pastThreeMonths', 'rangeReport')\n\n valid_profiles = ('winxp-sp2', 'winxp-sp3', 'win7-sp1', 'win7x64-sp1')\n\n valid_content_types = ('application/json', 'application/xml')\n\n def __init__(self, ax_address, verifySSL=True, apiToken=None,\n clientToken=None, contentType='application/json'):\n self.base_url = 'https://{}/wsapis/v1.1.0'.format(ax_address)\n self.verify_SSL = verifySSL\n self.content_type = contentType\n self.api_token = apiToken\n self.client_token = clientToken\n\n def authenticate(self, username, password):\n\n headers = {}\n url = '{}/auth/login?'.format(self.base_url)\n\n if self.client_token:\n headers['X-FeClient-Token'] = self.client_token\n\n response = requests.post(url, auth=(username, password),\n headers=headers, verify=self.verify_SSL)\n\n if response.status_code == 200:\n self.api_token = response.headers['X-FeApi-Token']\n elif response.status_code == 400:\n raise Exception('Authentication Refused')\n elif response.status_code == 503:\n raise Exception('Web Services API server disabled')\n else:\n raise Exception('Unexpected response: {}'.format(response.text))\n\n return response\n\n def retrieve_alert(self, **kwargs):\n\n # Valid filters to be passed in kwargs\n valid_filter_params = ('alert_id',\n 'duration',\n 'info_level',\n 'file_name',\n 'file_type',\n 'url',\n 'md5',\n 'malware_name',\n 'malware_type',\n 'start_time',\n 'end_time')\n\n headers = {'X-FeApi-Token': self.api_token,\n 'Accept': self.content_type}\n\n url = '{}/alerts?'.format(self.base_url)\n\n for key, value in kwargs.items():\n if key in valid_filter_params:\n url = '{}&{}=\"{}\"'.format(url, key, value)\n\n if self.client_token:\n headers['X-FeClient-Token'] = self.client_token\n\n response = requests.get(url, headers=headers, verify=self.verify_SSL)\n\n if response.status_code == 200:\n pass\n elif response.status_code == 400:\n raise Exception('Filter value invalid')\n else:\n raise Exception('Unexpected response: {}'.format(response.text))\n\n return response\n\n def retrieve_report_by_reportID(self, reportID, formatPDF=False,\n reportType='alertDetailsReport'):\n\n headers = {'X-FeApi-Token': self.api_token,\n 'Accept': self.content_type}\n\n url = '{}/reports/report?report_type={}&id={}'.format(self.base_url,\n reportType,\n reportID)\n\n if self.client_token:\n headers['X-FeClient-Token'] = self.client_token\n\n if formatPDF:\n headers['Accept'] = 'application/pdf'\n\n response = requests.get(url, headers=headers, verify=self.verify_SSL)\n\n if response.status_code == 200:\n pass\n else:\n raise Exception('Unexpected response: {}'.format(response.text))\n\n return response\n\n def retrieve_report_by_infectionID(self, infectionID, formatPDF=False,\n infectionType='malware-object',\n reportType='alertDetailsReport'):\n\n headers = {'X-FeApi-Token': self.api_token,\n 'Accept': self.content_type}\n\n url = '{}/reports/report?report_type={}&infection_id={}&infection_type={}'\n url = url.format(self.base_url, reportType, infectionID, infectionType)\n\n if self.client_token:\n headers['X-FeClient-Token'] = self.client_token\n\n if formatPDF:\n headers['Accept'] = 'application/pdf'\n\n response = requests.get(url, headers=headers, verify=self.verify_SSL)\n\n if response.status_code == 200:\n pass\n else:\n raise Exception('Unexpected response: {}'.format(response.text))\n\n return response\n\n def query_configuration(self):\n\n headers = {'X-FeApi-Token': self.api_token,\n 'Accept': self.content_type}\n\n url = '{}/config'.format(self.base_url)\n\n if self.client_token:\n headers['X-FeClient-Token'] = self.client_token\n\n response = requests.get(url, headers=headers, verify=self.verify_SSL)\n\n if response.status_code == 200:\n pass\n elif response.status_code == 401:\n raise Exception('Invalid session token')\n else:\n raise Exception('Unexpected response: {}'.format(response.text))\n\n return response\n\n def submit_file(self, fileHandle, fileName,\n profiles=['win7-sp1'],\n analysisType='2',\n force='false',\n timeout='500',\n application='0',\n prefetch='1',\n priority='0'):\n\n headers = {'X-FeApi-Token': self.api_token,\n 'Accept': self.content_type}\n\n url = '{}/submissions'.format(self.base_url)\n\n rawData = {'application': str(application),\n 'timeout': str(timeout),\n 'priority': str(priority),\n 'profiles': profiles,\n 'analysistype': str(analysisType),\n 'force': str(force),\n 'prefetch': str(prefetch)}\n\n submissionData = ('', json.dumps(rawData), 'application/json')\n\n # Ensure file handle is at top of file\n fileHandle.seek(0)\n fileData = (fileName, fileHandle.read())\n\n files = {'options': submissionData,\n 'filename': fileData}\n\n response = requests.post(url, headers=headers, files=files,\n verify=self.verify_SSL)\n\n if response.status_code == 200:\n pass\n elif response.status_code == 400:\n raise Exception('Filter value invalid')\n else:\n raise Exception('Unexpected response: {}'.format(response.text))\n\n return response\n\n def submit_url(self, urls,\n profiles=['win7-sp1'],\n analysisType='2',\n force='false',\n timeout='500',\n application='0',\n prefetch='1',\n priority='0'):\n\n headers = {'X-FeApi-Token': self.api_token,\n 'Accept': self.content_type}\n\n url = '{}/submissions/url'.format(self.base_url)\n\n # Convert to list if urls are passed as tuple\n if isinstance(urls, tuple):\n urls = list(urls)\n\n # Lazy check for single url submissions\n # that are not in a list and then convert\n if not isinstance(urls, list):\n urls = [urls]\n\n rawData = {'urls': urls,\n 'application': str(application),\n 'timeout': str(timeout),\n 'priority': str(priority),\n 'profiles': profiles,\n 'analysistype': str(analysisType),\n 'force': str(force),\n 'prefetch': str(prefetch)}\n\n submissionData = ('', json.dumps(rawData), 'application/json')\n files = {'options': submissionData}\n\n response = requests.post(url, headers=headers, files=files,\n verify=self.verify_SSL)\n\n if response.status_code == 200:\n pass\n elif response.status_code == 400:\n raise Exception('Filter value invalid')\n elif response.status_code == 500:\n raise Exception('Server encountered issue, retry later')\n else:\n raise Exception('Unexpected response: {}'.format(response.text))\n\n return response\n\n def query_submission_status(self, submissionKey):\n\n headers = {'X-FeApi-Token': self.api_token,\n 'Accept': self.content_type}\n\n url = '{}/submissions/status/{}'.format(self.base_url,\n submissionKey)\n\n response = requests.get(url, headers=headers, verify=self.verify_SSL)\n\n if response.status_code == 200:\n pass\n elif response.status_code == 401:\n raise Exception('Invalid session token')\n elif response.status_code == 404:\n raise Exception('Invalid submission key')\n else:\n raise Exception('Unexpected response: {}'.format(response.text))\n\n return response\n\n def retrieve_submission_results(self, submissionKey, infoLevel='extended'):\n\n headers = {'X-FeApi-Token': self.api_token,\n 'Accept': self.content_type}\n\n url = '{}/submissions/results/{}'.format(self.base_url,\n submissionKey)\n\n if infoLevel and (infoLevel in self.valid_info_levels):\n url = '{}?info_level={}'.format(url, infoLevel)\n\n response = requests.get(url, headers=headers, verify=self.verify_SSL)\n\n if response.status_code == 200:\n pass\n elif response.status_code == 401:\n raise Exception('Invalid session token')\n elif response.status_code == 404:\n raise Exception('Invalid submission key')\n else:\n raise Exception('Unexpected response: {}'.format(response.text))\n\n return response\n\n def logout(self):\n\n headers = {'X-FeApi-Token': self.api_token,\n 'Accept': self.content_type}\n\n url = '{}/auth/logout'.format(self.base_url)\n\n response = requests.post(url, headers=headers, verify=self.verify_SSL)\n\n if response.status_code == 204:\n pass\n elif response.status_code == 304:\n raise Exception('Missing session token')\n else:\n raise Exception('Unexpected response: {}'.format(response.text))\n\n return response\n\n\nclass ResponseHandler(object):\n\n xml_namespaces = {'f': 'http://www.fireeye.com/alert/2011/AlertSchema'}\n valid_response_types = ('json', 'xml', 'text')\n\n def __init__(self, responseObject, responseType='json'):\n\n if responseType not in self.valid_response_types:\n raise Exception('Invalid response type specified')\n\n self.response_type = responseType\n\n # Check if responseObject is requests response object\n if isinstance(responseObject, requests.models.Response):\n # Process requests response object depending on specified type\n if responseType == 'json':\n try:\n self.response_object = responseObject.json()\n except ValueError:\n # Attempt to cleanup malformed or unwanted JSON elements\n # from FireEye and then use demjson to load the object\n cleanedObject = re.sub(r'\\n\\s+', '', responseObject.text)\n cleanedObject = re.sub(r'\\n', '', cleanedObject)\n cleanedObject = re.sub(r'(\\\"+)?N/A(\\\"+)?', '\\\"N/A\\\"', cleanedObject)\n self.response_object = demjson.decode(cleanedObject)\n except:\n message = 'JSON parsing error of response:\\n{}'\\\n .format(responseObject.text)\n raise Exception(message)\n elif responseType == 'xml':\n self.response_object = lxml.etree.fromstring(responseObject.content)\n elif responseType == 'text':\n self.response_object = responseObject.text\n else: # placeholder for future types\n self.response_object = responseObject.text\n else:\n self.response_object = responseObject\n\n def find_md5(self):\n\n if self.response_type == 'json':\n return self._findMd5JSON()\n elif self.response_type == 'xml':\n return self._findMd5XML()\n else:\n raise Exception('Invalid response type for find md5 method')\n\n def _findMd5JSON(self):\n malwareSection = self._findMalwareSectionJSON()\n md5_values = self._lookForKeyInJsonList(malwareSection, 'md5sum')\n return md5_values\n\n def _findMd5XML(self):\n\n try:\n xpath_value = '/notification/malware/analyis/md5sum/'\n md5_entries = self.response_object.xpath(xpath_value)\n except lxml.etree.XPathEvalError:\n xpath_value = '/f:alerts/f:alert/f:explanation/f:malware-detected/f:malware/f:md5sum'\n md5_entries = self.response_object.xpath(xpath_value, namespaces=self.xml_namespaces)\n except:\n md5_entries = []\n\n md5_values = [md5.text for md5 in md5_entries]\n\n return md5_values\n\n def find_profiles(self):\n\n if self.response_type == 'json':\n return self._findProfilesJSON()\n elif self.response_type == 'xml':\n return self._findProfilesXML()\n else:\n raise Exception('Invalid response type for find profiles method')\n\n def _findProfilesJSON(self):\n malwareSection = self._findMalwareSectionJSON()\n profile_values = self._lookForKeyInJsonList(malwareSection, 'profile')\n return profile_values\n\n def _findProfilesXML(self):\n\n try:\n xpath_value = '/notification/malware/analysis/profile/name'\n profile_entries = self.response_object.xpath(xpath_value)\n except lxml.etree.XPathEvalError:\n xpath_value = '/f:alerts/f:alert/f:explanation/f:malware-detected/f:malware/f:profile'\n profile_entries = self.response_object.xpath(xpath_value, namespaces=self.xml_namespaces)\n except:\n profile_entries = []\n\n profile_values = [profile.text for profile in profile_entries]\n\n return profile_values\n\n def find_malware_section(self):\n\n if self.response_type == 'json':\n return self._findMalwareSectionJSON()\n elif self.response_type == 'xml':\n return self._findMalwareSectionXML()\n else:\n raise Exception('Invalid response type for find malware section method')\n\n def _findMalwareSectionJSON(self):\n\n malware_sections = []\n\n alerts = self._lookForListOrDict(self.response_object, 'alert')\n\n for alert in alerts:\n explanations = self._lookForListOrDict(alert, 'explanation')\n\n for explanation in explanations:\n malwareDetections = self._lookForListOrDict(explanation,\n 'malware-detected')\n for malwareDetected in malwareDetections:\n malware_sections.extend(self._lookForListOrDict(malwareDetected,\n 'malware'))\n\n return malware_sections\n\n def _findMalwareSectionXML(self):\n\n try:\n xpath_value = '/notification/malware/analysis'\n malware_entries = self.response_object.xpath(xpath_value)\n except lxml.etree.XPathEvalError:\n xpath_value = '/f:alerts/f:alert/f:explanation/f:malware-detected/f:malware'\n malware_entries = self.response_object.xpath(xpath_value, namespaces=self.xml_namespaces)\n except:\n malware_entries = []\n\n malware_sections = [section.text for section in malware_entries]\n\n return malware_sections\n\n def _lookForListOrDict(self, subDict, targetName):\n\n returnData = []\n\n if targetName in subDict and subDict[targetName]:\n if isinstance(subDict[targetName], dict):\n returnData = [subDict[targetName]]\n else:\n returnData = subDict[targetName]\n\n return returnData\n\n def _lookForKeyInJsonList(self, targetList, targetKey):\n\n returnData = []\n\n for entry in targetList:\n if (targetKey in entry) and (entry[targetKey] != \"\"):\n returnData.append(entry[targetKey])\n\n return returnData\n\n def format_JSON(self):\n\n formattedObject = {}\n\n # Traversal logic:\n # http://nvie.com/posts/modifying-deeply-nested-structures/\n def traverse(obj):\n if isinstance(obj, dict):\n return {k: traverse(v) for k, v in obj.items()}\n elif isinstance(obj, list):\n return [traverse(elem) for elem in obj]\n else:\n return obj # no container, just values (str, int, float)\n\n if self.response_type != 'json':\n raise Exception('Invalid response object type for format JSON method')\n\n for key, value in self.response_object.items():\n formattedObject[key] = traverse(value)\n\n return formattedObject\n","sub_path":"worker/fireeye/fireeye/FireEyeMAS.py","file_name":"FireEyeMAS.py","file_ext":"py","file_size_in_byte":18812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"248143915","text":"from __future__ import division\nimport paho.mqtt.client as mqtt\nimport pandas as pd\nimport numpy as np\nfrom pylab import rcParams\nimport simpy\nimport random\nimport statistics\nimport pandas as pd\nimport numpy as np\nimport json\nimport matplotlib.pyplot as plt\nimport pickle\nimport math\n\nbroker_url = \"localhost\"\nbroker_port = 1883\n\nclient = mqtt.Client()\nclient.connect(broker_url, broker_port)\n\ncontrollables = ['CDE', 'CWE', 'DWE', 'FGE', 'FRE', 'HPE', 'HTE']\nstate_connected = ['FGE', 'FRE', 'HPE', 'HTE']\nload_data = pickle.load( open( \"../data/ampds.p\", \"rb\" ) )\n\ndef get_rands_from_data(inputdata, num):\n\n #print(inputdata)\n data = inputdata.fillna(0)\n hist, bins = np.histogram(data, bins=50)\n\n bin_midpoints = bins[:-1] + np.diff(bins)/2\n cdf = np.cumsum(hist)\n cdf = cdf / cdf[-1]\n values = np.random.rand(num)\n value_bins = np.searchsorted(cdf, values)\n random_from_cdf = bin_midpoints[value_bins]\n\n return random_from_cdf\n\n#TODO add some sophistication so that it's time-based\ndef get_distrs_from_ds(time):\n global load_distrs\n distrs = []\n for l in load_distrs:\n distrs.append(l[time:time+60])\n \n return distrs\n\n# - is_controllable\n# - state_connection\n# - time_triggers\n#add sophistication for the special keys\ndef init_info(ds ,isDefault):\n infos = []\n controllables = ['CDE', 'CWE', 'DWE', 'FGE', 'FRE', 'HPE', 'HTE']\n state_connected = ['FGE', 'FRE', 'HPE', 'HTE']\n for key in ds.keys():\n if \"INFO\" not in key:\n tmp = ds[key+\"_INFO\"]\n if isDefault:\n tmp['is_controllable']= key in controllables\n tmp['state_connection'] = [0.0, 0.0]\n if key in state_connected:\n tmp['state_connection'] = [0.01, -0.1]\n infos.append(tmp)\n return infos\n\nclass Meter(object):\n\n load_distros = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,]\n load_infos = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,]\n\n #structure of load infos - \n # - is_controllable\n # - state_connection\n #consumption of power by appliances on time step\n\n loads = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,]\n states = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,]\n state_targets = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,]\n\n net_load = 0\n #power_thresh = 200\n \n def __init__(self, json_path):\n #params = json.load(open(json_path))\n \"\"\n\nclass House(object):\n \n controls = [False,False,False,False,False,False,False,False,False,False,False,False,False]\n \n meter = Meter('house_params.json')\n \n \n def __init__(self, json_path):\n self.meter.meter = Meter(json_path)\n\n def get_state(self):\n data = {}\n data['controls'] = self.controls\n data['loads'] = self.meter.loads\n return data\n\n\n def update_state(self):\n infos = self.meter.load_infos\n for i in range(0, len(infos)):\n #state connection is in format [effect when on, effect when off], 2 numbers\n #TODO add in state initialization\n if infos[i]['state_connection'][0]>0 and self.controls[i]:\n self.meter.states[i]+=infos[i]['state_connection'][0]\n else :\n self.meter.states[i]+=infos[i]['state_connection'][1]\n\n def update_loads(self):\n load=0 \n infos = self.meter.load_infos\n for i in range(0, len(infos)):\n if self.controls[i]:\n tmp = get_rands_from_data(self.meter.load_distros[i], 1)[0]\n if len(self.meter.loads)==i:\n self.meter.loads.append(0)\n self.meter.loads[i]= tmp\n\n\n #critical loads can be treated as 1 in this scenario \n def get_critical_load(self):\n infos = self.meter.load_infos\n crit_load = 0\n for i in range(0, len(infos)):\n if infos[i]['is_controllable'] == False:\n crit_load+=self.meter.loads[i]\n self.controls[i] = True\n return crit_load\n \n def get_control_loads(self):\n infos = self.meter.load_infos\n load = 0\n for i in range(0, len(infos)):\n if infos[i]['is_controllable']:\n load+=self.meter.loads[i]\n\n return load\n\n \n #important to call these 3 at least once before running simulation\n def set_load_distros(self, distros):\n self.meter.load_distros = distros\n\n #performs all functions for a typical iteration\n def run_load(self):\n #print(\"Next\")\n self.meter.net_load = 0\n self.update_loads()\n self.meter.net_load+=self.get_critical_load()\n self.meter.net_load+=self.get_control_loads()\n #print(self.meter.load_distros)\n self.update_state()\n #print(self.meter.load_infos)\n #print(\"LOAD IS\"+str(self.meter.net_load))\n return self.meter.net_load\n\n def set_infos(self, infs):\n self.meter.load_infos = infs\n for i in range(0, len(infs)):\n self.controls.append(not infs[i]['is_controllable'])\n\ntotal_load = 0\ntimestep = 0\nnum_houses = 4\nhouses = []\nload_distrs = []\n\nfor key in load_data.keys():\n if \"INFO\" not in key:\n load_distrs.append(load_data[key]['apparent'])\n\ninfos = init_info(load_data, True)\ndistrs = get_distrs_from_ds(0)\n\n\n\nfor i in range(0, num_houses):\n h = House('house_params.json')\n h.set_load_distros(distrs)\n #h.meter.infos = infos\n h.set_infos(infos)\n houses.append(h)\n\n \ndef on_timer_advance(client, userdata, message):\n newdata = int(message.payload.decode())\n\n global timestep\n global houses\n data = {}\n tmp = {}\n \n timestep = newdata\n print(str(timestep))\n\n i = 0\n reset_distrs = False\n tmp_distrs = []\n if timestep%60==0:\n reset_distrs=True\n tmp_distrs = get_distrs_from_ds(timestep)\n\n for h in houses:\n tmp = h.get_state()\n print(\"LOAD - \"+str(i))\n tmp['total'] = h.run_load()\n tmp['timestep'] = timestep\n tmp['id'] = i\n tmp['total'] = str(tmp['total'])\n tmp['loads'] = json.dumps(np.array(tmp['loads']).tolist())\n if reset_distrs:\n h.set_load_distros(tmp_distrs)\n\n i+=1\n print(tmp)\n client.publish(topic=\"load-\"+str(i), payload=json.dumps(tmp), qos=1, retain=False)\n\n data['timestep'] = timestep\n data['finished'] = True\n print(json.dumps(data))\n client.publish(topic=\"loads\", payload=json.dumps(data), qos=1, retain=False)\n\ndef on_control_received(client, userdata, message):\n newdata = json.loads(message.payload.decode())\n\n global houses\n load_id = newdata['id']\n houses[i] = newdata['control']\n\n\nclient.subscribe(\"timestep\", qos=1)\n\nfor i in range(0, num_houses):\n client.subscribe(\"control-\"+str(i), qos=1)\n client.message_callback_add(\"control\"+str(i), on_control_received)\nclient.message_callback_add(\"timestep\", on_timer_advance)\n\nclient.loop_forever()","sub_path":"pubsub/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":6974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"425010711","text":"import arcade\n\n\ndef main() -> None:\n \"\"\"Processes inputs.\"\"\"\n with open('input', 'r') as f:\n interpreter = arcade.Game(\n f.read().strip().split(','),\n silent=True\n )\n interpreter.insert_quarters()\n interpreter.run_ops()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"2019/13/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"528861425","text":"from utils import *\n\ntopic_names=['value for money','garage service', 'mobile fitter', \n 'change of date', 'wait time', 'delivery punctuality',\n 'ease of booking' , 'location', 'booking confusion' , 'tyre quality' ,\n 'length of fitting' , 'discounts']\n\n\n\ndef get_inference_from_supervised(text,model,max_len,tokenizer,encode): \n \n print(\"\\n Inference and Results from Supervised model Inference : \\n\")\n new_text = [clean_text(text)]\n print(text)\n print(new_text)\n seq = tokenizer.texts_to_sequences(new_text)\n padded = pad_sequences(seq, maxlen=max_len, padding=padding_type, truncating=trunc_type)\n pred = model.predict(padded)\n acc = model.predict_proba(padded)\n a=acc[0]\n idx=heapq.nlargest(3,range(len(a)),a.take)\n n_cat=topic_names[idx[0]],topic_names[idx[1]],topic_names[idx[2]]\n predicted_label = encode.inverse_transform(pred)\n print('')\n \n print(f'Best Predicted Topic is: {predicted_label[0]}')\n print(\"Top 3 Topic Categories : \", n_cat)\n\n return n_cat\n\n\ndef get_inference_from_unsupervised_model(model, vectorizer, text, threshold):\n v_text = vectorizer.transform([text])\n score = model.transform(v_text)\n\n labels = set()\n \n for i in range(len(score[0])):\n if score[0][i] > threshold:\n labels.add(topic_names[i])\n \n a=np.array(score[0])\n idx=heapq.nlargest(3,range(len(a)),a.take)\n n_cat=topic_names[idx[0]],topic_names[idx[1]],topic_names[idx[2]]\n \n if not labels:\n return 'None', -1, set()\n\n print(\"Inference and Results from Unsupervised model Inference : \\n\")\n print(\"Best Predicted Topic is : \",topic_names[np.argmax(score)])\n print(\"Top 3 Topic Categories : \",n_cat)\n \n return topic_names[np.argmax(score)], score, labels,idx,n_cat\n","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"358193421","text":"def quicksort(lista):\r\n if lista == []:\r\n return []\r\n else:\r\n \r\n pivote = lista[0]\r\n\r\n menor, igual, mayor = ordenar1(lista[1:],[],[pivote],[])\r\n\r\n return quicksort(menor) + igual + quicksort(mayor)\r\n\r\ndef ordenar1(lista,menor,igual,mayor):\r\n if lista == []:\r\n return (menor,igual,mayor)\r\n else:\r\n cabeza = lista[0]\r\n if cabeza < igual[0]:\r\n return ordenar1(lista[1:], menor + [cabeza] , igual, mayor)\r\n elif cabeza > igual[0]:\r\n return ordenar1(lista[1:], menor, igual, mayor + [cabeza])\r\n else:\r\n return ordenar1(lista[1:], menor, igual + [cabeza], mayor)\r\n\r\nlista=[6,-1,56,3,3,32,2,3]\r\n\r\nprint(quicksort(lista))\r\n","sub_path":"Asignaciones/Recursividad, Listas y arboles/Quicksort.py","file_name":"Quicksort.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"175089308","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 24 14:18:59 2019\n\n@author: wkosater\n\"\"\"\n\nfrom Bio.PDB import *\nimport pandas as pd\nimport random\nimport pdb\npd.options.mode.chained_assignment = None \n\ntest2_test_tables = []\ncounter = 0\n\"\"\"Step 1: Generate new deterministic substitutions\"\"\" \nwhile counter < len(test1_table):\n \n #Find the highest and lowest SASA values (highest = surface, and lowest = core) \n highest_SASA = test1_table[counter]['SASA'].idxmax()\n minimum_SASA = test1_table[counter]['SASA'].idxmin()\n \n #Returns position of highest SASA residue\n highest_SASA_index = int(test1_table[counter][2][highest_SASA]) \n lowest_SASA_index = int(test1_table[counter][2][minimum_SASA])\n \n temp_table = test1_table[counter]\n z=[]\n temp_table = temp_table.rename(columns={'T/F':'TF'})\n temp_table = temp_table.rename(columns={2:'index'})\n \n #Substitutions applied \n if temp_table['TF'][highest_SASA] == False:\n temp_table['TF'][highest_SASA] = True\n #Apply sub to all position with index = highest_SASA_index\n temp_table.loc[temp_table['index'].str.strip() == str(highest_SASA_index), 'TF'] = True\n print(\"Surface subs applied\")\n else:\n print(\"Surface subs already true\")\n \n \n if temp_table['TF'][minimum_SASA] == False:\n temp_table['TF'][minimum_SASA] = True\n #Apply sub to all position with index= lowest_SASA_index\n temp_table.loc[temp_table['index'].str.strip() == str(lowest_SASA_index), 'TF'] = True\n print(\"Core subs applied\")\n else:\n print(\"Core subs already true\")\n \n counter += 1\n test2_test_tables.append(temp_table)\n \n\"\"\"Step 2: Generate probabilities of substitution based on\ndistance, substitutions (taken from test1.py)\"\"\"\n\ntable_counter = 0 \n\n\ntest2_table = []\n\nwhile table_counter < len(test2_test_tables): #(1000)\n position_counter = 0\n d = []\n s = []\n indices = []\n subs_round_2_test2 = [] \n \n \n while position_counter < len(corrected_SASA): #(461)\n x = test2_test_tables[table_counter].loc[test2_test_tables[table_counter][1].eq(position_counter),[0,'TF']]\n tflist = x['TF'].to_list()\n possible_sub = True in tflist #Are there substitutions around the center?\n \n if possible_sub == True:\n x = x.drop(x[x['TF']==False].index) #Drop all non-substituted (False) residues \n d.append(min(x[0])) #Takes closest sub distance (maybe reassess the biological basis behind this) \n indices.append(min(x[0].index.values))\n s.append(corrected_SASA[position_counter])\n position_counter += 1\n \n elif possible_sub == False:\n position_counter += 1\n \n \n d = [float(i) for i in d] #Convert d into list of floats\n\n probabilities = []\n\n for sasa, distance in zip(s, d): #Calculation of probabilities based on formula\n probabilities.append(sasa+(1/distance**x1) - (sasa*(1/distance**x1)))\n \n probabilities = [p*100 for p in probabilities]\n \n \n \n p_index = 0\n while p_index < len(probabilities): \n if random.randint(0,100) < p:\n subs_round_2_test2.append(True)\n else:\n subs_round_2_test2.append(False)\n p_index += 1\n \n subs_round_2_test2 = pd.DataFrame(subs_round_2_test2)\n subs_round_2_test2['index'] = indices\n integers = [*range(0,len(subs_round_2_test2[0]))]\n subs_round_2_test2['integers'] = integers\n \n \n test2_test_tables_temp = pd.DataFrame(test2_test_tables[table_counter])\n #Now to assign the new True/False to the DataFrame\n \n i = 0\n #for i in subs_round_2_test2['index']:\n \"\"\"test2_test_tables_temp.set_value(subs_round_2_test2['index'][i], 'T/F', \n subs_round_2_test2[0][i])\"\"\"\n \n while i < len(subs_round_2_test2['integers']):\n test2_test_tables_temp.at[i,'TF'] = subs_round_2_test2[0][i]\n i += 1\n \n test2_test_tables_temp = test2_test_tables_temp.dropna() #Drop any instance of NaN\n position_list = test2_test_tables_temp[1].to_list()\n position_list = [int(p) for p in position_list]\n\n test2_table.append(test2_test_tables_temp) #List of tables for analysis\n \n table_counter += 1\n \n print(table_counter)\n \nprint(\"Test 1 and 2 finished. Now running statistical analysis\") \nexec(open(\"stats_and_vis_test1.py\").read()) ","sub_path":"test2(2).py","file_name":"test2(2).py","file_ext":"py","file_size_in_byte":4530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"588724291","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 28 21:09:48 2020\n\n@author: qtckp\n\"\"\"\n\nimport sys\nsys.path.append('..')\n\n\nimport numpy as np\nfrom geneticalgorithm2 import geneticalgorithm2 as ga\n\n\nsubset_size = 20 # how many objects we can choose\n\nobjects_count = 100 # how many objects are in set\n\nmy_set = np.random.random(objects_count)*10 - 5 # set values\n\n# minimized function\ndef f(X):\n return abs(np.mean(my_set[X==1]) - np.median(my_set[X==1]))\n\n# initialize start generation and params\n\nN = 1000 # size of population\nstart_generation = np.zeros((N, objects_count))\nindexes = np.arange(0, objects_count, dtype = np.int8) # indexes of variables\n\nfor i in range(N):\n inds = np.random.choice(indexes, subset_size, replace = False)\n start_generation[i, inds] = 1 \n\n\ndef my_crossover(parent_a, parent_b):\n a_indexes = set(indexes[parent_a == 1])\n b_indexes = set(indexes[parent_b == 1])\n \n intersect = a_indexes.intersection(b_indexes) # elements in both parents\n a_only = a_indexes - intersect # elements only in 'a' parent\n b_only = b_indexes - intersect\n \n child_inds = np.array(list(a_only) + list(b_only), dtype = np.int8)\n np.random.shuffle(child_inds) # mix\n \n childs = np.zeros((2, parent_a.size))\n if intersect:\n childs[:, np.array(list(intersect))] = 1\n childs[0, child_inds[:int(child_inds.size/2)]] = 1\n childs[1, child_inds[int(child_inds.size/2):]] = 1\n \n return childs[0,:], childs[1,:]\n \n\nmodel = ga(function=f, \n dimension=objects_count, \n variable_type='bool',\n algorithm_parameters={\n 'max_num_iteration': 500,\n 'mutation_probability': 0, # no mutation, just crossover\n 'elit_ratio': 0.05,\n 'crossover_probability': 0.5,\n 'parents_portion': 0.3,\n 'crossover_type': my_crossover,\n 'max_iteration_without_improv': 20\n }\n )\n\nmodel.run(no_plot = False, start_generation={'variables': start_generation, 'scores': None})","sub_path":"tests/best_subset.py","file_name":"best_subset.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"194613109","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 30 22:17:41 2020\n\n@author: eric\n\"\"\"\n\nimport pygame\nimport pdb\nimport random\nimport numpy as np\nimport time as tm\nimport thorpy\n\nSCREEN_WIDTH = 900\nSCREEN_HEIGHT = 700\nPLAYCREEN_HEIGHT = SCREEN_HEIGHT-100\n\nfrom pygame.locals import (\n RLEACCEL,\n MOUSEBUTTONDOWN,\n MOUSEBUTTONUP,\n QUIT,\n)\n\n\n#Classess:\nclass Ball(pygame.sprite.Sprite):\n \n def __init__(self, coords, veldir,speed, nbr, radius):\n super(Ball,self).__init__()\n \n \n #self.radius = random.randint(10,40) \n self.radius = radius\n self.mass = self.radius**2 \n self.surf = pygame.Surface([2*self.radius,2*self.radius])\n self.surf.fill([255,255,255])\n #self.surf.set_colorkey([255,255,255], RLEACCEL) #Masks the white color. #which color is transparent. RLEACCEL optional, faster rendering on non-acclerated displays\n self.surf.set_colorkey([255,255,255])\n \n self.rect = self.surf.get_rect(center = coords)\n self.coords = coords #This one refers to top left point of surf! (even when I used center above...) \n \n# self.speed = random.randint(5,15)\n# theta = random.uniform(0,np.pi*2) \n# self.veldir = np.array([np.cos(theta), np.sin(theta)]) \n\n self.speed = speed \n self.veldir = veldir \n\n self.nbr = nbr\n \n def update(self, d):\n\n if self.speed < 0.5:\n self.speed = 0\n \n vel = self.speed*self.veldir\n self.coords = self.coords + vel\n self.rect.move_ip([ int(np.round(self.coords[0]-self.rect.x)),int(np.round(self.coords[1]-self.rect.y) ) ])\n\n hitwall = False\n\n if self.coords[0] < 0:\n self.veldir[0] = np.abs(self.veldir[0])\n hitwall = True\n \n \n if self.coords[0]+self.radius*2 >= SCREEN_WIDTH:\n self.veldir[0] = -np.abs(self.veldir[0])\n hitwall = True\n \n if self.coords[1] < 0:\n self.veldir[1] = np.abs(self.veldir[1])\n hitwall = True\n \n if self.coords[1]+self.radius*2 >= PLAYCREEN_HEIGHT:\n self.veldir[1] = -np.abs(self.veldir[1])\n hitwall = True\n\n\n if hitwall:\n self.speed = self.speed*self.mass**(-1/d)\n \n self.surf.fill([255,255,255]) \n pygame.draw.circle(self.surf, [0,0,255],[self.radius,self.radius], self.radius)\n\n\n#Function which computes the new velocities of two balls after collision\n#Not to self, should be possible to generalize if multiple collisions occurs simultanously.\ndef collision(ball1, ball2,d):\n \n #Find collision vector, defined from center of ball2 to collision point\n\n coll_dir = (ball2.coords-ball1.coords) + [ball2.radius-ball1.radius,ball2.radius-ball1.radius] #Need to add this part to get to center of ball\n coll_dir = coll_dir/(np.sqrt(coll_dir[0]**2+coll_dir[1]**2)) \n \n #Solve second degree equation to compute magnitude of collision force\n v1 = ball1.speed*ball1.veldir\n v2 = ball2.speed*ball2.veldir\n\n relv = v2-v1\n speed_relv = np.sqrt(relv[0]**2+relv[1]**2)\n \n m1 = ball1.mass\n m2 = ball2.mass\n \n di = d*(m1+m2)*speed_relv*8/(m1*m2*(m1+m2))\n \n sp1 = v1[0]*coll_dir[0]+v1[1]*coll_dir[1]\n sp2 = -v2[0]*coll_dir[0]-v2[1]*coll_dir[1]\n \n p = 2/(m1+m2)*(sp1 + sp2)\n \n if di > p**2: #To prevent complex roots. What does complex roots imply?\n di = (1-1e-6)*p**2\n# pdb.set_trace()\n \n k1 = -p/2 + 0.5*np.sqrt(p**2-di)\n k2 = -p/2 - 0.5*np.sqrt(p**2-di)\n\n if p < 0.0:\n k = k1 \n else:\n k = k2\n \n \n v1_new = v1+k*m2*coll_dir\n v2_new = v2-k*m1*coll_dir\n \n ball1.speed = np.sqrt(v1_new[0]**2 + v1_new[1]**2 ) \n ball2.speed = np.sqrt(v2_new[0]**2 + v2_new[1]**2 )\n \n ball1.veldir = v1_new/ball1.speed\n ball2.veldir = v2_new/ball2.speed \n \n# print(p)\n# print(k1)\n# print(k2)\n# print(k)\n \n#Main game:\n\npygame.init()\nscreen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])\n#screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)\npygame.display.set_caption('Ball Game')\n\nballs = pygame.sprite.Group()\nclock = pygame.time.Clock()\n\n\n\nmaxMass = 75\nminMass = 10\n\nmassSlider = thorpy.SliderX(maxMass-minMass, [minMass,maxMass], 'Mass slider ', type_=int)\nmassSlider.set_font_size(14)\nquitButton = thorpy.make_button('Quit', func = thorpy.functions.quit_func)\nquitButton.set_font_size(14)\nbox = thorpy.Box(elements=[massSlider,quitButton])\n\nbox.set_main_color([255,255,255])\nbox_xsize = 100\nbox_ysize = 5\nbox.enlarge([box_xsize,box_ysize])\nmenu = thorpy.Menu(box)\n\nfor element in menu.get_population():\n element.surface = screen\n \nbox.set_topleft([SCREEN_WIDTH/2-box_xsize,SCREEN_HEIGHT-(SCREEN_HEIGHT-PLAYCREEN_HEIGHT)+box_ysize])\n\n\nthorpy.store(box, mode='h', align='bottom', gap=25)\n\n\n\nrunning = True\n\ncoll_dissipation = 100\nwall_disspation_factor = 20\nnbr = 0\n\ncoll_prevframe = [] #list of integers keeping track if balls were colliding in previous frame or not.\nmousedown = False\nspeed_init = 1\n\nscreen.fill([255,255,255]) \npygame.draw.line(screen, [0,0,0], [0,PLAYCREEN_HEIGHT], [SCREEN_WIDTH,PLAYCREEN_HEIGHT],2)\nbox.blit()\n#box.update()\n\nwhile running:\n \n screen.fill([255,255,255]) \n pygame.draw.line(screen, [0,0,0], [0,PLAYCREEN_HEIGHT], [SCREEN_WIDTH,PLAYCREEN_HEIGHT],2)\n box.blit()\n #box.update() #This line is not needed for this program\n\n \n for event in pygame.event.get():\n \n if event.type == QUIT:\n running = False\n \n elif event.type == MOUSEBUTTONDOWN and mousedown == False:\n coords = np.array(pygame.mouse.get_pos())\n \n if coords[1] < PLAYCREEN_HEIGHT:\n mousedown = True\n \n if event.type == MOUSEBUTTONUP and mousedown == True:\n \n new_ball = Ball(coords,veldir_init_ball,speed_init_ball, nbr,radius)\n balls.add(new_ball)\n nbr +=1\n mousedown = False\n \n \n menu.react(event)\n\n if mousedown == True:\n radius = massSlider.get_value()\n pygame.draw.circle(screen, [0,0,255], coords, radius)\n \n mousepos = np.array(pygame.mouse.get_pos())\n \n if mousepos[0] != coords[0] and mousepos[1] != coords[1]:\n \n veldir_init = mousepos-coords\n speed_init = np.sqrt(veldir_init[0]**2+veldir_init[1]**2)\n \n if speed_init < 100:\n pygame.draw.line(screen, [0,0,0], coords, mousepos,2)\n mousepos_old = mousepos\n #pygame.draw.circle(screen, [0,0,0], coords, speed_init, width=1)\n else:\n pygame.draw.line(screen, [0,0,0], coords, mousepos_old,2)\n veldir_init = mousepos_old-coords\n\n speed_init = np.sqrt(veldir_init[0]**2+veldir_init[1]**2)\n \n veldir_init_ball = veldir_init/speed_init\n speed_init_ball = speed_init/4\n \n if speed_init_ball < 4:\n speed_init_ball = 0\n \n \n other_balls = balls.copy()\n \n totK = 0\n \n for ball in balls:\n screen.blit(ball.surf,ball.rect)\n \n if len(other_balls) > 1:\n \n other_balls.remove(ball)\n \n for other_ball in other_balls:\n i = ball.nbr\n j = other_ball.nbr\n \n if pygame.sprite.collide_circle(ball,other_ball): #Can not use groups with this one? \n if ([i,j] or [j,i] ) not in coll_prevframe: \n collision(ball,other_ball,coll_dissipation) \n coll_prevframe.append([i,j])\n coll_prevframe.append([j,i]) #Might be redundant. Not sure if it improves collision detection\n \n\n else:\n if [i,j] in coll_prevframe:\n coll_prevframe.remove([i,j])\n coll_prevframe.remove([j,i])\n \n totK += 0.5*ball.mass*ball.speed**2\n \n \n #print(totK)\n \n balls.update(wall_disspation_factor)\n pygame.display.flip()\n #menu.blit_and_update()\n clock.tick(40)\n \npygame.quit()","sub_path":"BallGame6.py","file_name":"BallGame6.py","file_ext":"py","file_size_in_byte":8463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"381931714","text":"from django.shortcuts import render , redirect\nfrom courses.models import Course , Video\nfrom django.shortcuts import HttpResponse\nfrom django.contrib.auth import logout\nfrom courses.forms import RegistrationForm , LoginForm\nfrom django.views import View\n\n\nclass SignupView(View):\n def get(self , request):\n form = RegistrationForm()\n print(\"Respinse form Class Based\")\n return render(request , \n template_name=\"courses/signup.html\" , context= { 'form' : form } ) \n \n def post(self , request):\n form = RegistrationForm(request.POST)\n if(form.is_valid()):\n user = form.save()\n if(user is not None):\n return redirect('login')\n return render(request , \n template_name=\"courses/signup.html\" , context= { 'form' : form } )\n \n\nclass LoginView(View):\n def get(self , request):\n form = LoginForm()\n context = {\n \"form\" : form\n }\n return render(request , \n template_name=\"courses/login.html\" , context=context ) \n\n def post(self , request):\n form = LoginForm(request = request , data=request.POST)\n context = {\n \"form\" : form\n }\n if(form.is_valid()):\n return redirect(\"home\")\n return render(request , \n template_name=\"courses/login.html\" , context=context ) \n\n\n\ndef signout(request ):\n logout(request)\n return redirect(\"home\")","sub_path":"courses/views/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"62198000","text":"import pytest\n\nfrom pandas.util.testing import assert_frame_equal\n\nfrom .context import gtfstk, HAS_GEOPANDAS, DATA_DIR, cairns, cairns_shapeless\nfrom gtfstk import *\n\nif HAS_GEOPANDAS:\n from geopandas import GeoDataFrame\n\n\ndef test_build_geometry_by_shape():\n feed = cairns.copy()\n shape_ids = feed.shapes[\"shape_id\"].unique()[:2]\n d0 = build_geometry_by_shape(feed)\n d1 = build_geometry_by_shape(feed, shape_ids=shape_ids)\n for d in [d0, d1]:\n # Should be a dictionary\n assert isinstance(d, dict)\n # The first key should be a valid shape ID\n assert list(d.keys())[0] in feed.shapes[\"shape_id\"].values\n # The first value should be a Shapely linestring\n assert isinstance(list(d.values())[0], sg.LineString)\n # Lengths should be right\n assert len(d0) == feed.shapes[\"shape_id\"].nunique()\n assert len(d1) == len(shape_ids)\n # Should be empty if feed.shapes is None\n feed2 = cairns_shapeless.copy()\n assert build_geometry_by_shape(feed2) == {}\n\n\ndef test_shapes_to_geojson():\n feed = cairns.copy()\n shape_ids = feed.shapes.loc[:2, \"shape_id\"]\n collection = shapes_to_geojson(feed, shape_ids)\n geometry_by_shape = build_geometry_by_shape(feed, shape_ids=shape_ids)\n for f in collection[\"features\"]:\n shape = f[\"properties\"][\"shape_id\"]\n geom = sg.shape(f[\"geometry\"])\n assert geom.equals(geometry_by_shape[shape])\n\n\n@pytest.mark.skipif(not HAS_GEOPANDAS, reason=\"Requires GeoPandas\")\ndef test_get_shapes_intersecting_geometry():\n feed = cairns.copy()\n path = DATA_DIR / \"cairns_square_stop_750070.geojson\"\n polygon = sg.shape(json.load(path.open())[\"features\"][0][\"geometry\"])\n pshapes = get_shapes_intersecting_geometry(feed, polygon)\n shape_ids = [\"120N0005\", \"1200010\", \"1200001\"]\n assert set(pshapes[\"shape_id\"].unique()) == set(shape_ids)\n\n\ndef test_append_dist_to_shapes():\n feed1 = cairns.copy()\n s1 = feed1.shapes\n feed2 = append_dist_to_shapes(feed1)\n s2 = feed2.shapes\n # Check that colums of st2 equal the columns of st1 plus\n # a shape_dist_traveled column\n cols1 = list(s1.columns.values) + [\"shape_dist_traveled\"]\n cols2 = list(s2.columns.values)\n assert set(cols1) == set(cols2)\n\n # Check that within each trip the shape_dist_traveled column\n # is monotonically increasing\n for name, group in s2.groupby(\"shape_id\"):\n sdt = list(group[\"shape_dist_traveled\"].values)\n assert sdt == sorted(sdt)\n\n\n@pytest.mark.skipif(not HAS_GEOPANDAS, reason=\"Requires GeoPandas\")\ndef test_geometrize_shapes():\n shapes = cairns.shapes.copy()\n geo_shapes = geometrize_shapes(shapes, use_utm=True)\n # Should be a GeoDataFrame\n assert isinstance(geo_shapes, GeoDataFrame)\n # Should have the correct shape\n assert geo_shapes.shape[0] == shapes[\"shape_id\"].nunique()\n assert geo_shapes.shape[1] == shapes.shape[1] - 2\n # Should have the correct columns\n expect_cols = set(list(shapes.columns) + [\"geometry\"]) - set(\n [\n \"shape_pt_lon\",\n \"shape_pt_lat\",\n \"shape_pt_sequence\",\n \"shape_dist_traveled\",\n ]\n )\n assert set(geo_shapes.columns) == expect_cols\n\n\n@pytest.mark.skipif(not HAS_GEOPANDAS, reason=\"Requires GeoPandas\")\ndef test_ungeometrize_shapes():\n shapes = cairns.shapes.copy()\n geo_shapes = geometrize_shapes(shapes)\n shapes2 = ungeometrize_shapes(geo_shapes)\n # Test columns are correct\n expect_cols = set(list(shapes.columns)) - set([\"shape_dist_traveled\"])\n assert set(shapes2.columns) == expect_cols\n # Data frames should agree on certain columns\n cols = [\"shape_id\", \"shape_pt_lon\", \"shape_pt_lat\"]\n assert_frame_equal(shapes2[cols], shapes[cols])\n","sub_path":"tests/test_shapes.py","file_name":"test_shapes.py","file_ext":"py","file_size_in_byte":3750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"179861549","text":"from flask import Flask\nfrom flask import request\nfrom flask import redirect\nfrom flask import url_for\nfrom flask import render_template\nfrom flask import jsonify\nfrom flask import session\n\n\nfrom models import User\n\n\napp = Flask(__name__)\napp.secret_key = 'random string'\n\n\n# 通过 session 来获取当前登录的用户\ndef current_user():\n # print('session, debug', session.permanent)\n username = session.get('username', '')\n u = User.query.filter_by(username=username).first()\n return u\n\n\n@app.route('/')\ndef index():\n view = 'login_view'\n return redirect(url_for(view))\n\n\n# 显示登录界面的函数 GET\n@app.route('/login')\ndef login_view():\n return render_template('login.html')\n\n\n# 处理登录请求 POST\n@app.route('/login', methods=['POST'])\ndef login():\n # u = User(request.form)\n form = request.get_json()\n username = form.get('username', '')\n user = User.query.filter_by(username=username).first()\n r = {\n 'success': False,\n 'message': '登录失败',\n }\n if user is not None and user.validate_auth(form):\n r['success'] = True\n r['next'] = url_for('login_view')\n session.permanent = True\n session['username'] = username\n else:\n r['success'] = False\n r['message'] = '登录失败'\n return jsonify(r)\n\n\n# 处理注册的请求 POST\n@app.route('/register', methods=['POST'])\ndef register():\n form = request.get_json()\n u = User(form)\n r = {\n }\n status, msgs = u.valid()\n if status:\n u.save()\n r['success'] = True\n # 下面这句可以在关闭浏览器后保持用户登录\n session.permanent = True\n session['username'] = u.username\n else:\n r['success'] = False\n r['message'] = '\\n'.join(msgs)\n return jsonify(r)\n\n\nif __name__ == '__main__':\n config = {\n 'debug': True,\n }\n app.run(**config)\n","sub_path":"web15/web15作业.py","file_name":"web15作业.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"187509682","text":"#!/usr/bin/python3\n# File name : setup.py\n# Description : DarkPaw Setup Script\n# Author : TangoCash\n# Date : 2020/4/13\n\nimport os\nimport sys\nimport time\n\ncurpath = os.path.realpath(__file__)\nthisPath = \"/\" + os.path.dirname(curpath)\nautostart_dir = \"/home/pi/.config/autostart\"\nautostart_file = autostart_dir + \"/darkpaw.desktop\"\n\n\ndef replace_num(file, initial, new_num):\n\tnewline = \"\"\n\tstr_num = str(new_num)\n\twith open(file, \"r\") as f:\n\t\tfor line in f.readlines():\n\t\t\tif (line.find(initial) == 0):\n\t\t\t\tline = (str_num + '\\n')\n\t\t\tnewline += line\n\twith open(file, \"w\") as f:\n\t\tf.writelines(newline)\n\n\ndef run_os_command(cmd, max_runs=4):\n\ttry:\n\t\tsys.stdout.write('###################################################\\n')\n\t\tsys.stdout.write('Command: ' + cmd + '\\n')\n\t\tfor x in range(0, max_runs):\n\t\t\tif os.system(cmd) == 0:\n\t\t\t\tbreak\n\texcept:\n\t\tprint('AN ERROR OCCURRED RUNNING THE FOLLOWING COMMAND: ' + cmd)\n\t\tpass\n\n\ndef upgrade_system():\n\t# Upgrade the existing system\n\trun_os_command(\"sudo apt-get update\")\n\trun_os_command(\"sudo apt-get purge -y wolfram-engine\")\n\trun_os_command(\"sudo apt-get purge -y libreoffice*\")\n\trun_os_command(\"sudo apt-get -y clean\")\n\trun_os_command(\"sudo apt-get -y autoremove\")\n\trun_os_command(\"sudo apt-get -y upgrade\")\n\n\t# fix conflict with onboard Raspberry Pi audio\n\ttry:\n\t\trun_os_command('sudo touch /etc/modprobe.d/snd-blacklist.conf')\n\t\twith open(\"/etc/modprobe.d/snd-blacklist.conf\", 'w') as file_to_write:\n\t\t\tfile_to_write.write(\"blacklist snd_bcm2835\")\n\texcept:\n\t\tpass\n\n\ndef create_autostart_rc():\n\ttry:\n\t\trun_os_command('sudo touch //home/pi/startup.sh')\n\t\twith open(\"//home/pi/startup.sh\", 'w') as file_to_write:\n\t\t\tfile_to_write.write(\"#!/bin/sh\\nsudo python3 \" + thisPath + \"/server/server.py\")\n\t\trun_os_command('sudo chmod 777 //home/pi/startup.sh')\n\t\treplace_num('/etc/rc.local', 'fi', 'fi\\n//home/pi/startup.sh start')\n\texcept:\n\t\tprint('Autostart failed. Please try again')\n\t\tpass\n\n\ndef create_autostart_x():\n\ttry:\n\t\tif (not os.path.exists(autostart_dir)):\n\t\t\trun_os_command(\"sudo mkdir '\" + autostart_dir + \"/'\", 1)\n\t\tif (not os.path.isfile(autostart_file)):\n\t\t\trun_os_command(\"sudo touch \" + autostart_file, 1)\n\n\t\twith open(autostart_file, 'w') as file_to_write:\n\t\t\tfile_to_write.write(\n\t\t\t\t\"[Desktop Entry]\\n Name=DarkPaw\\n Comment=DarkPaw\\n Exec=sudo python3 \" + thisPath + \"/server/server.py\\n Icon=false\\n Terminal=false\\n MutipleArgs=false\\n Type=Application\\n Catagories=Application;Development;\\n StartupNotify=true\")\n\texcept:\n\t\tprint('Autostart failed. Please try again')\n\t\tpass\n\n\ndef reboot_system():\n\t# Reboot the server to have the changes take effect\n\trun_os_command(\"sudo reboot\")\n\n\ndef install_darkpaw():\n\t# Enable the interface(s)\n\ttry:\n\t\treplace_num(\"/boot/config.txt\", '#dtparam=i2c_arm=on', 'dtparam=i2c_arm=on\\n')\n\texcept:\n\t\tpass\n\n\t# Prepare to install. Clean & Update the repositories\n\trun_os_command(\"sudo apt-get clean\")\n\trun_os_command(\"sudo apt-get update\")\n\n\t# Install software #1\n\trun_os_command(\"sudo apt-get install -y python3-dev python3-pip libfreetype6-dev libjpeg-dev build-essential\")\n\trun_os_command(\"sudo apt-get install -y i2c-tools\")\n\trun_os_command(\"sudo apt-get install -y python3-smbus\")\n\trun_os_command(\"sudo apt-get install -y libqtgui4 libhdf5-dev libhdf5-serial-dev libatlas-base-dev libjasper-dev libqt4-test\")\n\n\t# Create the Access Point\n\trun_os_command(\"git clone https://github.com/oblique/create_ap.git //home/pi/create_ap\")\n\trun_os_command(\"cd //home/pi/create_ap && make && sudo make install\", 1)\n\n\t# Install software #2\n\trun_os_command(\"sudo apt-get install -y util-linux procps hostapd iproute2 iw haveged dnsmasq\")\n\n\t# Install python modules\n\trun_os_command(\"sudo pip3 install -U pip\")\n\trun_os_command(\"sudo -H pip3 install --upgrade luma.oled\")\n\trun_os_command(\"sudo pip3 install adafruit-pca9685\")\n\trun_os_command(\"sudo pip3 install rpi_ws281x\")\n\trun_os_command(\"sudo pip3 install mpu6050-raspberrypi\")\n\trun_os_command(\"sudo pip3 install flask\")\n\trun_os_command(\"sudo pip3 install flask_cors\")\n\trun_os_command(\"sudo pip3 install websockets\")\n\trun_os_command(\"sudo pip3 install opencv-contrib-python==3.4.3.18\")\n\trun_os_command(\"sudo pip3 install numpy\")\n\trun_os_command(\"sudo pip3 install imutils zmq pybase64 psutil\")\n\n\t# Set up the autostart\n\tcreate_autostart_rc()\n\n\t# Download, build & Install Sphinxbase & PocketSphinx\n\trun_os_command(\"sudo apt-get install -y bison libasound2-dev swig\")\n\trun_os_command(\"sudo apt-get install -y libpulse-dev\")\n\trun_os_command(\"sudo apt-get install -y portaudio19-dev python3-pyaudio\")\n\trun_os_command(\"mkdir //home/pi/speech\")\n\trun_os_command(\"wget https://sourceforge.net/projects/cmusphinx/files/sphinxbase/5prealpha/sphinxbase-5prealpha.tar.gz/download -O //home/pi/speech/sphinxbase.tar.gz\")\n\trun_os_command(\"wget https://sourceforge.net/projects/cmusphinx/files/pocketsphinx/5prealpha/pocketsphinx-5prealpha.tar.gz/download -O //home/pi/speech/pocketsphinx.tar.gz\")\n\trun_os_command(\"cd //home/pi/speech && tar -xzvf sphinxbase.tar.gz\")\n\trun_os_command(\"cd //home/pi/speech && tar -xzvf pocketsphinx.tar.gz\")\n\trun_os_command(\"cd //home/pi/speech/sphinxbase-5prealpha/ && ./configure -enable-fixed && make && sudo make install\", 1)\n\trun_os_command(\"cd //home/pi/speech/pocketsphinx-5prealpha/ && ./configure && make && sudo make install\", 1)\n\trun_os_command(\"sudo pip3 install SpeechRecognition\", 1)\n\trun_os_command(\"sudo pip3 install pocketsphinx\", 1)\n\trun_os_command(\"sudo amixer -c1 sset Mic 80%\")\n\trun_os_command(\"sudo alsactl store\")\n\n\ndef install_controller():\n\t# Install Software\n\trun_os_command(\"sudo apt-get install -y bluetooth libbluetooth3 libbluetooth-dev libusb-dev\")\n\trun_os_command(\"sudo systemctl enable bluetooth.service\")\n\trun_os_command(\"sudo usermod -G bluetooth -a pi\")\n\n\t# PS3 controller pairing tool\n\trun_os_command(\"mkdir //home/pi/sixpair\")\n\trun_os_command(\"wget -O //home/pi/sixpair/sixpair.c http://www.pabr.org/sixlinux/sixpair.c\")\n\trun_os_command(\"cd //home/pi/sixpair && gcc -o sixpair sixpair.c -lusb\")\n\n\t# Install python modules\n\trun_os_command(\"sudo pip3 install dbus-python pexpect pygame\")\n\n\ndef set_new_master():\n\t# Set new bluetooth master for PS3 Controller\n\tsys.stdout.write('###################################################\\n')\n\tsys.stdout.write('PLEASE CONNECT PS3 CONTROLLER VIA USB..............\\n')\n\tsys.stdout.write('AND PRESS ENTER TO CONTINUE........................\\n')\n\tsys.stdout.write('###################################################\\n')\n\tinput('')\n\n\trun_os_command(\"sudo //home/pi/sixpair/sixpair\")\n\n\tsys.stdout.write('###################################################\\n')\n\tsys.stdout.write('PLEASE DISCONNECT PS3 CONTROLLER...................\\n')\n\tsys.stdout.write('AND PRESS ENTER TO CONTINUE........................\\n')\n\tsys.stdout.write('###################################################\\n')\n\tinput('')\n\nwhile True:\n\ttry:\n\t\tselection = int(input(\n\t\t\t\"Select an option:\\n 1 = Upgrade OS;\\n 2 = Install DarkPaw;\\n 3 = Install Game Controller;\\n 4 = Reprog PS3 Game Controller;\\n 9 = Reboot;\\n 0 = Exit\\n\\nOption to select: \"))\n\n\t\tif selection == 1:\n\t\t\tupgrade_system()\n\t\t\tsys.stdout.write('###################################################\\n')\n\t\t\tsys.stdout.write('IT IS RECOMMENDED YOU REBOOT BEFORE CONTINUING.....\\n')\n\t\t\tsys.stdout.write('###################################################\\n')\n\t\telif selection == 2:\n\t\t\tinstall_darkpaw()\n\t\telif selection == 3:\n\t\t\tinstall_controller()\n\t\t\tsys.stdout.write('###################################################\\n')\n\t\t\tsys.stdout.write('IT IS RECOMMENDED YOU REBOOT BEFORE CONTINUING.....\\n')\n\t\t\tsys.stdout.write('###################################################\\n')\n\t\telif selection == 4:\n\t\t\tset_new_master()\n\t\telif selection == 9:\n\t\t\treboot_system()\n\t\telif selection == 0:\n\t\t\tbreak\n\t\telse:\n\t\t\tprint(\"Invalid selection. Please try again\")\n\texcept:\n\t\tprint(\"ex: Invalid selection. Please try again\")\n\t\tpass\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":7929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"510642710","text":"import torch.nn as nn\nimport math\nimport torch.nn.functional as F\nimport torch\n\n\ndef _scaleFunc_pos(mu, std, th_pos):\n alpha = (th_pos - mu) / std\n pdf = torch.exp(-(alpha.pow(2) / 2)) / math.sqrt(2 * math.pi)\n cdf = (1 + torch.erf(alpha / math.sqrt(2))) / 2\n\n return mu + std * (pdf / (1 - cdf))\n\n\ndef _scaleFunc_neg(mu, std, th_neg):\n beta = (th_neg - mu) / std\n pdf = torch.exp(-(beta.pow(2) / 2)) / math.sqrt(2 * math.pi)\n cdf = (1 + torch.erf(beta / math.sqrt(2))) / 2\n\n return mu - std * (pdf / cdf)\n\n\n\nclass _quanFunc(torch.autograd.Function):\n def __init__(self, mu, delta, alpha):\n super(_quanFunc, self).__init__()\n self.mu = mu.item()\n self.delta = delta.item()\n self.alpha = alpha.item()\n\n def forward(self, input):\n output = input.clone().zero_()\n output[input.gt(self.mu + self.delta)] = 1\n output[input.lt(self.mu - self.delta)] = -1\n\n return output\n\n def backward(self, grad_output):\n # saved tensors - tuple of tensors with one element\n grad_input = grad_output.clone() / self.alpha\n return grad_input\n\n\n\nclass quanLinear(nn.Linear):\n def __init__(self, in_features, out_features, bias=True,\n n_thresholds=1):\n super(quanLinear, self).__init__(in_features, out_features, bias)\n self.mu, self.std = self.weight.mean(), self.weight.std()\n\n max_w_init = self.weight.abs().max()\n self.init_factor = torch.Tensor([0.05])\n deltas = (max_w_init) * self.init_factor\n\n self.delta_th = nn.Parameter(deltas)\n self.th_clip = F.hardtanh(self.delta_th.abs(), min_val=(-3 * self.std).item(), max_val=(3 * self.std).item())\n self.scale_factor = _scaleFunc_pos(self.mu, self.std, self.mu + self.th_clip)\n\n def forward(self, input):\n self.mu = self.weight.mean()\n self.std = self.weight.std()\n self.th_clip = F.hardtanh(self.delta_th.abs(), min_val=(-3 * self.std).item(), max_val=(3 * self.std).item())\n self.scale_factor = _scaleFunc_pos(self.mu, self.std, self.mu + self.th_clip)\n \n for idx,param in enumerate(self.th_clip):\n tern_weight = _quanFunc(self.mu,\n param,\n self.scale_factor[idx])(self.weight) * self.scale_factor[idx]\n if idx == 0:\n output = F.linear(input, tern_weight, self.bias)\n else:\n output += F.linear(input, tern_weight, self.bias)\n\n return output\n\n\nclass quanConv2d(nn.Conv2d):\n def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1,\n groups=1, bias=True, n_thresholds=1):\n super(quanConv2d, self).__init__(in_channels, out_channels, kernel_size, stride,\n padding, dilation, groups, bias)\n self.mu, self.std = self.weight.mean(), self.weight.std()\n\n max_w_init = self.weight.abs().max()\n self.init_factor = torch.Tensor([0.05])\n deltas = (max_w_init) * self.init_factor\n\n self.delta_th = nn.Parameter(deltas)\n self.th_clip = F.hardtanh(self.delta_th.abs(), min_val=(-3 * self.std).item(), max_val=(3 * self.std).item())\n self.scale_factor = _scaleFunc_pos(self.mu, self.std, self.mu + self.th_clip)\n\n def forward(self, input):\n self.mu = self.weight.mean()\n self.std = self.weight.std()\n self.th_clip = F.hardtanh(self.delta_th.abs(), min_val=(-3 * self.std).item(), max_val=(3 * self.std).item())\n self.scale_factor = _scaleFunc_pos(self.mu, self.std, self.mu + self.th_clip)\n \n for idx,param in enumerate(self.th_clip):\n tern_weight = _quanFunc(self.mu,\n param,\n self.scale_factor[idx])(self.weight) * self.scale_factor[idx]\n if idx == 0:\n output = F.conv2d(input, tern_weight, self.bias, self.stride, self.padding, self.dilation,\n self.groups)\n else:\n output += F.conv2d(input, tern_weight, self.bias, self.stride, self.padding, self.dilation,\n self.groups)\n\n return output\n","sub_path":"models/tern_threshold_trainable_5.py","file_name":"tern_threshold_trainable_5.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"313243188","text":"from functools import reduce\n\nfrom random import randint, sample\n\n# 先构造数据,三个dict\ns1 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}\ns2 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}\ns3 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}\n\n# 方法一,使用集合,对集合进行 & 操作\nprint(s1.keys() & s2.keys() & s3.keys())\n\n# 方法二,使用map和reduce函数,进行 & 操作\nm = list(map(dict.keys, [s1, s2, s3]))\nprint(reduce(lambda a, b: a & b, m))\n\n\n","sub_path":"basis_python_efficient/p1_数据结构与算法/py5_查找多个字典的公共键.py","file_name":"py5_查找多个字典的公共键.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"470627511","text":"import sys\nimport os\n\n\ndef palindrome(s):\n text = list(s)\n text = reversed(text)\n string = \"\"\n string = string.join(text)\n return (string == s)\n \n\n\ndef solution(s):\n return palindrome(s)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) <= 1:\n sys.exit(os.error(\"Argment required\"))\n\n print(solution(sys.argv[1]))\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"12984547","text":"import pytest\n\nfrom pyapp.conf import loaders\nfrom pyapp.exceptions import InvalidConfiguration\n\n\nclass TestModuleLoader(object):\n def test__module_exists(self):\n target = loaders.ModuleLoader('tests.settings')\n\n actual = dict(target)\n\n assert str(target) == 'python:tests.settings'\n assert all(key.isupper() for key in actual)\n\n def test__module_not_found(self):\n target = loaders.ModuleLoader('tests.unknown.settings')\n\n with pytest.raises(InvalidConfiguration):\n dict(target)\n\n assert str(target) == 'python:tests.unknown.settings'\n\n\nclass TestSettingsLoaderRegistry(object):\n def test_register__as_decorator(self):\n target = loaders.SettingsLoaderRegistry()\n\n @target.register\n class SimpleSettings(object):\n scheme = 'eek'\n\n @classmethod\n def from_url(cls, settings_url):\n return cls(settings_url)\n\n def __init__(self, settings_url):\n self.settings_url = settings_url\n\n def __iter__(self):\n return {\n 'SIMPLE': self.settings_url\n }.items()\n\n assert 'eek' in target.loaders\n assert isinstance(target.factory('eek:sample'), SimpleSettings)\n\n def test_register__as_method(self):\n target = loaders.SettingsLoaderRegistry()\n\n class SimpleSettings(object):\n @classmethod\n def from_url(cls, settings_url):\n return cls(settings_url)\n\n def __init__(self, settings_url):\n self.settings_url = settings_url\n\n def __iter__(self):\n return {\n 'SIMPLE': self.settings_url\n }.items()\n\n target.register(SimpleSettings, scheme='eek')\n\n assert 'eek' in target.loaders\n assert isinstance(target.factory('eek:sample'), SimpleSettings)\n\n @pytest.mark.parametrize(('settings_uri', 'expected', 'str_value'), (\n ('sample.settings', loaders.ModuleLoader, 'python:sample.settings'),\n ('python:sample.settings', loaders.ModuleLoader, 'python:sample.settings'),\n ('file:///path/to/sample.json', loaders.FileLoader, 'file:///path/to/sample.json'),\n ))\n def test_factory__loaders_correctly_resolved(self, settings_uri, expected, str_value):\n target = loaders.SettingsLoaderRegistry()\n\n actual = target.factory(settings_uri)\n\n assert isinstance(actual, expected)\n assert str(actual) == str_value\n\n @pytest.mark.parametrize(('settings_uri', 'expected'), (\n ('py:sample.settings', 'Unknown scheme `py` in settings URI:'),\n ))\n def test_factory__invalid_settings_uri(self, settings_uri, expected):\n target = loaders.SettingsLoaderRegistry()\n\n with pytest.raises(InvalidConfiguration) as e:\n target.factory(settings_uri)\n\n assert str(e.value).startswith(expected)\n","sub_path":"tests/test_conf_loaders.py","file_name":"test_conf_loaders.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"371214670","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the arrayManipulation function below.\ndef arrayManipulation(n, queries):\n pass\n\nif __name__ == '__main__':\n n,m = map(int, input().split())\n arr = [0] * (n+1)\n for _ in range(m):\n a,b,k = map(int, input().split())\n arr[a-1] += k\n if b <= (n+1):\n arr[b] -= k # NOTE: This solution is from the Discussions tab\n mx = 0\n x = 0\n # print(arr)\n for a in arr:\n x += a\n if(mx < x):\n mx = x\n print(mx)\n","sub_path":"Problem Solving/Arrays/ArrayManipulation.py","file_name":"ArrayManipulation.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"209565748","text":"seznam_zvirat = [\"pes\", \"kočka\", \"králík\", \"had\"]\r\n\r\ndef kontrola_seznamu(seznam):\r\n\t\"\"\"Funkce zjistí, zda napsané slovo je či není v seznamu\"\"\"\r\n\tkontrolni_slovo = (input(\"Zadej zvíře, které chceš zkontrolovat, zda se nachází v seznamu: \")).lower()\r\n\r\n\tif kontrolni_slovo in seznam:\r\n\t\tprint(\"Ano, slovo {} je v seznamu zvířat\".format (kontrolni_slovo))\r\n\telse:\r\n\t\tprint(\"Bohužel, toto zvíře není v seznamu\")\r\n\r\nkontrola_seznamu(seznam_zvirat)","sub_path":"du_3.py","file_name":"du_3.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"411765379","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 ('cflatpages', '0002_auto_20160629_0803'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='cflatpage',\n options={'ordering': ['num'], 'verbose_name': 'categorized flatpage', 'verbose_name_plural': 'categorized flatpages'},\n ),\n migrations.RemoveField(\n model_name='cflatpage',\n name='pos',\n ),\n migrations.AddField(\n model_name='cflatpage',\n name='num',\n field=models.PositiveSmallIntegerField(default=1, verbose_name='order number'),\n ),\n ]\n","sub_path":"cflatpages/migrations/0003_auto_20160629_1128.py","file_name":"0003_auto_20160629_1128.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"641531037","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n\turl(r'^$', views.home, name = 'home'),\n\turl(r'^about$', views.about, name = 'about'),\n\turl(r'^contact$', views.contact, name = 'contact'),\n\turl(r'^post$', views.post, name = 'post'),\n\turl(r'^post_list/', views.post_list, name = 'post_list'),\n\turl(r'^post/(?P[0-9]+)/edit$', views.post_edit, name = 'post_edit'),\n\turl(r'^post/(?P[0-9]+)/remove$', views.post_remove, name = 'post_remove'),\n\turl(r'^user/register$', views.register, name = 'register'),\n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"114820874","text":"#! python 3\n__author__ = 'lucas.araujo'\n\n\ndef count(array):\n d = {}\n for i in array:\n if i in d.keys():\n d[i] += 1\n else:\n d[i] = 1\n return d\n\n\nprint(count(['a', 'a', 'b', 'b', 'b']))\n","sub_path":"S1/array_size.py","file_name":"array_size.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"5835803","text":"#-------------------------------------------------------------------------------\r\n# Name: circuitEnumerator\r\n# Purpose: enumerate all legal circuits in the 5-state machine architecture\r\n# where recombinases sites are stationary\r\n#\r\n# Author: mquintin\r\n#\r\n# Created: 19/05/2015\r\n# Copyright: (c) mquintin 2015\r\n# Licence: \r\n#-------------------------------------------------------------------------------\r\nimport operator, collections, copy\r\n\r\n#maximum number of parts\r\nnmax = 14\r\n\r\n#for when we need to iterate\r\nparttypes = 13\r\nparts = range(0,parttypes)\r\nrecs = [3,4,5] #recombinase sites\r\nrecidx = [1,2,5,8,11,12] #locations of rec sites\r\nseq0 = [-12,3,4,-12,-12,5,-12,-12,-4,-12,-12,5,-3,-12]\r\ngenes = range(6,parttypes)\r\nruncounter = [0]\r\n\r\n#because these aren't built in to python\r\ndef prod(factors):\r\n return reduce(operator.mul, factors, 1)\r\ndef flatten(x):\r\n if isinstance(x, collections.Iterable):\r\n return [a for i in x for a in flatten(i)]\r\n else:\r\n return [x]\r\n\r\n##functions to build:\r\n##\tvalidate each atomic part:\r\n##\t\tinitial validity score = 1\r\n##\t\tif they get used properly, set score = score*2\r\n##\t\tif they do something illegal in any state, set score = abs(score)*-1 and/or reject the machine and break\r\n##\t\tpermutation independent checks:\r\n##\t\t\teach recombinase site is used exactly 0 or 2 times\r\n##\t\t\tno adjacent opposing unidirectional terminators\r\n##\t\t\tno adjacent identical parts\r\n##\t\t\tonly use lowest numbered genes (build this into the generation step)\r\n##\t\tpermutation dependent checks:\r\n##\t\t\tin initial state and after RecB, RecA1 and RecA2 sites aren't staggered (eg 1,2,1,2; 1,2,B,2,1,B)\r\n##\t\tScore parts for every permutation:\r\n##\t\t\tif recombinase site, +1\r\n##\t\t\tif promoter...n>1 genes... terminator, +1 to each\r\n##\t\t\tif promoter...promoter, no score\r\n##\tPermute based on using recombinase A\r\n##\tPermute based on using recombinase B\r\n##\tGet the truth table for each gene in the current state\r\n##\tGet the truth table for all states\r\n\r\n##ID\tPartName\r\n##0\tBiTerminator\r\n##1\tUniTerminator\r\n##2\tPromoter\r\n##3\tRecA1\r\n##4\tRecA2\r\n##5\tRecB\r\n##6\tGene1\r\n##7\tGene2\r\n##8\tGene3\r\n##9\tGene4\r\n##10\tGene5\r\n##11\tGene6\r\n##12\tGene7\r\n##13\tGene8\r\n##14\tGene9\r\n##15\tGene10\r\n##16\tGene11\r\n##17\tGene12\r\n##18\tGene13\r\n##19\tGene14\r\n\r\n\r\n#flip/delete recombinaseA sites\r\n#IDs of interest are 3 & 4 (and -3,-4) for recA, 5 for recB\r\n#There is guaranteed to be no overlap between 3&4\r\n#There is guaranteed to be either 0 or 2 of each\r\n#\r\n#seq=[int]\r\n#x= absolute value of part number to flip\r\n#return:[int]\r\ndef permute(seq,x):\r\n s = copy.deepcopy(seq)\r\n #location of sites\r\n idx = [i for i,j in enumerate(s) if x==abs(j)]\r\n if(len(idx) == 2):\r\n if(s[idx[0]] + s[idx[1]] == 0): #opposite: invert\r\n subseq = s[idx[0]:idx[1]+1]\r\n subseq.reverse()\r\n s[idx[0]:idx[1]+1] = subseq\r\n else: #excise\r\n s[idx[0]:idx[1]+1] = []\r\n return s\r\n\r\ndef permuteA(seq):\r\n s = permute(seq,3)\r\n s = permute(s,4)\r\n return s\r\n\r\ndef permuteB(seq):\r\n s = permute(seq,5)\r\n return s\r\n\r\n#increment the last element in the given circuit\r\n#if it overflows, add an element to the end and start the count over\r\ndef getNextSeq(seq):\r\n runcounter[0] += 1\r\n if runcounter[0] == 500000:\r\n runcounter[0] = 0\r\n print(seq)\r\n if (seq[-1] <= (-1 * genes[1])): #these are all going to fail anyway\r\n seq[-1] = (-1 * genes[1]) + 1\r\n return seq\r\n pointer = len(seq)-1\r\n return nextSeq(seq,pointer)\r\n\r\ndef nextSeq(seq,pointer):\r\n while (pointer in recidx):\r\n pointer -= 1\r\n if seq[pointer] >= parts[-1]:\r\n if pointer <= 0:\r\n #print(seq, pointer)\r\n #start at the lowest value seq of length +1\r\n newseq = [-parts[-1]]*(len(seq)+1)\r\n return newseq\r\n else:\r\n return nextSeq(seq,pointer-1)\r\n else:\r\n seq[pointer]+=1 #increment at pointer\r\n #reset every value after the pointer\r\n for i in range(0,len(seq)):\r\n if (i > pointer) & (i not in recidx):\r\n seq[i] = (-1 * parts[-1])\r\n return seq\r\n\r\n#enforces rules about part numbers\r\ndef validateFormat(seq):\r\n #each recombinase site is used 0 or 2 times\r\n pos = map(abs,seq)\r\n for r in recs: #recs = [3,4,5]: recombinase sites\r\n if pos.count(r) not in [0,2]:\r\n return 0\r\n #a gene and a promoter are present\r\n if pos.count(6) < 1:\r\n return 0\r\n if pos.count(2) <1:\r\n return 0\r\n #the circuit must use only the lowest numbered genes.\r\n #get the highest gene number, make sure all genes between\r\n #it and geneA (6) are present\r\n genesUsed = range(6,max(pos)) #doesn't include the max, we know it's used\r\n for g in genesUsed:\r\n if pos.count(g) <1:\r\n return 0\r\n #adjacency rules\r\n for i in range(0,len(seq)-1):\r\n #no adjacent identical parts\r\n if seq[i]==seq[i+1]:\r\n return 0\r\n #no adjacent opposing unidirectional terminators\r\n if sorted(seq[i:i+2]) == [-1,1]:\r\n return 0\r\n #recombinaseA sites are not improperly staggered, where the result will\r\n #depend on if RecA1 or RecA2 switches first\r\n #ex: 1,2,1,2 1,2,B,2,1,B\r\n if pos.count(3) == 2 & pos.count(4) == 2:\r\n x = [pos.index(3),len(pos - pos[::-1].index(3))] #first and last occurrence\r\n y = [pos.index(4),len(pos - pos[::-1].index(4))]\r\n xy = (x+y).sort\r\n if (x[0] == xy[0] & x[1] == xy[2]) | (x[0] == xy[1] & x[1] == xy[2]):\r\n return 0\r\n #in terms of RecB, the only invalid arrangements are x,y,B,y,x,B and its\r\n #reverse, or x,B,y,x,B,y. If the B sites are 2 away, make sure the sites\r\n #between them are matching targets (x,B,y,y,B,x B,x,x,B,y,y)\r\n if pos.count(5) == 2:\r\n z = [pos.index(5),len(pos - pos[::-1].index(5))]\r\n if z[1] - z[0] == 2:\r\n if sorted([pos[z[0]+1],pos[z[0]+2]]) == [3,4]:\r\n return 0\r\n return 1\r\n\r\n#enforces rules about interaction of parts\r\n#only checks left to right; must also validate the inverse of a sequence\r\n#returns a list of integers >=1 iff the corresponding part didn't misbehave\r\n# >1 if the part us properly used\r\ndef validateExpression(seq):\r\n res = [1] * len(seq)\r\n for i in range(0,len(seq)):\r\n if abs(seq[i]) in[3,4,5]:\r\n res[i] *=2 #already know the count of recombinases is good\r\n if seq[i] == 2: #promoter\r\n #express = [] #idx of genes that this promoter expresses\r\n for j in range(i+1,len(seq)):\r\n if seq[j] in [0,1]: #terminators\r\n #if len(express) > 0:\r\n # for k in ([i] + [j] + express):\r\n # res[k]*=2 #good score\r\n break; #this promoter's done\r\n if seq[j] in genes:\r\n res[j] *= 2\r\n res[i] *= 2\r\n #express.append(j)\r\n if seq[j] == 2: #redundant promoter\r\n #if len(express) == 0:\r\n break;\r\n return res;\r\n\r\n#returns two lists of lists. The first is\r\ndef validatePermutation(seq):\r\n s = copy.deepcopy(seq)\r\n scores = [validateExpression(s)]\r\n imap = range(0,len(s)) #map indexes to positions in the score list\r\n #shuffle A\r\n recA1 = [i for i,j in enumerate(s) if 3==abs(j)]\r\n if len(recA1) == 2:\r\n imap = permuteIdx(imap,recA1[0],recA1[1],seq[recA1[0]]==seq[recA1[1]])\r\n recA2 = [i for i,j in enumerate(s) if 4==abs(j)]\r\n if len(recA2) == 2:\r\n imap = permuteIdx(imap,recA2[0],recA2[1],seq[recA2[0]]==seq[recA2[1]])\r\n if len(recA1 + recA2) > 0:\r\n val = validateExpression(permuteA(copy.deepcopy(seq)))\r\n for i in range(0,len(imap)):\r\n score = [1] * len(seq)\r\n score[imap[i]] *= val[i]\r\n scores.append(score)\r\n #shuffle B\r\n imap = range(0,len(s))\r\n recB = [i for i,j in enumerate(s) if 5==abs(j)]\r\n if len(recB) == 2:\r\n imap = permuteIdx(imap,recB[0],recB[1],seq[recB[0]]==seq[recB[1]])\r\n val = validateExpression(permuteB(copy.deepcopy(seq)))\r\n for i in range(0,len(imap)):\r\n score = [1] * len(seq)\r\n score[imap[i]] *= val[i]\r\n scores.append(score)\r\n if (len(recA1 + recA2) > 0) & (len(recB) > 0):\r\n #shuffle A,B\r\n imap = range(0,len(s))\r\n recA1 = [i for i,j in enumerate(s) if 3==abs(j)]\r\n if len(recA1) == 2:\r\n imap = permuteIdx(imap,recA1[0],recA1[1],seq[recA1[0]]==seq[recA1[1]])\r\n recA2 = [i for i,j in enumerate(s) if 4==abs(j)]\r\n if len(recA2) == 2:\r\n imap = permuteIdx(imap,recA2[0],recA2[1],seq[recA2[0]]==seq[recA2[1]])\r\n recB = [i for i,j in enumerate(s) if 5==abs(j)]\r\n imap = permuteIdx(imap,recB[0],recB[1],seq[recB[0]]==seq[recB[1]])\r\n val = validateExpression(permuteA(permuteB(copy.deepcopy(seq))))\r\n for i in range(0,len(imap)):\r\n score = [1] * len(seq)\r\n score[imap[i]] *= val[i]\r\n scores.append(score)\r\n #shuffle B,A\r\n imap = range(0,len(s))\r\n recB = [i for i,j in enumerate(s) if 5==abs(j)]\r\n imap = permuteIdx(imap,recB[0],recB[1],seq[recB[0]]==seq[recB[1]])\r\n recA1 = [i for i,j in enumerate(s) if 3==abs(j)]\r\n if len(recA1) == 2:\r\n imap = permuteIdx(imap,recA1[0],recA1[1],seq[recA1[0]]==seq[recA1[1]])\r\n recA2 = [i for i,j in enumerate(s) if 4==abs(j)]\r\n if len(recA2) == 2:\r\n imap = permuteIdx(imap,recA2[0],recA2[1],seq[recA2[0]]==seq[recA2[1]])\r\n val = validateExpression(permuteB(permuteA(copy.deepcopy(seq))))\r\n for i in range(0,len(imap)):\r\n score = [1] * len(seq)\r\n score[imap[i]] *= val[i]\r\n scores.append(score)\r\n #print(scores)\r\n return scores\r\n\r\n\r\n#rearrange the given index list with recombination sites at the given positions\r\ndef permuteIdx(imap, left, right, match):\r\n i = copy.deepcopy(imap)\r\n if(not match): #opposite: invert\r\n subseq = i[left:right+1]\r\n subseq.reverse()\r\n i[left:right+1] = subseq\r\n else: #excise\r\n i[left:right+1] = []\r\n return i\r\n\r\ndef getUseScores(seq):\r\n s = copy.deepcopy(seq)\r\n\r\n\r\n#check that the machine is legal in all states\r\ndef validate(seq):\r\n formatOK = validateFormat(seq)\r\n if formatOK == 0:\r\n return 0\r\n scores = []\r\n v0 = validatePermutation(seq)\r\n if not all([x>=1 for x in v0]):\r\n return 0\r\n pa = permuteA(seq)\r\n pb = permuteB(seq)\r\n pab = permuteB(pa)\r\n pba = permuteA(pb)\r\n va = validateExpression(pa)\r\n if not all([x>=1 for x in va]): #no part did something illegal here\r\n return 0\r\n vb = validateExpression(pb)\r\n if not all([x>=1 for x in vb]):\r\n return 0\r\n vab = validateExpression(permuteB(pa))\r\n if not all([x>=1 for x in vab]):\r\n return 0\r\n vba = validateExpression(permuteA(vb))\r\n if not all([x>=1 for x in vba]):\r\n return 0\r\n rev = map(lambda x : x*-1,seq[::-1]) #reverse seq and flip the signs\r\n v0r = validateExpression(rev)\r\n par = permuteA(rev)\r\n pbr = permuteB(rev)\r\n pabr = permuteB(par)\r\n pbar = permuteA(pbr)\r\n var = validateExpression(par)\r\n if not all([x>=1 for x in v0r]):\r\n return 0\r\n if not all([x>=1 for x in var]): #no part did something illegal here\r\n return 0\r\n vbr = validateExpression(pbr)\r\n if not all([x>=1 for x in vbr]):\r\n return 0\r\n vabr = validateExpression(permuteB(par))\r\n if not all([x>=1 for x in vabr]):\r\n return 0\r\n vbar = validateExpression(permuteA(vbr))\r\n if not all([x>=1 for x in vbar]):\r\n return 0\r\n #check that all parts are used\r\n allScores= validatePermutation(seq) #[v0,va,vb,vab,vba,v0r,var,vbr,vabr,vbar]\r\n total = [1] * len(seq)\r\n for score in allScores:\r\n total = [a * b for a,b in zip(total,score)] #a part will get >1 if it's\r\n #used properly once\r\n #print(\"total: \",total)\r\n #print(\"flat: \", flatten(total))\r\n if not all([x>1 for x in flatten(total)]):\r\n return 0\r\n return 1\r\n\r\n#output a list of ints of length = # of genes, in order\r\n#0 if not expressed, 1 if expressed\r\ndef truth(seq):\r\n res = [0] * len(genes)\r\n offset = genes[0] #part number of the first gene\r\n rev = map(lambda x : x*-1,seq[::-1]) #reverse seq and flip the signs\r\n for s in [seq,rev]:\r\n transcribing = False\r\n idx = 0\r\n while idx < len(s):\r\n if s[idx]==2:\r\n transcribing = True\r\n if s[idx] in [0,1]:\r\n transcribing = False\r\n if transcribing & (s[idx] in genes):\r\n res[s[idx]-offset] = 1\r\n idx += 1\r\n return res\r\n\r\n#create/append line in sequence file to represent the machine\r\ndef writeSeq(seq,sfile):\r\n with open(sfile, 'a') as f:\r\n f.write(\"\\t\".join(map(str,seq)))\r\n f.write(\"\\n\")\r\n\r\n#create append line in truth file\r\n#each line contains nGenes*5 tab-delimited digits\r\n#these correspond to each gene in numerical order for each orientation\r\n#in the order [no change, recA, recB, recA/B, recB/A]\r\ndef writeTruth(seq,tfile):\r\n pa = permuteA(seq)\r\n pb = permuteB(seq)\r\n pab = permuteB(pa)\r\n pba = permuteA(pb)\r\n t = truth(seq) + truth(pa) + truth(pb) + truth(pab) + truth (pba)\r\n with open(tfile, 'a') as f:\r\n f.write(\"\\t\".join(map(str,t)))\r\n f.write(\"\\n\")\r\n\r\n\r\n\r\n#build all the circuits up to the max length, print them if they validate\r\n#shortest legal circuits start at length 2 (promoter+gene)\r\ndef generate(seq, seqfile, truthfile):\r\n pa = permuteA(seq)\r\n pb = permuteB(seq)\r\n pab = permuteB(pa)\r\n pba = permuteA(pb)\r\n if validate(seq):\r\n writeSeq(seq,seqfile)\r\n writeTruth(seq,truthfile)\r\n\r\ndef test():\r\n #seq = getNextSeq([1,-5,-6])\r\n #writeSeq([1,2,3,4],'testseq.txt')\r\n #writeTruth([0,1,0,1],'testtruth.txt')\r\n #print(seq)\r\n seq = [-12,3,4,-12,-12,5,-12,5,-4,12,12,5,-3,12]\r\n generate(seq,'testseq.txt','testtruth.txt')\r\n print(validate(seq))\r\n print('seq: ', seq)\r\n pa = permuteA(seq)\r\n print('pa: ', pa)\r\n print('seq: ', seq)\r\n pb = permuteB(seq)\r\n print('pb: ', pb)\r\n print('seq: ', seq)\r\n pab = permuteB(pa)\r\n print('pab: ', pab)\r\n print('seq: ', seq)\r\n pba = permuteA(pb)\r\n print('pba: ', pba)\r\n print('seq: ', seq)\r\n print([pa,pb,pab,pba])\r\n print([validateFormat(seq),\r\n validatePermutation(seq),\r\n validatePermutation(pa),\r\n validatePermutation(pb),\r\n validatePermutation(pab),\r\n validatePermutation(pba),\r\n validate(seq)])\r\n print('validate expression:')\r\n print(validateExpression(seq))\r\n## print(pab)\r\n## print(validateExpression(pab))\r\n print(truth(seq))\r\n## print(not all([x>1 for x in flatten(truth(seq))]))\r\n## generate(seq,'testseq.txt','testtruth.txt')\r\n\r\n\r\n\r\ndef main():\r\n testing = 1\r\n if testing:\r\n test()\r\n else:\r\n #seq = [-1,-1*genes[0],-2] #the shortest circuit is 3 elements: pro/gene/term\r\n #seq = [-5,-6,-19,-19,-19,-19,-19]\r\n seq = seq0\r\n while len(seq) <= nmax:\r\n generate(seq, \"circuits14.txt\", \"truth14.txt\")\r\n seq=getNextSeq(seq)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"curcuitEnumerator_14pieces.py","file_name":"curcuitEnumerator_14pieces.py","file_ext":"py","file_size_in_byte":15506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"74925965","text":"from model import FullLotto\n\n\nnum_col_list = ['num1', 'num2', 'num3', 'num4', 'num5', 'num6', 'bonus']\ndef get_numbers(lotto: FullLotto) -> list:\n result = []\n for col in num_col_list:\n result.append(getattr(lotto, col))\n return result\n\ndef check(set1: set, set2: set, bonus: int, prize: int) -> bool:\n common_set = set1 & set2\n if prize == 2:\n return bonus in common_set and len(common_set) == 6\n elif prize == 3:\n return len(common_set) == 5\n else:\n raise ValueError('parameter \"prize\" is invalid.')\n\ndef check_second_and_third(lottos: list, picked: list, q: list) -> bool:\n current_set = set(picked)\n for lotto in lottos:\n past_set = set(get_numbers(lotto))\n is_second = None\n is_third = None\n if 'except_second' in q:\n is_second = check(set1=past_set, set2=current_set, bonus=lotto.bonus, prize=2)\n if 'except_third' in q:\n is_third = check(set1=past_set, set2=current_set, bonus=lotto.bonus, prize=3)\n if is_second or is_third:\n return True\n else:\n return False","sub_path":"router/util/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"306627959","text":"from Lab5task1 import point\nimport copy\n\nclass rectangle:\n\tdef __init__(self):\n\t\tself.width = 0\n\t\tself.height = 0\n\t\tself.corner = 0\n\n\ndef find_center(r):\n\tc = point()\n\tc.x = r.corner.x + r.width/2.0\n\tc.y = r.corner.y + r.height/2.0\n\treturn c\n\ndef move_rectangle(r, dx, dy):\n\tr.corner.x += dx\n\tr.corner.y += dy\n\ndef new_move(r, dx, dy):\n\tres = copy.deepcopy(r)\n\tmove_rectangle(res, dx, dy)\n\treturn res\n\n\nrect = rectangle()\nrect.width = 40.0\nrect.height = 80.0\n\nrect.corner = point()\nrect.corner.x = 0.0\nrect.corner.y = 0.0\n\nprint('Center')\nc = find_center(rect)\n\nprint('(%g, %g)' % (c.x,c.y))\nprint('')\n\nprint('(%g, %g)' % (rect.corner.x, rect.corner.y))\nprint('move')\n\nmove_rectangle(rect, 200, 100)\nprint('(%g, %g)' % (rect.corner.x, rect.corner.y))\nprint('')\nprint('New move')\n\nn_rect = new_move(rect, 80, 160)\nprint('(%g, %g)' % (n_rect.corner.x, n_rect.corner.y))\n\n\n\n\n\n\n\t\n\n","sub_path":"Lab5task2.py","file_name":"Lab5task2.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"292574509","text":"#-*-coding:utf-8-*-\nimport sys\nimport os\nimport shutil\n# The sysconfig module provides access to Python’s configuration information\n# like the list of installation paths and the configuration variables relevant for the current platform.\nimport sysconfig # sysconfig的官方文档:https://docs.python.org/3/library/sysconfig.html\n\nmsg_unknown_os = \"\"\"could not determine operating system!\ntry setting it in site_cfg.py manually, see site_cfg_template.py\"\"\"\n\nmsg_numpydoc = \"\"\"could not find numpydoc!\nIf it is installed in a non-standard location, try setting it in\nsite_cfg.py manually.\"\"\"\n# os.path.exists(path) Return True if path refers to an existing path. Returns False for broken symbolic links.\n# On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file,\n# even if the path physically exists.\nif not os.path.exists('site_cfg.py'):\n try:\n # shutil的官方文档:https://docs.python.org/2/library/shutil.html\n shutil.copyfile('site_cfg_template.py', 'site_cfg.py')\n\n except:\n pass\n\ntry:\n import site_cfg\n\nexcept ImportError:\n site_cfg = None\n\nhas_attr = lambda obj, attr: obj and hasattr(obj, attr)\n\nclass Config(object):\n def python_version(self):\n if has_attr(site_cfg, 'python_version'):\n if site_cfg.python_version == 'auto':\n return \"%d.%d\" % tuple(sys.version_info[:2])\n else:\n return site_cfg.python_version\n else:\n return \"%d.%d\" % tuple(sys.version_info[:2])\n\n def python_include(self):\n if (has_attr(site_cfg, 'python_include')\n and (site_cfg.python_include != 'auto')):\n return site_cfg.python_include\n\n else:\n return sysconfig.get_config_var('INCLUDEPY')\n\n\n def system(self):\n if has_attr(site_cfg, 'system') and site_cfg.system is not None:\n return site_cfg.system\n else:\n if os.name in ['posix']:\n return 'posix'\n elif os.name in ['nt']:\n return 'windows'\n else:\n raise ValueError(msg_unknown_os)\n\n def compile_flags(self):\n if has_attr(site_cfg, 'compile_flags'):\n flags = site_cfg.compile_flags\n\n else:\n flags = '-g -O2'\n\n return flags.split()\n\n def link_flags(self):\n if has_attr(site_cfg, 'link_flags'):\n flags = site_cfg.link_flags\n\n else:\n flags = ''\n\n return flags.split()\n\n def debug_flags(self):\n if has_attr(site_cfg, 'debug_flags'):\n return site_cfg.debug_flags\n else:\n return ''\n\n def numpydoc_path(self):\n if (has_attr(site_cfg, 'numpydoc_path') and\n (site_cfg.numpydoc_path is not None)):\n return site_cfg.numpydoc_path\n\n else:\n try:\n import numpydoc\n except ImportError:\n raise ValueError(msg_numpydoc)\n\n def is_release(self):\n if has_attr(site_cfg, 'is_release'):\n return site_cfg.is_release\n else:\n return ''\n\n def tetgen_path(self):\n if has_attr(site_cfg, 'tetgen_path'):\n return site_cfg.tetgen_path\n else:\n return '/usr/bin/tetgen'\n","sub_path":"sfepy/sfepy/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"177884252","text":"#!/usr/bin/env python3\n\n# It doesn't matter which python3 is used for running this installation script,\n# as Thonny installation is not interfering with any specific Python version,\n# Python path won't be modified.\n\nimport sys\nimport os.path\nimport shutil\n\ndef replace_prefix_and_save_launcher(source_filename, target_filename):\n with open(source_filename) as f:\n content = f.read()\n\n target_dir = os.path.dirname(target_filename) \n if not os.path.exists(target_dir):\n os.makedirs(target_dir)\n with open(target_filename, mode=\"w\") as f:\n f.write(content.replace(\"$prefix\", prefix))\n \n # Seems that even desktop files have to be executable \n # https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles\n os.chmod(target_filename, 0o755)\n \n\nif len(sys.argv) == 2:\n prefix = os.path.expanduser(sys.argv[1].strip().rstrip(\"/\"))\nelse:\n print(\"\"\"Installer should be run with argument indicating the part of filesystem \nwhere Thonny should live. \n\nUsage examples for single user install:\n\n ./install ~/.local\n ./install /home/john/my_local_applications\n\nUsage examples for systemwide install:\n\n sudo ./install /usr\n sudo ./install /usr/local\n\"\"\")\n exit(1)\n \n\nsource_main_dir = os.path.dirname(os.path.realpath(__file__))\ntarget_main_dir = prefix + \"/lib/thonny\"\ntarget_script_path = prefix + \"/bin/thonny\"\nif prefix.startswith(\"/home\"):\n target_menu_dir = os.path.expanduser(\"~/.local/share/applications\")\nelse:\n target_menu_dir = \"/usr/share/applications\" \n\n\nif os.path.exists(target_main_dir):\n answer = input(target_main_dir + \" already exists, may I clear it before installing this version [Y/n]: \").strip()\n if not answer or answer.lower() == \"y\":\n shutil.rmtree(target_main_dir)\n\nprint(\"Copying files to \" + target_main_dir + \" ... \", end=\"\")\nshutil.copytree(source_main_dir + \"/thonny\", target_main_dir + \"/thonny\")\nprint(\"Done!\")\n\n\nprint(\"Creating executable \" + target_script_path + \" ... \", end=\"\")\nreplace_prefix_and_save_launcher(source_main_dir + \"/thonny.sh\", target_script_path)\nprint(\"Done!\")\n\n\nprint(\"Creating start menu item ... \", end=\"\")\nreplace_prefix_and_save_launcher(source_main_dir + \"/Thonny.desktop\",\n target_menu_dir + \"/Thonny.desktop\")\nprint(\"Done!\")\n\n\nprint(\"Creating desktop icon ... \", end=\"\")\nreplace_prefix_and_save_launcher(source_main_dir + \"/Thonny.desktop\",\n os.path.expanduser(\"~/Desktop/Thonny.desktop\"))\nprint(\"Done!\")\n\nprint()\nprint(\"Installation was successful, you can start Thonny from start menu or desktop\")\nprint()\n\n","sub_path":"installers/linux/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"603270442","text":"# coding: UTF-8\n\"\"\"\n @author: samuel ko\n @readme: StyleGAN2 PyTorch\n\"\"\"\nimport torchvision_sunner.transforms as sunnertransforms\nimport torchvision_sunner.data as sunnerData\nimport torchvision.transforms as transforms\n\nfrom torch.autograd import grad\n\nfrom network.stylegan2 import G_stylegan2, D_stylegan2\nfrom utils.utils import plotLossCurve, copy_G_params, load_params\nfrom loss.loss import D_logistic_r1, D_logistic_r2, G_logistic_ns_pathreg\nfrom opts.opts import TrainOptions, INFO\n\nfrom torchvision.utils import save_image\nfrom tqdm import tqdm\nfrom matplotlib import pyplot as plt\nimport torch.optim as optim\nimport numpy as np\nimport random\nimport torch\nimport os\n\n\n# Set random seem for reproducibility\n# manualSeed = 999\n#manualSeed = random.randint(1, 10000) # use if you want new results\n# print(\"Random Seed: \", manualSeed)\n# random.seed(manualSeed)\n# torch.manual_seed(manualSeed)\n\n# Hyper-parameters\nCRITIC_ITER = 3\nPL_DECAY = 0.01\nPL_WEIGHT = 2.0\nmoving_average = True\n\n\ndef main(opts):\n # Create the data loader\n loader = sunnerData.DataLoader(sunnerData.ImageDataset(\n root=[[opts.path]],\n transform=transforms.Compose([\n sunnertransforms.Resize((opts.resolution, opts.resolution)),\n sunnertransforms.ToTensor(),\n sunnertransforms.ToFloat(),\n sunnertransforms.Transpose(sunnertransforms.BHWC2BCHW),\n sunnertransforms.Normalize(),\n ])),\n batch_size=opts.batch_size,\n shuffle=True,\n drop_last=True\n )\n\n # Create the model\n start_epoch = 0\n G = G_stylegan2(fmap_base=opts.fmap_base,\n resolution=opts.resolution,\n mapping_layers=opts.mapping_layers,\n opts=opts,\n return_dlatents=True)\n D = D_stylegan2(fmap_base=opts.fmap_base,\n resolution=opts.resolution,\n structure='resnet')\n\n # Load the pre-trained weight\n if os.path.exists(opts.resume):\n INFO(\"Load the pre-trained weight!\")\n state = torch.load(opts.resume)\n G.load_state_dict(state['G'])\n D.load_state_dict(state['D'])\n start_epoch = state['start_epoch']\n else:\n INFO(\"Pre-trained weight cannot load successfully, train from scratch!\")\n\n # Multi-GPU support\n if torch.cuda.device_count() > 1:\n INFO(\"Multiple GPU:\" + str(torch.cuda.device_count()) + \"\\t GPUs\")\n G = torch.nn.DataParallel(G)\n D = torch.nn.DataParallel(D)\n G.to(opts.device)\n D.to(opts.device)\n\n # Create the criterion, optimizer and scheduler\n loss_type = 'styleGAN' # 'Rah' / 'styleGAN' / 'GAN'\n lr_D = 0.003\n lr_G = 0.003\n optim_D = torch.optim.Adam(D.parameters(), lr=lr_D, betas=(0.9, 0.999))\n # g_mapping has 100x lower learning rate\n params_G = [{\"params\": G.g_synthesis.parameters()},\n\t\t\t\t{\"params\": G.g_mapping.parameters(), \"lr\": lr_G * 0.01}]\n optim_G = torch.optim.Adam(params_G, lr=lr_G, betas=(0.9, 0.999))\n scheduler_D = optim.lr_scheduler.ExponentialLR(optim_D, gamma=0.99)\n scheduler_G = optim.lr_scheduler.ExponentialLR(optim_G, gamma=0.99)\n\n # Train\n if moving_average:\n avg_param_G = copy_G_params(G)\n fix_z = torch.randn([opts.batch_size, 512]).to(opts.device)\n softplus = torch.nn.Softplus()\n Loss_D_list = [0.0]\n Loss_G_list = [0.0]\n for ep in range(start_epoch, opts.epoch):\n bar = tqdm(loader)\n loss_D_list = []\n loss_G_list = []\n for i, (real_img,) in enumerate(bar):\n\n real_img = real_img.to(opts.device)\n latents = torch.randn([real_img.size(0), 512]).to(opts.device)\n\n # =======================================================================================================\n # (1) Update D network: D_logistic_r1(default)\n # =======================================================================================================\n # Compute adversarial loss toward discriminator\n real_img = real_img.to(opts.device)\n real_logit = D(real_img)\n fake_img, fake_dlatent = G(latents)\n fake_logit = D(fake_img.detach())\n\n if loss_type == 'styleGAN':\n d_loss = softplus(fake_logit)\n d_loss = d_loss + softplus(-real_logit)\n\n # original\n r1_penalty = D_logistic_r1(real_img.detach(), D)\n d_loss = (d_loss + r1_penalty).mean()\n # lite\n # d_loss = d_loss.mean()\n elif loss_type == 'Rah':\n # difference between real and fake:\n r_f_diff = real_logit - torch.mean(fake_logit)\n\n # difference between fake and real samples\n f_r_diff = fake_logit - torch.mean(real_logit)\n\n d_loss = (torch.mean(torch.nn.ReLU()(1 - r_f_diff))\n + torch.mean(torch.nn.ReLU()(1 + f_r_diff)))\n elif loss_type == 'GAN':\n import torch.nn as nn\n criterion = nn.BCEWithLogitsLoss()\n d_loss = (criterion(real_logit.squeeze(), torch.ones(real_img.size(0)).to(opts.device))\n + criterion(fake_logit.squeeze(), torch.zeros(fake_img.size(0)).to(opts.device)))\n\n else:\n print(\"Loss type not exist!\")\n exit()\n\n loss_D_list.append(d_loss.mean().item())\n\n # Update discriminator\n optim_D.zero_grad()\n d_loss.backward()\n optim_D.step()\n\n # =======================================================================================================\n # (2) Update G network: G_logistic_ns_pathreg(default)\n # =======================================================================================================\n # if i % CRITIC_ITER == 0:\n G.zero_grad()\n fake_scores_out = D(fake_img)\n if loss_type == 'styleGAN':\n _g_loss = softplus(-fake_scores_out)\n\n # Compute |J*y|.\n # pl_noise = (torch.randn(fake_img.shape) / np.sqrt(fake_img.shape[2] * fake_img.shape[3])).to(fake_img.device)\n # pl_grads = grad(torch.sum(fake_img * pl_noise), fake_dlatent, retain_graph=True)[0]\n # pl_lengths = torch.sqrt(torch.sum(torch.sum(torch.mul(pl_grads, pl_grads), dim=2), dim=1))\n # pl_mean = PL_DECAY * torch.sum(pl_lengths)\n #\n # pl_penalty = torch.mul(pl_lengths - pl_mean, pl_lengths - pl_mean)\n # reg = pl_penalty * PL_WEIGHT\n #\n # # original\n # g_loss = (_g_loss + reg).mean()\n # lite\n g_loss = _g_loss.mean()\n\n elif loss_type == 'Rah':\n real_scores_out = D(real_img)\n # difference between real and fake:\n r_f_diff = real_scores_out - torch.mean(fake_scores_out)\n\n # difference between fake and real samples\n f_r_diff = fake_scores_out - torch.mean(real_scores_out)\n\n # return the loss\n g_loss = (torch.mean(torch.nn.ReLU()(1 + r_f_diff))\n + torch.mean(torch.nn.ReLU()(1 - f_r_diff)))\n elif loss_type == 'GAN':\n import torch.nn as nn\n criterion = nn.BCEWithLogitsLoss()\n g_loss = criterion(fake_scores_out.squeeze(), torch.ones(fake_img.size(0)).to(opts.device))\n else:\n print(\"Loss type not exist!\")\n exit()\n loss_G_list.append(g_loss.mean().item())\n\n # Update generator\n g_loss.backward(retain_graph=True)\n optim_G.step()\n\n # Output training stats\n bar.set_description(\n \"Epoch {} [{}, {}] [G]: {} [D]: {}\".format(ep, i + 1, len(loader), loss_G_list[-1], loss_D_list[-1]))\n if moving_average:\n for p, avg_p in zip(G.parameters(), avg_param_G):\n avg_p.mul_(0.999).add_(0.001, p.data)\n\n # Save the result\n Loss_G_list.append(np.mean(loss_G_list))\n Loss_D_list.append(np.mean(loss_D_list))\n\n # Save model\n state = {\n 'G': G.state_dict(),\n 'D': D.state_dict(),\n 'Loss_G': Loss_G_list,\n 'Loss_D': Loss_D_list,\n 'start_epoch': ep,\n }\n torch.save(state, os.path.join(opts.det, 'models', 'all_model_epoch_%d.pth' % (ep)))\n\n # Check how the generator is doing by saving G's output on fixed_noise\n if moving_average:\n backup_para = copy_G_params(G)\n load_params(G, avg_param_G)\n with torch.no_grad():\n fake_img = G(fix_z)[0].detach().cpu()\n save_image(fake_img, os.path.join(opts.det, 'images', str(ep) + '.png'), nrow=5, normalize=True)\n # Save avg_G model\n torch.save(G.state_dict(), os.path.join(opts.det, 'models', 'Avg_G_epoch_%d.pth' % (ep)))\n\n if moving_average:\n load_params(G, backup_para)\n\n scheduler_D.step()\n scheduler_G.step()\n\n # Plot the total loss curve\n Loss_D_list = Loss_D_list[1:]\n Loss_G_list = Loss_G_list[1:]\n plotLossCurve(opts, Loss_D_list, Loss_G_list)\n\n\nif __name__ == '__main__':\n opts = TrainOptions().parse()\n main(opts)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"252655820","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n Author: kun.wang\n Create: 2015-06-24\n\nusing: PySide\n\"\"\"\n\nimport sys\n# import PySide.QtCore as QtCore\nimport PySide.QtGui as QtGui\n\nfrom attribute_editor import TaskAttribEditor\n\n\nclass TaskEditor(QtGui.QWidget):\n def __init__(self, parent=None):\n super(TaskEditor, self).__init__(parent)\n\n self.main_layout = QtGui.QVBoxLayout()\n self.main_layout.setContentsMargins(5, 10, 0, 0)\n self.setLayout(self.main_layout)\n\n self.attrib_editor = TaskAttribEditor()\n self.attrib_editor.setMaximumWidth(300)\n self.main_layout.addWidget(self.attrib_editor)\n\n self.body = QtGui.QTabWidget()\n self.main_layout.addWidget(self.body)\n\n self.body.currentChanged.connect(self.on_tab_change)\n\n def load(self):\n self.attrib_editor.load()\n editor = self.body.currentWidget()\n if hasattr(editor, 'load'):\n editor.load()\n\n def on_tab_change(self, index):\n editor = self.body.widget(index)\n if hasattr(editor, 'load'):\n editor.load()\n\n\nif __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n\n a = TaskEditor()\n a.resize(900, 600)\n a.show()\n\n sys.exit(app.exec_())\n\n\n\n","sub_path":"OpenCGPipeline/HoneyMongo/honey_gui/task_ui/task_editor.py","file_name":"task_editor.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"514686756","text":"# -*- coding: UTF-8 -*-\n\ntry:\n from tkinter import *\nexcept ImportError:\n from Tkinter import *\nfrom tkinter import ttk\nfrom threading import Thread\nfrom time import strftime\nimport pycep_correios\nfrom datetime import date\nimport sqlite3\nfrom tkinter import messagebox as mb\nimport sys\n\nconexao = sqlite3.connect('escola2.db')\nconexao.cursor()\nc = conexao\n\nclass Tela(Thread):\n def __init__(self, root):\n self.root = root\n self.root.geometry('800x800')\n #self.root.state(\"zoomed\")\n\n self.menuwidget = Menu(root)\n self.filemenu = Menu(self.menuwidget)\n self.filemenu1 = Menu(self.menuwidget)\n self.filemenu2 = Menu(self.menuwidget)\n self.filemenu3 = Menu(self.menuwidget)\n\n self.menuwidget.add_cascade(label='CONFIGURAÇÕES', menu=self.filemenu)\n self.filemenu.add_command(label='Cargo', command='')\n self.filemenu.add_command(label='Backgroud', command='')\n self.filemenu.add_command(label='Turmas', command='')\n #self.filemenu.add_command(label='Habilitar Login', command='')\n #self.filemenu.add_command(label='Usuários', command='')\n self.filemenu.add_command(label='SAIR', command=self.root.destroy)\n\n self.menuwidget.add_cascade(label='CADASTROS', menu=self.filemenu1)\n self.filemenu1.add_command(label='Aluno', command=self.cadastro_aluno)\n self.filemenu1.add_command(label='Funcionário', command=self.cadastro_funcionario)\n\n self.menuwidget.add_cascade(label='AVALIAÇÕES', menu=self.filemenu2)\n self.filemenu2.add_command(label='none', command='')\n self.filemenu2.add_command(label='none', command='')\n self.filemenu2.add_command(label='none', command='')\n\n self.menuwidget.add_cascade(label='RELATÓRIOS', menu=self.filemenu3)\n self.filemenu3.add_command(label='none', command='')\n self.filemenu3.add_command(label='none', command='')\n self.filemenu3.add_command(label='none', command='')\n\n\n self.root.config(menu=self.menuwidget)\n\n super(Tela, self).__init__()\n\n\n #------------------------------------------------------------------------------------------\n\n #FUNÇÃO PARA LIMITAR ENTRYS\n def on_write(self,*args):\n self.s = self.var.get()\n if len(self.s) > 0:\n if not self.s[-1].isdigit(): # retirar ultimo caracter caso nao seja digito\n self.var.set(self.s[:-1])\n else: # aproveitar apenas os primeiros 5 chars\n self.var.set(self.s[:self.max_len])\n\n #-----------------------TOP LEVEL ALUNO---------------------------------------------------\n def cadastro_aluno(self):\n\n #PEQUENA FUNÇÃO PARA LIMITAR OS CARACTERES NOS ENTRYS\n self.max_len = 11 # maximo num de caracteres\n self.var = StringVar()\n self.var.trace(\"w\", self.on_write) # rastrear valor da variavel e executar funcao de validacao quando mudar\n\n self.cad = Toplevel(self.root)\n self.cad.title('Cadastro de Aluno')\n self.cad.grid()\n #self.cad.focus_force() #\n self.cad.grab_set() #\n self.cad.geometry('600x560')\n self.cad.resizable(width=False, height=False)\n\n\n self.lin = Label(self.cad, text='-' * 150)\n self.lin.place(x=0, y=5)\n self.tt1 = Label(self.cad, text='DADOS PESSOAIS')\n self.tt1[\"font\"] = (\"Calibri\", \"13\", \"bold\")\n self.tt1.place(x=0, y=5)\n\n self.nome = Label(self.cad, text='Nome: ')\n self.nome.place(x=10, y=50)\n self.n_nome = Entry(self.cad, width=80)\n self.n_nome.focus_force() # MANTER O FOCO NO ENTRY\n self.n_nome.place(x=70, y=50)\n\n self.cpf = Label(self.cad, text='CPF: ')\n self.cpf.place(x=10, y=100)\n self.n_cpf = Entry(self.cad, width=20, textvariable=self.var)\n self.n_cpf.focus_force() # MANTER O FOCO NO ENTRY\n self.n_cpf.place(x=70, y=100)\n\n self.max_len = 8 # maximo num de caracteres\n self.var = StringVar()\n self.var.trace(\"w\", self.on_write) # rastrear valor da variavel e executar funcao de validacao quando mudar\n\n self.rg = Label(self.cad, text='RG: ')\n self.rg.place(x=350, y=100)\n self.n_rg = Entry(self.cad, width=25,textvariable=self.var )\n self.n_rg.focus_force() # MANTER O FOCO NO ENTRY\n self.n_rg.place(x=400, y=100)\n\n self.nasc = Label(self.cad, text='Data de nascimento: ')\n self.nasc.place(x=10, y=150)\n self.dia = Entry(self.cad, width=5)\n self.mes = Entry(self.cad, width=5)\n self.ano = Entry(self.cad, width=10)\n self.dia.place(x=130, y=150)\n self.mes.place(x=160, y=150)\n self.ano.place(x=190, y=150)\n #self.data = (f'{1} / {2} / {3}'.format(self.dia.get(), self.mes.get(), self.ano.get()))\n\n self.sexo = Label(self.cad, text='Sexo: ')\n self.sexo.place(x=350, y=150)\n self.itens1 = ['Selecione', 'MASCULINO', 'FEMININO']\n self.n_sexo = ttk.Combobox(self.cad, width=22)\n self.n_sexo[\"values\"] = self.itens1\n self.n_sexo.current(0)\n self.n_sexo.bind(\"<>\")\n self.n_sexo.place(x=400, y=150)\n\n #1° fase do EJA Corresponde do 1º ao 5º ano do Ensino Regular (séries iniciais do Ensino Fundamental)\n self.esc = Label(self.cad, text='Escolaridade: ')\n self.esc.place(x=10, y=200)\n self.itens2 = ['Selecione', '1° ano', '2° ano', '3° ano', '4° ano', '5° ano']\n self.n_esc = ttk.Combobox(self.cad, width=15)\n self.n_esc[\"values\"] = self.itens2\n self.n_esc.current(0)\n self.n_esc.bind(\"<>\")\n self.n_esc.place(x=100, y=200)\n\n self.sit = Label(self.cad, text='Situação: ')\n self.sit.place(x=235, y=200)\n self.itens3 = ['Selecione', 'Cursando','Reprovado', 'Aprovado']\n self.n_sit = ttk.Combobox(self.cad, width=9)\n self.n_sit[\"values\"] = self.itens3\n self.n_sit.current(0)\n self.n_sit.bind(\"<>\")\n self.n_sit.place(x=300, y=200)\n\n self.hist = Label(self.cad, text='Histórico entregue? ')\n self.hist.place(x=400, y=200)\n self.itens3 = ['', 'SIM', 'NÃO']\n self.n_hist = ttk.Combobox(self.cad, width=4)\n self.n_hist[\"values\"] = self.itens3\n self.n_hist.current(0)\n self.n_hist.bind(\"<>\")\n self.n_hist.place(x=509, y=200)\n\n #************************************************************#\n\n self.lin1 = Label(self.cad, text='-' * 150)\n self.lin1.place(x=0, y=250)\n self.tt2 = Label(self.cad, text='RESPONSÁVEL ')\n self.tt2[\"font\"] = (\"Calibri\", \"13\", \"bold\")\n self.tt2.place(x=0, y=250)\n\n self.nome_resp = Label(self.cad, text='Nome: ')\n self.nome_resp.place(x=10, y=300)\n self.n_nome_resp = Entry(self.cad, width=30)\n self.n_nome_resp.focus_force() # MANTER O FOCO NO ENTRY\n self.n_nome_resp.place(x=70, y=300)\n\n self.cpf_resp = Label(self.cad, text='CPF: ')\n self.cpf_resp.place(x=270, y=300)\n self.n_cpf_resp = Entry(self.cad, width=16)\n self.n_cpf_resp.focus_force() # MANTER O FOCO NO ENTRY\n self.n_cpf_resp.place(x=310, y=300)\n\n self.fone = Label(self.cad, text='Fone: ')\n self.fone.place(x=430, y=300)\n self.n_fone = Entry(self.cad, width=13)\n self.n_fone.focus_force() # MANTER O FOCO NO ENTRY\n self.n_fone.place(x=470, y=300)\n\n #************************************************************#\n\n self.lin2 = Label(self.cad, text='-'*250)\n self.lin2.place(x=0 , y=350)\n self.tt3 = Label(self.cad, text='ENDEREÇO')\n self.tt3[\"font\"] = (\"Calibri\", \"13\", \"bold\")\n self.tt3.place(x=0, y=350)\n\n self.cep = Label(self.cad, text='CEP: ')\n self.cep.place(x=10, y=400)\n self.n_cep = Entry(self.cad, width=20)\n self.n_cep.focus_force() # MANTER O FOCO NO ENTRY\n self.n_cep.place(x=70, y=400)\n self.b_cep = Button(self.cad, text='Buscar', command=self.pesquisa_cep_aluno)\n self.b_cep.place(x=200, y=395)\n\n self.cid = Label(self.cad, text='Cidade: ')\n self.cid.place(x=270, y=400)\n self.n_cid = Entry(self.cad, width=15)\n self.n_cid.focus_force() # MANTER O FOCO NO ENTRY\n self.n_cid.place(x=320, y=400)\n\n self.uf = Label(self.cad, text='UF: ')\n self.uf.place(x=440, y=400)\n self.itens = ['Selecione', 'AC', 'AL', 'AM', 'AP', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MG', 'MS'\n , 'MT', 'PA', 'PB', 'PE', 'PI', 'PR', 'RJ', 'RN', 'RO', 'RR', 'RS', 'SC', 'SE', 'SP', 'TO']\n self.n_uf = ttk.Combobox(self.cad, width=10)\n self.n_uf[\"values\"] = self.itens\n self.n_uf.current(0)\n self.n_uf.bind(\"<>\")\n self.n_uf .place(x=470, y=400)\n\n self.bai = Label(self.cad, text='Bairro: ')\n self.bai.place(x=10, y=450)\n self.n_bai = Entry(self.cad, width=20)\n self.n_bai.focus_force() # MANTER O FOCO NO ENTRY\n self.n_bai.place(x=70, y=450)\n\n self.rua = Label(self.cad, text='Rua: ')\n self.rua.place(x=200, y=450)\n self.n_rua = Entry(self.cad, width=30)\n self.n_rua.focus_force() # MANTER O FOCO NO ENTRY\n self.n_rua.place(x=250, y=450)\n\n self.casa = Label(self.cad, text='Casa N°: ')\n self.casa.place(x=440, y=450)\n self.n_casa = Entry(self.cad, width=8)\n self.n_casa.focus_force() # MANTER O FOCO NO ENTRY\n self.n_casa.place(x=500, y=450)\n\n self.b_save = Button(self.cad, text='Salvar', command=self.save_aluno)\n self.b_save[\"font\"] = (\"Arial\", \"10\", \"bold\")\n self.b_save.place(x=90, y=500)\n\n self.b_limpa = Button(self.cad, text='Limpar', command=self.limpa_tela_aluno)\n self.b_limpa[\"font\"] = (\"Arial\", \"10\", \"bold\")\n self.b_limpa.place(x=150, y=500)\n\n self.b_busca = Button(self.cad, text='Buscar', command=self.pesquisa_aluno)\n self.b_busca[\"font\"] = (\"Arial\", \"10\", \"bold\")\n self.b_busca.place(x=250, y=500)\n\n self.b_busca = Button(self.cad, text='Alterar', command='')\n self.b_busca[\"font\"] = (\"Arial\", \"10\", \"bold\")\n self.b_busca.place(x=300, y=500)\n\n self.b_excluir = Button(self.cad, text='Excluir', command='')\n self.b_excluir[\"font\"] = (\"Arial\", \"10\", \"bold\")\n self.b_excluir.place(x=400, y=500)\n\n self.b_sair = Button(self.cad, text='Sair', command=self.cad.destroy)\n self.b_sair[\"font\"] = (\"Arial\", \"10\", \"bold\")\n self.b_sair.place(x=500, y=500)\n\n self.cad.mainloop()\n\n#---------------------FUNÇÕES--------------------------------------------------------------------\n def pesquisa_cep_aluno(self):\n #OBS: HÁ A NECESSIDADE DE ACESSO A INTERNET PARA USAR ESTA FUNÇÃO\n try:\n print(self.n_cep.get())\n self.endereco = pycep_correios.consultar_cep(self.n_cep.get())\n print(self.endereco)\n print(self.endereco['cidade'])\n\n #limpa os Entrys para nao haja repetição em caso de varios cliks na função pesquisar\n self.n_cid.delete(0, END)\n self.n_uf.delete(0, END)\n self.n_bai.delete(0, END)\n self.n_rua.delete(0, END)\n\n self.n_cid.insert(END, self.endereco['cidade'])\n self.n_bai.insert(END, self.endereco['bairro'])\n self.n_uf.delete(0, END)\n self.n_uf.insert(END, self.endereco['uf'])\n self.n_rua.insert(END, self.endereco['end'])\n except:\n mb.showinfo('Aviso', 'Desculpe! talvez este CEP não exista ou você está sem acesso a internet. Por favor verifcar sua conexão ou o campo CEP.')\n print('CEP INVÁLIDO')\n print(sys.exc_info())\n\n def save_aluno(self):\n try:\n self.nome_aluno = self.n_nome.get().strip().title()\n self.cpf_aluno = self.n_cpf.get().strip()\n self.rg_aluno = self.n_rg.get().strip()\n self.nasc_aluno = self.dia.get() + '/' + self.mes.get()+ '/' + self.ano.get()\n self.sexo_aluno = self.n_sexo.get()\n self.esc_aluno = self.n_esc.get()\n self.sit_aluno = self.n_sit.get()\n self.hist_aluno = self.n_hist.get()\n\n self.nome_res = self.n_nome_resp.get().strip().title()\n self.cpf_res = self.n_nome_resp.get().strip\n self.fone_res = self.n_fone.get()\n\n self.cep_aluno = self.n_cep.get()\n self.cid_aluno = self.n_cid.get()\n self.uf_aluno = self.n_uf.get()\n self.bai_aluno = self.n_bai.get()\n self.rua_aluno = self.n_rua.get()\n self.casa_aluno = self.n_casa.get()\n\n print('ok')\n\n except:\n print('ERRO NA FUNÇÃO SALVAR PEGANDO OS DADOS DOS ENTRYS')\n print(sys.exc_info())\n\n\n try:\n con = sqlite3.connect('escola2.db')\n cursor = con.cursor()\n\n cursor.execute('''\n INSERT INTO aluno(nm_aluno, nr_cpf, nr_rg, dta_nasc, escol, tp_sexo, sit, hist)\n VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')\n '''%(self.nome_aluno,self.cpf_aluno,self.rg_aluno,self.nasc_aluno,self.esc_aluno,self.sexo_aluno,self.sit_aluno,self.hist_aluno))\n con.commit()\n\n\n #CASO FOR NECESSÁRIO VAI SER USADO O CADASTRO DO RESPONSÁVEL\n\n cursor.execute('''\n INSERT INTO responsavel(nome_resp, cpf_resp, fone_resp)\n VALUES ('%s', '%s', '%s')\n '''%(self.nome_resp, self.cpf_resp, self.fone_res))\n\n cursor.execute('''\n INSERT INTO endereco(cep, cidade, uf, bairro, rua, n_casa)\n VALUES ('%s', '%s', '%s', '%s', '%s', '%s')\n '''%(self.cep_aluno, self.cid_aluno, self.uf_aluno, self.bai_aluno, self.rua_aluno, self.casa_aluno))\n\n con.commit()\n mb.showinfo('SALVO', 'SALVO COM SUCESSO')\n con.close()\n\n except:\n\n mb.showerror('ERROR! DESCULPE NÃO FOI POSSIVEL SALVAR!', sys.exc_info()[1:])\n print(sys.exc_info())\n\n self.limpa_tela_aluno()\n\n def limpa_tela_aluno(self):\n self.n_nome.delete(0, END)\n self.n_rg.delete(0, END)\n self.n_cpf.delete(0, END)\n self.dia.delete(0, END)\n self.mes.delete(0, END)\n self.ano.delete(0, END)\n self.n_sexo.delete(0, END)\n self.n_uf.insert(END, 'Selecione')\n self.n_esc.delete(0, END)\n self.n_esc.insert(END, 'Selecione')\n self.n_sit.delete(0, END)\n self.n_sit.insert(END, 'Selecione')\n self.n_nome_resp.delete(0, END)\n self.n_cpf_resp.delete(0, END)\n self.n_fone.delete(0, END)\n self.n_cep.delete(0, END)\n self.n_cid.delete(0, END)\n self.n_uf.delete(0, END)\n self.n_uf.insert(END, 'Selecione')\n self.n_rua.delete(0, END)\n self.n_rua.delete(0, END)\n self.n_bai.delete(0, END)\n self.n_casa.delete(0, END)\n self.n_hist.delete(0, END)\n\n def pesquisa_aluno(self):\n con = sqlite3.connect('escola2.db')\n cursor = con.cursor()\n self.au = ('''SELECT nr_cpf, nm_aluno, nr_rg, dta_nasc, escol, tp_sexo, sit, hist, id_aluno from aluno where nr_cpf = (?)''')\n self.sc = ''' SELECT cep, cidade, uf, bairro, rua, n_casa \n FROM endereco a\n INNER JOIN aluno b on a.id_endereco = b.id_aluno '''\n self.x = self.n_cpf.get()\n cursor.execute(self.au, [self.n_cpf.get()])\n cursor.executescript(self.sc)\n busca = cursor.fetchall()\n for i in busca:\n if self.n_cpf.get() in i:\n self.n_cpf.delete(0, END)\n self.backup = i[0]\n self.n_cpf.insert(END, i[0])\n self.n_nome.insert(END, i[1])\n self.n_rg.insert(END, i[2])\n self.dia.insert(END, i[3])\n self.mes.insert(END, i[3])\n self.ano.insert(END, i[3])\n self.n_esc.delete(0, END)\n self.n_esc.insert(END, i[4])\n self.n_sexo.delete(0, END)\n self.n_sexo.insert(END, i[5])\n self.n_sit.delete(0, END)\n self.n_sit.insert(END, i[6])\n self.n_hist.delete(0, END)\n self.n_hist.insert(END, i[7])\n print(i[8])\n print(i)\n\n\n # self.n_uf.insert(END, 'Selecione')\n # self.n_esc.delete(0, END)\n # self.n_esc.insert(END, 'Selecione')\n # self.n_sit.delete(0, END)\n # self.n_sit.insert(END, 'Selecione')\n # self.n_nome_resp.delete(0, END)\n # self.n_cpf_resp.delete(0, END)\n # self.n_fone.delete(0, END)\n # self.n_cep.delete(0, END)\n # self.n_cid.delete(0, END)\n # self.n_uf.delete(0, END)\n # self.n_uf.insert(END, 'Selecione')\n # self.n_rua.delete(0, END)\n # self.n_rua.delete(0, END)\n # self.n_bai.delete(0, END)\n # self.n_casa.delete(0, END)\n # self.n_hist.delete(0, END)\n\n\n\n\n\n\n #-------------------TOP LEVEL FUNCIONÁRIO-----------------------------------\n\n def cadastro_funcionario(self):\n self.cadf = Toplevel(self.root)\n self.cadf.title('Cadastro de Funcionário')\n self.cadf.grid()\n self.cadf.focus_force() #\n self.cadf.grab_set() #\n self.cadf.geometry('600x350')\n self.cadf.resizable(width=False, height=False)\n\n self.lin = Label(self.cadf, text='-' * 150)\n self.lin.place(x=0, y=5)\n self.tt1 = Label(self.cadf, text='CADASTRO')\n self.tt1[\"font\"] = (\"Calibri\", \"13\", \"bold\")\n self.tt1.place(x=0, y=5)\n\n self.nome_f = Label(self.cadf, text='Nome: ')\n self.nome_f.place(x=10, y=50)\n self.n_nome_f = Entry(self.cadf, width=80)\n self.n_nome_f.focus_force()\n self.n_nome_f.place(x=70, y=50)\n #self.n_nome_f.config(state='disabled')\n\n self.cpf_f = Label(self.cadf, text='CPF: ')\n self.cpf_f.place(x=10, y=100)\n self.n_cpf_f = Entry(self.cadf, width=45)\n self.n_cpf_f.focus_force() # MANTER O FOCO NO ENTRY\n self.n_cpf_f.place(x=70, y=100)\n\n self.rg_f = Label(self.cadf, text='RG: ')\n self.rg_f.place(x=350, y=100)\n self.n_rg_f = Entry(self.cadf, width=25)\n self.n_rg_f.focus_force() # MANTER O FOCO NO ENTRY\n self.n_rg_f.place(x=400, y=100)\n\n self.nasc_f = Label(self.cadf, text='Data de nascimento: ')\n self.nasc_f.place(x=10, y=150)\n self.n_nasc_f = Entry(self.cadf, width=32)\n self.n_nasc_f.focus_force() # MANTER O FOCO NO ENTRY\n self.n_nasc_f.place(x=150, y=150)\n\n self.sexo_f = Label(self.cadf, text='Sexo: ')\n self.sexo_f.place(x=350, y=150)\n self.itens = ['Selecione', 'MASCULINO', 'FEMININO']\n self.n_sexo_f = ttk.Combobox(self.cadf, width=22)\n self.n_sexo_f[\"values\"] = self.itens\n self.n_sexo_f.current(0)\n self.n_sexo_f.bind(\"<>\")\n self.n_sexo_f.place(x=400, y=150)\n\n self.fone_f = Label(self.cadf, text='Fone: ')\n self.fone_f.place(x=10, y=200)\n self.n_fone_f = Entry(self.cadf, width=30)\n self.n_fone_f.focus_force() # MANTER O FOCO NO ENTRY\n self.n_fone_f.place(x=70, y=200)\n\n self.cargo = Label(self.cadf, text='Cargo: ')\n self.cargo.place(x=300, y=200)\n self.itens1 = ['Selecione', 'MASCULINO', 'FEMININO']\n self.n_cargo = ttk.Combobox(self.cadf, width=30)\n self.n_cargo[\"values\"] = self.itens1\n self.n_cargo.current(0)\n self.n_cargo.bind(\"<>\")\n self.n_cargo.place(x=350, y=200)\n\n self.b_save_f = Button(self.cadf, text='Salvar', command='')\n self.b_save_f[\"font\"] = (\"Arial\", \"10\", \"bold\")\n self.b_save_f.place(x=90, y=300)\n\n self.b_limpa_f = Button(self.cadf, text='Limpar', command='')\n self.b_limpa_f[\"font\"] = (\"Arial\", \"10\", \"bold\")\n self.b_limpa_f.place(x=190, y=300)\n\n self.b_busca_f = Button(self.cadf, text='Alterar', command='')\n self.b_busca_f[\"font\"] = (\"Arial\", \"10\", \"bold\")\n self.b_busca_f.place(x=290, y=300)\n\n self.b_excluir_f = Button(self.cadf, text='Excluir', command='')\n self.b_excluir_f[\"font\"] = (\"Arial\", \"10\", \"bold\")\n self.b_excluir_f.place(x=400, y=300)\n\n self.b_sair_f = Button(self.cadf, text='Sair', command=self.cadf.destroy)\n self.b_sair_f[\"font\"] = (\"Arial\", \"10\", \"bold\")\n self.b_sair_f.place(x=500, y=300)\n\n self.cadf.mainloop()\n\n def run(self):\n self.lbr = Label(self.root)\n self.lbr.pack(side='top') #top, bottom, left, or right\n\n self.lbr['text'] = strftime('%H:%M:%S') # formato de hora\n self.lbr['font'] = 'Helvita 10 bold' # define a fonte do relogio\n self.lbr['foreground'] = 'black' # define a cor dos numeros\n #self.lbr['bg'] = 'gray' # define a cor do fundo bg e a abreviatura de background\n self.contador()\n\n #----------------RELOGIO USANDO THREDE----------------------------------------------------\n\n def contador(self):\n self.agora = strftime('%H:%M:%S')\n if self.lbr['text'] != self.agora:\n self.lbr['text'] = self.agora\n self.lbr.after(100, self.contador)\n\n\n\na = Tk()\nb = Tela(a)\nb.start()\na.mainloop()","sub_path":"Aulas - UNIMETA (ITALO)/TRABALHOS/ESTUDO DE CASO.py","file_name":"ESTUDO DE CASO.py","file_ext":"py","file_size_in_byte":21765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"160989279","text":"import asyncio\nimport time\nfrom concurrent.futures import CancelledError\nfrom datetime import datetime\n\nfrom discord import Forbidden, Embed, NotFound, PermissionOverwrite\nfrom discord.ext import commands\nfrom discord.ext.commands import Context, command\n\nimport prometheus_client as prom\n\nfrom cogs.BaseCog import BaseCog\nfrom utils import Questions, Emoji, Utils, Configuration, Lang\nfrom utils.Database import BugReport, Attachments\n\n\nclass Bugs(BaseCog):\n\n def __init__(self, bot):\n super().__init__(bot)\n bot.loop.create_task(self.startup_cleanup())\n self.bug_messages = set()\n self.in_progress = dict()\n self.sweeps = dict()\n self.blocking = set()\n m = self.bot.metrics\n m.reports_in_progress.set_function(lambda: len(self.in_progress))\n\n async def sweep_trash(self, user):\n await asyncio.sleep(Configuration.get_var(\"bug_trash_sweep_minutes\")*60)\n if user.id in self.in_progress:\n if not self.in_progress[user.id].done() or not self.in_progress[user.id].cancelled():\n await user.send(Lang.get_string(\"bugs/sweep_trash\"))\n\n await self.delete_progress(user.id)\n\n async def delete_progress(self, uid):\n if uid in self.in_progress:\n self.in_progress[uid].cancel()\n del self.in_progress[uid]\n if uid in self.sweeps:\n self.sweeps[uid].cancel()\n\n async def shutdown(self):\n for name, cid in Configuration.get_var(\"channels\").items():\n channel = self.bot.get_channel(cid)\n message = await channel.send(Lang.get_string(\"bugs/shutdown_message\"))\n Configuration.set_persistent_var(f\"{name}_shutdown\", message.id)\n\n async def startup_cleanup(self):\n for name, cid in Configuration.get_var(\"channels\").items():\n channel = self.bot.get_channel(cid)\n shutdown_id = Configuration.get_persistent_var(f\"{name}_shutdown\")\n if shutdown_id is not None:\n message = await channel.fetch_message(shutdown_id)\n if message is not None:\n await message.delete()\n Configuration.set_persistent_var(f\"{name}_shutdown\", None)\n await self.send_bug_info(name)\n\n async def send_bug_info(self, key):\n channel = self.bot.get_channel(Configuration.get_var(\"channels\")[key])\n bug_info_id = Configuration.get_persistent_var(f\"{key}_message\")\n if bug_info_id is not None:\n try:\n message = await channel.fetch_message(bug_info_id)\n except NotFound:\n pass\n else:\n await message.delete()\n if message.id in self.bug_messages:\n self.bug_messages.remove(message.id)\n\n bugemoji = Emoji.get_emoji('BUG')\n message = await channel.send(Lang.get_string(\"bugs/bug_info\", bug_emoji=bugemoji))\n await message.add_reaction(bugemoji)\n self.bug_messages.add(message.id)\n Configuration.set_persistent_var(f\"{key}_message\", message.id)\n\n @commands.command(aliases=[\"bugmaint\"])\n @commands.guild_only()\n @commands.is_owner()\n async def bug_maintenance(self, ctx, active: bool):\n member_role = ctx.guild.get_role(Configuration.get_var(\"member_role\"))\n\n if active:\n if len(self.in_progress) > 0:\n await ctx.send(f\"There are {len(self.in_progress)} report(s) in progress. Not activating maintenance mode.\")\n return\n await ctx.send(\"setting bug maintenance mode **on**\")\n else:\n await ctx.send(\"setting bug maintenance mode **off**\")\n pass\n\n # show/hide maintenance channel\n maint_message_channel = self.bot.get_channel(Configuration.get_var(\"bug_maintenance_channel\"))\n\n overwrite = maint_message_channel.overwrites[member_role]\n overwrite.read_messages = active\n await maint_message_channel.set_permissions(member_role, overwrite=overwrite)\n\n for name, cid in Configuration.get_var(\"channels\").items():\n # show/hide reporting channels\n channel = self.bot.get_channel(cid)\n overwrite = channel.overwrites[member_role]\n overwrite.read_messages = None if active else True\n await channel.set_permissions(member_role, overwrite=overwrite)\n\n @commands.group(name='bug', invoke_without_command=True)\n async def bug(self, ctx: Context):\n # remove command to not flood chat (unless we are in a DM already)\n if ctx.guild is not None:\n await ctx.message.delete()\n await self.report_bug(ctx.author, ctx.channel)\n\n @commands.guild_only()\n @bug.command(aliases=[\"resetactive\", \"reset_in_progress\", \"resetinprogress\", \"reset\", \"clean\"])\n async def reset_active(self, ctx):\n is_owner = await ctx.bot.is_owner(ctx.author)\n if is_owner:\n to_kill = len(self.in_progress)\n active_keys = self.in_progress.keys()\n for uid in active_keys:\n await self.delete_progress(uid)\n self.in_progress = dict()\n await ctx.send(f\"Ok. Number of dead bugs cleaned up: {active_keys}. Number still alive: {len(self.in_progress)}\")\n\n async def report_bug(self, user, trigger_channel):\n # fully ignore muted users\n m = self.bot.metrics\n await asyncio.sleep(1)\n guild = self.bot.get_guild(Configuration.get_var(\"guild_id\"))\n member = guild.get_member(user.id)\n mute_role = guild.get_role(Configuration.get_var(\"muted_role\"))\n if member is None:\n # user isn't even on the server, how did we get here?\n return\n if mute_role in member.roles:\n # muted, hard ignore\n return\n\n if user.id in self.in_progress:\n # already tracking progress for this user\n if user.id in self.blocking:\n # user blocked from starting a new report. waiting for DM response\n await trigger_channel.send(Lang.get_string(\"bugs/stop_spamming\", user=user.mention), delete_after=10)\n return\n\n should_reset = False\n\n async def start_over():\n nonlocal should_reset\n should_reset = True\n\n # block more clicks to the initial trigger\n self.blocking.add(user.id)\n\n # ask if user wants to start over\n await Questions.ask(self.bot, trigger_channel, user, Lang.get_string(\"bugs/start_over\", user=user.mention),\n [\n Questions.Option(\"YES\", Lang.get_string(\"bugs/start_over_yes\"), handler=start_over),\n Questions.Option(\"NO\", Lang.get_string(\"bugs/start_over_no\"))\n ], delete_after=True, show_embed=True)\n\n # not starting over. remove blocking\n if user.id in self.blocking:\n self.blocking.remove(user.id)\n\n # cancel running task, delete progress, and fall through to start a new report\n await self.delete_progress(user.id)\n if not should_reset:\n # in-progress report should not be reset. bail out\n return\n\n # Start a bug report\n task = self.bot.loop.create_task(self.actual_bug_reporter(user, trigger_channel))\n sweep = self.bot.loop.create_task(self.sweep_trash(user))\n self.in_progress[user.id] = task\n self.sweeps[user.id] = sweep\n try:\n await task\n except CancelledError as ex:\n pass\n\n async def actual_bug_reporter(self, user, trigger_channel):\n # wrap everything so users can't get stuck in limbo\n m = self.bot.metrics\n active_question = None\n restarting = False\n try:\n channel = await user.create_dm()\n\n # vars to store everything\n asking = True\n platform = \"\"\n branch = \"\"\n app_build = None\n additional = False\n additional_text = \"\"\n attachments = False\n attachment_links = []\n report = None\n\n # define all the parts we need as inner functions for easier sinfulness\n\n async def abort():\n nonlocal asking\n await user.send(Lang.get_string(\"bugs/abort_report\"))\n asking = False\n m.reports_abort_count.inc()\n m.reports_exit_question.observe(active_question)\n await self.delete_progress(user.id)\n\n def set_platform(p):\n nonlocal platform\n platform = p\n\n def set_branch(b):\n nonlocal branch\n branch = b\n\n def add_additional():\n nonlocal additional\n additional = True\n\n def add_attachments():\n nonlocal attachments\n attachments = True\n\n def verify_version(v):\n if \"latest\" in v:\n return Lang.get_string(\"bugs/latest_not_allowed\")\n # TODO: double check if we actually want to enforce this\n if len(Utils.NUMBER_MATCHER.findall(v)) is 0:\n return Lang.get_string(\"bugs/no_numbers\")\n if len(v) > 20:\n return Lang.get_string(\"bugs/love_letter\")\n return True\n\n def max_length(length):\n def real_check(text):\n if len(text) > length:\n return Lang.get_string(\"bugs/text_too_long\", max=length)\n return True\n\n return real_check\n\n async def send_report():\n # save report in the database\n br = BugReport.create(reporter=user.id, platform=platform, deviceinfo=deviceinfo,\n platform_version=platform_version, branch=branch, app_version=app_version,\n app_build=app_build, title=title, steps=steps, expected=expected, actual=actual,\n additional=additional_text)\n for url in attachment_links:\n Attachments.create(report=br, url=url)\n\n # send report\n channel_name = f\"{platform}_{branch}\".lower()\n c = Configuration.get_var(\"channels\")[channel_name]\n message = await self.bot.get_channel(c).send(\n content=Lang.get_string(\"bugs/report_header\", id=br.id, user=user.mention), embed=report)\n if len(attachment_links) is not 0:\n key = \"attachment_info\" if len(attachment_links) is 1 else \"attachment_info_plural\"\n attachment = await self.bot.get_channel(c).send(\n Lang.get_string(f\"bugs/{key}\", id=br.id, links=\"\\n\".join(attachment_links)))\n br.attachment_message_id = attachment.id\n br.message_id = message.id\n br.save()\n await channel.send(Lang.get_string(\"bugs/report_confirmation\", channel_id=c))\n await self.send_bug_info(channel_name)\n\n async def restart():\n nonlocal restarting\n restarting = True\n m.reports_restarted.inc()\n await self.delete_progress(user.id)\n self.bot.loop.create_task(self.report_bug(user, trigger_channel))\n\n # start global report timer and question timer\n report_start_time = question_start_time = time.time()\n m.reports_started.inc()\n\n def update_metrics():\n nonlocal active_question\n nonlocal question_start_time\n\n now = time.time()\n question_duration = now - question_start_time\n question_start_time = now\n\n # Record the time taken to answer the previous question\n gauge = getattr(m, f\"reports_question_{active_question}_duration\")\n gauge.set(question_duration)\n\n active_question = active_question + 1\n\n active_question = 0\n await Questions.ask(self.bot, channel, user, Lang.get_string(\"bugs/question_ready\"),\n [\n Questions.Option(\"YES\", \"Press this reaction to answer YES and begin a report\"),\n Questions.Option(\"NO\", \"Press this reaction to answer NO\", handler=abort),\n ], show_embed=True)\n update_metrics()\n\n if asking:\n # question 1: android or ios?\n await Questions.ask(self.bot, channel, user, Lang.get_string(\"bugs/question_platform\"),\n [\n Questions.Option(\"ANDROID\", \"Android\", lambda: set_platform(\"Android\")),\n Questions.Option(\"IOS\", \"iOS\", lambda: set_platform(\"iOS\"))\n ], show_embed=True)\n update_metrics()\n\n # question 2: android/ios version\n platform_version = await Questions.ask_text(self.bot, channel, user,\n Lang.get_string(\"bugs/question_platform_version\",\n platform=platform),\n validator=verify_version)\n update_metrics()\n\n # question 3: hardware info\n deviceinfo = await Questions.ask_text(self.bot, channel, user,\n Lang.get_string(\"bugs/question_device_info\",\n platform=platform, max=100),\n validator=max_length(100))\n update_metrics()\n\n # question 4: stable or beta?\n await Questions.ask(self.bot, channel, user, Lang.get_string(\"bugs/question_app_branch\"),\n [\n Questions.Option(\"STABLE\", \"Live\", lambda: set_branch(\"Stable\")),\n Questions.Option(\"BETA\", \"Beta\", lambda: set_branch(\"Beta\"))\n ], show_embed=True)\n update_metrics()\n\n # question 5: sky app version\n app_version = await Questions.ask_text(self.bot,\n channel,\n user,\n Lang.get_string(\n \"bugs/question_app_version\",\n version_help=Lang.get_string(\"bugs/version_\" + platform.lower())),\n validator=verify_version)\n update_metrics()\n\n # question 6: sky app build number\n app_build = await Questions.ask_text(self.bot, channel, user, Lang.get_string(\"bugs/question_app_build\"),\n validator=verify_version)\n update_metrics()\n\n # question 7: Title\n title = await Questions.ask_text(self.bot, channel, user, Lang.get_string(\"bugs/question_title\", max=100),\n validator=max_length(100))\n update_metrics()\n\n # question 8: \"actual\" - defect behavior\n actual = await Questions.ask_text(self.bot, channel, user, Lang.get_string(\"bugs/question_actual\", max=400),\n validator=max_length(400))\n update_metrics()\n\n # question 9: steps to reproduce\n steps = await Questions.ask_text(self.bot, channel, user, Lang.get_string(\"bugs/question_steps\", max=800),\n validator=max_length(800))\n update_metrics()\n\n # question 10: expected behavior\n expected = await Questions.ask_text(self.bot, channel, user,\n Lang.get_string(\"bugs/question_expected\", max=200),\n validator=max_length(200))\n update_metrics()\n\n # question 11: attachments y/n\n await Questions.ask(self.bot, channel, user, Lang.get_string(\"bugs/question_attachments\"),\n [\n Questions.Option(\"YES\", Lang.get_string(\"bugs/attachments_yes\"), handler=add_attachments),\n Questions.Option(\"NO\", Lang.get_string(\"bugs/skip_step\"))\n ], show_embed=True)\n update_metrics()\n\n if attachments:\n # question 12: attachments\n attachment_links = await Questions.ask_attachements(self.bot, channel, user)\n # update metrics outside condition to keep count up-to-date and reflect skipped question as zero time\n update_metrics()\n\n # question 13: additional info y/n\n await Questions.ask(self.bot, channel, user, Lang.get_string(\"bugs/question_additional\"),\n [\n Questions.Option(\"YES\", Lang.get_string(\"bugs/additional_info_yes\"), handler=add_additional),\n Questions.Option(\"NO\", Lang.get_string(\"bugs/skip_step\"))\n ], show_embed=True)\n update_metrics()\n\n if additional:\n # question 14: additional info\n additional_text = await Questions.ask_text(self.bot, channel, user,\n Lang.get_string(\"bugs/question_additional_info\"),\n validator=max_length(500))\n # update metrics outside condition to keep count up-to-date and reflect skipped question as zero time\n update_metrics()\n\n # assemble the report and show to user for review\n report = Embed(timestamp=datetime.utcfromtimestamp(time.time()))\n report.set_author(name=f\"{user} ({user.id})\", icon_url=user.avatar_url_as(size=32))\n report.add_field(name=Lang.get_string(\"bugs/platform\"), value=f\"{platform} {platform_version}\")\n report.add_field(name=Lang.get_string(\"bugs/app_version\"), value=app_version)\n report.add_field(name=Lang.get_string(\"bugs/app_build\"), value=app_build)\n report.add_field(name=Lang.get_string(\"bugs/device_info\"), value=deviceinfo, inline=False)\n report.add_field(name=Lang.get_string(\"bugs/title\"), value=title, inline=False)\n report.add_field(name=Lang.get_string(\"bugs/description\"), value=actual, inline=False)\n report.add_field(name=Lang.get_string(\"bugs/steps_to_reproduce\"), value=steps, inline=False)\n report.add_field(name=Lang.get_string(\"bugs/expected\"), value=expected)\n if additional:\n report.add_field(name=Lang.get_string(\"bugs/additional_info\"), value=additional_text, inline=False)\n\n await channel.send(content=Lang.get_string(\"bugs/report_header\", id=\"##\", user=user.mention), embed=report)\n if attachment_links:\n attachment_message = ''\n for a in attachment_links:\n attachment_message += f\"{a}\\n\"\n await channel.send(attachment_message)\n\n review_time = 300\n await asyncio.sleep(1)\n\n # Question 15 - final review\n await Questions.ask(self.bot, channel, user,\n Lang.get_string(\"bugs/question_ok\", timeout=Questions.timeout_format(review_time)),\n [\n Questions.Option(\"YES\", Lang.get_string(\"bugs/send_report\"), send_report),\n Questions.Option(\"NO\", Lang.get_string(\"bugs/mistake\"), restart)\n ], show_embed=True, timeout=review_time)\n update_metrics()\n report_duration = time.time() - report_start_time\n m.reports_duration.set(report_duration)\n else:\n return\n\n except Forbidden as ex:\n m.bot_cannot_dm_member.inc()\n await trigger_channel.send(\n Lang.get_string(\"bugs/dm_unable\", user=user.mention),\n delete_after=30)\n except asyncio.TimeoutError as ex:\n m.report_incomplete_count.inc()\n await channel.send(Lang.get_string(\"bugs/report_timeout\"))\n if active_question is not None:\n m.reports_exit_question.observe(active_question)\n self.bot.loop.create_task(self.delete_progress(user.id))\n except CancelledError as ex:\n m.report_incomplete_count.inc()\n if active_question is not None:\n m.reports_exit_question.observe(active_question)\n if not restarting:\n raise ex\n except Exception as ex:\n self.bot.loop.create_task(self.delete_progress(user.id))\n await Utils.handle_exception(\"bug reporting\", self.bot, ex)\n raise ex\n else:\n self.bot.loop.create_task(self.delete_progress(user.id))\n\n @commands.Cog.listener()\n async def on_raw_reaction_add(self, event):\n if event.message_id in self.bug_messages and event.user_id != self.bot.user.id:\n user = self.bot.get_user(event.user_id)\n channel = self.bot.get_channel(event.channel_id)\n message = await channel.fetch_message(event.message_id)\n await message.remove_reaction(event.emoji, user)\n await self.report_bug(user, channel)\n\n\ndef setup(bot):\n bot.add_cog(Bugs(bot))\n","sub_path":"cogs/Bugs.py","file_name":"Bugs.py","file_ext":"py","file_size_in_byte":22568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"177317811","text":"\"\"\"\nDesarrollar una función que determine si una cadena de caracteres es capicúa, sin utilizar cadenas auxiliares.\nEscribir además un programa que permita verificar su funcionamiento.\n\"\"\"\nfrom funciones_tp4 import chequear_capicua\n\ndef main():\n texto = input(\"Ingresar texto: \")\n if chequear_capicua(texto):\n print(f\"{texto} es una cadena de texto capicua!\")\n else:\n print(f\"{texto} no es capicua\")\n\nif __name__ == '__main__':\n main()","sub_path":"tp_4_cadenas_de_caracteres/ej1.py","file_name":"ej1.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"379672576","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom turtle import*\r\n\r\nn=int(input(\"Choisissez un nb :\"))\r\ni=0\r\n\r\ncolor(\"red\")\r\nspeed(5000000000000000000)\r\nwhile(i<=n):\r\n width(1)\r\n circle(250)\r\n right(360/n)\r\n i=i+1\r\ndone()\r\n\r\n","sub_path":"TP4/ex6.py","file_name":"ex6.py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"257630888","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('articles', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Notification',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=200, verbose_name='\\u6807\\u9898')),\n ('date', models.CharField(default='2016-01-01', max_length=100, verbose_name='\\u53d1\\u8868\\u65e5\\u671f')),\n ('content', models.TextField(max_length=5000, verbose_name='\\u5185\\u5bb9')),\n ('create_timestamp', models.DateTimeField(auto_now_add=True)),\n ('last_update_timestamp', models.DateTimeField(auto_now=True)),\n ],\n options={\n 'verbose_name': '\\u901a\\u77e5\\u516c\\u544a',\n 'verbose_name_plural': '\\u901a\\u77e5\\u516c\\u544a',\n },\n ),\n migrations.DeleteModel(\n name='EnrollStudent',\n ),\n migrations.DeleteModel(\n name='Recruit',\n ),\n migrations.AlterModelOptions(\n name='news',\n options={'verbose_name': '\\u7efc\\u5408\\u65b0\\u95fb', 'verbose_name_plural': '\\u7efc\\u5408\\u65b0\\u95fb'},\n ),\n migrations.AddField(\n model_name='news',\n name='content',\n field=models.TextField(default=datetime.datetime(2016, 1, 23, 5, 47, 33, 933623, tzinfo=utc), max_length=10000, verbose_name='\\u5185\\u5bb9'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='news',\n name='create_timestamp',\n field=models.DateTimeField(default=datetime.datetime(2016, 1, 23, 5, 47, 46, 296849, tzinfo=utc), auto_now_add=True),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='news',\n name='date',\n field=models.CharField(default='2016-01-01', max_length=100, verbose_name='\\u53d1\\u8868\\u65e5\\u671f'),\n ),\n migrations.AddField(\n model_name='news',\n name='last_update_timestamp',\n field=models.DateTimeField(default=datetime.datetime(2016, 1, 23, 5, 48, 35, 612035, tzinfo=utc), auto_now=True),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='news',\n name='title',\n field=models.CharField(default=datetime.datetime(2016, 1, 23, 5, 48, 44, 658834, tzinfo=utc), max_length=200, verbose_name='\\u6807\\u9898'),\n preserve_default=False,\n ),\n ]\n","sub_path":"ccms/apps/articles/migrations/0002_auto_20160123_1348.py","file_name":"0002_auto_20160123_1348.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"223346191","text":"import os\nimport discord\nimport settings\nimport google\nimport sqlite3\nimport redis\n\nDEFAULT_PATH = os.path.join(os.path.dirname(__file__), 'database.sqlite3')\n\ncon = sqlite3.connect('db.sqlite3')\n\nr = redis.from_url(settings.REDIS_URL)\n\nclass DiscordClient(discord.Client):\n\tdef __init__(self, *args, **kwargs):\n\t\tself.actions = {\n\t\t\"!google\": self.search_google,\n\t\t\"!recent\": self.get_recent,\n\t\t\"hi\": self.say_hey\n\t}\n\t\tsuper().__init__(*args, **kwargs)\n\n\tdef say_hey(self, message):\n\t\treturn [\"Hey\"]\n\n\tdef get_recent(self, message):\n\t\t''' Return Recent searches by the user \n\t\t '''\n\t\tsearch_keyword = \" \".join(message.content.split()[1:])\n\t\trecent_list = list(r.lrange(str(message.author),0, 10))\n\t\trecent_search = [str(s) for s in recent_list if search_keyword in str(s)]\n\t\treturn recent_search\n\t\n\tdef search_google(self, message):\n\t\tsearch_keyword = \" \".join(message.content.split()[1:])\n\t\tr.lpush(str(message.author), search_keyword)\n\t\tr.ltrim(str(message.author),0, 20)\n\t\treturn google.google_results(search_keyword)\n\t\n\n\tasync def on_ready(self):\n\t\tprint('Logged on as {0}!'.format(self.user))\n\n\tasync def on_message(self, message):\n\t\tif (str(message.author).split(\"#\")[0]!=settings.discord_bot_name and \n\t\tmessage.content.split()[0].lower() in self.actions):\n\t\t\tresponse = self.actions[message.content.split()[0]](message)\n\t\t\tfor m in response:\n\t\t\t\tawait message.channel.send(str(m))\n\nclient = DiscordClient()\nclient.run(settings.discord_token)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"82808928","text":"from flask import Flask, request\nfrom gevent import wsgi\n\nfrom notifier import Notifier\n\nimport logging\nimport logging.handlers\nimport os\nimport json\nimport configargparse\n\nimport scanner\n\n\ndef log_setup(log_console=True, log_file=True):\n formatter = logging.Formatter('%(asctime)s %(levelname)s [%(threadName)s] %(name)s - %(message)s')\n log = logging.getLogger()\n\n if log_file:\n if not os.path.exists(\"log\"):\n os.mkdir(\"log\")\n # rotate with 20mb size log files\n file_handler = logging.handlers.RotatingFileHandler('log/server.log', maxBytes=1024 * 1024 * 20, backupCount=10,\n encoding=\"utf-8\")\n file_handler.setFormatter(formatter)\n log.addHandler(file_handler)\n if log_console:\n console_handler = logging.StreamHandler()\n console_handler.setFormatter(formatter)\n log.addHandler(console_handler)\n\n return log\n\n\napp = Flask(__name__)\n\n\n@app.route('/', methods=['POST'])\ndef webhook_receiver():\n data = json.loads(request.data)\n notifier.enqueue(data)\n return \"\"\n\n\n@app.route('/location/', methods=['GET'])\ndef set_location():\n lat = request.args['lat']\n lon = request.args['lon']\n notifier.set_location(lat, lon)\n return \"\"\n\n\n@app.route('/scan/', methods=['GET'])\ndef scan():\n pokemon_name = request.args.get('name')\n loc = request.args.get('loc')\n\n if pokemon_name is None or loc is None:\n return \"name and loc must be provided\"\n\n lat_lon = loc.split(',')\n lat, lon = float(lat_lon[0]), float(lat_lon[1])\n\n data = scanner.scan_and_encounter([lat, lon], pokemon_name)\n return json.dumps(data)\n\n\nif __name__ == '__main__':\n # Setup logging\n log = log_setup()\n log.setLevel(logging.INFO)\n\n # Removes logging of each received request to flask server\n logging.getLogger('pywsgi').setLevel(logging.WARNING)\n\n # Remove logging of each sent request to discord\n logging.getLogger('requests').setLevel(logging.WARNING)\n\n parser = configargparse.ArgParser()\n parser.add_argument('--host', help='Host', default='localhost')\n parser.add_argument('-p', '--port', help='Port', type=int, default=8000)\n parser.add_argument('--debug', help=\"Debug mode\", action='store_true', default=False)\n parser.add_argument('-c', '--config', help=\"config.json file to use\", default=\"config/config.json\")\n args = parser.parse_args()\n\n if args.debug:\n logging.getLogger('notifier').setLevel(logging.DEBUG)\n\n notifier = Notifier(args.config)\n notifier.start()\n\n log.info(\"Webhook server started on http://{}:{}\".format(args.host, args.port))\n server = wsgi.WSGIServer((args.host, args.port), app, log=logging.getLogger('pywsgi'))\n server.serve_forever()\n","sub_path":"runserver.py","file_name":"runserver.py","file_ext":"py","file_size_in_byte":2777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"99748415","text":"# 378. Kth Smallest Element in a Sorted Matrix\nclass Solution:\n def kthSmallest(self, matrix, k):\n \"\"\"\n :type matrix: List[List[int]]\n :type k: int\n :rtype: int\n \"\"\"\n import heapq\n heap = [(row[0], row, 1) for row in matrix]\n heapq.heapify(heap)\n length = len(matrix[0])\n for _ in range(k-1):\n value, row, index = heap[0]\n if index < length:\n heapq.heapreplace(heap, (row[index], row, index+1))\n else:\n heapq.heappop(heap)\n return heap[0][0]\n","sub_path":"378/lc378-solution2.py","file_name":"lc378-solution2.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"4761237","text":"import numpy as np\nimport pandas as pd\nimport os, json\n\nfrom skimage.exposure import adjust_gamma\nfrom keras.models import Sequential\nfrom keras.layers import Input, Dropout, Flatten, Activation, Convolution2D, MaxPooling2D, Dense\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.optimizers import Adam\nfrom sklearn.model_selection import train_test_split\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\n\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom scipy import ndimage\nfrom scipy.misc import imresize\n\n### Create steering angle labels\ndata = pd.read_csv('data/driving_log.csv', header=None)\ndata.columns = ('center image', 'left image', 'right image', 'steering angle', 'throttle', 'break', 'speed')\n\nangles = np.array(data['steering angle'])\n\nprint(\"Loading of steering angle labels complete. \", len(angles), \" labels loaded\")\n\n# create np arrays for center / left / right images\nimages = np.asarray(os.listdir(\"data/IMG\"))\ncenter = np.ndarray(shape=(len(angles), 20, 64, 3))\nleft = np.ndarray(shape=(len(angles), 20, 64, 3))\nright = np.ndarray(shape=(len(angles), 20, 64, 3))\n\nprint(\"ndarrays created for images, left & right\")\n# Load images\n# Resize images to 32 x 64 to increase training / validation speed\n# Crop image as top 12px not useful for learning --> input img dimension 20 x 64 x 3\ncount = 0\n\nfor image in images:\n image_file = os.path.join(\"data/IMG\", image)\n if image.startswith(\"center\"):\n image_data = ndimage.imread(image_file).astype(np.float32)\n center[count % len(angles)] = imresize(image_data, (32,64,3))[12:,:,:]\n elif image.startswith(\"left\"):\n image_data = ndimage.imread(image_file).astype(np.float32)\n left[count % len(angles)] = imresize(image_data, (32,64,3))[12:,:,:]\n elif image.startswith(\"right\"):\n image_data = ndimage.imread(image_file).astype(np.float32)\n right[count % len(angles)] = imresize(image_data, (32,64,3))[12:,:,:]\n count += 1\n if count%100==0:\n print(\"Went throught \", count , \"of overall \", len(images))\n\nprint(\"Loading of images complete. \", count, \" images loaded\")\n\n# Create training set\nX_train = np.concatenate((center, left, right), axis=0)\ny_train = np.concatenate((angles, (angles - 0.1), (angles + 0.1)), axis=0)\n\nprint(\"Training set created\")\n\n# Adjust gamma in images to increase contrast\nX_train = adjust_gamma(X_train)\n\nprint(\"Training set gamma adjusted\")\n\n# Mirror images & labels to adjust for left steering bias (issue of training set)\nmirror = np.ndarray(shape=(X_train.shape))\n\ncount = 0\nfor i in range(len(X_train)):\n mirror[count] = np.fliplr(X_train[i])\n count += 1\n\nmirror_angles = y_train * -1\n\nX_train = np.concatenate((X_train, mirror), axis=0)\ny_train = np.concatenate((y_train, mirror_angles), axis=0)\n\nprint(\"Images mirrored. Full training set created\")\n\n# Split training / validation set\nX_train, X_validation, y_train, y_validation = train_test_split(X_train, y_train, test_size = 0.1)\n\nprint(\"Training set split --> training (90%) & validation (10%)\")\n\n# Create Keras Model Architecture\nmodel = Sequential()\n\nmodel.add(BatchNormalization(axis=1, input_shape=(20,64,3)))\nmodel.add(Convolution2D(16, 3, 3, border_mode=\"valid\", subsample=(2,2), activation=\"relu\"))\nmodel.add(Convolution2D(24, 3, 3, border_mode=\"valid\", subsample=(1,2), activation=\"relu\"))\nmodel.add(Convolution2D(36, 3, 3, border_mode=\"valid\", activation=\"relu\"))\nmodel.add(Convolution2D(48, 3, 3, border_mode=\"valid\", activation=\"relu\"))\nmodel.add(Convolution2D(48, 3, 3, border_mode=\"valid\", activation=\"relu\"))\nmodel.add(Flatten())\nmodel.add(Dense(512))\nmodel.add(Dropout(0.5))\nmodel.add(Activation(\"relu\"))\nmodel.add(Dense(10))\nmodel.add(Activation(\"relu\"))\nmodel.add(Dense(1))\n\nmodel.summary()\n\n# Optimize model with Adam / learning rate to 0.0001, loss function is mean-squared-error\nadam = Adam(lr=0.0001)\nmodel.compile(loss=\"mse\", optimizer= adam)\n\n# Save model when loss improves\ncheckpoint = ModelCheckpoint(filepath = 'model.h5', verbose = 1, save_best_only = True, monitor=\"val_loss\")\n\n# Stop training when loss stops to decrease\ncallback = EarlyStopping(monitor=\"val_loss\", patience=2, verbose=1)\n\n# Train model\nmodel.fit(X_train,\n y_train,\n nb_epoch=20,\n verbose=1,\n batch_size=64,\n shuffle=True,\n validation_data=(X_validation, y_validation),\n callbacks=[checkpoint, callback])\n\njson_string = model.to_json()\nwith open(\"model.json\", \"w\") as savefile:\n json.dump(json_string, savefile)\n\nmodel.save(\"model.h5\")\n\nprint(\"Model saved\")","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"162240344","text":"import sys\nimport os\nimport time\nfrom termcolor import colored\nfrom subprocess import Popen\n\nprint(\"Logiciel de dev\")\ntime.sleep(2)\nprint(\"loading\")\ntime.sleep(1)\nprint(\"###\")\ntime.sleep(2)\nos.system(\"cls\")\nprint(\"############\")\ntime.sleep(1)\nos.system(\"cls\")\nprint(\"###################\")\ntime.sleep(2)\nos.system(\"cls\")\nprint(\"#####################################################\")\nprint(\"Loading Complete\")\ntime.sleep(2)\n\nos.system(\"cls\")\nprint(\"help pour avoir la liste des commandes\")\n\nwhile True:\n commande = input(\">>>\")\n\n if commande == \"help\":\n print(\"Voici les commandes :\")\n print(\" Affiche votre version de Windows\")\n\n if commande == \"version\":\n if os.name == \"nt\":\n version = \"Windows\"\n\n print(\"Votre OS :\", version)\n print(\"Votre login :\", os.getlogin())\n\n if commande == \"clear\":\n os.system(\"CLS\")\n\n if commande == \"color\":\n #green = '\\033[32m'\n #print(green)\n\n print(\"\\033[1;32;32m Set color green \\n\")\n os.system(\"CLS\")\n\n if commande == \"matrix\":\n import subprocess\n\n \n p = subprocess.Popen(filepath, shell=True, stdout=subprocess.PIPE)\n\n stdout, stderr = p.communicate()\n print\n p.returncode # is 0 if success\n\n if commande == \"animation\":\n print(\"Sa va rendre vert l'écriture tout effacé puis sa va demander votre commande que vous avez programmer\")\n question = input(\"La commande :\")\n devant = input(\"Le devant de la question (sur ce logiciel : >>>):\")\n reponse = input(\"La réponse :\")\n\n print(\"\\033[1;32;32m Set color green \\n\")\n time.sleep(1)\n os.system(\"CLS\")\n\n test = input(devant)\n if test == question:\n print(reponse)\n else:\n print(\"Accès refusé:\")\n\n test = input(devant)\n\n\n\n\n\n else:\n print(\"Commande inconue ! help pour avoir plus d'info\")\n\n\n\n\n\n\n\n","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"177726174","text":"import re\nimport json\nimport tornado.web\nfrom tornado.httpclient import HTTPRequest\nfrom tornado.httpclient import AsyncHTTPClient\nfrom handlers import BaseHandler\n\nclass AuthHandler(BaseHandler):\n def get(self):\n auth_url = \"https://github.com/login/oauth/authorize?client_id=36d0c8db8cd823a1a719&scope=user%20public_repo,notifications\"\n self.redirect(auth_url)\n\nclass LoginHandler(BaseHandler):\n @tornado.web.asynchronous\n def get(self):\n '''\n 获取access_token\n '''\n def token_callback(response):\n if response.error:\n print(response.error)\n self.finish()\n else:\n res = re.split(r'[\\=\\&]+',response.body.decode())\n access_token = res[1]\n '''\n 获取user\n '''\n def user_callback(response1):\n if response1.error:\n print(response1.error)\n self.finish()\n else:\n res1 = json.loads(response1.body.decode())\n self.on_login_success(res1['login'])\n self.redirect(\"/home\")\n \n user_url = \"https://api.github.com/user?access_token=\"+access_token\n headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36'}\n http_client.fetch(HTTPRequest(user_url,method=\"GET\",headers=headers), user_callback)\n\n code = self.get_argument(\"code\")\n client_id = \"36d0c8db8cd823a1a719\"\n client_secret = \"82ebf5778ac2d57dbd2c14fc895d8b3810d06d6a\"\n token_url = \"https://github.com/login/oauth/access_token?client_id=\"+client_id+\"&client_secret=\"+client_secret+\"&code=\"+code\n http_client = AsyncHTTPClient()\n http_client.fetch(HTTPRequest(token_url,method=\"GET\"), token_callback)\n\nclass LogoutHandler(BaseHandler):\n @tornado.web.asynchronous\n def get(self):\n self.clear_cookie(\"user\")\n self.clear_cookie(\"tag\")\n self.redirect(\"/\")","sub_path":"handlers/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"533733528","text":"from flask import Blueprint, render_template, flash, url_for, send_from_directory, current_app\nfrom flask_login import login_required, current_user\nfrom flask_babel import _\nfrom werkzeug.exceptions import abort\nfrom werkzeug.utils import redirect\n\nfrom app.extentions import db\nfrom app.album.forms import CreateAlbumForm, UpdateAlbumForm\nfrom app.album.models import Album\nfrom app.helpers.helpers import save_image_upload\n\nbp_album = Blueprint('album', __name__, template_folder='templates')\n\n\n@bp_album.route('/')\n@login_required\ndef albums_list():\n albums = Album.query.all()\n return render_template('list_albums.html', albums=albums)\n\n\n@bp_album.route('/create', methods=['GET', 'POST'])\n@login_required\ndef create():\n form = CreateAlbumForm()\n\n if form.validate_on_submit():\n album = Album(\n form.title.data,\n form.artist.data,\n form.description.data,\n form.genre.data,\n save_image_upload(form.image),\n form.release_date.data,\n current_user.id\n )\n db.session.add(album)\n db.session.commit()\n flash(_('New album has been added.'), 'success')\n return redirect(url_for('album.albums_list'))\n return render_template('create_album.html', form=form)\n\n\n@bp_album.route('/uploads/', methods=['GET'])\ndef uploads(filename):\n return send_from_directory(current_app.config['IMAGE_UPLOADS'], filename)\n\n\n@bp_album.route('/show/')\n@login_required\ndef show(slug):\n album = Album.query.filter_by(slug=slug).first()\n if not album:\n abort(404)\n\n return render_template('show_album.html', album=album)\n\n\n@bp_album.route(\"/edit/\", methods=[\"GET\", \"POST\"])\n@login_required\ndef edit(slug):\n form = UpdateAlbumForm()\n\n album = Album.query.filter_by(slug=slug).first()\n\n if not album or not current_user.is_album_owner(album):\n flash(_(\"You are not authorized to do this.\"), \"danger\")\n return redirect(url_for(\"main.home\"))\n\n if form.validate_on_submit():\n title = form.title.data\n artist = form.artist.data\n description = form.description.data\n genre = form.genre.data\n\n album.title = title\n album.artist = artist\n album.description = description\n album.genre = genre\n\n db.session.add(album)\n db.session.commit()\n flash(_(\"The album has been updated.\"), \"success\")\n return redirect(url_for(\"album.show\", slug=album.slug))\n\n form.title.data = album.title\n form.artist.data = album.artist\n form.description.data = album.description\n form.genre.data = album.genre\n return render_template(\"edit_album.html\", album=album, form=form)\n\n\n@bp_album.route(\"/delete/\", methods=[\"POST\"])\n@login_required\ndef delete(slug):\n album = Album.query.filter_by(slug=slug).first()\n if not album or not current_user.is_album_owner(album):\n flash(\"You are not authorized to do this.\", \"danger\")\n return redirect(url_for(\"main.index\"))\n db.session.delete(album)\n db.session.commit()\n flash(_(\"The album has been deleted.\"), \"success\")\n return redirect(url_for(\"main.index\"))\n","sub_path":"app/album/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"371251817","text":"\n\nfrom xai.brain.wordbase.nouns._snoot import _SNOOT\n\n#calss header\nclass _SNOOTS(_SNOOT, ):\n\tdef __init__(self,): \n\t\t_SNOOT.__init__(self)\n\t\tself.name = \"SNOOTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"snoot\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_snoots.py","file_name":"_snoots.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"90500640","text":"import tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\n\n\nclass myCallback(tf.keras.callbacks.Callback):\n def on_epoch_end(self,epoch,logs={}):\n if(logs.get('loss')<0.4):\n print(\"stop training\")\n self.model.stop_training = True\n\n\ncallbacks = myCallback()\n\nfashion_mnist = keras.datasets.fashion_mnist\n(train_imgs, train_labels), (test_imgs, test_labels) = fashion_mnist.load_data()\n\nmodel = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(128, activation=tf.nn.relu),\n keras.layers.Dense(10, activation=tf.nn.softmax)\n])\n# model.summary() #中间层的每个neuron都会有个bias\n\ntrain_imgs = train_imgs / 255 # fashion mnist 28*28 每个像素点为灰度值(0,255) 做了个一次normalization/scaling的处理,让数值处于0-1之间,方便训练\n# model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])\nmodel.compile(optimizer=tf.optimizers.Adam(), loss=tf.losses.sparse_categorical_crossentropy,\n metrics=['accuracy']) # metrics=['accuracy']看到精度信息\n# output_label 是one hot vector\nmodel.fit(train_imgs, train_labels, epochs=5, callbacks=[callbacks])\n# 训练数据集做了normalization,所以测试数据集也要做normalization\n# test_imgs_scaled = test_imgs / 255\n# model.evaluate(test_imgs_scaled, test_labels)\n# print(np.argmax(model.predict([[test_imgs[0] / 255]])))\n# print(test_labels[0])\n# import matplotlib.pyplot as plt\n#\n# plt.imshow(test_imgs[0])","sub_path":"src/load_new_network.py","file_name":"load_new_network.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"373430229","text":"import nltk\nimport pandas as pd\nimport os\nfrom keras.layers import Embedding\nfrom keras.preprocessing import text\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.preprocessing.text import Tokenizer\nimport numpy as np\nfrom keras.utils import to_categorical\nfrom tw_sklearn.my_nltk import tokenize_only\n\nimport json\nimport tw_word2vec.word2vec as tw_w2v\n\nMAX_NB_WORDS = 20000\nEMBEDDING_DIM = 300\nMAX_SEQUENCE_LENGTH = 100\n\ndefault_model: dict = tw_w2v.get_word2vec_dic(\"../data/needed_word2vec.bin\")\ntypes = ['Component-Whole(e2,e1)', 'Content-Container(e1,e2)', 'Product-Producer(e2,e1)', 'Other',\n 'Instrument-Agency(e2,e1)', 'Entity-Destination(e1,e2)', 'Entity-Origin(e1,e2)', 'Instrument-Agency(e1,e2)',\n 'Cause-Effect(e1,e2)', 'Product-Producer(e1,e2)', 'Member-Collection(e1,e2)', 'Message-Topic(e2,e1)',\n 'Entity-Origin(e2,e1)', 'Component-Whole(e1,e2)', 'Cause-Effect(e2,e1)', 'Content-Container(e2,e1)',\n 'Member-Collection(e2,e1)', 'Entity-Destination(e2,e1)', 'Message-Topic(e1,e2)']\nprint(\"类型个数\", len(types))\ntokenizer = Tokenizer(num_words=MAX_NB_WORDS) # 传入我们词向量的字典\ntokenizer.fit_on_texts(default_model.keys()) # 传入我们的训练数据,得到训练数据中出现的词的字典\n\nword_index = tokenizer.word_index\nnum_words = min(MAX_NB_WORDS, len(word_index))\nembedding_matrix = np.zeros((num_words, EMBEDDING_DIM))\nfor word, i in word_index.items():\n if i >= MAX_NB_WORDS:\n continue\n embedding_vector = default_model[word]\n if embedding_vector is not None:\n # 文本数据中的词在词向量字典中没有,向量为取0;如果有则取词向量中该词���向量\n embedding_matrix[i] = embedding_vector\n\nembedding_layer = Embedding(num_words, # 词个数\n EMBEDDING_DIM, # 300维向量\n weights=[embedding_matrix], # 向量矩阵\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=False)\n\nif not os.path.isfile(\"../data/posi_matrix.npy\"):\n position_matrix = np.random.randn(100, 20)\n np.save(\"../data/posi_matrix\", position_matrix)\nposition_matrix = np.load(\"../data/posi_matrix.npy\")\nkeyword = {}\nwith open(\"../data/tf_idf.txt\",'r') as load_f:\n keyword = json.load(load_f)\n\ndef get_xy(filepath, percent=1):\n # 读取数据\n train = pd.read_csv(filepath_or_buffer=filepath, delimiter='|',\n # header=[\"type\",\"e1\",\"e2\",\"doc\"],\n names=[\"type\", \"e1\", \"e2\", \"doc\"]\n )\n\n add_keyword(train)\n texts = train['doc'].values.tolist()\n sequences = tokenizer.texts_to_sequences(texts)\n data = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH) # 限制每篇文章的长度——可作为输入了\n data_position = add_position(train, data)\n data[:0:10] = train[\"keyword\"][0:10]\n y = train['type'].map(lambda x: types.index(x.replace(\"\\n\", '')))\n y = to_categorical(np.asarray(y)) # 转化label\n if (percent == 1):\n return (data, data_position, y)\n # 打乱文章顺序\n indices = np.arange(data.shape[0])\n np.random.shuffle(indices)\n data = data[indices]\n data_position = data_position[indices]\n labels = y[indices]\n num_validation_samples = int((1 - percent) * data.shape[0])\n # 切割数据\n print(\"drop num_validation_samples \", num_validation_samples)\n x_train = data[:-num_validation_samples]\n x_train_position = data_position[:-num_validation_samples]\n y_train = labels[:-num_validation_samples]\n x_test = data[-num_validation_samples:]\n x_test_position = data_position[-num_validation_samples:]\n y_test = labels[-num_validation_samples:]\n print('Shape of data tensor:', x_train.shape)\n print('Shape of data_posi tensor:', x_train_position.shape)\n print('Shape of label tensor:', y_train.shape)\n return (x_train, x_train_position, y_train, x_test, x_test_position, y_test)\n\ndef add_keyword(source):\n indices = np.arange(source.shape[0])\n result = list()\n for i in indices:\n text = source.loc[i, ['doc']].values[0]\n temp_keyword = \"\"\n type = source.loc[i, ['type']].values[0]\n for word in tokenize_only(text):\n if word in keyword[type].keys():\n temp_keyword += \" \"+ word\n result.append(tokenizer.texts_to_sequences(temp_keyword))\n source[\"keyword\"] =pd.Series(result,index=indices)\n return source\n\ndef add_position(source, data=None):\n indices = np.arange(source.shape[0])\n result = np.zeros((len(indices), MAX_SEQUENCE_LENGTH, 40))\n for i in indices:\n text = source.loc[i, ['doc']].values[0]\n e1_position = source.loc[i, ['e1']].values[0]\n e2_position = source.loc[i, ['e2']].values[0]\n tokens = []\n\n if data is None:\n tokens = tokenize_only(text)\n else:\n tokens = list(filter(lambda x: x != 0, data[i]))\n sentence_posi_maxtrix = np.zeros((MAX_SEQUENCE_LENGTH, 40))\n for j in range(len(tokens)):\n e1_pv = position_matrix[j - e1_position]\n e2_pv = position_matrix[j - e2_position]\n word_position_matrix = np.append(e1_pv, e2_pv)\n sentence_posi_maxtrix[-len(tokens) + j] = word_position_matrix\n result[i] = (sentence_posi_maxtrix)\n return result\n\n\ndef get_keys(d, value):\n return [k for k, v in d.items() if v == value]\n\n\ndef get_sentence_vec(list_doc) -> object:\n sequences = tokenizer.texts_to_sequences(list_doc)\n return pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH)\n\n\nif __name__ == '__main__':\n x_train, x_train_posi, y_train, x_test, x_test_posi, y_test = get_xy(\"../data/train.txt\", 0.8)\n print(x_train)\n print(x_train_posi)\n print(y_train)\n","sub_path":"tw_word2vec/keras_input.py","file_name":"keras_input.py","file_ext":"py","file_size_in_byte":5808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"241968897","text":"# 크롤링 라이브러리 import\r\nimport urllib3\r\n\r\n\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\ndef daum() :\r\n # 엔터치기\r\n req = requests.get('https://www.mss.go.kr/site/smba/ex/bbs/List.do?cbIdx=310', verify=False)\r\n\r\n soup = BeautifulSoup(req.text, 'html.parser')\r\n\r\n list_daum = []\r\n list_daum_href = []\r\n\r\n for i in soup.select(\"#contents_inner > div > table > tbody > tr\"):\r\n list_daum.append(i.find(\"a\").text)\r\n list_daum_href.append(i.find(\"a\")[\"href\"])\r\n\r\n return list_daum, list_daum_href\r\n\r\n\r\ndef today() :\r\n # 엔터치기\r\n req = requests.get('https://www.kised.or.kr/misAnnouncement/index.es?mid=a10302000000' , verify=False)\r\n\r\n # 이런 식으로 HTML에 있는 코드를 다 가져온다\r\n soup = BeautifulSoup(req.text, 'html.parser')\r\n\r\n list_today = []\r\n list_today_href = []\r\n\r\n for i in soup.select(\"#txt > ul > li\") :\r\n list_today.append(i.find(\"a\").text)\r\n list_today_href.append(i.find(\"a\")[\"href\"])\r\n\r\n return list_today, list_today_href\r\n\r\n\r\ndef clien():\r\n # 엔터치기\r\n req = requests.get('http://www.newsnjob.com/news/articleList.html?sc_section_code=S1N2&view_type=sm' , verify=False)\r\n\r\n # 이런 식으로 HTML에 있는 코드를 다 가져온다\r\n soup = BeautifulSoup(req.text, 'html.parser')\r\n\r\n\r\n myList = []\r\n myList_href = []\r\n\r\n for i in soup.select(\"#user-container > div.float-center.max-width-1080 > div.user-content > section > article > div.article-list > section > div > div.list-titles\"):\r\n myList.append(i.text)\r\n myList_href.append(\"http://www.newsnjob.com/\" + i.find(\"a\")[\"href\"])\r\n\r\n return myList, myList_href\r\n\r\n\r\ndef blog():\r\n # 엔터치기\r\n req = requests.get('https://bvutf66khjg2.tistory.com/')\r\n\r\n # 이런 식으로 HTML에 있는 코드를 다 가져온다\r\n soup = BeautifulSoup(req.text, 'html.parser')\r\n\r\n\r\n blog = []\r\n blog_href = []\r\n\r\n for i in soup.select(\"#content > div.inner > div:nth-child(1)\"):\r\n blog.append(i.find(\"span\", class_=\"title\").text)\r\n blog_href.append(\"https://bvutf66khjg2.tistory.com/\" + i.find(\"a\")[\"href\"])\r\n\r\n\r\n return blog, blog_href\r\n\r\n\r\ndef blog1():\r\n # 엔터치기\r\n req = requests.get('https://bvutf66khjg2.tistory.com/')\r\n\r\n # 이런 식으로 HTML에 있는 코드를 다 가져온다\r\n soup = BeautifulSoup(req.text, 'html.parser')\r\n\r\n\r\n blog1 = []\r\n blog1_src = []\r\n blog1_href = []\r\n\r\n for i in soup.select(\"#content > div.inner > div:nth-child(1)\"):\r\n\r\n blog1.append(i.find(\"img\")[\"src\"])\r\n blog1_href.append(\"https://bvutf66khjg2.tistory.com\" + i.find(\"a\")[\"href\"])\r\n blog1_src.append(i.find(\"img\")[\"src\"])\r\n\r\n return blog1, blog1_href, blog1_src\r\n\r\n\r\n\r\ndef blog2():\r\n # 엔터치기\r\n req = requests.get('https://bvutf66khjg2.tistory.com/')\r\n\r\n # 이런 식으로 HTML에 있는 코드를 다 가져온다\r\n soup = BeautifulSoup(req.text, 'html.parser')\r\n\r\n\r\n blog2 = []\r\n blog2_href = []\r\n\r\n for i in soup.select(\"#content > div.inner > div:nth-child(2)\"):\r\n blog2.append(i.find(\"span\", class_=\"title\").text)\r\n blog2_href.append(\"https://bvutf66khjg2.tistory.com/\" + i.find(\"a\")[\"href\"])\r\n\r\n\r\n return blog2, blog2_href\r\n\r\n\r\ndef blog3():\r\n # 엔터치기\r\n req = requests.get('https://bvutf66khjg2.tistory.com/')\r\n\r\n # 이런 식으로 HTML에 있는 코드를 다 가져온다\r\n soup = BeautifulSoup(req.text, 'html.parser')\r\n\r\n\r\n blog3 = []\r\n blog3_src = []\r\n blog3_href = []\r\n\r\n for i in soup.select(\"#content > div.inner > div:nth-child(2)\"):\r\n\r\n blog3.append(i.find(\"img\")[\"src\"])\r\n blog3_href.append(\"https://bvutf66khjg2.tistory.com\" + i.find(\"a\")[\"href\"])\r\n blog3_src.append(i.find(\"img\")[\"src\"])\r\n\r\n return blog3, blog3_href, blog3_src\r\n\r\n\r\ndef blog4():\r\n # 엔터치기\r\n req = requests.get('https://bvutf66khjg2.tistory.com/')\r\n\r\n # 이런 식으로 HTML에 있는 코드를 다 가져온다\r\n soup = BeautifulSoup(req.text, 'html.parser')\r\n\r\n\r\n blog4 = []\r\n blog4_href = []\r\n\r\n for i in soup.select(\"#content > div.inner > div:nth-child(3)\"):\r\n blog4.append(i.find(\"span\", class_=\"title\").text)\r\n blog4_href.append(\"https://bvutf66khjg2.tistory.com/\" + i.find(\"a\")[\"href\"])\r\n\r\n\r\n return blog4, blog4_href\r\n\r\n\r\ndef blog5():\r\n # 엔터치기\r\n req = requests.get('https://bvutf66khjg2.tistory.com/')\r\n\r\n # 이런 식으로 HTML에 있는 코드를 다 가져온다\r\n soup = BeautifulSoup(req.text, 'html.parser')\r\n\r\n\r\n blog5 = []\r\n blog5_src = []\r\n blog5_href = []\r\n\r\n for i in soup.select(\"#content > div.inner > div:nth-child(3)\"):\r\n\r\n blog5.append(i.find(\"img\")[\"src\"])\r\n blog5_href.append(\"https://bvutf66khjg2.tistory.com\" + i.find(\"a\")[\"href\"])\r\n blog5_src.append(i.find(\"img\")[\"src\"])\r\n\r\n return blog5, blog5_href, blog5_src\r\n\r\n","sub_path":"crawling 이미지 크롤링 백업.py","file_name":"crawling 이미지 크롤링 백업.py","file_ext":"py","file_size_in_byte":4937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"646322005","text":"from django.test import TestCase, RequestFactory\nfrom django.contrib.auth.models import AnonymousUser\nfrom .views import *\n\n\nclass IndexTest(TestCase):\n def test_access_to_index_page(self):\n \"\"\"\n Access to the index page\n \"\"\"\n response = self.client.get(reverse(\"index\"))\n self.assertTemplateUsed(response, \"trash/index.html\")\n\n\nclass AddItemTest(TestCase):\n fixtures = ['init_data.json']\n\n def test_access_to_add_item_page(self):\n \"\"\"\n Access to the add item page, should return a list of bins\n \"\"\"\n response = self.client.get(reverse(\"additem\"))\n self.assertIsNotNone(response.context[\"bins\"])\n\n # def test_item_successfully(self):\n # \"\"\"\n # Add item, should redirect to index page after success\n # \"\"\"\n # args = {\n # \"name\": \"Name\",\n # \"description\": \"Description\",\n # \"bin\": \"Paper\",\n # \"sc_code\": 123\n # }\n # response = self.client.post(reverse(\"additem\"), args)\n # self.assertTrue(ADD_ITEM_SUCCESSFULLY_MESSAGE in response.cookies['messages'].value)\n # self.assertEqual(response.status_code, 200)\n # self.assertRedirects(response, \"/auction/\")\n\n\nclass TrashBinsTest(TestCase):\n fixtures = ['init_data.json']\n\n def test_access_to_trash_bins_page(self):\n \"\"\"\n Access to the trash bins page\n \"\"\"\n response = self.client.get(reverse(\"trashbins\"))\n self.assertTemplateUsed(response, \"trash/bins.html\")\n\n def test_show_bin_items_with_not_existing_bin(self):\n \"\"\"\n Show items of the not existing bin, should redirect to main page\n \"\"\"\n bin_name = \"money\"\n response = self.client.get(reverse(\"show_binitems\", args=(bin_name,)))\n self.assertRedirects(response, \"/\")\n\n def test_show_bin_items_with_existing_bin(self):\n \"\"\"\n Show items of the existing bin\n \"\"\"\n bin_name = \"plastic\"\n response = self.client.get(reverse(\"show_binitems\", args=(bin_name,)))\n self.assertContains(response, b\"plastic\")\n self.assertTemplateUsed(response, \"trash/binitems.html\")\n\n\nclass SearchTest(TestCase):\n fixtures = ['init_data.json']\n\n def test_search_not_existing_bar_code(self):\n \"\"\"\n Search not existing bar code, should redirect to main page\n \"\"\"\n context = {\n \"criteria\": NOT_FOUND_BAR_CODE\n }\n response = self.client.get(reverse(\"search\"), context)\n self.assertRedirects(response, \"/\")\n\n def test_search_all(self):\n \"\"\"\n Search all items, return list of items and redirect to search result page\n \"\"\"\n context = {\n \"criteria\": \"\"\n }\n response = self.client.get(reverse(\"search\"), context)\n self.assertTrue(len(response.context[\"items\"]) <= 20)\n self.assertIsNotNone(response.context[\"items\"])\n self.assertTemplateUsed(response, \"trash/searchresult.html\")\n\n def test_search_by_name(self):\n \"\"\"\n Search for specific items by name, return match list of items\n \"\"\"\n context = {\n \"criteria\": \"spoon\"\n }\n response = self.client.get(reverse(\"search\"), context)\n self.assertIsNotNone(response.context[\"items\"])\n self.assertTrue(\"spoon\" in response.context[\"items\"][0].name)\n\n def test_search_by_code_existing_items(self):\n \"\"\"\n Search for existing items by code, return match list of items\n \"\"\"\n context = {\n \"criteria\": \"scnr12345\"\n }\n response = self.client.get(reverse(\"search\"), context)\n self.assertIsNotNone(response.context[\"items\"])\n self.assertTrue(\"12345\" in response.context[\"items\"][0].sc_code)\n\n def test_search_by_code_not_existing_items(self):\n \"\"\"\n Search for not existing items by code, redirect to the add item page\n \"\"\"\n new_sc_code = \"9999\"\n context = {\n \"criteria\": \"scnr\" + new_sc_code\n }\n response = self.client.get(reverse(\"search\"), context)\n self.assertRedirects(response, \"/additem/?scnf={}\".format(new_sc_code))\n\n\nclass MapTest(TestCase):\n def test_open_map(self):\n response = self.client.get(reverse(\"openmap\"))\n self.assertIsNotNone(response.context[\"data\"])\n self.assertTemplateUsed(response, \"trash/maps.html\")\n\n\nclass AboutUsTest(TestCase):\n def test_access_about_page(self):\n response = self.client.get(reverse(\"aboutus\"))\n self.assertTemplateUsed(response, \"trash/aboutus.html\")","sub_path":"trash/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"269526350","text":"#coding=utf-8\n#description:\n_author_ = 'Kai,Chen'\n_time_ = '2018/4/24'\n\nfrom enum import Enum , unique\n\nclass Weekday(Enum):\n Sun = 0\n Mon = 1\n Tue = 2\n Wed = 3\n Thu = 4\n Fri = 5\n Sat = 6\n\nfor name, member in Weekday.__members__.items():\n print(name, '=>', member)","sub_path":"programme/enum_02.py","file_name":"enum_02.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"326216050","text":"import re\nfrom feature_extraction.WordToInteger.word_to_int import WordToInt\nfrom feature_extraction.FactTree.PropositionLogic import Proposition\n\n\nclass Answer():\n query_dict = {\n \"lease_term_length\": {\n \"topic\": ['lease', 'time'],\n \"fact\": ('NN', 'time'),\n \"return\": ('CD', int)\n },\n \"lease_ends_in\": {\n \"topic\": ['lease', 'time'],\n \"fact\": ('NN', 'time'),\n \"return\": ('CD', int)\n },\n \"rent_in_lease_amount\": {\n \"topic\": ['pay'],\n \"fact\": ('NN', 'pay'),\n \"return\": ('CD', int)\n }\n }\n\n #########################################\n # CONSTRUCTOR\n def __init__(self):\n self.propositions = Proposition()\n self.current_dict_entry = None\n\n ##################################################\n # QUERY\n # ------------------------------------------------\n # Attempts to extract the answer from a user\n # based on the topic.\n #\n # query: string\n # sentence: string\n def query(self, query, sentence):\n self.current_dict_entry = self.query_dict[query.lower()]\n self.propositions.build(sentence)\n proposition_lst = self.propositions.get_proposition_lst()\n return self.__find_possible_answers(proposition_lst)\n\n #########################################\n # FIND POSSIBLE ANSWERS\n # ---------------------------------------\n # Finds all propositions which match\n # the category of answer we are searching for\n #\n # proposition_lst: List of all proposition statements\n def __find_possible_answers(self, proposition_lst):\n topics = self.current_dict_entry['topic'].copy()\n tag = self.current_dict_entry['return'][0]\n topics_found = 0\n initial_topic_len = len(topics)\n possible_answers = []\n\n for propositions in proposition_lst:\n if propositions.contains_tag(tag):\n possible_answers.append(propositions)\n for i in range(len(topics) - 1, -1, -1):\n if propositions.category_match(topics[i]):\n topics.pop()\n topics_found += 1\n\n if topics_found == 0:\n # return \"Off topic\"\n return None\n elif topics_found < initial_topic_len:\n # return \"Insufficient data\"\n return None\n else:\n return self.__extract_answer(possible_answers)\n\n #########################################\n # EXTRACT ANSWER\n # ---------------------------------------\n # Finds the proposition which is in the\n # same category as the answer we want\n # to extract\n #\n # answer: List of propositions\n def __extract_answer(self, possible_answers):\n fact = self.current_dict_entry['fact']\n tag = self.current_dict_entry['return'][0]\n for answers in possible_answers:\n if fact[1] in answers.category:\n return self.__parse_answer(answers.get_tagged_word(tag))\n # return \"On topic but missing information\"\n return None\n\n #########################################\n # PARSE ANSWER\n # ---------------------------------------\n # Get the keyword from the proposition\n # to answer the query\n #\n # answer: List of clause/predicate/compliments\n def __parse_answer(self, answer):\n regex = re.compile(self.current_dict_entry['return'][0])\n value = \"\"\n for word_set in answer:\n words = word_set.get_word()\n for word in words:\n if regex.match(word[1]):\n value += word[0]\n return self.__format_answer(value)\n\n ##############################################\n # FORMAT ANSWER\n # --------------------------------------------\n # Formats the answer in whatever value is expected\n # Will support booleans in the future\n #\n # value: string\n def __format_answer(self, value):\n return_type = self.current_dict_entry['return'][1]\n # More types supported in the future\n if return_type == int:\n return self.__return_int(value)\n\n #########################################\n # RETURN INT\n # ---------------------------------------\n # Tries to convert the value to an integer\n # if it fails then parse the word and give\n # it's integer value\n # nine hundred two --> 902\n #\n # value: string\n @staticmethod\n def __return_int(value):\n try:\n return int(value)\n except ValueError:\n model = WordToInt()\n return model.text2int(value)\n\n\nif __name__ == '__main__':\n a = Answer()\n result = a.query(\"lease_term_length\", \"I have 3 dogs and my lease is twenty months\")\n print(result)\n result = a.query(\"lease_term_length\", \"my lease expires in 4 years\")\n print(result)\n result = a.query(\"lease_term_length\", \"my lease is time\")\n print(result)\n result = a.query(\"lease_term_length\", \"I have 4 Mihai and my lease ends in 2 months\")\n print(result)\n","sub_path":"src/nlp_service/feature_extraction/fact_extraction.py","file_name":"fact_extraction.py","file_ext":"py","file_size_in_byte":5050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"535566237","text":"import os\nfrom setuptools import setup, find_packages\n\nhere = os.path.abspath(os.path.dirname(__file__))\nversion_ns = {}\nwith open(os.path.join(here, \"akernel\", \"_version.py\")) as f:\n exec(f.read(), {}, version_ns)\n\ndef get_data_files():\n \"\"\"Get the data files for the package.\n \"\"\"\n data_files = [\n ('share/jupyter/kernels/akernel', ['share/jupyter/kernels/akernel/kernel.json']),\n ]\n return data_files\n\nsetup(\n name=\"akernel\",\n version=version_ns[\"__version__\"],\n url=\"https://github.com/davidbrochart/akernel.git\",\n author=\"David Brochart\",\n author_email=\"david.brochart@gmail.com\",\n description=\"An asynchronous Python Jupyter kernel\",\n long_description=open(\"README.md\").read(),\n long_description_content_type='text/markdown',\n packages=find_packages(),\n python_requires=\">=3.7\",\n install_requires=[\n \"pyzmq\",\n \"typer>=0.4.0\",\n \"click\",\n \"python-dateutil\",\n \"colorama\",\n \"gast\",\n ],\n extras_require={\n \"test\": [\n \"mypy\",\n \"flake8\",\n \"black\",\n \"pytest\",\n \"pytest-asyncio\",\n \"types-python-dateutil\",\n \"kernel_driver\",\n \"ipyx>=0.1.2\",\n ],\n \"react\": [\n \"ipyx>=0.1.2\",\n ],\n },\n entry_points={\n \"console_scripts\": [\"akernel = akernel.akernel:cli\"],\n },\n classifiers=(\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ),\n data_files=get_data_files()\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"68219806","text":"from blackmole.settings import BASE_DIR\nfrom mole.models import System\nfrom mole.models import Asset\nfrom mole.models import SystemAndAsset\nfrom mole.libs.extender import fileoperator as fo\nfrom mole.libs.logger.logger import get_logger\n\n\nclass SystemAndAssetresFormater:\n def __init__(self):\n self.assetres_dir = BASE_DIR + '/mole/res/assetres/'\n self.system_filename = self.assetres_dir + 'system.csv'\n self.asset_filename = self.assetres_dir + 'asset.csv'\n self.systemandasset_filename = self.assetres_dir + 'systemandasset.csv'\n self.logger = get_logger()\n\n def clean_system_and_systemandasset_data(self):\n SystemAndAsset.objects.all().delete()\n System.objects.all().delete()\n Asset.objects.all().delete()\n\n def init_system(self):\n system_list = fo.read_list_from_file(self.system_filename)\n for system in system_list:\n system_elememts = system.split(',')\n s = System()\n s.name = system_elememts[0]\n s.team = system_elememts[1]\n s.level = system_elememts[2]\n s.save()\n\n def init_asset(self):\n asset_list = fo.read_list_from_file(self.asset_filename)\n for asset in asset_list:\n asset_elements = asset.split(',')\n a = Asset()\n a.ip = asset_elements[0]\n a.ip_type = asset_elements[1]\n a.host_type = asset_elements[2]\n a.os = asset_elements[3]\n a.db_list = asset_elements[5]\n a.mw_list = asset_elements[6]\n a.ot_list = asset_elements[7]\n a.save()\n\n def system_has(self, system_name):\n result = System.objects.filter(name=system_name).all()\n if result.count() > 0:\n return True\n else:\n return False\n\n def asset_has(self, asset_ip):\n result = Asset.objects.filter(ip=asset_ip).all()\n if result.count() > 0:\n return True\n else:\n return False\n\n def append_systemandasset_record(self, system_name, asset_ip):\n if not self.system_has(system_name):\n s = System()\n s.name = system_name\n s.save()\n else:\n pass\n if not self.asset_has(asset_ip):\n a = Asset()\n a.ip = asset_ip\n a.save()\n else:\n pass\n system = System.objects.filter(name=system_name).all()[0]\n asset = Asset.objects.filter(ip=asset_ip).all()[0]\n sa = SystemAndAsset()\n sa.system = system\n sa.asset = asset\n sa.save()\n\n def init_systemandasset(self):\n systemandasset_list = fo.read_list_from_file(self.systemandasset_filename)\n for systemandasset in systemandasset_list:\n systemandasset_elememts = systemandasset.split(',')\n system_name = systemandasset_elememts[0]\n asset_ip = systemandasset_elememts[1]\n self.append_systemandasset_record(system_name, asset_ip)\n\n def format_and_push_into_db(self):\n self.logger.info('assetresformater:format_and_push_into_db init_system')\n self.init_system()\n self.logger.info('assetresformater:format_and_push_into_db init_asset')\n self.init_asset()\n self.logger.info('assetresformater:format_and_push_into_db init_systemandasset')\n self.init_systemandasset()\n","sub_path":"blackmole/mole/libs/formater/systemandassetresformater.py","file_name":"systemandassetresformater.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"283744742","text":"n, k = map(int, input().split())\n\nitem = [[0, 0]]\nfor i in range(n):\n item.append(list(map(int, input().split())))\n\nbag = [[0]*(k+1) for _ in range(n + 1)]\n\nfor i in range(1, n+1):\n for j in range(1, k+1):\n if j >= item[i][0]:\n bag[i][j] = max(bag[i-1][j], bag[i-1][j-item[i][0]]+item[i][1])\n else:\n bag[i][j] = bag[i-1][j]\n\nprint(bag[n][k])","sub_path":"BOJ/BOJ Python/PY12865_평범한_배낭.py","file_name":"PY12865_평범한_배낭.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"588678490","text":"# USBDevice.py\n#\n# Contains class definitions for USBDevice and USBDeviceRequest.\n\nfrom facedancer.usb.USB import *\nfrom facedancer.usb.USBClass import *\nfrom facedancer.usb.USBConfiguration import USBConfiguration\n\nfrom facedancer.fuzz.helpers import mutable\nimport traceback\nimport time\nimport struct\n\nclass USBDevice(USBDescribable):\n name = \"Device\"\n\n DESCRIPTOR_TYPE_NUMBER = DescriptorType.device\n DESCRIPTOR_LENGTH = 0x12\n\n def __init__(self, phy, device_class=0, device_subclass=0,\n protocol_rel_num=0, max_packet_size_ep0=64, vendor_id=0, product_id=0,\n device_rev=0, manufacturer_string=\"\", product_string=\"\",\n serial_number_string=\"\", configurations=[], descriptors={},\n spec_version=0x0200, quirks=[], usb_class=None, usb_vendor=None, bos=None, scheduler=None):\n super(USBDevice, self).__init__(phy)\n self.phy = phy\n descriptors = descriptors if descriptors else {}\n configurations=configurations if configurations else []\n self.supported_device_class_trigger = False\n self.supported_device_class_count = 0\n\n self.quirks = quirks[:]\n self.correct_set_address = ('fast_set_address' not in quirks)\n\n self.strings = [ ]\n\n self.usb_spec_version = spec_version\n\n # FIXME: Accept Class objects rather than raw numbers!!\n self.device_class = device_class\n self.device_subclass = device_subclass\n self.protocol_rel_num = protocol_rel_num\n self.max_packet_size_ep0 = max_packet_size_ep0\n self.vendor_id = vendor_id\n self.product_id = product_id\n self.device_rev = device_rev\n self.manufacturer_string_id = self.get_string_id(manufacturer_string)\n self.product_string_id = self.get_string_id(product_string)\n\n if serial_number_string is not None:\n self.serial_number_string_id = self.get_string_id(serial_number_string)\n else:\n self.serial_number_string_id = 0\n\n# maps from USB.desc_type_* to bytearray OR callable\n self.descriptors = {\n DescriptorType.device: self.get_descriptor,\n DescriptorType.configuration: self.handle_get_configuration_descriptor_request,\n DescriptorType.other_speed_configuration: self.get_other_speed_configuration_descriptor,\n DescriptorType.string: self.handle_get_string_descriptor_request,\n DescriptorType.hub: self.handle_get_hub_descriptor_request,\n DescriptorType.device_qualifier: self.get_device_qualifier_descriptor,\n DescriptorType.bos: self.get_bos_descriptor,\n }\n self.descriptors.update(descriptors)\n\n self.config_num = -1\n self.configuration = None\n self.configurations = configurations\n\n self.usb_class = usb_class\n self.usb_vendor = usb_vendor\n\n self.bos = bos\n\n for c in self.configurations:\n csi = 0\n if c.configuration_string:\n csi = self.get_string_id(c.configuration_string)\n c.set_configuration_string_index(csi)\n c.set_device(self)\n # this is fool-proof against weird drivers\n if self.usb_class is None:\n self.usb_class = c.usb_class\n if self.usb_vendor is None:\n self.usb_vendor = c.usb_vendor\n\n if self.usb_vendor:\n self.usb_vendor.device = self\n if self.usb_class:\n self.usb_class.device = self\n\n self.state = State.detached\n self.ready = False\n\n self.address = 0\n\n self.setup_request_handlers()\n self.endpoints = {}\n\n # If we don't have a scheduler, create a basic scheduler.\n if scheduler:\n self.scheduler = scheduler\n else:\n from facedancer.app.core import FacedancerBasicScheduler\n self.scheduler = FacedancerBasicScheduler(self.phy)\n\n # Add our IRQ-servicing task to the scheduler's list of tasks to be serviced.\n self.scheduler.add_task(lambda : self.phy.service_irqs())\n\n @classmethod\n def from_binary_descriptor(cls, phy, data):\n \"\"\"\n Creates a USBDevice object from its descriptor.\n \"\"\"\n print(\"Device\")\n # Pad the descriptor out with zeroes to the full length of a configuration descriptor.\n if len(data) < cls.DESCRIPTOR_LENGTH:\n padding_necessary = cls.DESCRIPTOR_LENGTH - len(data)\n data.extend([0] * padding_necessary)\n\n # Parse the core descriptor into its components...\n spec_version_msb, spec_version_lsb, device_class, device_subclass, device_protocol, \\\n max_packet_size_ep0, vendor_id, product_id, device_rev_msb, device_rev_lsb, \\\n manufacturer_string_index, product_string_index, \\\n serial_number_string_index, num_configurations = struct.unpack(\" 2:\n self.verbose(\"received SET_ADDRESS request for address\", self.address)\n\n self.set_address(self.address)\n\n # USB 2.0 specification, section 9.4.3 (p 281 of pdf)\n def handle_get_descriptor_request(self, req):\n dtype = (req.value >> 8) & 0xff\n dindex = req.value & 0xff\n lang = req.index\n n = req.length\n\n response = None\n\n self.verbose((\"received GET_DESCRIPTOR req %d, index %d, \" \\\n + \"language 0x%04x, length %d\") \\\n % (dtype, dindex, lang, n))\n\n response = self.descriptors.get(dtype, None)\n if callable(response):\n response = response(dindex)\n\n if response:\n n = min(n, len(response))\n #self.phy.verbose += 1\n self.send_control_message(response[:n])\n\n #self.phy.verbose -= 1\n\n self.verbose(\"sent %d bytes in response\" % n)\n else:\n self.phy.stall_ep0()\n\n def handle_get_configuration_descriptor_request(self, num):\n if num < len(self.configurations):\n return self.configurations[num].get_descriptor()\n else:\n return self.configurations[0].get_descriptor()\n\n def get_other_speed_configuration_descriptor(self, num):\n if num < len(self.configurations):\n return self.configurations[num].get_other_speed_descriptor()\n else:\n return self.configurations[0].get_other_speed_descriptor()\n\n def get_bos_descriptor(self, num):\n if self.bos:\n return self.bos.get_descriptor()\n # no bos? stall ep\n return None\n\n @mutable('string_descriptor_zero')\n def get_string0_descriptor(self):\n d = struct.pack(\n ' len(self.configurations):\n self.error('Host tries to set invalid configuration: %#x' % (req.value - 1))\n self.config_num = 0\n else:\n self.config_num = req.value - 1\n\n self.info('Setting configuration: %#x' % (self.config_num+1))\n self.configuration = self.configurations[self.config_num]\n self.state = State.configured\n\n # collate endpoint numbers\n self.endpoints = { }\n for i in self.configuration.interfaces:\n for e in i.endpoints:\n #if e.transfer_type==e.transfer_type_isochronous:\n # self.warning(\"Isochronous transfer isn't yet supported by greatfet firmware !\")\n #else:\n self.endpoints[e.number] = e\n\n # HACK: blindly acknowledge request\n self.ack_status_stage()\n\n # notify the device of the recofiguration, in case\n # it needs to e.g. set up endpoints accordingly\n self.phy.configured(self.configuration) #<---- this should work but will lead to timeouts\n\n # USB 2.0 specification, section 9.4.4 (p 282 of pdf)\n def handle_get_interface_request(self, req):\n self.debug(\"received GET_INTERFACE request\")\n\n if req.index == 0:\n # HACK: currently only support one interface\n self.send_control_message(b'\\x00')\n else:\n self.phy.stall_ep0()\n\n # USB 2.0 specification, section 9.4.10 (p 288 of pdf)\n def handle_set_interface_request(self, req):\n self.debug(\"received SET_INTERFACE request\")\n\n # USB 2.0 specification, section 9.4.11 (p 288 of pdf)\n def handle_synch_frame_request(self, req):\n self.debug(\"received SYNCH_FRAME request\")\n\n def __repr__(self):\n return \"\".format(self.vendor_id, self.product_id)\n\n\nclass USBDeviceRequest:\n\n setup_request_types = {\n Request.type_standard: 'standard',\n Request.type_class: 'class',\n Request.type_vendor: 'vendor',\n }\n setup_request_receipients = {\n Request.recipient_device: 'device',\n Request.recipient_interface: 'interface',\n Request.recipient_endpoint: 'endpoint',\n Request.recipient_other: 'other',\n }\n\n def __init__(self, raw_bytes):\n '''Expects raw 8-byte setup data request packet'''\n (\n self.request_type,\n self.request,\n self.value,\n self.index,\n self.length\n ) = struct.unpack('\"\n\n # Pretty print, where possible.\n type = self.get_type_string()\n recipient = self.get_recipient_string()\n request = self.get_request_number_string()\n value = self.get_value_string()\n\n s = \"%s, %s request to %s (%s: value=%s, index=%x, length=%d)\" \\\n % (direction_marker, type, recipient, request,\n value, self.index, self.length)\n return s\n\n def get_type_string(self):\n return self.setup_request_types[self.get_type()]\n\n def get_recipient_string(self):\n return self.setup_request_receipients[self.get_type()]\n\n def get_request_number_string(self):\n if self.get_type() == 0:\n return self._get_standard_request_number_string()\n else:\n type = self.get_type_string()\n return \"{} request {}\".format(type, self.request)\n\n _standard_req_descriptions = {\n 0: 'GET_STATUS',\n 1: 'CLEAR_FEATURE',\n 3: 'SET_FEATURE',\n 5: 'SET_ADDRESS',\n 6: 'GET_DESCRIPTOR',\n 7: 'SET_DESCRIPTOR',\n 8: 'GET_CONFIGRUATION',\n 9: 'SET_CONFIGURATION',\n 10: 'GET_INTERFACE',\n 11: 'SET_INTERFACE',\n 12: 'SYNCH_FRAME'\n }\n\n _descriptor_number_description = {\n 1: 'DEVICE',\n 2: 'CONFIGURATION',\n 3: 'STRING',\n 4: 'INTERFACE',\n 5: 'ENDPOINT',\n 6: 'DEVICE_QUALIFIER',\n 7: 'OTHER_SPEED_CONFIG',\n 8: 'POWER',\n 33: 'HID',\n 34: 'REPORT',\n }\n\n def _get_standard_request_number_string(self):\n return self._standard_req_descriptions[self.request]\n\n def get_value_string(self):\n # If this is a GET_DESCRIPTOR request, parse it.\n if self.get_type() == 0 and self.request == 6:\n description = self._get_descriptor_number_string()\n return \"{} descriptor\".format(description)\n else:\n return \"%x\" % self.value\n\n def _get_descriptor_number_string(self):\n try:\n descriptor_index = self.value >> 8\n return self._descriptor_number_description[descriptor_index]\n except KeyError:\n return \"unknown descriptor 0x%x\" % self.value\n\n def raw(self):\n \"\"\"returns request as bytes\"\"\"\n b = struct.pack(\n '> 8,\n self.index >> 8,\n self.length >> 8,\n )\n return b\n\n def get_direction(self):\n return (self.request_type >> 7) & 0x01\n\n def get_type(self):\n return (self.request_type >> 5) & 0x03\n\n def get_recipient(self):\n return self.request_type & 0x1f\n\n # meaning of bits in wIndex changes whether we're talking about an\n # interface or an endpoint (see USB 2.0 spec section 9.3.4)\n def get_index(self):\n rec = self.get_recipient()\n if rec == 1: # interface\n return self.index\n elif rec == 2: # endpoint\n return self.index & 0x0f\n else:\n return self.index\n\n\n","sub_path":"facedancer/usb/USBDevice.py","file_name":"USBDevice.py","file_ext":"py","file_size_in_byte":25304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"47028820","text":"tri = [round(0.5 * n * (n+1)) for n in range(286,100000)]\ntriset = set(tri)\n\ncincos = [round(0.5 * n * (3*n-1)) for n in range(166,100000)]\ncincoset = set(cincos)\n\nhexes = [n * (2*n - 1) for n in range(144,100000)]\nhexset = set(hexes)\n\nfor t in tri:\n if t in cincoset and t in hexset:\n print(t)\n break\n\n","sub_path":"045-tri-pent-hex.py","file_name":"045-tri-pent-hex.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"35286579","text":"\"\"\"\nStill in development.\n\"\"\"\nimport math\nimport torch\nfrom torch import nn\nfrom models.layers_transposed import Conv, Hourglass, SELayer, Backbone\nfrom models.loss_model_parallel import MultiTaskLossParallel\nfrom models.loss_model import MultiTaskLoss\nfrom torchvision.models import densenet\nfrom thop import profile\n\n\nclass Merge(nn.Module):\n \"\"\"Change the channel dimension of the input tensor\"\"\"\n\n def __init__(self, x_dim, y_dim, bn=False):\n super(Merge, self).__init__()\n self.conv = Conv(x_dim, y_dim, 1, relu=False, bn=bn)\n\n def forward(self, x):\n return self.conv(x)\n\n\nclass Features(nn.Module):\n \"\"\"Input: feature maps produced by hourglass block\n Return: 5 different scales of feature maps, 128*128, 64*64, 32*32, 16*16, 8*8\"\"\"\n\n def __init__(self, inp_dim, increase=128, bn=False):\n super(Features, self).__init__()\n # Regress 5 different scales of heatmaps per stack\n self.before_regress = nn.ModuleList(\n [nn.Sequential(Conv(inp_dim + i * increase, inp_dim, 3, bn=bn, dropout=False),\n Conv(inp_dim, inp_dim, 3, bn=bn, dropout=False),\n # ##################### Channel Attention layer #####################\n SELayer(inp_dim),\n ) for i in range(5)])\n\n def forward(self, fms):\n assert len(fms) == 5, \"hourglass output {} tensors,but 5 scale heatmaps are supervised\".format(len(fms))\n outs = []\n for i, f, before_regress in zip(range(5), fms, self.before_regress):\n out = before_regress(f)\n outs.append(out)\n return outs\n # > orig\n # return [self.before_regress[i](fms[i]) for i in range(5)]\n\n\nclass PoseNet(nn.Module):\n def __init__(self, num_stages, inp_dim, oup_dim, bn=False, increase=128, init_weights=True, **kwargs):\n \"\"\"\n Pack or initialize the trainable parameters of the network\n :param num_stages: number of stack\n :param inp_dim: input tensor channels fed into the hourglass block\n :param oup_dim: channels of regressed feature maps\n :param bn: use batch normalization\n :param increase: increased channels once down-sampling\n :param kwargs:\n \"\"\"\n super(PoseNet, self).__init__()\n # <512x512>\n # nstack: 4\n # inp_dim: 256\n # oup_dim: 50\n # bn: True\n # increase: 128\n # init_weights: True\n self.pre = Backbone() # > 256: It doesn't affect the results regardless of which self.pre is used\n self.hourglass = nn.ModuleList()\n self.features = nn.ModuleList()\n self.outs = nn.ModuleList()\n self.merge_features = nn.ModuleList()\n self.merge_preds = nn.ModuleList()\n for t in range(num_stages): # 4\n self.hourglass.append(Hourglass(depth=4, nFeat=inp_dim, increase=increase, bn=bn))\n self.features.append(Features(inp_dim=inp_dim, increase=increase, bn=bn))\n # TODO: change the outs layers, Conv(inp_dim + j * increase, oup_dim, 1, relu=False, bn=False)\n self.outs.append(nn.ModuleList([Conv(inp_dim, oup_dim, 1, relu=False, bn=False) for _ in range(5)]))\n\n # TODO: change the merge layers, Merge(inp_dim + j * increase, inp_dim + j * increase)\n if t < num_stages - 1:\n self.merge_features.append(nn.ModuleList([Merge(inp_dim, inp_dim + j * increase, bn=bn) for j in range(5)]))\n self.merge_preds.append(nn.ModuleList([Merge(oup_dim, inp_dim + j * increase, bn=bn) for j in range(5)]))\n self.num_stages = num_stages\n self.num_scales = 5\n if init_weights:\n self._initialize_weights()\n\n def forward(self, imgs):\n # Input Tensor: a batch of images within [0,1], shape=(N, H, W, C). Pre-processing was done in data generator\n x = imgs.permute(0, 3, 1, 2) # Permute the dimensions of images to (N, C, H, W)\n x = self.pre(x)\n pred = []\n feat_caches = [[]] * self.num_scales\n # loop over stack\n for t, hg, se_blocks, out_blocks in \\\n zip(range(self.num_stages), self.hourglass, self.features, self.outs): # > 4\n preds_instack = []\n # -> (0:256, 1:384, 2:512, 3:640, 4:786)\n hg_outs = hg(x) # -> 5 scales of feature maps\n\n if t == 0: # cache for smaller feature maps produced by hourglass block\n feat_caches = [torch.zeros_like(hg_outs[s]) for s in range(self.num_scales)]\n else:\n hg_outs = [hg_outs[s] + feat_caches[s] for s in range(self.num_scales)]\n\n feats_instack = se_blocks(hg_outs) # > 5 convs -> 5 scales\n\n for s, feats, head in zip(range(self.num_scales), feats_instack, out_blocks): # handle 5 scales of heatmaps\n # > outs/bottlenecks: 1x1 conv layer * 5\n pred_out = head(feats)\n preds_instack.append(pred_out)\n\n if t != self.num_stages - 1:\n cache = self.merge_preds[t][s](pred_out) + self.merge_features[t][s](feats)\n if s == 0:\n x = x + cache\n feat_caches[s] = cache\n pred.append(preds_instack)\n # returned list shape: [nstack * [batch*128*128, batch*64*64, batch*32*32, batch*16*16, batch*8*8]]z\n return pred\n\n def _initialize_weights(self):\n for m in self.modules():\n # 卷积的初始化方法\n if isinstance(m, nn.Conv2d):\n # TODO: 使用正态分布进行初始化(0, 0.01) 网络权重看看\n # n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n # He kaiming 初始化, 方差为2/n. math.sqrt(2. / n) 或者直接使用现成的nn.init中的函数。在这里会梯度爆炸\n m.weight.data.normal_(0, 0.001) # # math.sqrt(2. / n)\n # torch.nn.init.kaiming_normal_(m.weight)\n # bias都初始化为0\n if m.bias is not None: # 当有BN层时,卷积层Con不加bias!\n m.bias.data.zero_()\n # batchnorm使用全1初始化 bias全0\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n elif isinstance(m, nn.Linear):\n torch.nn.init.normal_(m.weight.data, 0, 0.01) # todo: 0.001?\n # m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\n\nclass Network(torch.nn.Module):\n \"\"\"\n Wrap the network module as well as the loss module on all GPUs to balance the computation among GPUs.\n \"\"\"\n def __init__(self, opt, config, bn=False, dist=False, swa=False):\n super(Network, self).__init__()\n self.posenet = PoseNet(num_stages=opt.nstack,\n inp_dim=opt.hourglass_inp_dim,\n oup_dim=config.num_layers,\n bn=bn,\n increase=opt.increase)\n # If we use train_parallel, we implement the parallel loss . And if we use train_distributed,\n # we should use single process loss because each process on these 4 GPUs is independent\n self.criterion = MultiTaskLoss(opt, config) if dist else MultiTaskLossParallel(opt, config)\n self.swa = swa\n\n def forward(self, input_all):\n # Batch will be divided and Parallel Model will call this forward on every GPU\n inp_imgs = input_all[0]\n target_tuple = input_all[1:]\n output_tuple = self.posenet(inp_imgs)\n\n if not self.training: # testing mode\n loss = self.criterion(output_tuple, target_tuple)\n # output will be concatenated along batch channel automatically after the parallel model return\n return output_tuple, loss\n\n else: # training mode\n if not self.swa:\n loss = self.criterion(output_tuple, target_tuple)\n\n # output will be concatenated along batch channel automatically after the parallel model return\n return loss\n else:\n return output_tuple\n\n\nclass NetworkEval(torch.nn.Module):\n \"\"\"\n Wrap the network module as well as the loss module on all GPUs to balance the computation among GPUs.\n \"\"\"\n def __init__(self, opt, config, bn=False):\n super(NetworkEval, self).__init__()\n self.posenet = PoseNet(opt.nstack, opt.hourglass_inp_dim, config.num_layers, bn=bn, init_weights=False,\n increase=opt.increase)\n\n def forward(self, inp_imgs):\n # Batch will be divided and Parallel Model will call this forward on every GPU\n output_tuple = self.posenet(inp_imgs)\n\n if not self.training:\n # output will be concatenated along batch channel automatically after the parallel model return\n return output_tuple\n else:\n # output will be concatenated along batch channel automatically after the parallel model return\n raise ValueError('\\nOnly eval mode is available!!')\n\n\nif __name__ == '__main__':\n from time import time\n\n # model = PoseNet(4, 256, 50, bn=True, increase=128) # .cuda()\n # for param in model.parameters():\n # if param.requires_grad:\n # print('param autograd')\n # break\n model = Backbone()\n t0 = time()\n input = torch.rand(1, 512, 512, 3) # .cuda()\n print(model)\n total_ops, total_params = profile(model, inputs=(input,))\n print(\"%s | %.2f | %.2f\" % ('SimplePose', total_params / (1000 ** 2), total_ops / (1000 ** 3)))\n\n\n t1 = time()\n print('********** Consuming Time is: {} second **********'.format(t1 - t0))\n\n # #\n # import torch.onnx\n #\n # pose = PoseNet(4, 256, 34)\n # dummy_input = torch.randn(1, 512, 512, 3)\n # torch.onnx.export(pose, dummy_input, \"posenet.onnx\") # netron --host=localhost\n","sub_path":"models/posenet.py","file_name":"posenet.py","file_ext":"py","file_size_in_byte":9996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"264238190","text":"from dagster import file_relative_path\nfrom dagster.api.snapshot_repository import sync_get_external_repository\nfrom dagster.core.host_representation import EnvironmentHandle, ExternalRepository, RepositoryHandle\n\n\ndef test_repository_snapshot_api():\n repo_handle = RepositoryHandle(\n repository_name='bar',\n environment_handle=EnvironmentHandle.legacy_from_yaml(\n 'test', file_relative_path(__file__, 'repository_file.yaml')\n ),\n )\n\n external_repository = sync_get_external_repository(repo_handle)\n\n assert isinstance(external_repository, ExternalRepository)\n assert external_repository.name == 'bar'\n","sub_path":"python_modules/dagster/dagster_tests/api_tests/test_api_snapshot_repository.py","file_name":"test_api_snapshot_repository.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"472383033","text":"import tensorflow as tf\nimport numpy as np\na=np.array([[1,6,3],\n [5,4,9],\n [1,2,3],\n [7,5,8]],dtype=np.int64)\ninput_values=np.array([5,6,3,4],dtype=np.int64)\ninput_shape=np.array([3,9,12],dtype=np.int64)\nreduction_axes=np.array([0],dtype=np.int64)\nprint(a.shape)\nb=tf.raw_ops.SparseReduceSum(input_indices=a, input_values=input_values, input_shape=input_shape, reduction_axes=reduction_axes)\nwith tf.Session() as sess:\n print(sess.run(b))\n\n'''\ninput_indices 位于稀疏矩阵中的位置\ninput_values 稀疏矩阵中的值\ninput_shape 稀疏矩阵的形状,用0填充\nreduction_axes 输出稀疏矩阵的维度\n'''","sub_path":"TF_fun/TF_SparseReduceSum.py","file_name":"TF_SparseReduceSum.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"270382947","text":"import os\nimport sys\nimport datetime\n\nimport transaction\nfrom sqlalchemy import engine_from_config\nfrom pyramid.paster import (\n get_appsettings,\n setup_logging,\n )\n\nfrom ..models import (\n DBSession,\n MyModel,\n Base,\n User,\n Target\n )\n\n\ndef usage(argv):\n cmd = os.path.basename(argv[0])\n print('usage: %s \\n'\n '(example: \"%s development.ini\")' % (cmd, cmd))\n sys.exit(1)\n\n\ndef main(argv=sys.argv):\n if len(argv) != 2:\n usage(argv)\n config_uri = argv[1]\n setup_logging(config_uri)\n settings = get_appsettings(config_uri)\n engine = engine_from_config(settings, 'sqlalchemy.')\n DBSession.configure(bind=engine)\n Base.metadata.create_all(engine)\n with transaction.manager:\n model = MyModel(name='one', value=1)\n user1 = User(name=\"Vasya\",username=\"vasya\",password=\"123456\",mail=\"vasya@mail.ru\")\n\n user2 = User(name=\"Petya\",username=\"petya\",password=\"123456\",mail=\"petya@mail.ru\")\n\n user3 = User(name=\"Mama\",username=\"mom\",password=\"123456\",mail=\"mom@mail.ru\")\n\n target1 = Target(name=\"Python for real dummies like us\", deadline=datetime.datetime(year=1987, month=10, day=5),\n bid=100,\n url=\"biomech\")\n target1.planned_progress = 70\n target1.current_progress = 30\n target1.user = user1\n target1.overseer = user2\n target1 = Target(name=\"Inroduction to Gay Ritchi technologies\",\n deadline=datetime.datetime(year=2008, month=10, day=5), bid=500, url=\"nanotech\")\n target1.planned_progress = 60\n target1.current_progress = 40\n target1.is_success = \"success\"\n target1.user = user2\n target1.overseer = user3\n DBSession.add(target1)\n target1 = Target(name=\"Total unconciousness!\", deadline=datetime.datetime(year=2012, month=10, day=5), bid=900,\n url=\"nanotech\")\n target1.planned_progress = 60\n target1.current_progress = 40\n target1.is_success = \"fail\"\n target1.user = user2\n target1.overseer = user3\n DBSession.add(target1)\n target1 = Target(name=\"Subj to read\", deadline=datetime.datetime(year=2008, month=10, day=5), bid=500,\n type=\"omni\", url=\"http://fullcycle.ru\")\n target1.planned_progress = 80\n target1.current_progress = 70\n target1.user = user2\n target1.overseer = user3\n DBSession.add(user1)\n DBSession.add(user2)\n DBSession.add(user3)\n #DBSession.add(model)\n users = DBSession.query(User).all()\n print(users)\n\n","sub_path":"kickass/scripts/initializedb.py","file_name":"initializedb.py","file_ext":"py","file_size_in_byte":2656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"20663933","text":"from tkinter import *\r\nfrom tkinter import messagebox\r\n\r\ndef ask_quit():\r\n\tif messagebox.askokcancel(\"Quit?\",\"Are you sure?\"):\r\n\t\troot.destroy()\r\n\r\ndef callback(event):\r\n\tmessagebox.showinfo('Clicked!','clicked at {},{}'.format(event.x, event.y))\r\n\r\ndef menucallback():\r\n\tmessagebox.showinfo('Menu!','clicked a menu thing')\r\n\r\nroot = Tk()\r\nroot.protocol(\"WM_DELETE_WINDOW\", ask_quit)\r\n\r\nmenu = Menu(root)\r\nroot.config(menu=menu)\r\n\r\nfilemenu = Menu(menu)\r\nmenu.add_cascade(label='File', menu=filemenu)\r\nfilemenu.add_command(label='New', command = menucallback)\r\nfilemenu.add_command(label='Open', command = menucallback)\r\nfilemenu.add_separator()\r\nfilemenu.add_command(label='Exit', command=ask_quit)\r\n\r\nhelpmenu = Menu(menu)\r\nmenu.add_cascade(label='Help', menu=helpmenu)\r\nhelpmenu.add_command(label='About...', command=menucallback)\r\n\r\nroot.frame = Frame(root, width=150, height=150, background = 'cyan')\r\nroot.frame.bind(\"\", callback)\r\nroot.frame.pack()\r\n\r\nroot.quit_button = Button(root, text=\"Quit\", command = ask_quit)\r\nroot.quit_button.pack()\r\n\r\nroot.mainloop()\r\n","sub_path":"GuiTest.py","file_name":"GuiTest.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"449116036","text":"from numpy import *\nfrom numpy.linalg import *\ntabuleiro = array(eval(input(\"Tabuleiro: \"))) # Leitura do tabuleiro\nmov = input(\"Movimentos: \") # Sequencia de movimentos do personagem\nxtab = 0\t# Posicao inicial do personagem\nytab = 0\nmoeda = 0\t# Contadores de atributos do personagem\nlife = 100\n# Limites do tabuleiro\nlimcol = shape(tabuleiro)[1]\t# Limites colunas\nlimlinh = shape(tabuleiro)[0]\t# Limites linhas\n# Analise da jogada\nfor x in mov:\n\tif(x == 'A'): \n\t\tif(xtab-1 != -1):\n\t\t\tif(tabuleiro[ytab,xtab-1] != 33):\n\t\t\t\txtab = xtab -1 # Move personagem para ESQUERDA\n\telif(x == 'D'): \n\t\tif(xtab+1 != limcol):\n\t\t\tif(tabuleiro[ytab,xtab+1]!=33):\n\t\t\t\txtab =xtab +1 # Move personagem para DIREITA\n\telif(x == 'W'): \n\t\tif(ytab-1 != -1):\n\t\t\tif(tabuleiro[ytab-1,xtab]!=33):\n\t\t\t\tytab = ytab -1\t# Move personagem para CIMA\n\telif x == 'S':\n\t\tif(ytab+1 != limlinh):\n\t\t\tif(tabuleiro[ytab+1,xtab]!=33):\n\t\t\t\tytab = ytab + 1\t# Move personagem para BAIXO\n\n# Trata evento\n\tif tabuleiro[ytab,xtab] == 11:\t# Moeda\n\t\tmoeda =moeda +1 \n\t\ttabuleiro[ytab,xtab] = 0 # Apaga moeda do tabuleiro\n\telif tabuleiro[ytab,xtab] == 22: \n\t\tlife = life - 5\t# Zumbi\n\n\n# Imprime saidas\nprint(\"posicao x: \", xtab)\nprint(\"posicao y: \", ytab)\nprint(\"moedas: \", moeda)\nprint(\"life: \", life)","sub_path":"5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4444/codes/1834_1280.py","file_name":"1834_1280.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"57287628","text":"import importlib\nimport sys\nimport socket\nimport selectors\nimport traceback\nimport threading\nfrom collections import deque\nimport random\nimport logging\nimport time\nfrom types import FunctionType\nimport functools\nimport json\nimport io\nimport struct\nimport inspect\nfrom queue import Queue\nimport numpy as np\nimport copy\nfrom influxdb import InfluxDBClient\n\n#############################################\n# Class for server side messages\n#############################################\n\nclass ServerMessage:\n \"\"\"\n ServerMessage class for communication between the SocketDeviceServer and\n SocketDeviceClient classes.\n A message has the following structure:\n - fixed-lenght header\n - json header\n - content\n See https://realpython.com/python-sockets/#application-client-and-server\n for a more thorough explanation, most of the code is adapted from this.\n \"\"\"\n def __init__(self, obj, selector, sock, addr, data, timeout):\n self.selector = selector\n self.sock = sock\n self.addr = addr\n self._recv_buffer = b\"\"\n self._send_buffer = b\"\"\n self._jsonheader_len = None\n self.jsonheader = None\n self.request = None\n self.response_created = False\n\n self.obj = obj\n self.data = data\n self.timeout = timeout\n\n def _set_selector_events_mask(self, mode):\n \"\"\"Set selector to listen for events: mode is 'r', 'w', or 'rw'.\"\"\"\n if mode == \"r\":\n events = selectors.EVENT_READ\n elif mode == \"w\":\n events = selectors.EVENT_WRITE\n elif mode == \"rw\":\n events = selectors.EVENT_READ | selectors.EVENT_WRITE\n else:\n raise ValueError(f\"Invalid events mask mode {repr(mode)}.\")\n self.selector.modify(self.sock, events, data=self)\n\n def _read(self):\n try:\n # Should be ready to read\n data = self.sock.recv(4096)\n except BlockingIOError:\n # Resource temporarily unavailable (errno EWOULDBLOCK)\n pass\n else:\n if data:\n self._recv_buffer += data\n else:\n raise RuntimeError(\"Peer closed.\")\n\n def _write(self):\n if self._send_buffer:\n try:\n # Should be ready to write\n sent = self.sock.send(self._send_buffer)\n except BlockingIOError:\n # Resource temporarily unavailable (errno EWOULDBLOCK)\n pass\n else:\n self._send_buffer = self._send_buffer[sent:]\n # Close when the buffer is drained. The response has been sent.\n if sent and not self._send_buffer:\n self.close()\n\n def _json_encode(self, obj, encoding):\n return json.dumps(obj, ensure_ascii=False).encode(encoding)\n\n def _json_decode(self, json_bytes, encoding):\n tiow = io.TextIOWrapper(\n io.BytesIO(json_bytes), encoding=encoding, newline=\"\"\n )\n obj = json.load(tiow)\n tiow.close()\n return obj\n\n def _create_message(\n self, *, content_bytes, content_type, content_encoding\n ):\n jsonheader = {\n \"byteorder\": sys.byteorder,\n \"content-type\": content_type,\n \"content-encoding\": content_encoding,\n \"content-length\": len(content_bytes),\n }\n jsonheader_bytes = self._json_encode(jsonheader, \"utf-8\")\n message_hdr = struct.pack(\">H\", len(jsonheader_bytes))\n message = message_hdr + jsonheader_bytes + content_bytes\n return message\n\n def _create_response_json_content(self):\n action = self.request.get(\"action\")\n if action == \"query\":\n query = self.request.get(\"value\")\n if self.data.get(query):\n content = {\"result\": self.data.get(query)}\n else:\n content = {\"error\": f'No match for \"{query}\".'}\n elif action == \"command\":\n command = self.request.get(\"value\")\n try:\n retval = eval('self.obj.{0}'.format(command))\n if not retval is None:\n content = {\"result\": retval}\n else:\n content = {\"result\": \"command {} performed\".format(command)}\n except AttributeError:\n content = {\"error\": \"no match for {0}.\".format(command)}\n elif action == \"info\":\n content = {\"result\":self.data['info']}\n else:\n content = {\"error\": f'invalid action \"{action}\".'}\n content_encoding = \"utf-8\"\n response = {\n \"content_bytes\": self._json_encode(content, content_encoding),\n \"content_type\": \"text/json\",\n \"content_encoding\": content_encoding,\n }\n return response\n\n def _create_response_binary_content(self):\n response = {\n \"content_bytes\": b\"First 10 bytes of request: \"\n + self.request[:10],\n \"content_type\": \"binary/custom-server-binary-type\",\n \"content_encoding\": \"binary\",\n }\n return response\n\n def process_events(self, mask):\n if mask & selectors.EVENT_READ:\n self.read()\n if mask & selectors.EVENT_WRITE:\n self.write()\n\n def read(self):\n self._read()\n\n if self._jsonheader_len is None:\n self.process_protoheader()\n\n if self._jsonheader_len is not None:\n if self.jsonheader is None:\n self.process_jsonheader()\n\n if self.jsonheader:\n if self.request is None:\n self.process_request()\n\n def write(self):\n if self.request:\n if not self.response_created:\n self.create_response()\n\n self._write()\n\n def close(self):\n try:\n self.selector.unregister(self.sock)\n except Exception as e:\n logging.warning(\n f\"error: selector.unregister() exception for\",\n f\"{self.addr}: {repr(e)}\",\n )\n\n try:\n self.sock.close()\n except OSError as e:\n logging.warning(\n f\"error: socket.close() exception for\",\n f\"{self.addr}: {repr(e)}\",\n )\n finally:\n # Delete reference to socket object for garbage collection\n self.sock = None\n\n def process_protoheader(self):\n hdrlen = 2\n if len(self._recv_buffer) >= hdrlen:\n self._jsonheader_len = struct.unpack(\n \">H\", self._recv_buffer[:hdrlen]\n )[0]\n self._recv_buffer = self._recv_buffer[hdrlen:]\n\n def process_jsonheader(self):\n hdrlen = self._jsonheader_len\n if len(self._recv_buffer) >= hdrlen:\n self.jsonheader = self._json_decode(\n self._recv_buffer[:hdrlen], \"utf-8\"\n )\n self._recv_buffer = self._recv_buffer[hdrlen:]\n for reqhdr in (\n \"byteorder\",\n \"content-length\",\n \"content-type\",\n \"content-encoding\",\n ):\n if reqhdr not in self.jsonheader:\n raise ValueError(f'Missing required header \"{reqhdr}\".')\n\n def process_request(self):\n content_len = self.jsonheader[\"content-length\"]\n if not len(self._recv_buffer) >= content_len:\n return\n data = self._recv_buffer[:content_len]\n self._recv_buffer = self._recv_buffer[content_len:]\n if self.jsonheader[\"content-type\"] == \"text/json\":\n encoding = self.jsonheader[\"content-encoding\"]\n self.request = self._json_decode(data, encoding)\n else:\n # Binary or unknown content-type\n self.request = data\n # Set selector to listen for write events, we're done reading.\n self._set_selector_events_mask(\"w\")\n\n def create_response(self):\n if self.jsonheader[\"content-type\"] == \"text/json\":\n response = self._create_response_json_content()\n else:\n # Binary or unknown content-type\n response = self._create_response_binary_content()\n message = self._create_message(**response)\n self.response_created = True\n self._send_buffer += message\n\n#############################################\n# Socket Server Class\n#############################################\n\nclass socketServer(threading.Thread):\n \"\"\"\n Handles communication with external clients in a separate thread.\n \"\"\"\n def __init__(self, communication, host, port, timeout):\n threading.Thread.__init__(self)\n self.communication = communication\n self.host = ''\n self.timeout = float(timeout)\n self.port = int(port)\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.sock.bind((self.host, self.port))\n self.sock.listen()\n self.sock.setblocking(False)\n self.sel = selectors.DefaultSelector()\n self.sel.register(self.sock, selectors.EVENT_READ, data=None)\n\n self.active = threading.Event()\n self.active.clear()\n\n def accept_wrapper(self, sock):\n conn, addr = sock.accept() # Should be ready to read\n logging.info(\"{0} accepted connection from\".format(self.communication.device_name), addr)\n conn.setblocking(False)\n message = ServerMessage(self.communication.transfer_cavity, self.sel, conn, addr, self.communication.data_server,\n self.timeout)\n self.sel.register(conn, selectors.EVENT_READ, data=message)\n\n def run(self):\n self.active.set()\n logging.warning('socketServer running')\n while self.active.is_set():\n events = self.sel.select(timeout = self.timeout)\n for key, mask in events:\n if key.data is None:\n self.accept_wrapper(key.fileobj)\n else:\n message = key.data\n try:\n message.process_events(mask)\n except Exception as err:\n logging.warning(\"{2} socket warning for \"\n +\"{0}:{1} : \".format(self.host, self.port, self.device.device_name)\n +str(err))\n message.close()\n\n#############################################\n# InfluxDB class\n#############################################\n\nclass InfluxDBCommunication(threading.Thread):\n \"\"\"\n\n \"\"\"\n def __init__(self, device, host, port, username, password, dt):\n threading.Thread.__init__(self)\n self.active = threading.Event()\n self.device = device\n\n self.influxdb_client = InfluxDBClient(\n host = host,\n port = port,\n username = username,\n password = password\n )\n self.influxdb_client.switch_database(\"lasers\")\n\n self.dt = dt\n\n self.col_names = [\"cavity lock\", \"cavity error\", \"seed 1 lock\",\n \"seed 2 lock\", \"seed 1 error\", \"seed 2 error\", \"seed 1 frequency\",\n \"seed 2 frequency\", \"seed 1 lockpoint\", \"seed 2 lockpoint\"]\n\n def run(self):\n logging.warning('influxDB running')\n while self.active.is_set():\n fields = dict( (key, val) for key, val in zip(self.col_names, self.device.data_server.get('ReadValue'))\n if not np.isnan(val))\n\n json_body = [\n {\n \"measurement\": self.device.device_name,\n \"time\": int(1000 * time.time()),\n \"fields\": fields,\n }\n ]\n try:\n self.influxdb_client.write_points(json_body, time_precision='ms')\n except Exception as err:\n logging.warning(\"InfluxDB error: \" + str(err))\n logging.warning(traceback.format_exc())\n\n time.sleep(self.dt)\n\n#############################################\n# Class for network communication with LaserLocking\n#############################################\n\nclass NetworkIOLocking:\n \"\"\"\n Network IO for laser lock parameters\n \"\"\"\n def __init__(self, transfer_cavity, host, port):\n self.device_name = 'Laser Locking 1'\n\n self.master_locked_flag = False\n self.master_err = np.nan\n self.slave_locked_flags = [np.nan]*2\n self.slave_err = [np.nan]*2\n self.slave_frequency = [np.nan]*2\n self.slave_lockpoint = [np.nan]*2\n\n self.transfer_cavity = transfer_cavity\n\n self.thread_communication = socketServer(self, host, int(port), 2)\n # closes communication thread upon closing of main thread\n self.thread_communication.setDaemon(True)\n self.thread_communication.start()\n\n self.thread_influxdb = InfluxDBCommunication(\n self, \"172.28.82.114\", 8086, \"bsmonitor\", \"molecules\", 5\n )\n self.thread_influxdb.setDaemon(True)\n self.thread_influxdb.start()\n self.thread_influxdb.active.set()\n\n @property\n def data_server(self):\n return {\n 'ReadValue':[self.master_locked_flag, self.master_err]+\\\n self.slave_locked_flags+self.slave_err+\\\n self.slave_frequency+self.slave_lockpoint,\n 'verification':'laser locking',\n 'info':self.device_name\n }\n","sub_path":"SWP/NetworkIOLocking.py","file_name":"NetworkIOLocking.py","file_ext":"py","file_size_in_byte":13608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"585330803","text":"#!/bin/env python\r\nimport shutil\r\nimport glob\r\nfrom os import path, stat\r\nfrom pathlib import Path\r\nimport sys\r\n\r\nif len(sys.argv) != 2:\r\n print(\"Usage: hek-sync.py \")\r\n sys.exit(1)\r\n\r\ndev_root = \".\"\r\nhek_root = sys.argv[1]\r\n\r\ndef do_copy(src_file, dst_file):\r\n Path(dst_file).parent.mkdir(parents=True, exist_ok=True)\r\n shutil.copy2(src_file, dst_file)\r\n\r\ndef sync(pattern):\r\n dev_files = {path.relpath(f, dev_root): stat(f).st_mtime for f in glob.glob(path.join(dev_root, path.normpath(pattern)), recursive=True)}\r\n hek_files = {path.relpath(f, hek_root): stat(f).st_mtime for f in glob.glob(path.join(hek_root, path.normpath(pattern)), recursive=True)}\r\n for f in {*dev_files.keys(), *hek_files.keys()}:\r\n if f in dev_files and (f not in hek_files or dev_files[f] > hek_files[f]):\r\n print(\"Copying to HEK: \" + f)\r\n do_copy(path.join(dev_root, f), path.join(hek_root, f))\r\n elif f in hek_files and (f not in dev_files or hek_files[f] > dev_files[f]):\r\n print(\"Copying to local: \" + f)\r\n do_copy(path.join(hek_root, f), path.join(dev_root, f))\r\n\r\nsync(\"data/levels/boiling_point/**/**.tif\")\r\nsync(\"data/levels/boiling_point/**/**.JMS\")\r\nsync(\"tags/levels/boiling_point/**/**.*\")\r\n","sub_path":"hek-sync.py","file_name":"hek-sync.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"72226853","text":"__author__ = 'max'\n\ndef take(count,iterable):\n '''\n :param count:\n Args:\n count: the maximum number to retrieve from iterable\n iterable: the source series.\n yield: At most count numbers from iterable\n '''\n\n counter = 0\n for item in iterable:\n if counter == count:\n return\n counter += 1\n yield item\n\ndef run_take():\n mylist = [1,2,3,5,6,8]\n for item in take(5,mylist):\n print(item)\n\nif __name__ == \"__main__\":\n run_take()","sub_path":"Python/Essentials/Generators/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"382827424","text":"#!/usr/bin/env python \n# -*- coding: utf-8 -*-\n# 代码来自http://blog.csdn.net/victordiao/article/details/52176400,有改动。\nimport urllib\nimport re #导入对excel文件进行操作的库\nimport xlwt #创建表格,设置编码模式,创建新的sheet\n\nbook=xlwt.Workbook(encoding='utf-8',style_compression=0)\nsheet=book.add_sheet('dede',cell_overwrite_ok=True)\nfor j in range(1,1192): #j的作用是对url不断进行修改,翻页,需要事先看好网页\n print (j)\n url = 'http://guba.eastmoney.com/list,600030,5,f_'+str(j)+'.html'\n try:\n request=urllib.request.Request(url)\n response=urllib.request.urlopen(request)\n content = response.read().decode('utf-8')\n pattern = re.compile('',re.S) #####()里面就是提取的内容,.任意字符,*?匹配0或无数次+非贪婪模式\n title = re.findall(pattern, content)#符合正则的内容提取为列表,注意索引从0开始\n pattern = re.compile('(.*?)', re.S)\n author = re.findall(pattern, content)\n pattern = re.compile('(.*?).*?(.*?)', re.S)\n time = re.findall(pattern, content)\n pattern = re.compile('
(.*?).*?(.*?)', re.S)\n num = re.findall(pattern, content)\n for i in range(0,80): ####从列表中提取,每个列表80个元素,index为0-79\n titleans=title[i+1]\n sheet.write((j-1)*80+i,0,titleans)\n authorans=author[i]\n sheet.write((j - 1) * 80 + i, 1, authorans)\n fabiaotime=time[i][0]\n sheet.write((j - 1) * 80 + i, 2, fabiaotime)\n gengxintime=time[i][1]\n sheet.write((j - 1) * 80 + i, 3, gengxintime)\n yuedu = num[i][0]\n #print yuedu\n sheet.write((j - 1) * 80 + i, 4, yuedu)\n pinglun = num[i][1]\n #print pinglun\n sheet.write((j - 1) * 80 + i, 5, pinglun)\n #保存\n book.save('C:\\\\Users\\\\mcc\\\\Desktop\\\\Python Learning Notes\\\\600030.xls')\n\n except Exception as e:\n print(\"出错了\")","sub_path":"guba.py","file_name":"guba.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"398087287","text":"'''\n\tJeremy Kerby\n\tUrllibExample.py\n\tExecuting simple API call to Food2Fork API. Using standard urllib module.\n\tDecember 2015\n'''\n#!/usr/bin/python\nimport json\nimport urllib.request\nimport urllib.parse\n\nQUERY = 'ginger'\nKEY = 'KEY'\ndata = {}\ndata['key'] = KEY \ndata['q'] = QUERY \n\nurl_values = urllib.parse.urlencode(data)\nurl = 'http://food2fork.com/api/search'\nfull_url = url + '?' + url_values\n\nprint('> Target URL:', full_url)\n\ndata = urllib.request.urlopen(full_url)\n\nprint('> HTTP Status:', data.status)\n\nparsed_json = json.loads(data.read().decode('utf8'))\n\ncount = int(parsed_json['count'])\n\nprint('The following recipes contain', QUERY)\n\nfor title in range(count):\n\tprint('-', parsed_json['recipes'][title]['title'])\n","sub_path":"urllib/UrllibExample.py","file_name":"UrllibExample.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"625307476","text":"from __future__ import print_function\nfrom setuptools import setup\nimport os\nimport dg_graph\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\nlong_description = '''Diggi graph traversal tool.'''\n\nsetup(\n name='dg_graph',\n version=dg_graph.__version__,\n url='https://bitbucket.org/serviciosveca/dg_graph',\n license='Apache Software License',\n author='Servicios VECA',\n install_requires = [\n\t\t'graph_db>=0.0.1',\n\t],\n author_email='1josegomezr@gmail.com',\n description='dg_graph.',\n long_description=long_description,\n packages=['dg_graph'],\n include_package_data=True,\n platforms='any',\n keywords='graph database grafos',\n # test_suite='dg_graph.test.all',\n classifiers = []\n)\n","sub_path":"pypi_install_script/dg_graph-0.0.10.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"375702756","text":"# from django.shortcuts import render\nfrom django.contrib.auth.models import User\nfrom django.contrib import auth\nfrom django.http import HttpResponse\nfrom django.http import JsonResponse\nimport json\nfrom rest_framework import status\nfrom .models import *\nfrom rest_framework import permissions\nfrom rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAdminUser\n# from rest_framework.decorators import list_route\nfrom rest_framework import mixins\nfrom rest_framework import generics\n# from .serializers import UserSerializer\nfrom . import models , permissions\nfrom . import serializers\nfrom job.models import job\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.exceptions import APIException\nfrom rest_framework.views import APIView\nfrom rest_framework.decorators import api_view, renderer_classes\nfrom rest_framework.response import Response\nfrom rest_framework.authentication import TokenAuthentication, SessionAuthentication\nfrom django.contrib.sessions.models import Session\nfrom rest_framework.authtoken.models import Token\nfrom django.db.models import Q\nfrom rest_framework.renderers import StaticHTMLRenderer\nfrom rest_auth.registration.views import VerifyEmailView, RegisterView\nfrom django.core.exceptions import ObjectDoesNotExist\nimport operator\nfrom rest_framework.renderers import JSONRenderer\n\n\n@api_view(['POST'])\ndef LoggedInUserGetProfile(request):\n\n total_rating = 0\n\n try:\n req_dict = request.data\n token = Token.objects.get(key=req_dict['session_token'])\n \n # get user\n user_profile_data = CustomUser.objects.get(id=token.user_id)\n user_serializer = serializers.CustomUserDetailsSerializer(user_profile_data)\n \n # get rating\n ratings = Rating.objects.filter(being_rated=token.user_id)\n\n for rating in ratings:\n serialized_rating = serializers.RatingSerializer(rating)\n total_rating += int(serialized_rating.data['rating'])\n\n if total_rating > 0:\n total_rating = total_rating/len(ratings)\n \n # add all necessary fields to return object\n return_object = {\n \"business_name\": user_serializer.data['business_name'],\n \"profile_picture\": user_serializer.data['profile_picture'],\n \"description\": user_serializer.data['description'],\n \"location\": user_serializer.data['location'],\n \"phone\": user_serializer.data['phone'],\n \"user_name\": user_serializer.data['name'],\n \"rating\": total_rating,\n \"user_projects\": user_serializer.data['jobs'] if len(user_serializer.data['jobs']) > 0 else [],\n \"open_bids\": []\n }\n\n open_bids = job.objects.filter(current_bid=token.user_id)\n\n for open_bid in open_bids:\n serialized_bid = serializers.jobSerialize(open_bid)\n return_object['open_bids'].append(serialized_bid.data)\n\n return JsonResponse(return_object, safe=False, status=200)\n\n except:\n return JsonResponse({'error':'failed retrieving user info','status':'failure'}, status=400)\n\n\n@api_view(['POST'])\ndef OtherUsersGetProfile(request):\n\n total_rating = 0\n try:\n req_dict = request.data\n token = Token.objects.get(key=req_dict['session_token'])\n\n # get user\n user_profile_data = CustomUser.objects.get(id=req_dict['user_id'])\n user_serializer = serializers.CustomUserDetailsSerializer(user_profile_data)\n\n # get rating\n ratings = Rating.objects.filter(being_rated=req_dict['user_id'])\n\n for rating in ratings:\n serialized_rating = serializers.RatingSerializer(rating)\n total_rating += int(serialized_rating.data['rating'])\n\n if total_rating > 0:\n total_rating = total_rating/len(ratings)\n\n # add all necessary fields to the return object\n return_object = {\n \"business_name\": user_serializer.data['business_name'],\n \"profile_picture\": user_serializer.data['profile_picture'],\n \"description\": user_serializer.data['description'],\n \"location\": user_serializer.data['location'],\n \"phone\": user_serializer.data['phone'], \n \"rating\": total_rating,\n \"user_name\": user_serializer.data['name'],\n \"business_id\": user_serializer.data['id'],\n \"user_projects\": user_serializer.data['jobs'] if len(user_serializer.data['jobs']) > 0 else []\n }\n\n return JsonResponse(return_object, safe=False, status=200) \n except:\n return JsonResponse({'error':'failed retrieving user info','status':'failure'}, status=400)\n\n@api_view(['POST'])\ndef userUpdateProfile(request):\n\n try:\n req_dict = request.data\n token = Token.objects.get(key=req_dict['session_token'])\n\n # get user\n user_profile_data = CustomUser.objects.get(id=token.user_id)\n print(user_profile_data.business_name)\n serialized_qs = serializers.CustomUserDetailsSerializer(user_profile_data, data={'name': req_dict['name'], 'business_name': req_dict['business_name'], 'description': req_dict['description'], 'phone': req_dict['phone_number'], 'location':req_dict['location']}, partial=True)\n \n if serialized_qs.is_valid():\n serialized_qs.save()\n\n return JsonResponse({'status': 'success'}, status=200)\n\n except:\n return JsonResponse({'error':'Failed updating user info','status':'failure'}, status=400)\n\n\nfrom rest_auth.views import LoginView, LogoutView\nclass LogoutViewCustom(LogoutView):\n authentication_classes = (TokenAuthentication,)\n \n\nclass LoginViewCustom(LoginView):\n authentication_classes = (TokenAuthentication,)\n\nclass RegisterViewCustom(RegisterView):\n authentication_classes = (TokenAuthentication,)\n\nclass VerifyEmailViewCustom(VerifyEmailView):\n authentication_classes = (TokenAuthentication,)\n\n\n\n##### POST: /user/rate ###\n@api_view([\"POST\"])\ndef userSendRating(request):\n\n req_dict = json.loads(request.body)\n\n try:\n token = Token.objects.get(key=req_dict['session_token'])\n user = CustomUser.objects.get(id=token.user_id)\n being_rated = CustomUser.objects.get(id=req_dict['user_being_rated_id'])\n rating_val = req_dict['rating']\n\n if int(rating_val) < 0 or int(rating_val) > 5: # ensure rating is between 1 and 5 \n return JsonResponse({'error': 'please give a rating between 1 and 5', 'status': 'failure'}, status=400)\n\n # update existing rating object\n rating = Rating.objects.get(rater=user, being_rated=being_rated)\n \n serialized_qs = serializers.RatingSerializer(rating, data={'rating': req_dict['rating']}, partial=True)\n if serialized_qs.is_valid():\n serialized_qs.save()\n\n return JsonResponse({'status': 'success'}, status=200)\n except ObjectDoesNotExist: # if rating doesn't exist\n\n rating = Rating.objects.create(rating=req_dict['rating'], rater=user, being_rated=being_rated)\n return JsonResponse({'status': 'success'}, status=200)\n\n except:\n return JsonResponse({'error':'failed posting rating','status':'failure'}, status=400)\n\n\nclass resultPage(object):\n def __init__(self, amount, total, results):\n self.amount = amount\n self.total = total\n self.results = results\n \nsorted_hash = []\n#POST: /user/search\n@api_view([\"POST\"])\ndef userSearch(request):\n req_dict = request.data\n # try:\n terms = req_dict['search_terms'].split()\n searchLocal = req_dict['location']\n pageAmount = int(req_dict['page_amount'])\n pageNumber =int(req_dict['page_number'])\n result_hash = {}\n user_list = models.CustomUser.objects.all()\n\n \n\n #search job, description and business for search terms, if none add all to results\n if(len(terms)>0):\n for term in terms:\n queryset = user_list.filter(\n Q(business_name__icontains=term) | \n Q(description__icontains=term) | \n Q(name__icontains=term))\n for q in queryset:\n if q in result_hash.keys():\n result_hash[q] = result_hash[q]+1\n else:\n result_hash[q] = 1 \n else:\n for q in user_list:\n result_hash[q] = 1\n\n if (searchLocal!=\"\"):\n for q in list(result_hash.keys()):\n if q.location!=searchLocal:\n del result_hash[q]\n\n sorted_hash = sorted(result_hash.items(), key=operator.itemgetter(1),reverse=True)\n\n \n # #Display Results according to page parameters\n temp_list = []\n if(len(sorted_hash)<=pageAmount):\n if(pageNumber==0):\n for i in sorted_hash:\n temp_list.append(i[0])\n else:\n return HttpResponse(\"\")\n else:\n temp_list = []\n for i in range(pageAmount*pageNumber, (pageAmount*pageNumber)+pageAmount):\n temp_list.append(sorted_hash[i][0])\n pageResponse = resultPage(len(temp_list),len(sorted_hash),temp_list)\n serialized_qs = serializers.resultSerializer(pageResponse)\n return HttpResponse(JSONRenderer().render(serialized_qs.data), content_type='application/json')\n\n # except:\n # return JsonResponse({'error':'search failed','status':'failure'}, status=400)","sub_path":"backend/uaConsultants/user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"275077020","text":"\"\"\"\ntests.test_api.py\n~~~~~~~~~~~~~~~~~\nTest api calls\n\"\"\"\n\nimport json\nfrom pprint import pformat as pf\n\nimport pytest\n\nimport api\n\n\ndef test_client(api_client):\n assert api_client\n\n\n@pytest.mark.parametrize(\n \"params\", [\"hub.verify_token=invalid\", \"hub.verify_token=foo&hub.challenge=bar\"]\n)\ndef test_webhook_always_return_200(api_client, params):\n assert api_client.get(f\"/webhook?{params}\").status_code == 200\n\n\n@pytest.mark.parametrize(\n \"params\",\n [\n \"hub.verify_token=invalid&hub.mode=subscribe\",\n \"hub.verify_token=foo\",\n \"hub.verify_token=foobar&hub.mode=unsubscribe\",\n ],\n)\ndef test_get_webhook_failed(api_client, params, monkeypatch):\n monkeypatch.setattr(api.main, \"FB_VERIFY_TOKEN\", value=\"foobar\")\n response = api_client.get(f\"/webhook?{params}\")\n assert response.json() == \"Invalid Request or Verification Token\"\n monkeypatch.undo()\n\n\n@pytest.mark.parametrize(\"token,challenge\", [(\"foo\", 123), (\"flamingo\", \"ant\")])\ndef test_get_webhook_succeeded(api_client, token, challenge, monkeypatch):\n monkeypatch.setattr(api.main, \"FB_VERIFY_TOKEN\", value=token)\n response = api_client.get(\n f\"/webhook?hub.verify_token={token}&hub.challenge={challenge}&hub.mode=subscribe\"\n )\n assert response.json() == challenge\n monkeypatch.undo()\n\n\ndef test_get_privacy_policy(api_client):\n assert api_client.get(\"/privacy-policy\").status_code == 200\n\n\ndef test_post_message_200_resp_valid_data(api_client, test_data_valid_event, mocker):\n mocker.patch(\"api.utils.handle_user_message\", return_value=\"mocked response\")\n resp = api_client.post(f\"/webhook\", data=json.dumps(test_data_valid_event))\n print(f\"Response: \\n{pf(resp.json())}\")\n assert resp.status_code == 200\n","sub_path":"Covid Tracking Bot/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"585670859","text":"import dearpygui.dearpygui as dpg \n\nimport numpy as np\nimport struct\nimport serial \nimport time \n\n\nCOMPORT = 'COM16'\nBAUDRATE = 9600\n\ntry: comp = serial.Serial( COMPORT, baudrate = BAUDRATE )\nexcept: print(0)\n\nX = [ 0 for _ in range(100) ]\nY = [ 0 for _ in range(100) ]\nZ = [ 0 for _ in range(100) ]\n\ndef make_data_run( phase ):\n global X\n global Y\n global Z\n t = np.linspace(0,2*np.pi, 100)\n X = np.cos(t + np.radians(phase) )\n Y = np.sin(2*t + np.radians(phase) )\n Z = np.cos(t + np.radians(phase) )*np.sin(t + np.radians(phase) )\n \n dpg.configure_item(\"X_value\", x = t, y = X )\n dpg.configure_item(\"Y_value\", x = t, y = Y )\n dpg.configure_item(\"Z_value\", x = t, y = Z )\n\ndef att_data_run( x_val, y_val, z_val ):\n global X\n global Y \n global Z\n \n t = np.linspace(0,2*np.pi, 100)\n \n X.append(x_val)\n X.pop(0)\n \n Y.append(y_val)\n Y.pop(0)\n \n Z.append(z_val)\n Z.pop(0)\n\n dpg.configure_item(\"X_value\", x = t, y = X )\n dpg.configure_item(\"Y_value\", x = t, y = Y )\n dpg.configure_item(\"Z_value\", x = t, y = Z )\n\n \n\nwith dpg.window() as main_window:\n pass\n\nwith dpg.window(id='Ploter', label=\"simple plot\", no_resize=True, no_title_bar=True, no_move=True):\n with dpg.plot(id='Graph', label=\"Plot Acelerometro\", height=300, width=400, anti_aliased=True):\n dpg.add_plot_legend()\n\n dpg.add_plot_axis(dpg.mvXAxis, label=\"Tempo\", id='x_axis')\n dpg.set_axis_limits(\"x_axis\", 0, 2*3.1415)\n\n dpg.add_plot_axis(dpg.mvYAxis, label=\"Valores XYZ\", id=\"y_axis\")\n #dpg.set_axis_limits('y_axis', -1.25,1.25)\n \n dpg.add_line_series([], [], label=\"X_value\", id=\"X_value\", parent=\"y_axis\")\n dpg.add_line_series([], [], label=\"Y_value\", id=\"Y_value\", parent=\"y_axis\")\n dpg.add_line_series([], [], label=\"Z_value\", id=\"Z_value\", parent=\"y_axis\")\n\n\ndef resize_group( sender, data, user ):\n dpg.configure_item('Ploter', height = data[1], width = data[0] ) \n dpg.configure_item('Graph', height = data[1]*0.9, width = data[0]*0.9, pos=[ data[0]*0.05, data[1]*0.05] ) \n\n\ndpg.setup_viewport()\n\ndpg.set_primary_window ( main_window, True )\ndpg.set_viewport_min_height( height = 700 ) \ndpg.set_viewport_min_width ( width = 800 ) \ndpg.set_viewport_title ( title = 'Ploter Acelerometro' )\n\ndpg.maximize_viewport() \n\ndpg.add_resize_handler(main_window, callback=resize_group)\n\n\n\nx_data, y_data, z_data = 0.0, 0.0, 0.0 \n\nwhile dpg.is_dearpygui_running():\n dpg.render_dearpygui_frame() \n count = dpg.get_frame_count() \n try: \n pBytes = b''\n while comp.in_waiting: \n nBytes = comp.inWaiting()\n pBytes += comp.read(nBytes)\n time.sleep(0.001)\n #print(pBytes)\n\n print( f'[{count} / {len(pBytes)}]: {pBytes}' ) \n #x_data, y_data, z_data = struct.unpack('fff', pBytes )\n #att_data_run(x_data, y_data, z_data)\n except: \n pass#print( e, f'. Recebido um buffer de {nBytes}' )\n","sub_path":"MMA845x/ploter.py","file_name":"ploter.py","file_ext":"py","file_size_in_byte":3051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"566062675","text":"'''\r\nCreated on Dec 16, 2016\r\n\r\n@author: Dragos Stefanescu\r\n'''\r\nfrom copy import deepcopy\r\nfrom Domain.Client import Client\r\n\r\nclass FileRepository:\r\n def __init__ (self,fName):\r\n '''\r\n Initializarea Repository-ului pentru clienti\r\n fName : string , numele fisierului \r\n '''\r\n self.__lista = []\r\n self.__fName = fName\r\n self.__load_from_file()\r\n \r\n def __load_from_file(self):\r\n '''\r\n Incarca clientii din fisier\r\n '''\r\n try:\r\n f = open(self.__fName , \"r\")\r\n except IOError :\r\n return \r\n \r\n line = f.readline().strip()\r\n \r\n while line != \"\":\r\n atribute = line.split(\",\")\r\n client = Client(int(atribute[0]),atribute[1],atribute[2])\r\n self.__lista.append(client)\r\n line = f.readline().strip()\r\n \r\n f.close()\r\n \r\n def gasesteZbor(self , cod):\r\n '''\r\n Functie ce returneaza clientii cu un zbor cu un anumit cod\r\n +cod : int , codul zborului \r\n '''\r\n lista = []\r\n all_clients = self.getAll()\r\n for client in all_clients:\r\n if client.get_zbor() == cod:\r\n lista.append(client)\r\n \r\n return lista\r\n \r\n def getAll(self):\r\n '''\r\n Returneaza toti clientii din lista\r\n '''\r\n return deepcopy(self.__lista)","sub_path":"simulare fp/Repository/ClientiRepository.py","file_name":"ClientiRepository.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"112944410","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nfrom scrapy.pipelines.images import ImagesPipeline\nfrom scrapy import Request\nfrom parser_1semena.settings import IMAGES_STORE\nimport os\nimport json\n\n\n#class Parser1SemenaPipeline(object):\n# def process_item(self, item, spider):\n# return item\n\n\nclass JsonPipeline(object):\n def open_spider(self, spider):\n self.list_fields = [\"url\", \"last_segment_url\", \"breadcrumbs\", \"name\", \"product_summary\", \"product_price\", \"description_html\", \"description\",\n \"image\", \"image_\", \"product_tags\", \"product_categories\", \"features\", \"review\", ]\n self.name_fields = {\"url\": \"url\", \"last_segment_url\": \"последний сегмент url\", \"breadcrumbs\": \"хлебные крошки\",\n \"name\":\"название\", \"product_summary\": \"краткое описание\", \"product_price\": \"цена\",\n \"description_html\": \"полное описание html\", \"description\": \"полное описание без тегов html\",\n \"image\": \"главное фото\", \"image_\": \"Фото\", \"product_tags\": \"теги\", \"product_categories\": \"Категории\",\n \"features\": \"Характеристики\", \"review\": \"Отзывы\"}\n self.indent = 8\n self.first_item = True\n self.file = open('semena.json', 'w')\n self.file.write(\"[\\n\" )\n\n\n def close_spider(self, spider):\n self.file.write(\"\\n]\\n\")\n self.file.close()\n\n\n def write_field(self, field, level):\n if isinstance(field, (list, tuple)):\n self.file.write(\"[\\n\")\n for i, it in enumerate(field):\n self.file.write(\" \" * self.indent * level)\n self.write_field(it, level + 1)\n if not (i == len(field) - 1):\n self.file.write(\",\")\n self.file.write(\"\\n\")\n self.file.write(\" \" * self.indent * (level - 1))\n self.file.write(\"]\")\n elif isinstance(field, dict):\n self.file.write(\"{\\n\")\n for i, it in enumerate(field):\n self.file.write(\" \" * self.indent * level)\n self.file.write(json.dumps(it, ensure_ascii=False))\n self.file.write(\": \")\n self.write_field(field[it], level + 1)\n if not (i == len(field) - 1):\n self.file.write(\",\")\n self.file.write(\"\\n\")\n self.file.write(\" \" * self.indent * (level - 1))\n self.file.write(\"}\")\n else:\n self.file.write(json.dumps(field, ensure_ascii=False))\n\n\n def process_item(self, item, spider):\n if self.first_item:\n self.first_item = False\n else:\n self.file.write(\",\\n\")\n\n self.file.write(\" \" * self.indent + \"{\\n\")\n for f, field in enumerate(self.list_fields):\n if field in item:\n self.file.write(\" \" * self.indent * 2)\n self.file.write(json.dumps(self.name_fields[field], ensure_ascii=False))\n self.file.write(\": \")\n self.write_field(item[field], 3)\n if not (f == len(self.list_fields) - 1):\n self.file.write(\",\")\n self.file.write(\"\\n\")\n self.file.write(\" \" * self.indent + \"}\")\n return item\n\n '''\n def __init__(self):\n self.file = open(\"semena.json\", 'wb')\n self.exporter = JsonItemExporter(self.file, encoding='utf-8', ensure_ascii=False, indent=8)\n self.exporter.start_exporting()\n\n\n def close_spider(self, spider):\n self.exporter.finish_exporting()\n self.file.close()\n\n\n def process_item(self, item, spider):\n self.exporter.export_item(item)\n return item\n '''\n\n\nclass ImageNamePipeline(ImagesPipeline):\n def get_media_requests(self, item, info):\n path = IMAGES_STORE + '/%s' % item['last_segment_url']\n try:\n os.mkdir(path)\n except:\n pass\n\n return [Request(x, meta={'image_dir': item['last_segment_url'], 'image_name': item['image'] if i==0 else item['image_'][i-1]})\n for i, x in enumerate(item.get('image_url', []), start=0)]\n\n\n def file_path(self, request, response=None, info=None):\n return \"{0}/{1}\".format(request.meta['image_dir'], request.meta['image_name'])\n","sub_path":"parser_1semena/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":4577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"107656922","text":"def peven(n):\n s = 0\n i = 0 \n for i in range(2, n + 1, 2):\n s += 1.0 / i\n return(s)\n\ndef podd(n):\n s = 0\n for i in range(1, n + 1, 2):\n s += 1.0/i\n return(s)\n\ndef dcall(fn, n):\n s = fn(n)\n return(s)\n\nif __name__ == \"__main__\":\n n = int(input(\"Please input a number:\\n\"))\n if n % 2 == 0:\n sum = dcall(peven, n)\n else:\n sum = dcall(podd, n)\n print(sum)\n","sub_path":"100 exercises/76.py","file_name":"76.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"450707347","text":"print(\"Loading\")\nimport matplotlib.pyplot as plt\n\n# Create a pipeline that standardizes the data then creates a model\n#Load libraries for data processing\nimport pandas as pd #data processing, CSV file I/O (e.g. pd.read_csv)\nimport numpy as np\nfrom scipy.stats import norm\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.cross_validation import cross_val_score, KFold\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\n# visualization\nimport seaborn as sns \nplt.style.use('fivethirtyeight')\nsns.set_style(\"white\")\n\nplt.rcParams['figure.figsize'] = (8,4) \n#plt.rcParams['axes.titlesize'] = 'large'\nprint(\"Successful\")\n\n#load data\nprint(\"Loading dataset\")\ndata = pd.read_csv('data/clean-data.csv', index_col=False)\nprint(\"Data recieved \" , data)\ndata.drop('Unnamed: 0',axis=1, inplace=True)\nprint(\"Dropping ID\")\n# Split-out validation dataset\narray = data.values\nX = array[:,1:31]\ny = array[:,0]\nprint(\"Split X\" , X)\nprint(\"Split y \", y)\n\n# Divide records in training and testing sets.\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=7)\n\n#transform the class labels from their original string representation (M and B) into integers\nle = LabelEncoder()\ny = le.fit_transform(y)\nprint(\"Label Encoder \", y)\nprint(\"----------------------------------------------------------------\")\n\n# Spot-Check Algorithms\nmodels = []\nmodels.append(( 'LogisticRegression' , LogisticRegression()))\nmodels.append(( 'LinearDiscriminantAnalysis' , LinearDiscriminantAnalysis()))\nmodels.append(( 'KNeighborsClassifier' , KNeighborsClassifier()))\nmodels.append(( 'DecisionTreeClassifier' , DecisionTreeClassifier()))\nmodels.append(( 'GaussianNB' , GaussianNB()))\nmodels.append(( 'SVM' , SVC()))\n\n# Test options and evaluation metric\nnum_folds = 10\nnum_instances = len(X_train)\nseed = 7 \nscoring = 'accuracy'\n\n# Test options and evaluation metric\nnum_folds = 10\nnum_instances = len(X_train)\nseed = 7 \nscoring = 'accuracy'\nresults = []\nnames = []\nfor name, model in models:\n kfold = KFold(n=num_instances, n_folds=num_folds, random_state=seed)\n cv_results = cross_val_score(model, X_train, y_train, cv=kfold, scoring=scoring)\n results.append(cv_results)\n names.append(name)\n msg = \"%s: %f (%f)\" % (name, cv_results.mean(), cv_results.std())\n print(msg)\nprint('-> 10-Fold cross-validation accurcay score for the training data for six classifiers')\n\n# # Compare Algorithmsss\n# fig = plt.figure()\n# fig.suptitle( 'Algorithm Comparison' )\n# ax = fig.add_subplot(111)\n# plt.boxplot(results)\n# ax.set_xticklabels(names)\n# plt.show()\n\n# Standardize the dataset\npipelines = []\npipelines.append(( 'ScaledLR' , Pipeline([( 'Scaler' , StandardScaler()),( 'LR' ,\n LogisticRegression())])))\npipelines.append(( 'ScaledLDA' , Pipeline([( 'Scaler' , StandardScaler()),( 'LDA' ,\n LinearDiscriminantAnalysis())])))\npipelines.append(( 'ScaledKNN' , Pipeline([( 'Scaler' , StandardScaler()),( 'KNN' ,\n KNeighborsClassifier())])))\npipelines.append(( 'ScaledCART' , Pipeline([( 'Scaler' , StandardScaler()),( 'CART' ,\n DecisionTreeClassifier())])))\npipelines.append(( 'ScaledNB' , Pipeline([( 'Scaler' , StandardScaler()),( 'NB' ,\n GaussianNB())])))\npipelines.append(( 'ScaledSVM' , Pipeline([( 'Scaler' , StandardScaler()),( 'SVM' , SVC())])))\n\nresults = []\nnames = []\nfor name, model in pipelines:\n kfold = KFold(n=num_instances, n_folds=num_folds, random_state=seed)\n cv_results = cross_val_score(model, X_train, y_train, cv=kfold,\n scoring=scoring)\n results.append(cv_results)\n names.append(name)\n msg = \"%s: %f (%f)\" % (name, cv_results.mean(), cv_results.std())\n# print(msg)\n\n# Compare Algorithms\n# fig = plt.figure()\n# fig.suptitle( 'Scaled Algorithm Comparison' )\n# ax = fig.add_subplot(111)\n# plt.boxplot(results)\n# ax.set_xticklabels(names)\n# plt.show()\n\n#Make Support Vector Classifier Pipeline\npipe_svc = Pipeline([('scl', StandardScaler()),\n ('pca', PCA(n_components=2)),\n ('clf', SVC(probability=True, verbose=False))])\n\n#Fit Pipeline to training Data\npipe_svc.fit(X_train, y_train)\nprint(\"---------------------------------------------------------------------------\")\nprint('--> Fitted Pipeline to training Data')\n\nscores = cross_val_score(estimator=pipe_svc, X=X_train, y=y_train, cv=10, n_jobs=1, verbose=0)\nprint(\"---------------------------------------------------------------------------\")\n\nprint('--> Model Training Accuracy: %.3f +/- %.3f' %(np.mean(scores), np.std(scores)))\n\n#Tune Hyperparameters\nparam_range = [0.0001, 0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 1000.0]\nparam_grid = [{'clf__C': param_range,'clf__kernel': ['linear']},\n {'clf__C': param_range,'clf__gamma': param_range,\n 'clf__kernel': ['rbf']}]\ngs_svc = GridSearchCV(estimator=pipe_svc,\n param_grid=param_grid,\n scoring='accuracy',\n cv=10,\n n_jobs=1)\ngs_svc = gs_svc.fit(X_train, y_train)\nprint(\"---------------------------------------------------------------------------\")\nprint(\"Support Vector Classifier Pipeline\")\nprint('--> Tuned Parameters Best Score: ',gs_svc.best_score_)\nprint('--> Best Parameters: \\n',gs_svc.best_params_)\n\nprint(\"---------------------------------------------------------------------------\")\n\nprint(\"k-NN hyperparameters\")\n\nfrom sklearn.neighbors import KNeighborsClassifier as KNN\n\npipe_knn = Pipeline([('scl', StandardScaler()),\n ('pca', PCA(n_components=2)),\n ('clf', KNeighborsClassifier())])\n \n#Fit Pipeline to training Data\npipe_knn.fit(X_train, y_train) \n\nscores = cross_val_score(estimator=pipe_knn, \n X=X_train, \n y=y_train, \n cv=10,\n n_jobs=1)\nprint(\"---------------------------------------------------------------------------\")\nprint('--> Model Training Accuracy: %.3f +/- %.3f' %(np.mean(scores), np.std(scores)))\n\n#Tune Hyperparameters\nparam_range = range(1, 31)\nparam_grid = [{'clf__n_neighbors': param_range}]\n# instantiate the grid\ngrid = GridSearchCV(estimator=pipe_knn, \n param_grid=param_grid, \n cv=10, \n scoring='accuracy')\ngs_knn = grid.fit(X_train, y_train)\nprint(\"---------------------------------------------------------------------------\")\n\nprint('--> Tuned Parameters Best Score: ', gs_knn.best_score_)\nprint('--> Best Parameters: \\n', gs_knn.best_params_)\n\nprint(\"---------------------------------------------------------------------------\")\n\n#Use best parameters\nclf_svc = gs_svc.best_estimator_\n\n#Get Final Scores\nclf_svc.fit(X_train, y_train)\nscores = cross_val_score(estimator=clf_svc,\n X=X_train,\n y=y_train,\n cv=10,\n n_jobs=1)\nprint(\"---------------------------------------------------------------------------\")\nprint('--> Final Model Training Accuracy: %.3f +/- %.3f' %(np.mean(scores), np.std(scores)))\n\nprint('--> Final Accuracy on Test set: %.5f' % clf_svc.score(X_test,y_test))\n\nprint(\"---------------------------------------------------------------------------\")\n\nclf_svc.fit(X_train, y_train)\ny_pred = clf_svc.predict(X_test)\n\nprint(accuracy_score(y_test, y_pred))\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))\n","sub_path":"using_different_ml_algorithms.py","file_name":"using_different_ml_algorithms.py","file_ext":"py","file_size_in_byte":7969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"10604986","text":"# -*- coding: utf-8 -*-\n\nimport re\n# from rest_framework import serializers\n\nfrom libs.exceptions import ParameterInvalidError\n\n\ndef phone_validator(value):\n if not re.match(r'^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$', value):\n raise ParameterInvalidError('请输入正确的手机号码')\n return value\n\n\nif __name__ == '__main__':\n print('@@@', phone_validator('16625111287'))\n","sub_path":"libs/mvalidators.py","file_name":"mvalidators.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"511370600","text":"def solution(board, moves):\n answer = 0 \n stack = []\n\n for i in moves:\n\n cnt = 0\n while cnt < len(board): \n\n if board[cnt][i - 1] != 0:\n if stack[-1:] == [board[cnt][i - 1]]:\n answer += 2\n stack.pop() \n else:\n stack.append(board[cnt][i - 1])\n\n board[cnt][i - 1] = 0\n cnt = len(board)\n\n cnt +=1\n\n return answer\n\n###############################################################\n\ndef solution2(board, moves):\n stacklist = []\n answer = 0\n\n for i in moves:\n for j in range(len(board)):\n if board[j][i-1] != 0:\n stacklist.append(board[j][i-1])\n board[j][i-1] = 0\n\n if len(stacklist) > 1:\n if stacklist[-1] == stacklist[-2]:\n stacklist.pop(-1)\n stacklist.pop(-1)\n answer += 2 \n break\n\n return answer","sub_path":"programmers/lv1/크레인인형뽑기.py","file_name":"크레인인형뽑기.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"427556063","text":"#!/usr/bin/env nativepython3\n# BSD 2-Clause License\n#\n# Copyright (c) 2020, Konrad Weihmann\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# 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# Based on the public domain script from\n# https://github.com/eliben/pyelftools/blob/master/examples/dwarf_lineprogram_filenames.py\n# originally written by William Woodruff (william@yossarian.net)\n\nfrom __future__ import print_function\n\nimport argparse\nimport glob\nimport os\nimport sys\nfrom collections import defaultdict\n\nfrom elftools.common.exceptions import ELFError\nfrom elftools.elf.elffile import ELFFile\n\ndef create_parser():\n parser = argparse.ArgumentParser(\n description='Tracefiles - get original sources from packaged files')\n parser.add_argument(\"pkgroot\", help=\"Root dir to packages\")\n parser.add_argument(\"sourcesdir\", help=\"Root dir to original sources\")\n parser.add_argument(\"files\", nargs='+', help=\"Files to parse\")\n\n return parser.parse_args()\n \ndef process_file(filename, root, pkgroot):\n res = set()\n if os.path.isdir(filename) or not os.access(filename, os.R_OK):\n return res\n try:\n with open(filename, 'rb') as f:\n try:\n elffile = ELFFile(f)\n if not elffile.has_dwarf_info():\n return res\n\n dwarfinfo = elffile.get_dwarf_info()\n for CU in dwarfinfo.iter_CUs():\n # Every compilation unit in the DWARF information may or may not\n # have a corresponding line program in .debug_line.\n line_program = dwarfinfo.line_program_for_CU(CU)\n if line_program is None:\n continue\n\n # Print a reverse mapping of filename -> #entries\n res.update(line_entry_mapping(line_program))\n except ELFError:\n return find_in_source_root(filename, root, pkgroot)\n except OSError:\n pass\n return res\n\ndef find_in_source_root(filename, root, pkgroot):\n for x in [filename.replace(pkgroot, \"\", 1), filename.replace(pkgroot, \"\", 1) + \".in\"]:\n _clean = x.lstrip(\"/\").split(\"/\")\n while _clean:\n _tmp = glob.glob(os.path.join(root, *_clean))\n _tmp += glob.glob(os.path.join(root, \"*\", *_clean))\n _tmp += glob.glob(os.path.join(root, \"**\", *_clean))\n if _tmp:\n return _tmp\n _clean = _clean[1:]\n return []\n\ndef line_entry_mapping(line_program):\n res = set()\n filename_map = defaultdict(int)\n\n # The line program, when decoded, returns a list of line program\n # entries. Each entry contains a state, which we'll use to build\n # a reverse mapping of filename -> #entries.\n lp_entries = line_program.get_entries()\n for lpe in lp_entries:\n # We skip LPEs that don't have an associated file.\n # This can happen if instructions in the compiled binary\n # don't correspond directly to any original source file.\n if not lpe.state or lpe.state.file == 0:\n continue\n filename = lpe_filename(line_program, lpe.state.file)\n filename_map[filename] += 1\n\n for filename, _ in filename_map.items():\n if not filename.startswith(\"/\"):\n res.add(filename)\n return res\n\ndef lpe_filename(line_program, file_index):\n # Retrieving the filename associated with a line program entry\n # involves two levels of indirection: we take the file index from\n # the LPE to grab the file_entry from the line program header,\n # then take the directory index from the file_entry to grab the\n # directory name from the line program header. Finally, we\n # join the (base) filename from the file_entry to the directory\n # name to get the absolute filename.\n lp_header = line_program.header\n file_entries = lp_header[\"file_entry\"]\n\n # File and directory indices are 1-indexed.\n file_entry = file_entries[file_index - 1]\n dir_index = file_entry[\"dir_index\"]\n\n # A dir_index of 0 indicates that no absolute directory was recorded during\n # compilation; return just the basename.\n if dir_index == 0:\n return file_entry.name.decode()\n\n directory = lp_header[\"include_directory\"][dir_index - 1]\n return os.path.join(directory, file_entry.name).decode()\n\n\nif __name__ == '__main__':\n args = create_parser()\n res = set()\n for filename in args.files:\n res.update(process_file(filename, args.sourcesdir, args.pkgroot))\n print(\"\\n\".join([os.path.join(args.sourcesdir, x) for x in sorted(res)]))\n","sub_path":"recipes-support/tracefiles-native/files/tracefiles.py","file_name":"tracefiles.py","file_ext":"py","file_size_in_byte":5803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"433275344","text":"import tensorflow as tf\nimport numpy as np\nimport os\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nBATCH_SIZE = 32\nEPOCH = 50000\nSAVE_DIR = '/home/konosuke-a/python_code/cnncancer_k/MNIST/vae' # absolute path\nconfig = tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True))\n\nmnist = input_data.read_data_sets('MNIST_data', one_hot=False)\n\ndef batchnorm(input):\n with tf.variable_scope('batchnorm',reuse=tf.AUTO_REUSE):\n input = tf.identity(input)\n channels = input.get_shape()[3]\n print(input.get_shape())\n offset = tf.get_variable(\"offset_{}\".format(channels), [channels], dtype=tf.float32, initializer=tf.zeros_initializer())\n scale = tf.get_variable(\"scale_{}\".format(channels), [channels], dtype=tf.float32, initializer=tf.random_normal_initializer(1.0, 0.02))\n mean, variance = tf.nn.moments(input, axes=[0, 1, 2], keep_dims=False)\n variance_epsilon = 1e-5\n normalized = tf.nn.batch_normalization(input, mean, variance, offset, scale, variance_epsilon=variance_epsilon)\n return normalized\n\ndef Save_all_variables(save_dir,sess):\n names = [v.name for v in tf.trainable_variables()]\n for n in names:\n v = tf.get_default_graph().get_tensor_by_name(n)\n save_name = n.split('/')[-1].split(':')[0]\n print('saved variables ', save_dir +'/variables/'+ save_name + '.npy')\n np.save(save_dir +'/variables/'+ save_name + '.npy', sess.run(v))\n\n\ndef lrelu(x,a=0.2):\n with tf.name_scope('lrelu'):\n x = tf.identity(x)\n return (0.5 * (1+a)*x + (0.5*(1-a)) * tf.abs(x))\n\nwith tf.variable_scope('Encoder'):\n with tf.variable_scope('Input'):\n x = tf.placeholder(tf.float32, shape=[BATCH_SIZE, 784], name='input_x')\n x_image = tf.reshape(x,[-1,28,28,1])\n \n with tf.variable_scope('conv1'):\n # [n,28,28,1] -> [n,14,14,32]\n pad = tf.pad(x_image,[[0,0],[1,1],[1,1],[0,0]],mode='CONSTANT')\n w_conv1 = tf.get_variable(name='w_conv1',shape=[4,4,1,32], dtype=tf.float32, initializer=tf.random_normal_initializer(0,0.02))\n b_conv1 = tf.get_variable(name='b_conv1',shape=[32], dtype=tf.float32, initializer=tf.random_normal_initializer(0,0.02))\n conv1 = lrelu(tf.nn.conv2d(pad,w_conv1,strides=[1,2,2,1],padding='VALID') + b_conv1)\n \n with tf.variable_scope('conv2'):\n # [n,14,14,32] -> [n,7,7,64]\n pad = tf.pad(conv1,[[0,0],[1,1],[1,1],[0,0]],mode='CONSTANT')\n w_conv2 = tf.get_variable(name='w_conv2',shape=[4,4,32,64], dtype=tf.float32, initializer=tf.random_normal_initializer(0,0.02))\n b_conv2 = tf.get_variable(name='b_conv1',shape=[64], dtype=tf.float32, initializer=tf.random_normal_initializer(0,0.02))\n conv2 = lrelu(tf.nn.conv2d(pad,w_conv2,strides=[1,2,2,1],padding='VALID') + b_conv2)\n \n with tf.variable_scope('mu_vector'):\n print(conv2.get_shape())\n conv2_flatten = tf.reshape(conv2, [BATCH_SIZE,7*7*64])\n w_mu = tf.get_variable(name='w_mu', shape=[7*7*64,2],dtype=tf.float32, initializer=tf.random_normal_initializer(0,0.02))\n b_mu = tf.get_variable(name='b_mu', shape=[2],dtype=tf.float32, initializer=tf.random_normal_initializer(0,0.02))\n mu3 = tf.matmul(conv2_flatten, w_mu) + b_mu\n \n with tf.variable_scope('sigma_vector'):\n conv2_flatten = tf.reshape(conv2, [BATCH_SIZE,7*7*64])\n w_sigma = tf.get_variable(name='w_sigma', shape=[7*7*64,2],dtype=tf.float32, initializer=tf.random_normal_initializer(0,0.02))\n b_sigma = tf.get_variable(name='b_sigma', shape=[2],dtype=tf.float32, initializer=tf.random_normal_initializer(0,0.02))\n sigma3 = tf.matmul(conv2_flatten, w_sigma) + b_sigma\n\n with tf.variable_scope('z_vector'):\n z_vector = mu3 + sigma3*tf.random_normal([BATCH_SIZE,2],mean=0,stddev=1)\n\nwith tf.variable_scope('Decoder'):\n with tf.variable_scope('FC'):\n w_fc = tf.get_variable(name='w_fc', shape=[2,7*7*64])\n b_fc = tf.get_variable(name='b_fc', shape=[7*7*64])\n fc = lrelu(tf.matmul(z_vector,w_fc) + b_fc)\n \n with tf.variable_scope('deconv2'):\n n,h,w,ch = [int(i) for i in conv2.get_shape()]\n fc_tensor = tf.reshape(fc, [n,7,7,64])\n w_deconv2 = tf.get_variable(name='w_deconv2',shape=[5,5,32,64], dtype=tf.float32, initializer=tf.random_normal_initializer(0,0.02))\n b_deconv2 = tf.get_variable(name='b_deconv2',shape=[32], dtype=tf.float32, initializer=tf.random_normal_initializer(0,0.02))\n deconv2 = lrelu(tf.nn.conv2d_transpose(fc_tensor, w_deconv2, [n, h*2, w*2, 32], [1,2,2,1], padding=\"SAME\") + b_deconv2)\n\n with tf.variable_scope('deconv1'):\n n,h,w,ch = [int(i) for i in conv1.get_shape()]\n w_deconv1 = tf.get_variable(name='w_deconv1',shape=[5,5,1,32], dtype=tf.float32, initializer=tf.random_normal_initializer(0,0.02))\n b_deconv1 = tf.get_variable(name='b_deconv1',shape=[1], dtype=tf.float32, initializer=tf.random_normal_initializer(0,0.02))\n deconv1 = tf.nn.sigmoid(tf.nn.conv2d_transpose(deconv2, w_deconv1, [n, h*2, w*2, 1], [1,2,2,1], padding=\"SAME\") + b_deconv1)\n\nwith tf.variable_scope('loss'):\n EPS = 1e-7\n # NOTE なぜか論文記載の方法では学習がうまくいかなかった. 後ほど原因検証.\n #reconsruct_loss = 1/BATCH_SIZE * tf.reduce_sum(x_image*tf.log(deconv1+EPS) - (1-x_image)*tf.log(1-deconv1+EPS))\n #kl_loss = 0.5*tf.reduce_sum(1+tf.log(sigma3**2 + EPS) - mu3**2 - sigma3**2)\n #reconsruct_loss = -tf.reduce_sum(x_image*tf.log(tf.clip_by_value(deconv1,1e-20,1e+20)) + (1-x_image)*tf.log(tf.clip_by_value(1-deconv1,1e-20,1e+20)))\n reconsruct_loss = -tf.reduce_sum(x_image*tf.log(deconv1 + EPS) + (1-x_image)*tf.log(1-deconv1 + EPS))\n #reconsruct_loss = tf.reduce_sum(tf.square(x_image-deconv1))/BATCH_SIZE\n\n kl_loss = 0.5*tf.reduce_sum(tf.square(mu3) + tf.exp(sigma3)**2 - 2*sigma3 -1)\n loss = reconsruct_loss + kl_loss\n\nwith tf.variable_scope('optimize'):\n trainable_vars_list = [var for var in tf.trainable_variables()]\n adam = tf.train.AdamOptimizer(0.0002,0.5)\n gradients_vars = adam.compute_gradients(loss, var_list=trainable_vars_list)\n train_op = adam.apply_gradients(gradients_vars)\n\nwith tf.name_scope('summary'):\n with tf.name_scope('Input_image_summary'):\n tf.summary.image('Input_image', tf.image.convert_image_dtype(x_image, dtype=tf.uint8, saturate=True))\n\n with tf.name_scope('Reconstruct_image_summary'):\n tf.summary.image('Reconstruct_image', tf.image.convert_image_dtype(deconv1, dtype=tf.uint8, saturate=True))\n\n with tf.name_scope('Loss_summary'):\n tf.summary.scalar('total_loss', loss)\n tf.summary.scalar('reconsruct_loss', reconsruct_loss)\n tf.summary.scalar('kl_loss', kl_loss)\n\n for var in tf.trainable_variables():\n tf.summary.histogram(var.op.name + '/Variable_histogram', var)\n\n for grad, var in gradients_vars:\n tf.summary.histogram(var.op.name + '/Gradients', grad)\n\n# Session\ninit = tf.global_variables_initializer()\nwith tf.Session(config=config) as sess:\n sess.run(init)\n\n # mkdir if not exist directory\n if not os.path.exists(SAVE_DIR): # NOT CHANGE\n os.mkdir(SAVE_DIR)\n os.mkdir(os.path.join(SAVE_DIR,'summary'))\n os.mkdir(os.path.join(SAVE_DIR,'variables'))\n \n # remove old summary if already exist\n if tf.gfile.Exists(os.path.join(SAVE_DIR,'summary')): # NOT CHANGE\n tf.gfile.DeleteRecursively(os.path.join(SAVE_DIR,'summary'))\n \n # merging summary & set summary writer\n merged = tf.summary.merge_all()\n summary_writer = tf.summary.FileWriter(os.path.join(SAVE_DIR,'summary'), graph=sess.graph)\n\n # train\n for step in range(EPOCH):\n x_batch, t_batch = mnist.train.next_batch(BATCH_SIZE)\n sess.run(train_op, feed_dict={x:x_batch}) \n if step % 50 == 0:\n print('step', step)\n print('reconsruct_loss: ', sess.run(reconsruct_loss, feed_dict={x:x_batch}))\n print('kl_loss: ', sess.run(kl_loss, feed_dict={x:x_batch}))\n print('total_loss: ', sess.run(loss, feed_dict={x:x_batch}))\n print()\n summary_writer.add_summary(sess.run(merged, feed_dict={x:x_batch}), step)\n \n Save_all_variables(save_dir=SAVE_DIR,sess=sess)\n \n # test (plot latent z-vector)\n x_test, t_test = mnist.test.images, mnist.test.labels\n batches = np.arange(0,10000-32,32)\n z_tmp = np.zeros([np.max(batches)+32, 2])\n for i in batches:\n z_tmp[i:i+32] = sess.run(z_vector, feed_dict={x:x_test[i:i+32]})\n print(z_tmp.shape)\n \n plt.figure()\n plt.title(\"Plot latent vector of VAE\")\n for i in range(len(z_tmp)):\n if t_test[i] == 0:\n p0 = plt.scatter(z_tmp[i,0], z_tmp[i, 1],c=\"red\",s=1)\n if t_test[i] == 1:\n p1 = plt.scatter(z_tmp[i,0], z_tmp[i, 1], c=\"blue\",s=1)\n if t_test[i] == 2:\n p2 = plt.scatter(z_tmp[i,0], z_tmp[i, 1], c=\"green\",s=1)\n if t_test[i] == 3:\n p3 = plt.scatter(z_tmp[i,0], z_tmp[i, 1], c=\"pink\",s=1)\n if t_test[i] == 4:\n p4 = plt.scatter(z_tmp[i,0], z_tmp[i, 1], c=\"yellow\",s=1)\n if t_test[i] == 5:\n p5 = plt.scatter(z_tmp[i,0], z_tmp[i, 1], c=\"orange\",s=1)\n if t_test[i] == 6:\n p6 = plt.scatter(z_tmp[i,0], z_tmp[i, 1], c=\"cyan\",s=1)\n if t_test[i] == 7:\n p7 = plt.scatter(z_tmp[i,0], z_tmp[i, 1], c=\"deeppink\",s=1)\n if t_test[i] == 8:\n p8 = plt.scatter(z_tmp[i,0], z_tmp[i, 1], c=\"c\",s=1)\n if t_test[i] == 9:\n p9 = plt.scatter(z_tmp[i,0], z_tmp[i, 1], c=\"purple\",s=1)\n plt.legend([p0,p1,p2,p3,p4,p5,p6,p7,p8,p9],[\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"], bbox_to_anchor=(1.01,1), loc=2, borderaxespad=0)\n filename = \"VAE_latent.png\"\n plt.savefig(filename)\n \n # TODO 10dim 混合ガウス分布を用いて、\n # unsupervisedに論文と同様の結果が得られるのか検証\n # ckptでモデル保存できるようにしたほうが簡単かも\n","sub_path":"MNIST/MNIST_VAE.py","file_name":"MNIST_VAE.py","file_ext":"py","file_size_in_byte":10104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"269441697","text":"import random\n\n\nclass Unit:\n def __init__(self, name, clan, base_skill=None,\n health=100, strength=1, agility=1, intelligence=1):\n self.name = name\n self.clan = clan\n self.base_skill = base_skill\n self.health = health\n self.strength = strength\n self.agility = agility\n self.intelligence = intelligence\n\n def __str__(self):\n return f'Профессия: {self.__class__.__name__} \\n' \\\n f'Имя: {self.name} \\n' \\\n f'Клан: {self.clan} \\n' \\\n f'Здоровье: ({self.health}/100) \\n' \\\n f'Оружие: '\n\n def do_healing(self):\n if self.health < 91:\n self.health += 10\n else:\n self.health = 100\n\n def do_skill_up(self): # вариант когда нам известны ВСЕ существующие хар-ки персонажей\n if self.base_skill == 'intelligence' and self.intelligence < 10:\n self.intelligence += 1\n if self.base_skill == 'agility' and self.agility < 10:\n self.agility += 1\n if self.base_skill == 'strength' and self.strength < 10:\n self.strength += 1\n\n\nclass Mage(Unit):\n def __init__(self, name, clan, base_skill='intelligence', __weapon=None):\n super(Mage, self).__init__(name, clan)\n self.base_skill = base_skill\n self.__weapon = random.choice(['Air', 'Fire', 'Water'])\n self.health = random.randint(59, 89) # удобней проверять do_healing\n\n def __str__(self):\n result = super(Mage, self).__str__()\n return f'{result} {self.__weapon} \\n' \\\n f'Баз.навык [{self.base_skill}] = {self.intelligence}'\n\n\nclass Archer(Unit):\n def __init__(self, name, clan, base_skill='agility', __weapon=None):\n super(Archer, self).__init__(name, clan)\n self.base_skill = base_skill\n self.__weapon = random.choice(['Bow', 'Arbalest', 'Sling'])\n self.health = random.randint(59, 89) # удобней проверять do_healing\n\n def __str__(self):\n result = super(Archer, self).__str__()\n return f'{result} {self.__weapon} \\n' \\\n f'Баз.навык [{self.base_skill}] = {self.agility}'\n\n\nclass Knight(Unit):\n def __init__(self, name, clan, base_skill='strength', __weapon=None):\n super(Knight, self).__init__(name, clan)\n self.base_skill = base_skill\n self.__weapon = random.choice(['Sword', 'Axe', 'Pike'])\n self.health = random.randint(59, 89) # удобней проверять do_healing\n\n def __str__(self):\n result = super(Knight, self).__str__()\n return f'{result} {self.__weapon} \\n' \\\n f'Баз.навык [{self.base_skill}] = {self.strength}'\n\n\nmage_1 = Mage('Harry Potter', 'Hogwarts School') # меняем имя профессии(класса)\n\nprint(mage_1, '\\n')\n\nmage_1.do_skill_up() # 2 раза повышаем базовый навык\nmage_1.do_skill_up()\nmage_1.do_healing() # 2 раза пополняем здоровье +10\nmage_1.do_healing()\nprint(mage_1)\n","sub_path":"HW11.py","file_name":"HW11.py","file_ext":"py","file_size_in_byte":3154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"176278517","text":"'''\nKth Largest Element in an unsorted array\nYou may assume k is always valid, 1 ≤ k ≤ array's length\n'''\nfrom heapq import heappush, heappop\nclass Solution(object):\n\n#using Naive Quicksort , choosing the rightmost element as pivot [TLE- O(nlon), worst case:O(n^2)]\n def findKthLargest(self, nums, k):\n self.quicksort(nums,0,len(nums)-1)\n return nums[-k]\n\n def quicksort(self,nums,lo,hi):\n if lo=k:\n return self.quickselect(nums, lo, pos-1, k)\n return self.quickselect(nums, pos+1, hi, k)\n\n def partitionl(self,nums,l,h):\n pivot=nums[h] # choose pivot as the last element\n i,j=l,l\n for j in range(l,h):\n if nums[j]>pivot: # decreasing\n nums[i],nums[j]=nums[j],nums[i]\n i+=1\n nums[i],nums[h]=nums[h],nums[i]\n return i\n\nobj=Solution()\nnums=[3,1,2,4]\nprint(obj.findKthLargest3(nums,2))\n","sub_path":"Sort/Kthlargest_215.py","file_name":"Kthlargest_215.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"197820777","text":"# Copyright 1996-2021 Cyberbotics Ltd.\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\"\"\"Joint state publisher.\"\"\"\n\nfrom sensor_msgs.msg import JointState\nfrom rclpy.time import Time\nfrom webots_ros2_core.webots.controller import Node\n\n\nclass JointStatePublisher:\n \"\"\"\n Publishes joint states.\n\n Discovers all joints with positional sensors and publishes corresponding ROS2 messages of type\n [`sensor_msgs/JointState`](https://github.com/ros2/common_interfaces/blob/master/sensor_msgs/msg/JointState.msg).\n\n Args:\n robot (WebotsNode): Webots Robot node.\n jointPrefix (str): Prefix to all joint names.\n node (Node): ROS2 node.\n \"\"\"\n\n def __init__(self, robot, joint_prefix, node, frame_id='joint_states'):\n \"\"\"Initialize the position sensors and the topic.\"\"\"\n self.__robot = robot\n self.__frame_id = frame_id\n self.__joint_prefix = joint_prefix\n self.__node = node\n self.__sensors = []\n self.__timestep = int(robot.getBasicTimeStep())\n self.__last_joint_states = None\n self.__previous_time = 0\n self.__previous_position = []\n self.__joint_names = []\n\n for i in range(robot.getNumberOfDevices()):\n device = robot.getDeviceByIndex(i)\n if device.getNodeType() == Node.POSITION_SENSOR:\n motor = device.getMotor()\n name = motor.getName() if motor is not None else device.getName()\n self.__joint_names.append(name)\n self.__sensors.append(device)\n self.__previous_position.append(0)\n device.enable(self.__timestep)\n self.__publisher = self.__node.create_publisher(JointState, 'joint_states', 1)\n\n def publish(self):\n \"\"\"Publish the 'joint_states' topic with up to date value.\"\"\"\n msg = JointState()\n msg.header.stamp = Time(seconds=self.__robot.getTime()).to_msg()\n msg.header.frame_id = self.__frame_id\n msg.name = [s + self.__joint_prefix for s in self.__joint_names]\n msg.position = []\n time_difference = self.__robot.getTime() - self.__previous_time\n for i in range(len(self.__sensors)):\n value = self.__sensors[i].getValue()\n msg.position.append(value)\n msg.velocity.append((value - self.__previous_position[i]) /\n time_difference if time_difference > 0 else 0.0)\n self.__previous_position[i] = value\n msg.effort = [0.0] * 6\n self.__publisher.publish(msg)\n self.__last_joint_states = msg\n self.__previous_time = self.__robot.getTime()\n","sub_path":"webots_ros2_core/webots_ros2_core/joint_state_publisher.py","file_name":"joint_state_publisher.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"394426419","text":"from odoo import api, fields, models\r\nimport logging\r\n_logger = logging.getLogger(__name__)\r\nfrom odoo import exceptions\r\nfrom datetime import datetime, timedelta\r\n\r\n\r\nclass ShippingInstructionWizard(models.TransientModel):\r\n _name = 'shipping.instruction.wizard'\r\n\r\n report_type = fields.Selection([('1', 'Shipping Instruction'), ('2', 'Shipping Instruction to Carrier')\r\n , ('3', 'Shipping Instruction (Excel)')], string=\"Report Type\" , default='1')\r\n service_type = fields.Selection([('ocean', 'Ocean'), ('air', 'Air'), ('land', 'Land')], string=\"Shipment Mode\")\r\n type = fields.Selection([('1', 'MAWB'), ('2', 'HAWB')], string='Type')\r\n to_char = fields.Char(string='TO')\r\n attn_char = fields.Char(string='ATTN')\r\n remarks = fields.Text(string='Remarks')\r\n\r\n shipper = fields.Text(string='Shipper')\r\n consignee = fields.Text(string='Consignee')\r\n oversea_agent = fields.Text(string='Overseas Agent')\r\n pcs_weight_m3 = fields.Char(string='Pcs/ Weight/ M3')\r\n commodity = fields.Char(string='Commodity')\r\n\r\n @api.model\r\n def default_get(self, fields):\r\n result = super(ShippingInstructionWizard, self).default_get(fields)\r\n si_id = self.env.context.get('si_id')\r\n if si_id:\r\n si = self.env['freight.website.si'].browse(si_id)\r\n if si.cargo_type == 'fcl':\r\n cargo_line = si.fcl_line_ids\r\n else:\r\n cargo_line = si.lcl_line_ids\r\n pcs = 0\r\n gross_weight = 0\r\n measurement = 0\r\n\r\n for si_line in cargo_line:\r\n pcs = pcs + si_line.packages_no\r\n gross_weight = gross_weight + si_line.exp_gross_weight\r\n measurement = measurement + si_line.exp_vol\r\n\r\n si_to_char = si.customer_name.name\r\n si_attn_char = si.contact_name.name\r\n si_note = si.note\r\n\r\n si_shipper = si.shipper\r\n si_consignee = si.consignee\r\n si_oversea_agent = si.shipping_agent\r\n si_pcs_weight_m3 = str(pcs) +' /' + str(gross_weight) +' /' + str(measurement)\r\n\r\n # for rec in self:\r\n result.update({'service_type': si.service_type,\r\n 'type': si.air_freight_type,\r\n 'to_char': si_to_char or False,\r\n 'attn_char': si_attn_char or False,\r\n 'remarks': si_note or False,\r\n 'shipper': si_shipper or False,\r\n 'consignee': si_consignee or False,\r\n 'oversea_agent': si_oversea_agent or False,\r\n 'pcs_weight_m3': si_pcs_weight_m3 or False,\r\n #'commodity': si.booking_ref.commodity.name or False,\r\n 'commodity': si.booking_ref.commodity1 or False,\r\n })\r\n result = self._convert_to_write(result)\r\n return result\r\n\r\n @api.multi\r\n def action_print(self):\r\n si = self.env['freight.website.si']\r\n si_ids = si.browse(self._context.get('active_ids'))\r\n if si_ids:\r\n if self.report_type == '1':\r\n si_ids.write({'air_freight_type': self.type,\r\n 'to_char': self.to_char,\r\n 'attn_char': self.attn_char,\r\n 'shipper': self.shipper,\r\n 'consignee': self.consignee,\r\n 'shipping_agent': self.oversea_agent,\r\n 'pcs_weight_m3': self.pcs_weight_m3,\r\n 'commodity': self.commodity,\r\n 'note': self.remarks,\r\n })\r\n return self.env.ref('sci_goexcel_shipping_instruction.action_si_report').report_action(si_ids)\r\n if self.report_type == '2':\r\n return self.env.ref('sci_goexcel_shipping_instruction.action_si_report_carrier').report_action(si_ids)\r\n if self.report_type == '3':\r\n return self.env.ref('sci_goexcel_freight.action_si_report_xlsx').report_action(si_ids)\r\n\r\n @api.multi\r\n def action_send(self):\r\n '''\r\n This function opens a window to compose an email, with the template message loaded by default\r\n '''\r\n\r\n si_id = self.env.context.get('si_id')\r\n if self.report_type == '1':\r\n si = self.env['freight.website.si'].browse(si_id)\r\n si.air_freight_type = self.type\r\n si.to_char = self.to_char\r\n si.attn_char = self.attn_char\r\n si.shipper = self.shipper\r\n si.consignee = self.consignee\r\n si.shipping_agent = self.oversea_agent\r\n si.pcs_weight_m3 = self.pcs_weight_m3\r\n si.commodity = self.commodity\r\n si.note = self.remarks\r\n\r\n self.ensure_one()\r\n ir_model_data = self.env['ir.model.data']\r\n try:\r\n template_id = \\\r\n ir_model_data.get_object_reference('sci_goexcel_shipping_instruction', 'email_template_si')[1]\r\n except ValueError:\r\n template_id = False\r\n try:\r\n compose_form_id = ir_model_data.get_object_reference('mail', 'email_compose_message_wizard_form')[1]\r\n except ValueError:\r\n compose_form_id = False\r\n\r\n ctx = {\r\n 'default_model': 'freight.website.si',\r\n 'default_res_id': self.env.context.get('si_id'),\r\n 'default_use_template': bool(template_id),\r\n 'default_template_id': template_id,\r\n 'default_composition_mode': 'comment',\r\n 'mark_so_as_sent': True,\r\n 'custom_layout': \"mail.mail_notification_light\",\r\n 'force_email': True\r\n }\r\n return {\r\n 'type': 'ir.actions.act_window',\r\n 'view_type': 'form',\r\n 'view_mode': 'form',\r\n 'res_model': 'mail.compose.message',\r\n 'views': [(compose_form_id, 'form')],\r\n 'view_id': compose_form_id,\r\n 'target': 'new',\r\n 'context': ctx,\r\n }\r\n if self.report_type == '2':\r\n '''\r\n This function opens a window to compose an email, with the template message loaded by default\r\n '''\r\n self.ensure_one()\r\n ir_model_data = self.env['ir.model.data']\r\n try:\r\n template_id = \\\r\n ir_model_data.get_object_reference('sci_goexcel_shipping_instruction', 'email_template_si_carrier')[\r\n 1]\r\n except ValueError:\r\n template_id = False\r\n try:\r\n compose_form_id = ir_model_data.get_object_reference('mail', 'email_compose_message_wizard_form')[1]\r\n except ValueError:\r\n compose_form_id = False\r\n\r\n ctx = {\r\n 'default_model': 'freight.website.si',\r\n 'default_res_id': self.env.context.get('si_id'),\r\n 'default_use_template': bool(template_id),\r\n 'default_template_id': template_id,\r\n 'default_composition_mode': 'comment',\r\n 'mark_so_as_sent': True,\r\n 'custom_layout': \"mail.mail_notification_light\",\r\n # 'proforma': self.env.context.get('proforma', False),\r\n 'force_email': True\r\n }\r\n # base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')\r\n # ctx['action_url'] = \"{}/web?db={}\".format(base_url, self.env.cr.dbname)\r\n return {\r\n 'type': 'ir.actions.act_window',\r\n 'view_type': 'form',\r\n 'view_mode': 'form',\r\n 'res_model': 'mail.compose.message',\r\n 'views': [(compose_form_id, 'form')],\r\n 'view_id': compose_form_id,\r\n 'target': 'new',\r\n 'context': ctx,\r\n }\r\n\r\n\r\n\r\n\r\n","sub_path":"sci_goexcel_shipping_instruction/wizard/shipping_instruction_wizard.py","file_name":"shipping_instruction_wizard.py","file_ext":"py","file_size_in_byte":8203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"477165313","text":"import numpy as np\ndef calcular_estado(candidatos_viejos, opciones, eliminar):\n candidatos = candidatos_viejos\n\n for i in range(0,np.size(eliminar,0)):\n indx = eliminar[i] - i\n candidatos = np.delete(candidatos,indx,0) #VER ESTO\n \n repeticiones = np.zeros((np.size(opciones,0),np.size(opciones,1)), dtype=int)\n\n for j in range(0,np.size(opciones,0)-1):\n for k in range(0,np.size(opciones,1)):\n a = np.argwhere(opciones[i,j] == candidatos)\n if len(a) is not 0:\n repeticiones[i,j] = sum(sum(a))\n\n estado = repeticiones\n return estado,candidatos\n ","sub_path":"calcular_estado.py","file_name":"calcular_estado.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"560607356","text":"# -*- coding: utf-8-*-\nimport random\nimport re\nimport jasperpath\nimport sys, pygame\nimport time\nimport pygame.camera\nfrom pygame.locals import *\nimport pygame.image\npygame.camera.init()\ncam = pygame.camera.Camera(\"/dev/video0\",(640,480))\n\n\nimage = 'nu.png'\nsize = width, height = 480, 320\nscreensize = 480, 320\ngray = (100, 100, 100)\nnvb = ( 60, 60, 100)\nwhite = (255, 255, 255)\nred = (255, 0, 0)\ngreen = ( 0, 255, 0)\nblue = ( 0, 0, 255)\nyellow = (255, 255, 0)\norang = (255, 128, 0)\npurple = (255, 0, 255)\ncyan = ( 0, 255, 255)\nblack = (0, 0, 0)\n\nx=0\ny=0\nnsize = 160,120\n\n#mark1\nnew_word = \"VIDEO\" \nmessage = \"camera on\"\n\nWORDS = (\"%s\" %new_word)\n\nPRIORITY = 4\n\ndef handle(self, text, mic, profile):\n \"\"\"\n Responds to user-input, typically speech text, by relaying the\n meaning of life.\n\n Arguments:\n text -- user-input, typically transcribed speech\n mic -- used to interact with the user (for both input and output)\n profile -- contains information related to the user (e.g., phone\n number)\n \"\"\"\n\n mic.say(\"%s\" %message)\n cam.start()\n pic = cam.get_image()\n pic = pygame.transform.smoothscale(pic, nsize)\n\n done = True\n while done == True :\n for e in pygame.event.get() :\n if e.type == pygame.QUIT :\n done = False\n if e.type == pygame.MOUSEBUTTONDOWN:\n done = False\n\n\n self.pygm.background.fill(black)\n picc = pic.get_rect()\n picc.center = self.pygm.background.get_rect().center\n self.pygm.background.blit(pic, picc)\n self.screen.blit(self.pygm.background, (x,y))\n \n #self.pygm.screen.blit(pic, (x, y))\n pygame.display.flip()\n pic = cam.get_image()\n pic = pygame.transform.smoothscale(pic, nsize)\n\n cam.stop()\n\n\n\n\n \n\n\ndef isValid(text):\n \"\"\"\n Returns True if the input is related to the meaning of life.\n\n Arguments:\n text -- user-input, typically transcribed speech\n \"\"\"\n return bool(re.search(r'\\b%s\\b' %new_word, text, re.IGNORECASE)) \n","sub_path":"client/modules/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"208871936","text":"import tensorflow as tf\nimport numpy as np\nimport os\n\n# Final Working Model with 70% accuracy\n\nnum_training = 300\nnum_validation = 50\nnum_test = 50\n\nlocal_config = {\n 'batch_size': 1,\n 'train_size': np.inf,\n 'epoch': 200,\n 'eps': 1e-5,\n 'learning_rate': 1e-3,\n 'beta1': 0.9,\n 'load_size': 22050 * 4,\n 'sample_rate': 22050,\n 'name_scope': 'SoundNet',\n 'phase': 'train',\n 'dataset_name': 'ESC50',\n 'subname': 'mp3',\n 'checkpoint_dir': 'checkpoint',\n 'dump_dir': 'output',\n 'model_dir': None,\n 'param_g_dir': '../models/sound5.npy',\n}\n\n\ndef conv2d(prev_layer, in_ch, out_ch, k_h=1, k_w=1, d_h=1, d_w=1, p_h=0, p_w=0, pad='VALID', name_scope='conv'):\n with tf.variable_scope(name_scope) as scope:\n # h x w x input_channel x output_channel\n w_conv = tf.get_variable('weights', [k_h, k_w, in_ch, out_ch],\n initializer=tf.truncated_normal_initializer(0.0, stddev=0.01))\n b_conv = tf.get_variable('biases', [out_ch],\n initializer=tf.constant_initializer(0.0))\n\n padded_input = tf.pad(prev_layer, [[0, 0], [p_h, p_h], [p_w, p_w], [0, 0]], \"CONSTANT\") if pad == 'VALID' \\\n else prev_layer\n\n output = tf.nn.conv2d(padded_input, w_conv,\n [1, d_h, d_w, 1], padding=pad, name='z') + b_conv\n\n return output\n\n\ndef batch_norm(prev_layer, out_ch, eps, name_scope='conv'):\n with tf.variable_scope(name_scope) as scope:\n # mu_conv, var_conv = tf.nn.moments(prev_layer, [0, 1, 2], keep_dims=False)\n mu_conv = tf.get_variable('mean', [out_ch],\n initializer=tf.constant_initializer(0))\n var_conv = tf.get_variable('var', [out_ch],\n initializer=tf.constant_initializer(1))\n gamma_conv = tf.get_variable('gamma', [out_ch],\n initializer=tf.constant_initializer(1))\n beta_conv = tf.get_variable('beta', [out_ch],\n initializer=tf.constant_initializer(0))\n output = tf.nn.batch_normalization(prev_layer, mu_conv,\n var_conv, beta_conv, gamma_conv, eps, name='batch_norm')\n\n return output\n\n\ndef relu(prev_layer, name_scope='conv'):\n with tf.variable_scope(name_scope) as scope:\n return tf.nn.relu(prev_layer, name='a')\n\n\ndef maxpool(prev_layer, k_h=1, k_w=1, d_h=1, d_w=1, name_scope='conv'):\n with tf.variable_scope(name_scope) as scope:\n return tf.nn.max_pool(prev_layer,\n [1, k_h, k_w, 1], [1, d_h, d_w, 1], padding='VALID', name='maxpool')\n\n\nclass SoundEncoder(object):\n def __init__(self, sess):\n self.sess = sess\n self.num_epoch = local_config['epoch']\n self.batch_size = local_config['batch_size']\n self.param_G = np.load(local_config['param_g_dir'], encoding='latin1').item()\n # Load checkpoint\n self._build_model()\n\n if self.load(local_config['checkpoint_dir']):\n print(\" [*] Load SUCCESS\")\n else:\n print(\" [!] Load failed...\")\n\n\n\n def FC(self, input, inp_neurons, out_neurons):\n # W = tf.get_variable('w',[inp_neurons,out_neurons], tf.float32, tf.random_normal_initializer(0.0, 0.02))\n W = tf.get_variable('w', [inp_neurons, out_neurons], tf.float32, tf.contrib.layers.xavier_initializer())\n b = tf.get_variable('b', [out_neurons], initializer=tf.constant_initializer(0.0))\n\n weight_decay = tf.multiply(tf.nn.l2_loss(W), 0.004, name='weight_loss')\n tf.add_to_collection('losses', weight_decay)\n\n return tf.matmul(input, W) + b\n\n def Normalization(self, input):\n return tf.nn.local_response_normalization(input,\n alpha=0.001 / 9.0,\n beta=0.75,\n depth_radius=4,\n bias=1.0)\n\n @property\n def get_model_dir(self):\n if local_config['model_dir'] is None:\n return \"{}_{}\".format(\n local_config['dataset_name'], local_config['batch_size'])\n else:\n return local_config['model_dir']\n\n def load(self, ckpt_dir='checkpoint'):\n return self.load_from_ckpt(ckpt_dir) if self.param_G is None \\\n else self.load_from_npy()\n\n def save(self, checkpoint_dir, step):\n \"\"\" Checkpoint saver \"\"\"\n model_name = \"SoundNet.model\"\n checkpoint_dir = os.path.join(checkpoint_dir, self.get_model_dir)\n\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n\n self.saver.save(self.sess,\n os.path.join(checkpoint_dir, model_name),\n global_step=step)\n\n def load_from_ckpt(self, checkpoint_dir='checkpoint'):\n \"\"\" Checkpoint loader \"\"\"\n print(\" [*] Reading checkpoints...\")\n\n checkpoint_dir = os.path.join(checkpoint_dir, self.get_model_dir)\n\n ckpt = tf.train.get_checkpoint_state(checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n ckpt_name = os.path.basename(ckpt.model_checkpoint_path)\n self.saver.restore(self.sess, os.path.join(checkpoint_dir, ckpt_name))\n print(\" [*] Success to read {}\".format(ckpt_name))\n self.counter = int(ckpt_name.rsplit('-', 1)[-1])\n print(\" [*] Start counter from {}\".format(self.counter))\n return True\n else:\n print(\" [*] Failed to find a checkpoint under {}\".format(checkpoint_dir))\n return False\n\n def load_from_npy(self):\n if self.param_G is None: return False\n data_dict = self.param_G\n for key in data_dict:\n with tf.variable_scope(local_config['name_scope'] + '/' + key, reuse=True):\n for subkey in data_dict[key]:\n try:\n var = tf.get_variable(subkey)\n self.sess.run(var.assign(data_dict[key][subkey]))\n print('Assign pretrain model {} to {}'.format(subkey, key))\n except:\n print('Ignore {}'.format(key))\n\n self.param_G.clear()\n return True\n\n def _model(self, name_scope = 'Soundnet'):\n print('-' * 5 + ' Sample model ' + '-' * 5)\n\n print('intput layer: ' + str(self.X.get_shape()))\n with tf.variable_scope(name_scope) as scope:\n self.layers = {}\n\n # Stream one: conv1 ~ conv7\n self.layers[1] = conv2d(self.X, 1, 32, k_h=64, d_h=2, p_h=32, name_scope='conv1')\n self.layers[2] = batch_norm(self.layers[1], 32, local_config['eps'], name_scope='conv1')\n self.layers[3] = relu(self.layers[2], name_scope='conv1')\n self.layers[4] = maxpool(self.layers[3], k_h=8, d_h=8, name_scope='conv1')\n print('Conv1 {}'.format(self.layers[4].shape))\n\n self.layers[5] = conv2d(self.layers[4], 32, 64, k_h=32, d_h=2, p_h=16, name_scope='conv2')\n self.layers[6] = batch_norm(self.layers[5], 64, local_config['eps'], name_scope='conv2')\n self.layers[7] = relu(self.layers[6], name_scope='conv2')\n self.layers[8] = maxpool(self.layers[7], k_h=8, d_h=8, name_scope='conv2')\n print('Conv2 {}'.format(self.layers[8].shape))\n\n self.layers[9] = conv2d(self.layers[8], 64, 128, k_h=16, d_h=2, p_h=8, name_scope='conv3')\n self.layers[10] = batch_norm(self.layers[9], 128, local_config['eps'], name_scope='conv3')\n self.layers[11] = relu(self.layers[10], name_scope='conv3')\n self.layers[12] = maxpool(self.layers[11], k_h=8, d_h=8, name_scope='conv3')\n print('Conv3 {}'.format(self.layers[12].shape))\n\n self.layers[13] = conv2d(self.layers[12], 128, 256, k_h=8, d_h=2, p_h=4, name_scope='conv4')\n self.layers[14] = batch_norm(self.layers[13], 256, local_config['eps'], name_scope='conv4')\n self.layers[15] = relu(self.layers[14], name_scope='conv4')\n print('Conv3 {}'.format(self.layers[14].shape))\n # Split one: conv8, conv8_2\n # NOTE: here we use a padding of 2 to skip an unknown error\n # https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/common_shape_fns.cc#L45\n # self.flat = tf.contrib.layers.flatten(self.layers[15])\n # print('Flat final {}'.format(self.flat.shape))\n self.layers[16] = conv2d(self.layers[15], 256, 1000, k_h=16, d_h=12, p_h=4, name_scope='conv5')\n self.layers[17] = conv2d(self.layers[15], 256, 401, k_h=16, d_h=12, p_h=4, name_scope='conv5_2')\n\n self.layers[18] = tf.contrib.layers.flatten(self.layers[16])\n print('Conv4 {}'.format(self.layers[18]))\n self.layers[19] = tf.layers.dense(self.layers[18],1024, activation=tf.nn.relu, name=\"fc1\")\n self.layers[20] = tf.layers.dense(self.layers[19], 128, activation=tf.nn.relu, name=\"fc2\")\n self.layers[21] = tf.layers.dense(self.layers[20], 10, None,name=\"fc3\")\n\n # self.layers[19] = self.FC(self.layers[18], self.layers[18].get_shape()[1], 1024)\n # self.layers[20] = tf.nn.relu(self.layers[19])\n # if self.is_train:\n # self.drop_out5 = tf.nn.dropout(self.layers[20], self.keep_prob_fc5)\n # else:\n # self.drop_out5 = self.layers[20]\n #\n # self.layers[21] = self.FC(self.drop_out5, self.drop_out5.get_shape()[1], 128)\n # self.layers[22] = tf.nn.relu(self.layers[21])\n # if self.is_train:\n # self.drop_out6 = tf.nn.dropout(self.layers[22], self.keep_prob_fc6)\n # else:\n # self.drop_out6 = self.layers[22]\n #\n # with tf.variable_scope('fc7'):\n #\n # self.fc7 = self.FC(self.drop_out6, self.drop_out6.get_shape()[1], 10)\n # print('fc7 layer: ' + str(self.fc7.get_shape()))\n #\n # # Return the last layer\n # return self.fc7\n return self.layers[21]\n\n def _input_ops(self):\n # Placeholders\n self.X = tf.placeholder(tf.float32, [None,220500, 1, 1])\n self.Y = tf.placeholder(tf.int64, [None])\n\n self.is_train = True\n self.keep_prob_fc5 = tf.placeholder(tf.float32)\n self.keep_prob_fc6 = tf.placeholder(tf.float32)\n\n def _build_optimizer(self):\n # Adam optimizer 'self.train_op' that minimizes 'self.loss_op'\n # Optimizer and summary\n t_vars=tf.global_variables()\n all_vars=[]\n for name in ['fc1','fc2','fc3']:\n d_vars = [var for var in t_vars if name in var.name]\n all_vars.append(d_vars)\n self.global_step = tf.Variable(0, trainable=False)\n self.initial_lr = local_config['learning_rate']\n # self.exp_decay = tf.train.exponential_decay(self.initial_lr, self.global_step, 500, 0.96)\n self.train_op = tf.train.AdamOptimizer(learning_rate=self.initial_lr, beta1=local_config['beta1']).minimize(\n self.loss_op,\n global_step=self.global_step,\n var_list=all_vars)\n\n def _loss(self, labels, logits):\n\n cross_entropy_mean = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits))\n tf.add_to_collection('losses', cross_entropy_mean)\n # self.loss_op = tf.add_n(tf.get_collection('losses'), name='total_loss')\n self.loss_op = cross_entropy_mean\n\n def _build_model(self):\n # Define input variables\n self._input_ops()\n\n # Convert Y to one-hot vector\n labels = tf.one_hot(self.Y, 10)\n\n # Build a model and get logits\n logits = self._model(name_scope=local_config['name_scope'])\n\n # Compute loss\n self._loss(labels, logits)\n\n # Build optimizer\n self._build_optimizer()\n\n # Compute accuracy\n predict = tf.argmax(logits, 1)\n correct = tf.equal(predict, self.Y)\n self.accuracy_op = tf.reduce_mean(tf.cast(correct, tf.float32))\n\n def train(self, sess, X_train, Y_train, X_val, Y_val):\n sess.run(tf.global_variables_initializer())\n\n step = 0\n losses = []\n accuracies = []\n print('-' * 5 + ' Start training ' + '-' * 5)\n\n self.is_train = True\n self.log_step = 5\n for epoch in range(self.num_epoch):\n print('train for epoch %d' % epoch)\n for i in range(num_training // self.batch_size):\n X_ = X_train[i * self.batch_size:(i + 1) * self.batch_size][:]\n Y_ = Y_train[i * self.batch_size:(i + 1) * self.batch_size]\n\n feed_dict = {self.X: X_, self.Y: Y_, self.keep_prob_fc5: 0.7, self.keep_prob_fc6: 0.8}\n fetches = [self.train_op, self.loss_op, self.accuracy_op]\n\n _, loss, accuracy = sess.run(fetches, feed_dict=feed_dict)\n losses.append(loss)\n accuracies.append(accuracy)\n if step % self.log_step == 0:\n print('iteration (%d): loss = %.3f, accuracy = %.3f' %\n (step, loss, accuracy))\n step += 1\n\n # Print validation results\n self.is_train = False\n print('validation for epoch %d' % epoch)\n val_accuracy = self.evaluate(sess, X_val, Y_val)\n print('- epoch %d: validation accuracy = %.3f' % (epoch, val_accuracy))\n self.is_train = True\n\n def evaluate(self, sess, X_eval, Y_eval):\n eval_accuracy = 0.0\n eval_iter = 0\n for i in range(X_eval.shape[0] // self.batch_size):\n X_ = X_eval[i * self.batch_size:(i + 1) * self.batch_size][:]\n Y_ = Y_eval[i * self.batch_size:(i + 1) * self.batch_size]\n\n feed_dict = {self.X: X_, self.Y: Y_, self.keep_prob_fc5: 0.7, self.keep_prob_fc6: 0.8}\n accuracy = sess.run(self.accuracy_op, feed_dict=feed_dict)\n eval_accuracy += accuracy\n eval_iter += 1\n return eval_accuracy / eval_iter\n\n\ndef load_data():\n # load the data\n\n sound_samples = np.load('../data/shruthi_x.npy', encoding='latin1')\n print(sound_samples.shape)\n sound_labels = np.load('../data/shruthi_y.npy', encoding='latin1').reshape(-1)\n print(sound_labels.shape)\n X_train = sound_samples[:300]\n X_val = sound_samples[300:350]\n X_test = sound_samples[350:400]\n print(X_train.shape)\n\n Y_train = sound_labels[:300]\n Y_val = sound_labels[300:350]\n Y_test = sound_labels[350:400]\n return {\n 'X_train': X_train,\n 'Y_train': Y_train,\n 'X_val': X_val,\n 'Y_val': Y_val,\n 'X_test': X_test,\n 'Y_test': Y_test\n }\n\n\n\ndef train_encoder():\n # train the enoder with the necessary params\n\n tf.reset_default_graph()\n sess = tf.Session()\n data = load_data()\n model = SoundEncoder(sess)\n\n model.train(sess, data['X_train'], data['Y_train'], data['X_val'], data['Y_val'])\n model.is_train = False\n accuracy = model.evaluate(sess, data['X_test'], data['Y_test'])\n print('***** test accuracy: %.3f' % accuracy)\n\n # Save your model\n saver = tf.train.Saver()\n model_path = saver.save(sess, \"./S2I.ckpt\")\n print(\"Model saved in %s\" % model_path)\n\n sess.close()\n\n\nif __name__ == '__main__':\n train_encoder()","sub_path":"Encoder/SoundEncoder.py","file_name":"SoundEncoder.py","file_ext":"py","file_size_in_byte":15555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"619048204","text":"import sys\nimport numpy as np\n\ndef readFile(fileName, linesToSkipInitial,linesToSkipLater, linesToRead,timeStepsToSkip):\n # function takes the file name/location if not in same workspace\n # the number of lines to skip of useless garbage\n # the number of lines we want to get data from\n # a list of col indices that you want to read\n # so if you want to read the 3rd and 4th column you\n # would pass a list [2, 3]\n # \n \n # open file and read lines\n fileObj = open(fileName, 'r')\n allLinesList = fileObj.readlines()\n\n # create list for output data to be stored in\n outputRdfList = [0]*linesToRead\n rList = [0]*linesToRead\n\n for removeIndx in range(linesToSkipInitial+timeStepsToSkip*(linesToSkipLater+linesToRead)):\n del allLinesList[0]\n \n currTimeStep = 0\n for indx in range(len(allLinesList)):\n outIndx = indx%(linesToRead + linesToSkipLater) - 1\n if(outIndx != -1):\n currLineList = allLinesList[indx].split()\n rList[outIndx] = float(currLineList[1])\n tempGr = (float(currLineList[2]) + outputRdfList[outIndx]*currTimeStep)/(currTimeStep + 1)\n outputRdfList[outIndx] = tempGr\n \n else:\n currTimeStep += 1\n\n \n return rList, outputRdfList\n\n\ndef readMyCOMFile(fileName, linesToRead):\n\n\n linesToSkipInitial = 3\n linesToSkipLater = 1\n # open file and read lines\n fileObj = open(fileName, 'r')\n allLinesList = fileObj.readlines()\n \n # create list for output data to be stored in\n \n outputList = []\n tsList = []\n\n for removeIndx in range(linesToSkipInitial):\n del allLinesList[0]\n\n\n for indx in range(len(allLinesList)):\n outIndx = indx%(linesToRead + linesToSkipLater) \n if(outIndx != 0):\n currLineList = allLinesList[indx].split()\n tsList.append([float(currLineList[1]),float(currLineList[2]),float(currLineList[3])])\n elif(indx>0):\n copyList = tsList.copy()\n outputList.append(copyList)\n tsList = []\n copyList = tsList.copy()\n outputList.append(copyList) \n \n return outputList\n\ndef readMyRdfFileOneAtaTime(fileName, linesToSkipInitial,linesToSkipLater, linesToRead):\n # function takes the file name/location if not in same workspace\n # the number of lines to skip of useless garbage\n # the number of lines we want to get data from\n # a list of col indices that you want to read\n # so if you want to read the 3rd and 4th column you\n # would pass a list [2, 3]\n \n # open file and read lines\n fileObj = open(fileName, 'r')\n allLinesList = fileObj.readlines()\n fileObj.close()\n\n # create list for output data to be stored in\n outputRdfList = []\n tsList = []\n rList = []\n\n for removeIndx in range(linesToSkipInitial):\n del allLinesList[0]\n \n currTimeStep = 0\n for lineNum in range(len(allLinesList)):\n outIndx = lineNum%(linesToRead + linesToSkipLater) - 1\n if(outIndx != -1 and currTimeStep == 0):\n currLineList = allLinesList[lineNum].split()\n rList.append(float(currLineList[1]))\n tempGr = float(currLineList[2])\n tsList.append(tempGr)\n elif(outIndx != -1):\n currLineList = allLinesList[lineNum].split() \n tempGr = float(currLineList[2])\n tsList.append(tempGr)\n elif(lineNum>0):\n addGr = tsList.copy()\n outputRdfList.append(addGr)\n tsList = []\n currTimeStep += 1\n\n \n return rList, outputRdfList\n\ndef readMyPeOUTFile(fileName):\n \n data = np.loadtxt(fileName)\n \n TS = data[:,0]\n PE = data[:,1]\n \n return TS, PE\n\ndef readMyDumpFileForXYZ(fileName, numAtoms):\n # function takes the dump file name/location\n # and iterates through to get the coordinates of each atom and puts it in\n # a list with the following format for n total atoms and ts timesteps\n # [[[x,y,z],[x,y,z],...n],[[x,y,z],[x,y,z],...n],...ts]\n # this function assumes the dump command in lammps was x y z ix iy iz\n\n linesToAlwaysSkip = 9\n # open file and read lines\n fileObj = open(fileName, 'r')\n sys.stdout.write('READING DUMPFILE\\n')\n sys.stdout.flush()\n allLinesList = fileObj.readlines()\n sys.stdout.write('SORTING DUMPFILE\\n')\n sys.stdout.flush()\n fileObj.close()\n \n # create list for output data to be stored in\n outputCoordsList = [] #[[[x,y,z],[x,y,z]...n],[[x,y,z],[x,y,z]...n],...ts]\n timeStepCoords = [] # [[x,y,z]*nAtoms]\n for indx in range(len(allLinesList)):\n sys.stdout.write('CURRENT LINE: ' + str(indx) + '\\n')\n sys.stdout.flush()\n outIndx = indx%(numAtoms+linesToAlwaysSkip)\n if(outIndx not in range(linesToAlwaysSkip)):\n currLineList = allLinesList[indx].split()\n currCoords = [float(currLineList[-6]),float(currLineList[-5]),float(currLineList[-4])]\n timeStepCoords.append(currCoords)\n if(outIndx == numAtoms+linesToAlwaysSkip-1):\n tmpList = timeStepCoords.copy()\n outputCoordsList.append(tmpList)\n timeStepCoords = []\n sys.stdout.write('FINISHED READING DUMPFILE\\n')\n sys.stdout.flush()\n return outputCoordsList\n\ndef formatDumpFileForXYZ(inFile,outFile, numAtoms):\n # function takes the dump file name/location\n # and iterates through to get the coordinates of each atom and puts it in\n # a list with the following format for n total atoms and ts timesteps\n # [[[x,y,z],[x,y,z],...n],[[x,y,z],[x,y,z],...n],...ts]\n # this function assumes the dump command in lammps was x y z ix iy iz\n\n linesToAlwaysSkip = 9\n # open file and read lines\n inFileObj = open(inFile, 'r')\n sys.stdout.write('READING DUMPFILE\\n')\n sys.stdout.flush()\n allLinesList = inFileObj.readlines()\n sys.stdout.write('SORTING DUMPFILE\\n')\n sys.stdout.flush()\n inFileObj.close()\n sys.stdout.write('WRITING TO OUTPUT FILE\\n')\n sys.stdout.flush()\n outFileObj = open(outFile,'w')\n \n # create list for output data to be stored in\n outputCoordsList = [] #[[[x,y,z],[x,y,z]...n],[[x,y,z],[x,y,z]...n],...ts]\n timeStepCoords = [] # [[x,y,z]*nAtoms]\n for indx in range(len(allLinesList)):\n sys.stdout.write('CURRENT LINE: ' + str(indx) + '\\n')\n sys.stdout.flush()\n outIndx = indx%(numAtoms+linesToAlwaysSkip)\n if(outIndx not in range(linesToAlwaysSkip)):\n currLineList = allLinesList[indx].split()\n outFileObj.write(currLineList[0] + '\\t' + \"{:.6f}\".format(float(currLineList[-6])) + '\\t' + \"{:.6f}\".format(float(currLineList[-5])) + '\\t' + \"{:.6f}\".format(float(currLineList[-4])) + '\\n')\n elif(outIndx == 1):\n outFileObj.write('# ' + allLinesList[indx])\n \n sys.stdout.write('FINISHED READING DUMPFILE\\n')\n sys.stdout.flush()\n outFileObj.close()\n\ndef readMyDumpFileForAvgVal(fileName,linesToAlwaysSkip, numVals, indxWanted):\n # function takes the dump file name/location\n # and iterates through to get a value held at indxWanted of each line\n # for numVals in each time step. linesToAlwaySkip = 9 \n \n # open file and read lines\n fileObj = open(fileName, 'r')\n allLinesList = fileObj.readlines()\n fileObj.close()\n # create list for output data to be stored in\n outputValsList = [] #[[val,val,val...n],[val,val,val...n]...ts]\n timeStepVals = [] #[val,val,val...n]\n for indx in range(len(allLinesList)):\n outIndx = indx%(numVals+linesToAlwaysSkip)\n if(outIndx not in range(linesToAlwaysSkip)):\n currLineList = allLinesList[indx].split()\n currVal = currLineList[indxWanted]\n timeStepVals.append(float(currVal))\n if(outIndx == numVals+linesToAlwaysSkip-1):\n tmplList = timeStepVals.copy()\n outputValsList.append(tmpList) \n timeStepVals = []\n \n return outputValsList\n\ndef readMyVMDradGyrData(fileName):\n fileObj = open(fileName,'r')\n allLinesList = fileObj.readlines()\n radGyr = [float(line) for line in allLinesList]\n fileObj.close()\n return radGyr\n\ndef readFileForMultipleLines(fileName,cols):\n # takes a string filename for the file of interest\n # and a list of columns that you want (will return one long list)\n # should be indexed how you want if you want first column, pass 0\n # loads the data from these columns and returns them in a list of lists\n # all # lines will be ignored \n\n data = np.loadtxt(fileName)\n outputList = []\n for colNum in cols:\n currData = data[:,colNum]\n copyList = currData.copy()\n outputList.append(copyList)\n\n return outputList\n\ndef readFormattedDump(fileName,atomsPerMol,mols):\n # takes a string filename for the file of interest\n # and a list of columns that you want (will return one long list)\n # should be indexed how you want if you want first column, pass 0\n # loads the data from these columns and returns them in a list of lists\n # all # lines will be ignored \n \n data = np.loadtxt(fileName)\n timestepList = []\n outputList = []\n totalAtoms = atomsPerMol*mols\n first = 0\n last = atomsPerMol\n currTS = 1\n while(last<= int(len(data[:,0]))):\n tmpList = data[first:last,1:4]\n copyList = tmpList.copy()\n timestepList.append(copyList)\n if(last%totalAtoms == 0):\n sys.stdout.write('CURRENT TS: ' + str(currTS) + '\\n')\n sys.stdout.flush()\n currTS += 1\n polsAtTS = timestepList.copy()\n outputList.append(polsAtTS)\n timestepList = []\n first = last\n last += atomsPerMol\n\n return outputList\n\ndef readIndividualDump(fileName,atomsPerMol,totMols):\n# function takes the dump file name/location\n # and iterates through to get the coordinates of each atom and puts it in\n # a list with the following format for n total atoms and ts timesteps\n # [[[x,y,z],[x,y,z],...n],[[x,y,z],[x,y,z],...n],...ts]\n # this function assumes the dump command in lammps was x y z ix iy iz\n\n linesToSkip = 9\n # open file and read lines\n fileObj = open(fileName, 'r')\n allLinesList = fileObj.readlines()\n fileObj.close()\n \n del allLinesList[0:linesToSkip]\n \n # create list for output data to be stored in\n outputCoordsList = [] #[[[x,y,z],[x,y,z]...n],[[x,y,z],[x,y,z]...n]]\n # list for atoms in a polymer\n polymerList = []\n currAtom = 0\n currMol = 1\n while(currMol<=totMols):\n while(currAtom= 2:\n queryset = queryset.limit(100)\n\n return queryset\n\n def map_order_field(self, name):\n descending = False\n if name.startswith('-'):\n name = name[1:]\n descending = True\n field = column(name)\n if descending:\n field = desc(field)\n return field\n\n def sort_queryset(self, queryset, data):\n if 'order_by' in data:\n order_by = list(map(lambda x: self.map_order_field(x), data['order_by']))\n queryset = queryset.order_by(*order_by)\n\n return queryset\n\n def execute(self, data):\n request = self.context.get('request')\n session = create_session(request)\n\n query = data['query']\n\n if data['v'] >= 2:\n params = data.get('params_obj', {})\n else:\n params = data.get('params', [])\n\n if 'timezone' in data:\n try:\n session.execute('SET TIME ZONE :tz', {'tz': data['timezone']})\n except SQLAlchemyError:\n session.rollback()\n pass\n\n subquery = text(query).columns().subquery('__jet_q2')\n count_rows = None\n\n if data['count']:\n try:\n count_queryset = select([func.count()]).select_from(subquery)\n count_queryset = self.filter_queryset(count_queryset, data)\n\n count_result = session.execute(count_queryset, params)\n count_rows = count_result.all()[0][0]\n except Exception:\n pass\n\n try:\n queryset = select(['*']).select_from(subquery)\n queryset = self.filter_queryset(queryset, data)\n queryset = self.paginate_queryset(queryset, data)\n queryset = self.sort_queryset(queryset, data)\n\n result = session.execute(queryset, params)\n\n def map_column(x):\n if x == '?column?':\n return\n return x\n\n def map_row_column(x):\n if isinstance(x, bytes):\n try:\n return x.decode('utf-8')\n except UnicodeDecodeError:\n return x.hex()\n else:\n return x\n\n def map_row(row):\n return list(map(lambda x: map_row_column(row[x]), row.keys()))\n\n response = {'data': list(map(map_row, result)), 'columns': list(map(map_column, result.keys()))}\n\n if count_rows is not None:\n response['count'] = count_rows\n\n return response\n except SQLAlchemyError as e:\n session.rollback()\n raise SqlError(e)\n except TypeError as e:\n raise SqlError(e)\n except Exception as e:\n raise SqlError(e)\n finally:\n session.close()\n\n\nclass SqlsSerializer(Serializer):\n queries = SqlSerializer(many=True)\n\n def execute(self, data):\n serializer = SqlSerializer(context=self.context)\n\n def map_query(query):\n try:\n return serializer.execute(query)\n except SqlError as e:\n return {'error': str(e.detail)}\n\n return list(map(map_query, data['queries']))\n","sub_path":"packages/jet_bridge_base/jet_bridge_base/serializers/sql.py","file_name":"sql.py","file_ext":"py","file_size_in_byte":7653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"293990275","text":"n, m = map(int,input().split())\r\nfirst=0\r\nlength=0\r\nb=0\r\nfor i in range(m,101):\r\n if (n*2)/i-i+1<0:\r\n break\r\n if ((n*2)/i-i+1)%2==0:\r\n first = int(((n*2)/i-i+1)//2)\r\n length = i\r\n b=1\r\n break\r\nif b==0:\r\n print(-1)\r\nelse:\r\n for i in range(length):\r\n print(first+i,end=\" \")","sub_path":"수열의 합.py","file_name":"수열의 합.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"489295883","text":"import time\nimport copy\nclass Halma():\n\n\tdef __init__(self,time_limit,clr,board):\n\t\tself.time_limit=time.time()+3\n\t\tself.clr=clr\n\t\tself.board=board\n\t\tself.white_positions=[]\n\t\tself.black_positions=[]\n\t\t#store all positions of white and black pieces\n\t\tfor l in range(0,16):\n\t\t\tfor m in range(0,16):\n\t\t\t\tif self.board[l][m]=='W':\n\t\t\t\t\tself.white_positions.append([l,m])\n\t\t\t\telif self.board[l][m]=='B':\n\t\t\t \t\tself.black_positions.append([l,m])\n\n\n\tdef isWin(self):\n\t\t#check if any player won\n\t\tif self.clr=='WHITE':\n\t\t\tfor i in range(len(blackcamp)):\n\t\t\t\tif board[blackcamp[i][0]][blackcamp[i][1]]=='W':\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\treturn False\n\t\t\treturn True\n\t\tif self.clr=='BLACK':\n\t\t\tfor i in range(len(whitecamp)):\n\t\t\t\tif board[whitecamp[i][0]][whitecamp[i][1]]=='B':\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\treturn False\n\t\t\treturn True\n\n\n\tdef getLegalMoves(self,clr,i,j):\n\t\t#get all possible single moves and jumps from a piece\n\t\tmvs=[]\n\t\tif clr=='WHITE':\n\t\t\tfor l in range(1,-2,-1):\n\t\t\t\tfor m in range(1,-2,-1):\n\t\t\t\t\tif i+l<0 or j+m<0 or i+l>15 or j+m>15:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telif i+l==i and j+m==j:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telif board[i+l][j+m]=='.':\n\t\t\t\t\t\tmvs.append([i,j,i+l,j+m,'stmove'])\n\t\t\tvisited=[]\n\t\t\tself.getJumps(clr,mvs,i,j,1,len(mvs)-1,visited)\n\t\telif clr=='BLACK':\n\t\t\tfor l in range(-1,2):\n\t\t\t\tfor m in range(-1,2):\n\t\t\t\t\tif i+l<0 or j+m<0 or i+l>15 or j+m>15:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telif i+l==i and j+m==j:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telif board[i+l][j+m]=='.':\n\t\t\t\t\t\tmvs.append([i,j,i+l,j+m,'stmove'])\n\t\t\tvisited=[]\n\t\t\tmvs,visited=self.getJumps(clr,mvs,i,j,1,len(mvs)-1,visited)\n\t\treturn mvs\n\n\n\tdef getJumps(self,clr,mvs,i,j,depth,parent,visited):\n\t\tpt=len(mvs)\n\t\tvisited.append([i,j])\n\t\tfor l in range(-1,2):\n\t\t\tfor m in range(-1,2):\n\t\t\t\tmx,my=i+l,j+m\n\t\t\t\ttx,ty=mx+l,my+m\n\t\t\t\tif tx<0 or ty<0 or tx>15 or ty>15:\n\t\t\t\t\tcontinue\n\t\t\t\telif tx==i and ty==j:\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tif self.board[mx][my]!='.' and self.board[tx][ty]=='.':\n\t\t\t\t\t\tif depth==1:\n\t\t\t\t\t\t\tt=[i,j,tx,ty,'jump']\n\t\t\t\t\t\t\tif t not in mvs and [tx,ty] not in visited:\n\t\t\t\t\t\t\t\tmvs.append(t)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif len(mvs[parent])!=1:\n\t\t\t\t\t\t\t\tif len(mvs[parent])==5:\n\t\t\t\t\t\t\t\t\tif mvs[parent][4]=='jump':\n\t\t\t\t\t\t\t\t\t\tt=[mvs[parent],[i,j,tx,ty,'jump']]\n\t\t\t\t\t\t\t\t\t\tif t not in mvs and [tx,ty] not in visited:\n\t\t\t\t\t\t\t\t\t\t\tmvs.append(t)\n\t\t\t\t\t\t\tif len(mvs[parent])!=1:\n\t\t\t\t\t\t\t\tif (len(mvs[parent])==5 and mvs[parent][4]!='jump') or len(mvs[parent])!=5:\n\t\t\t\t\t\t\t\t\tt=[]\n\t\t\t\t\t\t\t\t\tfor k in mvs[parent]:\n\t\t\t\t\t\t\t\t\t\tt.append(k)\n\t\t\t\t\t\t\t\t\tt.append([i,j,tx,ty,'jump'])\n\t\t\t\t\t\t\t\t\tif t not in mvs and [tx,ty] not in visited:\n\t\t\t\t\t\t\t\t\t\tmvs.append(t)\n\n\t\t\t\t\t\tif [tx,ty] not in visited:\n\t\t\t\t\t\t\tif len(mvs[pt])!=5 or (len(mvs[pt])==5 and mvs[pt][4]!='stmove' and mvs[pt][4]!='jump'):\n\t\t\t\t\t\t\t\tif mvs[pt][len(mvs[pt])-1][2]==tx and mvs[pt][len(mvs[pt])-1][3]==ty:\n\t\t\t\t\t\t\t\t\tmvs,visited=self.getJumps(clr,mvs,tx,ty,depth+1,pt,visited)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tmvs,visited=self.getJumps(clr,mvs,tx,ty,depth+1,len(mvs)-1,visited)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif mvs[pt][2]==tx and mvs[pt][3]==ty:\n\t\t\t\t\t\t\t\t\tmvs,visited=self.getJumps(clr,mvs,tx,ty,depth+1,pt,visited)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tmvs,visited=self.getJumps(clr,mvs,tx,ty,depth+1,len(mvs)-1,visited)\n\t\treturn mvs,visited\n\n\n\tdef getAllMoves(self,clr):\n\t\t#get all possible moves for a color\n\t\tpriority=[]\n\t\tmvs=[]\n\t\t#Move the pieces that are still in the camp first\n\t\tif clr=='BLACK':\n\t\t\tfor i in range(len(blackcamp)):\n\t\t\t\tif self.board[blackcamp[i][0]][blackcamp[i][1]]=='B':\n\t\t\t\t\tmv=self.getLegalMoves(clr,blackcamp[i][0],blackcamp[i][1])\n\t\t\t\t\tfor m in mv:\n\t\t\t\t\t\t#print(m)\n\t\t\t\t\t\tif len(m)!=5 or (len(m)==5 and m[4]!='stmove' and m[4]!='jump'):\n\t\t\t\t\t\t\tfromx=m[0][0]\n\t\t\t\t\t\t\tfromy=m[0][1]\n\t\t\t\t\t\t\ttox=m[len(m)-1][2]\n\t\t\t\t\t\t\ttoy=m[len(m)-1][3]\n\t\t\t\t\t\t\tif (tox>fromx and toy>fromy) or (tox>fromx and toy==fromy) or (tox==fromx and toy>fromy):\n\t\t\t\t\t\t\t\tif [fromx,fromy] in blackcamp and [tox,toy] not in blackcamp:\n\t\t\t\t\t\t\t\t\tpriority.append(m)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tmvs.append(m)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tfromx=m[0]\n\t\t\t\t\t\t\tfromy=m[1]\n\t\t\t\t\t\t\ttox=m[2]\n\t\t\t\t\t\t\ttoy=m[3]\n\t\t\t\t\t\t\tif (tox>fromx and toy>fromy) or (tox>fromx and toy==fromy) or (tox==fromx and toy>fromy):\n\t\t\t\t\t\t\t\tif [fromx,fromy] in blackcamp and [tox,toy] not in blackcamp:\n\t\t\t\t\t\t\t\t\tpriority.append(m)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tmvs.append(m)\n\t\telse:\n\t\t\tfor i in range(len(whitecamp)):\n\t\t\t\tif self.board[whitecamp[i][0]][whitecamp[i][1]]=='W':\n\t\t\t\t\tmv=self.getLegalMoves(clr,whitecamp[i][0],whitecamp[i][1])\n\t\t\t\t\tfor m in mv:\n\t\t\t\t\t\tif len(m)!=5 or (len(m)==5 and m[4]!='stmove' and m[4]!='jump'):\n\t\t\t\t\t\t\tfromx=m[0][0]\n\t\t\t\t\t\t\tfromy=m[0][1]\n\t\t\t\t\t\t\ttox=m[len(m)-1][2]\n\t\t\t\t\t\t\ttoy=m[len(m)-1][3]\n\t\t\t\t\t\t\tif (tox=self.time_limit:\n\t\t\t\treturn best_move\n\t\t\tflag,val,move=self.minimax(depth,self.clr,self.time_limit,float('-inf'),float('inf'),True)\n\t\t\tif flag!=1:\n\t\t\t\tbest_val=val\n\t\t\t\tbest_move=move\n\t\t\telse:\n\t\t\t\treturn best_move\n\t\t\tif best_val==50:\n\t\t\t\treturn best_move\n\t\t\tif depth==1 and type=='s':\n\t\t\t\treturn best_move\n\t\t\tif depth==3:\n\t\t\t\treturn best_move\n\t\t\tdepth+=1\n\t\treturn best_move\n\n\n\tdef minimax(self, depth, player,max_time,alpha,beta,maxplayer=True):\n\t\t#minimax using alpha-beta pruning\n\t\tbest_move=None\n\t\tif depth==0 :\n\t\t\treturn 0,self.evalFunction(player),best_move\n\t\t#if time exceeds maximum allocated time, return if move is not None, else increase the time allocated.\n\t\tif time.time()>max_time:\n\t\t\tif best_move is not None:\n\t\t\t\treturn 1,self.evalFunction(player),best_move\n\t\t\telse:\n\t\t\t\tself.time_limit=self.time_limit+1\n\t\tif maxplayer:\n\t\t\tbest_score=float('-inf')\n\t\t\tmoves=self.getAllMoves(player)\n\t\telse:\n\t\t\tbest_score=float('inf')\n\t\t\tif player=='BLACK':\n\t\t\t\tp='WHITE'\n\t\t\telse:\n\t\t\t\tp='BLACK'\n\t\t\tmoves=self.getAllMoves(p)\n\t\tfor m in moves:\n\t\t\tprint(m)\n\t\t\tif time.time()>max_time:\n\t\t\t\tif best_move is not None:\n\t\t\t\t\treturn 1,self.evalFunction(player),best_move\n\t\t\t\telse:\n\t\t\t\t\tself.time_limit=self.time_limit+1\n\t\t\tif len(m)!=5 or (len(m)==5 and m[4]!='stmove' and m[4]!='jump'):\n\t\t\t\tfinal=len(m)-1\n\t\t\t\tif self.board[m[0][0]][m[0][1]]=='B':\n\t\t\t\t\tself.board[m[final][2]][m[final][3]]='B'\n\t\t\t\t\tself.black_positions.remove([m[0][0],m[0][1]])\n\t\t\t\t\tself.black_positions.append([m[final][2],m[final][3]])\n\t\t\t\telse:\n\t\t\t\t\tself.board[m[final][2]][m[final][3]]='W'\n\t\t\t\t\tself.white_positions.remove([m[0][0],m[0][1]])\n\t\t\t\t\tself.white_positions.append([m[final][2],m[final][3]])\n\t\t\t\tself.board[m[0][0]][m[0][1]]='.'\n\t\t\telse:\n\t\t\t\tif self.board[m[0]][m[1]]=='B':\n\t\t\t\t\tself.board[m[2]][m[3]]='B'\n\t\t\t\t\tself.black_positions.remove([m[0],m[1]])\n\t\t\t\t\tself.black_positions.append([m[2],m[3]])\n\t\t\t\telse:\n\t\t\t\t\tself.board[m[2]][m[3]]='W'\n\t\t\t\t\tself.white_positions.remove([m[0],m[1]])\n\t\t\t\t\tself.white_positions.append([m[2],m[3]])\n\t\t\t\tself.board[m[0]][m[1]]='.'\n\t\t\tif maxplayer and self.isWin():\n\t\t\t\treturn 0,50, m\n\t\t\tfl,val,_=self.minimax(depth-1,player,max_time,alpha,beta,not maxplayer)\n\t\t\tif len(m)!=5 or (len(m)==5 and m[4]!='stmove' and m[4]!='jump'):\n\t\t\t\tfinal=len(m)-1\n\t\t\t\tif self.board[m[final][2]][m[final][3]]=='B':\n\t\t\t\t\tself.board[m[0][0]][m[0][1]]='B'\n\t\t\t\t\tself.black_positions.append([m[0][0],m[0][1]])\n\t\t\t\t\tself.black_positions.remove([m[final][2],m[final][3]])\n\t\t\t\telse:\n\t\t\t\t\tself.board[m[0][0]][m[0][1]]='W'\n\t\t\t\t\tself.white_positions.append([m[0][0],m[0][1]])\n\t\t\t\t\tself.white_positions.remove([m[final][2],m[final][3]])\n\t\t\t\tself.board[m[final][2]][m[final][3]]='.'\n\t\t\telse:\n\t\t\t\tif self.board[m[2]][m[3]]=='B':\n\t\t\t\t\tself.board[m[0]][m[1]]='B'\n\t\t\t\t\tself.black_positions.append([m[0],m[1]])\n\t\t\t\t\tself.black_positions.remove([m[2],m[3]])\n\t\t\t\telse:\n\t\t\t\t\tself.board[m[0]][m[1]]='W'\n\t\t\t\t\tself.white_positions.append([m[0],m[1]])\n\t\t\t\t\tself.white_positions.remove([m[2],m[3]])\n\t\t\t\tself.board[m[2]][m[3]]='.'\n\t\t\tif val==50:\n\t\t\t\treturn 0,val,m\n\t\t\tif maxplayer and val>best_score:\n\t\t\t\tbest_score=val\n\t\t\t\tbest_move=m\n\t\t\tif maxplayer and val>=beta:\n\t\t\t\treturn 0,best_score, best_move\n\t\t\tif maxplayer:\n\t\t\t\talpha=max(alpha, val)\n\t\t\tif not maxplayer and val', methods=['GET'])\ndef get_states(id):\n \"\"\"Retrieves a state_id object\"\"\"\n state = storage.get(State, id)\n if not state:\n abort(404)\n return jsonify(state.to_dict())\n\n\n@app_views.route('/states/', methods=['DELETE'])\ndef del_state(id):\n \"\"\"Deletes a State object\"\"\"\n state = storage.get(State, id)\n if not state:\n abort(404)\n\n storage.delete(state)\n storage.save()\n return {}, 200\n\n\n@app_views.route('/states', methods=['POST'])\ndef post_state():\n \"\"\"Creates a State\"\"\"\n info = request.get_json()\n if not info:\n abort(400, description=\"Not a JSON\")\n if 'name' not in info:\n abort(400, description=\"Missing name\")\n new_state = State(**info)\n new_state.save()\n return new_state.to_dict(), 201\n\n\n@app_views.route('/states/', methods=['PUT'])\ndef put_state(id):\n \"\"\"Updates a State object\"\"\"\n state = storage.get(State, id)\n if not state:\n abort(404)\n info_update = request.get_json()\n if not info_update:\n abort(400, description=\"Not a JSON\")\n\n ignore_key = [\"id\", \"created_at\", \"updated_at\"]\n for key, value in info_update.items():\n if key not in ignore_key:\n setattr(state, key, value)\n state.save()\n\n return jsonify(state.to_dict()), 200\n","sub_path":"api/v1/views/states.py","file_name":"states.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"593116282","text":"# pip install python-twitter\nimport os\nimport json\nimport twitter\nimport json\nimport pprint\nimport sqlite3\nfrom sqlite3 import Error\n \n \n\n# Consumer API Keys\nCONSUMER_KEY = 'OfJ4o1ElzOcGuwAtd94amZMnn' # (API key)\nCONSUMER_SECRET = 'KNYKEL2oFKZFXq6BQtNAKpXFTBqzI9RrIS8k4KA7MaDSMco5R9' # (API secret key)\n\n# Access token & access token secret\nTOKEN_KEY = '1054132964773298181-2a3tCStAeTDpyNw99j4pHoVfPJ9IFI' #(Access token)\nTOKEN_SECRET = 'kyWq49CyltVmEVQ9BaF0f80cp3qjtpyaqaI79hgA8F6tK' # (Access token secret)\n# Read and write (access level)\n\n# NEWS_SOURCES_URL = [r'nbcnews.com', r'cnn.com', r'usatoday.com']\nNEWS_SOURCES = [r'NBCNews', r'USATODAY', r'CNN']\n\n# MAX_TIMELINE = 200 # default -- we'll always get as many tweets as we can.\nMAX_SOURCES = 100\nSINGULAR_SOURCE = 1\nMAX_RETWEETERS = 100\nCONSERVATIVE = 10\n\n# if 0, get pool through retweets. if 1, get through quering the url\nPOOL_METHOD = 1\n\n\ndef create_connection(db_file):\n \"\"\" create a database connection to a SQLite database \"\"\"\n try:\n conn = sqlite3.connect(db_file)\n print(sqlite3.version)\n except Error as e:\n print(e)\n finally:\n conn.close()\n\n\n\n\ndef html_encode(text):\n\thtml_escape_table = {\n\t\t# '&': r\"&\",\n\t\t'\"': r\""\",\n\t\t\"'\": r\"'\",\n\t\t' ': r\"%20\",\n\t\t':': r\"%3A\",\n\t\t'/': r\"%2F\",\n\t\t'=': r\"%3D\"\n\t}\n\treturn \"\".join(html_escape_table.get(c, c) for c in text)\n\n\n'''\nBuilds query in HTML-encoded format that Twitter's Standard Search API requires.\nGiven a list of news sources' screen names (list of string), returns query (raw string).\n\nNumber of results (count) has a maximum of 100, default of 15.\nMore parameters: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets\n\t%3a is ':'\n \t%20 is '\n'''\ndef build_search_query(news_sources, num_articles):\n\tqry = r\"\"\n\tfor source in news_sources:\n\t\tqry += r'from:' + source + r' OR '\n\t# get rid of last 'OR ', add part to filter out retweets:\n\tqry = qry[:-3] + r'-filter:retweets'\n\tencoded_qry = html_encode(qry)\n\t# latest tweets + encoded qry + add src (typd or sprv) and count to query\n\tencoded_qry = r'f=tweets&vertical=news&q=' + encoded_qry + r'&src=typd&count=' + str(num_articles)\n\treturn encoded_qry\n\ndef build_article_query(article_url, num_results):\n\tqry = r\"url:\" + article_url + \" \"\n\tqry += r'-filter:retweets'\n\tencoded_qry = html_encode(qry)\n\tencoded_qry = r'f=tweets&vertical=news&q=' + encoded_qry + r'&src=typd&count=' + str(num_results)\n\treturn encoded_qry\n\n'''\nGiven a screen name (string), return the numeric Twitter id (int)\n'''\ndef id_from_screen_name(api, name):\n\treturn api.GetUser(screen_name=name)._json['id']\n\n'''\nHelpers to write the full results from search and timeline to a file\n'''\ndef write_timeline_to_file(userid, timeline):\n\tfile_name = str(user) + \"_timeline.txt\"\n\twith open(file_name, 'a') as f:\n\t\tfor twt in timeine:\n\t\t\tf.write(json.dumps(twt))\n\t\t\tf.write('\\n')\n\tprint(\"writing timline to file complete\")\ndef write_search_to_file(article_tweets):\n\tfile_name = 'tweets_output.txt'\n\twith open(file_name, 'a') as f: # won't over-write, but will just append\n\t\tfor twt in res:\n\t\t\tf.write(json.dumps(twt))\n\t\t\tf.write('\\n')\n\n\n\n\n'''\nGiven a user's numeric Twitter id (int), returns 200 (maximum allowed) of their tweets (list of JSON dicts),\nWrites it out to a file, with each line being a tweet in JSON, if write_to_file=True.\n\nReturns tuple: (full timeline JSON, string containing all text from tweets)\n'''\ndef timeline(api, userid, write_to_file):\n\t# not including retweets right now\n\tres_twts = api.GetUserTimeline(user_id=userid, count=200, include_rts=False)\n\tres = [twt._json for twt in res_twts]\n\n\t# to collect all the text in one string:\n\ttwt_str = \"\"\n\tfor twt in res:\n\t\ttwt_str += twt['full_text'] + \"\\n\"\n\n\treturn twt_str, res\n\n'''\nGiven a list of news sources' screen names (list of string), returns 100 (maximum allowed) of\n(hopefully only) their tweets (list of JSON dicts). Should not include any retweeted, since it is straight from the source.\n\nReturns tuple: (full search JSON, list of JSON mapping from article url to pool)\n'''\ndef search0(api, news_sources, num_articles, pool_size, pool_method, write_to_file):\n\tqry = build_search_query(news_sources, num_articles) \n\tprint(qry)\n\tres_twts = api.GetSearch(raw_query=qry)\n\tres = [twt._json for twt in res_twts] # tweets of news article\n\n\tall_articles_pool = []\n\tfor twt in res:\n\t\tif len(twt['entities']['urls']) != 0:\n\t\t\tarticle_pool = {} #key: url; value: list of user_ids \n\t\t\tres_pool = api.GetRetweeters(status_id=twt['id'], count=pool_size)\n\t\t\ttwt['pool'] = res_pool # could be an empty list\n\t\t\tarticle_pool['url'] = twt['entities']['urls'][0]['expanded_url']\n\t\t\tarticle_pool['pool'] = res_pool\n\t\t\tall_articles_pool.append(article_pool)\n\n\tarticle_urls = [article['url'] for article in all_articles_pool]\n\treturn all_articles_pool, article_urls, res\n\n'''\npool_size not used here since we are not calling the API to get retweeter id's for each article.\n'''\ndef search1(api, news_sources, num_articles, pool_size, write_to_file):\n\tqry = build_search_query(news_sources, num_articles)\n\tprint(qry)\n\tres_twts = api.GetSearch(raw_query=qry)\n\tres = [twt._json for twt in res_twts]\n\n\t# all_articles_pool = [] don't need to keep a list of retwitters anymore\n\tall_articles_pooltweets = []\n\tfor twt in res: # for each article\n\t\tif len(twt['entities']['urls']) != 0:\n\t\t\tarticles_pooltweets = {}\n\t\t\tpooltweets = []\n\n\t\t\t# get url\n\t\t\tarticle_url = twt['entities']['urls'][0]['expanded_url']\n\n\t\t\t# search through Twitter for this url\n\t\t\tqry_article = build_article_query(article_url, num_articles)\n\t\t\tres_twts_article = api.GetSearch(raw_query=qry_article)\n\t\t\tres_article = [twt._json for twt in res_twts_article]\n\n\t\t\tfor twt_person in res_article: # for each person\n\t\t\t\tif twt_person['user']['verified'] == False:\n\t\t\t\t\tuser_id = twt_person['user']['id']\n\t\t\t\t\t# get their tweets\n\t\t\t\t\tstr_person_tweets = timeline(api, user_id, write_to_file=False)[0]\n\t\t\t\t\tpooltweets.append(str_person_tweets)\n\n\t\t\tarticles_pooltweets['url'] = article_url\n\t\t\tarticles_pooltweets['pool_tweets'] = pooltweets\n\t\t\tall_articles_pooltweets.append(articles_pooltweets)\n\treturn all_articles_pooltweets\n\n\n'''\nall_articles_pooltweets is a list.\neach element will hold a dict.\nthe dict will have two keys, 'url' and 'pool_tweets'.\n'url' is the url of the news article.\n'pool_tweets' is a list, with each element\nbeing the string concatenation of a person in the pool's tweets.\n'''\ndef get_articles_pooltweets(api, news_sources, num_articles, pool_size, pool_method):\n\tif pool_method == 0:\n\t\tres = search0(api, news_sources, num_articles, pool_size, pool_method, write_to_file=False)[0]\n\n\t\tall_articles_pooltweets = []\n\n\t\t# num_retweeters = 0 # delete?\n\t\tfor article in res:\n\t\t\tarticles_pooltweets = {}\n\t\t\tpooltweets = []\n\n\t\t\tfor person in article['pool']:\n\t\t\t\tstr_person_tweets = timeline(api, person, write_to_file=False)[0]\n\t\t\t\tpooltweets.append(str_person_tweets)\n\t\t\t\n\t\t\tarticles_pooltweets['url'] = article['url']\n\t\t\tarticles_pooltweets['pool_tweets'] = pooltweets\n\t\t\tall_articles_pooltweets.append(articles_pooltweets)\n\n\t\treturn all_articles_pooltweets\n\telse:\n\t\tres = search1(api, news_sources, num_articles, pool_size, write_to_file=False)\n\t\treturn res\n\n'''\nTakes output from get_articles_tweets and turns it into:\n(one news article's url, string holding one user's tweets)\n\nreturns tuple, each element is the same but the second is in json format.\n'''\ndef format_converter(articles_pooltweets):\n\tarticle_tuples = []\n\tarticles_tuples_json = []\n\tfor article in articles_pooltweets:\n\t\tfor persontweets in article['pool_tweets']:\n\t\t\tres_json = {} # for json\n\t\t\tres_json['article_url'] = article['url']\n\t\t\tres_json['person_tweets'] = persontweets\n\n\t\t\tarticle_tuples.append((article['url'], persontweets))\n\t\t\tarticles_tuples_json.append(res_json)\n\treturn article_tuples, articles_tuples_json\n\n# res = format_converter(get_articles_tweets())\n# with open('asdf.txt', 'a') as f:\n# \tf.write(str(res))\n\n\ndef get_usertweets_articles(twitter_handle, news_sources, num_articles, num_retweeters, pool_method):\n\tapi = twitter.Api(consumer_key=CONSUMER_KEY,\n\t\t\t\t\t\tconsumer_secret=CONSUMER_SECRET,\n\t\t\t\t\t\taccess_token_key=TOKEN_KEY,\n\t\t\t\t\t\taccess_token_secret=TOKEN_SECRET,\n\t\t\t\t\t\ttweet_mode='extended')\n\n\tuser_tweets = timeline(api, id_from_screen_name(api, twitter_handle), write_to_file=False)[0]\n\tarticles_pooltweets = format_converter(get_articles_pooltweets(api, news_sources, num_articles, num_retweeters, pool_method))[1]\n\tres_json = {}\n\tres_json['user_tweets'] = user_tweets\n\tres_json['article_pooltweets'] = articles_pooltweets\n\n\treturn res_json, user_tweets, articles_pooltweets\n\t\n# res = get_usertweets_articles(\"aasdfang\", NEWS_SOURCES, CONSERVATIVE, CONSERVATIVE, POOL_METHOD)[0]\n# with open('ex.txt', 'a') as f:\n# \tf.write(json.dumps(res))\n\n\n\n\n#example to get data out of file:\n'''\nthetweets = []\nwith open('tweets_output.txt') as f:\n\tdata = f.readlines()\n\tfor l in data:\n\t\tthetweets.append(json.loads(l))\nprint(thetweets[5]['retweeted_by'])\n'''","sub_path":"public/scripts/python_twitter_test.py","file_name":"python_twitter_test.py","file_ext":"py","file_size_in_byte":8989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"302847942","text":"\n\nfrom xai.brain.wordbase.nouns._duke import _DUKE\n\n#calss header\nclass _DUKES(_DUKE, ):\n\tdef __init__(self,): \n\t\t_DUKE.__init__(self)\n\t\tself.name = \"DUKES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"duke\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_dukes.py","file_name":"_dukes.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"96466384","text":"from get_refresh_token import *\nfrom vilageFcst import *\nfrom ultraSrtNcst import *\nimport set_text\nimport pandas as pd\nfrom random_picture import *\n\naccess_token = get_refresh_token()\nfriend_url = \"https://kapi.kakao.com/v1/api/talk/friends\"\n\n# eunjin\n# GET /v1/api/talk/friends HTTP/1.1\n# Host: kapi.kakao.com\n# Authorization: Bearer {ACCESS_TOKEN}\n\nheaders={\"Authorization\" : \"Bearer \" + access_token}\nresult = json.loads(requests.get(friend_url, headers=headers).text)\n\nprint(\"=============================================\")\nprint(result)\nprint(\"=============================================\")\nfriends_list = result[\"elements\"]\nprint(friends_list)\nprint(\"=============================================\")\nprint(friends_list[0].get(\"uuid\"))\nfriend_id = friends_list[0].get(\"uuid\")\nprint(friend_id)\n\nfamilys = [\n {\n \"id\": 1806945511,\n \"nx\": \"60\",\n \"ny\" : \"121\"\n },\n {\n \"id\": 1806947703,\n \"nx\": \"61\",\n \"ny\": \"121\"\n },\n {\n \"id\": 1810629941,\n \"nx\": \"52\",\n \"ny\": \"38\"\n }\n]\ndf = pd.DataFrame()\nfor family in familys:\n family_dict = {}\n family_dict['id'] = family['id']\n family_dict['nx'] = family['nx']\n family_dict['ny'] = family['ny']\n df = df.append(family_dict, ignore_index=True)\n\nfor idx in friends_list:\n id = idx[\"id\"]\n uuid = idx[\"uuid\"]\n nx = df[df[\"id\"] == id][\"nx\"].values[0]\n ny = df[df[\"id\"] == id][\"ny\"].values[0]\n weather_data = getVilageFcst(nx, ny)\n yesterday_data = getultraSrtNcst(nx, ny)\n text_middle = set_text.set_text(weather_data, yesterday_data)\n\n if id == 1806945511:\n text_head = \"자기!!\\n\"\n elif id == 1806947703:\n text_head = \"언니!!\\n\"\n elif id == 1810629941:\n text_head = \"엄마!!\\n\"\n\n text = text_head + text_middle\n print(text)\n send_url = \"https://kapi.kakao.com/v1/api/talk/friends/message/default/send\"\n picture_url = random_picture()\n data = {\n 'receiver_uuids': '[\"{}\"]'.format(uuid),\n \"template_object\": json.dumps({\n \"object_type\": \"text\",\n \"text\": text,\n \"link\": {\n \"web_url\": \"https://m.weather.naver.com\",\n \"mobile_web_url\": \"https://m.weather.naver.com\"\n },\n \"buttons\": [\n {\n \"title\": \"은진이 사진\",\n \"link\": {\n \"web_url\": picture_url,\n \"mobile_web_url\": picture_url\n }\n },\n {\n \"title\": \"네이버 날씨\",\n \"link\": {\n \"web_url\": \"https://m.weather.naver.com\",\n \"mobile_web_url\": \"https://m.weather.naver.com\"\n }\n }\n ]\n })\n }\n\n response = requests.post(send_url, headers=headers, data=data)\n print(response.text)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"605199153","text":"'''\n\nMIT License\n\nCopyright (c) 2020 isirk\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n'''\n\nimport discord, random, json, time, asyncio\nfrom discord.ext import commands, menus\nfrom discord.ext.commands.cooldowns import BucketType\nfrom copy import deepcopy as dc\nimport async_cleverbot as ac\n\nconfig = \"tools/config.json\"\nwith open(config) as f:\n data = json.load(f)\ncb = data['CLEVERBOT']\n\ncleverbot = ac.Cleverbot(cb)\n\ndef rps_winner(userOneChoice, userTwoChoice):\n if userOneChoice == \"\\U0001faa8\":\n if userTwoChoice == \"\\U00002702\": return \"You won!\"\n if userTwoChoice == \"\\U0001faa8\": return \"Tie!\"\n if userTwoChoice == \"\\U0001f4f0\": return \"I won!\"\n elif userOneChoice == \"\\U00002702\":\n if userTwoChoice == \"\\U00002702\": return \"Tie!\"\n if userTwoChoice == \"\\U0001faa8\": return \"I won!\"\n if userTwoChoice == \"\\U0001f4f0\": return \"You Won!\"\n elif userOneChoice == \"\\U0001f4f0\":\n if userTwoChoice == \"\\U00002702\": return \"I won!\"\n if userTwoChoice == \"\\U0001faa8\": return \"You won!\"\n if userTwoChoice == \"\\U0001f4f0\": return \"Tie!\"\n else: return \"error\"\n \nclass games(commands.Cog):\n '''Game Commands'''\n def __init__(self, bot):\n self.bot = bot \n @commands.max_concurrency(1, per=BucketType.channel, wait=False)\n @commands.command(aliases=['cb'])\n async def chatbot(self, ctx):\n '''Talk to chatbot'''\n talk = True\n await ctx.send('Chatbot Started!\\nType `cancel` to end.')\n while talk is True:\n try:\n m = await self.bot.wait_for('message', timeout=30, check=lambda m:(ctx.author == m.author and ctx.channel == m.channel))\n except asyncio.TimeoutError:\n await ctx.send('Timeout Error')\n talk = False\n else:\n if m.content.lower() == \"cancel\":\n talk = False\n await ctx.send('Chatbot Session Ended.')\n else:\n async with ctx.channel.typing():\n response = await cleverbot.ask(m.content) # Ask a question, returns async_cleverbot.cleverbot.Response\n await ctx.send(response.text)\n \n @commands.command()\n @commands.cooldown(1,3,BucketType.user)\n async def dice(self, ctx):\n '''Roll a dice'''\n dice = ['1', '2', '3', '4', '5', '6', 'off the table...\\n*You Found The Mystery!*']\n embed = discord.Embed(title=\"Dice\", description=f'The Dice Rolled {random.choice(dice)}', color=self.bot.color)\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/attachments/758138226874908705/766312838910181421/unknown.png\")\n embed.set_footer(text=self.bot.footer)\n embed.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)\n await ctx.send(embed=embed)\n\n @commands.command()\n @commands.cooldown(1,3,BucketType.user)\n async def quiz(self, ctx):\n '''Take a Chritmas quiz'''\n qa = {\n \"`Was King William I of England was crowned on Christmas Day.(Yes/No)`\": \"YES\",\n \"`When is Christmas?`\": \"DECEMBER 25\",\n \"`Who delivers toys?`\" : \"SANTA\"\n }\n total_questions = len(qa)\n start_time = time.time()\n\n def check(message):\n return ctx.author == message.author and ctx.channel == message.channel\n\n for i, (question, answer) in enumerate(qa.items()):\n content = \"\"\n append = \"Type your answer below\"\n\n if i == 0:\n content += \"Quiz Started!\\n\"\n else:\n content += \"Correct!\\n\"\n content += (f\"**Question {i+1})** {question}\\n\"\n f\"{append}\")\n await ctx.send(content)\n\n try:\n message = await self.bot.wait_for(\"message\", timeout=45.0, check=check)\n except asyncio.TimeoutError:\n return await ctx.send(\"Timeout Error\")\n\n if message.content.upper() != answer:\n return await ctx.send(f\"Incorrect.\\nIf you would like to try again type `{ctx.prefix}quiz`\")\n time_taken = time.time()- start_time\n await ctx.send(f\"Correct!\\nYou took **{time_taken:,.2f} seconds!**\")\n\n \n @commands.cooldown(1,3,BucketType.user)\n @commands.command()\n async def rps(self, ctx):\n \"\"\"Rock paper scissors, either play against the bot or against a user\"\"\"\n choices = [\"\\U0001f4f0\", \"\\U0001faa8\", \"\\U00002702\"]\n s = m = await ctx.send(embed = discord.Embed(title = f\"Rock, Paper, Scissors.\", description = f\" {str(ctx.author)} Choose your weapon!\", color=self.bot.color))\n for i in choices:\n await m.add_reaction(i)\n\n def check(reaction, user):\n return user == ctx.author and str(reaction.emoji) in choices\n\n try:\n reaction = await self.bot.wait_for('reaction_add', timeout = 30.0, check = check)\n reaction = reaction[0].emoji\n botChoice = random.choice(choices)\n result = rps_winner(reaction, botChoice)\n\n await s.edit(embed= discord.Embed(title =result , description = f\"I picked {botChoice} and you picked {reaction}.\", color=self.bot.color))\n\n except asyncio.TimeoutError: return await ctx.send(\"You didn't add a reaction in time!\")\n \n @commands.max_concurrency(1, per=BucketType.guild, wait=False)\n @commands.command(aliases=['2048', '24'])\n async def twenty(self, ctx):\n \"\"\"Starts a 2048 game inside of Discord.\n Join the support server to post your score!\"\"\"\n ## Made by NeuroAssassin [https://github.com/NeuroAssassin/Toxic-Cogs/blob/master/twenty/twenty.py]\n board = [\n [\"_\", \"_\", \"_\", \"_\"],\n [\"_\", \"_\", \"_\", \"_\"],\n [\"_\", \"_\", \"_\", \"_\"],\n [\"_\", \"_\", \"_\", 2],\n ]\n score = 0\n total = 0\n embed=discord.Embed(title=\"2048\", description=f\"If a reaction is not received every 5 minutes, the game will time out.\\n\\n```{self.print_board(board)}```\", color=self.bot.color)\n message = await ctx.send(embed=embed)\n await message.add_reaction(\"\\u2B06\")\n await message.add_reaction(\"\\u2B07\")\n await message.add_reaction(\"\\u2B05\")\n await message.add_reaction(\"\\u27A1\")\n await message.add_reaction(\"\\u274C\")\n\n def check(reaction, user):\n return (\n (user.id == ctx.author.id)\n and (str(reaction.emoji) in [\"\\u2B06\", \"\\u2B07\", \"\\u2B05\", \"\\u27A1\", \"\\u274C\"])\n and (reaction.message.id == message.id)\n )\n\n while True:\n try:\n reaction, user = await self.bot.wait_for(\n \"reaction_add\", check=check, timeout=300.0\n )\n except asyncio.TimeoutError:\n await ctx.send(f\"Ending game.\\nYour score was **{score}**\")\n await message.delete()\n return\n else:\n try:\n await message.remove_reaction(str(reaction.emoji), ctx.author)\n except discord.errors.Forbidden:\n pass\n if str(reaction.emoji) == \"\\u2B06\":\n msg, nb, total = self.execute_move(\"up\", board)\n elif str(reaction.emoji) == \"\\u2B07\":\n msg, nb, total = self.execute_move(\"down\", board)\n elif str(reaction.emoji) == \"\\u2B05\":\n msg, nb, total = self.execute_move(\"left\", board)\n elif str(reaction.emoji) == \"\\u27A1\":\n msg, nb, total = self.execute_move(\"right\", board)\n elif str(reaction.emoji) == \"\\u274C\":\n await ctx.send(f\"Ending game.\\nYour score was **{score}**\")\n await message.delete()\n return\n score += total\n if msg == \"Lost\":\n await ctx.send(\n f\"Oh no! It appears you have lost {ctx.author.mention}. You finished with a score of {score}!\"\n )\n await message.delete()\n return\n board = nb\n sem=discord.Embed(title=f\"Score: **{score}**\", description=f\"```{self.print_board(board)}```\", color=self.bot.color)\n 'await message.edit(content=f\"Score: **{score}**```{self.print_board(board)}```\")'\n await message.edit(embed=sem)\n\n def print_board(self, board):\n col_width = max(len(str(word)) for row in board for word in row) + 2 # padding\n whole_thing = \"\"\n for row in board:\n whole_thing += \"\".join(str(word).ljust(col_width) for word in row) + \"\\n\"\n return whole_thing\n\n def execute_move(self, move, pboard):\n board = dc(pboard)\n total = 0\n if move.lower() == \"left\":\n nb, total = self.check_left(board)\n for x in range(len(nb)):\n while nb[x][0] == \"_\" and (nb[x][1] != \"_\" or nb[x][2] != \"_\" or nb[x][3] != \"_\"):\n nb[x][0] = nb[x][1]\n nb[x][1] = nb[x][2]\n nb[x][2] = nb[x][3]\n nb[x][3] = \"_\"\n while nb[x][1] == \"_\" and (nb[x][2] != \"_\" or nb[x][3] != \"_\"):\n nb[x][1] = nb[x][2]\n nb[x][2] = nb[x][3]\n nb[x][3] = \"_\"\n while nb[x][2] == \"_\" and (nb[x][3] != \"_\"):\n nb[x][2] = nb[x][3]\n nb[x][3] = \"_\"\n if move.lower() == \"right\":\n nb, total = self.check_right(board)\n for x in range(len(nb)):\n while nb[x][3] == \"_\" and (nb[x][2] != \"_\" or nb[x][1] != \"_\" or nb[x][0] != \"_\"):\n nb[x][3] = nb[x][2]\n nb[x][2] = nb[x][1]\n nb[x][1] = nb[x][0]\n nb[x][0] = \"_\"\n while nb[x][2] == \"_\" and (nb[x][1] != \"_\" or nb[x][0] != \"_\"):\n nb[x][2] = nb[x][1]\n nb[x][1] = nb[x][0]\n nb[x][0] = \"_\"\n while nb[x][1] == \"_\" and (nb[x][0] != \"_\"):\n nb[x][1] = nb[x][0]\n nb[x][0] = \"_\"\n if move.lower() == \"down\":\n nb = self.columize(board)\n nb, total = self.check_down(nb)\n for x in range(len(nb)):\n while nb[x][0] == \"_\" and (nb[x][1] != \"_\" or nb[x][2] != \"_\" or nb[x][3] != \"_\"):\n nb[x][0] = nb[x][1]\n nb[x][1] = nb[x][2]\n nb[x][2] = nb[x][3]\n nb[x][3] = \"_\"\n while nb[x][1] == \"_\" and (nb[x][2] != \"_\" or nb[x][3] != \"_\"):\n nb[x][1] = nb[x][2]\n nb[x][2] = nb[x][3]\n nb[x][3] = \"_\"\n while nb[x][2] == \"_\" and (nb[x][3] != \"_\"):\n nb[x][2] = nb[x][3]\n nb[x][3] = \"_\"\n nb = self.rowize(nb)\n if move.lower() == \"up\":\n nb = self.columize(board)\n nb, total = self.check_up(nb)\n for x in range(len(nb)):\n while nb[x][3] == \"_\" and (nb[x][2] != \"_\" or nb[x][1] != \"_\" or nb[x][0] != \"_\"):\n nb[x][3] = nb[x][2]\n nb[x][2] = nb[x][1]\n nb[x][1] = nb[x][0]\n nb[x][0] = \"_\"\n while nb[x][2] == \"_\" and (nb[x][1] != \"_\" or nb[x][0] != \"_\"):\n nb[x][2] = nb[x][1]\n nb[x][1] = nb[x][0]\n nb[x][0] = \"_\"\n while nb[x][1] == \"_\" and (nb[x][0] != \"_\"):\n nb[x][1] = nb[x][0]\n nb[x][0] = \"_\"\n nb = self.rowize(nb)\n if (\n nb != pboard\n ): # So the user doesn't make a move that doesn't change anything, and just add a number\n some_message, nb = self.add_number(nb)\n else:\n some_message = \"\"\n if some_message.startswith(\"Lost\"):\n return \"Lost\", nb, total\n else:\n return \"\", nb, total\n\n def add_number(self, board):\n try:\n row = random.randint(0, 3)\n except RecursionError:\n return \"Lost\", board\n if \"_\" in board[row]:\n number_of_zeroes = board[row].count(\"_\")\n if number_of_zeroes == 1:\n column = board[row].index(\"_\")\n else:\n column = random.randint(0, 3)\n while board[row][column] != \"_\":\n column = random.randint(0, 3)\n else:\n result, board = self.add_number(board)\n return result, board\n joining = random.randint(0, 100)\n if joining < 85:\n joining = 2\n else:\n joining = 4\n board[row][column] = joining\n return \"\", board\n\n def columize(self, board):\n new_board = [[], [], [], []]\n # Make first column\n new_board[0].append(board[3][0])\n new_board[0].append(board[2][0])\n new_board[0].append(board[1][0])\n new_board[0].append(board[0][0])\n # Make second column\n new_board[1].append(board[3][1])\n new_board[1].append(board[2][1])\n new_board[1].append(board[1][1])\n new_board[1].append(board[0][1])\n # Make third column\n new_board[2].append(board[3][2])\n new_board[2].append(board[2][2])\n new_board[2].append(board[1][2])\n new_board[2].append(board[0][2])\n # Make fourth column\n new_board[3].append(board[3][3])\n new_board[3].append(board[2][3])\n new_board[3].append(board[1][3])\n new_board[3].append(board[0][3])\n board = new_board\n return board\n\n def rowize(self, board):\n new_board = [[], [], [], []]\n # Make first row\n new_board[0].append(board[0][3])\n new_board[0].append(board[1][3])\n new_board[0].append(board[2][3])\n new_board[0].append(board[3][3])\n # Make second row\n new_board[1].append(board[0][2])\n new_board[1].append(board[1][2])\n new_board[1].append(board[2][2])\n new_board[1].append(board[3][2])\n # Make third row\n new_board[2].append(board[0][1])\n new_board[2].append(board[1][1])\n new_board[2].append(board[2][1])\n new_board[2].append(board[3][1])\n # Make fourth row\n new_board[3].append(board[0][0])\n new_board[3].append(board[1][0])\n new_board[3].append(board[2][0])\n new_board[3].append(board[3][0])\n board = new_board\n return board\n\n def check_left(self, board):\n total = 0\n for x in range(len(board)):\n for y in range(len(board[x])):\n try:\n if board[x][y + 1] != \"_\":\n if board[x][y] == board[x][y + 1]:\n board[x][y] = board[x][y] + board[x][y + 1]\n total += board[x][y]\n board[x][y + 1] = \"_\"\n elif board[x][y + 2] != \"_\":\n if board[x][y] == board[x][y + 2]:\n board[x][y] = board[x][y] + board[x][y + 2]\n total += board[x][y]\n board[x][y + 2] = \"_\"\n elif board[x][y + 3] != \"_\":\n if board[x][y] == board[x][y + 3]:\n board[x][y] = board[x][y] + board[x][y + 3]\n total += board[x][y]\n board[x][y + 3] = \"_\"\n except IndexError:\n pass\n return board, total\n\n def check_right(self, board):\n total = 0\n for x in range(len(board)):\n board[x].reverse()\n for y in range(len(board[x])):\n try:\n if board[x][y + 1] != \"_\":\n if board[x][y] == board[x][y + 1]:\n board[x][y] = board[x][y] + board[x][y + 1]\n total += board[x][y]\n board[x][y + 1] = \"_\"\n elif board[x][y + 2] != \"_\":\n if board[x][y] == board[x][y + 2]:\n board[x][y] = board[x][y] + board[x][y + 2]\n total += board[x][y]\n board[x][y + 2] = \"_\"\n elif board[x][y + 3] != \"_\":\n if board[x][y] == board[x][y + 3]:\n board[x][y] = board[x][y] + board[x][y + 3]\n total += board[x][y]\n board[x][y + 3] = \"_\"\n except IndexError:\n pass\n board[x].reverse()\n return board, total\n\n def check_up(self, board):\n total = 0\n for x in range(len(board)):\n board[x].reverse()\n for y in range(len(board[x])):\n try:\n if board[x][y + 1] != \"_\":\n if board[x][y] == board[x][y + 1]:\n board[x][y] = board[x][y] + board[x][y + 1]\n total += board[x][y]\n board[x][y + 1] = \"_\"\n elif board[x][y + 2] != \"_\":\n if board[x][y] == board[x][y + 2]:\n board[x][y] = board[x][y] + board[x][y + 2]\n total += board[x][y]\n board[x][y + 2] = \"_\"\n elif board[x][y + 3] != \"_\":\n if board[x][y] == board[x][y + 3]:\n board[x][y] = board[x][y] + board[x][y + 3]\n total += board[x][y]\n board[x][y + 3] = \"_\"\n except IndexError:\n pass\n board[x].reverse()\n return board, total\n\n def check_down(self, board):\n total = 0\n for x in range(len(board)):\n for y in range(len(board[x])):\n try:\n if board[x][y + 1] != \"_\":\n if board[x][y] == board[x][y + 1]:\n board[x][y] = board[x][y] + board[x][y + 1]\n total += board[x][y]\n board[x][y + 1] = \"_\"\n elif board[x][y + 2] != \"_\":\n if board[x][y] == board[x][y + 2]:\n board[x][y] = board[x][y] + board[x][y + 2]\n total += board[x][y]\n board[x][y + 2] = \"_\"\n elif board[x][y + 3] != \"_\":\n if board[x][y] == board[x][y + 3]:\n board[x][y] = board[x][y] + board[x][y + 3]\n total += board[x][y]\n board[x][y + 3] = \"_\"\n except IndexError:\n pass\n return board, total\n\n @commands.max_concurrency(1, per=BucketType.guild, wait=False)\n @commands.command()\n async def simon(self, ctx):\n \"\"\"Start a game of Simon.\"\"\"\n await ctx.send(\n \"Starting game...\\n**RULES:**\\n```1. When you are ready for the sequence, click the green checkmark.\\n2. Watch the sequence carefully, then repeat it back into chat. For example, if the 1 then the 2 changed, I would type 12.\\n3. You are given 10 seconds to repeat the sequence.\\n4. When waiting for confirmation for next sequence, click the green check within 5 minutes of the bot being ready.\\n5. Answer as soon as you can once the bot adds the stop watch emoji.```\"\n )\n board = [[1, 2], [3, 4]]\n level = [1, 4]\n points = 0\n message = await ctx.send(\"```\" + self.print_board(board) + \"```\")\n await message.add_reaction(\"\\u2705\")\n await message.add_reaction(\"\\u274C\")\n await ctx.send(\"Click the Green Check Reaction when you are ready for the sequence.\")\n\n def check(reaction, user):\n return (\n (user.id == ctx.author.id)\n and (str(reaction.emoji) in [\"\\u2705\", \"\\u274C\"])\n and (reaction.message.id == message.id)\n )\n\n randoms = []\n for x in range(4):\n randoms.append(random.randint(1, 4))\n\n while True:\n try:\n reaction, user = await self.bot.wait_for(\n \"reaction_add\", check=check, timeout=300.0\n )\n except asyncio.TimeoutError:\n await message.delete()\n await ctx.send(\n f\"Game has ended due to no response for starting the next sequence. You got {points} sequence{'s' if points != 1 else ''} correct!\"\n )\n return\n else:\n if str(reaction.emoji) == \"\\u274C\":\n await message.delete()\n await ctx.send(\n f\"Game has ended due to no response. You got {points} sequence{'s' if points != 1 else ''} correct!\"\n )\n return\n await message.remove_reaction(\"\\u2705\", self.bot.user)\n await message.remove_reaction(\"\\u274C\", self.bot.user)\n try:\n await message.remove_reaction(\"\\u2705\", ctx.author)\n except discord.errors.Forbidden:\n pass\n await message.add_reaction(\"\\u26A0\")\n for x in randoms:\n await asyncio.sleep(1)\n if x == 1:\n board[0][0] = \"-\"\n await message.edit(content=\"```\" + self.print_board(board) + \"```\")\n await asyncio.sleep(level[0])\n board[0][0] = 1\n elif x == 2:\n board[0][1] = \"-\"\n await message.edit(content=\"```\" + self.print_board(board) + \"```\")\n await asyncio.sleep(level[0])\n board[0][1] = 2\n elif x == 3:\n board[1][0] = \"-\"\n await message.edit(content=\"```\" + self.print_board(board) + \"```\")\n await asyncio.sleep(level[0])\n board[1][0] = 3\n elif x == 4:\n board[1][1] = \"-\"\n await message.edit(content=\"```\" + self.print_board(board) + \"```\")\n await asyncio.sleep(level[0])\n board[1][1] = 4\n await message.edit(content=\"```\" + self.print_board(board) + \"```\")\n await message.remove_reaction(\"\\u26A0\", self.bot.user)\n answer = \"\".join(list(map(str, randoms)))\n await message.add_reaction(\"\\u23F1\")\n\n def check_t(m):\n return (m.author.id == ctx.author.id) and (m.content.isdigit())\n\n try:\n user_answer = await self.bot.wait_for(\"message\", check=check_t, timeout=10.0)\n except asyncio.TimeoutError:\n await ctx.send(\n f\"Sorry {ctx.author.mention}! You took too long to answer. You got {points} sequence{'s' if points != 1 else ''} correct!\"\n )\n await message.remove_reaction(\"\\u23F1\", self.bot.user)\n return\n else:\n try:\n await user_answer.delete()\n except discord.errors.Forbidden:\n pass\n await message.remove_reaction(\"\\u23F1\", self.bot.user)\n if str(user_answer.content) == str(answer):\n await message.add_reaction(\"\\U0001F44D\")\n else:\n await message.add_reaction(\"\\U0001F6AB\")\n await ctx.send(\n f\"Sorry, but that was the incorrect pattern. The pattern was {answer}. You got {points} sequence{'s' if points != 1 else ''} correct!\"\n )\n return\n another_message = await ctx.send(\"Sequence was correct.\")\n points += 1\n await asyncio.sleep(3)\n await message.remove_reaction(\"\\U0001F44D\", self.bot.user)\n await message.add_reaction(\"\\u2705\")\n await message.add_reaction(\"\\u274C\")\n await another_message.delete()\n level[0] *= 0.90\n randoms.append(random.randint(1, 4))\n\n def print_board(self, board):\n col_width = max(len(str(word)) for row in board for word in row) + 2 # padding\n whole_thing = \"\"\n for row in board:\n whole_thing += \"\".join(str(word).ljust(col_width) for word in row) + \"\\n\"\n return whole_thing\n\ndef setup(bot):\n bot.add_cog(games(bot))\n","sub_path":"cogs/games.py","file_name":"games.py","file_ext":"py","file_size_in_byte":26026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"200423774","text":"# Copyright (c) 2016-2019, Matteo Cafasso\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# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n\n# 3. 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,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS\n# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n# OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT\n# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport sys\n\nimport clips\n\nfrom clips._clips import lib, ffi # pylint: disable=E0611\n\n\nclass DataObject(object):\n \"\"\"CLIPS DATA_OBJECT structure wrapper.\"\"\"\n\n __slots__ = '_env', '_data', '_type'\n\n def __init__(self, env, data=None, dtype=None):\n self._env = env\n self._type = dtype\n self._data = data if data is not None else ffi.new(\"DATA_OBJECT *\")\n\n @property\n def byref(self):\n \"\"\"Return the DATA_OBJECT structure pointer.\"\"\"\n return self._data\n\n @property\n def byval(self):\n \"\"\"Return the DATA_OBJECT structure.\"\"\"\n return self._data[0]\n\n @property\n def value(self):\n \"\"\"Return the DATA_OBJECT stored value.\"\"\"\n dtype = lib.get_data_type(self._data)\n dvalue = lib.get_data_value(self._data)\n\n if dvalue == ffi.NULL:\n return None\n\n return self.python_value(dtype, dvalue)\n\n @value.setter\n def value(self, value):\n \"\"\"Sets the DATA_OBJECT stored value.\"\"\"\n dtype = TYPES[type(value)] if self._type is None else self._type\n\n lib.set_data_type(self._data, dtype)\n lib.set_data_value(self._data, self.clips_value(value))\n\n def python_value(self, dtype, dvalue):\n \"\"\"Convert a CLIPS type into Python.\"\"\"\n try:\n return CONVERTERS[dtype](dvalue)\n except KeyError:\n if dtype == clips.common.CLIPSType.MULTIFIELD:\n return self.multifield_to_list()\n if dtype == clips.common.CLIPSType.FACT_ADDRESS:\n return clips.facts.new_fact(self._env, lib.to_pointer(dvalue))\n if dtype == clips.common.CLIPSType.INSTANCE_ADDRESS:\n return clips.classes.Instance(self._env, lib.to_pointer(dvalue))\n\n return None\n\n def clips_value(self, dvalue):\n \"\"\"Convert a Python type into CLIPS.\"\"\"\n try:\n return VALUES[type(dvalue)](self._env, dvalue)\n except KeyError:\n if isinstance(dvalue, (list, tuple)):\n return self.list_to_multifield(dvalue)\n if isinstance(dvalue, (clips.facts.Fact)):\n return dvalue._fact\n if isinstance(dvalue, (clips.classes.Instance)):\n return dvalue._ist\n\n return ffi.NULL\n\n def multifield_to_list(self):\n end = lib.get_data_end(self._data)\n begin = lib.get_data_begin(self._data)\n multifield = lib.get_data_value(self._data)\n\n return [self.python_value(lib.get_multifield_type(multifield, i),\n lib.get_multifield_value(multifield, i))\n for i in range(begin, end + 1)]\n\n def list_to_multifield(self, values):\n index = 1\n size = len(values)\n multifield = lib.EnvCreateMultifield(self._env, size)\n\n for value in values:\n lib.set_multifield_type(multifield, index, TYPES[type(value)])\n lib.set_multifield_value(multifield, index, self.clips_value(value))\n\n index += 1\n\n lib.set_data_begin(self._data, 1)\n lib.set_data_end(self._data, size)\n\n return multifield\n\n\ndef string_to_str(string):\n return ffi.string(lib.to_string(string)).decode()\n\n\nCONVERTERS = {clips.common.CLIPSType.FLOAT: lib.to_double,\n clips.common.CLIPSType.INTEGER: lib.to_integer,\n clips.common.CLIPSType.STRING: string_to_str,\n clips.common.CLIPSType.EXTERNAL_ADDRESS: lib.to_external_address,\n clips.common.CLIPSType.SYMBOL:\n lambda v: clips.common.Symbol(string_to_str(v)),\n clips.common.CLIPSType.INSTANCE_NAME:\n lambda v: clips.common.InstanceName(string_to_str(v))}\n\nTYPES = {type(None): clips.common.CLIPSType.SYMBOL,\n bool: clips.common.CLIPSType.SYMBOL,\n int: clips.common.CLIPSType.INTEGER,\n float: clips.common.CLIPSType.FLOAT,\n str: clips.common.CLIPSType.STRING,\n list: clips.common.CLIPSType.MULTIFIELD,\n tuple: clips.common.CLIPSType.MULTIFIELD,\n clips.common.Symbol: clips.common.CLIPSType.SYMBOL,\n clips.facts.ImpliedFact: clips.common.CLIPSType.FACT_ADDRESS,\n clips.facts.TemplateFact: clips.common.CLIPSType.FACT_ADDRESS,\n clips.classes.Instance: clips.common.CLIPSType.INSTANCE_ADDRESS,\n clips.common.InstanceName: clips.common.CLIPSType.INSTANCE_NAME}\nVALUES = {type(None): lambda e, v: lib.EnvAddSymbol(e, b'nil'),\n bool: lambda e, v: lib.EnvAddSymbol(e, b'TRUE' if v else b'FALSE'),\n int: lib.EnvAddLong,\n float: lib.EnvAddDouble,\n ffi.CData: lambda _, v: v,\n str: lambda e, v: lib.EnvAddSymbol(e, v.encode()),\n clips.common.Symbol: lambda e, v: lib.EnvAddSymbol(e, v.encode()),\n clips.common.InstanceName:\n lambda e, v: lib.EnvAddSymbol(e, v.encode())}\n\nif sys.version_info.major == 2:\n # pylint: disable=E0602\n TYPES[unicode] = clips.common.CLIPSType.STRING\n # pylint: disable=E0602\n TYPES[long] = clips.common.CLIPSType.INTEGER\n # pylint: disable=E0602\n VALUES[unicode] = lambda e, v: lib.EnvAddSymbol(e, v.encode())\n # pylint: disable=E0602\n VALUES[long] = lib.EnvAddLong\n","sub_path":"clips/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"327949538","text":"from PIL import Image\nimport re\nimport os\nfn = os.path.join(os.path.dirname(__file__), 'my_file')\ndef boxLocation(num,mode):\n boxLoca = (0,0)\n if(mode=='1'):\n if (num == 0):\n boxLoca = (80,114)\n if (num == 1):\n boxLoca = (890,114)\n if (num == 2):\n boxLoca = (1698,114)\n if (num == 3):\n boxLoca = (80,1245)\n if (num == 4):\n boxLoca = (890,1245)\n if (num == 5):\n boxLoca = (1698,1245)\n if (num == 6):\n boxLoca = (80,2372)\n if (num == 7):\n boxLoca = (890,2372)\n if (num == 8):\n boxLoca = (1698,2372)\n if(mode=='2'):\n if (num == 0):\n boxLoca = (0,0)\n if (num == 1):\n boxLoca = (697,0)\n if (num == 2):\n boxLoca = (1394,0)\n if (num == 3):\n boxLoca = (0,1016)\n if (num == 4):\n boxLoca = (687,1016)\n if (num == 5):\n boxLoca = (1394,1016)\n if (num == 6):\n boxLoca = (0,2032)\n if (num == 7):\n boxLoca = (697,2032)\n if (num == 8):\n boxLoca = (1394,2032)\n return boxLoca\n# Input a file and get path,head,data\ndef GetFile():\n file = input('输入文件名:')\n data = open(file)\n data = data.read().splitlines()\n file2Read = file.split('\\\\')\n length = len(file2Read)\n pathF = ''\n for words in file2Read[0:length-1]:\n if not len(words)==0:\n words = words + '\\\\\\\\'\n pathF = pathF + words\n fileHead = file2Read[length-1].split('.')[0]\n fileHead = ''.join(fileHead)\n return pathF,fileHead,data\n# Choose the pics bed\ndef Getbed():\n opt = input('1:OCG_high 2:TCG 3:OCG_low 4:CHN \\n请选择:')\n if opt=='1':\n bed = 'D:\\\\\\\\YGO\\\\\\\\OCG_high\\\\\\\\'\n if opt=='2':\n bed = 'D:\\\\\\\\YGO\\\\\\\\TCG\\\\\\\\'\n if opt=='3':\n bed = 'D:\\\\\\\\YGO\\\\\\\\OCG_low\\\\\\\\'\n if opt=='4':\n bed = 'D:\\\\\\\\YGO\\\\\\\\CHN\\\\\\\\'\n return bed\npathF,fileHead,data = GetFile()\nprint(pathF,fileHead,data)\nmode = input(\"1:A4,2:157\\n请选择:\")\nbed = Getbed()\nnum = 0\ntimes = 1\nunFound = open(pathF+fileHead+'-unfound.txt','w')\nfor lines in data:\n PrintName = pathF + fileHead + '-' + str(times) + '.png'\n # When it is the First One,Create a white background\n if (num == 0):\n if (mode == '1'):\n backGround = Image.new('RGB', (2480, 3508), color='white')\n if (mode == '2'):\n backGround = Image.new('RGB', (2091, 3047), color='white')\n if (lines=='end' ) :\n if(num==9):\n break\n else:\n backGround.save(PrintName, 'PNG')\n print('程序结束!')\n break\n if not(len(lines)==0):\n try:\n try:\n CardFile = bed + lines + '.jpg'\n CardUnderOperate = Image.open(CardFile)\n except:\n CardFile = bed + lines + '.png'\n CardUnderOperate = Image.open(CardFile)\n except :\n unFound.write(lines+'\\n')\n continue\n box1 = boxLocation(num,mode)\n backGround.paste(CardUnderOperate,box1)\n num = num + 1\n if (num==9):\n backGround.save(PrintName,'PNG')\n times = times + 1\n num = 0\nunFound.write('end')\nexit()\n\n","sub_path":"TypeSet.py","file_name":"TypeSet.py","file_ext":"py","file_size_in_byte":3337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"649972331","text":"from docx import Document\nfrom docx.shared import Inches\n\nclass PerElementPickList():\n def __init__(self):\n pass\n\n def Create(self, orders, people, elements, filename='PerElementPickList.docx'):\n\n picklist = {}\n\n for order in orders:\n elementId = order.Element.Id\n\n if elementId in picklist:\n picklist[elementId].append((order.Person.Id, order.Quantity))\n else:\n picklist[elementId] = [(order.Person.Id, order.Quantity)]\n\n document = Document()\n\n for elementId, personList in picklist.items():\n\n document.add_picture('images/2018/'+ elements[elementId].LEGOId +'.png', width=Inches(0.75))\n document.add_heading(elements[elementId].LEGOId + ' - ' + elements[elementId].Description.upper() + ' : ' + elements[elementId].Color, 0)\n\n table = document.add_table(rows=1, cols=2)\n headerRow = table.rows[0].cells\n headerRow[0].text = \"Name\"\n headerRow[1].text = \"Quantity\"\n\n for item in personList:\n lineItem = table.add_row().cells\n lineItem[0].text = people[item[0]].Name\n lineItem[1].text = item[1]\n\n document.add_page_break()\n\n document.save(filename)","sub_path":"PerElementPickList.py","file_name":"PerElementPickList.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"529207985","text":"from django.test import TestCase\nfrom django.contrib.auth.models import User\n\nfrom curricula.models import Curriculum, Unit\nfrom lessons.models import Lesson, Resource\n\n\nclass CurriculaRenderingTestCase(TestCase):\n def setUp(self):\n user = User.objects.create_user(username='admin', password='12345')\n user.is_staff = True\n user.save()\n self.client.login(username='admin', password='12345')\n\n self.test_curriculum = Curriculum.objects.create(\n title=\"Test Curriculum\",\n slug=\"test-curriculum\",\n assessment_commentary=\"Assessment Commentary\")\n self.csf_curriculum = Curriculum.objects.create(\n title=\"CSF Curriculum\",\n slug=\"csf-curriculum\",\n assessment_commentary=\"CSF Commentary\",\n unit_template_override='curricula/csf_unit.html')\n self.pl_curriculum = Curriculum.objects.create(\n title=\"PL Curriculum\",\n slug=\"pl-curriculum\",\n assessment_commentary=\"PL Commentary\",\n unit_template_override='curricula/pl_unit.html')\n self.test_unit = Unit.objects.create(\n title=\"Test Unit\",\n parent=self.test_curriculum,\n slug=\"test-unit\",\n description=\"Test unit description\",\n show_calendar=True\n )\n self.hoc_unit = Unit.objects.create(\n title=\"HoC Unit\",\n parent=self.test_curriculum,\n slug=\"hoc-unit\",\n description=\"Hoc unit description\",\n lesson_template_override=\"curricula/hoc_lesson.html\"\n )\n self.csf_unit = Unit.objects.create(\n title=\"CSF Unit\",\n parent=self.csf_curriculum,\n slug=\"csf-unit\",\n description=\"CSF unit description\",\n lesson_template_override=\"curricula/csf_lesson.html\"\n )\n self.pl_unit = Unit.objects.create(\n title=\"PL Unit\",\n parent=self.pl_curriculum,\n slug=\"pl-unit\",\n description=\"PL unit description\",\n lesson_template_override=\"curricula/pl_lesson.html\"\n )\n resource = Resource.objects.create(\n name=\"Test Resource\",\n slug=\"test-resource\",\n student=True\n )\n self.test_lesson = Lesson.objects.create(\n title=\"Test Lesson\",\n parent=self.test_unit,\n overview=\"Overview\",\n prep=\"Prep\"\n )\n self.test_lesson.resources.add(resource)\n self.hoc_lesson = Lesson.objects.create(\n title=\"HoC Lesson\",\n parent=self.hoc_unit,\n overview=\"HoC Overview\",\n prep=\"Prep\"\n )\n self.hoc_lesson.resources.add(resource)\n self.csf_lesson = Lesson.objects.create(\n title=\"CSF Lesson\",\n parent=self.csf_unit,\n overview=\"CSF Overview\",\n prep=\"Prep\"\n )\n self.csf_lesson.resources.add(resource)\n self.pl_lesson = Lesson.objects.create(\n title=\"PL Lesson\",\n parent=self.pl_unit,\n overview=\"PL Overview\",\n prep=\"Prep\"\n )\n self.pl_lesson.resources.add(resource)\n\n def test_homepage(self):\n response = self.client.get('/')\n self.assertEqual(response.status_code, 200)\n\n def test_render_curriculum(self):\n response = self.client.get('/test-curriculum/')\n self.assertEqual(response.status_code, 200)\n\n def test_render_unit(self):\n response = self.client.get('/test-curriculum/test-unit/')\n self.assertEqual(response.status_code, 200)\n response = self.client.get('/csf-curriculum/csf-unit/')\n self.assertEqual(response.status_code, 200)\n response = self.client.get('/test-curriculum/hoc-unit/')\n self.assertEqual(response.status_code, 200)\n response = self.client.get('/pl-curriculum/pl-unit/')\n self.assertEqual(response.status_code, 200)\n response = self.client.get('/test-curriculum/test-unit/glance/')\n self.assertEqual(response.status_code, 200)\n response = self.client.get('/test-curriculum/test-unit/vocab/')\n self.assertEqual(response.status_code, 200)\n response = self.client.get('/test-curriculum/test-unit/code/')\n self.assertEqual(response.status_code, 200)\n response = self.client.get('/test-curriculum/test-unit/resources/')\n self.assertEqual(response.status_code, 200)\n response = self.client.get('/test-curriculum/test-unit/objectives/')\n self.assertEqual(response.status_code, 200)\n response = self.client.get('/test-curriculum/test-unit/unit_feedback/')\n self.assertEqual(response.status_code, 200)\n response = self.client.get('/test-curriculum/test-unit/?pdf=1')\n self.assertEqual(response.status_code, 200)\n response = self.client.get('/pl-curriculum/pl-unit/?pdf=1')\n self.assertEqual(response.status_code, 200)\n\n def test_render_lesson(self):\n response = self.client.get('/test-curriculum/test-unit/1/')\n self.assertEqual(response.status_code, 200)\n response = self.client.get('/test-curriculum/hoc-unit/1/')\n self.assertEqual(response.status_code, 200)\n response = self.client.get('/csf-curriculum/csf-unit/1/')\n self.assertEqual(response.status_code, 200)\n response = self.client.get('/pl-curriculum/pl-unit/1/')\n self.assertEqual(response.status_code, 200)\n\n def test_render_lesson_with_levels(self):\n stage = {\n \"levels\": [{\n \"path\": \"/s/dance/stage/1/puzzle/1\",\n \"name\": \"Dance_Party_11\",\n \"mini_rubric\": True\n },{\n \"path\": \"/s/dance/stage/1/puzzle/2\",\n \"name\": \"Dance_Party_22\",\n \"teacher_markdown\": \"teacher markdown\",\n \"named_level\": True\n }],\n \"stageName\": \"test stage\"\n }\n self.test_lesson.stage = stage\n self.test_lesson.save()\n response = self.client.get('/test-curriculum/test-unit/1/')\n self.assertEqual(response.status_code, 200)\n","sub_path":"curricula/tests/test_curricula_rendering.py","file_name":"test_curricula_rendering.py","file_ext":"py","file_size_in_byte":6163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"433293992","text":"# This function is designed to create a message in a previously created SNS topic\n# for the purpose of triggering a lambda cleaner function\n\nimport boto3\nfrom datetime import timedelta\nfrom ec2_metadata import ec2_metadata\nimport sys\nimport argparse\nimport json\nimport subprocess\n\n# Function to get the uptime of the instance as a string\n# Format is Days Hours:Minutes:Seconds.Microseconds\ndef get_uptime():\n try:\n with open('/proc/uptime', 'r') as f:\n uptime_seconds = float(f.readline().split()[0])\n uptime = timedelta(seconds = uptime_seconds)\n except:\n uptime = \"unknown\"\n return str(uptime)\n\n# Function to find the ARN of the SNS topic given the topic name\ndef get_topic_arn( topic_name ):\n global sns\n topics = (sns.list_topics())\n for topic in topics['Topics']:\n if topic_name in topic['TopicArn']:\n return topic['TopicArn']\n \n# Function to find the region the instance is in\ndef get_region():\n try:\n region = ec2_metadata.region\n return region\n except Exception as e:\n print(\"Error determining region: \" + e)\n exit(1)\n\n# Function to find the stack name of the current instance\ndef get_stack( region ):\n instance_id = ec2_metadata.instance_id\n command = \"aws ec2 describe-instances \\\n --region \" + region + \" \\\n --instance-id \" + instance_id + \" \\\n --output json\"\n response = json.loads(subprocess.check_output(command.split()))\n tags = response['Reservations'][0]['Instances'][0]['Tags']\n stack = None\n for tag in tags:\n if tag['Key'] == 'aws:cloudformation:stack-name':\n stack = (tag['Value'])\n if stack is None:\n print(\"Unable to find stack name from metadata, exiting\")\n exit(1)\n else:\n return stack\n\n# Function to send a message to an SNS queue\ndef send_message( target_arn, stack ):\n global sns\n uptime = get_uptime()\n message = \"Instance \" + ec2_metadata.public_hostname + \" ran for \" + uptime\n try:\n sns.publish(\n TargetArn = target_arn,\n Subject = \"Import Complete\",\n Message = message,\n MessageStructure = 'string',\n MessageAttributes = {\n \"Uptime\" : {\n 'DataType' : 'String',\n 'StringValue' : uptime\n },\n \"Stack\" : {\n 'DataType' : 'String',\n 'StringValue' : stack\n }\n }\n )\n return \"Sent Message to \" + target_arn\n except Exception as e:\n return e\n\n### Execution Begins Here ###\ndef main(argv):\n global sns\n \n # Get options, if any\n parser = argparse.ArgumentParser()\n parser.add_argument('-t','--topic', help='Topic name', required=True)\n parser.add_argument('-p','--profile', help='Profile to use, if configured', required=False)\n parser.add_argument('-r','--region', help='AWS Region', required=False)\n parser.add_argument('-s', '--stack', help='Stack name', required=False)\n args = parser.parse_args()\n \n # Set Variables\n topic = args.topic\n profile = args.profile\n \n if args.region is not None:\n region = args.region\n else:\n region = get_region()\n \n if args.stack is not None:\n stack = args.stack\n else:\n stack = get_stack( region )\n \n # Create the session\n if profile is not None:\n session = boto3.Session(region_name=region, profile_name=profile)\n else:\n session = boto3.Session(region_name=region)\n \n sns = session.client('sns')\n\n # Get the arn for the provided topic name\n topic_arn = get_topic_arn(topic)\n\n # Send Message to Queue\n print(send_message( topic_arn, stack ))\n \nif __name__ == \"__main__\":\n main(sys.argv[1:])\n ","sub_path":"notify_completion.py","file_name":"notify_completion.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"415438463","text":"import msgpackrpc\n\nclass FileServer(object):\n def upload_text(self, text_str):\n print('text data uploaded:\\n{}'.format(text_str))\n return 'received {} bytes'.format(len(text_str))\n\nserver = msgpackrpc.Server(FileServer())\nserver.listen(msgpackrpc.Address('128.97.92.68', 18800))\nserver.start()\n\n","sub_path":"config_line/sample_file_server.py","file_name":"sample_file_server.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"356387982","text":"\"\"\"\n===============\nauthor:Administrator\ntime:15:00\nE-mail:1223607348@qq.com\n===============\n'''\nddt:数据驱动思想\n@ddt:装饰器\n'''\n\"\"\"\nimport unittest\nfrom ddt import ddt,data\nfrom register import register_check\nfrom read_excel import ReadExcel\n# 读取测试用例\n@ddt\nclass RegisterTestCase(unittest.TestCase):\n \"\"\"测试登录功能函数的测试用例类\"\"\"\n # cases = ReadExcel('cases.xlsx', 'cases').read_cases_obj()\n excel = ReadExcel('cases.xlsx', 'cases')\n cases = excel.read_cases_obj()\n def setUp(self):\n print('用例{}开始执行'.format(self))\n def tearDown(self):\n print('用例{}执行结束'.format(self))\n @data(*cases)\n def test_register(self,case):\n # '''注册模块的用例'''\n # 预期结果\n excepted = eval(case.excepted)\n # print(excepted)\n # 入参参数data\n data = eval(case.data)\n # print(data)\n # 执行功能函数,获取实际结果\n res = register_check(*data)\n try:\n # 对比预期结果和实际结果\n self.assertEqual(excepted,res)\n except AssertionError as error:\n print('测试用例不通过')\n self.excel.write_data(case.case_id+1,4,'failed')\n print('预期结果:{}'.format(excepted))\n print('实际结果:{}'.format(res))\n raise error\n else:\n print('测试用例通过')\n self.excel.write_data(case.case_id+1, 4, 'passed')\n print('预期结果:{}'.format(excepted))\n print('实际结果:{}'.format(res))\n","sub_path":"one/python14_logging/ddt_read_result/testcases.py","file_name":"testcases.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"223481646","text":"#!/usr/bin/env python\n\nimport os\nimport os.path as osp\n\nimport chainer_mask_rcnn as cmr\nimport numpy as np\nimport skimage.color\n\nimport instance_occlsegm_lib\nfrom instance_occlsegm_lib.contrib import instance_occlsegm\n\n\ndata = instance_occlsegm.datasets.PanopticOcclusionSegmentationDataset('train')\nclass_names = data.class_names\nimg, bboxes, labels, masks, _, _ = data[1]\n\nkeep = labels == 16\nbboxes = bboxes[keep]\nlabels = labels[keep]\nmasks = masks[keep]\nassert keep.sum() == 1\n\nimg_org = img.copy()\n\nmask = masks[0]\nimg_gray = skimage.color.rgb2gray(img)\nimg_gray = skimage.color.gray2rgb(img_gray)\nimg_gray = (img_gray * 255).astype(np.uint8)\nimg[mask != 1] = img_gray[mask != 1]\n\n# captions = ['{}: {}'.format(l, class_names[l]) for l in labels]\ncaptions = [class_names[l] for l in labels]\nfor caption in captions:\n print(caption)\n\nviz_org = cmr.utils.draw_instance_bboxes(\n img_org,\n bboxes,\n labels + 1,\n n_class=len(class_names) + 1,\n captions=captions,\n)\nviz_bg = cmr.utils.draw_instance_bboxes(\n img,\n bboxes,\n labels + 1,\n masks=masks == 0,\n n_class=len(class_names) + 1,\n captions=captions,\n)\nviz_vis = cmr.utils.draw_instance_bboxes(\n img,\n bboxes,\n labels + 1,\n masks=masks == 1,\n n_class=len(class_names) + 1,\n captions=captions,\n)\nviz_occ = cmr.utils.draw_instance_bboxes(\n img,\n bboxes,\n labels + 1,\n masks=masks == 2,\n n_class=len(class_names) + 1,\n captions=captions,\n)\n\nbbox = bboxes[0]\ny1, x1, y2, x2 = [int(round(x)) for x in bbox]\nviz_bg = viz_bg[y1:y2, x1:x2]\nviz_vis = viz_vis[y1:y2, x1:x2]\nviz_occ = viz_occ[y1:y2, x1:x2]\n\noffset_y = 60\nviz_org = viz_org[offset_y:-30, 30:-40]\n# viz_bg = viz_bg[offset_y:, :]\n# viz_vis = viz_vis[offset_y:, :]\n# viz_occ = viz_occ[offset_y:, :]\n\nviz_bg = instance_occlsegm_lib.image.resize(viz_bg, height=viz_org.shape[0])\nviz_vis = instance_occlsegm_lib.image.resize(viz_vis, height=viz_org.shape[0])\nviz_occ = instance_occlsegm_lib.image.resize(viz_occ, height=viz_org.shape[0])\n\nout_dir = 'logs/multi_class_masks'\ntry:\n os.makedirs(out_dir)\nexcept OSError:\n pass\n\ninstance_occlsegm_lib.io.imsave(osp.join(out_dir, 'image.jpg'), viz_org)\ninstance_occlsegm_lib.io.imsave(osp.join(out_dir, 'background.jpg'), viz_bg)\ninstance_occlsegm_lib.io.imsave(osp.join(out_dir, 'visible.jpg'), viz_vis)\ninstance_occlsegm_lib.io.imsave(osp.join(out_dir, 'occluded.jpg'), viz_occ)\n\n# viz_masks = np.hstack([viz_bg, viz_vis, viz_occ])\n# viz_org = instance_occlsegm_lib.image.resize(\n# viz_org, width=viz_masks.shape[1])\n# viz_masks = instance_occlsegm_lib.image.resize(\n# viz_masks, width=viz_org.shape[1])\n# viz = np.vstack([viz_org, viz_masks])\n# viz = instance_occlsegm_lib.image.tile(\n# [img_org, viz_bg, viz_vis, viz_occ], (1, 4), boundary=True\n# )\n# instance_occlsegm_lib.io.imsave('result.jpg', viz)\n# instance_occlsegm_lib.io.imshow(viz)\n# instance_occlsegm_lib.io.waitkey()\n","sub_path":"demos/instance_occlsegm/examples/instance_occlsegm/paper/visualize_multi_class_masks.py","file_name":"visualize_multi_class_masks.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"240214974","text":"from goto import with_goto\nfrom CodigoIntermedio import CodigoIntermedio\nfrom Entorno.Entorno import Entorno\n@with_goto\ndef prueba():\n\tstack =[]\n\tci = CodigoIntermedio(Entorno())\n\tt0=t0*1\n\tt0=t0+0\n\tt4=t4-0\n\tt0=t1*2\n\tabsoluto=10\n\thora=1+1\n\tvalor=hora\n\thora=valor\n\tseno=seno+0\n\tseno=seno-0\n\tseno=seno*1\n\tseno=seno*2\n\tt1=t2/1\n\tt3=t3/1\n\tt4=t5*1\n\tvalor=seno+0\n\tvalor=seno-0\n\tt6=t7*1\n\tt8=t9/1\n\tx=y*0\n\tt11=0/t12\n\tt12=t13+0\n\tval=nuevo-0\n\tvalor=seno/1\n\tvalor=absoluto*2\n\tvalor=absoluto*0\n\tvalor=0/absoluto","sub_path":"parser/fase2/team14/optimizacion.py","file_name":"optimizacion.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"299707381","text":"# Note: Warning! This program should be run only within the Python's terminal or in an external console!\n# After build and run, immediately click the Python's terminal or the external console.\nimport pyautogui\nimport time\n\nprint(\"\\nInitializing...\")\n# Acts as timer 'before' starting other program line:\ntime.sleep(1.5)\n\ninitial1 = [\"Hello,\", \"I\", \"am\", \"a\", \"nameless\", \"bot.\"]\ntime.sleep(1)\nfor a in range(0, 6):\n pyautogui.typewrite(initial1[a])\n pyautogui.typewrite(\" \")\n # Waiting time of 'next word within the list 'initial1''.\n time.sleep(0.1)\n\ninitial2 = [\"Are,\", \"you\", \"going\", \"to\", \"call\", \"me\", \"with\", \"a\", \"name?\"]\ntime.sleep(1)\nfor a in range(0, 9):\n pyautogui.typewrite(initial2[a])\n pyautogui.typewrite(\" \")\n time.sleep(0.1)\n# This can either be a 'yes' or 'no' regardless of alphanumeric case.\nbotIntro = str(input(\"\\n-> \"))\n# Note: Both functions 'str.lower()' and 'str.upper()' does not work, so I have to resort to this instead:\nif botIntro == str(\"Yes\") or botIntro == str(\"yes\") or botIntro == str(\"YES\") or botIntro == str(\"yEs\") or botIntro == str(\"yeS\") or botIntro == str(\"YeS\") or botIntro == str(\"yES\") or botIntro == str(\"YEs\") and not (str(\"No\") or botIntro == str(\"no\") or botIntro == str(\"nO\")):\n question1 = [\"Then,\", \"what\", \"will\", \"be\", \"my\", \"name?\"]\n time.sleep(1)\n for a in range(0, 6):\n pyautogui.typewrite(question1[a])\n pyautogui.typewrite(\" \")\n time.sleep(0.1)\n # Bot's name:\n botName = str(input(\"\\n-> \"))\n\n state1 = [\"Thank\", \"you.\"]\n time.sleep(1)\n for a in range(0, 2):\n pyautogui.typewrite(state1[a])\n pyautogui.typewrite(\" \")\n time.sleep(0.1)\n\n state2 = [\"I\", \"see,\", \"so\", \"from\", \"now\", \"on\", \"I\", \"will\", \"be\", \"called\", \"as\", botName+\".\"]\n time.sleep(1)\n for a in range(0, 12):\n pyautogui.typewrite(state2[a])\n pyautogui.typewrite(\" \")\n time.sleep(0.1)\n # A sentence within a new line.\n state3 = [\"\\nMmm\", \"I\", botName+\",\"]\n time.sleep(1)\n for a in range(0, 3):\n pyautogui.typewrite(state3[a])\n pyautogui.typewrite(\" \")\n time.sleep(0.1)\n state4 = [\"as\", \"your\", \"bot,\"]\n time.sleep(1)\n for a in range(0, 3):\n pyautogui.typewrite(state4[a])\n pyautogui.typewrite(\" \")\n time.sleep(0.1)\n state5 = [\"should\", \"know\", \"your\", \"name\", \"as\", \"well.\"]\n time.sleep(1)\n for a in range(0, 6):\n pyautogui.typewrite(state5[a])\n pyautogui.typewrite(\" \")\n time.sleep(0.1)\n if botName == str(\"\") or botName == str(\" \"):\n print(\"Error. Provide a valid name.\")\n else:\n question2 = [\"\\nWhat\", \"is\", \"your\", \"name?\"]\n time.sleep(1)\n for a in range(0, 4):\n pyautogui.typewrite(question2[a])\n pyautogui.typewrite(\" \")\n time.sleep(0.1)\n # User's name:\n uName = str(input(\"\\n-> \"))\nelif botIntro == str(\"No\") or botIntro == str(\"no\") or botIntro == str(\"nO\") and not (botIntro == str(\"Yes\") or botIntro == str(\"yes\") or botIntro == str(\"YES\") or botIntro == str(\"yEs\") or botIntro == str(\"yeS\") or botIntro == str(\"YeS\") or botIntro == str(\"yES\") or botIntro == str(\"YEs\")):\n comments = [\"Very\", \"well\", \"then\", \"goodbye.\"]\n time.sleep(1)\n for y in range(0, 4):\n pyautogui.typewrite(comments[y])\n pyautogui.typewrite(\" \")\n time.sleep(0.1)\nelse:\n print(\"Pardon. My system does not recognize the input.\")\n","sub_path":"myBot_beta.py","file_name":"myBot_beta.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"380528768","text":"#\r\n# @lc app=leetcode id=1131 lang=python3\r\n#\r\n# [1131] Maximum of Absolute Value Expression\r\n#\r\n# https://leetcode.com/problems/maximum-of-absolute-value-expression/description/\r\n#\r\n# algorithms\r\n# Medium (50.30%)\r\n# Likes: 38\r\n# Dislikes: 46\r\n# Total Accepted: 2.4K\r\n# Total Submissions: 4.7K\r\n# Testcase Example: '[1,2,3,4]\\r\\n[-1,4,5,6]\\r'\r\n#\r\n# Given two arrays of integers with equal lengths, return the maximum value\r\n# of:\r\n#\r\n# |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|\r\n#\r\n# where the maximum is taken over all 0 <= i, j < arr1.length.\r\n#\r\n#\r\n# Example 1:\r\n#\r\n#\r\n# Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]\r\n# Output: 13\r\n#\r\n#\r\n# Example 2:\r\n#\r\n#\r\n# Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]\r\n# Output: 20\r\n#\r\n#\r\n#\r\n# Constraints:\r\n#\r\n#\r\n# 2 <= arr1.length == arr2.length <= 40000\r\n# -10^6 <= arr1[i], arr2[i] <= 10^6\r\n#\r\n#\r\nclass Solution:\r\n def maxAbsValExpr(self, arr1, arr2) -> int:\r\n if len(arr1) != len(arr2):\r\n return 0\r\n # NOTE: |a+b| = max(a+b, a-b, b-a,-b-a)\r\n # thus the ans can be converted to max - min for 4 situations, other 4 situations are just oppsite (arr1[i]+arr2[i]+i, arr1[i]-arr2[i]+i, -arr1[i]+arr2[i]+i, -arr1[i]+arr2[i]+i)\r\n # implementation 1\r\n # mns = [float('inf')] * 4\r\n # mxs = [-float('inf')] * 4\r\n # ops = [(1, 1, 1), (1, -1, 1), (-1, 1, 1), (-1, -1, 1)]\r\n # for i in range(len(arr1)):\r\n # for j in range(len(ops)):\r\n # cur = arr1[i] * ops[j][0] + arr2[i] * ops[j][1] + i\r\n # mns[j] = min(mns[j], cur)\r\n # mxs[j] = max(mxs[j], cur)\r\n # return max([mxs[i] - mns[i] for i in range(len(mns))])\r\n # implementation 2, more concise\r\n res = 0\r\n for p, q in ((1, 1), (1, -1), (-1, 1), (-1, -1)):\r\n mn = p * arr1[0] + q * arr2[0]\r\n for i in range(len(arr1)):\r\n cur = arr1[i] * p + arr2[i] * q + i\r\n res = max(res, cur - mn)\r\n mn = min(mn, cur)\r\n return res\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(Solution().maxAbsValExpr(arr1=[1, 2, 3, 4], arr2=[-1, 4, 5, 6]))\r\n print(Solution().maxAbsValExpr(arr1=[1, -2, -5, 0, 10],\r\n arr2=[0, -2, -1, -7, -4]))\r\n","sub_path":"Medium/1131.maximum-of-absolute-value-expression.py","file_name":"1131.maximum-of-absolute-value-expression.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"146984596","text":"class Muscle:\n\n def __init__(self, name, sets=0):\n self.name = name\n self.sets = sets\n\n\nclass Exercise:\n\n def __init__(self, name, ch=0, bk=0, fd=0, md=0, rd=0, bi=0, tr=0, qa=0, hm=0, gl=0, cv=0):\n self.name = name\n self.chest = ch\n self.back = bk\n self.fdelts = fd\n self.mdelts = md\n self.rdelts = rd\n self.biceps = bi\n self.triceps = tr\n self.quads = qa\n self.hams = hm\n self.glutes = gl\n self.calves = cv\n\n\nmuscleList = []\n\nmuscleList.append(Muscle(\"Chest\", 0))\nmuscleList.append(Muscle(\"Back\", 0))\nmuscleList.append(Muscle(\"Front Delts\", 0))\nmuscleList.append(Muscle(\"Middle Delts\", 0))\nmuscleList.append(Muscle(\"Rear Delts\", 0))\nmuscleList.append(Muscle(\"Biceps\", 0))\nmuscleList.append(Muscle(\"Triceps\", 0))\nmuscleList.append(Muscle(\"Quads\", 0))\nmuscleList.append(Muscle(\"Hams\", 0))\nmuscleList.append(Muscle(\"Glutes\", 0))\nmuscleList.append(Muscle(\"Calves\", 0))\n\nexerciseList = []\n\nexerciseList.append(Exercise(\"Horizontal Press\",1,0,1,0,0,0,1,0,0,0,0))\nexerciseList.append(Exercise(\"Incline Press\",1,0,1,1,0,0,1,0,0,0,0))\nexerciseList.append(Exercise(\"Fly\",1,0,1,0,0,0,0,0,0,0,0))\nexerciseList.append(Exercise(\"Horizontal Pull\",0,1,0,1,1,1,0,0,0,0,0))\nexerciseList.append(Exercise(\"Vertical Pull\",0,1,0,0,1,1,0,0,0,0,0))\nexerciseList.append(Exercise(\"Vertical Press\",0,0,1,1,0,0,1,0,0,0,0))\nexerciseList.append(Exercise(\"Lateral Raise\",0,0,0,1,0,0,0,0,0,0,0))\nexerciseList.append(Exercise(\"Rear Delt Iso\",0,0,0,0,1,0,0,0,0,0,0))\nexerciseList.append(Exercise(\"Bicep Iso\",0,0,0,0,0,1,0,0,0,0,0))\nexerciseList.append(Exercise(\"Tricep Iso\",0,0,0,0,0,0,1,0,0,0,0))\nexerciseList.append(Exercise(\"Squat\",0,0,0,0,0,0,0,1,0,1,0))\nexerciseList.append(Exercise(\"Quad Iso\",0,0,0,0,0,0,0,1,0,0,0))\nexerciseList.append(Exercise(\"Hip Hinge\",0,0,0,0,0,0,0,0,1,1,0))\nexerciseList.append(Exercise(\"Ham Iso\",0,0,0,0,0,0,0,0,1,0,0))\nexerciseList.append(Exercise(\"Horizontal Hip Extension\",0,0,0,0,0,0,0,0,1,1,0))\nexerciseList.append(Exercise(\"Glute Iso\",0,0,0,0,0,0,0,0,0,1,0))\nexerciseList.append(Exercise(\"Pull Over\",1,1,0,0,0,0,1,0,0,0,0))\nexerciseList.append(Exercise(\"Calf Iso\",0,0,0,0,0,0,0,0,0,0,1))\n\nprint(\"Welcome to Volume Tracker\")\nprint(\"Inspired by The Muscle and Strength Pyramids\")\nprint(\"\\nCreate a file named program.txt with your workout program\")\nprint(\"Each line should contain the movement pattern followed by the number of sets\")\nprint(\"Ex. Horizontal Press 4\")\nprint(\"\\nMovement Patterns:\")\nprint(\"Squat\\nHip Hinge\\nVertical Pull\\nVertical Push\\n\"\n \"Horizontal Pull\\nHorizontal Push\\nIncline Push\\nHorizontal Hip Extension\\n\"\n \"Pullover\\nFly\\nBiceps\\nTriceps\\nSide Delts\\nRear Delts\\n\")\n\n\nfile = open(\"program.txt\", \"r\")\n\nfor line in file:\n the_string = line\n name, sets = the_string.split()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"11428249","text":"#!/usr/bin/env python\n\nimport logging\nimport logging.handlers\nimport logging.config\n\n\n\ndef initlog(level=None):\n\n if level is None:\n level = logging.DEBUG if __debug__ else logging.INFO\n\n class MyFormatter(logging.Formatter):\n def format(self, record):\n dformatter = '%(levelname)s: [%(asctime)s] - %(pathname)s %(lineno)d - %(message)s'\n formatter = '%(levelname)s: [%(asctime)s] - %(message)s'\n if record.levelno <= logging.DEBUG:\n self._fmt = dformatter\n else:\n self._fmt = formatter\n return super(MyFormatter, self).format(record)\n\n config = {\n \"version\": 1,\n \"disable_existing_loggers\": True,\n \"formatters\": {\n \"custom\": {\n '()': MyFormatter\n },\n \"simple\": {\n \"format\": \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n },\n \"verbose\": {\n \"format\": \"%(asctime)s - %(levelname)s - %(module)s %(lineno)d - %(message)s\"\n }\n },\n \"handlers\": {\n \"console\": {\n \"class\": \"logging.StreamHandler\",\n \"level\": \"DEBUG\",\n \"formatter\": \"custom\",\n \"stream\": \"ext://sys.stdout\"\n },\n \"file_handler\": {\n \"class\": \"logging.handlers.RotatingFileHandler\",\n \"level\": \"DEBUG\",\n \"formatter\": \"custom\",\n \"filename\": \"app.log\",\n \"maxBytes\": 10*1000**3, # 10M\n \"backupCount\": 5,\n \"encoding\": \"utf8\"\n }\n },\n 'root': {\n 'level': level,\n 'handlers': ['file_handler']\n },\n \"loggers\": {\n \"myloger\": {\n \"level\": level,\n \"handlers\": [\n \"console\"\n ],\n }\n },\n }\n\n logging.config.dictConfig(config)\n\n\ninitlog()\nlogging.debug('debug 1')\nlogger = logging.getLogger(\"myloger\")\nlogger.debug('test d')\n\n","sub_path":"python/initlog.py","file_name":"initlog.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"135208460","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index),\n path('register', views.register),\n path('quotes', views.quotes),\n path('login', views.login),\n path('logout', views.logout),\n path('create_quote', views.create_quote),\n path('delete_quote/', views.delete_quote),\n path('edit_user', views.edit_user),\n path('update_user', views.update_user),\n path('show_user/', views.show_user),\n path('like//', views.like),\n]","sub_path":"python_belt_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"567242046","text":"# This script will periodically open a browser telling\n# telling the user to take a break and playing one of\n# their favorite songs on youtube\n\nimport random\nimport time\nimport webbrowser\n\n# list of songs to choose from\nsongs = ['https://www.youtube.com/watch?v=pBkHHoOIIn8',\n 'https://www.youtube.com/watch?v=rVeMiVU77wo',\n 'https://www.youtube.com/watch?v=bpOSxM0rNPM',\n 'https://www.youtube.com/watch?v=aNYjOVo5IEw',\n 'https://www.youtube.com/watch?v=TRqiFPpw2fY',\n 'https://www.youtube.com/watch?v=SBjQ9tuuTJQ']\n\n# number of repetitions during the day\nrepeat = 3\n\n# amount of time to wait between playing songs (in seconds)\nwait_time = 7200\n\n# number of current iterations\nnum_times = 0\n\nwhile num_times < repeat:\n # wait the specified amount of time\n time.sleep(wait_time)\n # increment number of times the loop has run\n num_times += 1\n # get a random index from the songs array\n index = random.randrange(0, len(songs))\n # open a new window with the url found at index in songs\n webbrowser.open(songs[index], 1)\n","sub_path":"Object_Oriented_Python/take_a_break.py","file_name":"take_a_break.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"250059477","text":"from django.contrib import admin\nfrom django.urls import reverse\nfrom django.utils.html import format_html\n\n# Register your models here.\nfrom .models import Comment\n\n\nclass CommentsInline(admin.TabularInline):\n model = Comment\n extra = 0\n readonly_fields = ('responded_user',)\n\n def get_fields(self, request, obj=None):\n return [\n 'responded_user',\n 'content'\n ]\n\n def responded_user(self, obj):\n comment_id = obj.id\n url = reverse('admin:comments_comment_change', args=(obj.id,))\n return format_html(f'{obj.user}')\n\n@admin.register(Comment)\nclass CommentAdmin(admin.ModelAdmin):\n fields = [\n 'user',\n 'content_type',\n 'product',\n 'object_id',\n 'content',\n 'parent_comment_author',\n 'parent_comment_text'\n ]\n\n list_display = [\n 'user',\n 'content_type',\n 'product',\n 'parent_comment_author',\n 'text',\n 'timestamp'\n ]\n\n readonly_fields = ('parent_comment_author', 'product', 'parent_comment_text')\n\n\n def product(self, obj):\n url = reverse('admin:products_product_change', args=(obj.content_object.id,))\n return format_html(f'{obj.content_object}')\n\n def parent_comment_author(self, obj):\n parent_comment_id = getattr(obj.parent, 'id', None)\n if not parent_comment_id:\n return '-'\n url = reverse('admin:comments_comment_change', args=(obj.parent.id,))\n return format_html(f'{obj.parent.user}')\n\n def parent_comment_text(self, obj):\n parent_comment_id = getattr(obj.parent, 'id', None)\n if not parent_comment_id:\n return '-'\n return obj.parent.content\n\n\n def text(self, obj):\n text = obj.content\n content = (text[:50] + '...') if len(text) > 50 else text\n url = reverse('admin:comments_comment_change', args=(obj.id,))\n return format_html(f'{content}')\n\n inlines = [CommentsInline]","sub_path":"comments/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"256500215","text":"import tflearn\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\ndef Create_LinerData(size, w=2.0, b=0.5):\n \"\"\"\n 生成线性训练数据\n \"\"\"\n x = np.linspace(-1, 1, size, dtype='float32')\n y = w*x + np.random.standard_normal(x.shape)*0.3+b # 生成线性数据\n x = np.reshape(x, (size, 1))\n y = np.reshape(y, (size, 1))\n\n return x, y\n\nx,y=Create_LinerData(100)\n\nprint(x.shape,y.shape)\n\ninput_ = tflearn.input_data(shape=[None])\nlinear = tflearn.single_unit(input_)\nregression = tflearn.regression(\n linear, optimizer='sgd', loss='mean_square',\n metric='R2', learning_rate=0.01)\n\nm = tflearn.DNN(regression)\nm.fit(x, y, n_epoch=1000, show_metric=True, snapshot_epoch=False)\n\nprint(\"\\nRegression result:\")\nprint(\"Y = \" + str(m.get_weights(linear.W)) +\n \"*X + \" + str(m.get_weights(linear.b)))\n\nprint(\"\\nTest prediction for x = 3.2, 3.3, 3.4:\")\nprint(m.predict([3.2, 3.3, 3.4]))\n\nplt.plot(x, y, 'o')\ny = m.get_weights(linear.b) + m.get_weights(linear.W)*x\nplt.plot(x, y)\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.title('linear_regression')\nplt.show()\n","sub_path":"python/learn-note/linear_regression/linear_regression_3.py","file_name":"linear_regression_3.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"360992635","text":"import numpy as np\nf_in = open(\"prepared_data.txt\")\nf_out = open(\"prepared_data_complete.txt\", \"w\")\n\nline = f_in.readline()\nwhile line != '':\n time_list = []\n for i in range(4):\n thr, m_size, time = line.split()\n time_list.append(float(time))\n line = f_in.readline()\n time_avg = np.average(time_list)\n f_out.write(thr + \" \" + m_size + \" \" + str(time_avg) + \"\\n\")\nf_in.close()\nf_out.close()\n","sub_path":"openMP/prepared_data2.py","file_name":"prepared_data2.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"401202068","text":"from os.path import dirname, join\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndata_path = join(dirname(__file__), \"data.csv\")\ndata = pd.read_csv(data_path, sep=\"|\")\nlegitimate_binaries = data[0:41323].drop(['legitimate'], axis=1)\nmalicious_binaries = data[41323::].drop(['legitimate'], axis=1)\nplt.hist([legitimate_binaries['SectionsMaxEntropy'], malicious_binaries['SectionsMaxEntropy']],\n range=[0, 8], normed=True,\n color=[\"green\", \"red\"],\n label=[\"legitimate\", \"malicious\"])\nplt.legend()\nplt.savefig(\"eda.png\")\n","sub_path":"data/eda.py","file_name":"eda.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"379992262","text":"from django.urls import path, re_path, include\r\nfrom django.conf.urls import url\r\n\r\nfrom . import views\r\n\r\napp_name = 'axf'\r\n\r\nurlpatterns = [\r\n re_path(r'^$', views.index, name=\"index\"),\r\n re_path(r'^home/$', views.home, name=\"home\"),\r\n re_path(r'^market/$', views.market, name=\"market\"),\r\n re_path(r'^cart/$', views.cart, name=\"cart\"),\r\n re_path(r'^mine/$', views.mine, name=\"mine\"),\r\n]","sub_path":"axf/axf/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"79392239","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse, HttpRequest, Http404, HttpResponseBadRequest\nfrom django.shortcuts import render, redirect\n\nfrom main.models import Team\n\n\n@login_required\ndef get(request: HttpRequest, team_id: int) -> HttpResponse:\n is_allowed_to_view_members = request.user.profile.is_verified_by_admin\n team = Team.objects.get(pk=team_id)\n try:\n my_team = request.user.teams.filter(pk=team_id).first()\n except Team.DoesNotExist:\n my_team = None\n\n is_member = my_team is not None\n\n return render(request, 'team/detail.html', context={\n 'profile': request.user.profile,\n 'team': team,\n 'is_member': is_member,\n 'is_allowed_to_view_members': is_allowed_to_view_members,\n })\n\n\n@login_required\ndef list(request: HttpRequest) -> HttpResponse:\n teams = Team.objects_ordered_by_remaining_space().all()\n my_team_ids = [team.id for team in request.user.teams.all()]\n return render(request, 'team/list.html', context={\n 'profile': request.user.profile,\n 'my_team_ids': my_team_ids,\n 'teams': teams,\n })\n\n\n@login_required\ndef toggle_membership(request: HttpRequest, team_id: int) -> HttpResponse:\n if request.method != 'POST':\n raise Http404\n\n next_url = request.POST.get('next')\n team = Team.objects.get(pk=team_id)\n successfully_toggled = team.toggle_membership(request.user)\n if not successfully_toggled:\n return HttpResponseBadRequest('Sorry, {} team is full.'.format(team.name))\n\n if next_url:\n return redirect(next_url)\n return redirect(get, team_id)\n","sub_path":"main/views/team.py","file_name":"team.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"258712204","text":"#!/usr/bin/python3\n\nimport sys\n\nclass Animal(object):\n def __init__(self):\n self.name = 'animal'\n self.sound = 'nothing'\n\n def speak(self):\n print(self.name + ' says ' + self.sound)\n\nclass Human(Animal):\n def __init__(self):\n super().__init__()\n self.name = 'human'\n self.sound = 'dude'\n \nclass Dog(Animal):\n def __init__(self):\n super().__init__()\n self.name = 'dog'\n self.sound = 'bow wow'\n\nclass Cat(Animal):\n def __init__(self):\n super().__init__()\n self.name = 'cat'\n self.sound = 'meow'\n\na = Animal()\na.speak()\n\nd = Dog()\nd.speak()\n\nc = Cat()\nc.speak()\n\nh = Human()\nh.speak()\n\nanimals = [ a, d, c, h ]\nfor animal in animals:\n animal.speak()\n\n","sub_path":"python/basics/pclass.py","file_name":"pclass.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"491639565","text":"#!/usr/bin/env python\n\n\"\"\"\n\"able was i ere i saw elba\" is a well_known palindrome. Write a generalized\nprogram that proves this phrase is a palindrome. Because the program is\ngeneralized, it should also prove that any other palindromes are actually\npalindromes and it should prove when phrases or words are not palindromes.\nBe sure to write your program such that this is the case. And, be sure that\nyour argument takes any palindrome on the command line as input (i.e., use the\nargparse module). Write the program to include a main() function and the ifmain\nstatement. The main() function should call the function or functions that you\ncreate to test for \"palindrome_ness\".\n\nCredit url: http://pymbook.readthedocs.org/en/latest/strings.html\nDate accessed: February 9th, 2016.\n\nCreated by Shraddha Shrestha on February 10, 2016.\nCopyright 2016 Shraddha Shrestha. All rights reserved.\n\n\"\"\"\n\nimport argparse\n\n\ndef parser():\n parser= argparse.ArgumentParser()\n parser.add_argument(\"phrase\", type=str, help=\"check for palindrome\")\n args = parser.parse_args()\n return args.phrase\n\n\ndef palindrome():\n forward = parser()\n reverse = str(forward)[::-1]\n if forward == reverse:\n print(\"YES, string is a palindrome!\")\n else:\n print(\"NOT a palindrome!\")\n\n\ndef main():\n parser()\n palindrome()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"answers/sthshraddha/Task1.py","file_name":"Task1.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"418323975","text":"import numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.layers import (\n Add,\n Input,\n Conv2D,\n Dense,\n Dropout,\n Flatten,\n ELU,\n MaxPooling2D,\n Multiply,\n BatchNormalization,\n LayerNormalization,\n)\nfrom tensorflow.keras.initializers import TruncatedNormal\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.constraints import unit_norm\n\n\ndef conv(x, filters, strides=1, weight_decay=1e-8, bn=True):\n initializer = TruncatedNormal(stddev=1e-3)\n regularizer = l2(weight_decay)\n x = Conv2D(\n filters=filters,\n kernel_size=(3, 3),\n strides=strides,\n padding=\"same\",\n kernel_initializer=initializer,\n kernel_regularizer=regularizer,\n use_bias=False,\n )(x)\n\n if bn:\n x = BatchNormalization()(x)\n\n x = ELU()(x)\n return x\n\n\ndef residual(x, filters, strides=1, dropout_rate=0.6):\n incoming = x\n x = conv(x, filters, strides=strides)\n x = Dropout(dropout_rate)(x)\n x = conv(x, filters, bn=False)\n\n if not incoming.shape == x.shape:\n # Upsample via convolution to match the shape\n incoming = Conv2D(\n filters=filters,\n kernel_size=(3, 3),\n strides=strides,\n padding=\"same\",\n use_bias=False,\n )(incoming)\n\n x = Add()([incoming, x])\n\n return x\n\n\ndef Model(size, channels=3, num_classes=1500, feature_dim=128, training=False):\n x = inputs = Input([size[0], size[1], channels], name=\"input\")\n x = conv(x, 32)\n x = conv(x, 32)\n x = MaxPooling2D((3, 3), (2, 2), padding=\"same\")(x)\n x = residual(x, 32)\n x = residual(x, 32)\n x = residual(x, 64, strides=2)\n x = residual(x, 64)\n x = residual(x, 128, strides=2)\n x = residual(x, 128)\n x = Flatten()(x)\n x = Dropout(0.6)(x)\n x = BatchNormalization()(x)\n x = Dense(\n feature_dim,\n kernel_regularizer=l2(1e-8),\n kernel_initializer=TruncatedNormal(stddev=1e-3),\n )(x)\n features = tf.nn.l2_normalize(x, axis=1)\n\n if training:\n outputs = Dense(num_classes)(x)\n\n else:\n outputs = features\n\n return tf.keras.Model(inputs, outputs, name=\"model\")\n","sub_path":"deepsort/deep/original.py","file_name":"original.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"435282925","text":"WIDTH = 2000\nHEIGHT = 1000\nG = 9.8\n\nclass Cluster(object):\n \n def __init__(self, gravityCoefficient, x, y, count = 5):\n self.centroid = PVector(x,y)\n self.particles = []\n self.dots = []\n self.dashes = []\n self.mass = .5\n self.gravity = self.mass*gravityCoefficient\n self.gType = True\n self.drawType = \"dot\"\n self.trace = False\n for i in range(count):\n self.addParticle()\n \n \n def move(self, x, y):\n self.position.x = x\n self.position.y = y\n if self.drawType==\"lastfew\": background(color(255))\n for particle in self.particles:\n particle.move()\n particle.display()\n \n # Add a particle to the system\n def addParticle(self):\n self.particles.append(Particle(self))\n \n def popParticle(self):\n try: self.particles.pop()\n except: print(\"already empty\")\n \n # Get average position of particles \n def get_centroid(self):\n x = 0\n y = 0\n for particle in self.particles:\n x += particle.position.x\n y += particle.position.y\n x=x/self.particles.length\n y=y/self.particles.length\n \n def increaseGravity(self):\n self.gravity += 1\n \n def decreaseGravity(self):\n self.gravity -= 1\n if self.gravity <= 0:\n self.gravity = 1\n \n \n \n \n\nclass Particle(object):\n \n def __init__(self, system):\n self.system = system\n self.distance = random(100)\n self.angle = radians(random(0,360))\n self.velocity = PVector(random(0,.1),random(0,.1))\n self.position = PVector( system.position.x + self.distance*cos(self.angle), system.position.y + self.distance*sin(self.angle))\n self.lastfew = []\n\n def display(self):\n stroke(0)\n fill(color(0))\n if self.system.drawType==\"dot\": ellipse(self.position.x, self.position.y, 2, 2)\n if self.system.drawType==\"line\":\n line(self.previousPosition.x, self.previousPosition.y, self.position.x, self.position.y)\n if self.system.drawType==\"lastfew\": \n for prevpos in self.lastfew:\n print(len(self.lastfew))\n ellipse(prevpos.x, prevpos.y, 2, 2)\n \n \n def move(self):\n \n self.updateVelocity()\n self.updatePosition()\n \n \n def getDistance(self):\n \n # Gets and sets the distance from the center point of the system to the point\n self.distance = sqrt((self.position.x - self.system.position.x)**2 +(self.position.y - self.system.position.y)**2)\n \n # Change of coords\n # d.x being positive means the particle is to the left of the system\n # d.y being positive means the particle is above the system\n \n self.d = PVector(self.system.position.x - self.position.x, self.system.position.y - self.position.y)\n # print(\"System Pos: \" + str(self.system.position.x), str(self.system.position.y), \"Part Pos: \"+str(self.position.x), str(self.position.y))\n \n # angle in radians between center and particle \n self.angle = atan2(self.d.y, self.d.x)\n \n def updatePosition(self):\n \n self.previousPosition = PVector(self.position.x, self.position.x)\n self.position.x += self.velocity.x\n self.position.y += self.velocity.y\n \n self.lastfew.append(self.position)\n if len(self.lastfew)>14:\n self.lastfew.pop(0)\n \n def updateVelocity(self):\n \n self.getDistance()\n # Add xy-components of gravity vector to velocity\n if self.system.gType:\n self.velocity.x += cos(self.angle)*self.system.gravity/self.distance**2\n self.velocity.y += sin(self.angle)*self.system.gravity/self.distance**2\n else:\n self.velocity.x += cos(self.angle)*self.system.gravity*self.distance**2/10000\n self.velocity.y += sin(self.angle)*self.system.gravity*self.distance**2/10000\n # Bounce off of the cursor if particle gets close \n #if self.distance < 10:self.bounce()\n \n def bounce(self):\n self.velocity.x = -self.velocity.x\n self.velocity.y = -self.velocity.y\n \n def trace(self):\n point(self.position.x, self.position.y)\n \nsystems = []\n\ndef setup():\n strokeWeight(1)\n size(WIDTH,HEIGHT)\n background(color(255))\n systems.append(ParticleSystem(G, mouseX,mouseY))\n \n\ndef draw():\n systems[0].move(mouseX, mouseY)\n \ndef keyPressed():\n if keyCode == UP:\n systems[0].addParticle()\n if keyCode == DOWN:\n systems[0].popParticle()\n if keyCode == LEFT:\n systems[0].decreaseGravity()\n if keyCode == RIGHT:\n systems[0].increaseGravity()\n if key == \"c\":\n background(color(255))\n if key == \"d\":\n systems[0].drawType = \"dot\"\n if key == \"l\":\n systems[0].drawType = \"line\"\n if key == \"t\":\n systems[0].trace = not systems[0].trace\n if key == \"g\":\n systems[0].gType = not systems[0].gType\n if key == \"f\":\n systems[0].drawType = \"lastfew\"\n","sub_path":"line art/lineart/lineart.pyde","file_name":"lineart.pyde","file_ext":"pyde","file_size_in_byte":5284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"632763012","text":"from rest_framework.authtoken.models import Token\nfrom main.models import VKUserInformation\n\n__author__ = 'ibrahimyilmaz'\n\nfrom django.contrib.auth.models import User\nfrom rest_framework import authentication\nfrom rest_framework import exceptions\n\n\nclass VKAuthentication(authentication.BaseAuthentication):\n def authenticate(self, request):\n pickify_token = request.META.get('HTTP_PICKIFY_TOKEN')\n access_token = request.META.get('HTTP_VK_ACCESS_TOKEN')\n if not access_token:\n return None\n\n try:\n import vk\n\n vkapi = vk.API(access_token=access_token)\n try:\n vkapi.getServerTime()\n except:\n return None\n query_result = Token.objects.filter(key=pickify_token)\n\n if query_result.count() == 0:\n raise exceptions.AuthenticationFailed('No such user')\n else:\n token = query_result[0]\n query_result = VKUserInformation.objects.filter(user_id=token.user_id)\n if query_result.count() == 0:\n raise exceptions.AuthenticationFailed('No such user')\n else:\n vk_user_information = query_result[0]\n if vk_user_information.vk_access_token != access_token:\n vk_user_information.vk_access_token = access_token\n vk_user_information.save()\n\n user = vk_user_information.user\n except User.DoesNotExist:\n raise exceptions.AuthenticationFailed('No such user')\n\n return (user, None)\n\n\n\n\n\n\n\n","sub_path":"main/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"504086385","text":"from WMCore.Configuration import Configuration\nconfig = Configuration()\n\nconfig.section_(\"General\")\nconfig.General.requestName = 'SingleK0L_step3_RECO_10_4_0_E2_500_v3'\nconfig.General.workArea = 'crab_projects'\n\n#optional\n#config.General.transferOutputs\n#config.General.transferLogs\n#config.General.failureLimit = \n\n#Expert use\n#config.General.instance\n#config.General.activity\n\nconfig.section_(\"JobType\")\nconfig.JobType.pluginName = 'Analysis'\n#config.JobType.psetName = 'step3_RAW2DIGI_L1Reco_RECO_EI_PAT_VALIDATION_DQM.py'\n#config.JobType.psetName = 'step3_RAW2DIGI_L1Reco_RECO_RECOSIM_EI_PAT_VALIDATION_DQM.py'\nconfig.JobType.psetName = 'step3_RAW2DIGI_L1Reco_RECO_RECOSIM_EI_PAT.py'\nconfig.JobType.outputFiles = ['step3.root']\n#config.JobType.eventsPerLumi = 2000\n\nconfig.JobType.maxMemoryMB = 3000\n\nconfig.section_(\"Data\")\n#config.Data.inputDBS = 'https://cmsweb.cern.ch/dbs/prod/phys03/DBSReader/'\n#config.Data.inputDataset = '/SinglePi/hatake-CMSSW_10_4_0_Step2_v1-6cb52d4242603d1fbf0661ab850234de/USER' # \"SinglePi\" PD name is the mistake of the step2 dataset name. This is K0L sample.\n#config.Data.inputDataset = '/Single_Pion_gun_13TeV_pythia8/Fall14DR73-NoPU_MCRUN2_73_V9-v1/GEN-SIM-RAW-RECO'\nconfig.Data.userInputFiles = open('/uscms_data/d2/hatake/PF/CMSSW_10_4_0/src/PFCalibration/PFChargedHadronAnalyzer/test/step2_file_list_SingleK0L.txt').readlines()\nconfig.Data.outputPrimaryDataset = 'SingleK0L'\n#config.Data.splitting = 'Automatic'\n#config.Data.userInputFiles = open('/afs/cern.ch/user/s/spandey/work/public/PF_cal/10_0_2/CMSSW_10_0_2/src/PFCalibration/PFChargedHadronAnalyzer/test/step2_file_list.txt').readlines()\nconfig.Data.ignoreLocality = True\nconfig.Data.splitting = 'FileBased'\nconfig.Data.unitsPerJob = 1\nNJOBS = 5000\n#NJOBS = 20000\nconfig.Data.totalUnits = config.Data.unitsPerJob * NJOBS\n#config.Data.publication = False\n#config.Data.publishDBS = '' default for the moment\n#config.Data.outLFN = '/home/spandey/t3store/PF_PGun'\n#config.Data.outLFNDirBase = '/store/user/spandey/step3/PGun_step3_RECO_1002_2_200_Feb_13/'\nconfig.Data.outLFNDirBase = '/store/group/hcal_upgrade/hatake/step3/SingleK0L_step3_RECO_10_4_0_E2_500_v3/'\n\nconfig.Data.publication = True\nconfig.Data.publishDBS = 'https://cmsweb.cern.ch/dbs/prod/phys03/DBSWriter/' # Parameter Data.publishDbsUrl has been renamed to Data.publishDBS\nconfig.Data.outputDatasetTag = config.General.requestName # <== Check!!!\n\nconfig.section_(\"Site\")\nconfig.Site.storageSite = 'T3_US_FNALLPC'\n#config.Site.blacklist = ['T3_US_UCR', 'T3_US_UMiss']\nconfig.Site.whitelist = ['T2_US_*','T3_US_FNALLPC','T3_US_Baylor']\n\n#config.section_(\"User\")\n#config.section_(\"Debug\")\n","sub_path":"PFChargedHadronAnalyzer/test/crab_step3_RAW2DIGI_L1Reco_RECO_EI_PAT_SingleK0L.py","file_name":"crab_step3_RAW2DIGI_L1Reco_RECO_EI_PAT_SingleK0L.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"272951660","text":"import time\r\nimport socket\r\nimport sys\r\nimport random\r\nimport array\r\nfrom utility import unpacker,injectError,CRCcheck\r\n\r\n#__________________________Establish connection______________________#\r\ns = socket.socket()\r\nhost1 = socket.gethostname()\r\nip = socket.gethostbyname(host1)\r\n\r\nhost = str(ip)\r\n\r\nport = 1234\r\nname = 'Receiver_Station_SAW'\r\n\r\n#Connect to remote ADDR, and then wraps the connection in an SSL channel\r\ns.connect((host,port))\r\n\r\ns.send(name.encode())\r\ns_name = s.recv(1518)\r\ns_name = s_name.decode()\r\n\r\nprint(\"Connected to \",s_name)\r\n\r\n#_____________________________________________________________________#\r\n\r\nf = s.recv(1518)\r\nf = f.decode()\r\nf = int(f)\r\n\r\nn = s.recv(1518)\r\nn = n.decode()\r\nn = int(n)\r\n\r\n\r\nwhile True:\r\n buffer = []\r\n message = []\r\n\r\n polynomial = '1011'\r\n #create a buffer to store data temporarily\r\n for x in range(0,n):\r\n buffer.append('0')\r\n \r\n for j in range(0,n):\r\n time.sleep(1)\r\n temp = s.recv(1518)\r\n temp = unpacker(temp)\r\n buffer[j] = temp\r\n time.sleep(1)\r\n\r\n\r\n i = n\r\n counter = 0\r\n time1 = time.time()\r\n TIMEOUT = 3\r\n switch = 0\r\n while counter < f: \r\n #send ack for correct data frame and nack for incorrect data frame\r\n #0 denotes no error 1 denotes error\r\n #error = random.randint(0,1)\r\n #Check CRC \r\n valid = injectError(buffer[counter % n])\r\n error = CRCcheck(valid,polynomial)\r\n #----> 1 represent error and 0 represent no error <----#\r\n e = str(error)\r\n #send the ack\r\n\r\n #random time delay <-------------------------------------->\r\n a = random.randint(0,4)\r\n time.sleep(a)\r\n print(\"Time: \",a)\r\n #<-------------------------------------------------------->\r\n #if timeout happens nothing is being sent\r\n if a < 3:\r\n s.send(e.encode())\r\n else:\r\n error = 1\r\n \r\n #collect the message from buffer\r\n if a < 3:\r\n if error != 1:\r\n message.append(valid[:-3])\r\n\r\n #as nothing being sent we have to ignore the previous message sent\r\n\r\n if i < f:\r\n switch = 0\r\n else:\r\n switch = 1\r\n #receiver\r\n temp1 = s.recv(1518)\r\n temp1 = unpacker(temp1)\r\n #print(temp1)\r\n #validate remaining ack\r\n if switch == 1:\r\n if error != 1:\r\n counter = counter + 1\r\n else:\r\n buffer[counter % n] = temp1\r\n #print(\"From connection->buffer\",temp1,buffer[counter % n])\r\n\r\n if switch == 0:\r\n #receive the dataframe\r\n if error != 1:\r\n #reorganize the buffer\r\n x = 0\r\n for x in range(0,n-1):\r\n buffer[x] = buffer[x+1]\r\n buffer[n-1] = temp1\r\n i = i + 1\r\n counter = counter + 1\r\n\r\n else:\r\n #correct the values in buffer\r\n buffer[counter % n] = temp1\r\n\r\n #Add the remaining elements in buffer in the message box\r\n '''\r\n\r\n for k in range(0,n):\r\n message.append(buffer[k])\r\n \r\n '''\r\n \r\n \r\n for i in range(0,n):\r\n message[i] = message[i][0:-3]\r\n \r\n s.close()\r\n #print(\"\\nMessage ->\",message)\r\n \r\n break","sub_path":"A2/selective-repeat/receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"618155202","text":"from django.contrib.auth import authenticate, login, logout as django_logout\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom django.contrib.auth.decorators import login_required\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\n\nfrom twython import Twython\nimport uuid\n\n# If you've got your own Profile setup, see the note in the models file\n# about adapting this to your own setup.\nfrom tweetreach.models import TwitterProfile, TweetAnalytics\n\ndef logout(request, redirect_url=settings.LOGOUT_REDIRECT_URL):\n \"\"\"\n Nothing hilariously hidden here, logs a user out. Strip this out if your\n application already has hooks to handle this.\n \"\"\"\n django_logout(request)\n return HttpResponseRedirect(request.build_absolute_uri(redirect_url))\n\ndef begin_auth(request, token):\n \"\"\"\n The view function that initiates the entire handshake.\n For the most part, this is 100% drag and drop.\n \"\"\"\n try:\n request.session['referrer_token'] = token\n # Instantiate Twython with the first leg of our trip.\n twitter = Twython(\n twitter_token = settings.TWITTER_KEY,\n twitter_secret = settings.TWITTER_SECRET,\n callback_url = request.build_absolute_uri(reverse('tweetreach.views.thanks')),\n )\n\n # Request an authorization url to send the user to...\n auth_props = twitter.get_authentication_tokens()\n\n # Then send them over there, durh.\n request.session['request_token'] = auth_props\n return HttpResponseRedirect(auth_props['auth_url'])\n except:\n return HttpResponseRedirect(reverse('twitter_exception'))\n\n\n\ndef thanks(request, redirect_url=settings.LOGIN_REDIRECT_URL):\n \"\"\"\n A user gets redirected here after hitting Twitter and authorizing your\n app to use their data.\n This is the view that stores the tokens you want\n for querying data. Pay attention to this.\n ***\n \"\"\"\n # Now that we've got the magic tokens back from Twitter, we need to exchange\n # for permanent ones and store them...\n twitter = Twython(\n twitter_token = settings.TWITTER_KEY,\n twitter_secret = settings.TWITTER_SECRET,\n oauth_token = request.session['request_token']['oauth_token'],\n oauth_token_secret = request.session['request_token']['oauth_token_secret'],\n )\n\n # Retrieve the tokens we want...\n authorized_tokens = twitter.get_authorized_tokens()\n\n # If they already exist, grab them, login and redirect to a page displaying stuff.\n try:\n user = User.objects.get(username = authorized_tokens['screen_name'])\n user.set_password(authorized_tokens['oauth_token_secret'])\n user.save()\n except User.DoesNotExist:\n # We mock a creation here; no email, password is just the token, etc.\n user = User.objects.create_user(authorized_tokens['screen_name'],\n \"fjdsfn@jfndjfn.com\",\n authorized_tokens['oauth_token_secret'])\n profile = TwitterProfile()\n profile.user = user\n profile.oauth_token = authorized_tokens['oauth_token']\n profile.oauth_secret = authorized_tokens['oauth_token_secret']\n profile.user_token = uuid.uuid1()\n profile.save()\n\n user = authenticate(\n username = authorized_tokens['screen_name'],\n password = authorized_tokens['oauth_token_secret']\n )\n login(request, user)\n return HttpResponseRedirect(redirect_url)\n\ndef tweet_log(request):\n token = request.session['referrer_token']\n if token == 'direct':\n return \n if TweetAnalytics.objects.filter\\\n (logged_in_account = request.user.username).exists():\n return\n referrer = TwitterProfile.objects.get(user_token = token)\n if request.META.has_key('HTTP_REFERER'):\n referrer_url = request.META[\"HTTP_REFERER\"]\n ip = request.META[\"REMOTE_ADDR\"]\n if referrer.user.username == request.user.username :\n return \n else:\n ta = TweetAnalytics(referrer = referrer,\n referrer_url = referrer_url,\n ip = ip,\n logged_in_account = request.user.username)\n ta.save()\n return\n\ndef dashboard(request):\n if not request.user.is_authenticated():\n return HttpResponseRedirect('/tweetreach/l/direct/')\n else:\n try:\n tweet_log(request)\n return HttpResponse(\"Logged successfully\")\n except:\n return HttpResponseRedirect(reverse('twitter_exception'))\n\ndef twitter_exception(request):\n return HttpResponse(\"some error has happened\")\n","sub_path":"tweetreach/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"79126298","text":"def CalcQval(df_in, decoy_col='Decoy', score_col='Score', better_score='higher'):\r\n if better_score == 'higher':\r\n sort_ascending = False\r\n elif better_score == 'lower':\r\n sort_ascending = True\r\n\r\n df = df_in.sort_values(score_col, ascending=sort_ascending)\r\n df['Decoy CumSum'] = df[decoy_col].cumsum()\r\n df['Target CumSum'] = (~df[decoy_col]).cumsum()\r\n df['Qval'] = df['Decoy CumSum'] / df['Target CumSum']\r\n\r\n return df['Qval'].sort_index()\r\n","sub_path":"calculate_qvalue.py","file_name":"calculate_qvalue.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"499171187","text":"from flask_security import current_user\nfrom flask_admin import BaseView, expose\nfrom flask_admin.contrib import sqla\nfrom flask import request, abort\nfrom Module import *\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.exc import InvalidRequestError\nimport random\nimport psycopg2\nimport datetime\nimport requests\nimport base64\nimport json\n\ndef uniqueID(len):\n letter = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n uniqueCode = \"\"\n for x in range(0,len):\n uniqueCode += letter[random.randrange(0,35)] \n return uniqueCode\n\ndef getSubject(id):\n subject = db.session.query(SubjectBacII).filter_by(id = id).first()\n subject_en = None\n subject_kh = None\n if subject != None:\n subject_en = subject.name_en\n subject_kh = subject.name_kh\n return (subject_en, subject_kh)\n\n\ndef postImage(image_patch):\n API_ENDPOINT = \"https://api.imgbb.com/1/upload\"\n API_KEY = \"4eea31e0d34fbec76e316d7cc9004ee9\"\n # with open(image_patch, \"rb\") as imageFile:\n # str_pic = base64.b64encode(imageFile.read())\n # image = str_pic\n image = image_patch.read()\n data = {\n 'key':API_KEY,\n 'image':image\n }\n r = requests.post(url = API_ENDPOINT, data = data)\n pastebin_url = r.text\n pastebin_url = json.loads(pastebin_url)\n return pastebin_url\n\n\n\n# Create customized model view class\nclass MyModelView(sqla.ModelView):\n\n def is_accessible(self):\n if not current_user.is_active or not current_user.is_authenticated:\n return False\n if current_user.has_role('superuser'):\n return True\n return False\n\n def _handle_view(self, name, **kwargs):\n \"\"\"\n Override builtin _handle_view in order to redirect users when a view is not accessible.\n \"\"\"\n if not self.is_accessible():\n if current_user.is_authenticated:\n # permission denied\n abort(403)\n else:\n # login\n return redirect(url_for('security.login', next=request.url))\n \n can_edit = True\n edit_modal = True\n create_modal = True \n can_export = True\n can_view_details = True\n details_modal = True\n\n\nclass UserAdminView(MyModelView):\n column_editable_list = ['email', 'first_name', 'last_name']\n column_searchable_list = column_editable_list\n column_exclude_list = ['password']\n # form_excluded_columns = column_exclude_list\n column_details_exclude_list = column_exclude_list\n column_filters = column_editable_list\n\n\nclass CustomView(BaseView):\n @expose('/')\n def index(self):\n return self.render('admin/custom_index.html')\n\n\nclass UserView(MyModelView):\n column_editable_list = ['profileUrl','displayName']\n column_searchable_list = [\"displayName\"]\n column_filters = column_searchable_list\n\n\nclass SchoolView(BaseView):\n @expose('/', methods=['POST','GET'])\n def index(self):\n print(\"==================\")\n if request.method == \"POST\":\n print(request.form.to_dict())\n _list = list()\n for i in range(1,100):\n _list.append({'row':i,'name_en':'English_en'+str(i),'name_kh':'Khmer'+str(i)})\n return self.render('admin/school_index.html', _list = _list)\n\n\nclass BacII_Post_View(BaseView):\n @expose('/', methods=['POST','GET'])\n def index(self):\n if request.method == \"POST\":\n data = request.form.to_dict()\n # return data\n if data['form_method'] == \"save_subject_bacii\":\n try:\n subject_name_en = data['subject_name_en']\n subject_name_kh = data['subject_name_kh']\n id_code = uniqueID(6)\n subject = SubjectBacII(id=id_code, name_en = subject_name_en, name_kh = subject_name_kh)\n db.session.add(subject)\n db.session.commit()\n except IntegrityError:\n db.session.rollback()\n self.index()\n except InvalidRequestError:\n db.session.rollback() \n self.index()\n except psycopg2.errors.UniqueViolation:\n db.session.rollback()\n self.index()\n if data['form_method'] == \"post_bacii\":\n try:\n owner = db.session.query(User).filter_by(id = \"JDEDIXA3\").first()\n subject = db.session.query(SubjectBacII).filter_by(id = data[\"subject\"]).first()\n print(subject)\n text_content = data[\"text_content\"]\n dateTime = datetime.datetime.now()\n title = data[\"title\"]\n imageurl = data[\"imageurl\"].split(\",\\r\\n\")\n # image = postImage(data[\"imageurl\"])\n # image = postImage(request.files[\"imageurl\"])\n # return str(image)\n # image = image.to_dict()\n # if image.get(\"status\") == 200:\n # imageurl = image.get(\"data\").get(\"image\").get(\"url\")\n # imagethumb = image.get(\"data\").get(\"thumb\").get(\"url\")\n # return image\n # [like, love, haha, wow, sad, angry]\n react = [0,0,0,0,0]\n id_code = uniqueID(10)\n post = BacII_Post(id=id_code, datetime = dateTime, title = title, content = text_content, imageurl = imageurl,react = react,subject = subject,user = owner)\n print(post)\n db.session.add(post)\n db.session.commit()\n except IntegrityError:\n db.session.rollback()\n self.index()\n except InvalidRequestError:\n db.session.rollback() \n self.index()\n except psycopg2.errors.UniqueViolation:\n db.session.rollback()\n self.index()\n if data['form_method'] == \"delete_subject\":\n # try:\n subject = db.session.query(SubjectBacII).filter_by(id = data[\"subject_id\"]).first()\n db.session.delete(subject)\n db.session.commit()\n # except Exception:\n # print(\"Can't Delete\")\n query_post = db.session.query(BacII_Post).order_by(BacII_Post.id.desc()).limit(5)\n post = []\n for x in query_post:\n subject = getSubject(x.subjectBacII)\n subject_en = subject[0]\n subject_kh = subject[1]\n post.append({'id':x.id, 'datetime':x.datetime,\"react\":x.react, 'title':x.title, 'content': x.content, 'imageurl':x.imageurl, \"subject_en\":subject_en, \"subject_kh\":subject_kh, 'owner':x.owner})\n list_subject = list()\n _object = SubjectBacII.query.all()\n for i in _object:\n list_subject.append({'row':i.id,'name_en':i.name_en,'name_kh':i.name_kh})\n return self.render('admin/bacii.html', post = post ,list_subject = list_subject)","sub_path":"View.py","file_name":"View.py","file_ext":"py","file_size_in_byte":7110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"463641292","text":"# -*- coding: utf-8 -*-\n# @File : views.py\n# @Author: Holly\n# @Date : 2019-11-14\nfrom flask import render_template, redirect, request, url_for, flash\nfrom flask_login import login_user, login_required, logout_user, current_user\nfrom flask_mail import Message\n\nfrom App.auth.forms import LoginForm, RegistrationForm\nfrom App.ext import db, mail\nfrom App.model import User\nfrom . import auth\n\n\n@auth.route('/login', methods=['GET', \"POST\"])\ndef login():\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n if user is not None and user.verify_password(form.password.data):\n login_user(user, form.remember_me.data)\n return redirect(request.args.get('next') or url_for('main.index'))\n flash('Invalid username or password.')\n return render_template('auth/login.html', form=form)\n\n\n@auth.route('/register', methods=['GET', \"POST\"])\ndef register():\n form = RegistrationForm()\n if form.validate_on_submit():\n user = User(email=form.email.data, username=form.username.data, password=form.password.data)\n db.session.add(user)\n db.session.commit()\n flash(\"You can login now\")\n return redirect(url_for('auth.login'))\n return render_template('auth/register.html', form=form)\n\n\n@auth.route('/confirm/')\n@login_required\ndef confirm(token):\n if current_user.confirmed:\n return redirect(url_for('main.index'))\n if current_user.confirm(token):\n flash('You have confirmed your account. Thanks!')\n else:\n flash('The confirmation link is invalid or has expired.')\n return redirect(url_for('main.index'))\n\n\ndef send_email(to, subject, template, **kwargs):\n msg = Message('test subject', sender=\"807296831@qq.com\", recipients=[\"li807296831@gmail.com\"])\n msg.body = render_template(template + '.txt', **kwargs)\n msg.html = render_template(template + '.html', **kwargs)\n mail.send(msg)\n\n\n@auth.route('/confirm')\n@login_required\ndef resend_confirmation():\n token = current_user.generate_confirmation_token()\n send_email(current_user.email, \"confirm your account\", 'auth/email/confirm', user=current_user, token=token)\n flash('A new confirmation email has been sent to you by email.')\n return redirect(url_for('main.index'))\n\n\n@auth.route('logout')\n@login_required\ndef logout():\n logout_user()\n flash(\"logout\")\n return redirect(url_for(\"main.index\"))\n\n\n@auth.before_app_request\ndef before_request():\n if current_user.is_authenticated() and not current_user.confirmed and request.endpoint[\n :5] != 'auth.' and request.endpoint != 'static':\n return redirect(url_for('auth.unconfirmed'))\n\n\n@auth.route('/unconfirmed')\ndef unconfirmed():\n if current_user.is_anonymous() or current_user.confirmed:\n return redirect(url_for('main.index'))\n return render_template('auth/unconfirmed.html')\n","sub_path":"first-flask/App/auth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"607800539","text":"import boto3\nimport time\nfrom botocore.exceptions import ClientError\n\nCustomerName = input('Customer Domain Name: ')\n\nec2 = boto3.resource('ec2')\nip = boto3.client('ec2')\ncf = boto3.client('cloudfront')\ns3 = boto3.client('s3')\n\ndef createInstance():\n #create the instance\n instances = ec2.create_instances(\n ImageId='ami-##############',\n MinCount=1,\n MaxCount=1,\n InstanceType='t3.micro',\n KeyName='###########',\n SecurityGroupIds= ['sg-##########'],\n )\n # Get the Instance ID\n for instance in instances:\n print(instance.id, instance.instance_type)\n print('Instance is not running... Please wait')\n instance.wait_until_running(InstanceIds=[instance.id])\n try:\n allocation = ip.allocate_address(Domain='vpc')\n response = ip.associate_address(AllocationId=allocation['AllocationId'], InstanceId=instance.id)\n print(response)\n except ClientError as e:\n print(e)\ncreateInstance()\n\n## Create S3 Bucket\ndef createS3Bucket():\n s3.create_bucket(Bucket=CustomerName, CreateBucketConfiguration={'LocationConstraint': 'us-west-2'})\ncreateS3Bucket()\n\n## Create CloudFront Distribution\ndef createCloudFront():\n cf.create_distribution(DistributionConfig=dict(CallerReference='firstOne',\n DefaultRootObject='index.html',\n Comment=CustomerName + 'Distribution',\n Enabled=True,\n Origins = dict(\n Quantity = 1, \n Items = [dict(\n Id = '1',\n DomainName=CustomerName+'.s3.amazonaws.com',\n S3OriginConfig = dict(OriginAccessIdentity = ''))\n ]),\n DefaultCacheBehavior = dict(\n TargetOriginId = '1',\n ViewerProtocolPolicy= 'redirect-to-https',\n TrustedSigners = dict(Quantity=0, Enabled=False),\n ForwardedValues=dict(\n Cookies = {'Forward':'all'},\n Headers = dict(Quantity=0),\n QueryString=False,\n QueryStringCacheKeys= dict(Quantity=0),\n ),\n MinTTL=1000)\n )\n )\ncreateCloudFront()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"258088366","text":"\n\"\"\"\n Special exception classes for STARS specific error handling.\n\"\"\"\n\nclass StarsException(Exception):\n \"\"\" \n These exceptions (and sub-classes) represent STARS-specific errors \n and provide extra parameters so an appropriate response and log entry can be made.\n \"\"\"\n def __init__(self, who, message, user_message=None):\n \"\"\" \n @param who - who generated this exception? Usually name of module or function\n @param message - the exception text itself\n @param user_message - a message suitable for rendering to user\n \"\"\"\n Exception.__init__(self, message)\n self.who = who\n self.user_message=user_message\n","sub_path":"stars/apps/helpers/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"378964548","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/9/2 14:25\n# @Author : yunfan\n\n'''\nAn image is represented by a 2-D array of integers, each integer representing the pixel value of the image\n(from 0 to 65535).\n\nGiven a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value\nnewColor, \"flood fill\" the image.\n\nTo perform a \"flood fill\", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel\nof the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same\ncolor as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.\n\nAt the end, return the modified image.\n\nExample 1:\nInput:\nimage = [[1,1,1],[1,1,0],[1,0,1]]\nsr = 1, sc = 1, newColor = 2\nOutput: [[2,2,2],[2,2,0],[2,0,1]]\nExplanation:\nFrom the center of the image (with position (sr, sc) = (1, 1)), all pixels connected\nby a path of the same color as the starting pixel are colored with the new color.\nNote the bottom corner is not colored 2, because it is not 4-directionally connected\nto the starting pixel.\nNote:\n\nThe length of image and image[0] will be in the range [1, 50].\nThe given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length.\nThe value of each color in image[i][j] and newColor will be an integer in [0, 65535].\n'''\n\ntx = [0, 0, 1, -1]\nty = [1, -1, 0, 0]\n\n\nclass Solution:\n\n def _dfs(self, image, tag, x, y, newColor):\n if image[x][y] == newColor:\n return\n image[x][y] = newColor\n for i in range(4):\n dx = x + tx[i]\n dy = y + ty[i]\n if dx >= 0 and dx < len(image) and dy >= 0 and dy < len(image[0]) and image[dx][dy] == tag:\n self._dfs(image, tag, dx, dy, newColor)\n\n def floodFill(self, image, sr, sc, newColor):\n \"\"\"\n :type image: List[List[int]]\n :type sr: int\n :type sc: int\n :type newColor: int\n :rtype: List[List[int]]\n \"\"\"\n if len(image) == 0 or len(image) == 0:\n return None\n self._dfs(image, image[sr][sc], sr, sc, newColor)\n return image\n\n\n# if __name__ == '__main__':\n# a = [[1, 1, 1], [1, 1, 0], [1, 0, 1]]\n# print(Solution().floodFill(a, 1, 1, 2))\n","sub_path":"leetcode/src/p733FloodFill/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"582553650","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# Print out all aggregations for the AQerep detailed data and the Airbase/AQerep historic data.\n#\n#\nfrom AirDBConsistency import AirDBConsistency\n#import os\n#import time\n\n# Create DB instance with path containing the data.\n# The folder can be empty. In this case the necessary\n# .zip files are downloaded from the EEA server.\nairdb = AirDBConsistency('../../AirData/')\n\nairdb.countries = ['BG'] # , 'SK', 'CZ', 'DK'] # comment out to use all countries\n\nairdb.pollutants = [1]\n#airdb.pollutants = [1012, 1014, 1015, 1018] # comment out to use major pollutants\n#airdb.pollutants = [5012, 5014, 5015, 5018] # comment out to use major pollutants\n\n\nairdb.downloadCountryZip()\n\n# Analyse AQerep time-series data:\nairdb.analyseAQerep()\n\n# Analyse AQerep aggregations time-series: \n#airdb.analyseAggregations()\n\n\n\n\n\n\n \n\n \n\n\n \n","sub_path":"server/scripts/ConsistencyChecks/consistencyCheck2.py","file_name":"consistencyCheck2.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"268297097","text":"# From M.Hagglund, translated to python by V. Normand\nimport numpy as np\n\n# Maps is a list of 2D ratemaps.\n\ndef spacing_analysis(maps):\n filt = matlab_style_gauss2D((9, 9), 9)\n filt2 = matlab_style_gauss3D((11, 11), 11)\n orig_fs = np.zeros(len(maps))\n win_size = 3\n\n #for i in range(0, len(maps)):\n\n maxx = maps[0].shape[0]\n maxy = maps[0].shape[1]\n winx = round(maxx/win_size)\n winy = round(maxx/win_size)\n\n frame = np.zeros([maxy, maxx])\n\n\ndef matlab_style_gauss2D(shape=(3,3),sigma=0.5):\n \"\"\"\n 2D gaussian mask - should give the same result as MATLAB's\n fspecial('gaussian',[shape],[sigma])\n \"\"\"\n m,n = [(ss-1.)/2. for ss in shape]\n y,x = np.ogrid[-m:m+1,-n:n+1]\n h = np.exp( -(x*x + y*y) / (2.*sigma*sigma) )\n h[ h < np.finfo(h.dtype).eps*h.max() ] = 0\n sumh = h.sum()\n if sumh != 0:\n h /= sumh\n return h\n","sub_path":"Helpers/function_spacing_analysis.py","file_name":"function_spacing_analysis.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"303617091","text":"import datetime\n\nclass Person(object):\n def __init__(self, YearBorn, weight, height, gender, name):\n __dic__ = '''Function to Initlise Person attributes'''\n self.age = datetime.datetime.now().year - YearBorn;\n self.gender = \"male\";\n self.name = name;\n\n self.weight = weight;\n self.height = height;\n self.emotion = None;\n self.foodLog = {};\n\n self.Max_Colories = (\n {(7, \"male\") : 1649, (7, \"female\") : 1530,\n (8, \"male\") : 1745, (8, \"female\") : 1625,\n (9, \"male\") : 1840, (9, \"female\") : 1721,\n (10,\"male\") : 2032, (10,\"female\") : 1936, #...\n (13,\"male\") : 2414, (13,\"female\") : 2223,\n (14,\"male\") : 2629, (14,\"female\") : 2342,\n (15,\"male\") : 2820, (15,\"female\") : 2390,\n (16,\"male\") : 2964, (16,\"female\") : 2414,\n (17,\"male\") : 3083, (17,\"female\") : 2462,\n (18,\"male\") : 3155, (18,\"female\") : 2462\n })[self.age, self.gender]\n self.hunger = self.Max_Colories; \n\n def eat(self, FoodName, calcs, quantity):\n __dic__ = \"Updates the maximum number of calores eaten today\"\n self.hunger -= calcs * quantity;\n self.foodLog[len(self.foodLog)] = (FoodName, calcs, quantity);\n\n def reset(self):\n self.hunger = 0;\n \n\nJared = Person(2000, 45, 172, \"male\", \"Jared\")\n","sub_path":"Python/FoodDiary.py","file_name":"FoodDiary.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"553411882","text":"#--------------------------------------------------------------------------------------\n# Setup: setup PATS, install required modules \n# \n#\n#\n# Author: Henry Wang\n# Created: Aug 08, 2015\n#--------------------------------------------------------------------------------------\nimport sys, os, shutil, site, pip\nfrom setuptools.command import easy_install\n\ndef setup():\n\n print(\"\\nCheck python version ...\")\n if sys.version_info[0] < 3: \n raise Exception(\"PATS must be installed and used under Python 3.x\")\n \n print(\"\\nSetup PATS(Python Auto Test Suite) at '%s' ...\\n\"%(os.path.dirname(os.path.abspath(__file__))))\n #easy_install.main(['nose', 'nose-html', 'ddt', 'selenium', 'pywinauto', 'requests', 'pil'])\n pip.main(['install', 'unittest-xml-reporting']) # https://github.com/xmlrunner/unittest-xml-reporting\n print(\"\")\n pip.main(['install', 'html-testRunner']) # https://github.com/oldani/HtmlTestRunner\n print(\"\")\n pip.main(['install', 'ddt']) # http://ddt.readthedocs.org/\n \n\n \"\"\"\n\tprint \"\\nModify ddt module ...\\n\"\n reload(site)\n import ddt\n dst = os.path.join(os.path.dirname(ddt.__file__), \"ddt.py\")\n src = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"setup\", \"ddt.py\")\n print \"replace: %s\"%dst\n print \"with: %s\"%src\n shutil.copyfile(src, dst)\n\t\"\"\"\n\n print(\"\\nPrepare .pth file ... \\n\")\n fileName = os.path.basename(os.path.normpath(os.path.dirname(os.path.abspath(__file__)))) + \".pth\"\n fileFullName = os.path.join(site.getsitepackages()[1], fileName)\n print(\"... '%s' is created\"%fileFullName)\n file = open(fileFullName, 'w')\n file.write(os.path.dirname(os.path.abspath(__file__)))\n file.close()\n\n\nif __name__ == \"__main__\":\n setup()\n\n\n\n\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"526160319","text":"#from sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import create_engine\nfrom avito_db_entities import Base, Category, Advert\n\n# start the DB engine\nengine = create_engine('sqlite:///avito_adv_old.db', echo=True)\n\nSession = sessionmaker(bind=engine, autocommit=True)\n\n\ndef create_session():\n session = Session()\n return session\n\nBase.metadata.create_all(engine)\n\nif __name__ == '__main__':\n Advert.__table__.drop(engine)\n session.add(Advert(advert_id='1', title='hello', href='_', description='akjfhaskhf'))\n session.commit()\n","sub_path":"not_needed/avito_db.py","file_name":"avito_db.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"479664519","text":"# Given a collection of numbers that might contain duplicates, return all possible unique permutations.\n\n# For example,\n# [1,1,2] have the following unique permutations:\n# [\n# [1,1,2],\n# [1,2,1],\n# [2,1,1]\n# ]\n\nclass Solution(object):\n def permuteUnique(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n ret = [[]] # start with null sequence\n for num in nums:\n new_ret = []\n for seq in ret:\n for i in range(len(seq), -1, -1):\n if i < len(seq) and seq[i] == num:\n break # the other case can be covered by other seq\n new_ret.append(seq[:i]+[num]+seq[i:])\n\n ret = new_ret\n\n return ret","sub_path":"medium/47.py","file_name":"47.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"168793533","text":"import random\nimport pandas as pd\nfrom sklearn.pipeline import Pipeline\nimport pickle\nfrom flask import Flask, request, render_template, jsonify\nimport numpy as np\n\ndef apply_scaling_factor(num):\n \"\"\"Applies a scaling factor to the model's prediction.\n Will need to be recalibrated every month of the season to\n adjust for new data.\"\"\"\n scaling_factor = 1.5\n y_pred_5_percentile = 1.2\n y_scaled = ((num-y_pred_5_percentile) * scaling_factor) +1\n return y_scaled\n\nwith open('avy_danger_prediction2.pkl', 'rb') as f:\n model = pickle.load(f)\napp = Flask(__name__, static_url_path=\"\")\n\n@app.route('/')\ndef index():\n \"\"\"Return the main page.\"\"\"\n return render_template('index.html')\n\n# Index([, 'Temperature (deg F)',\n # 'Wind Speed Minimum (mph)', 'Wind Speed Average (mph)',\n # 'Wind Speed Maximum (mph)', 'Wind Direction (deg.)',\n # 'Total Snow Depth (in)', 'max_1_day_temp', 'min_1_day_temp',\n # 'max_2_day_temp', 'min_2_day_temp', 'max_1_day_snow', 'max_2_day_snow',\n # 'max_3_day_snow', '4800_brooks'],\n # dtype='object')\n \n\n@app.route('/predict', methods=['GET', 'POST'])\ndef predict():\n \"\"\"Return a predicted avalanche danger level through the regression model.\"\"\"\n \n data = request.json\n #prediction = model.predict_proba([data['user_input']])\n #return jsonify({'probability': prediction[0][1]})\n print(data)\n # input_solar_text = data['input_solar_01']\n # print(input_solar_text, type(input_solar_text))\n # input_solar = float(input_solar_text)\n \n input_temp_text = data['input_temp_02']\n input_temp = float(input_temp_text)\n \n input_wind_speed_min_text = data['input_wind_speed_min_03']\n input_wind_speed_min = float(input_wind_speed_min_text)\n\n input_wind_speed_avg_text = data['input_wind_speed_avg_04']\n input_wind_speed_avg = float(input_wind_speed_avg_text)\n\n input_wind_speed_max_text = data['input_wind_speed_max_05']\n input_wind_speed_max = float(input_wind_speed_max_text)\n \n input_wind_direction_text = data['input_wind_direction_06']\n input_wind_direction = float(input_wind_direction_text)\n \n input_snowpack_height_text = data['input_snowpack_height_07']\n input_snowpack_height = float(input_snowpack_height_text)\n \n input_1day_max_temp_text = data['input_1day_max_temp_08']\n input_1day_max_temp = float(input_1day_max_temp_text)\n\n input_1day_min_temp_text = data['input_1day_min_temp_09']\n input_1day_min_temp = float(input_1day_min_temp_text)\n \n input_2day_max_temp_text = data['input_2day_max_temp_10']\n input_2day_max_temp = float(input_2day_max_temp_text)\n \n input_2_day_min_temp_text = data['input_2_day_min_temp_11']\n input_2_day_min_temp = float(input_2_day_min_temp_text)\n \n input_1day_max_snow_text = data['input_1day_max_snow_12']\n input_max_1_day_snow = float(input_1day_max_snow_text)\n \n input_2day_max_snow_text = data['input_2day_max_snow_13']\n input_2day_max_snow = float(input_2day_max_snow_text)\n \n input_3day_max_snow_text = data['input_3day_max_snow_14']\n input_3day_max_snow = float(input_3day_max_snow_text)\n \n input_precip_text = data['input_precip_15']\n input_precip = float(input_precip_text)\n \n arguments = pd.DataFrame([[\n input_temp,\n input_wind_speed_min, input_wind_speed_avg,\n input_wind_speed_max, input_wind_direction,\n input_snowpack_height,input_1day_max_temp,\n input_1day_min_temp, input_2day_max_temp,\n input_2_day_min_temp,input_max_1_day_snow,\n input_2day_max_snow,input_3day_max_snow,\n input_precip]],\n columns = [\n 'Temperature (deg F)',\n 'Wind Speed Minimum (mph)', 'Wind Speed Average (mph)',\n 'Wind Speed Maximum (mph)', 'Wind Direction (deg.)',\n 'Total Snow Depth (in)', 'max_1_day_temp',\n 'min_1_day_temp','max_2_day_temp',\n 'min_2_day_temp', 'max_1_day_snow',\n 'max_2_day_snow','max_3_day_snow',\n '4800_brooks'\n ])\n print(arguments.head())\n \n predicted = model.predict(arguments)[0]\n scaled_prediction = apply_scaling_factor(predicted)\n rounded_scaled_prediction = np.round(scaled_prediction,2)\n \n print(type(rounded_scaled_prediction))\n \n \n print((rounded_scaled_prediction), type(rounded_scaled_prediction))\n\n return jsonify({'Predicted Danger Level': rounded_scaled_prediction})\n","sub_path":"avalanche-predictor/webapp/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"253301418","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 9 21:58:47 2020\r\n\r\n@author: hamis\r\n\"\"\"\r\ndata = []\r\n\r\nfile = open(\"XMASData.txt\", \"r\")\r\n\r\nfor line in file:\r\n data.append(int(line.strip()))\r\n \r\n\r\ndef sumOfTwo(numberList, number):\r\n \r\n for integer1 in numberList:\r\n for integer2 in numberList[1:]:\r\n if integer1 + integer2 == number:\r\n return True\r\n \r\n return False\r\n \r\n\r\ndef inValidNumber(numberList):\r\n \r\n count = 0\r\n result = True\r\n \r\n while result != False:\r\n numericalList = numberList[count:count+25]\r\n targetNumber = numberList[count+25]\r\n if sumOfTwo(numericalList, targetNumber) == False:\r\n return targetNumber\r\n else:\r\n count += 1\r\n \r\n return None\r\n\r\ndef smallestLargest(numbers):\r\n smallest = None\r\n largest = None\r\n \r\n if numbers[0] <= numbers[1]:\r\n smallest = numbers[0]\r\n largest = numbers[1]\r\n else:\r\n smallest = numbers[1]\r\n largest = numbers[0]\r\n \r\n for number in range(2, len(numbers)):\r\n if numbers[number] < smallest:\r\n smallest = numbers[number]\r\n if numbers[number] > largest:\r\n largest = numbers[number]\r\n print(smallest, largest) \r\n return smallest + largest\r\n\r\n \r\ndef contiguousSet(data, number):\r\n \r\n endItem = 1\r\n while endItem != len(data):\r\n for item in range(0, len(data) - endItem):\r\n if sum(data[item:item + endItem + 1]) == number:\r\n print(sum(data[item:item + endItem + 1]))\r\n print(endItem)\r\n print(data[item:item + endItem + 1])\r\n return smallestLargest(data[item:item + endItem + 1])\r\n endItem += 1\r\n \r\n return None\r\n \r\nprint(\"The answer to Part A is:\", inValidNumber(data))\r\nprint(contiguousSet(data, 542529149))\r\n","sub_path":"2020/AoC_2020_Day9.py","file_name":"AoC_2020_Day9.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"203602933","text":"from sys import setrecursionlimit #Allows a change in recursion limit.\n\nsetrecursionlimit(15000) #WARNING This recursion limit is very high. I checked multiple times to make sure my machine and system could handle this\n # and this is about the highest it would go without crashing (I did this on repl.it, so it may be more than my computer could handle\n #on its own. Therefore, if someone happens to want to look at this. It would be a good idea to lower this to a reasonable value otherwise\n #it might crash. You will need to change the code though, because even trying to half the amount of recursion (seen in using two halves\n # down when I call the function, it still needs about a recursion limit of 13000. If lower than that, you will have to change that part\n # of the code a bit to fit. I wanted to do more with that, but I realized going down that road of trying to make less recursion was really\n # just doing it iteratively, which I didn't want. So, that is just some info on that.\n\n#Simply initializing some values I'll need later. 'values' will be the number of ways to get from the original place to the end,\n#cvalue is just an intermediate variable to help with navigating the squares (and the stack I have later)\n#recursiondepth is just used if I am debugging and optimizing how much recursion the program does\n#oldina and oldinb are what I used to keep track of the original input inside the function when it is calling itself with different inputs all the time\n#positionstack is what I use to fully navigate the chess board. I basically use it to push down one path until the end and then pop out of it\n#until I can go down another path.\nvalues = 0\ncvalue = []\nfor i in range(9):\n cvalue.append([])\n for j in range(9):\n cvalue[i].append([])\n cvalue[i][j].append(False)\n cvalue[i][j].append(False)\nrecursiondepth = 0\noldina = 0\noldinb = 0\npositionstack = []\npositionstack.append(0)\n\n#just taking the input and parsing out what I want from the input format\n\ninp = input()\norigcoora = int(inp[1])\norigcoorb = int(inp[3])\ninpa = int(inp[6])\ninpb = int(inp[8])\n\ndef function(a, b):\n global values\n global positionstack\n \n #Basically, I am seeing if I am calling the function a new time or not (because I make positionstack = 0 when I end the function)\n #and then if I am, setting up some stuff and starting the stack, and if not, just adding whatever position on the board I am to the stack\n if positionstack[0] != 0:\n if (positionstack[-1] != [a, b]):\n positionstack.append([a, b])\n elif positionstack[0] == 0:\n values = 0\n global oldina\n global oldinb\n oldina = a\n oldinb = b\n positionstack = []\n positionstack.append([a,b])\n \n global recursiondepth #for debugging purposes\n recursiondepth += 1 #same\n \n if (a==origcoora and b==origcoorb): #Basically, if (as I am solving backwards) the spot on the board is the original starting spot\n values += 1 #Then, add one to values (the number of paths), delete this value I am at on the stack\n positionstack.pop() #and go back to the last value on the stack\n newa = positionstack[-1][0]\n newb = positionstack[-1][1]\n function(newa, newb)\n \n if (a-1) < origcoora:\n cvalue[a][b][0] = True #cvalue is used to see if I have gone down the path (so I don't go down it twice) and this just\n if (b-1) < origcoorb: #tells it to also mark that I have gone down the path if that potential path is outside the bounds of the problem at hand\n cvalue[a][b][1] = True\n if (cvalue[a][b][0] == True): #If going left (again, solving in reverse here) is blocked\n if (cvalue[a][b][1] == False): #and going down isn't\n cvalue[a][b][1] = True #going down is now blocked for the future\n function(a, (b-1)) #go down\n else: #otherwise (if going left and going down are blocked)\n if(a == oldina and b == oldinb):#if the present coordinates are the far right and top coordinate (the spot I am trying to get to (really, I'm coming from there)\n positionstack = [] #so basically, if every pathway is blocked and I am at the farmost coordinate, it has finished\n positionstack.append(0) #so I just reset positionstack so that it can be used again (cause I have to call two halves of the problem so recursion depth isn't a problem)\n return values #and return the number of paths so that I can print it later\n elif(b == inpb and a != inpa): #if going left and going down are blocked, and I am as far up as I can go, but not as far right\n if len(positionstack) == 0 or len(positionstack) == 1: #sometimes I'd get a weird error where it didn't realize it matched, so this just fixed that \n return values\n positionstack.pop() #go back to the previous position (which would be to the right. Don't know why I was forced to create this scenario)\n newa = positionstack[-1][0] #same process I shouldn't have needed, but it fixed errors, so, whatever)\n newb = positionstack[-1][1] #etc.\n cvalue[a][b][0] = False #etc. (This part is just making it so if I encounter this square again, it won't be blocked, because I'll have come from a different square farther up\n cvalue[a][b][1] = False\n function(newa, newb) #you get the point\n else: #otherwise (if going left and down is blocked but we aren't at the top value) (again, didn't know why I needed the previous part, but it worked, so hey)\n cvalue[a][b][0] = False #same as before\n cvalue[a][b][1] = False\n if len(positionstack) == 0 or len(positionstack) == 1:\n return values #same error correction deal here\n positionstack.pop() #same going back to previous position, etc. etc.\n newa = positionstack[-1][0]\n newb = positionstack[-1][1]\n function(newa, newb)\n elif (cvalue[a][b][0] == False): #otherwise, if going left isn't blocked\n cvalue[a][b][0] = True #block going left for this square\n function((a-1), b) #go left on the path\n else: print(\"Error\") #if some other thing happens, error (this has never happened)\n return values #in case the other return values doesn't work (happens sometimes)\n\nprint(function(inpa-1, inpb) +function(inpa, inpb-1)) #basically, just doing the function twice for the two squares around the target square\n #because going from 1,1 to 8,8 required too much recursion, so this splits it up\n #because adding the distance for a-1, b and a, b-1 is the same as going to a,b\n\n \n","sub_path":"ChessProgram.py","file_name":"ChessProgram.py","file_ext":"py","file_size_in_byte":7024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"582963138","text":"from django.contrib import admin\r\nfrom django.urls import path,include\r\nfrom . import views\r\nfrom .views import (\r\n PostsListView,\r\n PostsDetailView,\r\n PostsCreateView,\r\n PostsUpdateView,\r\n PostsDeleteView,\r\n UserPostsListView\r\n\r\n)\r\n\r\nurlpatterns=[\r\n path('',PostsListView.as_view(),name='blog-home'),\r\n path('user//',UserPostsListView.as_view(),name='posts-user'),\r\n path('posts//',PostsDetailView.as_view(),name='posts-detail'),\r\n path('posts//update/',PostsUpdateView.as_view(),name='posts-update'),\r\n path('posts/create/',PostsCreateView.as_view(),name='posts-create'),\r\n path('posts//delete/',PostsDeleteView.as_view(),name='posts-delete'),\r\n path('about/',views.about,name='blog-about'),\r\n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"579227122","text":"\"\"\"Prompt and rename audio files after playing them with VLC.\"\"\"\n# This script is an answer to:\n# https://stackoverflow.com/questions/49643892/batch-file-to-give-the-rename-prompt-in-windows/\n\nimport os\nimport subprocess\n\nCOMMAND = \"/Applications/VLC.app/Contents/MacOS/VLC\"\nARGUMENTS = \"--play-and-exit\"\nDIRECTORY = \"/Users/sci-lmw1/dev/temp/\"\n\nos.chdir(DIRECTORY)\nfor filename in os.listdir('.'):\n # ignore directories, just process files\n if not os.path.isdir(filename):\n subprocess.call([COMMAND, ARGUMENTS, filename])\n new_name = input(\"New name for {}: \".format(filename))\n os.rename(filename, new_name)\n","sub_path":"rename_vlc_audio_files.py","file_name":"rename_vlc_audio_files.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"560188989","text":"from django.conf.urls import patterns, url\nfrom movie_list import views\n\nurlpatterns = patterns('',\n url(r'^all', views.show_all),\n url(r'^search', views.search),\n url(r'^add', views.add_item),\n url(r'^remove', views.remove),\n url(r'^send_message', views.send_message),\n url(r'^$', views.index, name='index'),\n)","sub_path":"movie_watchlist/movie_list/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"179335850","text":"import time\nfrom utils_host import HostSession\nfrom utils_guest import GuestSession\nfrom monitor import RemoteSerialMonitor, RemoteQMPMonitor\nimport re\nfrom vm import CreateTest\nfrom utils_migration import do_migration, change_balloon_val\n\ndef run_case(params):\n src_host_ip = params.get('src_host_ip')\n dst_host_ip = params.get('dst_host_ip')\n qmp_port = int(params.get('qmp_port'))\n serial_port = int(params.get('serial_port'))\n incoming_port = params.get('incoming_port')\n test = CreateTest(case_id='rhel7_10078', params=params)\n id = test.get_id()\n guest_name = test.guest_name\n src_host_session = HostSession(id, params)\n balloon_val = '1073741824'\n chk_timeout = 180\n\n test.main_step_log('1. Boot guest on src host with memory balloon device.')\n params.vm_base_cmd_add('device',\n 'virtio-balloon-pci,id=balloon0,bus=pci.0,addr=0x9')\n src_qemu_cmd = params.create_qemu_cmd()\n src_host_session.boot_guest(cmd=src_qemu_cmd, vm_alias='src')\n\n test.sub_step_log('1.1 Connecting to src serial')\n src_serial = RemoteSerialMonitor(id, params, src_host_ip, serial_port)\n src_guest_ip = src_serial.serial_login()\n\n test.main_step_log('2 Check if memory balloon device works.')\n test.sub_step_log('2.1 Check if balloon device exists')\n src_remote_qmp = RemoteQMPMonitor(id, params, src_host_ip, qmp_port)\n output = src_remote_qmp.qmp_cmd_output('{\"execute\":\"query-balloon\"}')\n original_val = eval(output).get('return').get('actual')\n if re.findall(r'No balloon', output):\n src_remote_qmp.test_error('No balloon device has been activated.')\n\n test.sub_step_log('2.2 Change the value of balloon to %s bytes'\n % balloon_val)\n change_balloon_val(new_value=balloon_val, remote_qmp=src_remote_qmp)\n\n test.sub_step_log('2.3 Restore balloon to original value')\n change_balloon_val(new_value=original_val, remote_qmp=src_remote_qmp)\n\n test.main_step_log('3. Hot unplug this memory balloon from guest.')\n cmd = '{\"execute\":\"device_del\",\"arguments\":{\"id\":\"balloon0\"}}'\n src_remote_qmp.qmp_cmd_output(cmd=cmd, recv_timeout=5)\n\n test.sub_step_log('Check if the balloon is hot unplug successfully')\n cmd = '{\"execute\":\"query-balloon\"}'\n output = src_remote_qmp.qmp_cmd_output(cmd=cmd, recv_timeout=5)\n if re.findall(r'No balloon', output):\n test.test_print(\"Balloon device is hot unplug successfully\")\n\n test.main_step_log('4. Boot guest with \\'-incoming\\' and '\n 'without memory balloon device on des host.')\n params.vm_base_cmd_del('device', 'virtio-balloon-pci,id=balloon0,'\n 'bus=pci.0,addr=0x9')\n incoming_val = 'tcp:0:%s' % incoming_port\n params.vm_base_cmd_add('incoming', incoming_val)\n dst_qemu_cmd = params.create_qemu_cmd()\n src_host_session.boot_remote_guest(cmd=dst_qemu_cmd,\n ip=dst_host_ip, vm_alias='dst')\n dst_remote_qmp = RemoteQMPMonitor(id, params, dst_host_ip, qmp_port)\n output = dst_remote_qmp.qmp_cmd_output('{\"execute\":\"query-balloon\"}',\n recv_timeout=5)\n if re.findall(r'No balloon', output):\n test.test_print(\"Destination guest don't have balloon device\")\n\n test.main_step_log('5. Start live migration, should finish successfully')\n flag = do_migration(remote_qmp=src_remote_qmp,\n migrate_port=incoming_port, dst_ip=dst_host_ip)\n if (flag == False):\n test.test_error('Migration timeout')\n\n test.main_step_log('6. Check guest on des, guest should work well.')\n dst_serial = RemoteSerialMonitor(id, params, dst_host_ip, serial_port)\n test.sub_step_log('Reboot dst guest and get ip of destination guest')\n dst_serial.serial_cmd(cmd='reboot')\n dst_guest_ip = dst_serial.serial_login()\n test.test_print('The ip of destination guest is %s' % dst_guest_ip)\n\n test.main_step_log('7. Hot plug a memory balloon device to '\n 'destination guest.')\n cmd = '{\"execute\":\"device_add\",\"arguments\":{\"driver\":\"virtio-balloon-pci\",' \\\n '\"bus\":\"pci.0\",\"addr\":\"0x9\",\"id\":\"balloon0\"}}'\n dst_remote_qmp.qmp_cmd_output(cmd=cmd, recv_timeout=5)\n output = dst_remote_qmp.qmp_cmd_output('{\"execute\":\"query-balloon\"}',\n recv_timeout=5)\n if re.findall(r'No balloon', output):\n dst_remote_qmp.test_error('Failed to hotplug balloon device')\n\n test.main_step_log('8. Repeat step2')\n change_balloon_val(new_value=balloon_val, remote_qmp=dst_remote_qmp)\n change_balloon_val(new_value=original_val, remote_qmp=dst_remote_qmp)\n\n test.main_step_log('9. Quit qemu on src host. Then boot guest with '\n '\\'-incoming\\' on src host')\n output = src_remote_qmp.qmp_cmd_output('{\"execute\":\"quit\"}')\n if output:\n test.test_error('Failed to quit qemu on src host')\n src_host_session.check_guest_process(src_ip=src_host_ip)\n params.vm_base_cmd_add('device', 'virtio-balloon-pci,id=balloon0,'\n 'bus=pci.0,addr=0x9')\n src_qemu_cmd = params.create_qemu_cmd()\n src_host_session.boot_guest(cmd=src_qemu_cmd, vm_alias='src')\n src_remote_qmp = RemoteQMPMonitor(id, params, src_host_ip, qmp_port)\n output = src_remote_qmp.qmp_cmd_output('{\"execute\":\"query-balloon\"}')\n if re.findall(r'No balloon', output):\n src_remote_qmp.test_error('src host do not has balloon device')\n\n test.main_step_log('10. Do migration from dst to src')\n flag = do_migration(remote_qmp=dst_remote_qmp,\n migrate_port=incoming_port, dst_ip=src_host_ip)\n if (flag == False):\n test.test_error('Migration timeout')\n\n test.main_step_log('11&12. Check guest on src, reboot, '\n 'ping external host,and shutdown.')\n test.sub_step_log('11.1 Reboot src guest')\n src_serial = RemoteSerialMonitor(id, params, src_host_ip, serial_port)\n src_remote_qmp.qmp_cmd_output('{\"execute\":\"system_reset\"}')\n src_guest_ip = src_serial.serial_login()\n\n test.sub_step_log('11.2 Ping external host and shutdown guest')\n src_guest_session = GuestSession(case_id=id, params=params, ip=src_guest_ip)\n src_guest_session.guest_ping_test('www.redhat.com', 10)\n\n test.sub_step_log('11.3 quit qemu on dst end and shutdown vm on src end')\n src_serial.serial_shutdown_vm()\n\n output = dst_remote_qmp.qmp_cmd_output('{\"execute\":\"quit\"}')\n if output:\n dst_remote_qmp.test_error('Failed to quit qemu on dst host')\n","sub_path":"virtkvmqe/migration_test_plan/migration/test_scenarios/rhel7_10078.py","file_name":"rhel7_10078.py","file_ext":"py","file_size_in_byte":6603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"277883129","text":"import sys\n\ndef main(prefix):\n infile = open(prefix + '.lammpstrj',\"r\")\n # Output position\n outfile = open(prefix+\"-last.lammpstrj\",\"w\")\n numStruct = 0\n i = 0\n start = []\n for line in infile:\n if line.strip() == 'ITEM: TIMESTEP':\n numStruct += 1\n start.append(i)\n i += 1\n infile2 = open(prefix + '.lammpstrj',\"r\")\n j = 0\n for line in infile2:\n if j == start[len(start)-1]:\n outfile.write(line)\n if j == start[len(start)-1] + 1:\n outfile.write(str(0) + '\\n') \n if j >= start[len(start)-1] + 2:\n outfile.write(line)\n j += 1\n\nif __name__ == '__main__':\n main(sys.argv[1])\n","sub_path":"npt-md/final-struct.py","file_name":"final-struct.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"30641263","text":"\"\"\" Sale model class represents methods for creation and retrieval from non-persistent databases of sale records.\"\"\"\n\n\nclass Sale:\n def __init__(self):\n self.sales = []\n self.sale_id = 0\n self.result = []\n\n \"\"\" Create a new sale record.\"\"\"\n\n def create_new_sale_record(self, product_data):\n name = (product_data['name']).strip()\n category = (product_data['category']).strip()\n price = product_data['price']\n quantity = product_data['quantity']\n username = 'mags'\n\n self.sale_id = self.sale_id + 1\n total = price * quantity\n new_sales_record = {\n \"id\": self.sale_id,\n \"product_name\": name,\n \"price\": price,\n \"category\": category,\n \"quantity\": quantity,\n \"total_amount\": total,\n \"created_by\": username\n }\n self.sales.append(new_sales_record)\n return new_sales_record\n\n \"\"\" Return all sale records available\"\"\"\n\n def all_sales(self):\n if len(self.sales) > 0:\n return self.sales\n\n def all_sales_by_user(self, username):\n pass\n\n \"\"\" Get a specific sale record given its ID.\"\"\"\n\n def get_single_sale(self, _id):\n for sale_record in self.sales:\n if sale_record['id'] == _id:\n return sale_record\n # if len(self.result) > 0:\n # \treturn self.result\n","sub_path":"app/models/sales.py","file_name":"sales.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"374450607","text":"from dbDataStructures import *\r\nfrom databaseInit import *\r\nfrom inventoryFunctions import *\r\nfrom orderingFunctions import *\r\nimport code\r\n\r\nbrownRice = RiceType(0, \"brown\")\r\nbrownRice.id = addRiceType(brownRice)\r\n\r\nwhiteRice = RiceType(1, \"white\")\r\nwhiteRice.id = addRiceType(whiteRice)\r\n\r\nsweetNSour = SauceType(0, \"sweet n sour\")\r\nsweetNSour.id = addSauceType(sweetNSour)\r\n\r\nteriyaki = SauceType(1, \"teriyaki\")\r\nteriyaki.id = addSauceType(teriyaki)\r\n\r\nmozziSticks = AppetizerType(0, \"mozzi sticks\")\r\nmozziSticks.id = addAppetizerType(mozziSticks)\r\n\r\nonionRings = AppetizerType(0, \"onion rings\")\r\nonionRings.id = addAppetizerType(onionRings)\r\n\r\nchicken = IngredientType(0, \"chicken\")\r\nchicken.id = addIngredientType(chicken)\r\n\r\ntofu = IngredientType(0, \"tofu\")\r\ntofu.id = addIngredientType(tofu)","sub_path":"officialProj/Project/initDatabaseForDebug.py","file_name":"initDatabaseForDebug.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"61112199","text":"import os, os.path\n\ndef get_filenames(rootdir):\n results=[]\n\n for root, subFolders, filenames in os.walk(rootdir):\n for filename in filenames:\n path=os.path.join(root, filename)\n results.append(path)\n return results \n\nblacklist=[\"blend\",\"mtl\",\"meta\",\"obj\",\"mat\",\"bin\",\"dll\",\"info\",\"blend1\",\"blend2\",\"tga\"]\nfor path in get_filenames(\"Assets/Meshes\"):\n black=0\n for b in blacklist:\n if path.endswith(b):\n black=1\n break\n if black:\n continue\n print(path)\n","sub_path":"python-scripts/crawl_files.py","file_name":"crawl_files.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"467177969","text":"import unittest, time\n\nfrom genr import genr\n\nclass TestBasics(unittest.TestCase):\n \n @genr\n def small_wait(self):\n time.sleep(0.1)\n\n def test_simple_run(self):\n future = self.small_wait()\n self.assertTrue(future.running())\n time.sleep(0.2)\n self.assertTrue(future.done())\n \n def test_inline_wrap(self):\n future = genr(time.sleep)(0.1)\n self.assertTrue(future.running())\n time.sleep(0.2)\n self.assertTrue(future.done())\n \n @genr\n def generator1(self):\n yield\n \n def test_generator_run(self):\n future = self.generator1()\n self.assertTrue(future.done())\n \n @genr\n def simple_return(self):\n return 'value'\n \n def test_return_value(self):\n self.assertTrue(\n self.simple_return().result() == 'value')\n \n @genr\n def yield_aggregates(self, aggr_type=None):\n if aggr_type is not None:\n tasks = [self.simple_return() for i in range(3)]\n result = yield aggr_type(tasks)\n else:\n result = yield self.simple_return()\n return result\n \n def test_yield_values(self):\n self.assertTrue(self.yield_aggregates().result() == 'value')\n for aggr_type in (tuple, list, set):\n values = self.yield_aggregates(aggr_type).result()\n self.assertTrue(type(values) == aggr_type)\n self.assertTrue(len(values) == 3 or (aggr_type == set and len(values) == 1))\n self.assertTrue('value' in values)\n \n @genr\n def delayed_yield(self):\n future = self.simple_return()\n yield\n value = yield future\n return value\n \n def test_delayed_yield(self):\n self.assertTrue(self.delayed_yield().result() == 'value')\n \n @genr\n def yield_something_else(self):\n value = yield 'value'\n return value\n \n def test_yield_something_else(self):\n self.assertTrue(self.yield_something_else().result() == 'value')\n \n @genr\n def generator2(self):\n checks = []\n t1 = genr(time.sleep)(0.1)\n t2 = genr(time.sleep)(0.2)\n checks.append(not t1.done())\n checks.append(not t2.done())\n yield\n checks.append(t1.done())\n checks.append(t2.done())\n return checks\n \n def test_yield_as_a_collection_point(self):\n checks = self.generator2()\n self.assertTrue(all(checks.result()))\n\n @genr\n def generator3(self):\n checks = []\n futures = []\n t1 = genr(time.sleep)(0.1)\n yield\n t2 = genr(time.sleep)(0.1)\n t3 = genr(time.sleep)(0.2)\n checks.append(not t2.done())\n checks.append(not t3.done())\n futures.append(t2)\n futures.append(t3)\n return checks, futures\n\n def test_return_as_a_collection_point(self):\n future = self.generator3()\n checks, futures = future.result()\n self.assertTrue(all(checks))\n for f in futures:\n self.assertTrue(f.done())\n\n \nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"441490262","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport os\nimport numpy as np\nfrom collections import OrderedDict\n\n\nclass POSCAR():\n def __init__(self, path='./POSCAR'):\n self.path = path\n self.parameters = OrderedDict()\n\n f = open(self.path, 'r')\n self.lines = f.readlines()\n f.close()\n\n def addParameters(self, key, value):\n self.parameters[key] = value\n if 'Matrix' in key:\n print(str(key) + ':\\n' + str(self.parameters[key]))\n else:\n print(str(key) + ':' + str(self.parameters[key]))\n\n def getSystemName(self):\n SystemName = str(self.lines[0].strip())\n self.addParameters(key='SystemName', value=SystemName)\n return SystemName\n\n def getScalingFactor(self):\n ScalingFactor = np.array(str(self.lines[1]).strip().split()).astype(np.float)[0]\n self.addParameters(key='ScalingFactor', value=ScalingFactor)\n return ScalingFactor\n\n def getLatticeMatrix(self):\n a = np.array(str(self.lines[2]).strip().split()).astype(np.float)\n b = np.array(str(self.lines[3]).strip().split()).astype(np.float)\n c = np.array(str(self.lines[4]).strip().split()).astype(np.float)\n LatticeMatrix = np.array([a, b, c])\n self.addParameters(key='LatticeMatrix', value=LatticeMatrix)\n\n def getAtomsInfo(self):\n AtomsInfo = OrderedDict()\n AtomsKeys = self.lines[5].strip().split()\n AtomsNumber = self.lines[6].strip().split()\n for i in range(len(AtomsKeys)):\n AtomsInfo[AtomsKeys[i]] = int(AtomsNumber[i])\n self.addParameters(key='AtomsInfo', value=AtomsInfo)\n return AtomsInfo\n\n def getCoordinateType(self):\n CoordinateType = str(self.lines[7].strip())\n self.addParameters(key='CoordinateType', value=CoordinateType)\n return CoordinateType\n\n def getAtomsPositionMatrix(self):\n AtomsSum = self.calAtomsSum()\n AtomsPositionMatrix = np.zeros((AtomsSum, 3))\n for i in range(AtomsSum):\n AtomsPositionMatrix[i] = np.array(\n str(self.lines[i + 8]).strip().split()).astype(np.float)\n self.addParameters(key='AtomsPositionMatrix',\n value=AtomsPositionMatrix)\n return AtomsPositionMatrix\n\n def calAtomsSum(self):\n AtomsInfo = self.getAtomsInfo()\n AtomsSum = 0\n for value in AtomsInfo.values():\n AtomsSum += value\n self.addParameters(key='AtomsSum', value=AtomsSum)\n return AtomsSum\n\n def calVolume(self):\n \"\"\"\n Get unit cell volume\n \"\"\"\n sf = self.getScalingFactor()\n a = np.array(str(self.lines[2]).strip().split()).astype(np.float) * sf\n b = np.array(str(self.lines[3]).strip().split()).astype(np.float) * sf\n c = np.array(str(self.lines[4]).strip().split()).astype(np.float) * sf\n Volume = np.dot(np.cross(a, b), c)\n self.addParameters(key='Volume', value=Volume)\n return Volume\n\n def calElementsPositionMatrix(self):\n AtomsInfo = self.getAtomsInfo()\n AtomsPositionMatrix = self.getAtomsPositionMatrix()\n\n ElementsPositionMatrix = OrderedDict()\n count = 0\n for key, value in AtomsInfo.items():\n ElementsPositionMatrix[key] = np.zeros((value, 3))\n for i in range(value):\n ElementsPositionMatrix[key][i] = AtomsPositionMatrix[i + count]\n count += value\n self.addParameters(key='ElementsPositionMatrix',\n value=ElementsPositionMatrix)\n return ElementsPositionMatrix\n\n def main(self):\n self.getSystemName() # 获取体系名称\n self.getScalingFactor() # 获取缩放系数\n self.getLatticeMatrix() # 获取晶格参数矩阵\n self.getAtomsInfo() # 获取原子(数量)信息\n self.getCoordinateType() # 获取坐标类型\n self.getAtomsPositionMatrix() # 获取原子位置矩阵\n\n self.calAtomsSum() # 计算原子总数\n self.calVolume() # 计算晶体面积\n self.calElementsPositionMatrix() # 获取每种元素的位置矩阵\n\n os.system('clear') # 注释掉此行可以方便脚本检查\n for key, value in self.parameters.items():\n if 'Matrix' in key:\n print(str(key) + ':\\n' + str(value))\n else:\n print(str(key) + ':' + str(value))\n\n return self.parameters\n\n\nif __name__ == \"__main__\":\n p = POSCAR(path='./SnO2.vasp')\n PoscarParameters = p.main() # 获得所需的参数\n","sub_path":"createTWIN/ReadPOSCAR.py","file_name":"ReadPOSCAR.py","file_ext":"py","file_size_in_byte":4575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"390795279","text":"import discord #Imports required modules\nimport base64\nimport parsingengine\n\ntoken = (\"YOUR-TOKEN-HERE\") # Connects to your bot\nans = 0\nseperator = ' '\n## Bot setup\n\nclient = discord.Client() # Creates the bot client\n\n@client.event\nasync def on_ready(): # When bot is ready, prints out bot name.\n print('Logged in as {0.user}'.format(client))\n\n\n@client.event\nasync def on_message(message): # When a message is sent in the discord server,\n if message.content.startswith('/calc'): # If it begins with /calc\n calculation = message.content\n calculation = calculation.split(' ')\n calculation = calculation[1:len(calculation)] # Finds all of the message that isnt /calc\n calculation = seperator.join(calculation)\n ans = parsingengine.parsingengine(calculation) # Calculates it\n await message.channel.send(ans) # Outputs answer\n\n\nclient.run(token) # Runs bot","sub_path":"Other/Calculator/Discord Bot with Calculator Intergration/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"87173942","text":"def solution(new_id):\n answer = new_id\n answer = stepOne(answer)\n answer = stepTwo(answer)\n answer = stepThree(answer)\n answer = stepFour(answer)\n answer = stepFive(answer)\n answer = stepSix(answer)\n answer = stepSeven(answer)\n return answer\ndef stepOne(new_id):\n return new_id.lower()\ndef stepTwo(new_id):\n tmp = list(new_id)\n result = ''\n for i in range(len(tmp)):\n ascii = ord(tmp[i])\n if (ascii <123 and ascii>96) or (ascii>47 and ascii<58) or ascii==45 or ascii==46 or ascii==95:\n result = result + tmp[i]\n return result\ndef stepThree(new_id):\n tmp = new_id\n changed = 1\n while(changed == 1):\n changed = 0\n if tmp.find('..') != -1:\n tmp.replace('..', '.')\n changed = 1\n return tmp\ndef stepFour(new_id):\n tmp = new_id\n tmp = tmp.strip('.')\n return tmp\ndef stepFive(new_id):\n tmp = new_id\n if tmp == '':\n tmp = 'a'\n return tmp\ndef stepSix(new_id):\n tmp = new_id\n tmp = tmp[0:15]\n tmp = stepFour(tmp)\n return tmp\ndef stepSeven(new_id):\n tmp = list(new_id)\n while(len(tmp) < 3):\n tmp.append(tmp[-1])\n return \"\".join(tmp)\nif __name__ == \"__main__\":\n result = solution(\"bat.y.abcdefghi\")\n print(result)","sub_path":"3. 컴공선배/8주차/프로그래머스/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"615203823","text":"import glfw\nfrom OpenGL.GL import *\nfrom OpenGL.GL.shaders import compileProgram, compileShader\nimport pyrr\nfrom TextureLoader import load_texture\nfrom ObjLoader import ObjLoader\n\nfrom camera import Camera\n\ncam = Camera()\nWIDTH, HEIGHT = 1280, 720\nlastX, lastY = WIDTH / 2, HEIGHT / 2\nfirst_mouse = True\nleft, right, forward, backward = False, False, False, False\n\n\n# the keyboard input callback\ndef key_input_clb(window, key, scancode, action, mode):\n global left, right, forward, backward\n if key == glfw.KEY_ESCAPE and action == glfw.PRESS:\n glfw.set_window_should_close(window, True)\n\n if key == glfw.KEY_W and action == glfw.PRESS:\n forward = True\n elif key == glfw.KEY_W and action == glfw.RELEASE:\n forward = False\n if key == glfw.KEY_S and action == glfw.PRESS:\n backward = True\n elif key == glfw.KEY_S and action == glfw.RELEASE:\n backward = False\n if key == glfw.KEY_A and action == glfw.PRESS:\n left = True\n elif key == glfw.KEY_A and action == glfw.RELEASE:\n left = False\n if key == glfw.KEY_D and action == glfw.PRESS:\n right = True\n elif key == glfw.KEY_D and action == glfw.RELEASE:\n right = False\n # if key in [glfw.KEY_W, glfw.KEY_S, glfw.KEY_D, glfw.KEY_A] and action == glfw.RELEASE:\n # left, right, forward, backward = False, False, False, False\n\n\n# do the movement, call this function in the main loop\ndef do_movement():\n if left:\n cam.process_keyboard(\"LEFT\", 0.05)\n if right:\n cam.process_keyboard(\"RIGHT\", 0.05)\n if forward:\n cam.process_keyboard(\"FORWARD\", 0.05)\n if backward:\n cam.process_keyboard(\"BACKWARD\", 0.05)\n\n\n# the mouse position callback function\ndef mouse_look_clb(window, xpos, ypos):\n global first_mouse, lastX, lastY\n\n if first_mouse:\n lastX = xpos\n lastY = ypos\n first_mouse = False\n\n xoffset = xpos - lastX\n yoffset = lastY - ypos\n\n lastX = xpos\n lastY = ypos\n\n cam.process_mouse_movement(xoffset, yoffset)\n\n\nvertex_src = \"\"\"\n# version 330\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec2 a_texture;\nlayout(location = 2) in vec3 a_normal;\n\nuniform mat4 model;\nuniform mat4 projection;\nuniform mat4 view;\n\nuniform mat4 light;\n\nout vec3 fragNormal;\nout vec2 v_texture;\n\nvoid main()\n{\n fragNormal=(light*vec4(a_normal,0.0f)).xyz;\n gl_Position = projection * view * model * vec4(a_position, 1.0);\n v_texture = a_texture;\n}\n\"\"\"\n\nfragment_src = \"\"\"\n# version 330\n\nin vec2 v_texture;\nin vec3 fragNormal;\n\nout vec4 out_color;\n\nuniform sampler2D s_texture;\n\nvoid main()\n{\n vec3 ambientLightIntensity = vec3(0.3f, 0.2f, 0.4f);\n vec3 sunLightIntensity = vec3(3.0f, 3.0f, 3.0f);\n vec3 sunLightDirection = normalize(vec3(10.0f, 5.0f, 2.0f));\n\n vec4 texel = texture(s_texture, v_texture);\n vec3 lightIntensity = ambientLightIntensity + sunLightIntensity * max(dot(fragNormal, sunLightDirection),0.0f);\n\n out_color = vec4(texel.rgb * lightIntensity, texel.a);\n}\n\"\"\"\n\n\n# the window resize callback function\ndef window_resize_clb(window, width, height):\n glViewport(0, 0, width, height)\n projection = pyrr.matrix44.create_perspective_projection_matrix(45, width / height, 0.1, 100)\n glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)\n\n\n# initializing glfw library\nif not glfw.init():\n raise Exception(\"glfw can not be initialized!\")\n\n# creating the window\nwindow = glfw.create_window(WIDTH, HEIGHT, \"My OpenGL window\", None, None)\n\n# check if window was created\nif not window:\n glfw.terminate()\n raise Exception(\"glfw window can not be created!\")\n\n# set window's position\nglfw.set_window_pos(window, 20, 20)\n\n# set the callback function for window resize\nglfw.set_window_size_callback(window, window_resize_clb)\n# set the mouse position callback\nglfw.set_cursor_pos_callback(window, mouse_look_clb)\n# set the keyboard input callback\nglfw.set_key_callback(window, key_input_clb)\n# capture the mouse cursor\nglfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)\n\n# make the context current\nglfw.make_context_current(window)\n\n# load here the 3d meshes\ncube_indices, cube_buffer = ObjLoader.load_model(\"meshes/chair.obj\")\nfloor_indices, floor_buffer = ObjLoader.load_model(\"meshes/floor.obj\")\nmonkey_indices, monkey_buffer = ObjLoader.load_model(\"meshes/monkey.obj\")\n\n\nshader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER))\n\n# VAO and VBO\nVAO = glGenVertexArrays(3)\nVBO = glGenBuffers(3)\n\n# DiningTable VAO\nglBindVertexArray(VAO[0])\n# DiningTable Vertex Buffer Object\nglBindBuffer(GL_ARRAY_BUFFER, VBO[0])\nglBufferData(GL_ARRAY_BUFFER, cube_buffer.nbytes, cube_buffer, GL_STATIC_DRAW)\n\n# DiningTable vertices\nglEnableVertexAttribArray(0)\nglVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8, ctypes.c_void_p(0))\n# DiningTable textures\nglEnableVertexAttribArray(1)\nglVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8, ctypes.c_void_p(12))\n# DiningTable normals\nglVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8, ctypes.c_void_p(20))\nglEnableVertexAttribArray(2)\n# floor VAO\nglBindVertexArray(VAO[1])\n# floor Vertex Buffer Object\nglBindBuffer(GL_ARRAY_BUFFER, VBO[1])\nglBufferData(GL_ARRAY_BUFFER, floor_buffer.nbytes, floor_buffer, GL_STATIC_DRAW)\n\n# floor vertices\nglEnableVertexAttribArray(0)\nglVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, floor_buffer.itemsize * 8, ctypes.c_void_p(0))\n# floor textures\nglEnableVertexAttribArray(1)\nglVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, floor_buffer.itemsize * 8, ctypes.c_void_p(12))\n# floor normals\nglVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, floor_buffer.itemsize * 8, ctypes.c_void_p(20))\nglEnableVertexAttribArray(2)\n\n# monkey VAO\nglBindVertexArray(VAO[2])\n# monkey Vertex Buffer Object\nglBindBuffer(GL_ARRAY_BUFFER, VBO[2])\nglBufferData(GL_ARRAY_BUFFER, monkey_buffer.nbytes, monkey_buffer, GL_STATIC_DRAW)\n\n# monkey vertices\nglEnableVertexAttribArray(0)\nglVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, monkey_buffer.itemsize * 8, ctypes.c_void_p(0))\n# monkey textures\nglEnableVertexAttribArray(1)\nglVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, monkey_buffer.itemsize * 8, ctypes.c_void_p(12))\n# monkey normals\nglVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, monkey_buffer.itemsize * 8, ctypes.c_void_p(20))\nglEnableVertexAttribArray(2)\n\ntextures = glGenTextures(3)\nload_texture(\"meshes/chair.jpg\", textures[0])\nload_texture(\"meshes/floor.jpg\", textures[1])\nload_texture(\"meshes/monkey.jpg\", textures[2])\n\n\n\nglUseProgram(shader)\nglClearColor(0.4, 0.1, 0.1, 1)\nglEnable(GL_DEPTH_TEST)\nglEnable(GL_BLEND)\nglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)\n\nprojection = pyrr.matrix44.create_perspective_projection_matrix(45, WIDTH / HEIGHT, 0.1, 100)\ncube_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([6, 4, 0]))\n\nmodel_loc = glGetUniformLocation(shader, \"model\")\nproj_loc = glGetUniformLocation(shader, \"projection\")\nview_loc = glGetUniformLocation(shader, \"view\")\nlight_loc = glGetUniformLocation(shader, \"light\")\n\nglUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)\n\n# the main application loop\nwhile not glfw.window_should_close(window):\n glfw.poll_events()\n do_movement()\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\n view = cam.get_view_matrix()\n glUniformMatrix4fv(view_loc, 1, GL_FALSE, view)\n\n rot_y = pyrr.Matrix44.from_y_rotation(0.8)\n model = pyrr.matrix44.multiply(rot_y, cube_pos)\n glUniformMatrix4fv(light_loc, 1, GL_FALSE, rot_y)\n\n # draw the DiningTable\n glBindVertexArray(VAO[0])\n glBindTexture(GL_TEXTURE_2D, textures[0])\n glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)\n glDrawArrays(GL_TRIANGLES, 0, len(cube_indices))\n\n # draw the floor\n glBindVertexArray(VAO[1])\n glBindTexture(GL_TEXTURE_2D, textures[1])\n glUniformMatrix4fv(model_loc, 1, GL_FALSE, pyrr.matrix44.create_from_translation(pyrr.Vector3([5, 4, 0])))\n glDrawArrays(GL_TRIANGLES, 0, len(floor_indices))\n\n # draw the monkey\n glBindVertexArray(VAO[2])\n glBindTexture(GL_TEXTURE_2D, textures[2])\n glUniformMatrix4fv(model_loc, 1, GL_FALSE, pyrr.matrix44.create_from_translation(pyrr.Vector3([20, 15, 2])))\n glDrawArrays(GL_TRIANGLES, 0, len(monkey_indices))\n\n\n glfw.swap_buffers(window)\n\n# terminate glfw, free up allocated resources\nglfw.terminate()\n","sub_path":"win.py","file_name":"win.py","file_ext":"py","file_size_in_byte":8397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"489068621","text":"import socket\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n# Get local host name\nHOST = socket.gethostname()\n\n# The port used by the server\nPORT = 54321\n\nlen = int(input('Enter a length for a set.(Ex, 5): '))\nmessage = ''\nfor i in range(len):\n message += (input('Enter a number: '))\n\nclient.sendto(message.encode(), (HOST, PORT))\ndata, addr = client.recvfrom(1024)\n\nprint('Received:', data.decode())\nclient.close()\n","sub_path":"UDP_Client.py","file_name":"UDP_Client.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"117013731","text":"from typing import Any, Dict, Tuple\n\nfrom loguru import logger\nfrom nonebot import IntentCommand, NLPSession, on_natural_language\nfrom nonebot.command import CommandManager\nfrom rapidfuzz import fuzz, process\n\n\ndef gen_commands_keys(commands: Dict[Tuple, Any]):\n result_set = set()\n for item in commands.keys():\n if len(item) == 1:\n result_set.add(item[0])\n return result_set\n\n\n@on_natural_language()\nasync def _(session: NLPSession):\n # 获取所有命令作为一个集合\n commands = CommandManager._commands # type: Dict[Tuple, Any]\n aliases = CommandManager._aliases # type: Dict[str, Any]\n choices = gen_commands_keys(commands)\n choices |= set(aliases.keys())\n\n raw_message = session.event.raw_message.split()\n # 假设该消息为命令,取第一个字段\n query_cmd = raw_message[0]\n cmd, confidence = process.extractOne(query_cmd, choices, scorer=fuzz.WRatio)\n logger.debug(f\"query_cmd: {query_cmd}\")\n logger.debug(f\"fuzz cmd, confidence: {cmd} {confidence}\")\n if confidence - 66 > 0:\n raw_message[0] = cmd\n return IntentCommand(confidence, \"switch\", current_arg=\" \".join(raw_message),)\n","sub_path":"app/bot/nlp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"258689117","text":"from app.data.models import UserData\nfrom app import login\nfrom mongoengine import DoesNotExist, MultipleObjectsReturned\nimport app.data.models as models\n\n\n@login.user_loader\ndef find_user_by_email(email):\n try:\n return UserData.objects.get(email=email)\n except DoesNotExist:\n return None\n except MultipleObjectsReturned:\n assert False\n\n\ndef save_user_data(user_data):\n if isinstance(user_data, models.UserData):\n user_data.save()\n user_data.reload()\n return user_data\n else:\n return None\n\n\ndef save_artist_data(artist):\n if isinstance(artist, models.SpotifyArtistData):\n artist.save()\n artist.reload()\n return artist\n else:\n return None\n\ndef update_user_location(user, location):\n user_full = find_user_by_email(user.get_id())\n if isinstance(user_full, models.UserData):\n if \"lat\" in location and \"lng\" in location:\n try:\n user_full.update(location=[location[\"lng\"], location[\"lat\"]])\n user_full.reload()\n return user_full\n except Exception as exp:\n print(exp)\n return None\n\n\ndef find_users_in_distance_for_user(user, min_distance=0, max_distance=10000):\n \"\"\"\n Function that returns the list of users that are in between min_distance and max_distance from the specified user.\n :param user: UserData\n :param min_distance: int\n :param max_distance: int\n :return: list of users\n \"\"\"\n if not isinstance(user, models.UserData):\n return []\n if user.location is None:\n return None\n if \"coordinates\" not in user.location or len(user.location[\"coordinates\"]) != 2:\n return None\n near_users = UserData.objects(location__near=user.location, location__max_distance = max_distance,\n location__min_distance=min_distance)\n return near_users\n\n\nif __name__ == \"__main__\":\n user_full = find_user_by_email(\"utkuyabas@gmail.com\")\n users = find_users_in_distance_for_user(user_full)\n print([u.name for u in users])","sub_path":"app/data/mongo_functions.py","file_name":"mongo_functions.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"52278141","text":"import re\n\ndef first_last(iterable):\n i = iter(iterable)\n f = next(i)\n yield f, \"first\"\n n = next(i)\n for another in i:\n yield n, None\n n = another\n yield n, \"last\"\n\ndef format_phone(phone_number):\n pattern = r'^8'\n repl = '+7'\n result = phone_number\n if len(phone_number) > 9:\n result = re.sub(pattern, repl, phone_number , re.I | re.U)\n return result","sub_path":"realestate/estatebase/lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"95495607","text":"import psycopg2\nimport math\nASOS = psycopg2.connect(database='asos', host='iemdb', user='nobody')\nacursor = ASOS.cursor()\n\n\ndata = []\nyears = []\n # Query out obs\nacursor.execute(\"\"\"\nselect extract(year from valid + '4 months'::interval) as yr, sum(valid - lag) from (select valid, lag(valid) OVER (ORDER by valid ASC), tmpf from alldata where station = 'LSE') as foo WHERE tmpf < -0.49 GROUP by yr ORDER by yr ASC\n\"\"\")\nfor row in acursor:\n data.append( (row[1].days * 86400. + row[1].seconds) / 3600.0 )\n years.append( float(row[0]) )\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nyears = np.array(years)\ndata = np.array(data)\n\nfig, ax = plt.subplots(1,1)\n\nax.set_title(\"Dubuque Airport Hours Below 0$^\\circ$F [1950-2014]\\nbased on Iowa Environmental Mesonet Unofficial METAR Archives\")\nax.set_xlabel(\"year of spring shown, *2014 thru 25 Feb\")\nbars = ax.bar( years-0.4, data / 24.0, facecolor='r', edgecolor='r')\nfor i,bar in enumerate(bars):\n if data[i] >= data[-1]:\n bar.set_facecolor('b')\n bar.set_edgecolor('b')\nax.set_ylabel(\"Hours Below 0$^{\\circ}F$ (expressed in days)\")\nax.set_xlim(1949.5,2014.5)\n#ax.set_ylim(0,21)\nax.grid(True)\n\n\nfig.savefig('test.ps')\nimport iemplot\niemplot.makefeature('test')\n","sub_path":"scripts/feature/asos/hours_above.py","file_name":"hours_above.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"142601886","text":"import os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n\nclass SetOfParliamentMembers:\n def __init__(self, name):\n self.name = name\n\n def total_mps(self):\n return len(self.dataframe)\n\n def data_from_csv(self, csv_file):\n self.dataframe = pd.read_csv(csv_file, sep=\";\")\n\n def data_from_dataframe(self, dataframe):\n self.dataframe = dataframe\n\n def display_chart(self):\n data = self.dataframe\n female_mps = data[data.sexe == \"F\"]\n male_mps = data[data.sexe == \"H\"]\n\n counts = [len(female_mps), len(male_mps)]\n counts = np.array(counts)\n nb_mps = counts.sum()\n proportions = counts / nb_mps\n\n labels = [\"Female ({})\".format(counts[0]), \"Male ({})\".format(counts[1])]\n\n fig, ax = plt.subplots()\n ax.axis(\"equal\")\n ax.pie(\n proportions,\n labels=labels,\n autopct=\"%1.1f pourcents\"\n )\n plt.title(\"{} ({} MPs)\".format(self.name, nb_mps))\n plt.show()\n\n def split_by_political_party(self):\n result = {}\n data = self.dataframe\n\n all_parties = data[\"parti_ratt_financier\"].dropna().unique()\n\n for party in all_parties:\n data_subset = data[data.parti_ratt_financier == party]\n subset = SetOfParliamentMembers('MPs from party \"{}\"'.format(party))\n subset.data_from_dataframe(data_subset)\n result[party] = subset\n\n return result\n\n\ndef launch_analysis(data_file, by_party=False, info=False):\n sopm = SetOfParliamentMembers(\"All MPs\")\n sopm.data_from_csv(os.path.join(\"data\", data_file))\n sopm.display_chart()\n\n if by_party:\n for party, s in sopm.split_by_political_party().items():\n s.display_chart()\n\n if info:\n print(sopm.total_mps())\n\n\nif __name__ == \"__main__\":\n launch_analysis('current_mps.csv')\n","sub_path":"PerfectionPython/analysis/csv.py","file_name":"csv.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"153704555","text":"import os\n\nSITE_ROOT = os.path.dirname(os.path.realpath(__file__+ '/../'))\n\nSITE_ID = 1\n\nDEBUG = False\nTEMPLATE_DEBUG = DEBUG\n\nUSE_ETAGS = True\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'stard0g101_cvine',\n 'USER': 'stard0g101_cvine',\n 'PASSWORD': '90aa508a',\n 'HOST': '127.0.0.1',\n 'PORT': '',\n }\n}\n\nSTATIC_URL = '/static/'\n\nSTATIC_ROOT = '/home/stard0g101/webapps/cartvine_static/'\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n '/home/stard0g101/webapps/cartvine_static/base/',\n)\n\n# Shopify Key\nSHOPIFY_API_KEY = '5a9dbf6950f6f4719a226e4f32276dca'\nSHOPIFY_API_SECRET = 'faba2795c9cf719949c8c7d5b4a1bd9e'\n\n#Facebook App Id\nFACEBOOK_APP_ID = '209234305864956'\nFACEBOOK_APP_SECRET = '8a2b5757c513965faff0de2c35dcdbf2'\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n 'LOCATION': 'unix:/home/stard0g101/webapps/cartvine_app/cartvine/memcached.sock',\n }\n}","sub_path":"conf/cartvine_app/live.local_settings.py","file_name":"live.local_settings.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"51251366","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n#\r\n# Copyright (c) 2010-2016 SMHI, Swedish Meteorological and Hydrological Institute \r\n# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).\r\n#\r\nfrom __future__ import unicode_literals\r\n\r\nimport codecs\r\nimport dateutil\r\nimport toolbox_utils\r\nimport plankton_core\r\n\r\nclass ImportPhytowin(plankton_core.DataImportPreparedBase):\r\n \"\"\" Class for parsing Phytowin CSV files. \"\"\"\r\n def __init__(self):\r\n \"\"\" \"\"\"\r\n # Initialize parent.\r\n super(ImportPhytowin, self).__init__()\r\n\r\n # Information needed for parsing. List of lists with: \r\n # Column 0: node level. \r\n # Column 1: internal key. \r\n # Column 2: view format. \r\n # Column 3: source file column name. Multiple alternatives should be separated by ''. \r\n # Column 4: export column name. None = not used, empty string ('') = same as column 1 (internal key).\r\n self._parsing_info = [\r\n \r\n # Metadata:\r\n ['visit', 'station_name', 'text', 'StatName', ''], \r\n ['visit', 'sample_date', 'text', 'Date', ''], \r\n ['visit', 'time', 'text', 'Time', ''], \r\n ['visit', 'reported_latitude', 'text', 'Latitude', ''], \r\n ['visit', 'reported_longitude', 'text', 'Longitude', ''], \r\n ['sample', 'sample_min_depth_m', 'float', 'Min. Depth', ''], \r\n ['sample', 'sample_max_depth_m', 'float', 'Max. Depth', ''], \r\n ['visit', 'water_depth_m', 'float', 'Depth', ''], \r\n\r\n # Header: \"Species\",\"A/H\",\"Size\",\"Descr\",\"Units\",\"Coeff\",\"Units/l\",\"ww mg/m3\",\"µgC/m3\"\r\n ['variable', 'reported_scientific_name', 'text', 'Species', None], # Internal use only. \r\n ['variable', 'scientific_name', 'text', 'Species', ''], \r\n ['variable', 'species_flag_code', 'text', '', ''], \r\n ['variable', 'reported_trophic_type', 'text', 'A/H', None], # Internal use only. \r\n ['variable', 'trophic_type', 'text', '', ''], # Will be calculated later.\r\n ['variable', 'reported_size_class', 'text', 'Size', None], # Internal use only. \r\n ['variable', 'size_class', 'text', 'Size', ''], \r\n ['variable', 'description', 'text', 'Descr', ''], \r\n ['variable', 'coefficient', 'text', 'Coeff', ''], \r\n\r\n # Param/value/unit. (Added later from \"copy parameters\".)\r\n ['variable', 'parameter', 'text', 'parameter', ''],\r\n ['variable', 'value', 'float', 'value', ''], \r\n ['variable', 'unit', 'text', 'unit', ''], \r\n\r\n # Copy parameters.\r\n ['copy_parameter', '# counted:ind', 'text', 'Units'], \r\n ['copy_parameter', 'Abundance:ind/l', 'text', 'Units/l'], \r\n ['copy_parameter', 'Wet weight:mg/m3', 'text', 'ww mg/m3'], \r\n ['copy_parameter', 'Carbon content:µgC/m3', 'text', 'µgC/m3'], \r\n ['copy_parameter', 'Abundance class:abu_class', 'text', 'Abundance (scale 1 to 5)'],# NET sample.\r\n \r\n # More metadata:\r\n ['dataset', 'sample_id', 'text', 'Sample Id', ''], \r\n ['dataset', 'project_code', 'text', 'Project', ''], \r\n ['visit', 'platform_code', 'text', 'Ship', ''], \r\n ['visit', 'station_number', 'text', 'StatNo', ''], \r\n ['variable', 'taxon_class', 'text', '', ''], # Will be calculated later.\r\n ['variable', 'magnification', 'text', 'Magnification', ''], \r\n ['variable', 'counted_units', 'text', 'Units', ''], \r\n ['sample', 'number_of_depths', 'text', 'No. Depths', ''], \r\n ['sample', 'sampler_type_code', 'text', 'Sampler', ''], \r\n ['sample', 'sample_size', 'text', 'Sample size', ''], \r\n ['sample', 'sampled_by', 'text', 'Sample by', ''], \r\n ['sample', 'sample_comment', 'text', 'Comment', ''], \r\n ['variable', 'mixed_volume', 'text', 'Mixed volume', ''], \r\n ['variable', 'preservative', 'text', 'Preservative', ''], \r\n ['variable', 'sedimentation_volume', 'text', 'Sedim. volume', ''], \r\n ['variable', 'preservative_amount', 'text', 'Amt. preservative', ''], \r\n ['variable', 'sedimentation_time_h', 'text', 'Sedim. time (hr)', ''], \r\n ['variable', 'chamber_diameter', 'text', 'Chamber diam.', ''], \r\n ['variable', 'analysis_date', 'text', 'Counted on', ''], \r\n ['variable', 'taxonomist', 'text', 'Counted by', ''], \r\n ]\r\n #\r\n self.clear() # \r\n #\r\n self._phytowin_to_peg_filename = 'toolbox_data/species/phytowin_translate_sizeclasses.xlsx'\r\n try:\r\n self._load_phytowin_species_and_sizes_mapping()\r\n except:\r\n print('Failed to load: ' + self._phytowin_to_peg_filename)\r\n \r\n\r\n def clear(self):\r\n \"\"\" \"\"\"\r\n self._phytowin_metadata = {}\r\n self._phytowin_header = []\r\n self._phytowin_rows = []\r\n self._phytowin_coeff2magni_dict = {}\r\n #\r\n self._phytowin_sample_info = {} # Information related to sample.\r\n self._phytowin_aggregated_rows = [] # Pre-calculated aggregations of data.\r\n #\r\n self._pythowin_peg_mapping = {}\r\n\r\n def read_file(self, file_name = None):\r\n \"\"\" \"\"\"\r\n if file_name == None:\r\n raise UserWarning('File name is missing.')\r\n file = None\r\n try:\r\n### txtencode = toolbox_settings.ToolboxSettings().getValue('General:Character encoding, txt-files', 'cp1252')\r\n txtencode = 'cp1252'\r\n file = codecs.open(file_name, mode = 'r', encoding = txtencode)\r\n \r\n # Read data header. Same header used for data and aggregated data.\r\n \r\n separator = ',' # Use ',' as default item separator.\r\n first_row = file.readline()\r\n if ';' in first_row:\r\n separator = ';' # Use ';' as item separator.\r\n \r\n self._phytowin_header = []\r\n for headeritem in first_row.strip(separator).split(separator):\r\n item = headeritem.strip().strip('\"').strip()\r\n self._phytowin_header.append(item)\r\n \r\n # Empty line.\r\n file.readline().strip(separator)\r\n \r\n # Read data rows. Continue until empty line occurs.\r\n self._phytowin_rows = []\r\n row = file.readline().strip(separator)\r\n while len(row.replace(separator, '').strip()) > 0:\r\n rowitems = []\r\n for item in row.split(separator):\r\n rowitems.append(item.strip().strip('\"').strip())\r\n self._phytowin_rows.append(rowitems) \r\n row = file.readline().strip(separator)\r\n \r\n # Read aggregated data rows. Continue until empty line occurs.\r\n self._phytowin_aggregated_rows = []\r\n row = file.readline().strip(separator)\r\n while len(row.replace(separator, '').strip()) > 0:\r\n rowitems = []\r\n for item in row.split(separator):\r\n rowitems.append(item.strip().strip('\"').strip())\r\n self._phytowin_aggregated_rows.append(rowitems) \r\n row = file.readline().strip(separator)\r\n \r\n if self._phytowin_header[1] not in ['Abundance (scale 1 to 5)']:\r\n # Read total counted.\r\n row = file.readline().strip(separator) # Not used.\r\n row = file.readline().strip(separator) # Empty.\r\n \r\n # Read total counted.\r\n row = file.readline().strip(separator) # Not used.\r\n row = file.readline().strip(separator) # Empty.\r\n \r\n # Read chamber and magnification info.\r\n # Put result in self._phytowin_coeff2magni_dict for later use.\r\n row = file.readline().strip(separator)\r\n while len(row.replace(separator, '').strip()) > 0:\r\n rowitems = []\r\n for item in row.split(separator):\r\n rowitems.append(item.strip().strip('\"').strip())\r\n if (len(rowitems) > 4) and (rowitems[3] == u\"COEFF=\"):\r\n self._phytowin_coeff2magni_dict[rowitems[4]] = rowitems[0]\r\n row = file.readline().strip(separator)\r\n \r\n # Read info related to sample.\r\n row = file.readline()\r\n while len(row.replace(separator, '').strip()) > 0:\r\n key, value = row.split(separator, 1) # Don't split values (maxsplit = 1).\r\n self._phytowin_sample_info[key.strip().strip('\"').strip()] = value.replace(separator, '').strip().strip('\"').strip()\r\n row = file.readline()\r\n # \r\n except (IOError, OSError):\r\n raise\r\n finally:\r\n if file: file.close()\r\n\r\n\r\n def create_tree_dataset(self, dataset_top_node): \r\n \"\"\" \"\"\"\r\n # Add data to dataset node.\r\n for parsinginforow in self._parsing_info:\r\n if parsinginforow[0] == 'dataset':\r\n dataset_top_node.add_data(parsinginforow[1], self._phytowin_sample_info[parsinginforow[3]]) \r\n \r\n # Create visit node and add data. Note: Only one visit in each file. \r\n visitnode = plankton_core.VisitNode()\r\n dataset_top_node.add_child(visitnode)\r\n \r\n for parsinginforow in self._parsing_info:\r\n if parsinginforow[0] == 'visit':\r\n\r\n \r\n \r\n if parsinginforow[1] == 'sample_date':\r\n sample_date = self._phytowin_sample_info[parsinginforow[3]]\r\n sample_date = sample_date \r\n try:\r\n value = dateutil.parser.parse(sample_date)\r\n if value:\r\n sample_date = unicode(value.strftime('%Y-%m-%d'))\r\n except:\r\n toolbox_utils.Logging().warning('Parser: Failed to convert to date: ' + sample_date)\r\n #\r\n visitnode.add_data(parsinginforow[1], sample_date) \r\n \r\n # Add visit_year and visit_month.\r\n try:\r\n visitnode.add_data('visit_year', sample_date[0:4])\r\n except: pass \r\n try:\r\n visitnode.add_data('visit_month', sample_date[5:7]) \r\n except: pass \r\n else:\r\n visitnode.add_data(parsinginforow[1], self._phytowin_sample_info[parsinginforow[3]]) \r\n \r\n # Create sample node and add data. Note: Only one sample in each file. \r\n samplenode = plankton_core.SampleNode()\r\n visitnode.add_child(samplenode)\r\n \r\n for parsinginforow in self._parsing_info:\r\n if parsinginforow[0] == 'sample':\r\n samplenode.add_data(parsinginforow[1], self._phytowin_sample_info[parsinginforow[3]]) \r\n \r\n # Create variable nodes.\r\n for row in self._phytowin_rows:\r\n variablenode = plankton_core.VariableNode()\r\n samplenode.add_child(variablenode)\r\n #\r\n for parsinginforow in self._parsing_info:\r\n if parsinginforow[0] == 'variable':\r\n value = self._phytowin_sample_info.get(parsinginforow[3], '')\r\n variablenode.add_data(parsinginforow[1], value) \r\n #\r\n row_dict = dict(zip(self._phytowin_header, row))\r\n #\r\n for parsinginforow in self._parsing_info:\r\n if parsinginforow[0] == 'variable':\r\n value = row_dict.get(parsinginforow[3], '')\r\n if len(value) > 0: # Don't overwrite from previous step.\r\n variablenode.add_data(parsinginforow[1], value) \r\n \r\n # Add text field with magnification info. Use coeff as key.\r\n if parsinginforow[1] == 'coefficient':\r\n if value in self._phytowin_coeff2magni_dict:\r\n value = self._phytowin_coeff2magni_dict[value].replace('Part counted with ', '')\r\n variablenode.add_data('magnification', value)\r\n \r\n # Copy to new variable nodes for parameters.\r\n for parsinginforow in self._parsing_info:\r\n if parsinginforow[0] == 'copy_parameter':\r\n paramunit = parsinginforow[1].split(':')\r\n parameter = paramunit[0]\r\n if len(paramunit) > 1:\r\n unit = paramunit[1]\r\n else: \r\n unit = ''\r\n value = row_dict.get(parsinginforow[3], '')\r\n if len(value.strip()) > 0:\r\n self.copy_variable(variablenode, p = parameter, v = value, u = unit)\r\n\r\n ### Special conversions of PhytoWin species and size classes. ###\r\n def update_species_and_sizes(self, dataset_top_node):\r\n \"\"\" \"\"\"\r\n for visit in dataset_top_node.get_children():\r\n for sample in visit.get_children():\r\n for variable in sample.get_children():\r\n scientificname = variable.get_data('reported_scientific_name')\r\n sizeclass = variable.get_data('reported_size_class')\r\n sflag = variable.get_data('species_flag_code')\r\n # Fix 'cf.' and 'sp.''.\r\n scientificname, sflag = plankton_core.DataImportUtils().cleanup_scientific_name_cf(scientificname, sflag)\r\n scientificname, sflag = plankton_core.DataImportUtils().cleanup_scientific_name_sp(scientificname, sflag)\r\n # Translate base on translation file.\r\n name, size, pw_sflag = self._convert_phytowin_species_and_sizes(scientificname, sizeclass)\r\n #\r\n if ('spp' in sflag) and ('spp' in pw_sflag):\r\n pass\r\n else:\r\n if pw_sflag: sflag += ' '+ pw_sflag \r\n #\r\n if name: variable.add_data('scientific_name', name)\r\n if size: variable.add_data('size_class', size)\r\n if sflag: variable.add_data('species_flag_code', sflag.strip())\r\n #\r\n # Get trophic level from peg.\r\n value = plankton_core.Species().get_bvol_value(name, size, 'bvol_trophic_type')\r\n if value:\r\n variable.add_data('trophic_type', value)\r\n else:\r\n variable.add_data('trophic_type', variable.get_data('reported_trophic_type'))\r\n # Get taxonomic class from peg.\r\n value = plankton_core.Species().get_taxon_value(name, 'taxon_class')\r\n variable.add_data('taxon_class', value)\r\n\r\n \r\n def _convert_phytowin_species_and_sizes(self, phytowin_name, phytowin_size_class):\r\n \"\"\" Returns 'PEG name', 'PEG size' and 'SFLAG' as tuple. \"\"\"\r\n if phytowin_name in self._pythowin_peg_mapping:\r\n nameobject = self._pythowin_peg_mapping[phytowin_name]\r\n if phytowin_size_class in nameobject[u'Sizes']:\r\n sizeobject = self._pythowin_peg_mapping[phytowin_name][u'Sizes'][phytowin_size_class]\r\n return (sizeobject[u'PEG name'], sizeobject[u'PEG size'], sizeobject[u'SFLAG'])\r\n else:\r\n# return (None, None, None)\r\n # Don't convert if not in translation list. Return parameters. \r\n return (phytowin_name, phytowin_size_class, '')\r\n else:\r\n# return (None, None, None)\r\n # Don't convert if not in translation list. Return parameters. \r\n return (phytowin_name, phytowin_size_class, '')\r\n \r\n def _load_phytowin_species_and_sizes_mapping(self):\r\n \"\"\" \"\"\"\r\n self._pythowin_peg_mapping = {} \r\n # Read data from Excel file.\r\n tablefilereader = toolbox_utils.TableFileReader(\r\n file_path = '',\r\n excel_file_name = self._phytowin_to_peg_filename,\r\n )\r\n #\r\n for row in tablefilereader.rows():\r\n if len(row) < 2:\r\n continue \r\n #\r\n phytowinname = row[0]\r\n phytowinsize = row[1]\r\n if phytowinsize:\r\n try:\r\n # Convert from float to int. Excel related problem.\r\n phytowinsize = unicode(int(float(phytowinsize)))\r\n except:\r\n phytowinsize = u''\r\n print(u'loadPhytowinPegMapping, phytowinsize: ' + row[1])\r\n pegname = row[2]\r\n pegsize = row[3]\r\n if pegsize:\r\n try:\r\n # Convert from float to int. Excel related problem.\r\n pegsize = unicode(int(float(pegsize)))\r\n except:\r\n pegsize = u''\r\n print(u'loadPhytowinPegMapping, pegsize: ' + row[3])\r\n sflag = row[4]\r\n #\r\n if phytowinname:\r\n if phytowinname not in self._pythowin_peg_mapping:\r\n self._pythowin_peg_mapping[phytowinname] = {}\r\n self._pythowin_peg_mapping[phytowinname][u'Sizes'] = {}\r\n phytowinobject = self._pythowin_peg_mapping[phytowinname]\r\n #\r\n phytowinobject[u'SFLAG'] = sflag\r\n #\r\n sizeobject = {u'PEG name': pegname, u'PEG size': pegsize, u'SFLAG': sflag}\r\n phytowinobject[u'Sizes'][phytowinsize] = sizeobject\r\n\r\n\r\n############################### From reports ##################################################\r\n\r\n# # Iterate over species in the dictionary.\r\n# for phytowinnameandsize in species_sample_dict.keys():\r\n# # NET samples: \r\n# ## Extract useful part from Species-column.\r\n# ## Example: \"Protoperidinium steinii HET 32 (cell: 32-37µm)\"\r\n# #parts = phytowinname.split(u' ')\r\n# #speciesname = u''\r\n# #for part in parts:\r\n# # if part not in [u'cf.', u'HET', u'32', u'(cell:', u'(width:', u'(no']:\r\n# # speciesname += part + u' '\r\n# # else:\r\n# # if part not in [u'cf.']:\r\n# # break # Break loop.\r\n# #speciesname = speciesname.strip()\r\n# #\r\n# # Counted samples:\r\n# namesize = phytowinnameandsize.split(':')\r\n# phytowinname = namesize[0]\r\n# # Remove 'cf.'\r\n# if u'cf.' in phytowinname: \r\n# parts = phytowinname.split(u' ')\r\n# speciesname = u''\r\n# for part in parts:\r\n# if part not in [u'cf.']:\r\n# speciesname += part + u' '\r\n# phytowinname = speciesname.strip()\r\n# #\r\n# sizeclass = namesize[1]\r\n# #\r\n# # if self._taxaphytowin is not None:\r\n# # pegname, pegsize, sflag = self._taxaphytowin.TaxaPhytowin().convert_from_phytowin_to_peg(phytowinname, phytowin_size_class = sizeclass)\r\n# # else:\r\n# # pegname = phytowinname\r\n# # pegsize = sizeclass\r\n# # sflag = ''\r\n# pegname = phytowinname\r\n# pegsize = sizeclass\r\n# sflag = ''\r\n# \r\n# # Check if 'cf.' was included in name. Add to Sflag.\r\n# if u'cf.' in variablenode.get_data('scientific_name'):\r\n# if sflag:\r\n# sflag = 'cf., ' + sflag\r\n# else:\r\n# sflag = 'cf.'\r\n\r\n\r\n# # Remove 'cf.'\r\n# if u'cf.' in phytowinname: \r\n# parts = phytowinname.split(u' ')\r\n# speciesname = u''\r\n# for part in parts:\r\n# if part not in [u'cf.']:\r\n# speciesname += part + u' '\r\n# phytowinname = speciesname.strip()\r\n\r\n\r\n# # Check if 'cf.' was included in name. Add to Sflag.\r\n# if u'cf.' in variablenode.get_data('scientific_name'):\r\n# if sflag:\r\n# sflag = 'cf., ' + sflag\r\n# else:\r\n# sflag = 'cf.'\r\n\r\n","sub_path":"plankton_core/dataimports_phytowin.py","file_name":"dataimports_phytowin.py","file_ext":"py","file_size_in_byte":21006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"406105587","text":"#!/usr/bin/python3\n\n# Plot 'brot using PIL / Pillow. Plots x,y, not y,x as does pylab.\n# JM Mon 5 Jan 2015 15:11:32 GMT\n# For 1, L, and I images, use integers. For RGB images, use a 3-tuple containing integer values. \n# For F images, use integer or floating point values.\n# Plot of set for Z^2 + 1/(z ):\n# Doesn't work as get Div by zero error.\n# JM Tue 17 Oct 2017 14:32:56 BST\n# Cured div 0 error by setting Z to 0.001. if (Z): wasn't working as Z was Z=(0,0).\n# Still getting maxiter colour. 1/Z very large ?\n# JM Thu 8 Nov 2018 15:46:56 GMT\n# 1/Z is indeed larger. Try 0.001/Z \n# Making numnerator larger gives smaller size image.\n# JM Thu 8 Nov 2018 16:19:02 GMT\n# Zoom in to RHS.\n# Fname: tst_Zm_RHS_Recip_Brot_(0.0025+0j)_-1.071_-1.059_-0.001_0.001_.png\n# JM Tue 11 Dec 14:10:29 GMT 2018\n\nfrom PIL import Image\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\nimport numpy as nm\nimport cmath\nfrom timeit import default_timer as timer\nfrom lc import colour_list\nimport sys\n\nstart = timer()\n\nX_MIN = -1.07\nX_MAX = -1.0591\nY_MIN = -0.005\nY_MAX = 0.005\noffset = 0.00001\nmaxiter = 950\ncalc_count = 0\nrnum = 93\nlenlc = len( colour_list )\nZnumerator = 0.0024\n\n# create a new X*Y pixel image surface\n# make the background white (default bg=black)\nX_SIZE = ( X_MAX - X_MIN ) / offset\nY_SIZE = ( Y_MAX - Y_MIN ) / offset\n\nX_SIZE += 1\nY_SIZE += 1\n\nX_SIZE = int( X_SIZE )\nY_SIZE = int( Y_SIZE )\n\nprint ( 'X: ', X_SIZE ,' Y: ', Y_SIZE )\nif ( len( sys.argv ) == 2 ):\n sys.exit()\n\n\nwhite = (255,255,255)\nrandcolour = ( 255, 255, 230 )\nimg = Image.new( \"RGB\", [ X_SIZE, Y_SIZE ], white )\n\nmycolour = ( 100, 150, 200 ) \nx_pixel = 0\nfor X in nm.arange ( X_MIN, X_MAX, offset ):\n\ty_pixel = 0\n\tfor Y in nm.arange ( Y_MIN, Y_MAX, offset ):\n\t\tZ = complex ( 0.001, 0.0 )\n\t\tC = complex ( X, Y )\n\t\titer_count = 0\n\n\t\twhile ( abs ( Z**2 ) < 4 and iter_count < maxiter ):\n\t\t\t\n\t\t\t#Z = Z**2 + C\n\t\t\tZ = Z**2 + ( Znumerator / Z ) + C\n\t\t\t#print( Z, C, ' ', iter_count, abs ( Z**2 ) )\n\t\t\titer_count = iter_count + 1\n\t\t\n\t\t\tcalc_count = calc_count + 1 \n\t\t#mycolour = ( 13 * iter_count, 23 * iter_count, 33 * iter_count ) \n\t\tif ( iter_count + rnum >= lenlc ):\n\t\t\tmycolour = colour_list[ iter_count % lenlc ]\n\t\telse: \n\t\t\tmycolour = colour_list[ iter_count + rnum ]\n\t\tif ( iter_count <= 2 ):\n\t\t\timg.putpixel( ( x_pixel, y_pixel ), white )\n\t\telif ( iter_count == maxiter ):\n\t\t\timg.putpixel( ( x_pixel, y_pixel ), randcolour ) \n\t\telse:\n\t\t\timg.putpixel( ( x_pixel, y_pixel ), mycolour ) \n\t\ty_pixel += 1\n\n\tx_pixel += 1\n\ndt = timer() - start\n\nMsgText = 'Brot for Z^2 + ' + str( Znumerator ) + '/Z'\nfname = 'Zm_RHS_Recip_Brot_' + str( Znumerator ) + '.png'\ndraw = ImageDraw.Draw(img)\nfont = ImageFont.truetype( \"/usr/share/fonts/truetype/ubuntu/UbuntuMono-B.ttf\", 12 )\ndraw.text( ( 0, 0 ), MsgText, ( 139,0,0 ), font=font )\n\nprint ( MsgText )\nprint ( 'Fname:', fname )\nprint ( 'X_MIN: ', X_MIN, 'X_MAX: ', X_MAX )\nprint ( 'Y_MIN: ', Y_MIN, 'Y_MAX: ', Y_MAX )\nprint ( 'Test Iter and Rand:', rnum, 'created in %f s' % dt )\nprint ( 'Calc: ', calc_count )\nimg.show()\n#img.save( fname )\n\n","sub_path":"zmrhb0025.py","file_name":"zmrhb0025.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"173151724","text":"from datetime import date\nfrom statistics import mean\nclass Match:\n def __init__(self,str):\n temp=str.split(\" \")\n temp = [i for i in temp if i != '' and i!=' ']\n self.date=temp[0]\n self.home_team=temp[1]\n self.away_team=temp[2]\n # print(\"Initializing %s %s\" %(self.home_team,self.away_team))\n self.home_sets=int(temp[3])\n self.away_sets=int(temp[4])\n self.home_scores=[]\n self.away_scores=[]\n for i in range(self.home_sets+self.away_sets):\n self.home_scores.append(int(temp[5+i*2]))\n self.away_scores.append(int(temp[6+i*2]))\n self.day=int(self.date[0:2])\n self.month=int(self.date[3:5])\n \n #update dates\n self.year=2019\n if(self.month<=5):\n self.year=2020\n\n \n self.DATE=date(self.year,self.month,self.day)\n t = temp[-1];\n if(t == \"9th place\"):\n self.importance = 1\n elif(t == \"Final\"):\n self.importance = 3\n elif(t == \"3rd place\"):\n self.importance = 2\n elif(t == \"4rd place\"):\n self.importance = 2\n elif(t == \"5th place\"):\n self.importance = 1\n elif(t == \"Semi-finals\"):\n self.importance = 2\n elif(t == \"7th place\"):\n self.importance = 1\n elif(t == \"6th place\"):\n self.importance = 1\n elif(t == \"8th place\"):\n self.importance = 1\n elif(t == \"Quarter-finals\"):\n self.importance = 1\n else:\n self.importance = 0\n #change dates\n # if(self.DATE>=date(2019,4,24)):\n # self.importance=3\n # elif(self.DATE>=date(2019,4,7)):\n # self.importance=2\n # elif(self.DATE>=date(2019,3,23)):\n # self.importance=1\n self.home_av_points=mean(self.home_scores)\n self.away_av_points=mean(self.away_scores)\n \n def __str__(self): \n return \"date=%s home team=%s away team=%s scores=%d-%d, home:%s, away:%s importance=%d\" % (self.date, self.home_team, self.away_team,self.home_sets,self.away_sets,self.home_scores.__str__(),self.away_scores.__str__(),self.importance) \n ","sub_path":"PlusLigaPolandData/src/match.py","file_name":"match.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"626436945","text":"from discord.ext import commands\nimport os\nimport random\nimport traceback\n\nbot = commands.Bot(command_prefix='/')\ntoken = os.environ['DISCORD_BOT_TOKEN']\nhelp_text = '/roll,/role:ロールを決める'\n\n'''\n@bot.event\nasync def on_command_error(ctx, error):\n await ctx.send(str(error))\n'''\n\n\n@bot.command()\nasync def ping(ctx):\n await ctx.send('pong')\n\n\n@bot.command()\nasync def roll(ctx):\n rolled_role = role_roller()\n await ctx.send(rolled_role)\n\n\n@bot.command()\nasync def role(ctx):\n rolled_role = role_roller()\n await ctx.send(rolled_role)\n\n\n@bot.command()\nasync def roller_help(ctx):\n await ctx.send(help_text)\n\n\n@bot.command()\nasync def five_roll(ctx):\n role_list = ['Top', 'Jg', 'Mid', 'Adc', 'Sup']\n random.shuffle(role_list)\n await ctx.send('----Role List----')\n for r in role_list:\n await ctx.send(r)\n\n\ndef role_roller():\n roll_index = random.randint(0, 1000)\n rolled_role = 'none'\n\n if roll_index % 5 == 0:\n rolled_role = 'Top'\n return rolled_role\n elif roll_index % 5 == 1:\n rolled_role = 'Jg'\n return rolled_role\n elif roll_index % 5 == 2:\n rolled_role = 'Mid'\n return rolled_role\n elif roll_index % 5 == 3:\n rolled_role = 'Adc'\n return rolled_role\n elif roll_index % 5 == 4:\n rolled_role = 'Sup'\n return rolled_role\n\n\nbot.run(token)\n","sub_path":"discordbot.py","file_name":"discordbot.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"126469631","text":"import os\nimport scipy.misc\nimport numpy as np \n\nfrom model import DCGAN\nfrom utils import pp, visualize, to_json\n\nimport tensorflow as tf \n\nflags = tf.app.flags\nflags.DEFINE_integer(\"epoch\", 25, \"Epoch to train [25]\")\nflags.DEFINE_float(\"learning_rate\", 0.0002, \"Learning rate for adam [0.0002]\")\nflags.DEFINE_float(\"beta1\", 0.5, \"Momentum term of adam [0.5]\")\nflags.DEFINE_float(\"train_size\", np.inf, \"The size of train images [np.inf]\")\nflags.DEFINE_integer(\"batch_size\", 64, \"Size of batch images [64]\")\nflags.DEFINE_integer(\"image_size\", 64, \"the size of image to use\")\nflags.DEFINE_string(\"dataset\", r\"C:\\Users\\plettlk\\DCGAN_Image_Completion\\61119\\scaled_tofu\", \"Dataset directory\")\nflags.DEFINE_string(\"checkpoint_dir\", \"checkpoint\", \"directory name to save the checkpoints [checkpoint]\")\nflags.DEFINE_string(\"sample_dir\", \"samples\", \"Directory name to save the image samples [samples]\")\nFLAGS = flags.FLAGS\n\n\nif not os.path.exists(FLAGS.checkpoint_dir):\n os.makedirs(FLAGS.checkpoint_dir)\nif not os.path.exists(FLAGS.sample_dir):\n os.makedirs(FLAGS.sample_dir)\n\nconfig = tf.ConfigProto()\nwith tf.Session(config=config) as sess:\n\n dcgan = DCGAN(sess, image_size=FLAGS.image_size, batch_size=FLAGS.batch_size,\n sample_size=FLAGS.batch_size, is_crop=False, checkpoint_dir=FLAGS.checkpoint_dir)\n\n dcgan.train(FLAGS)\n","sub_path":"DCGAN/train_dcgan.py","file_name":"train_dcgan.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"134500139","text":"import csv\nimport numpy\n\nwith open('weather_api_nulos.csv', 'r+', encoding=\"ISO-8859-1\") as nuls, \\\n open('weather_api_sem_nulos.csv', 'r+', encoding=\"ISO-8859-1\") as nots, \\\n open('weather_means_api.csv', 'w+') as meds:\n csv_nuls = csv.reader(nuls, delimiter=',')\n headerSave = True\n csv_nots = csv.reader(nots, delimiter=',')\n next(csv_nots, None)\n d = {}\n stock = []\n for l in csv_nots:\n # Mes, Dia, Ano, Hora\n stock.append((int(l[2]) * 1000000 + int(l[0]) * 10000 + int(l[1]) * 100 + int(l[3])))\n d[str(int(l[2]) * 1000000 + int(l[0]) * 10000 + int(l[1]) * 100 + int(l[3]))] = l\n for nul in csv_nuls:\n if headerSave:\n meds.write((','.join(nul)) + '\\n')\n headerSave = False\n continue\n\n nulVal = list(map(int, nul[:4]))\n nTime = nulVal[2] * 1000000 + nulVal[0] * 10000 + nulVal[1] * 100 + nulVal[3]\n\n print(nTime)\n\n targets = list(map(str, filter(lambda x: x < nTime, stock)))\n targets.sort(reverse=True)\n targets = targets[:3]\n\n line = list(map(str, map(numpy.mean, list(\n map(lambda x: list(map(int, x)), map(list, zip(*list(map(lambda x: d[x][6:11], targets)))))))))\n print(d[targets[0]])\n print(nul[:6])\n meds.write(','.join(nul[:6] + list(map(str,map(int,map(float,line))))))\n\n meds.write('\\n')\n","sub_path":"Tratamento de Dados/weather_api.py","file_name":"weather_api.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"464854653","text":"import argparse\nimport json\nimport os\nimport re\nimport sys\nfrom pathlib import Path\n\nimport chainer\nimport chainer.functions as F\nimport chainer.iterators as I\nimport matplotlib\nimport numpy as np\nfrom chainer import training\nfrom chainer.training import extensions\n\nfrom dataproc import Dataproc\nfrom evaluator import GraphEvaluator\nfrom model import build_model, Classifier\n\n\n# Global error handler\ndef global_except_hook(exctype, value, traceback):\n import sys\n from traceback import print_exception\n print_exception(exctype, value, traceback)\n sys.stderr.flush()\n\n import mpi4py.MPI\n mpi4py.MPI.COMM_WORLD.Abort(1)\n\n\nsys.excepthook = global_except_hook\n\n\ndef main():\n import chainermn\n chainer.global_config.autotune = True\n parser = argparse.ArgumentParser(description='ChainerMN example: Train MQAP using 3DCNN')\n parser.add_argument('--communicator', type=str,\n default='hierarchical', help='Type of communicator')\n parser.add_argument('--gpu', '-g', action='store_true',\n help='Use GPU')\n parser.add_argument('--out', '-o', default='result',\n help='Directory to output the result')\n parser.add_argument('--resume', '-r', action='store_true',\n help='Resume the training from snapshot')\n parser.add_argument('--weight', '-w', action='store_true',\n help='Resume only weight')\n parser.add_argument('--config', '-c', type=int, default=0,\n help='Number of config')\n parser.add_argument('--config_file', type=str, default='./data/lddt_config.json',\n help='Config file path')\n\n args = parser.parse_args()\n if args.gpu:\n if args.communicator == 'naive':\n print(\"Error: 'naive' communicator does not support GPU.\\n\")\n exit(-1)\n comm = chainermn.create_communicator(args.communicator, allreduce_grad_dtype='float16')\n device = comm.intra_rank\n else:\n if args.communicator != 'naive':\n print('Warning: using naive communicator '\n 'because only naive supports CPU-only execution')\n comm = chainermn.create_communicator('naive')\n device = -1\n f = open(args.config_file, 'r')\n\n config = json.load(f)['Config'][args.config]\n args.out = os.path.join(args.out, str(args.config))\n if comm.rank == 0:\n print('==========================================')\n chainer.print_runtime_info()\n print('Num process (COMM_WORLD): {}'.format(comm.size))\n if args.gpu:\n print('Using GPUs')\n print('Using {} communicator'.format(args.communicator))\n print('Num epoch: {}'.format(config['epoch']))\n print('Batch size: {}'.format(config['batch_size'] * comm.size))\n print('Optimizer: {}'.format(config['optimizer']))\n print('Learning Rate: {}'.format(config['learning_rate']))\n print('Out Directory: {}'.format(args.out))\n print('Vertex feature: {}'.format(config['vertex_feature']))\n if config['global_mode']:\n print('Using Global loss')\n if config['local_mode']:\n print('Using local loss')\n print('Local type : {}'.format(config['local_type']))\n print('Local label : {}'.format(config['local_label']))\n print('==========================================')\n d = Dataproc(size=comm.size, rank=comm.rank, config=config)\n if device >= 0:\n chainer.cuda.get_device(device).use()\n # sub_comm = comm.split(comm.rank // comm.intra_size, comm.rank)\n if config['local_type'] == 'Regression':\n local_loss_func = F.mean_squared_error\n else:\n local_loss_func = F.sigmoid_cross_entropy\n global_loss_func = F.mean_squared_error\n model = build_model(config=config, comm=comm)\n model = Classifier(predictor=model, local_loss_func=local_loss_func, global_loss_func=global_loss_func,\n config=config)\n if device >= 0:\n model.to_gpu()\n train, test = d.get_dataset(key='train'), d.get_dataset(key='test')\n train_iter = I.SerialIterator(dataset=train, batch_size=config['batch_size'], repeat=True, shuffle=True)\n test_iter = I.SerialIterator(dataset=test, batch_size=config['batch_size'], repeat=False, shuffle=False)\n # train_iter = I.MultiprocessIterator(dataset=train, batch_size=args.batch, repeat=True, shuffle=True, n_processes=10)\n # test_iter = I.MultiprocessIterator(dataset=test, batch_size=args.batch, repeat=False, shuffle=True, n_processes=10)\n\n if config['optimizer'] == 'Adam':\n optimizer = chainer.optimizers.Adam(alpha=config['learning_rate'],\n weight_decay_rate=config['weight_decay_rate'], amsgrad=True)\n optimizer = chainermn.create_multi_node_optimizer(optimizer, comm, double_buffering=False)\n elif config['optimizer'] == 'MomentumSGD':\n optimizer = chainer.optimizers.MomentumSGD(lr=config['learning_rate'])\n optimizer = chainermn.create_multi_node_optimizer(optimizer, comm, double_buffering=False)\n elif config['optimizer'] == 'SMORMS3':\n optimizer = chainer.optimizers.SMORMS3(lr=config['learning_rate'])\n optimizer = chainermn.create_multi_node_optimizer(optimizer, comm, double_buffering=False)\n elif config['optimizer'] == 'Eve':\n from my_optimizer.eve import Eve, create_multi_node_optimizer\n optimizer = Eve(alpha=config['learning_rate'])\n optimizer = create_multi_node_optimizer(optimizer, comm, double_buffering=False)\n elif config['optimizer'] == 'Adabound':\n from my_optimizer.adabound import Adam as Adabound\n optimizer = Adabound(alpha=config['learning_rate'], adabound=True, amsgrad=True,\n weight_decay_rate=config['weight_decay_rate'])\n optimizer = chainermn.create_multi_node_optimizer(optimizer, comm, double_buffering=False)\n optimizer.setup(model)\n val_interval = 1, 'epoch'\n log_interval = 1, 'epoch'\n updater = training.StandardUpdater(train_iter, optimizer, device=device, converter=d.get_converter())\n trainer = training.Trainer(updater, (config['epoch'], 'epoch'), out=args.out)\n evaluator = GraphEvaluator(iterator=test_iter, target=model.predictor, device=device, converter=d.get_converter(),\n comm=comm, local_loss_func=local_loss_func, global_loss_func=global_loss_func,\n name='val', config=config)\n evaluator = chainermn.create_multi_node_evaluator(evaluator, comm)\n trainer.extend(evaluator, trigger=val_interval)\n if comm.rank == 0:\n trainer.extend(extensions.dump_graph('main/loss'))\n trainer.extend(extensions.snapshot(), trigger=val_interval)\n trainer.extend(extensions.LogReport(trigger=log_interval))\n trainer.extend(extensions.PlotReport(['main/loss', 'val/main/loss'], 'epoch', file_name='loss.png'),\n trigger=val_interval)\n report_list = ['epoch', 'main/loss', 'val/main/loss']\n if config['global_mode']:\n report_list.extend(['main/global_loss', 'val/main/global_loss', 'val/main/global_pearson'])\n trainer.extend(extensions.PlotReport(['main/global_loss', 'val/main/global_loss'], 'epoch',\n file_name='global_loss.png'), trigger=val_interval)\n if config['local_mode']:\n report_list.extend(['main/local_loss', 'val/main/local_loss', 'val/main/local_mean_pearson'])\n if config['local_type'] == 'Classification':\n report_list.append('val/main/local_auc')\n trainer.extend(extensions.PlotReport(['val/main/local_auc'], 'epoch', file_name='local_auc.png'),\n trigger=val_interval)\n else:\n report_list.append('val/main/local_pearson')\n report_list.append('elapsed_time')\n trainer.extend(extensions.PrintReport(report_list), trigger=log_interval)\n trainer.extend(extensions.ProgressBar(update_interval=10))\n if args.resume:\n snap_list = [p for p in os.listdir(args.out) if 'snapshot' in p]\n snap_num = np.array([int(re.findall(\"[+-]?[0-9]+[\\.]?[0-9]*[eE]?[+-]?[0-9]*\", p)[0]) for p in snap_list])\n path = snap_list[np.argmax(snap_num)]\n path = os.path.join(args.out, path)\n if args.weight:\n obj_path = 'updater/model:main/predictor/'\n chainer.serializers.load_npz(path, model.predictor, obj_path)\n else:\n chainer.serializers.load_npz(path, trainer)\n if comm.rank == 0:\n protein_name_dict = d.get_protein_name_dict()\n out_path = Path(args.out)\n if not out_path.exists():\n out_path.mkdir(parents=True, exist_ok=True)\n np.savez(os.path.join(args.out, 'protein_name'), **protein_name_dict)\n f = open(os.path.join(args.out, 'lddt_config.json'), 'w')\n json.dump(config, f, ensure_ascii=False, indent=4, sort_keys=True, separators=(',', ': '))\n f.close()\n f = open(os.path.join(args.out, 'args.json'), 'w')\n json.dump(vars(args), f)\n f.close()\n if comm.rank == 0:\n print('train start!!!')\n trainer.run()\n\n\nif __name__ == '__main__':\n import multiprocessing as mp\n\n matplotlib.use('Agg')\n mp.set_start_method('forkserver', force=True)\n main()\n","sub_path":"source/training/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"532483726","text":"\"\"\"\n * Copyright (C) 2004 Evan Thomas\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\"\"\"\n\n\"\"\"\nReproduces Fig 6 from Thomas, et al Mossy fiber sprouting interacts with \nsodium channel mutations to increase dentate gyrus excitability, \nEpilepsia (2009)\n\"\"\"\n\nimport sys, os\n\nfrom p3 import *\nfrom time import clock\nfrom granule import *\nfrom support import *\n\ncomment = ''\nfor c in sys.argv[1:]:\n if c=='' or c==' ': continue\n comment = comment + ' %s' % c\napfn = 'ap%s' % comment\nsetAPfilename(apfn)\n\n#// define network size\nngcell = 500\nnbcell = 6\nnmcell = 15\nnhcell = 6\n\n#####################################\n#// NETWORK SPECIFICATION INTERFACE #\n#####################################\nNstate = 0\nNcmpt = 0\nGcell = []\nfor i in range(ngcell):\n c = Granule(useSlow=True)\n c.makesynapses()\n Nstate = Nstate + len(c.Y)\n Ncmpt = Ncmpt + len(c.compartments)\n Gcell.append(c)\nBcell = []\nfor i in range(nbcell):\n c = Basket(useSlow=True)\n c.makesynapses()\n Nstate = Nstate + len(c.Y)\n Ncmpt = Ncmpt + len(c.compartments)\n Bcell.append(c)\nMcell = []\nfor i in range(nmcell):\n c = Mossy(useSlow=True)\n c.makesynapses()\n Nstate = Nstate + len(c.Y)\n Ncmpt = Ncmpt + len(c.compartments)\n Mcell.append(c)\nHcell = []\nfor i in range(nhcell):\n c = Hipp(useSlow=True)\n c.makesynapses()\n Nstate = Nstate + len(c.Y)\n Ncmpt = Ncmpt + len(c.compartments)\n Hcell.append(c)\n\nduration = 400\nVhalfm = 0\nVhalfnf = 0\nVhalfhf = 0\nVhalfhs = 0\nVhalfns = 0\nVhalfha = 0\nVhalfma = 0\nVhalfmt = 0\nVhalfmn = 0\nVhalfml = 0\nAm = 1\nAh = 1\nsprout = 0\nGgaba = 1\nfor s in sys.argv[1:]:\n exec(s)\n \nNetwork = Gcell+Bcell+Mcell+Hcell\ns = 'Network with %d cells, %d compartments and %d state variables\\n'\nmessage_print(info, s % (len(Network), Ncmpt, Nstate))\n\nmodifyAll(Network=Network, Vhalfm=Vhalfm, Am=Am, Ah=Ah, \\\n Vhalfns=Vhalfns, Vhalfnf=Vhalfnf, \\\n Vhalfmt=Vhalfmt, \\\n Vhalfml=Vhalfml, \\\n Vhalfmn=Vhalfmn, \\\n Vhalfhf=Vhalfhf, \\\n Vhalfhs=Vhalfhs, \\\n Ggaba=Ggaba, \\\n Vhalfma=Vhalfma, Vhalfha=Vhalfha, \\\n )\n\nmessage_print(info, 'Making connections.\\n')\nexecfile('conx_sprout.py')\n \n###############\n# Run options #\n###############\ngd = GD()\ngd.duration = duration\ngd.tolerance = 1e-3\ngd.minStep = 0.05\ngd.network = Network\ngd.ap_handler = ap_print\ngd.trace_handler = trace_print\ngd.endWindow_handler = TimeTicker\ngd.stepTrace_handler = None\ngd.dumpCell_handler = dumpcell\n\n#######\n# Run #\n#######\ntry:\n start = clock()\n message_print(info, 'Starting run.\\n')\n parplex(gd)\n message_print(info, 'made it in %fs\\n' % (clock()-start))\nexcept ParplexRuntimeError:\n (e, v) = sys.exc_info()[:2]\n message_print(fatal, 'Caught ParplexRuntimeError: %s\\n' % v)\n dumpcell(e.currentCell, fatal)\n message_print(fatal, 'Didn\\'t make it\\n')\n sys.exit(0)\n\n#try:\n# from py2mat import Matwrap\n# m = Matwrap()\n# m.closeOnDel = False\n# m.write('cd \\'' + os.getcwd() + '\\'')\n# m.write('figure;traceplot(\\'%s.dat\\');\\n' % trfn)\n# m.write(\"legend('Granule', 'Basket', 'Mossy', 'HIPP');\\n\")\n# m.write('title(\\'%s\\')\\n' % comment)\n# m.write('figure;raster(\\'%s.dat\\');\\n' % apfn)\n# m.write('title(\\'%s\\')\\n' % comment)\n#except:\n# pass\n","sub_path":"sprout_run.py","file_name":"sprout_run.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"322836442","text":"\"\"\"\nCommon functions for tests\n\"\"\"\nfrom __future__ import annotations\n\n__author__ = \"Dan Gunter \"\n__date__ = \"10/29/13\"\n\n# Stdlib\nimport logging\nimport os\n\nimport pymongo\n\n# Third-party\nfrom mongomock import MongoClient\n\n# Package\nfrom pymatgen.db.query_engine import QueryEngine\n\n_log = logging.getLogger(\"pymatgen.db.tests\")\n\nTEST_FILES_DIR = os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n \"..\",\n \"..\",\n \"..\",\n \"test_files\",\n)\n\n\ndef has_mongo():\n \"\"\"Determine if MongoDB is up and usable\"\"\"\n if os.environ.get(\"MP_FAKEMONGO\"):\n mongo = False\n else:\n try:\n pymongo.MongoClient()\n mongo = True\n except:\n mongo = False\n return mongo\n\n\nclass MockQueryEngine(QueryEngine):\n \"\"\"Mock (fake) QueryEngine, unless a real connection works.\n You can disable the attempt to do a real connection\n by setting MP_FAKEMONGO to anything\n \"\"\"\n\n def __init__(\n self,\n host=\"127.0.0.1\",\n port=27017,\n database=\"vasp\",\n user=None,\n password=None,\n collection=\"tasks\",\n aliases_config=None,\n default_properties=None,\n ):\n if has_mongo():\n try:\n QueryEngine.__init__(\n self,\n host=host,\n port=port,\n database=database,\n user=user,\n password=password,\n collection=collection,\n aliases_config=aliases_config,\n default_properties=default_properties,\n )\n _log.warning(f\"Connected to real MongoDB at {host}:{port}\")\n return # actually connected! not mocked..\n except:\n _log.debug(f\"Connection to real MongoDB at {host}:{port} failed. This is normal; using mock.\")\n self.connection = MongoClient(host, port)\n self.db = self.connection[database]\n self._user, self._password = user, password\n self.host = host\n self.port = port\n self.database_name = database\n # colllection name is now a @property. the setter will set \"self.collection\" internally\n self.collection_name = collection\n self.set_aliases_and_defaults(aliases_config=aliases_config, default_properties=default_properties)\n","sub_path":"pymatgen/db/tests/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"619836318","text":"import openpyxl\nfrom selenium import webdriver\nimport urllib.request\nimport urllib.parse\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup as soups\n\ndef search_selenium(search_name, search_limit) :\n search_url = \"https://www.google.com/search?q=\" + urllib.parse.quote_plus(search_name) + \"&hl=ko&tbm=isch\"\n \n browser = webdriver.Chrome('C:/Users/home/chromedriver.exe')\n browser.get(search_url)\n \n image_count = len(browser.find_elements_by_tag_name(\"img\"))\n \n print(search_name + \"로드된 이미지 개수 : \", image_count)\n\n browser.implicitly_wait(2)\n \n\n for i in range( image_count ) :\n image = browser.find_elements_by_tag_name(\"img\")[i]\n image.screenshot(\"C:/Users/home/milk/\" + str(search_name) + str(i) + \".png\")\n\n browser.close()\n \n \nfilename = \"milk.xlsx\"\nmilk = openpyxl.load_workbook(filename)\nsheet = milk.worksheets[0]\n\n\nif __name__ == \"__main__\" :\n for row in sheet.rows:\n brand = row[0].value\n print(brand)\n check=0\n for i in row:\n if check == 0:\n check=1\n elif i.value == None:\n break\n else:\n search_limit=10\n search_name = brand + \" \" + (i.value)\n #print(plusUrl)\n search_selenium(search_name, search_limit)\n \n \n","sub_path":"crawl_milk.py","file_name":"crawl_milk.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"424555051","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nScript Header\n\n$Id: US27387\n\nCopyright (c) 2016-2017 Cisco Systems, Inc.\n\nName:\n bevCC27387_3pcc_BS_Video_IOT_Interop_247_Call_Termination.py\n\nPurpose:\n This test case verifies the ability of the DUT to receive video call.\n\nAuthor:\n Vishnu Prasad B (vishnpra@cisco.com)\n\nReferences:\n BW-SIPPhone-InteropTestPlan-R22.0\n\nDescription:\n Originate a video call from BroadWorks Phone 2(User A) to the Phone 1(DUT).\n Answer the call.\n\nTest bed requirement:\n 1: Two 3pcc BEV phones\n 2. Phones should be registered successfully before running the script\n\nTest Steps:\n 1. Phone 2 dials Phone 1.\n 2. Phone 1 answers the call, video call is established.\n 3. Phone 2 hangs up\n\nVerify:\n 1. Phone 2 rings and Phone 1 hears audible ring back.\n 2. Phone 2 receives the call.\n 3. Video Call is established.\n 4. Call is released from Phone 1.\n\nKnown Bugs:\n\"\"\"\n\nimport tng\nimport logging\nfrom tng.api import concurrent\nfrom tng_sl.device.endpoint.synergylite.synergylite_3pcc_extended \\\n import wait_for_ccapi_call_states\nfrom tng_sl.contrib.setup_helper import SetupHelpersTestCase\nfrom tng_sl.contrib.mpp.phone_config_helper import PhoneConfigHelper\nfrom tng_sl.contrib.mpp.phone_line_reg_helper import PhoneLineRegHelper\nfrom tng_sl.contrib.mpp.tshark_helper import TsharkHelper\n\nlog = logging.getLogger('VideoCallTermination')\n\n\nclass VideoCallTermination(SetupHelpersTestCase, tng.api.TestCase):\n helpers = (PhoneConfigHelper, PhoneLineRegHelper, TsharkHelper)\n helper_num_devices = 2\n\n def setUp(self):\n log.info(\"Start of setUp\")\n concurrent([\n self.oPhone1.ui.set_web_parameter_http,\n self.oPhone2.ui.set_web_parameter_http],\n Codec_Enable1=['Ext 1', 'H264 BP0 Enable', 1],\n Codec_Enable2=['Ext 1', 'H264 BP1 Enable', 1],\n Codec_Enable3=['Ext 1', 'H264 HP Enable', 1])\n log.info(\"End of setUp\")\n\n def test_video_call_termination(self):\n log.info(\"Start of video call termination\")\n log.info(\"Phone B dials Phone A's number: {}\".format(self.user_id1))\n self.oPhone2.ccapi.dial('null', self.user_id1, '', 1, 0, 1)\n\n # check phoneA ringout status and PhoneB ringing status\n wait_for_ccapi_call_states(\n self.devices, (\"RINGING\", \"PROCEEDING\"), timeout=20)\n\n log.info(\"Phone A answers the call\")\n self.oPhone1.ccapi.accept('0000')\n # check phoneA and PhoneB connected status\n wait_for_ccapi_call_states(\n self.devices, (\"CONNECTED\", \"CONNECTED\"), timeout=20)\n\n log.info(\"Phone B hangs up the call\")\n self.oPhone2.ccapi.hangUp('0000')\n # check Phone A and Phone B idle state\n wait_for_ccapi_call_states(self.devices, (\"IDLE\", \"IDLE\"))\n log.info(\"End of video call termination\")\n\n\ndef main():\n tng.api.runner()\n\nif __name__ == \"__main__\":\n tng.run(main)\n","sub_path":"bev/IOT/bevCC27387_3pcc_BS_Video_IOT_Interop_247_Call_Termination.py","file_name":"bevCC27387_3pcc_BS_Video_IOT_Interop_247_Call_Termination.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"230827407","text":"# -*- coding: utf-8 -*-\n\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy import PrimaryKeyConstraint, ForeignKey\n\n\nfrom fr.tagc.uorf.core.util.sql.Base import BasePRO\nfrom fr.tagc.uorf.core.util.sql.SQLCollationManager import SQLCollationManager\n\n\n## CellContext\n# ===========\n#\n# Each CellContext contains:\n# - orftranscriptasso_id: Integer - The ORF-transcript association ID.\n# - cell_context: String - The cellular context.\n#\nclass CellContext( BasePRO ):\n \n __tablename__ = 'CellContext'\n \n orftranscriptasso_id = Column( Integer, \n ForeignKey( 'ORFTranscriptAsso.id', ondelete='CASCADE', onupdate='CASCADE' ) )\n cell_context = Column( String( 50, collation = SQLCollationManager.get_instance().get_db_collation() ), \n ForeignKey( 'CellContextCatalog.context', ondelete='CASCADE', onupdate='CASCADE' ) )\n\n # Define the composite primary key\n __table_args__ = (\n PrimaryKeyConstraint( 'orftranscriptasso_id', 'cell_context' ),\n )\n\n\n\n ## __eq__\n # ------\n #\n # Tests the equality between two instances of this class.\n # Two instances are considered equals if their \"primary key-like\" attributes \n # (i.e. the attributes with unique constraint) are all equals.\n #\n # @param other: CellContext - Another CellContext object to compare to this object.\n #\n # @return Boolean - Are this object and 'other' equal?\n #\n def __eq__( self, other ):\n \n # Check if other object is of the same class\n if ( type( other ) != type( self ) ):\n return False\n \n # Check if the two instances may be considered equal\n elif ( ( self.orftranscriptasso_id == other.orftranscriptasso_id )\n and ( self.cell_context == other.cell_context ) ):\n return True\n \n else:\n return False\n\n\n ## __hash__\n # --------\n #\n # Returns the hash value of a CellContext object.\n # The hash value of an instance is computed using its \"primary key-like\" attributes \n # (i.e. the attributes with unique constraint).\n #\n # @return the hash value of the CellContext object.\n #\n def __hash__( self ):\n \n return hash( ( self.orftranscriptasso_id, self.cell_context ) )\n ","sub_path":"06_src/fr/tagc/uorf/core/model/PRO/processed/CellContext.py","file_name":"CellContext.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"497813281","text":"class Wypożyczalnia_samochodowa():\n def __init__(self, nazwa):\n self.nazwa = nazwa\n self.lista_pojazdow = []\n\n def dodaj_pojazd(self, rodzaj, marka, numer_rejestracyjny, ilosc):\n if rodzaj == 'osobowy':\n self.lista_pojazdow.append(Samochod_osobowy(marka,numer_rejestracyjny,ilosc)) \n elif rodzaj == 'dostawczy':\n self.lista_pojazdow.append(Samochod_dostawczy(marka,numer_rejestracyjny,ilosc))\n\n def wyswietl_wszystkie(self):\n print(f'\"{self.nazwa}\"')\n licz = 0\n for x in self.lista_pojazdow:\n licz += 1\n print(f'{licz}. ',end='')\n print(x.wyswietl())\n\n def wyswietl_dostepne(self):\n print(f'\"{self.nazwa}\"')\n print('Pojazdy dostępne:')\n licz = 0\n for x in self.lista_pojazdow:\n if x.wypozyczony:\n continue\n else:\n licz += 1\n print(f'{licz}. ',end='')\n print(x.wyswietl())\n\n def wyswietl_niedostepne(self):\n print(f'\"{self.nazwa}\"')\n print('Pojazdy niedostępne:')\n licz = 0\n for x in self.lista_pojazdow:\n if x.wypozyczony:\n licz += 1\n print(f'{licz}. ',end='')\n print(x.wyswietl())\n else:\n continue\n\n def pozycz(self,numer_rejestracyjny):\n for x in self.lista_pojazdow:\n if x.numer_rejestracyjny == numer_rejestracyjny and (not x.wypozyczony):\n x.pozycz()\n \n def oddaj(self,numer_rejestracyjny, przejechane):\n for x in self.lista_pojazdow:\n if x.numer_rejestracyjny == numer_rejestracyjny and x.wypozyczony:\n x.oddaj()\n x.zmien_przebieg(przejechane)\n\n\nclass Pojazd():\n def __init__(self, marka, numer_rejestracyjny):\n self.marka = marka\n self.numer_rejestracyjny = numer_rejestracyjny\n self.przebieg = 0\n self.wypozyczony = False\n\n def pozycz(self):\n self.wypozyczony = True\n print(f'Wypożyczono: {self.numer_rejestracyjny}')\n\n def oddaj(self):\n self.wypozyczony = False\n print(f'Zwrócono: {self.numer_rejestracyjny}')\n\n def zmien_przebieg(self, wartosc):\n self.przebieg += wartosc\n\n def wyswietl(self):\n if self.wypozyczony:\n return f'{self.marka}, {self.numer_rejestracyjny}, Przebieg: {self.przebieg} km, Pojazd niedostępny'\n else:\n return f'{self.marka}, {self.numer_rejestracyjny}, Przebieg: {self.przebieg} km, Pojazd dostępny'\n\n\nclass Samochod_osobowy(Pojazd):\n def __init__(self, marka, numer_rejestracyjny, ilosc):\n self.liczba_miejsc = ilosc\n super().__init__(marka, numer_rejestracyjny)\n\n def wyswietl(self):\n tekst = 'Samochód osobowy: ' + Pojazd.wyswietl(self) + f', Ilość miejsc: {self.liczba_miejsc}'\n return tekst\n\n\nclass Samochod_dostawczy(Pojazd):\n def __init__(self, marka, numer_rejestracyjny, ilosc):\n self.ladownosc = ilosc\n super().__init__(marka, numer_rejestracyjny)\n\n def wyswietl(self):\n tekst = 'Samochód dostawczy: ' + Pojazd.wyswietl(self) + f', Udźwig: {self.ladownosc} t'\n return tekst\n \n\nsklep = Wypożyczalnia_samochodowa('Fajna nazwa')\nsklep.dodaj_pojazd('osobowy', 'Audi', 'Kr 34346', 5)\nsklep.dodaj_pojazd('osobowy', 'BMW', 'Kr 99123', 4)\nsklep.dodaj_pojazd('osobowy', 'Volvo', 'Kr 00800', 7)\nsklep.dodaj_pojazd('dostawczy', 'Honda', 'Kr 66555', 15)\nsklep.dodaj_pojazd('dostawczy', 'Opel', 'Kr 11000', 8)\nsklep.wyswietl_wszystkie()\nsklep.pozycz('Kr 34346')\nsklep.pozycz('Kr 66555')\nsklep.wyswietl_dostepne()\nsklep.oddaj('Kr 34346', 950)\nsklep.wyswietl_niedostepne()\nsklep.wyswietl_dostepne()","sub_path":"07-ObjectOrientedProgramming/07.18..py","file_name":"07.18..py","file_ext":"py","file_size_in_byte":3778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"32456679","text":"\nfrom operator import itemgetter\nDATA_DIR = 'text-output/'\nfname = DATA_DIR+'wiki-perfectx.txt'\n\ndef find_waterloo(dictionary):\n\treturn dictionary[\"waterloo\"]\n\n\n\n\n\nwith open(fname) as f:\n content = f.readlines()\n# you may also want to remove whitespace characters like `\\n` at the end of each line\n\nwordcount_dict = {}\n\n#content = [x for x in content]\nfor line in content:\n\tkey, val = line.split(\"\\t\")\n\twordcount_dict[key] = int(val.rstrip())\n\nprint(sorted(wordcount_dict.items(), key=itemgetter(1), reverse=True)[:10])\n\nprint(len(wordcount_dict))\n#print(find_waterloo(wordcount_dict))\n\n\n","sub_path":"top_10.py","file_name":"top_10.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"622803719","text":"import cv2\nimport imutils\nimport numpy as np\n\ndef detectPedestrians(imageName):\n # Initializing the HOG person\n # detector\n hog = cv2.HOGDescriptor()\n hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())\n # Reading the Image\n image = cv2.imread(imageName)\n image = imutils.resize(image, width=min(400, image.shape[1]))\n\n # Detecting all the regions in the\n # Image that has a pedestrians inside it\n (regions, _) = hog.detectMultiScale(image, winStride=(4, 4), padding=(8, 8), scale=1.1)\n\n # Drawing the regions in the Image\n for (x, y, w, h) in regions:\n cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)\n\n cv2.imwrite('detected_' + imageName, image)\n\ndetectPedestrians('1.jpg')\ndetectPedestrians('2.jpg')\ndetectPedestrians('3.jpg')\n","sub_path":"lab6/lab6.py","file_name":"lab6.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"212655023","text":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nimport numpy as np\n\n#1. 데이터\nx = np.array([1,2,3])\ny = np.array([1,2,3])\n\n#2. 모델 구성\nmodel = Sequential()\nmodel.add(Dense(1, input_dim=1)) \n# model.add(Dense(output_dim=1, input_dim=1)) \n#3. 컴파일, 훈련\nmodel.compile(loss='mse', optimizer='adam') # 컴퓨터가 이해하도록 컴파일\n\nmodel.fit(x, y, epochs=1000, batch_size=1) # 훈련시키기\n\n#4. 평가, 예측\nloss = model.evaluate(x, y)\nprint('loss : ', loss)\n\nresult = model.predict([4])\nprint('4의 예측값 : ', result)\nmodel.summary()","sub_path":"keras01_1.py","file_name":"keras01_1.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"423368530","text":"__author__ = \"Eric Niyigaba\"\n__NetID__ = \"ericniyigaba\"\n__GitHubID__ = \"ericniyigaba\"\n__SelfGrade__ = \"4\"\n__Challenge__ = \"4\"\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\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\nprint(\"Sequence 1 Mean: \",numpy.mean(Sequence1))\nprint(\"Sequence 1 Variance: \",numpy.var(Sequence1))\nprint(\"Sequence 2 Mean: \",numpy.mean(Sequence2))\nprint(\"Sequence 2 Variance: \",numpy.var(Sequence2))\nprint(\"Sequence 3 Mean: \",numpy.mean(Sequence3))\nprint(\"Sequence 3 Variance: \",numpy.var(Sequence3))\nprint(\"Covariance of Sequences 1 and 2: \",numpy.cov(Sequence1,Sequence2))\n\npylab.figure()\nn, bins, patches = pylab.hist(Sequence1, 1000, normed=1, histtype='stepfilled')\npylab.setp(patches, 'facecolor', 'k', 'alpha', 0.75)\n\npylab.figure()\nn, bins, patches = pylab.hist(Sequence2, 1000, normed=1, histtype='stepfilled')\npylab.setp(patches, 'facecolor', 'g', 'alpha', 0.75)\n\npylab.figure()\nn, bins, patches = pylab.hist(Sequence3, 1000, normed=1, histtype='stepfilled')\npylab.setp(patches, 'facecolor', 'r', 'alpha', 0.75)\n\npylab.show()\n\n\"\"\"\nWhat is the type of random variable `Sequence1`?\nSequence 1 is a gaussian random variable\n\nWhat is its mean and variance?\nMean: 0\nVariance: 1\n\nWhat is the type of random variable `Sequence2`?\nSequence 2 is a gaussian random variable\n\nWhat is its mean and variance?\nMean: 0\nVariance: 1\n\nWhat is the type of random variable `Sequence3`?\nSequence 3 is an exponential random variable\n\nWhat is its mean and variance?\nMean: 2\nVariance: 4\n\nWhat is the empirical covariance between `Sequence1` and `Sequence2`?\nEmpirical Covariance: 0\nDo you think they are independent? Justify your answer.\nYes, because the covariance of two random variables for example X and Y is equivalent to\ncovariance of X and Y = E[XY] - E[X]E[Y] and since the covariance is 0, then\nE[XY] = E[X]E[Y] and thus the two random variables Sequence1 and\nSequence 2 are independent.\n\"\"\"\n\n","sub_path":"Students/ericniyigaba/4challenge.py","file_name":"4challenge.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"341397630","text":"import requests\n\ndef price():\n url = 'http://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'\n params = {\n 'start' : '1',\n 'limit' : '100',\n 'convert' : 'USD'\n }\n headers = {\n 'accept' :'application/json',\n 'X-CMC_PRO_API_KEY': '002eb6c7-22c2-41b1-9fdd-d2bf5375da4e'\n }\n\n r = requests.get(url = url , params = params, headers = headers).json()\n\n bitcoin = r['data'][0]\n\n price = round(bitcoin['quote']['USD']['price'],2)\n return price\n","sub_path":"user/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"170278491","text":"import logging\nfrom apps import App, action\nfrom scapy.sendrecv import sniff\nfrom scapy.utils import wrpcap\nimport datetime\nimport os\n\nlogger = logging.getLogger(__name__)\n\n\n@action\ndef capture(filename=None, timeout=None, count=0, interface=None, packet_filter=None, gz=True):\n \"\"\"\n Basic self contained function\n \"\"\"\n if timeout is None and count == 0:\n return 'Either timeout or count must be specified', 'InvalidInput'\n if not filename:\n filename = str(datetime.datetime.utcnow())\n filename = filename.replace(':', '-')\n filename = filename.replace('.', '-')\n filename += '.pcap'\n path = os.path.join('.', 'apps', 'Pcap', 'data')\n if not os.path.exists(path):\n os.mkdir(path)\n filename = os.path.join(path, filename)\n else:\n dirname = os.path.dirname(filename)\n if dirname and not os.path.exists(dirname):\n os.mkdir(dirname)\n if not filename.endswith('.pcap'):\n filename += '.pcap'\n args = {}\n if timeout is not None:\n args['timeout'] = timeout\n if count is not None:\n args['count'] = count\n if interface:\n args['iface'] = interface\n if packet_filter:\n args['filter'] = packet_filter\n print(args)\n packets = sniff(**args)\n print(filename)\n\n wrpcap(filename, packets, gz=gz)\n return filename\n\n\n\n","sub_path":"Pcap/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"25674276","text":"def regionsBySlashes(grid):\n \"\"\"\n :type grid: List[str]\n :rtype: int\n \"\"\"\n\n def union(a, b, res):\n new_cluster = min(res[a], res[b])\n res[a] = new_cluster\n res[b] = new_cluster\n\n res = {}\n for i in range(len(grid) * len(grid)):\n res[i] = i\n\n for item in grid:\n for one in item:\n if one == '/':\n union()\n\n\n\nif __name__ == '__main__':\n regionsBySlashes([\"/\\\\\", \"\\\\/\"])\n","sub_path":"coding/code_python/用斜线分割正方形_并查集.py","file_name":"用斜线分割正方形_并查集.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"311729226","text":"#!/usr/bin/env python\n# coding: utf-8\nimport urllib2\nimport logging\n\nfrom bottle import HTTPError\n\n\nlogger = logging.getLogger(\"pypiserver\")\n\n\ndef validate_package_name(name, fallback_url):\n if not name == name.lower():\n logger.warning(\"package name may not contains upper case: %s\" % name)\n raise HTTPError(400, output=\"package name may not contains uppercase\")\n if existed_package_name(fallback_url, name):\n logger.warning(\"package name already exists: %s\" % name)\n raise HTTPError(400, output=\"package already exists\")\n\n\ndef validate_package_version(version):\n pass\n\n\ndef existed_package_name(fallback_url, package_name):\n package_url = \"{0}/{1}\".format(fallback_url, package_name)\n try:\n req = urllib2.Request(url=package_url)\n urllib2.urlopen(req, timeout=2)\n except urllib2.HTTPError as e:\n if e.code == 404:\n return False\n return True\n","sub_path":"pypiserver/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"450454113","text":"# Copyright © 2020 Novobi, LLC\n# See LICENSE file for full copyright and licensing details.\nfrom odoo import api, fields, models, _\n\n\nclass PurchaseOrder(models.Model):\n _inherit = \"purchase.order\"\n\n inter_company_sale_order_id = fields.Many2one(\n 'sale.order', string='Created Sale Order', readonly=True, copy=False,\n help='Origin Sale Order on Inter Company')\n auto_sale_order_id = fields.Many2one(\n 'sale.order', string='Created by Sale Order',\n help='Destination Sale Order on Inter Company')\n delivery_picking_ids = fields.One2many('stock.picking', 'purchase_order_for_delivery',\n string='Delivery Materials', store=True, copy=False,\n compute='_compute_delivery_picking_ids')\n delivery_picking_count = fields.Integer(string='Delivery Materials Count', default=0, store=True, copy=False,\n compute='_compute_delivery_picking_ids')\n\n @api.depends('picking_ids')\n def _compute_delivery_picking_ids(self):\n stock_picking_env = self.env[\"stock.picking\"]\n input_location = self.env.ref(\"pcp_base.stock_location_input_wfp\")\n delivery_picking_type_wfp = self.env.ref(\"pcp_base.stock_picking_type_delivery_wfp\")\n for order in self:\n receipt_orders = order.picking_ids.filtered(lambda p: p.location_dest_id.id == input_location.id)\n delivery_orders = stock_picking_env.search([\n ('origin', 'in', receipt_orders.mapped('name')),\n ('picking_type_id', '=', delivery_picking_type_wfp.id)\n ])\n order.write({\n 'delivery_picking_ids': [(6, 0, delivery_orders.ids)],\n 'delivery_picking_count': len(delivery_orders.ids)\n })\n\n def inter_company_create_sale_order(self, company):\n \"\"\"\n Override function to write inter_company_sale_order_id field on SO.\n\n Create a Sales Order from the current PO (self)\n Note : In this method, reading the current PO is done as sudo, and the creation of the derived\n SO as intercompany_user, minimizing the access right required for the trigger user.\n :param company : the company of the created PO\n :rtype company : res.company record\n \"\"\"\n self = self.with_context(force_company=company.id)\n SaleOrder = self.env['sale.order']\n SaleOrderLine = self.env['sale.order.line']\n\n # find user for creating and validation SO/PO from partner company\n intercompany_uid = company.intercompany_user_id and company.intercompany_user_id.id or False\n if not intercompany_uid:\n raise Warning(_('Provide at least one user for inter company relation for % ') % company.name)\n # check intercompany user access rights\n if not SaleOrder.with_user(intercompany_uid).check_access_rights('create', raise_exception=False):\n raise Warning(_(\"Inter company user of company %s doesn't have enough access rights\") % company.name)\n\n for rec in self:\n # check pricelist currency should be same with SO/PO document\n company_partner = rec.company_id.partner_id.with_user(intercompany_uid)\n if rec.currency_id.id != company_partner.property_product_pricelist.currency_id.id:\n raise Warning(\n _('You cannot create SO from PO because sale price list currency is different than purchase price list currency.')\n + '\\n'\n + _('The currency of the SO is obtained from the pricelist of the company partner.')\n + '\\n\\n ({} {}, {} {}, {} {} (ID: {}))'.format(\n _('SO currency:'), company_partner.property_product_pricelist.currency_id.name,\n _('Pricelist:'), company_partner.property_product_pricelist.display_name,\n _('Partner:'), company_partner.display_name, company_partner.id,\n )\n )\n\n # create the SO and generate its lines from the PO lines\n # read it as sudo, because inter-compagny user can not have the access right on PO\n sale_order_data = rec.sudo()._prepare_sale_order_data(\n rec.name, company_partner, company,\n rec.dest_address_id and rec.dest_address_id.id or False)\n inter_user = self.env['res.users'].sudo().browse(intercompany_uid)\n sale_order = SaleOrder.with_context(allowed_company_ids=inter_user.company_ids.ids).with_user(intercompany_uid).create(sale_order_data)\n # lines are browse as sudo to access all data required to be copied on SO line (mainly for company dependent field like taxes)\n for line in rec.order_line.sudo():\n so_line_vals = rec._prepare_sale_order_line_data(line, company, sale_order.id)\n # TODO: create can be done in batch; this may be a performance bottleneck\n SaleOrderLine.with_user(intercompany_uid).with_context(allowed_company_ids=inter_user.company_ids.ids).create(so_line_vals)\n\n # PC-186: Write inter_company_sale_order_id field on SO\n rec.inter_company_sale_order_id = sale_order\n\n # write vendor reference field on PO\n if not rec.partner_ref:\n rec.partner_ref = sale_order.name\n\n # Validation of sales order\n if company.auto_validation:\n sale_order.with_user(intercompany_uid).action_confirm()\n\n def check_create_inter_company_sale_order(self):\n self.ensure_one()\n # get the company from partner then trigger action of intercompany relation\n company_rec = self.env['res.company']._find_company_from_partner(self.partner_id.id)\n is_create_sale_order = False\n if company_rec and company_rec.applicable_on in ('purchase', 'sale_purchase') and (not self.auto_generated):\n is_create_sale_order = True\n\n return is_create_sale_order\n\n def _create_picking(self):\n \"\"\"\n Unreserve the picking when the picking created from PO that will create a new Inter company Sale Order\n \"\"\"\n res = super(PurchaseOrder, self)._create_picking()\n for order in self.sudo().filtered(lambda o: o.check_create_inter_company_sale_order() or o.get_inter_company_sale_order()):\n reserved_transfer = order.picking_ids.filtered(lambda p: p.state == 'assigned' and p.picking_type_code == 'incoming')\n if reserved_transfer:\n reserved_transfer.mapped('move_lines.move_line_ids').unlink()\n return res\n\n def get_inter_company_sale_order(self):\n self.ensure_one()\n return self.inter_company_sale_order_id or self.auto_sale_order_id or False\n\n def action_view_delivery_materials(self):\n action = self.env.ref('stock.action_picking_tree_all')\n result = action.read()[0]\n pick_ids = self.mapped('delivery_picking_ids')\n\n # choose the view_mode accordingly\n if not pick_ids or len(pick_ids) > 1:\n result['domain'] = \"[('id','in',%s)]\" % (pick_ids.ids)\n elif len(pick_ids) == 1:\n res = self.env.ref('stock.view_picking_form', False)\n form_view = [(res and res.id or False, 'form')]\n if 'views' in result:\n result['views'] = form_view + [(state, view) for state, view in result['views'] if view != 'form']\n else:\n result['views'] = form_view\n result['res_id'] = pick_ids.id\n return result\n","sub_path":"pcp_inter_company_rules/models/purchase_order.py","file_name":"purchase_order.py","file_ext":"py","file_size_in_byte":7640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"263495050","text":"from bottle import route, run, template, redirect, request\r\nimport sqlite3\r\n\r\ncon = sqlite3.connect(\"webchat.db\")\r\n\r\n@route(\"/\", method=\"GET\")\r\ndef home():\r\n sql = f\"SELECT * FROM Content\"\r\n result = con.execute(sql)\r\n return template(\"home\", content=result.fetchall())\r\n\r\n@route(\"/\", method=\"POST\")\r\ndef home():\r\n name = request.forms.name\r\n message = request.forms.message\r\n print(name, message)\r\n\r\n sql = f\"INSERT INTO Content (name, message) VALUES('{name}', '{message}')\"\r\n con.execute(sql)\r\n con.commit()\r\n \r\n redirect(\"/\")\r\n\r\nif __name__ == \"__main__\":\r\n run(host=\"0.0.0.0\", port=8080, debug=True, reloader=True)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"367555368","text":"import os\nimport time\nfrom os.path import isfile, join\nfrom datetime import datetime\n\nclass BIB_builder():\n def __init__(self):\n # folder to store BIBFRAME files\n self.source = 'Webapp/Files/Processing/BIBFRAME'\n if not os.path.exists(self.source):\n os.makedirs(self.source)\n # processing folder\n self.folder = 'Webapp/Files/Processing'\n if not os.path.exists(self.folder):\n os.makedirs(self.folder)\n\n def merger(self):\n f_name = ''\n output = '%s/Merged-file_%s.xml' %(self.folder, datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))\n with open(output, \"w+\") as merged_file:\n merged_file.write('')\n # for all files in the BIBFRAME folder\n for files in [files for files in os.listdir(self.source) if isfile(join(self.source, files))]:\n # check if it is a marc file\n if files.endswith('.xml'):\n f_name = f_name + '--__--__--' + str(files)\n file = join(self.source, files)\n with open(file, 'r') as source_file:\n for lines in source_file:\n merged_file.write(lines)\n source_file.close()\n merged_file.write('')\n merged_file.close()\n return (output, f_name)","sub_path":"metadata-wrangling/BIBFRAME/Converter/APP-WIP/Django-based/BIBFRAME_Converter/Webapp/Code/Classes/BIB_builder.py","file_name":"BIB_builder.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"9996139","text":"from tkinter import *\nfrom tkinter import messagebox\ndef checked(i) :\n global player\n button = list[i]\n c=0\n if button[\"text\"] != \" \" :\n return\n button[\"text\"] = player \n button[\"bg\"] = \"yellow\"\n\n c=rowchecker(i)\n if c==3:\n result(player)\n return\n c=colchecker(i)\n if c==3:\n result(player)\n return\n c=diagonalchecker(i)\n if c==3:\n result(player)\n return\n c=arcdiagonalchecker(i)\n if c==3:\n result(player)\n return\n \n if player == \"X\" :\n player = \"O\"\n button[\"bg\"] = \"yellow\"\n else :\n player = \"X\"\n button[\"bg\"] = \"lightgreen\"\n \ndef result(player):\n messagebox.showinfo(\"result\",\"Player \"+player+ \" WIN!!!\")\n window.destroy()\n return\ndef rowchecker(i):\n button=list[i]\n c=0\n for j in range(9):\n if(j//3==i//3):\n if(list[j][\"text\"]==button[\"text\"]):\n c+=1\n return c\n\ndef colchecker(i):\n button=list[i]\n global player\n c=0\n for j in range(9):\n if(j%3==i%3):\n if(list[j][\"text\"]==button[\"text\"]):\n c+=1\n return c\ndef diagonalchecker(i):\n button=list[i]\n global player\n c=0\n for j in range(9):\n if(j//3==j%3):\n if(list[j][\"text\"]==button[\"text\"]):\n c+=1\n return c\ndef arcdiagonalchecker(i):\n button=list[i]\n global player\n c=0\n for j in range(9):\n if((j//3)+(j%3)==2):\n if(list[j][\"text\"]==button[\"text\"]):\n c+=1\n return c\n\nwindow = Tk()\nplayer = \"X\"\nlist= []\n\nfor i in range(9) :\n b = Button(window, text=\" \", command=lambda k=i: checked(k))\n b.grid(row=i//3, column=i%3)\n list.append(b)\n\nwindow.mainloop()\n\n\n","sub_path":"tic-tac-toe.py","file_name":"tic-tac-toe.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"593773200","text":"__all__ = ['GeventSchedule']\n\nimport time\nimport threading\n\nimport schedule\nfrom BusinessCentralLayer.middleware.redis_io import *\nfrom BusinessCentralLayer.sentinel import noticer\nfrom BusinessLogicLayer.cluster import __task__\nfrom config import REDIS_SECRET_KEY, SINGLE_TASK_CAP, CRAWLER_SEQUENCE, ENABLE_COROUTINE, LAUNCH_INTERVAL, logger, \\\n ENABLE_DDT\n\n\n# FIXME\n# 本方案刻意限制了部署性能,请服务器资源阔绰的玩家自行使用APSchedule模块兼容协程部署任务\n# 资源阔绰定义:4xCPU,4G RAM\n# 加速版本的调度器将在未来版本开源\nclass GeventSchedule(object):\n def __init__(self, go: bool = ENABLE_COROUTINE, deploy_cluster=CRAWLER_SEQUENCE, cap=SINGLE_TASK_CAP,\n crontab=LAUNCH_INTERVAL):\n # 任务队列\n self.deploy_cluster = deploy_cluster\n\n # 协程加速\n self.go = go\n\n # 单机采集极限\n self.cap = cap\n\n # 任务间隔\n self.crontab = crontab\n\n # 接入集群\n self.rc = RedisClient()\n\n self.rc_len = dict(zip(self.deploy_cluster, [1] * 3))\n\n def push_task(self, task_name: str) -> bool:\n \"\"\"\n\n @param task_name:\n @return:\n \"\"\"\n\n # 输入参数的数据类型错误\n if not isinstance(task_name, str):\n logger.error(f'The input type is wrong({task_name})')\n return False\n\n # 输入的参数不在模型的权限范围中\n if task_name not in self.deploy_cluster:\n logger.error(f'Spelling error in input({task_name}),Please choose from {self.deploy_cluster}')\n return False\n\n try:\n # 判断缓冲队列是否已达单机采集极限\n task_name = task_name.lower()\n self.rc_len[f'{task_name}'] = self.rc.__len__(REDIS_SECRET_KEY.format(f'{task_name}'))\n logger.info(f'[TEST] ||正在检查({task_name}) 任务队列...')\n\n # 若已达或超过单机采集极限,则休眠任务\n if self.rc_len[f\"{task_name}\"] >= self.cap:\n logger.debug(f'[SLEEP] || 任务队列已满 ({task_name}) ({self.rc_len[f\"{task_name}\"]}/{self.cap})')\n return True\n finally:\n # 无论队列是否已满,执行一次ddt\n self.ddt(class_=task_name)\n\n try:\n # 执行采集任务,通过self.go决定是否启动协程加速\n logger.info(f'[RUN] || ({task_name}) 采集任务启动')\n __task__.loads_task(task_name, self.go)\n\n # 判断任务是否完全失败,既单个类型链接的所有采集任务全部失败->Abnormal\n if self.rc.__len__(REDIS_SECRET_KEY.format(f'{task_name}')) < self.rc_len[f'{task_name}']:\n logger.error(f'[CRITICAL]Abnormal collection task({task_name})')\n else:\n return True\n except Exception as e:\n # 捕获未知错误\n logger.error(f'[ERROR]{self.__class__.__name__}({task_name}) crawler engine panic {e}')\n finally:\n # 单个类型的链接采集结束\n logger.success('[OVER] || 任务结束 {}({})'.format(self.__class__.__name__, task_name))\n\n @logger.catch()\n def run_check(self, class_: str) -> None:\n \"\"\"\n 启动任务:以非部署模式,传递参数\n @param class_:\n --传入的应是 config 中 crawler seq中的参数,如`v2ray`/`ssr`/`trojan`\n --确保操作的原子性,不要一次性传入多个参数,\n --正确的做法是通过<协程引擎>的消息队列形式驱动多任务\n --或使用for迭代work_seq顺序驱动多任务\n @return:\n \"\"\"\n __task__.loads_task(class_, self.go, startup=False, loads_=True)\n # self.push_task(class_)\n\n def ddt(self, class_: str = None) -> None:\n \"\"\"\n\n @param class_: subscribe type `ssr` or `v2ray` or `trojan` ...\n @return:\n \"\"\"\n if class_ is None:\n for item in self.deploy_cluster:\n threading.Thread(target=RedisDataDisasterTolerance().run, args=(item,)).start()\n elif isinstance(class_, str) and class_ in self.deploy_cluster:\n RedisDataDisasterTolerance().run(class_)\n else:\n logger.warning('{}.ddt() 输入参数错误,可能的原因为:类型错误/不在crawler_seq工作队列内'.format(self.__class__.__name__))\n\n def run(self) -> None:\n # logger.warning('This is a development server. Do not use it in a production deployment.')\n try:\n for task_name in self.deploy_cluster:\n try:\n schedule.every(self.crontab['action']).minutes.do(self.push_task, task_name=task_name)\n if ENABLE_DDT:\n schedule.every(self.crontab['refresh']).minutes.do(self.rc.refresh,\n key_name=REDIS_SECRET_KEY.format(task_name))\n logger.success(f\"START DDT -- {task_name}\")\n else:\n logger.warning(f'Not Authorized -- DDT({task_name})')\n logger.success(f\"START TASK -- {task_name}/crontab:{self.crontab['action']} minutes\")\n\n except schedule.IntervalError:\n logger.error('interval set error')\n\n self.crontab['action'] += 5\n\n while True:\n schedule.run_pending()\n time.sleep(1)\n\n except Exception as err:\n logger.exception('Exception occurred ||{}'.format(err))\n noticer.send_email(text_body='{}'.format(err), to='self')\n except KeyboardInterrupt as err:\n logger.stop('Forced stop ||{}'.format(err))\n\n\nif __name__ == '__main__':\n GeventSchedule().run()\n","sub_path":"V2RaycSpider1125/BusinessLogicLayer/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":5885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"324963169","text":"from collections import defaultdict, deque\nclass Solution(object):\n def minMutation(self, start, end, bank):\n \"\"\"\n :type start: str\n :type end: str\n :type bank: List[str]\n :rtype: int\n \"\"\"\n bank.append(start)\n possible = set([\"A\",\"C\",\"G\",\"T\"])\n #Find shortest path\n q = deque()\n q.append(start)\n dist = 0\n distances = defaultdict(int)\n visited = set()\n visited.add(start)\n distances[start] = 0\n while len(q) != 0:\n node = q.popleft()\n dist = distances[node]\n visited.add(node)\n dist += 1\n for i in range(len(start)):\n for c in (possible):\n check = node[:i] + c + node[i+1:]\n if check == end:\n print(distances)\n return dist\n if check in bank and check not in visited:\n q.append(check)\n distances[check] = dist\n print(distances)\n return -1\n\n\ns = Solution()\nprint(s.minMutation(\"AACCGGTT\", \"AAACGGTA\",[\"AACCGGTA\",\"AACCGCTA\",\"AAACGGTA\"]))\n","sub_path":"MinimumGeneticMutation.py","file_name":"MinimumGeneticMutation.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"135653476","text":"\"\"\"\nFile: program.py\nAuthor: Khoa Le Tan Dang \nEmail: letan.dangkhoa@gmail.com\nGithub: dangkhoasdc\nDescription: The main program of automatic counting of cells\n\"\"\"\n\nimport sys\nimport argparse\nfrom hed_bilateral import HedBilateralFilter\nfrom segment_hist import SegmentStage\nfrom cellcounting.db import allidb\nfrom cellcounting.fw import LocalFeatureFramework\nfrom cellcounting.features import SIFTFeature\nfrom cellcounting.classifier import svm\n\n\nif __name__ == '__main__':\n try:\n ftrain = sys.argv[1]\n ftest = sys.argv[2]\n except:\n ftrain = \"train/allidb1_1.txt\"\n ftest = \"test/allidb1_1.txt\"\n\n filter_kernel = (7, 7)\n sigma_color = 11.0\n preprocessor = HedBilateralFilter(filter_kernel, sigma_color)\n segmentation = SegmentStage(10)\n db = allidb.AllIdb()\n sift_feature = SIFTFeature()\n svm_clf = svm.SVM()\n framework = LocalFeatureFramework(db,\n preprocessor,\n segmentation,\n sift_feature,\n svm_clf)\n\n\n file_train = open(ftrain, \"r\")\n row_lst = [line.strip() for line in file_train.readlines()]\n file_train.close()\n\n image_lst = [line+\".jpg\" for line in row_lst]\n loc_lst = [allidb.get_true_locs(line+\".xyc\", db.scale_ratio) for line in row_lst]\n\n file_test = open(ftest, \"r\")\n row_lst = [line.strip() for line in file_test.readlines()]\n file_test.close()\n\n test_image_lst = [line+\".jpg\" for line in row_lst]\n test_loc_lst = [allidb.get_true_locs(line+\".xyc\", db.scale_ratio) for line in row_lst]\n\n framework.train(image_lst, loc_lst, \"dict\")\n for im, loc in zip(test_image_lst, test_loc_lst):\n framework.test(im, loc)\n\n","sub_path":"program_localfeature.py","file_name":"program_localfeature.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"314895123","text":"from rest_framework import serializers\nfrom index.models import Project, Manifest\n\n\nclass ProjectSerializer(serializers.ModelSerializer):\n def to_representation(self, instance):\n data = super(ProjectSerializer, self).to_representation(instance)\n data['image_bg'] = instance.get_image()\n return data\n\n class Meta:\n model = Project\n fields = ('id',\n 'title',\n 'subtitle',\n 'abstract',\n 'content',\n 'category',\n 'tags',\n 'image',\n 'date',\n 'date_modified',\n 'place',\n 'involved',\n 'sources',\n 'artifacts',)\n\n\nclass ManifestSerializer(serializers.ModelSerializer):\n class Meta:\n model = Manifest\n fields = ('id',\n 'intro',\n 'field1',\n 'field2',\n 'field3',\n 'code1',\n 'code2',\n 'code3',\n 'code',\n 'css',)\n","sub_path":"index/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"179720849","text":"# pylint:disable=unused-variable\n# pylint:disable=unused-argument\n# pylint:disable=redefined-outer-name\n\n\nimport pytest\nfrom servicelib.aiohttp.application import create_safe_application\nfrom servicelib.aiohttp.client_session import APP_CLIENT_SESSION_KEY\nfrom simcore_service_webserver._meta import api_version_prefix\nfrom simcore_service_webserver.application_config import load_default_config\nfrom simcore_service_webserver.catalog import (\n is_service_responsive,\n setup_catalog,\n to_backend_service,\n)\nfrom simcore_service_webserver.rest import APP_OPENAPI_SPECS_KEY, load_openapi_specs\nfrom yarl import URL\n\n\n@pytest.fixture\ndef client(loop, aiohttp_client, monkeypatch):\n monkeypatch.setenv(\"WEBSERVER_DEV_FEATURES_ENABLED\", \"1\")\n\n cfg = load_default_config()\n app = create_safe_application(cfg)\n\n app[APP_OPENAPI_SPECS_KEY] = load_openapi_specs()\n\n # __wrapped__ avoids app modules dependency checks\n setup_catalog.__wrapped__(app, disable_auth=True)\n\n # needs to start application ...\n yield loop.run_until_complete(aiohttp_client(app))\n\n\n@pytest.fixture\ndef mock_api_calls_to_catalog(client, mocker):\n client_session = client.app[APP_CLIENT_SESSION_KEY]\n\n class MockClientSession(mocker.MagicMock):\n async def __aenter__(self):\n # Mocks aiohttp.ClientResponse\n # https://docs.aiohttp.org/en/stable/client_reference.html#aiohttp.ClientResponse\n resp = mocker.Mock()\n resp.json.return_value = {}\n\n resp.status = 200\n return resp\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n pass\n\n mock = mocker.Mock(return_value=MockClientSession())\n client_session.get = mock\n client_session.post = mock\n client_session.request = mock\n yield mock\n\n\ndef test_url_translation():\n front_url = URL(\n f\"https://osparc.io/{api_version_prefix}/catalog/dags/123?page_size=6\"\n )\n\n rel_url = front_url.relative()\n assert rel_url.path.startswith(f\"/{api_version_prefix}/catalog\")\n\n api_target_origin = URL(\"http://catalog:8000\")\n api_target_url = to_backend_service(rel_url, api_target_origin, \"v5\")\n\n assert str(api_target_url) == \"http://catalog:8000/v5/dags/123?page_size=6\"\n\n\ndef test_catalog_routing(client):\n assert any(client.app.router.resources()), \"No routes detected?\"\n\n for resource in client.app.router.resources():\n assert resource.canonical.startswith(f\"/{api_version_prefix}/catalog\")\n\n\n# TODO: auto-create calls from openapi specs together with expected responses\n# TODO: this test shall simply check that Web API calls are redirected correctly\n@pytest.mark.skip(reason=\"DEV\")\nasync def test_catalog_api_calls(client, mock_api_calls_to_catalog):\n client_session = client.app[APP_CLIENT_SESSION_KEY]\n\n assert await is_service_responsive(client.app)\n mock_api_calls_to_catalog.assert_called_once()\n\n # from .login.decorators import login_required\n v = api_version_prefix\n\n # create resource\n data = {} # TODO: some fake data\n res = await client.post(f\"/{v}/catalog/dags\", json=data)\n assert res.status == 201\n\n # list resources\n res = await client.get(f\"/{v}/catalog/dags\")\n assert res.status == 200\n\n # get resource\n dag_id = 0\n res = await client.get(f\"/{v}/catalog/dags/{dag_id}\")\n assert res.status == 200\n\n # replace resource\n new_data = {} # TODO: some fake data\n res = await client.put(f\"/{v}/dags/{dag_id}\", json=new_data)\n assert res.status == 200\n\n # update resource\n patch_data = {} # TODO: some patch fake\n res = await client.patch(f\"/{v}/dags/{dag_id}\", json=patch_data)\n assert res.status == 200\n\n # delete\n res = await client.delete(f\"/{v}/dags/{dag_id}\")\n assert res.status == 204\n","sub_path":"services/web/server/tests/unit/isolated/test_catalog_setup.py","file_name":"test_catalog_setup.py","file_ext":"py","file_size_in_byte":3776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"523111192","text":"from matplotlib import pyplot as plt\n\n# Data to plot\nlabels = 'Java' , 'Python', 'Php', 'JavaScript' , 'C#', 'C++'\nsizes = [17.6,22.2,8.8,8,.7,6.7]\ncolors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue','red' , 'blue']\nexplode = (0.1, 0, 0, 0 , 0 ,0) # explode 1st slice\n\n# Plot\nplt.pie(sizes, explode=explode, labels=labels, colors=colors,\nautopct='%1.1f%%', shadow=True, startangle=140)\n\nplt.axis('equal')\nplt.show()","sub_path":"Assignment 12/q2.py","file_name":"q2.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"25102446","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# importCSV.py\n# \n# Copyright 2020 Luiz Oliveira\n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n# \n# \n\n\"\"\"\nData is imported from text files to be later processed and ploted\n\"\"\"\n\n# Libraries\nimport os\nimport re\nimport pandas as pd\n\n# Import Literature\nliteratureExp = pd.read_csv('dataset/fig4/fig4a.csv', header = 1, usecols=(0,1))\nliteratureExp.columns = ['(y-y0)/H','u/U']\nliteratureExp = literatureExp.dropna()\nliteratureLES = pd.read_csv('dataset/fig4/fig4a.csv', header = 1, usecols=(2,3))\nliteratureLES.columns = ['(y-y0)/H','u/U']\nmassLiterature = pd.read_csv('dataset/mass/mass.csv', header = 1)\nmassLiterature.columns = ['Vegetation Density', 'Td']\nmassLiterature.Td = massLiterature.Td * U / H\n\n# Tracer data\ntry:\n tracerData = pd.read_csv('preTreatment/tracerVolAve.dat',\n delimiter='\\t', header = 3)\n tracerData.columns = ['time', 'tracerVol']\n tracerData.tracerVol[0] = 1\n massTimeZero = tracerData.time[0]\n tracerData.time = tracerData.time - massTimeZero\nexcept:pass\n\n# Partial Tracer at Interface\ntry:\n interfaceTracer = dict()\n regions = ['Bottom', 'Middle', 'Top']\n for reg in regions:\n interfaceTracer[reg] = pd.read_csv('preTreatment/tracer'+reg+'.dat',\\\n delimiter='\\t', header = 4)\n interfaceTracer[reg].columns = ['time', 'tracer']\n interfaceTracer[reg].time = interfaceTracer[reg].time - massTimeZero\n Eraw = pd.read_csv('preTreatment/velocityInterface.dat', delimiter='\\t',\\\n header = 4)\n Eraw.columns = ['time', 'absVelInt']\n Eraw.time = Eraw.time - massTimeZero\n Eraw.absVelInt = Eraw.absVelInt/(2*H*L)\nexcept:pass\n\n# Generic Planes\nfiles = os.listdir('preTreatment')\n\n# Check for csv files\nrawFiles = list()\ncsvFiles = list()\ndatFiles = list()\nuniqueRaw = list()\nuniqueVar = list()\n\n# Removes ':' from file name\nfor item in files:\n if ':' in item: \n newname = item.split(':')[1]\n os.rename('preTreatment/'+item, 'preTreatment/'+newname)\n \nfiles = os.listdir('preTreatment')\n\nfor item in files:\n if re.search('.\\.raw', item):\n rawFiles.append(item)\n\nfor item in files:\n if re.search('.\\.csv', item):\n csvFiles.append(item)\n \nfor item in files:\n if re.search('.\\.dat', item):\n datFiles.append(item)\n\ncsvFiles.sort() \ndatFiles.sort() \nrawFiles.sort()\n\nfor item in rawFiles:\n try:\n plane = re.findall(\"_([\\d\\D]..)\", item)[0]\n variableName = re.split(\"_\", item)[0]\n if plane not in uniqueRaw:\n uniqueRaw.append(plane)\n if variableName not in uniqueVar:\n uniqueVar.append(variableName)\n except:continue\n\ndef cleanHeader(name):\n fh = open('preTreatment/'+name, \"rt\")\n data = fh.read()\n # data = re.sub(r':\\S+ ', r'', data)\n data = data.replace('# ', '')\n data = data.replace(' ', ' ') #removes double spacing\n \n fh.close()\n fh = open('preTreatment/'+name, \"wt\")\n fh.write(data)\n fh.close()\n\n# Import generated data\nfor item in rawFiles:\n for item2 in uniqueRaw:\n try:\n plane = re.findall(\"_([\\d\\D]..)\", item)[0]\n if plane == item2:\n cleanHeader(item)\n variableName = re.split(\"_\", item)[0]\n aux = pd.read_csv('preTreatment/'+item, sep=\" \", header=1,\n float_precision=\"high\",skipinitialspace=True)\n #if aux.isnull().values.any():continue\n try:\n if variableName not in locals():vars()[variableName] = aux\n else:\n vars()[variableName] = pd.concat([vars()[variableName],aux],\n ignore_index=True, axis=1)\n vars()[variableName] = vars()[variableName].dropna(axis=0, how='all')\n vars()[variableName] = vars()[variableName].dropna(axis=1, how='all')\n except:continue\n except:continue\n\nthickness = dict()\nfor item in csvFiles:\n try:\n thickness['raw'] = pd.read_csv('preTreatment/'+item, header=0,\\\n float_precision='high')\n if len(thickness['raw'].columns) == 8:\n thickness['raw'].drop(['Gradients_0','Gradients_1','Gradients_2'],\\\n axis=1, inplace=True)\n colNames = ['x', 'y', 'z', 'UMean_X', 'absGradient']\n thickness['raw'].columns = colNames\n \n del colNames\n except:continue\n\ntry:\n del aux, variableName, item2, plane\nexcept:pass\n\ndel files, item, rawFiles, csvFiles, reg\n","sub_path":"Post Processing/bin/importCSV.py","file_name":"importCSV.py","file_ext":"py","file_size_in_byte":5361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"511215423","text":"# -*- coding: utf-8 -*-\nimport os\n\nimport pandas as pd\nfrom sklearn.impute import SimpleImputer\nfrom pathlib import Path\n\n\ndef read_data(project_dir):\n # read raw train and test data and combine for ease of computation\n df_list = []\n for i in [\"train\", \"test\"]:\n fpath = os.path.join(project_dir, \"data\", \"raw\", f\"{i}.csv\")\n print(f\"Reading raw {i}ing data from {fpath}\")\n df = pd.read_csv(fpath)\n df[\"dataset\"] = i\n df_list.append(df)\n\n print(\"Returning combined dataset\")\n return pd.concat(df_list)\n\n\ndef impute_missing(df, project_dir):\n \"\"\"Impute missing values.\n There are 3 different strategies to handle different types of \"missingness\":\n 0 (for when NaN's are numeric and mean 0),\n 'None' (for when NaN's are categorical and mean 0), and\n most frequent (for when NaN's are categorical and sporadic).\n Lists corresponding to each of these are read in from ./imp/\n \"\"\"\n\n # impute missing values. Note that there are three types of\n imputers = {\n \"zero\": SimpleImputer(strategy=\"constant\", fill_value=0),\n \"freq\": SimpleImputer(strategy=\"most_frequent\"),\n \"none\": SimpleImputer(strategy=\"constant\", fill_value=\"None\"),\n }\n\n for strategy, imputer in imputers.items():\n fpath = os.path.join(project_dir, \"src\", \"data\", \"imp\", f\"{strategy}.txt\")\n print(f\"\\nReading imputation list from {fpath}\")\n cols = open(fpath).read().splitlines()\n for col in cols:\n n_missing = df[col].isna().sum()\n print(f\"Imputing {n_missing} values in {col} with {strategy}\")\n df[col] = imputer.fit_transform(df[[col]])\n\n return df\n\n\ndef write_data(project_dir, df):\n # write interim imputed data\n fpath = os.path.join(project_dir, \"data\", \"interim\", \"df.csv\")\n print(f\"\\nSaving imputed data to {fpath}\")\n df.to_csv(fpath, index=None)\n\n\ndef main():\n project_dir = Path(__file__).resolve().parents[2]\n df = read_data(project_dir)\n df = impute_missing(df, project_dir)\n write_data(project_dir, df)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/data/make_dataset.py","file_name":"make_dataset.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"228452799","text":"import sys\nfrom base64 import b64encode\n\nimport requests\nimport qdarkstyle\nfrom PyQt4 import QtGui\n\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Cipher import PKCS1_OAEP\n\n\nclass MainWindow(QtGui.QWidget):\n\n def __init__(self):\n super(MainWindow, self).__init__()\n self.SERVER = 'http://localhost:3000/'\n self.init_ui()\n\n def encrypt_text(self):\n self.error_label.clear()\n text = self.text_edit.toPlainText()\n\n try:\n if self.e_edit.text() == \"\" or self.n_edit.text() == \"\":\n self.get_pub_key()\n encryptor = PKCS1_OAEP.new(self.public_key)\n plain = bytes(text, 'utf-8')\n ciphertext = encryptor.encrypt(plain)\n\n url = self.SERVER + 'decrypt'\n query = {'public': self.public_key_str, 'crypto': b64encode(ciphertext)}\n requests.get(url, params=query)\n except Exception as err:\n error_text = str(err)[:50] + \"...\"\n self.error_label.setText(error_text)\n\n def get_pub_key(self):\n r = requests.get(self.SERVER + 'key')\n e, n = r.text.split(',')\n e, n = int(e, 16), int(n, 16)\n\n self.public_key = RSA.construct((n, e))\n self.public_key_str = r.text\n\n self.e_edit.setText(str(e))\n self.n_edit.setText(str(n))\n\n def init_ui(self):\n self.public_label = QtGui.QLabel('Public key:')\n\n self.e_label = QtGui.QLabel('E: ')\n self.e_edit = QtGui.QLineEdit()\n self.e_edit.setDisabled(True)\n\n self.n_label = QtGui.QLabel('N: ')\n self.n_edit = QtGui.QLineEdit()\n self.n_edit.setDisabled(True)\n\n self.text_edit = QtGui.QTextEdit()\n\n self.enc_button = QtGui.QPushButton('Send')\n self.enc_button.clicked.connect(self.encrypt_text)\n\n self.keys_button = QtGui.QPushButton('Get key')\n self.keys_button.clicked.connect(self.get_pub_key)\n\n self.error_label = QtGui.QLabel()\n self.error_label.setStyleSheet('color: red')\n\n grid = QtGui.QGridLayout()\n grid.setSpacing(10)\n\n grid.addWidget(self.public_label, 0, 0, 1, 2)\n grid.addWidget(self.e_label, 1, 0, 1, 1)\n grid.addWidget(self.e_edit, 1, 1, 1, 14)\n grid.addWidget(self.n_label, 2, 0, 1, 1)\n grid.addWidget(self.n_edit, 2, 1, 1, 14)\n\n grid.addWidget(self.text_edit, 3, 0, 3, 15)\n grid.addWidget(self.error_label, 6, 0, 1, 15)\n grid.addWidget(self.keys_button, 7, 0, 1, 2)\n grid.addWidget(self.enc_button, 7, 13, 1, 2)\n\n self.setLayout(grid)\n\n self.setGeometry(300, 100, 700, 600)\n self.setWindowTitle('RSA')\n self.show()\n\n\ndef main():\n app = QtGui.QApplication(sys.argv)\n app.setStyleSheet(qdarkstyle.load_stylesheet(pyside=False))\n window = MainWindow()\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"labs/lab_2/client/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"327873269","text":"# Sort Visualization\n\nimport array\nimport random\nimport numpy as np\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nLISTNUM = 100\nMIXNUM = 200\n\nfig = plt.figure()\nims = []\n\n# fixed seed value\nrandom.seed(0)\n\ndef mix_data(array):\n for i in range(MIXNUM):\n a = random.randrange(LISTNUM)\n b = random.randrange(LISTNUM)\n array[a], array[b] = array[b], array[a]\n\n\ndef plot(array):\n im = plt.bar(range(len(array)), array, width=0.9, color='C0')\n ims.append(im)\n\ndef insertion_sort(array):\n n = len(array)\n for i in range(1,n):\n tmp = array[i]\n if tmp < array[i-1]:\n j = i\n while True:\n array[j] = array[j-1]\n j -= 1\n if j <= 0 or tmp >= array[j-1]:\n break\n array[j] = tmp\n plot(array)\n # result\n for i in range(3):\n plot(array)\n\nif __name__ == '__main__':\n data = array.array('i', range(1, LISTNUM))\n mix_data(data)\n insertion_sort(data)\n ani = animation.ArtistAnimation(fig, ims, interval=100)\n ani.save('sort.gif', writer='imagemagick')\n","sub_path":"vissort.py","file_name":"vissort.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"491218211","text":"import math\ndef main():\n #escribe tu código abajo de esta línea\n b = int(input('Dame la base: '))\n h = int(input('Dame la altura: '))\n r = int(input('Dame el rendimiento por m2: '))\n area = b * h\n print(\"El area es: \"+str(area))\n distancia = (area/r)\n print(\"Rendimiento por m2/l: \"+str(distancia))\n\nif __name__ == '__main__':\n main()\n","sub_path":"assignments/13CantidadLitrosPintura/src/exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"527704741","text":"# Copyright 2018 Microsoft Corporation\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# Requires Python 2.6+ and Openssl 1.0+\n\nimport os\nimport subprocess\n\nfrom azurelinuxagent.common import logger\nfrom azurelinuxagent.common.cgroupapi import CGroupsApi\nfrom azurelinuxagent.common.cgroupstelemetry import CGroupsTelemetry\nfrom azurelinuxagent.common.exception import CGroupsException, ExtensionErrorCodes\nfrom azurelinuxagent.common.future import ustr\nfrom azurelinuxagent.common.osutil import get_osutil\nfrom azurelinuxagent.common.utils.extensionprocessutil import handle_process_completion\nfrom azurelinuxagent.common.version import AGENT_NAME, CURRENT_VERSION\nfrom azurelinuxagent.common.event import add_event, WALAEventOperation\n\n\nclass CGroupConfigurator(object):\n \"\"\"\n This class implements the high-level operations on CGroups (e.g. initialization, creation, etc)\n\n NOTE: with the exception of start_extension_command, none of the methods in this class raise exceptions (cgroup operations should not block extensions)\n \"\"\"\n class __impl(object):\n def __init__(self):\n \"\"\"\n Ensures the cgroups file system is mounted and selects the correct API to interact with it\n \"\"\"\n osutil = get_osutil()\n\n self._cgroups_supported = osutil.is_cgroups_supported()\n\n if self._cgroups_supported:\n self._enabled = True\n try:\n osutil.mount_cgroups()\n self._cgroups_api = CGroupsApi.create()\n status = \"The cgroup filesystem is ready to use\"\n except Exception as e:\n status = ustr(e)\n self._enabled = False\n else:\n self._enabled = False\n self._cgroups_api = None\n status = \"Cgroups are not supported by the platform\"\n\n logger.info(\"CGroups Status: {0}\".format(status))\n\n add_event(\n AGENT_NAME,\n version=CURRENT_VERSION,\n op=WALAEventOperation.InitializeCGroups,\n is_success=self._enabled,\n message=status,\n log_event=False)\n\n def enabled(self):\n return self._enabled\n\n def enable(self):\n if not self._cgroups_supported:\n raise CGroupsException(\"cgroups are not supported on the current platform\")\n\n self._enabled = True\n\n def disable(self):\n self._enabled = False\n\n def _invoke_cgroup_operation(self, operation, error_message, on_error=None):\n \"\"\"\n Ensures the given operation is invoked only if cgroups are enabled and traps any errors on the operation.\n \"\"\"\n if not self.enabled():\n return\n\n try:\n return operation()\n except Exception as e:\n logger.warn(\"{0} Error: {1}\".format(error_message, ustr(e)))\n if on_error is not None:\n try:\n on_error(e)\n except Exception as ex:\n logger.warn(\"CGroupConfigurator._invoke_cgroup_operation: {0}\".format(ustr(e)))\n\n def create_agent_cgroups(self, track_cgroups):\n \"\"\"\n Creates and returns the cgroups needed to track the VM Agent\n \"\"\"\n def __impl():\n cgroups = self._cgroups_api.create_agent_cgroups()\n\n if track_cgroups:\n for cgroup in cgroups:\n CGroupsTelemetry.track_cgroup(cgroup)\n\n return cgroups\n\n self._invoke_cgroup_operation(__impl, \"Failed to create a cgroup for the VM Agent; resource usage for the Agent will not be tracked.\")\n\n def cleanup_legacy_cgroups(self):\n def __impl():\n self._cgroups_api.cleanup_legacy_cgroups()\n\n message = 'Failed to process legacy cgroups. Collection of resource usage data will be disabled.'\n\n def disable_cgroups(exception):\n self.disable()\n CGroupsTelemetry.reset()\n add_event(\n AGENT_NAME,\n version=CURRENT_VERSION,\n op=WALAEventOperation.CGroupsCleanUp,\n is_success=False,\n log_event=False,\n message='{0} {1}'.format(message, ustr(exception)))\n\n self._invoke_cgroup_operation(__impl, message, on_error=disable_cgroups)\n\n def create_extension_cgroups_root(self):\n \"\"\"\n Creates the container (directory/cgroup) that includes the cgroups for all extensions (/sys/fs/cgroup/*/walinuxagent.extensions)\n \"\"\"\n def __impl():\n self._cgroups_api.create_extension_cgroups_root()\n\n self._invoke_cgroup_operation(__impl, \"Failed to create a root cgroup for extensions; resource usage for extensions will not be tracked.\")\n\n def create_extension_cgroups(self, name):\n \"\"\"\n Creates and returns the cgroups for the given extension\n \"\"\"\n def __impl():\n return self._cgroups_api.create_extension_cgroups(name)\n\n return self._invoke_cgroup_operation(__impl, \"Failed to create a cgroup for extension '{0}'; resource usage will not be tracked.\".format(name))\n\n def remove_extension_cgroups(self, name):\n \"\"\"\n Deletes the cgroup for the given extension\n \"\"\"\n def __impl():\n cgroups = self._cgroups_api.remove_extension_cgroups(name)\n return cgroups\n\n self._invoke_cgroup_operation(__impl, \"Failed to delete cgroups for extension '{0}'.\".format(name))\n\n def start_extension_command(self, extension_name, command, timeout, shell, cwd, env, stdout, stderr,\n error_code=ExtensionErrorCodes.PluginUnknownFailure):\n \"\"\"\n Starts a command (install/enable/etc) for an extension and adds the command's PID to the extension's cgroup\n :param extension_name: The extension executing the command\n :param command: The command to invoke\n :param timeout: Number of seconds to wait for command completion\n :param cwd: The working directory for the command\n :param env: The environment to pass to the command's process\n :param stdout: File object to redirect stdout to\n :param stderr: File object to redirect stderr to\n :param stderr: File object to redirect stderr to\n :param error_code: Extension error code to raise in case of error\n \"\"\"\n if not self.enabled():\n process = subprocess.Popen(command,\n shell=shell,\n cwd=cwd,\n env=env,\n stdout=stdout,\n stderr=stderr,\n preexec_fn=os.setsid)\n\n process_output = handle_process_completion(process=process,\n command=command,\n timeout=timeout,\n stdout=stdout,\n stderr=stderr,\n error_code=error_code)\n else:\n extension_cgroups, process_output = self._cgroups_api.start_extension_command(extension_name,\n command,\n timeout,\n shell=shell,\n cwd=cwd,\n env=env,\n stdout=stdout,\n stderr=stderr,\n error_code=error_code)\n\n return process_output\n\n # unique instance for the singleton (TODO: find a better pattern for a singleton)\n _instance = None\n\n @staticmethod\n def get_instance():\n if CGroupConfigurator._instance is None:\n CGroupConfigurator._instance = CGroupConfigurator.__impl()\n return CGroupConfigurator._instance\n","sub_path":"azurelinuxagent/common/cgroupconfigurator.py","file_name":"cgroupconfigurator.py","file_ext":"py","file_size_in_byte":9489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"147619510","text":"# -*- coding: utf-8 -*-\n\"\"\"\nfunctions to read default mouse gene list and structure list\n\"\"\"\nimport pandas as pd\n\n\ndef read_all_genes(entry_type='id'):\n \"\"\"\n read all available gene acronyms\n that have section data sets available\n in mouse atlas in the form of acronyms\n :param entry_type: str, optional\n the type of gene identifier. default:'acronym'\n supported:\n 'id', return the list of gene IDs (integers)\n 'acronym', return the list of gene acronyms (str)\n 'name', return the list of gene names (str)\n :return: list\n a list of gene acronyms\n \"\"\"\n all_gene_acronyms = pd.read_csv(\n \"abagen/data/all_genes_available.csv\"\n )\n return all_gene_acronyms[entry_type].values\n\n\ndef read_all_structures(entry_type='id'):\n \"\"\"\n read default structure (ROI) acronyms as documented in\n Rubinov et al, 2015\n :param entry_type: str, optional\n the type of structure identifier. default:'acronym'\n supported:\n 'id', return the list of structure IDs (integers)\n 'acronym', return the list of structure acronyms (str)\n 'name', return the list of structure names (str)\n\n :return: list\n a list of structure acronyms\n \"\"\"\n roilabels = pd.read_csv(\n \"abagen/data/roilabels-rubinov2015pnas.csv\"\n )\n return roilabels[entry_type].values\n","sub_path":"abagen/mouse/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"561151530","text":"# import tensorflow as tf\n#\n# x = tf.constant([ [1.0,2.0,3.0] ])\n# w = tf.constant([ [2.0],[2.0],[2.0] ])\n# y = tf.matmul(x,w)\n#\n# print (x.get_shape())\n#\n# sess = tf.Session()\n# init = tf.global_variables_initializer()\n# sess.run(init)\n# result = sess.run(y)\n#\n# print(result)\n#\n#\n# x = tf.Variable([ [1.,2.,3.] ], dtype=tf.float32)\n# w = tf.constant([ [2.],[2.],[2.]], dtype=tf.float32)\n# y = tf.matmul(x,w)\n#\n# sess = tf.Session()\n# init = tf.global_variables_initializer()\n# sess.run(init)\n# result = sess.run(y)\n#\n# print(result)\n\nimport tensorflow as tf\ninput_data = [[1.,2.,3.],[1.,2.,3.],[2.,3.,4.]] #3x3\nx1 = tf.placeholder(dtype=tf.float32, shape=[None,3])\nw = tf.Variable([[2.],[2.],[2.]], dtype=tf.float32) #3x1\ny = tf.matmul(x1,w)\n\nsess = tf.Session()\ninit = tf.global_variables_initializer()\nsess.run(init)\n\nresult = sess.run(y, feed_dict={x1:input_data})\n\nprint(result)","sub_path":"텐서플로우행렬표현.py","file_name":"텐서플로우행렬표현.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"427437849","text":"from pytube import YouTube\nimport ColorClass\nimport LogoClass\n\nbcolors = ColorClass.bcolors\n\n\nLogoClass.Logo()\nprint('')\nprint(f\"{bcolors.OKCYAN}description : A practical and completely free program that allows you to easily download videos from YouTube to your computer.{bcolors.BOLD}\")\n\nlink = input(f\"{bcolors.WARNING}Enter the link: {bcolors.ENDC}\")\nyt = YouTube(link)\nys = yt.streams.get_highest_resolution()\n\nprint('Title: '+yt.title)\nprint(f\"{bcolors.OKBLUE}---initiating download---{bcolors.ENDC}\")\n\nys.download()\n\nprint(f\"{bcolors.OKBLUE}---download completed---{bcolors.ENDC}\")\nLogoClass.endLogo()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"496992742","text":"\"\"\"Define automations for our cars.\"\"\"\nfrom typing import Union\n\nimport voluptuous as vol\n\nfrom const import (\n CONF_ENTITY_IDS,\n CONF_FRIENDLY_NAME,\n CONF_NOTIFICATION_TARGET,\n CONF_PROPERTIES,\n)\nfrom core import APP_SCHEMA, Base\nfrom helpers import config_validation as cv\nfrom notification import send_notification\n\nCONF_CAR = \"car\"\nCONF_FUEL_THRESHOLD = \"fuel_threshold\"\n\nHANDLE_LOW_FUEL = \"low_fuel\"\n\n\nclass NotifyLowFuel(Base): # pylint: disable=too-few-public-methods\n \"\"\"Define a feature to notify of the vehicle's ETA to home.\"\"\"\n\n APP_SCHEMA = APP_SCHEMA.extend(\n {\n CONF_ENTITY_IDS: vol.Schema(\n {vol.Required(CONF_CAR): cv.entity_id}, extra=vol.ALLOW_EXTRA\n ),\n CONF_PROPERTIES: vol.Schema(\n {\n vol.Required(CONF_FRIENDLY_NAME): str,\n vol.Required(CONF_FUEL_THRESHOLD): int,\n vol.Required(CONF_NOTIFICATION_TARGET): str,\n },\n extra=vol.ALLOW_EXTRA,\n ),\n }\n )\n\n def configure(self):\n \"\"\"Configure.\"\"\"\n self.registered = False\n\n self.listen_state(\n self._on_low_fuel,\n self.entity_ids[CONF_CAR],\n attribute=\"fuel_level\",\n constrain_enabled=True,\n )\n\n def _on_low_fuel(\n self, entity: Union[str, dict], attribute: str, old: str, new: str, kwargs: dict\n ) -> None:\n \"\"\"Send a notification when my car is low on gas.\"\"\"\n try:\n if int(new) < self.properties[\"fuel_threshold\"]:\n if self.registered:\n return\n\n self.log(\n \"Low fuel detected detected: {0}\".format(self.entity_ids[CONF_CAR])\n )\n\n self.registered = True\n send_notification(\n self,\n self.properties[CONF_NOTIFICATION_TARGET],\n \"{0} needs gas; fill 'er up!.\".format(\n self.properties[CONF_FRIENDLY_NAME]\n ),\n title=\"{0} is Low ⛽\".format(self.properties[CONF_FRIENDLY_NAME]),\n )\n else:\n self.registered = False\n except ValueError:\n return\n","sub_path":"appdaemon/settings/apps/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"264811237","text":"# coding: UTF-8\nimport http.cookiejar\nimport urllib.request\nimport urllib.parse\nimport re\nimport time\nimport configparser\nclass Smzdm:\n def __init__(self):\n self.cookies = http.cookiejar.CookieJar()\n self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookies))\n self.headers = {\n 'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36',\n 'Referer' : 'http://www.smzdm.com/',\n 'Origin' : 'http://www.smzdm.com/'\n }\n\n def login(self,account):\n url = \"https://zhiyou.smzdm.com/user/login/ajax_check\"\n data = urllib.parse.urlencode({\n 'username' : account['username'],\n 'password' : account['password'],\n 'rememberme' : 'on',\n 'redirect_url' : 'http://www.smzdm.com'\n }).encode()\n request = urllib.request.Request(url, headers=self.headers, data=data)\n content = self.opener.open(request)\n return content\n\n def logout(self):\n url = \"http://zhiyou.smzdm.com/user/logout\"\n request = urllib.request.Request(url, headers=self.headers,)\n self.opener.open(request)\n\n def checkin(self):\n url = \"http://zhiyou.smzdm.com/user/checkin/jsonp_checkin\"\n request = urllib.request.Request(url, headers=self.headers)\n self.opener.open(request)\n\n def is_checkin(self):\n url = \"http://zhiyou.smzdm.com/user/info/jsonp_get_current?\"\n request = urllib.request.Request(url, headers = self.headers)\n response = self.opener.open(request)\n content = response.read().decode('utf-8')\n pattern = re.compile('\\\"has_checkin\\\"\\:(.*?),')\n item = re.search(pattern, content)\n if item and item.group(1).strip() == 'true':\n return 'SUCCEED'\n else:\n return 'FAILED'\n\n\n\n def start_checkin(self):\n parser = configparser.RawConfigParser()\n parser.read(\"account.ini\")\n log = open('log.txt','a', newline='')\n for user in parser.sections():\n account = {}\n account['username'] = parser.get(user, 'username')\n account['password'] = parser.get(user, 'password')\n self.login(account)\n self.checkin()\n if self.is_checkin()=='SUCCEED':\n log.write(time.strftime('%Y-%m-%d',time.localtime(time.time()))+','+ account['username'] +',SUCCEED\\n')\n else:\n log.write(time.strftime('%Y-%m-%d',time.localtime(time.time()))+','+ account['username'] +',FAILED\\n')\n self.logout()\n log.close()\n\nsmzdm = Smzdm()\nsmzdm.start_checkin()\n\n","sub_path":"smzdm.py","file_name":"smzdm.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"201401445","text":"\n\nclass Task:\n\n __slots__ = (\"inputs\", \"consumers\", \"duration\", \"size\", \"name\", \"id\", \"info\", \"s_info\")\n\n def __init__(self, name=None, duration=1, size=0):\n self.inputs = []\n self.consumers = set()\n\n self.name = name\n self.id = None\n self.info = None\n self.s_info = None\n\n self.duration = duration\n self.size = size\n\n @property\n def label(self):\n if self.name:\n return self.name\n else:\n return \"id={}\".format(self.id)\n\n def cleanup(self):\n self.info = None\n self.s_info = None\n\n def add_input(self, task):\n assert isinstance(task, Task)\n self.inputs.append(task)\n task.consumers.add(self)\n\n def add_inputs(self, tasks):\n for t in tasks:\n self.add_input(t)\n\n def __repr__(self):\n if self.name:\n name = \" '\" + self.name + \"'\"\n else:\n name = \"\"\n if self.s_info is not None:\n s_info = \" \" + repr(self.s_info)\n else:\n s_info = \"\"\n return \"\".format(name, self.id, s_info)\n\n def is_predecessor_of(self, task):\n descendants = set()\n explore = [self]\n\n while explore:\n new = []\n for t in explore:\n for d in t.consumers:\n if d in descendants:\n continue\n if d == task:\n return True\n descendants.add(d)\n new.append(d)\n explore = new\n return False\n\n def validate(self):\n assert self.duration >= 0\n assert not self.is_predecessor_of(self)","sub_path":"schedtk/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"377393792","text":"#!/usr/bin/env python\n\nfrom agate.rows import Row\nfrom agate import utils\n\n\n@utils.allow_tableset_proxy\ndef homogenize(self, key, compare_values, default_row=None):\n \"\"\"\n Fills missing rows in a dataset with default values.\n\n Determines what rows are missing by comparing the values in the given\n column_names with the expected compare_values.\n\n Values not found in the table will be used to generate new rows with\n the given default_row.\n\n Default_row should be an array of values or an array-generating\n function. If not specified, the new rows will have `None` in columns\n not given in column_names.\n\n If it is an array of values, the length should be row length minus\n column_names count and the gap will be filled with the missing values.\n\n If it is an array-generating function, the function should take an array\n of missing values for each new row and output a full row including those\n values.\n\n :param key:\n Either a column name or a sequence of such names.\n :param compare_values:\n Either an array of column values if key is a single column name or a\n sequence of arrays of values if key is a sequence of names. It can\n also be a generator that yields one of the two. A row is created for\n each value or list of values not found in the rows of the table.\n :param default_row:\n An array of values or a function to generate new rows. The length of\n the input array should be equal to row length minus column_names\n count. The length of array generated by the function should be the\n row length.\n :returns:\n A new :class:`Table`.\n \"\"\"\n rows = list(self.rows)\n\n if not utils.issequence(key):\n key = [key]\n\n if len(key) == 1:\n if any(not utils.issequence(compare_value) for compare_value in compare_values):\n compare_values = [[compare_value] for compare_value in compare_values]\n\n column_values = [self.columns.get(name) for name in key]\n column_indexes = [self.column_names.index(name) for name in key]\n\n column_values = zip(*column_values)\n differences = list(set(map(tuple, compare_values)) - set(column_values))\n\n for difference in differences:\n if callable(default_row):\n rows.append(Row(default_row(difference), self.column_names))\n else:\n if default_row is not None:\n new_row = default_row\n else:\n new_row = [None] * (len(self.column_names) - len(key))\n\n for i, d in zip(column_indexes, difference):\n new_row.insert(i, d)\n\n rows.append(Row(new_row, self.column_names))\n\n return self._fork(rows, self.column_names, self.column_types)\n","sub_path":"agate/table/homogenize.py","file_name":"homogenize.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"598263956","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 12 23:13:47 2019\n\n@author: defaultuser0\n\"\"\"\n\ndir=\"C:\\\\Users\\\\defaultuser0.LAPTOP-6F0LJR1V\\\\Selenium\"\nimport os\nos.chdir(dir)\n\nimport parameters\nfrom time import sleep\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom parsel import Selector\nimport csv\nfrom selenium.webdriver.support.ui import Select\nimport pandas as pd\n\n\ndef validate_field(field):\n if field:\n pass\n else:\n field = ''\n return field\n\nwriter=csv.writer(open(parameters.file_name, 'w'))\nwriter.writerow(['Job Title','Company Name','Time','Applicants','Place','Job Description','Skill','Url'])\n\ndriver=webdriver.Chrome('D:/chromedriver')\ndriver.get('https://www.linkedin.com/')\n\nusername=driver.find_element_by_class_name('login-email')\nusername.send_keys(parameters.linkedin_username)\nsleep(0.5)\n\npassword=driver.find_element_by_id('login-password')\npassword.send_keys(parameters.linkedin_password)\nsleep(0.5)\n\nsign_in_button=driver.find_element_by_xpath('//*[@type=\"submit\"]')\nsign_in_button.click()\nsleep(5)\n\ndriver.get('http://google.com')\nsleep(2)\n\nsearch_query=driver.find_element_by_name('q')\nsearch_query.send_keys(parameters.search)\nsleep(0.5)\n\nsearch_query.send_keys(Keys.RETURN)\nsleep(3)\n\nlinks=driver.find_elements_by_xpath('//*[@class=\"r\"]/a')\nlink= links[0].get_attribute(\"href\")\nsleep(3)\n\ndriver.get(link)\nsleep(10)\n\n#Make all job position is visible\n\nelement=driver.find_elements_by_xpath('//*[@class=\"job-card-search__title artdeco-entity-lockup__title ember-view\"]//a')\n\nelement[1].send_keys(Keys.END)\nsleep(10)\nelement[1].send_keys(Keys.HOME)\nsleep(10)\n\nurl_link=driver.find_elements_by_xpath('//*[@class=\"job-card-search__title artdeco-entity-lockup__title ember-view\"]//a')\nprint(len(url_link))\njob_url_link=[content.get_attribute(\"href\") for content in url_link]\nfull_list=[]\nfull_list.append(job_url_link)\n\n\ndef find_number_of_next_page():\n next_page=None\n next_button=driver.find_elements_by_xpath('//*[@class=\"artdeco-pagination__pages artdeco-pagination__pages--number\"]//span')\n button_selected=driver.find_elements_by_xpath('//*[@class=\"artdeco-pagination__indicator artdeco-pagination__indicator--number active selected\"]/span')\n for i in range(len(next_button)):\n if button_selected[0].text==next_button[i].text:\n next_page=next_button[i+1]\n else:\n pass\n return(next_page)\n \n\nfrom selenium.common.exceptions import NoSuchElementException \n\ndef check_exists_by_xpath(xpath):\n try:\n driver.find_element_by_xpath(xpath)\n except NoSuchElementException:\n return False\n return True\nusername='//*[@class=\"t-16 t-black t-bold pt2 pb2\"]' \n\nlast_page=driver.find_elements_by_xpath('//*[@class=\"artdeco-pagination__pages artdeco-pagination__pages--number\"]//span')[-1].text\n\n#Next pages\nfor i in range(int(last_page)-1):\n url_list= []\n company_section= []\n next_page=find_number_of_next_page()\n next_page.click()\n sleep(10)\n element=driver.find_elements_by_xpath('//*[@class=\"job-card-search__title artdeco-entity-lockup__title ember-view\"]//a')\n element[1].send_keys(Keys.END)\n sleep(5)\n element[1].send_keys(Keys.HOME)\n sleep(5)\n company_section=driver.find_elements_by_xpath('//*[@class=\"job-card-search__title artdeco-entity-lockup__title ember-view\"]//a')\n url_list=[content.get_attribute(\"href\") for content in company_section]\n full_list.append(url_list)\n \n\n#Save url list as excel file \nurl_list_df=pd.Series(full_list)\nurl_list_df.to_excel('Seattle.xlsx')\n\n \n\n\n\n#Crawl content in each url\nlist_all=pd.read_excel('Seattle.xlsx')\n\nusername='//*[@class=\"t-16 t-black t-bold pt2 pb2\"]' \n\nfor i in range(len(list_all)):\n\n for link in eval(list_all.iloc[i+13,1]):\n driver.get(link)\n sleep(5)\n \n sel=Selector(text=driver.page_source)\n \n job_title=sel.xpath('//*[@class=\"jobs-top-card__job-title t-24\"]/text()').extract_first()\n if job_title:\n job_title=job_title.strip()\n \n \n company_name=sel.xpath('//*[@class=\"jobs-top-card__company-url ember-view\"]/text()').extract_first()\n if company_name:\n company_name=str(company_name).strip()\n \n posting_time=sel.xpath('//*[@class=\"mt1 full-width flex-grow-1 t-14 t-black--light\"]/span/text()').extract()\n if posting_time:\n posting_time=str(posting_time).strip()\n \n \n applicants=sel.xpath('//*[@class=\"jobs-top-card__bullet inline-flex align-items-center mr1\"]/span/text()').extract()\n if applicants:\n applicants=str(applicants).strip() \n \n place=sel.xpath('//*[@class=\"jobs-top-card__bullet\"]/text()').extract_first()\n if place:\n place=str(place).strip()\n \n description=sel.xpath('//*[@id=\"job-details\"]//text()').extract()\n description= [x.strip('\\n') for x in description]\n description=str(description)[1:-1]\n description=description.strip()\n \n \n skill=sel.xpath('//*[@class=\"jobs-ppc-criteria__value t-14 t-black t-normal ml2 block\"]//text()').extract()\n skill=str(skill).strip()\n \n url=driver.current_url\n \n job_title=validate_field(job_title)\n company_name=validate_field(company_name)\n posting_time=validate_field(posting_time)\n applicants=validate_field(applicants)\n place=validate_field(place)\n description=validate_field(description)\n skill=validate_field(skill)\n url =validate_field(url)\n \n print('Job Titile: '+job_title)\n print('Company Name: '+ company_name)\n print('Time: '+ posting_time)\n print('Applicant: '+ applicants) \n print('Place: '+place)\n print('Job Description: '+ description)\n print('Skill: '+ skill)\n print('Url: '+url)\n \n writer.writerow([job_title.encode('utf-8'),\n company_name.encode('utf-8'),\n posting_time.encode('utf-8'),\n applicants.encode('utf-8'),\n place.encode('utf-8'),\n description.encode('utf-8'),\n skill.encode('utf-8'),\n url.encode('utf-8')])\n\ndriver.quit()\n\n\n\n\n","sub_path":"Selenium_LinkedIn/Crawling data/linkedin.py","file_name":"linkedin.py","file_ext":"py","file_size_in_byte":6345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"170578123","text":"import os\nimport time\nimport pickle\nimport datetime\nimport itertools\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\n\nfrom onmt_modules.misc import sequence_mask\nfrom model_autopst import Generator_2 as Predictor\n\n\n\nclass Solver(object):\n\n def __init__(self, data_loader, config, hparams):\n \"\"\"Initialize configurations.\"\"\"\n\n \n self.data_loader = data_loader\n self.hparams = hparams\n self.gate_threshold = hparams.gate_threshold\n \n self.use_cuda = torch.cuda.is_available()\n self.device = torch.device('cuda:{}'.format(config.device_id) if self.use_cuda else 'cpu')\n self.num_iters = config.num_iters\n self.log_step = config.log_step\n \n # Build the model\n self.build_model()\n \n \n def build_model(self):\n \n self.P = Predictor(self.hparams)\n self.freeze_layers(self.P.encoder_cd)\n \n self.optimizer = torch.optim.Adam(self.P.parameters(), 0.0001, [0.9, 0.999])\n \n self.P.to(self.device)\n \n self.BCELoss = torch.nn.BCEWithLogitsLoss().to(self.device) \n \n \n checkpoint = torch.load(self.hparams.pretrained_path, \n map_location=lambda storage, loc: storage)\n \n self.P.load_state_dict(checkpoint['model'], strict=True)\n print('Loaded pretrained encoder .........................................')\n \n \n def freeze_layers(self, layer):\n print('Fixing layers!')\n for param in layer.parameters():\n param.requires_grad = False\n \n \n def train(self):\n # Set data loader\n data_loader = self.data_loader\n data_iter = iter(data_loader)\n \n \n # Print logs in specified order\n keys = ['P/loss_tx2sp', 'P/loss_stop_sp']\n \n \n # Start training.\n print('Start training...')\n start_time = time.time()\n for i in range(self.num_iters):\n\n try:\n sp_real, cep_real, cd_real, num_rep, _, len_real, len_short, _, spk_emb = next(data_iter)\n except:\n data_iter = iter(data_loader)\n sp_real, cep_real, cd_real, num_rep, _, len_real, len_short, _, spk_emb = next(data_iter)\n \n \n sp_real = sp_real.to(self.device)\n cep_real = cep_real.to(self.device)\n cd_real = cd_real.to(self.device)\n len_real = len_real.to(self.device)\n spk_emb = spk_emb.to(self.device)\n num_rep = num_rep.to(self.device)\n len_short = len_short.to(self.device)\n \n \n # real spect masks\n mask_sp_real = ~sequence_mask(len_real, sp_real.size(1))\n mask_long = (~mask_sp_real).float()\n \n len_real_mask = torch.min(len_real + 10, \n torch.full_like(len_real, sp_real.size(1)))\n loss_tx2sp_mask = sequence_mask(len_real_mask, sp_real.size(1)).float().unsqueeze(-1)\n \n # text input masks\n codes_mask = sequence_mask(len_short, num_rep.size(1)).float()\n \n \n # =================================================================================== #\n # 2. Train #\n # =================================================================================== #\n \n self.P = self.P.train()\n \n \n sp_real_sft = torch.zeros_like(sp_real)\n sp_real_sft[:, 1:, :] = sp_real[:, :-1, :] \n \n \n spect_pred, stop_pred_sp = self.P(cep_real.transpose(2,1),\n mask_long,\n codes_mask,\n num_rep,\n len_short+1,\n sp_real_sft.transpose(1,0), \n len_real+1,\n spk_emb)\n \n \n loss_tx2sp = (F.mse_loss(spect_pred.permute(1,0,2), sp_real, reduction='none')\n * loss_tx2sp_mask).sum() / loss_tx2sp_mask.sum()\n \n loss_stop_sp = self.BCELoss(stop_pred_sp.squeeze(-1).t(), mask_sp_real.float())\n \n loss_total = loss_tx2sp + loss_stop_sp\n \n # Backward and optimize\n self.optimizer.zero_grad()\n loss_total.backward()\n self.optimizer.step()\n \n\n # Logging\n loss = {}\n loss['P/loss_tx2sp'] = loss_tx2sp.item()\n loss['P/loss_stop_sp'] = loss_stop_sp.item()\n \n\n # =================================================================================== #\n # 4. Miscellaneous #\n # =================================================================================== #\n\n # Print out training information\n if (i+1) % self.log_step == 0:\n et = time.time() - start_time\n et = str(datetime.timedelta(seconds=et))[:-7]\n log = \"Elapsed [{}], Iteration [{}/{}]\".format(et, i+1, self.num_iters)\n for tag in keys:\n log += \", {}: {:.8f}\".format(tag, loss[tag])\n print(log)\n \n \n # Save model checkpoints.\n if (i+1) % 10000 == 0:\n torch.save({'model': self.P.state_dict(),\n 'optimizer': self.optimizer.state_dict()}, f'./assets/{i+1}-B.ckpt')\n print('Saved model checkpoints into assets ...') ","sub_path":"solver_2.py","file_name":"solver_2.py","file_ext":"py","file_size_in_byte":6016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"113499241","text":"#!/usr/bin/env python3\n\nimport os\nfrom collections import namedtuple\nfrom typing import Dict, List\n\nimport matplotlib.pyplot as plt\nimport requests\nfrom ortools.sat.python.cp_model import CpModel, CpSolver\nfrom shapely.geometry import LineString, Point, Polygon\n\nCoord = namedtuple('Coord', ['x', 'y'])\nPair = namedtuple('Pair', ['ax', 'ay', 'bx', 'by'])\n\nheaders = {\"Authorization\": \"Bearer \" + os.environ['ICFP2021_API_KEY']}\n\n\ndef get_problem(n: int) -> Dict:\n ''' Download a problem JSON '''\n r = requests.get(f\"https://poses.live/api/problems/{n}\", headers=headers)\n r.raise_for_status()\n return r.json()\n\n\ndef get_deltas(d_old: int, epsilon: int) -> List[Coord]:\n ''' Get the valid delta x,y for a given distance '''\n n = int(d_old ** 0.5 + 1) * 2\n deltas = []\n for x in range(-n, n + 1):\n for y in range(-n, n + 1):\n if abs((x ** 2 + y ** 2) / d_old - 1) <= (epsilon / 1e6):\n deltas.append(Coord(x, y))\n return deltas\n\n\ndef valid_edge(a: Coord, b: Coord, points: List[Coord], poly: Polygon) -> bool:\n ''' Returns True if this is a valid edge, else False '''\n assert a in points and b in points, 'invalid edge check'\n ab = LineString((a, b))\n if poly.contains(ab) or ab.within(poly):\n return True\n elif poly.exterior.crosses(ab):\n return False\n elif poly.touches(ab) and not poly.exterior.contains(ab):\n return False\n return True\n\n\nfor PROBLEM_NUMBER in range(1, 133):\n # Computed data\n hole = problem['hole']\n edges = problem['figure']['edges']\n vertices = problem['figure']['vertices']\n epsilon = problem['epsilon']\n xs, ys = [p[0] for p in hole], [p[1] for p in hole]\n poly = Polygon(hole)\n points = [(x, y) for x in range(min(xs), max(xs) + 1)\n for y in range(min(ys), max(ys) + 1) if poly.intersects(Point(x, y))]\n edge_dists = [(vertices[i][0] - vertices[j][0]) ** 2 +\n (vertices[i][1] - vertices[j][1]) ** 2 for i, j in edges]\n deltas = {d: get_deltas(d, epsilon) for d in set(edge_dists)}\n forbidden = {delta: get_forbidden(points, poly, delta)\n for delta in set(sum(deltas.values(), []))}\n # Constraint Model\n model = CpModel()\n pose = [(model.NewIntVar(min(xs), max(xs), f'P{i}x'), model.NewIntVar(\n min(ys), max(ys), f'P{i}y')) for i in range(len(vertices))]\n [model.AddAllowedAssignments([x, y], points) for x, y in pose]\n dx, dy = max(xs) - min(xs), max(ys) - min(ys)\n for i, (d, (j, k)) in enumerate(zip(edge_dists, edges)):\n xvar, yvar = model.NewIntVar(-dx, dx,\n f'E{i}x'), model.NewIntVar(-dy, dy, f'E{i}y')\n model.Add(xvar == pose[j][0] - pose[k][0])\n model.Add(yvar == pose[j][1] - pose[k][1])\n model.AddAllowedAssignments([xvar, yvar], deltas[d])\n model.AddForbiddenAssignments(\n pose[j] + pose[k], sorted(set(sum((forbidden[delta] for delta in deltas[d]), []))))\n # Solver\n solver = CpSolver()\n solver.parameters.max_time_in_seconds = 100.0\n status = solver.Solve(model)\n solution = dict(\n vertices=[(solver.Value(p[0]), solver.Value(p[1])) for p in pose])\n solution\n # Visualize\n fig, ax = plt.subplots()\n cycle = hole + [hole[0]]\n ax.plot([c[0] for c in cycle], [c[1] for c in cycle])\n ax.scatter([p[0] for p in points], [p[1] for p in points], s=2)\n ax.plot([p[0] for p in solution['vertices']], [p[1]\n for p in solution['vertices']], 'go-')\n # Submit\n r = requests.post(\n f'https://poses.live/api/problems/{PROBLEM_NUMBER}/solutions', headers=headers, json=solution)\n r.raise_for_status()\n","sub_path":"golf/nofun.py","file_name":"nofun.py","file_ext":"py","file_size_in_byte":3678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"139483595","text":"from django.urls import path\nfrom .import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('getResource', views.getResource, name='getResource'),\n path('getMeeting', views.getMeeting, name='getMeeting'),\n path('meetingDetail/', views.meetingDetails, name='meetingDetails'),\n path('newResource', views.newResource, name='newResource'),\n path('newMeeting', views.newMeeting, name='newMeeting'),\n path('loginmessage/', views.loginmessage, name='loginmessage'),\n path('logoutmessage/', views.logoutmessage, name='logoutmessage'),\n]\n","sub_path":"Club/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"468912414","text":"\"\"\"\nModule related to Occlusion sensitivity method\n\"\"\"\n\nfrom math import ceil\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom .base import BlackBoxExplainer, sanitize_input_output\nfrom ..commons import repeat_labels, batch_tensor\nfrom ..types import Callable, Tuple, Union, Optional\n\n\nclass Occlusion(BlackBoxExplainer):\n \"\"\"\n Used to compute the Occlusion sensitivity method, sweep a patch that occludes pixels over the\n images and use the variations of the model prediction to deduce critical areas.\n\n Ref. Zeiler & al., Visualizing and Understanding Convolutional Networks (2013).\n https://arxiv.org/abs/1311.2901\n\n Parameters\n ----------\n model\n Model used for computing explanations.\n batch_size\n Number of masked samples to process at once, if None process all at once.\n patch_size\n Size of the patches to apply, if integer then assume an hypercube.\n patch_stride\n Stride between two patches, if integer then assume an hypercube.\n occlusion_value\n Value used as occlusion.\n \"\"\"\n\n def __init__(self,\n model: Callable,\n batch_size: Optional[int] = 32,\n patch_size: Union[int, Tuple[int, int]] = 3,\n patch_stride: Union[int, Tuple[int, int]] = 3,\n occlusion_value: float = 0.0):\n super().__init__(model, batch_size)\n\n self.patch_size = patch_size\n self.patch_stride = patch_stride\n self.occlusion_value = occlusion_value\n\n @sanitize_input_output\n def explain(self,\n inputs: Union[tf.data.Dataset, tf.Tensor, np.ndarray],\n targets: Optional[Union[tf.Tensor, np.ndarray]] = None) -> tf.Tensor:\n \"\"\"\n Compute Occlusion sensitivity for a batch of samples.\n\n Parameters\n ----------\n inputs\n Input samples to be explained.\n targets\n One-hot encoded labels or regression target (e.g {+1, -1}), one for each sample.\n\n Returns\n -------\n explanations\n Occlusion sensitivity, same shape as the inputs, except for the channels.\n \"\"\"\n\n # check if data is images\n is_image = len(inputs.shape) > 2\n\n if is_image:\n if not isinstance(self.patch_size, tuple):\n self.patch_size = (self.patch_size, self.patch_size)\n if not isinstance(self.patch_stride, tuple):\n self.patch_stride = (self.patch_stride, self.patch_stride)\n\n occlusion_maps = None\n batch_size = self.batch_size or len(inputs)\n\n masks = Occlusion._get_masks((*inputs.shape[1:],), self.patch_size, self.patch_stride)\n base_scores = self.batch_inference_function(self.model, inputs, targets, batch_size)\n\n # since the number of masks is often very large, we process the entries one by one\n for single_input, single_target, single_base_score in zip(inputs, targets, base_scores):\n\n occlusion_map = tf.zeros(masks.shape[1:])\n\n for batch_masks in batch_tensor(masks, batch_size):\n\n occluded_inputs = Occlusion._apply_masks(single_input, batch_masks,\n self.occlusion_value)\n repeated_targets = repeat_labels(single_target[tf.newaxis, :], len(batch_masks))\n\n batch_scores = self.inference_function(self.model,\n occluded_inputs,\n repeated_targets)\n\n batch_sensitivity = Occlusion._compute_sensitivity(\n single_base_score, batch_scores, batch_masks\n )\n\n occlusion_map += batch_sensitivity\n\n occlusion_maps = occlusion_map if occlusion_maps is None else \\\n tf.concat([occlusion_maps, occlusion_map], axis=0)\n\n return occlusion_maps\n\n @staticmethod\n def _get_masks(input_shape: Union[Tuple[int, int, int], Tuple[int, int], Tuple[int]],\n patch_size: Union[int, Tuple[int, int]],\n patch_stride: Union[int, Tuple[int, int]]) -> tf.Tensor:\n \"\"\"\n Create all the possible patches for the given configuration.\n\n Parameters\n ----------\n input_shape\n Desired shape, dimension of one sample.\n patch_size\n Size of the patches to apply.\n patch_stride\n Stride between two patches.\n\n Returns\n -------\n occlusion_masks\n The boolean occlusion masks, same shape as the inputs, with 1 as occluded.\n \"\"\"\n masks = []\n\n # check if we have tabular data\n is_tabular = len(input_shape) == 1\n\n if is_tabular:\n x_anchors = [x * patch_stride for x in\n range(0, ceil((input_shape[0] - patch_size + 1) / patch_stride))]\n\n for x_anchor in x_anchors:\n mask = np.zeros(input_shape, dtype=bool)\n mask[x_anchor:x_anchor + patch_size] = 1\n masks.append(mask)\n else:\n x_anchors = [x * patch_stride[0] for x in\n range(0, ceil((input_shape[0] - patch_size[0] + 1) / patch_stride[0]))]\n y_anchors = [y * patch_stride[1] for y in\n range(0, ceil((input_shape[1] - patch_size[1] + 1) / patch_stride[1]))]\n\n for x_anchor in x_anchors:\n for y_anchor in y_anchors:\n mask = np.zeros(input_shape[:2], dtype=bool)\n mask[x_anchor:x_anchor + patch_size[0], y_anchor:y_anchor + patch_size[1]] = 1\n masks.append(mask)\n\n return tf.cast(masks, dtype=tf.bool)\n\n @staticmethod\n @tf.function\n def _apply_masks(current_input: tf.Tensor,\n masks: tf.Tensor,\n occlusion_value: float) -> tf.Tensor:\n \"\"\"\n Given input samples and an occlusion mask template, apply it for every sample.\n\n Parameters\n ----------\n current_input\n Input samples to be explained.\n masks\n The boolean occlusion masks, with 1 as occluded.\n occlusion_value\n Value used as occlusion.\n\n Returns\n -------\n occluded_inputs\n All the occluded combinations for each inputs.\n \"\"\"\n occluded_inputs = tf.expand_dims(current_input, axis=0)\n occluded_inputs = tf.repeat(occluded_inputs, repeats=len(masks), axis=0)\n\n # check if current input shape is (W, H, C)\n has_channels = len(current_input.shape) > 2\n if has_channels:\n masks = tf.expand_dims(masks, axis=-1)\n masks = tf.repeat(masks, repeats=current_input.shape[-1], axis=-1)\n\n occluded_inputs = occluded_inputs * tf.cast(tf.logical_not(masks), tf.float32)\n occluded_inputs += tf.cast(masks, tf.float32) * occlusion_value\n\n return occluded_inputs\n\n @staticmethod\n @tf.function\n def _compute_sensitivity(baseline_scores: tf.Tensor,\n occluded_scores: tf.Tensor,\n masks: tf.Tensor) -> tf.Tensor:\n \"\"\"\n Compute the sensitivity score given the score of the occluded inputs\n\n Parameters\n ----------\n baseline_scores\n Scores obtained with the original inputs (not occluded)\n occluded_scores\n Scores of the occluded combinations for the class of\n interest.\n masks\n The boolean occlusion masks, with 1 as occluded.\n\n Returns\n -------\n sensitivity\n Value reflecting the effect of each occlusion patchs on the output\n \"\"\"\n baseline_scores = tf.expand_dims(baseline_scores, axis=-1)\n occluded_scores = tf.reshape(occluded_scores, (-1, len(masks)))\n\n score_delta = baseline_scores - occluded_scores\n # reshape the delta score to fit masks\n score_delta = tf.reshape(score_delta, (*score_delta.shape, *(1,) * len(masks.shape[1:])))\n\n sensitivity = score_delta * tf.cast(masks, tf.float32)\n sensitivity = tf.reduce_sum(sensitivity, axis=1)\n\n return sensitivity\n","sub_path":"xplique/attributions/occlusion.py","file_name":"occlusion.py","file_ext":"py","file_size_in_byte":8255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"447545707","text":"import sys\nsys.stdin = open(\".\\\\Alg_Training\\\\input.txt\", \"rt\")\n\n# Test case\nT = int(input())\n\narr = []\n# T번의 테스트 케이스 진행\nfor a in range(T):\n N, s, e, k = map(int, input().split())\n \n # N개의 리스트 원소 삽입\n arr = list(map(int, input().split()))\n \n # list slice기능을 사용하면 sub리스트를 둘 필요가 없어진다.\n arr = arr[s-1:e]\n arr.sort()\n \n # print(\"#\", a + 1, \" \", arr[k - 1], sep='')\n print(\"#%d %d\" %(a + 1, arr[k-1]))","sub_path":"Alg_Training/코드_구현력_기르기/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"476736685","text":"import xadmin\nfrom .models import Coupon, CouponType\n\n\nclass CouponAdmin(object):\n list_display = [\"type\", 'is_delete', 'user', \"status\", \"code\", \"created\"]\n search_fields = ['code', 'user__username']\n list_editable = [\"is_delete\", ]\n list_filter = [\"type\", \"status\"]\n\n\nclass CouponTypeAdmin(object):\n list_display = [\"name\", 'is_delete', 'created', \"send_start\", \"send_end\", \"valid_start\", \"valid_end\", \"total\",\n \"send\", \"limit\", \"sub\", \"discount\"]\n search_fields = ['name']\n list_filter = ['is_delete', \"valid_start\", \"valid_end\", \"total\", \"send\", \"limit\"]\n\n\nxadmin.site.register(Coupon, CouponAdmin)\nxadmin.site.register(CouponType, CouponTypeAdmin)","sub_path":"apps/coupon/adminx.py","file_name":"adminx.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"52734787","text":"# coding=utf-8\nimport os\nimport bs4\nimport requests\nimport re\nimport sys\nimport json\nclass Problem():\n\n def __init__(self):\n self.title = ''\n self.ansowers = ''\n self.explain = ''\n self.words = ''\n self.comments = ''\n\n\ndef getHtmlUtf8(url):\n html = requests.get(url)\n content = html.content.decode('utf8')\n return content\n\ndef getlinks(content):\n links=[]\n html_bs4 = bs4.BeautifulSoup(content, \"html.parser\")\n href_attrs = html_bs4.find_all('td')\n for j in range(href_attrs.__len__()):\n # print(href_attrs[j].a['href'])\n links.append(href_attrs[j].a['href'])\n return links\n\n\ndef firststep(url):\n return getlinks(getHtmlUtf8(url))\n\ndef getex(url):\n content = getHtmlUtf8(url)\n bs4_content = bs4.BeautifulSoup(content, \"html.parser\")\n # print(bs4_content.text)\n p = Problem()\n title = bs4_content.find_all('div',class_='sub-text')\n # print(title[0].text)\n p.title = title[0].text\n answers = bs4_content.find_all('div', class_= 'sub-cont')\n p.ansowers = str(answers[0].text).replace('显示答案','')\n id = bs4_content.find_all('a',class_='js-open-error')\n qid = id[0]['data-qid']\n discuss = requests.get('http://ugcv2.kmf.com/api/gre/explain/'+qid+'/current')\n json_dis = json.loads(discuss.content.decode('utf8'))\n try:\n # print(bs4.BeautifulSoup(json_dis['result']['explain']['content']).text)\n p.explain = bs4.BeautifulSoup(json_dis['result']['explain']['content'],'html.parser').text\n except:\n pass\n # print('http://ugcv2.kmf.com/api/gre/comment/'+qid+'/list?psize=100&page=1&orderType=1&uid=0')\n try:\n comments_json = json.loads(requests.get('http://ugcv2.kmf.com/api/gre/comment/'+qid+'/list?psize=100&page=1&orderType=1&uid=0').content.decode('utf8'))\n total = comments_json['result']['pages']['total']\n for i in range(int(total)):\n # print(bs4.BeautifulSoup(comments_json['result']['item'][i]['content']).text)\n p.comments = p.comments+bs4.BeautifulSoup(comments_json['result']['item'][i]['content'],'html.parser').text+'\\n'\n except json.decoder.JSONDecodeError as e:\n pass\n return p\n\ndef getPs(links):\n ps = []\n # for i in range(1):\n for i in range(links.__len__()):\n print('处理第'+str(i)+'题')\n ps.append(getex(links[i]))\n return ps\ndef writetotxt(ps,file,record,start):\n print('输出到文件')\n for p in ps:\n if p is None:\n continue\n info = p.title+p.ansowers+p.explain+p.comments\n print('.',end='.')\n file.write(info.encode('utf-8'))\n record.write(str(start))\n\nif __name__ == '__main__':\n file = open('kmf.txt', 'wb+')\n\n record = open('record.txt','r')\n start = record.readline()\n record.close()\n\n record = open('record.txt', 'w')\n per_links_url = 'http://gre.kmf.com/question/tc/0?keyword=&page='\n end_links_url = ''\n # get links\n\n print(start)\n\n for i in range(int(start),293):\n print(\"\\n*******************第 \"+str(i) +\"页************\")\n links = firststep(per_links_url + end_links_url +str(i) )\n ps = getPs(links)\n writetotxt(ps,file,record,i+1)\n\n record.close()\n file.close()\n\n\n","sub_path":"gre/getkmf.py","file_name":"getkmf.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"216522104","text":"# -*- coding:utf-8 -*-\n# !/usr/bin/env python\n# Time 09 13:50\n# Author Yo\n# Email YoLoveLife@outlook.com\nfrom django.conf.urls import url\nfrom ..views import user as UserView\nurlpatterns = [\n #user\n url(r'^user/$', UserView.AuthorityUserView.as_view(), name='user'),\n url(r'^user/create/$',UserView.AuthorityUserCreateView.as_view(),name='usercreate'),\n url(r'^user/(?P[0-9]+)/update/',UserView.AuthorityUserUpdateView.as_view(),name='userupdate'),\n url(r'^user/(?P[0-8]+)/remove/',UserView.AuthorityUserDeleteView.as_view(),name='userdelete'),\n]\n","sub_path":"apps/authority/urls/views_urls.py","file_name":"views_urls.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"360301026","text":"# -*- coding: utf-8 -*-\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import Select\nimport unittest, time, re\n\nclass ALinks(unittest.TestCase):\n def setUp(self):\n self.driver = webdriver.Firefox()\n self.driver.implicitly_wait(30)\n self.base_url = \"http://deanza.edu/\"\n self.verificationErrors = []\n \n def test_a_links(self):\n link_title = {\n \"Assessment Center (Placement Tests)\" : \"De Anza College :: Admissions and Records :: Assessment & Placement :: Home\", \n \"Computer Access Lab\" : \"De Anza College :: Assistive Computer Technology :: Home\",\n \"Associate Degrees\" : \"De Anza College :: Counseling and Advising Center :: AA/AS Degree & Certificate Programs\",\n \"Associate Degree for Transfer (AA-T and AS-T)\" : \"De Anza College :: Transfer Planning :: SB1440 :: Home\",\n \"Astronomy Department\" : \"De Anza College :: Astronomy :: Home\",\n \"Athletics\" : \"De Anza College :: Athletics :: Welcome to Athletics\",\n \"Automotive Technology\" : \"De Anza College :: Automotive Technology Department :: What We Offer\",\n \"Awards and Achievements\" : \"De Anza College :: Awards and Achievements :: Home\",\n }\n \n driver = self.driver\n driver.get(self.base_url + \"directory/dir-az.html\")\n\n for link in link_title:\n title = link_title[link]\n driver.find_element_by_link_text(link).click()\n try: self.assertEqual(title, driver.title)\n except AssertionError as e: self.verificationErrors.append(str(e))\n driver.back()\n\n def tearDown(self):\n self.driver.quit()\n self.assertEqual([], self.verificationErrors)\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"A-links-Sri.py","file_name":"A-links-Sri.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"234476075","text":"'''\nShopping Patterns\nLC 1761\n\nAmazon is trying to understand customer shopping patterns and offer items that are regularly bought together to new customers. Each item that has been bought together can be represented as an undirected graph where edges join often bundled products. A group of n products is uniquely numbered from 1 of product_nodes. A trio is defined as a group of three related products that all connected by an edge. Trios are scored by counting the number of related products outside of the trio, this is referred as a product sum.\nGiven product relation data, determine the minimum product sum for all trios of related products in the group. If no such trio exists, return -1.\nExample\nproducts_nodes = 6\nproducts_edges = 6\n'''\n\n\nclass Shoppingpattens(object):\n def solution(self, n, edges):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :rtype: int\n \"\"\"\n graph = defaultdict(set)\n for a, b in edges:\n graph[a].add(b)\n graph[b].add(a)\n\n d = {n: len(graph[n]) for n in graph}\n res = float('inf')\n for a in graph:\n for b in graph[a]:\n for c in graph[a] & graph[b]:\n res = min(res, d[a]+d[b]+d[c]-6)\n graph[c].discard(a)\n graph[b].discard(b)\n if res == float('inf'):\n return -1\n return res\n","sub_path":"companyInterviewPractice/Amazon/AmazonOA/pdf/shoppingPatterns.py","file_name":"shoppingPatterns.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"179055476","text":"\nimport plotly.offline as po\nimport plotly.graph_objects as go\nimport plotly.io as pio\nimport pandas as pd\nimport numpy as np\n\nfrom plotly.subplots import make_subplots\n\nUP_COLOR = '#00FF00'\nDOWN_COLOR = '#FF0000'\nGRID_COLOR = '#404040'\n\npio.renderers.default = \"browser\"\n\ndef get_time_profile(df):\n\n dt = np.sort(np.unique(df.index.time))\n dt_mins = np.array([x.hour * 60 + x.minute for x in dt])\n dt_diff_1 = np.diff(dt_mins, prepend = True)\n dt_diff_2 = np.flip(np.diff(np.flip(dt_mins), prepend = True))\n dt_bound = np.round(dt_mins[np.where(dt_diff_1 + dt_diff_2 != 0)] / 15) / 4\n dt_bound = dt_bound[[-1] + list(range(len(dt_bound) - 1))]\n return dt_bound.reshape(-1, 2).tolist()\n\n\ndef kplot(df, position = None, wealth = None, k_indicator = None):\n\n fig = go.Figure()\n\n # ohlc data\n fig.add_trace(go.Candlestick(\n x = df.index,\n open = df.open,\n high = df.high,\n low = df.low,\n close = df.close,\n yaxis = 'y2',\n name = 'OHLC',\n ))\n\n # volume data\n colors = []\n for i in range(len(df.close)):\n if i != 0:\n if df.close[i] > df.close[i-1]:\n colors.append('#FF0000')\n else:\n colors.append('#00FF00')\n else:\n colors.append('#00FF00')\n fig.add_trace(go.Bar(\n type = 'bar',\n x = df.index,\n y = df.volume,\n yaxis = 'y',\n name = 'Volume',\n marker = dict( color=colors ),\n ))\n\n # signal data\n if position is not None:\n position[-1] = 0\n signal = position.diff().fillna(0)\n signal = signal[signal != 0]\n signal = signal.append(signal[signal.abs() == 2])\n signal[signal.abs() == 2] = signal[signal.abs() == 2] / 2\n signal = signal.sort_index()\n signal_dt = signal.index.tolist()\n signal_dt = [[signal_dt[2*i], signal_dt[2*i + 1]] for i in range(len(signal_dt) // 2)]\n signal_side = signal.values.reshape(-1, 2).tolist()\n signal_count = len(signal_dt)\n for i in range(signal_count):\n delta = df.loc[signal_dt[i][1]].open - df.loc[signal_dt[i][0]].open\n fig.add_trace(go.Scatter(\n x = [signal_dt[i][0], signal_dt[i][1]],\n y = [df.loc[signal_dt[i][0]].open, df.loc[signal_dt[i][1]].open],\n yaxis = 'y2',\n mode = 'lines+markers',\n marker = dict(color = UP_COLOR if (signal_side[i][0] * delta) > 0 else DOWN_COLOR),\n line = dict(color = UP_COLOR if (signal_side[i][0] * delta) > 0 else DOWN_COLOR),\n showlegend = False,\n ))\n \n # wealth data\n if wealth is not None:\n fig.add_trace(go.Scatter(\n x = wealth.index,\n y = wealth.values,\n yaxis = 'y3',\n name = 'Wealth',\n mode = 'lines',\n showlegend = True,\n connectgaps = True,\n line = dict(color = '#37ded8'),\n ))\n\n # indicator data\n if k_indicator is not None:\n for ind in k_indicator:\n fig.add_trace(go.Scatter(\n x = ind.index,\n y = ind.values,\n yaxis = 'y2',\n name = 'K_Indicator',\n mode = 'lines',\n showlegend = True,\n connectgaps = True,\n line = dict(color = '#fff200'),\n ))\n\n # layout\n time_profile = get_time_profile(df)\n fig.update_layout(\n plot_bgcolor = 'rgb(0, 0, 0)',\n xaxis = dict(\n rangeselector = dict(visible = True),\n rangebreaks=[\n dict(bounds = ['sat', 'mon'])\n ] + [\n dict(bounds = x, pattern = 'hour') for x in time_profile\n ],\n gridcolor = GRID_COLOR,\n ),\n yaxis = dict( \n domain = [0, 0.2], \n showticklabels = False,\n ),\n yaxis2 = dict( \n domain = [0.2, 0.8],\n side = 'left',\n gridcolor = GRID_COLOR,\n ),\n yaxis3 = dict( \n domain = [0.2, 0.8],\n side = 'right',\n overlaying = 'y2',\n ),\n legend = dict(\n orientation = 'h', \n y=0.9, \n x=0.3, \n yanchor ='bottom'\n ),\n margin = dict( \n t = 40, \n b = 40, \n r = 40,\n l = 40,\n ),\n )\n\n \n fig.write_html('stock.html', auto_open = True)\n \n# if __name__ == \"__main__\":\n# from data.process_data import FuturesData\n\n# # fd = FuturesData('RB')\n# df = fd.get_min_bar(\n# interval = 1, \n# shift = 0, \n# start_date = datetime.date(2019, 3, 21), \n# end_date = datetime.date(2019, 3, 31),\n# )\n\n# signal = df.iloc[[20, 40, 80, 160]].copy()\n# signal['signal'] = 0\n# signal['signal'].iloc[[0, 2]] = 1\n# signal['signal'].iloc[[1, 3]] = -1 \n# signal['price'] = signal['close']\n\n# kplot(df, signal)","sub_path":"backtester/kplot.py","file_name":"kplot.py","file_ext":"py","file_size_in_byte":5105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"467272670","text":"from __future__ import print_function\nimport os\nimport sys\nimport json\nimport logging\nimport argparse\nimport collections\n\nimport conda.api\nimport conda.install\nimport conda.cli.common\nfrom conda.cli.main_list import list_packages\nfrom conda.resolve import Resolve, NoPackagesFound\nfrom conda.toposort import toposort\n\n\ndef dependencies_for_env( prefix ):\n \"\"\"\n Return an OrderedDict of all packages in the packages in the\n given environment and each one's list of dependencies.\n The returned items are in toposort order. \n \"\"\"\n # Get all package strings as 'name-version-build'\n installed = conda.install.linked(prefix)\n exitcode, packages = list_packages(prefix, installed, regex=None, format='canonical', show_channel_urls=False)\n\n # If present, remove channel prefix (e.g. from 'ilastik::boost=1.55.0=5')\n packages = map( lambda p: p.split('::')[-1], packages )\n\n # Replace last two '-' with '='\n packages = map(lambda p: p[::-1].replace('-', '=', 2)[::-1], packages)\n\n # Load dependencies into a dict\n index = conda.api.get_index()\n r = Resolve(index)\n \n deps_dict = {}\n for package in packages:\n try:\n versions = r.get_pkgs(conda.cli.common.arg2spec(package))\n except NoPackagesFound:\n print(\"Skipping \" + package, file=sys.stderr)\n else:\n for pkg in sorted(versions):\n deps_dict[pkg.name] = []\n for dep in pkg.info['depends']:\n deps_dict[pkg.name].append(dep.split(' ')[0])\n\n # If a package's dependencies have been updated recently on the server,\n # there may be entries in the deps list that aren't actually present in our environment.\n # In that case, we just omit that dependency.\n for pkg_name, deps in deps_dict.items():\n to_remove = []\n for dep in deps:\n if dep not in deps_dict:\n to_remove.append(dep)\n for dep in to_remove:\n deps_dict[pkg_name].remove( dep )\n\n # Convenience: Return dict with keys in topologically sorted order\n sorted_keys = toposort( deps_dict )\n #print('\\n'.join(sorted_keys))\n\n deps_dict = collections.OrderedDict( map(lambda k: (k, deps_dict[k]), sorted_keys ) )\n return deps_dict\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--name', '-n')\n parser.add_argument('--prefix', '-p')\n parser.add_argument('--output', '-o')\n parser.add_argument('--keys-only', '-k', action='store_true')\n parser.add_argument('--format', '-f', choices=['json', 'delimited'], default='json')\n args = parser.parse_args()\n\n prefix = conda.cli.common.get_prefix(args)\n\n if not os.path.exists(prefix):\n sys.stderr.write(\"Error: No such environment: {}\\n\".format(prefix))\n sys.exit(1)\n\n # If writing to stdout, make sure the logs are silent\n if not args.output:\n for name in ['stdoutlog', 'fetch', 'progress', 'dotupdate']:\n logging.getLogger(name).setLevel(logging.WARN)\n \n deps_dict = dependencies_for_env( prefix )\n\n if args.keys_only:\n json_data = deps_dict.keys()\n else:\n json_data = deps_dict\n\n if args.format == 'json':\n output_text = json.dumps(json_data, sort_keys=True, indent=4, separators=(',', ': '))\n else:\n if isinstance(json_data, list):\n output_text = '\\n'.join(json_data)\n else:\n output_text = ''\n longest_keylen = max(map(len, json_data.keys()))\n for k,v in json_data.items():\n output_text += k + ' '*(longest_keylen-len(k)+1) + ' '.join(v) + '\\n'\n\n # Write the dict as json\n env_name = args.name or os.path.split(prefix)[-1]\n if args.output:\n with open(args.output, 'w') as output_file:\n output_file.write( output_text )\n else:\n sys.stdout.write( output_text )\n\n\nif __name__ == \"__main__\":\n #sys.argv += ['-p', '/miniforge/envs/ilastik-clang-py3qt5-minimal']\n #sys.argv += ['-o', 'ilastik-clang-py3qt5-minimal.json']\n sys.exit( main() )\n ","sub_path":"build-utils/dependencies-to-json.py","file_name":"dependencies-to-json.py","file_ext":"py","file_size_in_byte":4061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"373501472","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport pickle\nimport sklearn\nimport numpy as np\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.decomposition import PCA\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nimport warnings\nimport copy\n\nwarnings.filterwarnings('ignore')\n\n\n# In[2]:\n\n\ndef save_df_in_excel(filename, df):\n writer = pd.ExcelWriter(filename)\n df.to_excel(writer,\"Sheet\",index = True) \n writer.save()\n\n\n# In[3]:\n\n\n#Get the correlation between a feature and the target\ndef get_correlation_target(df,index_column,target):\n return stats.pearsonr(df.iloc[:,index_column],target)[0]\n\n\n# In[4]:\n\n\n#Get the list of adresses in regards of a column name\ndef get_list_adress_from_columns(df,list_columns):\n list_adress = df.iloc[-2,:]\n list_adress.index = range(len(list_adress))\n for i, text in enumerate(list_adress):\n if text == 0 or text == ' ' or pd.isna(text)==True :\n list_adress[i] = list_columns[i]\n list_adress.index = list_columns \n return list_adress\n\n\n# In[5]:\n\n\n#Prepare the data frame by removing Date, getting the list of columns and adresses \ndef prepare_df_to_get_correlations(df,bool_validation):\n df = df.drop(columns='Date')\n df.columns = range(len(df.columns))\n list_columns = df.iloc[-3,:]\n #list_columns.index = range(len(list_columns))\n #list_columns = list_columns.reset_index(drop=True,inplace=False)\n size = len(list_columns)\n list_columns.update(pd.Series(['WEEKDAYS', 'MONTHS','QUARTERS','Energie'], index=[size-4, size-3,size-2,size-1]))\n if(bool_validation == 0):\n list_adress = get_list_adress_from_columns(df,list_columns)\n df.columns = range(len(df.columns))\n df = df.iloc[:-3,:]\n df_energie = df.iloc[:,-1]\n df_energie_kw = df_energie/0.25\n df.iloc[:,-1] = df_energie_kw\n df.Energie = df_energie_kw \n if(bool_validation == 0):\n return df, list_adress, list_columns\n else :\n return df\n\n\n# In[6]:\n\n\nscaler = MinMaxScaler()\n\n\n# In[7]:\n\n\n#Normalization of the data frame\ndef normalization(df):\n scaler.fit(df)\n return pd.DataFrame(scaler.transform(df))\n\n\n# In[8]:\n\n\n#Change the time step of the data frame\ndef df_changed_time_step(df,step_in_15minutes):\n df_changed_time_step = pd.DataFrame(df.iloc[0:step_in_15minutes].median(axis=0)).transpose()\n for i in range(1,int(len(df.index)/step_in_15minutes)):\n df_changed_time_step.loc[i] = (df.iloc[step_in_15minutes*i:step_in_15minutes*(i+1)].median(axis=0)).transpose()\n df_norm_changed_time_step = normalization(df_changed_time_step)\n return df_norm_changed_time_step\n\n\n# In[9]:\n\n\ndef add_Energie_median(df,step_in_15minutes):\n list_energie = [df.iloc[:,-1][1:step_in_15minutes].median()]\n for i in range(1,int(len(df.index)/step_in_15minutes)):\n list_energie.append(df.iloc[:,-1][step_in_15minutes*i:step_in_15minutes*(i+1)].median())\n return list_energie\n\n\n# In[24]:\n\n\ndef build_correlation_matrix(df,target,correlation_level):\n list_correlations = [get_correlation_target(df,i,target) for i in range(len(df.columns))]\n df_correlations = pd.DataFrame([list_correlations],columns=list_columns[:-1]).transpose()\n df_correlations.columns = ['Corrélation avec Energie totale']\n df_correlations[\"Texte\"] = list_adress[:-1]\n df_correlations_correlation_level = df_correlations[abs(df_correlations['Corrélation avec Energie totale'])>correlation_level]\n return df_correlations_correlation_level\n\n\n# In[11]:\n\n\ndef build_correlation_matrix_after_first_matrix(df_corr,target,correlation_level):\n list_correlations = [get_correlation_target(df_corr,i,target) for i in range(len(df_corr.columns))]\n df_correlations = pd.DataFrame([list_correlations],columns=df_corr.columns).transpose()\n df_correlations.columns = ['Corrélation avec Energie totale']\n df_correlations[\"Texte\"] = list_adress[:-1]\n df_correlations_correlation_level = df_correlations[abs(df_correlations['Corrélation avec Energie totale'])>correlation_level]\n return df_correlations_correlation_level\n\n\n# In[31]:\n\n\ndef launch_correlations(df,target,name,correlation_level):\n #list_columns = list_columns.tolist()\n df_correlations_correlation_level = build_correlation_matrix(df,target,correlation_level)\n name_columns_correlations_correlation_level = df_correlations_correlation_level.index.values.tolist() \n list_columns_str = str(list_columns)\n df_columns = pd.DataFrame(list_columns)\n #list_columns = list_columns.reset_index(drop=True,inplace=False)\n list_index = [df_columns.index[df_columns[\"Adress\"] == val][0] for val in name_columns_correlations_correlation_level]\n pickle.dump(df , open( name+\".p\", \"wb\" ) )\n pickle.dump(df.Energie , open( \"target\"+name+\".p\", \"wb\" ) )\n name_corr = name + \"_corr.p\"\n name_index = \"list_index_\"+name+\".p\"\n pickle.dump(df_correlations_correlation_level, open(name_corr, \"wb\" ) )\n pickle.dump(list_index, open( name_index, \"wb\" ) )\n return df_correlations_correlation_level, list_index\n\n\n# In[13]:\n\n\nfrom sklearn.datasets import load_boston\nimport pandas as pd\nimport numpy as np\nimport statsmodels.api as sm\n\n\ndef stepwise_selection(X, y, \n initial_list=[], \n threshold_in=0.01, \n threshold_out = 0.05, \n verbose=True):\n \"\"\" Perform a forward-backward feature selection \n based on p-value from statsmodels.api.OLS\n Arguments:\n X - pandas.DataFrame with candidate features\n y - list-like with the target\n initial_list - list of features to start with (column names of X)\n threshold_in - include a feature if its p-value < threshold_in\n threshold_out - exclude a feature if its p-value > threshold_out\n verbose - whether to print the sequence of inclusions and exclusions\n Returns: list of selected features \n Always set threshold_in < threshold_out to avoid infinite looping.\n See https://en.wikipedia.org/wiki/Stepwise_regression for the details\n \"\"\"\n included = list(initial_list)\n while True:\n changed=False\n # forward step\n excluded = list(set(X.columns)-set(included))\n new_pval = pd.Series(index=excluded)\n for new_column in excluded:\n model = sm.OLS(y, sm.add_constant(pd.DataFrame(X[included+[new_column]]))).fit()\n new_pval[new_column] = model.pvalues[new_column]\n best_pval = new_pval.min()\n if best_pval < threshold_in:\n best_feature = new_pval.argmin()\n included.append(best_feature)\n changed=True\n if verbose:\n print('Add {:30} with p-value {:.6}'.format(best_feature, best_pval))\n\n # backward step\n model = sm.OLS(y, sm.add_constant(pd.DataFrame(X[included]))).fit()\n # use all coefs except intercept\n pvalues = model.pvalues.iloc[1:]\n worst_pval = pvalues.max() # null if pvalues is empty\n if worst_pval > threshold_out:\n changed=True\n worst_feature = pvalues.argmax()\n included.remove(worst_feature)\n if verbose:\n print('Drop {:30} with p-value {:.6}'.format(worst_feature, worst_pval))\n if not changed:\n break\n return included\n\n\n# In[14]:\n\n\ndef list_without_duplicates(myList):\n y = list(set(myList))\n return y\n\n\n# In[15]:\n\n\ndef remove_too_much_correlations(df_norm,df_corr,list_text,list_index_corr,num,var):\n list_text_corr = list_text[list_index_corr]\n df_norm_just_corr = df_norm.iloc[:,list_index_corr]\n df_norm_just_corr.columns = range(len(df_norm_just_corr.columns))\n df_norm_just_corr.index = range(len(df_norm_just_corr.index))\n list_correlation = np.full((num, num), 0.00000)\n for j in range(len(var)-1):\n for i in range(len(df_norm_just_corr.columns)-1):\n list_correlation[j][i]=get_correlation_target(df_norm_just_corr,i,df_norm_just_corr.iloc[:,j])\n df_correlations = pd.DataFrame(list_correlation)\n df_correlations[df_correlations==1]=-1\n list_max_correlations = df_correlations.max(axis=1).tolist()\n #test = df_correlations.iloc[:,i].values\n list_index_max = []\n for i, max_i in enumerate(list_max_correlations):\n test = list(df_correlations.iloc[:,i].values)\n list_index_max.append(test.index(max_i))\n list_index_max_couples = np.full((num, 2),0)\n for i in range(0,len(var)):\n list_index_max_couples[i][0] = i\n for i in range(0,len(var)):\n list_index_max_couples[i][1] = list_index_max[i]\n list_to_delete = []\n for i in range(1,len(df_corr)-1):\n for j in range(i+1,len(df_corr.columns)):\n if(list_index_max_couples[i][0] == list_index_max_couples[j][1]):\n list_to_delete.append(j)\n list_index_max_couples = np.delete(list_index_max_couples,list_to_delete,axis=0)\n list_index_to_keep = []\n for i in range(0,len(list_index_max_couples)):\n if(df_corr.iloc[list_index_max_couples[i][0],0]>df_corr.iloc[list_index_max_couples[i][1],0]):\n list_index_to_keep.append(list_index_max_couples[i][0])\n else :\n list_index_to_keep.append(list_index_max_couples[i][1])\n df_corr_corr = df_corr.iloc[list_index_to_keep]\n df_norm_just_corr = df_norm_just_corr.iloc[:,list_index_to_keep]\n bb = sorted(list_index_to_keep)\n list_index_corr_to_keep = [list_index_corr[val]for val in bb]\n list_text_corr_corr = list_text_corr[list_index_to_keep]\n df_norm_just_corr = pd.DataFrame(df_norm_just_corr,columns = list_index_to_keep)\n df_norm_just_corr.columns = list_text_corr_corr\n df_norm_just_corr = df_norm_just_corr.astype(float)\n df_norm_just_corr = df_norm_just_corr.transpose().drop_duplicates().transpose()\n list_index_corr_to_keep = list_without_duplicates(list_index_corr_to_keep)\n return df_norm_just_corr, list_index_corr_to_keep\n\n\n# In[16]:\n\n\ndef twice_corr(df_norm,df_corr,list_text,list_index_corr):\n a,b = remove_too_much_correlations(df_norm,df_corr,list_text,list_index_corr,len(df_corr),df_corr)\n c,d = remove_too_much_correlations(df_norm,a,list_text,b,len(a.columns),a.columns)\n return c,d\n\n\n# In[17]:\n\n\ndef twice_corr_once(df_norm,df_corr,list_text,list_index_corr):\n a,b = remove_too_much_correlations(df_norm,df_corr,list_text,list_index_corr,len(df_corr),df_corr)\n return a,b\n\n\n# In[18]:\n\n\ndef save_results_of_EDA(df,df_Energie,name):\n pickle.dump(df , open( \"X_\"+name+\".p\", \"wb\" ) )\n pickle.dump(df_Energie , open( \"y_\"+name+\".p\", \"wb\" ) )\n\n\n# In[32]:\n\n\ndef get_normalized_df_with_different_steps(df):\n df_norm = normalization(df)\n df_norm = df_norm.iloc[:,:-1]\n df_norm.Energie = df.iloc[:,-1]\n pickle.dump(df_norm , open( \"data_norm.p\", \"wb\" ) )\n pickle.dump(df_norm.Energie , open( \"target.p\", \"wb\" ) )\n df_norm_hour = df_changed_time_step(df.iloc[:,:-1],4)\n df_norm_6_hour = df_changed_time_step(df.iloc[:,:-1],24) \n df_norm_day = df_changed_time_step(df.iloc[:,:-1],96)\n\n df_norm_week = df_changed_time_step(df.iloc[96*5:,:-1],96*7)\n\n\n df_norm_hour.Energie = add_Energie_median(df,4)\n df_norm_6_hour.Energie = add_Energie_median(df,24)\n df_norm_day.Energie = add_Energie_median(df,96)\n df_norm_week.Energie = add_Energie_median(df.iloc[96*5:],96*7)\n return df_norm, df_norm_hour,df_norm_6_hour,df_norm_day,df_norm_week\n\n\n# In[20]:\n\n\ndef get_data_from_statistics(df_norm, df_norm_hour,df_norm_6_hour,df_norm_day,df_norm_week):\n df_corr_15_min, list_index_corr_15_min = launch_correlations(df_norm,df_norm.Energie,\"15_min\",0.7)\n df_corr_hour, list_index_corr_hour = launch_correlations(df_norm_hour,df_norm_hour.Energie,\"hour\",0.7)\n df_corr_6_hour, list_index_corr_6_hour = launch_correlations(df_norm_6_hour,df_norm_6_hour.Energie,\"6_hour\",0.7)\n df_corr_day, list_index_corr_day = launch_correlations(df_norm_day,df_norm_day.Energie,\"day\",0.7)\n df_corr_week, list_index_corr_week = launch_correlations(df_norm_week,df_norm_week.Energie,\"week\",0.8)\n\n df_15_min, index_15_min = twice_corr(df_norm,df_corr_15_min,list_adress,list_index_corr_15_min)\n df_hour,index_hour = twice_corr(df_norm_hour,df_corr_hour,list_adress,list_index_corr_hour)\n df_6_hour,index_6_hour = twice_corr(df_norm_6_hour,df_corr_6_hour,list_adress,list_index_corr_6_hour)\n df_day,index_day = twice_corr(df_norm_day,df_corr_day,list_adress,list_index_corr_day)\n df_week,index_week = twice_corr_once(df_norm_week,df_corr_week,list_adress,list_index_corr_week)\n\n df_corr_week2 = build_correlation_matrix_after_first_matrix(df_week,df_norm_week.Energie,0.7)\n\n df_week2,index_week2 = twice_corr_once(df_norm_week,df_corr_week2,list_adress,index_week)\n \n return df_15_min, df_hour,df_6_hour,df_day,df_week2\n\n\n# In[29]:\n\n\ndef launch_EDA(df,name):\n df_norm, df_norm_hour,df_norm_6_hour,df_norm_day,df_norm_week = get_normalized_df_with_different_steps(df)\n df_15_min, df_hour,df_6_hour,df_day,df_week = get_data_from_statistics(df_norm, df_norm_hour,df_norm_6_hour,df_norm_day,df_norm_week)\n save_results_of_EDA(df_15_min,df_norm.Energie,name+\"15_min\")\n save_results_of_EDA(df_hour,df_norm_hour.Energie,name+\"hour\")\n save_results_of_EDA(df_6_hour,df_norm_6_hour.Energie,name+\"6_hour\")\n save_results_of_EDA(df_day,df_norm_day.Energie,name+\"day\")\n save_results_of_EDA(df_week,df_norm_week.Energie,name+\"week\")\n\n\n# In[34]:\n\n\ndf = pickle.load(open(\"data_total_prepared.p\", \"rb\") )\n\n\n# In[35]:\n\n\ndf,list_adress,list_columns = prepare_df_to_get_correlations(df,0)\n\n\n# In[36]:\n\n\nlaunch_EDA(df,'learning')\n\n\n# In[41]:\n\n\ndf_validation = pickle.load(open(\"data_validation_total_prepared.p\", \"rb\") )\n#df_validation = prepare_df_to_get_correlations(df_validation,1)\n\n\n# In[38]:\n\n\ndf_validation = prepare_df_to_get_correlations(df_validation,1)\n\n\n# In[1]:\n\n\n#launch_EDA(df,'validation')\n\n","sub_path":"Version finale janvier 2019/Python/Exploratory Data Analysis.py","file_name":"Exploratory Data Analysis.py","file_ext":"py","file_size_in_byte":13904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"422760933","text":"import json\n\nout_file = {\"cards\":[],\"characters\":[],\"roles\":[],\"highnoon\":[],\"fistfulofcards\":[],\"wildwestshow\":[],\"goldrush\":[]}\n\ndef add_cards(values, expansion):\n for card in values[\"carte\"]:\n card.pop('count')\n card['expansion'] = expansion\n out_file['cards'].append(card)\n\ndef add_characters(values, expansion):\n for card in values[\"personaggi\"]:\n card.pop('count')\n card['hp'] = 4\n card['expansion'] = expansion\n out_file['characters'].append(card)\n\ndef add_roles(values, expansion):\n for card in values[\"ruoli\"]:\n card.pop('count')\n card['expansion'] = expansion\n out_file['roles'].append(card)\n\ndef add_expansion(values, expansion, pop_count=True):\n for card in values[expansion]:\n if pop_count:\n card.pop('count')\n out_file[expansion].append(card)\n\nwith open('bang_base.json', 'r') as content_file:\n values = json.loads(content_file.read())\n add_cards(values, 'base')\n add_characters(values, 'base')\n add_roles(values, 'base')\n\nwith open('bang_dodge_city.json', 'r') as content_file:\n values = json.loads(content_file.read())\n add_cards(values, 'dodgecity')\n add_characters(values, 'dodgecity')\n add_roles(values, 'dodgecity')\n\nwith open('bang_valley_of_shadows.json', 'r') as content_file:\n values = json.loads(content_file.read())\n add_cards(values, 'valleyofshadows')\n add_characters(values, 'valleyofshadows')\n\nwith open('bang_high_noon_fistful_cards.json', 'r') as content_file:\n values = json.loads(content_file.read())\n add_expansion(values, 'fistfulofcards')\n add_expansion(values, 'highnoon')\n\nwith open('bang_wild_west_show.json', 'r') as content_file:\n values = json.loads(content_file.read())\n add_expansion(values, 'wildwestshow')\n add_characters(values, 'wildwestshow')\n\nwith open('bang_armed_dangerous.json', 'r') as content_file:\n values = json.loads(content_file.read())\n add_cards(values, 'armedanddangerous')\n add_characters(values, 'armedanddangerous')\n\nwith open('bang_gold_rush.json', 'r') as content_file:\n values = json.loads(content_file.read())\n add_expansion(values, 'goldrush', pop_count=False)\n add_characters(values, 'goldrush')\n add_roles(values, 'goldrush')\n\nwith open('bang_tutte_carte.json', 'w') as content_file:\n content_file.write(json.dumps(out_file))","sub_path":"unisci.py","file_name":"unisci.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"144816148","text":"from netgan import netgan\nfrom netgan import utils\nimport networkx as nx\nimport scipy.sparse as sp\nimport numpy as np\n\n\n\n\n# try out a simple netgan\nif __name__==\"__main__\":\n # some parameters\n N = 100\n rw_len = 50\n \n # create an adjacency matrix\n G = nx.relaxed_caveman_graph(10,10,0.1)\n G.remove_edges_from(G.selfloop_edges())\n adj = nx.adjacency_matrix(G) \n \n # split up edges apparently (would rather just split up graphs)\n val_share = 0.1\n test_share = 0.05\n train_ones, val_ones, val_zeros, test_ones, test_zeros = utils.train_val_test_split_adjacency(adj, val_share, test_share, undirected=True, connected=True, asserts=True)\n train_graph = sp.coo_matrix((np.ones(len(train_ones)),(train_ones[:,0], train_ones[:,1]))).tocsr()\n\n \n # create the random walk generator\n walker = utils.RandomWalker(adj,rw_len)\n walk_generator = walker.walk\n \n ng = netgan.NetGAN(N,rw_len,walk_generator, gpu_id=None)\n \n stopping_criterion = \"val\"\n\n assert stopping_criterion in [\"val\", \"eo\"], \"Please set the desired stopping criterion.\"\n\n if stopping_criterion == \"val\": # use val criterion for early stopping\n stopping = None\n elif stopping_criterion == \"eo\": #use eo criterion for early stopping\n stopping = 0.5 # set the target edge overlap here\n \n log_dict = ng.train(A_orig=adj, val_ones=val_ones, val_zeros=val_zeros, stopping=stopping,max_iters=5)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"29361715","text":"#!/usr/local/bin/python3\n#coding: utf-8\n\nimport cv2\nimport numpy as np\n\n\n# Segment Laughing Man (to make gif transparent)\ndef segment_lm(lm):\n lm_region = np.zeros(lm.shape)\n for v, line in enumerate(lm):\n non_white_pxs = np.array(np.where(line < 250))\n if non_white_pxs.size > 0:\n min_h, max_h = np.min(non_white_pxs, axis=1)[0], np.max(non_white_pxs, axis=1)[0]\n lm_region[v, min_h:max_h, :] = 1\n\n segmented_lm = lm_region * lm\n\n return segmented_lm, lm_region\n\n\n# Synthesize Laughing Man frame\ndef synth_lm(frame, segmented_lm, lm_region, rect):\n\n # Sizing up face region so that Laughing Man covers the whole face.\n rect[0] = max(rect[0] - 30, 0)\n rect[1] = max(rect[1] - 30, 0)\n rect[2] = min(rect[2] + 60, frame.shape[1] - rect[0])\n rect[3] = min(rect[3] + 60, frame.shape[0] - rect[1])\n\n segmented_lm = cv2.resize(segmented_lm, tuple(rect[2:]))\n lm_region = cv2.resize(lm_region, tuple(rect[2:]))\n\n masked_frame = frame[rect[1]:rect[1]+rect[3], rect[0]:rect[0]+rect[2], :] * (1.0 - lm_region)\n\n frame[rect[1]:rect[1]+rect[3], rect[0]:rect[0]+rect[2], :] = segmented_lm + masked_frame\n\n return frame\n\n\ndef stream_lm_gif(gif_cap):\n\n gif_cap.grab()\n gif_cap.grab()\n gif_ret, lm = gif_cap.read()\n if not gif_ret:\n gif_cap = cv2.VideoCapture(\"laughing_man.gif\")\n gif_ret, lm = gif_cap.read()\n\n return lm, gif_cap\n\n\ndef main():\n\n cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')\n\n # VideoCapture with camera\n cap = cv2.VideoCapture(0)\n ret, frame = cap.read()\n\n # VideoCapture from gif file\n gif_cap = cv2.VideoCapture(\"laughing_man.gif\")\n _, lm = gif_cap.read()\n segmented_lm, mask = segment_lm(lm)\n\n # Main loop\n while ret:\n\n # Face detection with small-sizing acceleration.\n small_frame = cv2.resize(frame, (int(frame.shape[1]/4), int(frame.shape[0]/4)))\n faces = np.array(cascade.detectMultiScale(small_frame)) * 4\n\n # Synthesize Laughing Man\n if faces.shape[0] > 0:\n\n for rect in faces:\n frame = synth_lm(frame, segmented_lm, mask, rect)\n\n cv2.imshow('laughing man', frame)\n\n ret, frame = cap.read()\n\n lm, gif_cap = stream_lm_gif(gif_cap)\n segmented_lm = lm * mask\n\n if cv2.waitKey(10) == 27:\n break\n\n cap.release()\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"laughing_man.py","file_name":"laughing_man.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"159316955","text":"\"\"\"blog URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom django.views.static import serve\n\nfrom blog.settings import DEBUG, MEDIA_ROOT\nfrom postapp import views\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^postapp/',include('postapp.urls')),\n url(r'^ckeditor/',include('ckeditor_uploader.urls')),\n url(r'^page/(\\d+)',views.indexview),\n url(r'^post/(\\d+)',views.detailview),\n url(r'^category/(\\d+)',views.article_view),\n url(r'^archive/(\\d+)/(\\d+)',views.archive_view),\n url(r'^archive/',views.archive_view),\n url(r'^search/',include('haystack.urls')),\n]\nif DEBUG:\n urlpatterns.append(url(r'^media/(?P.*)$',serve,{'document_root':MEDIA_ROOT}),)\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"161593348","text":"import RPi.GPIO as GPIO\nimport time\ndef dectobin(v, r):\n return [int(bit) for bit in bin(v)[2:].zfill(r)]\ndef dectodtac(v,r,dac):\n sig = dectobin(v,r)\n GPIO.output(dac, sig)\n time.sleep(0.1)\n return sig\n\nleds = [ 21, 20, 16, 12, 7, 8, 25, 24 ]\ndac = [ 26, 19, 13, 6, 5, 11, 9, 10 ]\naux = [ 22,23,27,18,15,14,3,2]\n\nmV = 3.3\nbits = len(dac)\nraz = 2**bits\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(dac, GPIO.OUT, initial = GPIO.LOW)\n\ntry:\n while 0==0:\n print(\"Please write a number\")\n inputS = input()\n if inputS.isdigit():\n v = int(inputS)\n if v >=raz:\n print(\"Too large, try again\")\n continue\n elif v < 0:\n print(\"Too small, try again\")\n continue\n else:\n print(\"decimal value\", dectobin(v, bits))\n print(\"value\", v)\n dectodtac(v, bits, dac)\n volt = (v/raz)*mV\n print(\"Voltage\", volt)\n else:\n if inputS == 'qu':\n break\n else:\n print(\"Please, enter a number\")\nexcept KeyboardInterrupt:\n print(\"program was interupted from keyboard\")\nelse:\n print(\"no exceptions happened\")\nfinally:\n GPIO.output(dac, GPIO.LOW)\n GPIO.cleanup(dac)\n print(\"done, GPIO cleaned up\")\n\n","sub_path":"4_dtac_1.py","file_name":"4_dtac_1.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"382234297","text":"import cv2\nimport numpy\n\n# Read the image\nimg=cv2.imread('Images/test_image.jpg',1)\n\n#Save just the Red channel\nimg1=img.copy()\nimg1[:,:,1]=0\nimg1[:,:,2]=0\n\n#Save just the Blue channel\nimg2=img.copy()\nimg2[:,:,0]=0\nimg2[:,:,2]=0\n\n#Save just the Green channel\nimg3=img.copy()\nimg3[:,:,0]=0\nimg3[:,:,1]=0\n\n\n# Show the images\ncv2.imshow('Original Image',img)\ncv2.imshow('RED',img1)\ncv2.imshow('BLUE',img2)\ncv2.imshow('GREEN',img3)\n\n# Close and exit\ncv2.waitKey(0) # 0 makes it wait infinitely\ncv2.destroyAllWindows()\n","sub_path":"Split_Color.py","file_name":"Split_Color.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"502157787","text":"import sys\nfrom PyQt4 import QtGui\n\nclass Window(QtGui.QMainWindow):\n\n def __init__(self):\n super(Window, self).__init__()\n self.setGeometry(500, 100, 500, 500)\n self.setWindowTitle('adModX')\n\n aboutManual = QtGui.QAction('&Manual', self)\n aboutManual.setShortcut('Ctrl+M')\n aboutManual.setStatusTip('How to use this application')\n aboutManual.triggered.connect(self.form_manual)\n\n aboutAction = QtGui.QAction('&About', self)\n aboutAction.setShortcut('Ctrl+A')\n aboutAction.setStatusTip('About the Author')\n aboutAction.triggered.connect(self.form_about)\n\n self.statusBar()\n\n mainMenu = self.menuBar()\n aboutMenu = mainMenu.addMenu('&Help')\n aboutMenu.addAction(aboutManual)\n aboutMenu.addAction(aboutAction)\n\n self.home()\n\n def home(self):\n\n # model file ---------------------------------------------------------------------------------------------------\n self.textModel = QtGui.QLabel('Model file', self)\n self.textModel.move(10, 25)\n\n btnopenModel = QtGui.QPushButton('Open', self)\n btnopenModel.clicked.connect(self.openModel)\n btnopenModel.setStatusTip('Open the ModEM model file location')\n btnopenModel.move(10, 50)\n\n btnsaveModel = QtGui.QPushButton('Save', self)\n btnsaveModel.clicked.connect(self.saveModel)\n btnsaveModel.move(10, 90)\n\n self.lineEditOpenModel = QtGui.QLineEdit('', self)\n self.lineEditOpenModel.move(130, 50)\n self.lineEditOpenModel.resize(350,30)\n\n self.lineEditSaveModel = QtGui.QLineEdit('', self)\n self.lineEditSaveModel.move(130, 90)\n self.lineEditSaveModel.resize(350,30)\n\n # Station file -------------------------------------------------------------------------------------------------\n self.textSta = QtGui.QLabel('Station file', self)\n self.textSta.move(10, 125)\n\n btnopenSta = QtGui.QPushButton('Open', self)\n btnopenSta.clicked.connect(self.openSta)\n btnopenSta.move(10, 150)\n\n btnsaveSta = QtGui.QPushButton('Save', self)\n btnsaveSta.clicked.connect(self.saveSta)\n btnsaveSta.move(10, 190)\n\n self.lineEditOpenSta = QtGui.QLineEdit('', self)\n self.lineEditOpenSta.move(130, 150)\n self.lineEditOpenSta.resize(350,30)\n\n self.lineEditSaveSta = QtGui.QLineEdit('', self)\n self.lineEditSaveSta.move(130, 190)\n self.lineEditSaveSta.resize(350,30)\n\n # Log file -----------------------------------------------------------------------------------------------------\n self.textLog = QtGui.QLabel('Log file', self)\n self.textLog.move(10, 225)\n\n btnopenLog = QtGui.QPushButton('Open', self)\n btnopenLog.clicked.connect(self.openLog)\n btnopenLog.move(10, 250)\n\n btnsaveLog = QtGui.QPushButton('Save', self)\n btnsaveLog.clicked.connect(self.saveLog)\n btnsaveLog.move(10, 290)\n\n self.lineEditOpenLog = QtGui.QLineEdit('', self)\n self.lineEditOpenLog.move(130, 250)\n self.lineEditOpenLog.resize(350, 30)\n\n self.lineEditSaveLog = QtGui.QLineEdit('', self)\n self.lineEditSaveLog.move(130, 290)\n self.lineEditSaveLog.resize(350, 30)\n\n # Info file ----------------------------------------------------------------------------------------------------\n self.textInfo = QtGui.QLabel('Info file', self)\n self.textInfo.move(10, 325)\n\n btnopenInfo = QtGui.QPushButton('Open', self)\n btnopenInfo.clicked.connect(self.openInfo)\n btnopenInfo.move(10, 350)\n\n btnsaveInfo = QtGui.QPushButton('Save', self)\n btnsaveInfo.clicked.connect(self.saveInfo)\n btnsaveInfo.move(10, 390)\n\n self.lineEditOpenInfo = QtGui.QLineEdit('', self)\n self.lineEditOpenInfo.move(130, 350)\n self.lineEditOpenInfo.resize(350, 30)\n\n self.lineEditSaveInfo = QtGui.QLineEdit('', self)\n self.lineEditSaveInfo.move(130, 390)\n self.lineEditSaveInfo.resize(350, 30)\n\n # --------------------------------------------------------------------------------------------------------------\n\n btnProcess = QtGui.QPushButton('Process', self)\n btnProcess.clicked.connect(self.process_app)\n btnProcess.setStatusTip('Process to convert the file')\n btnProcess.move(380, 440)\n\n btnClose = QtGui.QPushButton('Close', self)\n btnClose.clicked.connect(self.close_app)\n btnClose.setStatusTip('Leave the application')\n btnClose.move(270, 440)\n\n # --------------------------------------------------------------------------------------------------------------\n self.show()\n\n def form_about(self):\n pass\n\n def form_manual(self):\n pass\n\n def openModel(self):\n self.nameOpenModel = QtGui.QFileDialog.getOpenFileName(self, 'Open Model File')\n self.lineEditOpenModel.setText(self.nameOpenModel)\n\n def saveModel(self):\n self.nameSaveModel = QtGui.QFileDialog.getSaveFileName(self, 'Save Model File')\n self.lineEditSaveModel.setText(self.nameSaveModel)\n\n def openSta(self):\n self.nameOpenSta = QtGui.QFileDialog.getOpenFileName(self, 'Open Station File')\n self.lineEditOpenSta.setText(self.nameOpenSta)\n\n def saveSta(self):\n self.nameSaveSta = QtGui.QFileDialog.getSaveFileName(self, 'Save Station File')\n self.lineEditSaveSta.setText(self.nameSaveSta)\n\n def openLog(self):\n self.nameOpenLog = QtGui.QFileDialog.getOpenFileName(self, 'Open Log File')\n self.lineEditOpenLog.setText(self.nameOpenLog)\n\n def saveLog(self):\n self.nameSaveLog = QtGui.QFileDialog.getSaveFileName(self, 'Save Log File')\n self.lineEditSaveLog.setText(self.nameSaveLog)\n \n def openInfo(self):\n self.nameOpenInfo = QtGui.QFileDialog.getOpenFileName(self, 'Open Info File')\n self.lineEditOpenInfo.setText(self.nameOpenInfo)\n\n def saveInfo(self):\n self.nameSaveInfo = QtGui.QFileDialog.getSaveFileName(self, 'Save Info File')\n self.lineEditSaveInfo.setText(self.nameSaveInfo)\n\n def close_app(self):\n choice = QtGui.QMessageBox.question(self, 'adModX', 'Exit the application ?',\n QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)\n\n if choice == QtGui.QMessageBox.Yes:\n sys.exit()\n else:\n pass\n\n\n def process_app(self):\n pass\n\nif __name__ == \"__main__\":\n app = QtGui.QApplication(sys.argv)\n main = Window()\n sys.exit(app.exec_())","sub_path":"adModx.py","file_name":"adModx.py","file_ext":"py","file_size_in_byte":6634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"438710692","text":"import sys\nimport os\nimport Queue\nfrom threading import Thread\nfrom bus import bus\n\nclass io:\n SCR_WIDTH = 80\n SCR_HEIGHT = 25\n SCR_MEM_MIN = 16892\n SCR_MEM_MAX = SCR_MEM_MIN + SCR_WIDTH * SCR_HEIGHT\n\n IN_MEM_MIN = 16636\n IN_MEM_MAX = 16891\n IN_MEM_LEN = IN_MEM_MAX - IN_MEM_MIN\n\n pixel = 0\n\n inputQueue = Queue.Queue(IN_MEM_LEN)\n\n def __init__(self, bus):\n self.thr = Thread(target=self.listenKeyboard)\n self.keyboardListening = False\n self.bus = bus\n bus.register(self)\n self.clear()\n return\n\n def addressToPosition(self, address):\n \"\"\"\n Convert ram address memory to (x, y) position\n \"\"\"\n y = 0\n address -= self.SCR_MEM_MIN - 1\n while address > self.SCR_WIDTH:\n y += 1\n address -= self.SCR_WIDTH\n return (address, y + 1)\n\n def event(self):\n if self.bus:\n ad = self.bus.address\n if (self.bus.mode == 2 and ad >= self.SCR_MEM_MIN and ad <= self.SCR_MEM_MAX):\n (x, y) = self.addressToPosition(ad)\n self.updatePixelWithBusData(x, y)\n self.flushScreen()\n if (self.bus.mode == 1 and ad >= self.IN_MEM_MIN and ad <= self.IN_MEM_MAX):\n self.bus.data = self.readInput(ad)\n return True\n return False\n\n def clock(self): # TODO\n #print('Clock on I/O')\n return\n\n def getPixelInMemory(self, x, y):\n \"\"\"\n Get pixel at position (x,y) with ram memory\n \"\"\"\n ad = self.SCR_MEM_MIN + (y * self.SCR_WIDTH) + x\n self.pixel = self.bus.readInMemory(ad)\n return\n\n def resetCursorPosition(self):\n \"\"\"\n Reset position of current cursor\n \"\"\"\n y = self.SCR_HEIGHT + 2\n sys.stdout.write(\"\\033[%d;%dH\" % (y, 0))\n return\n\n def updatePixelWithBusData(self, x, y):\n \"\"\"\n Update pixel at position with bus data\n \"\"\"\n u = unichr(self.bus.data) # int to ASCII\n u.encode('utf-8')\n #print(str(x) + \" - \" + str(y) + \" : \" + str(u))\n sys.stdout.write(\"\\033[%d;%dH%s\" % (y, x, u))\n return\n\n def updatePixel(self, x, y):\n \"\"\"\n Update pixel at position with ram memory\n \"\"\"\n self.getPixelInMemory(x, y)\n self.updatePixelWithBusData(x, y)\n return\n\n def updateFullScreen(self):\n \"\"\"\n Update all pixel of the screen with ram memory\n \"\"\"\n for x in range(self.SCR_WIDTH):\n for y in range(self.SCR_HEIGHT):\n updatePixel(x, y)\n self.flushScreen()\n return\n\n def clear(self):\n \"\"\"\n Clear screen\n \"\"\"\n os.system('clear')\n return\n\n def flushScreen(self):\n \"\"\"\n Update screen with last write\n \"\"\"\n self.resetCursorPosition()\n sys.stdout.flush()\n return\n\n cInputIndex = IN_MEM_MIN\n\n def keypressEvent(self, key):\n \"\"\"\n On keypres event\n \"\"\"\n if (not self.inputQueue.full()):\n self.inputQueue.put(key)\n\n def readInput(self, index):\n if (self.inputQueue.empty()):\n return 0\n inputIndx = self.IN_MEM_MAX - index\n key = self.inputQueue.get(inputIndx)\n return key\n\n def debugInputMemory(self): # For developpement\n res = \"\"\n while not self.inputQueue.empty():\n res += chr(self.readInput(self.IN_MEM_MIN))\n print(res)\n\n def pushWordInMemory(self, word): # For developpement\n for c in word:\n self.keypressEvent(ord(c))\n\n def listenKeyboard(self):\n \"\"\"\n Listening keyboard sync\n \"\"\"\n getch = _Getch()\n while self.keyboardListening:\n ch = getch()\n if not ch or ch == chr(4):\n break\n self.keypressEvent(ord(ch))\n\n def startKeyboardListening(self):\n \"\"\"\n Start listening keyboard async\n \"\"\"\n self.keyboardListening = True\n self.thr.start()\n\n def stopKeyboardListening(self):\n \"\"\"\n Stop listening keyboard async\n \"\"\"\n self.keyboardListening = False\n print(\"Press any key to quit\")\n\nclass _Getch:\n \"\"\"\n Gets a single character from standard input. Does not echo to the screen.\n \"\"\"\n def __init__(self):\n try:\n self.impl = _GetchWindows()\n except ImportError:\n self.impl = _GetchUnix()\n\n def __call__(self):\n return self.impl()\n\nclass _GetchUnix:\n def __init__(self):\n import tty, sys\n\n def __call__(self):\n import sys, tty, termios\n fd = sys.stdin.fileno()\n old_settings = termios.tcgetattr(fd)\n try:\n tty.setraw(sys.stdin.fileno())\n ch = sys.stdin.read(1)\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n return ch\n\n\nclass _GetchWindows:\n def __init__(self):\n import msvcrt\n\n def __call__(self):\n import msvcrt\n return msvcrt.getch()\n","sub_path":"io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":5101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"229306762","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 20 09:29:33 2018\n\n@author: 612383287\n\"\"\"\n#---------------------------------------------------#\n# CHAPTER 12 #\n#---------------------------------------------------#\n\n #---- Task 1 (Loop through a list)----#\n\nmy_shopping_cart = [\"cake\", \"plates\", \"plastic forks\", \"juice\", \"cups\"]\nfor item in my_shopping_cart:\n print (item)\n\n#---------------------------------------------------#\n# What is printed:\n#cake\n#plates\n#plastic forks\n#juice\n#cups\n#---------------------------------------------------#\n\n#Only got 5 items in your shoppingcart, the loop will only run 5 times. \n\n#Recap- list\nx = ['aa', 'b', 'cc']\nx[1] = 33 #overwrite\nx.append('dd') #add more items\n \n \n #---- Task 2 (Update list values)----#\n \nvalues = [875, 23, 451]\nfor val in values:\n print('---> '+str(val))\n\nfor val in values:\n print('---> '+str(val+50))\n \n #---- Task 3 (Create your own list)----#\n \nvalues = ['this', 55, 'that']\nfor item in values:\n print('***', item)\n\n \n #---- Task 4 (Loop through a string type)----#\n \nfor char in \"Yes\":\n print(char) \n\nfor char in 'I like to eat cake'.split('-'):\n print(char)\n \n #---- Task 5 (Loop through a tuple)----#\ntuple_a = (6,7,8)\n\nfor integer in tuple_a:\n print(integer)\n \n #-Task 6&7(Loop through dictionary data type)-#\n \nsalary = {}\nsalary['al'] = 20000\nsalary['bo'] = 50000\nsalary['ced'] = 1500 \n\nprint(sorted(salary.items()))\n\ndensities = {'iron':(7.8, 500, 3), 'gold':(19.3, 900, 4), 'zinc':(7.13, 200, 6), 'lead':(11.4, 800, 1)}\n\nmetals = list(densities.keys())\nprint(metals)\n\n#Sort the dictionary keys by their values, in reverse order:\nmetals.sort(reverse=True,key=lambda m:densities[m])\nprint(metals) \n\n\nkeyValue = (sorted(densities.items(), key=lambda kv:kv[1][1], reverse=True))\n\nprint ('From the highest share value:')\nfor key in keyValue:\n print (key[0], key[1][1])\n\n#---------------------------------------------------#\n# What is printed:\n#From the highest share value:\n#gold 900\n#lead 800\n#iron 500\n#zinc 200\n#---------------------------------------------------# \nfor metal, metalValue in keyValue:\n print(metal, metalValue)\n \nfor metal, metalValue in keyValue:\n print('metal:',metal, 'metalValue:',metalValue)\n \nfor metal in metals:\n print(metal,densities[metal])\n#---------------------------------------------------#\n# What is printed:\n#gold (19.3, 900, 4)\n#lead (11.4, 800, 1)\n#iron (7.8, 500, 3)\n#zinc (7.13, 200, 6)\n#metal: gold metalValue: (19.3, 900, 4)\n#metal: lead metalValue: (11.4, 800, 1)\n#metal: iron metalValue: (7.8, 500, 3)\n#metal: zinc metalValue: (7.13, 200, 6)\n#gold(19.3, 900, 4)\n#lead(11.4, 800, 1)\n#iron(7.8, 500, 3)\n#zinc(7.13, 200, 6)\n#---------------------------------------------------# \n\nfor metal in metals:\n print('{0:>8} = {1:5.1f}'.format(metal,densities[metal][0]))\n \n #-Task 8 (Combining counting loops and conditionals)-#\n \nfor metal in metals:\n if densities[metal][0] < 8:\n print(metal,densities[metal][0])\n else:\n print('!')\n \n #-Task 9 (Design a sum function)-#\n \n#Adding up the values within a list. \nvalues = [3, 12, 9]\ntotal = 0\nfor val in values:\n total += val\n print('TOTAL:' + str(total)) \n#total += val means the same as total = total + val.\nprint(total) \ntotal=100 \nfor val in values:\n total -= val\n print('TOTAL:' + str(total)) \n#total -= val means the same as total = total - val.\nprint(total) \ntotal=0\nfor metal in metals:\n if densities[metal][0] < 8:\n print('The densities below 8 are:',metal,densities[metal][0])\n total+=densities[metal][0]\n else:\n print('!')\n \nprint('The total of these densities is', total)\ntotal=0\nfor metal in metals:\n if densities[metal][1] < 600:\n print('The share price below 600 are:',metal,densities[metal][1])\n total+=densities[metal][1]\n else:\n print('!')\n \nprint('The total of these share prices are', total)\n\nchristmas_wishlist= {}\nchristmas_wishlist['private_jet']=(10)\nchristmas_wishlist['idris elba']=(9)\nchristmas_wishlist['skincare']=(7)\nchristmas_wishlist['chocolate']=(5)\n\npresent=list(christmas_wishlist.items())\n\nfor gift, item in christmas_wishlist.items():\n if item <= 8:\n print('Yay I received', item, 'of', gift,'.')\n else:\n print('No I want more of', gift,'.')\n \nfor k, v in christmas_wishlist.items():\n print('k:',k,'v:',v)\n \n #-Task 10 (Using loop with index values)-#\n #&\n #-Task 11 (Using a loop with the range function) -# \n \nprint(range(3))\nprint(list(range(3)))\nprint(len(range(3)))\n\nvalues = [3, 12, 9]\nfor index in range(len(values)):\n values[index] = values[index] * 2\n print(values)\n \nvalues = [3, 12, 9]\nfor index in range(len(values)):\n values[index] = values[index] ** 2\n print(values)\n \nfor i in range(3,10,2):\n print(i)\n \nfor index in range(1, len(values),2):\n print(values[index], 'with index' , index)\n values[index] = values[index] ** 2\n print(values)\n \napple= [1,2,3]\n\nfor a in apple:\n print(apple)\n#Prints 123 three times because three things in the list.\n\nchocolate = ['lindt', 'mars', 'snickers', 'dairy_milk']\nprint(chocolate) \nprint( list(range(len(chocolate))))#shows the index positions of the items in the list. Starts at 0. \nfor index in range(1, len(chocolate),2):\n print(chocolate[index]) \n \n #-Task 12 (Using break in for loops)-# \n \nnums = [1,5,30,200,101,100,22]\n\nfor n in nums:\n if n >100:\n print('break')\n break\n\nfor index in range(len(nums)):\n print('loop index', index, 'with value', nums[index])\n \n#---------------------------------------------------#\n#loop index 0 with value 1\n#loop index 1 with value 5\n#loop index 2 with value 30\n#loop index 3 with value 200\n#loop index 4 with value 101\n#loop index 5 with value 100\n#loop index 6 with value 22\n#---------------------------------------------------#\n \nfor index in range(len(nums)):\n if nums[index] >100:\n print('break:' , nums[index], 'with index', index)\n break\ncolors = ['red', 'green', 'blue','green','green','green','blue', 'red', 'blue']\nd={}\nfor item in colors:\n if item not in d:\n d[item] = 1\n print(d,'first time')\n else:\n d[item] = d[item] + 1\n print(d)\n \n \n #-Task 13 (Using nested loops)-#\n \nouter_vals = [1, 2, 3]\ninner_vals = ['A', 'B', 'C']\n#dict = {}\n#for oval in outer_vals:\n# print(oval)\n# for ival in inner_vals:\n# print(ival)\n# dict[ival] = oval\n#print(dict)\n \ndict = {}\nfor oval in [1, 2, 3]:\n for ival in ['A', 'B', 'C']:\n dict[oval] = ival\n print(dict)\n \n #-Task 14 (Multiplication table with a for loop)-#\n\nfor i in range(1,11):\n for j in range(1,11):\n print('{0:>3}'.format(i*j), end = '')\n print('\\n')\n\n\n","sub_path":"ch12_The_For_Loop/ch12_muna.py","file_name":"ch12_muna.py","file_ext":"py","file_size_in_byte":7000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"107098420","text":"from flask import Flask, render_template, redirect, url_for, request\nimport relays\n\napp = Flask(__name__)\ndesk_up = False\n@app.route('/')\n@app.route('/home')\ndef home():\n return render_template('index.html', title='Desk Control')\n\n@app.route('/up', methods=['POST'])\ndef up():\n if request.method == 'POST':\n if request.form.get('up') == 'true' and desk_up == False:\n relays.up()\n print(request.method)\n return redirect(url_for('home'))\n else:\n return redirect(url_for('home'))\n\n@app.route('/down', methods=['POST'])\ndef down():\n if request.method == 'POST':\n if request.form.get('down') == 'true':\n relays.down()\n print(request.method)\n return redirect(url_for('home'))\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port= 5000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"308724112","text":"from .. import db\nfrom tablib import Dataset\nfrom ..auth import get_current_user\nfrom ..shared_models.person import Person\nfrom ..shared_models.club import Club, ClubLeaderPosition\nfrom error import Error\nimport re\nfrom ..util import has_multiple_lines\n\ndef setup_clubs(data):\n user = get_current_user()\n\n club_data, parse_errors = _parse_clubs(data)\n\n if not parse_errors:\n clubs, setup_errors = _setup_club_graph(club_data)\n\n if not setup_errors:\n for club in clubs:\n db.add(club)\n\n db.commit()\n\n conflicts = _create_club_clusters(clubs)\n\n if not conflicts:\n db.commit()\n else:\n return conflicts\n else:\n return setup_errors\n else:\n return parse_errors\n\n #no errors to return if at this point\n return []\n\ndef _parse_clubs(data):\n clubs = []\n errors = []\n\n for index, row in enumerate(data):\n club_data, parse_errors = _parse_club(row, index)\n\n if not parse_errors:\n clubs.append(club_data)\n else:\n errors.extend(parse_errors)\n\n return clubs, errors\n\ndef _parse_club(club_data, index):\n user = get_current_user()\n \n errors = []\n\n raw_club_data = {\n 'name': club_data[0],\n 'meeting frequency': club_data[1],\n 'presidents': club_data[2],\n 'other leaders': club_data[3],\n 'faculty sponsors': club_data[4]\n }\n\n formatted_club_data = {\n 'name': raw_club_data['name'],\n 'meeting_frequency': raw_club_data['meeting frequency'],\n 'club_leaders': [],\n 'faculty_sponsors': []\n }\n\n for key, value in raw_club_data.iteritems():\n if value == '' and key != 'other leaders':\n errors.append(Error(user.username, 'clubs', 'error', 'No ' + key + ' on line ' + str(index + 2)))\n if key == 'name':\n if value.find('(') != -1 or value.find(')') != -1:\n errors.append(Error(user.username, 'clubs', 'error', 'Cannot have parentheses in club names. Please fix this club name: ' + value))\n elif key == 'presidents':\n presidents, parse_errors = _parse_presidents(value)\n if not parse_errors:\n formatted_club_data['club_leaders'].extend(presidents)\n else:\n errors.extend(parse_errors)\n elif key == 'other leaders':\n other_leaders, parse_errors = _parse_other_leaders(value, user)\n if not parse_errors:\n formatted_club_data['club_leaders'].extend(other_leaders)\n else:\n errors.extend(parse_errors)\n elif key == 'faculty sponsors':\n faculty_sponsors, parse_errors = _parse_faculty_sponsors(value)\n if not parse_errors:\n formatted_club_data['faculty_sponsors'].extend(faculty_sponsors)\n else:\n errors.extend(parse_errors)\n\n return formatted_club_data, errors\n\n#TODO: parse errors for different fields\ndef _parse_presidents(presidents_str):\n presidents = [name.split(None, 1) for name in presidents_str.split(', ')]\n return [{'first_name': president[0], 'last_name': president[1], 'position': 'president'} for president in presidents], []\n\ndef _parse_other_leaders(other_leaders_str, user):\n other_leaders = []\n errors = []\n\n if has_multiple_lines(other_leaders_str):\n other_leaders = other_leaders_str.splitlines()\n else:\n other_leaders = other_leaders_str.split(', ')\n\n other_leaders = [_parse_leader(leader, user, errors) for leader in filter(None, other_leaders)]\n\n return other_leaders, errors\n\ndef _parse_leader(leader_str, user, errors):\n leader = filter(None, re.split(r' \\(|\\)', leader_str))\n \n if len(leader) < 2:\n errors.append(Error(user.username, 'clubs', 'error', 'No leadership position provided for ' + leader_str + '.'))\n return None\n\n leader[0] = leader[0].split(None, 1)\n\n return {'first_name': leader[0][0], 'last_name': leader[0][1], 'position': leader[1]}\n\ndef _parse_faculty_sponsors(faculty_sponsors_str):\n faculty_sponsors = [name.split(None, 1) for name in faculty_sponsors_str.split(', ')]\n return [{'first_name': faculty_sponsor[0], 'last_name': faculty_sponsor[1]} for faculty_sponsor in faculty_sponsors], []\n\ndef _setup_club_graph(clubs_data):\n clubs = []\n errors = []\n\n user = get_current_user()\n\n for club_data in clubs_data:\n initialized_clubs, setup_errors = _initialize_club(club_data)\n\n if not setup_errors:\n clubs.extend(initialized_clubs)\n else:\n errors.extend(setup_errors)\n\n return clubs, errors\n\ndef _initialize_club(club_data):\n clubs = []\n errors = []\n\n if club_data['meeting_frequency'] == 'both sessions':\n initialized_clubs, init_errors = _initialize_both_sessions_club(club_data)\n \n if not init_errors:\n clubs.extend(initialized_clubs)\n else:\n errors.extend(init_errors)\n else:\n initialized_club, init_errors = _initialize_single_session_club(club_data)\n\n if not init_errors:\n clubs.append(initialized_club)\n else:\n errors.extend(init_errors)\n\n return clubs, errors\n\ndef _initialize_both_sessions_club(club_data):\n clubs = []\n errors = []\n\n for club_week in range(2):\n initialized_club, init_errors = _initialize_single_session_club(club_data)\n \n if not init_errors:\n initialized_club.club_week = 'week ' + str(club_week + 1)\n clubs.append(initialized_club)\n else:\n errors.extend(init_errors)\n\n return clubs, errors\n\ndef _initialize_single_session_club(club_data):\n errors = []\n\n user = get_current_user()\n\n club = Club(user.username, club_data['name'], club_data['meeting_frequency'])\n\n for club_leader_data in club_data['club_leaders']:\n club_leader = Person.query.filter_by(username=user.username,\n first_name=club_leader_data['first_name'],\n last_name=club_leader_data['last_name']).first()\n\n if club_leader is not None:\n club_leader_position = ClubLeaderPosition(club, club_leader, club_leader_data['position'])\n club.leaders.append(club_leader_position)\n\n if _leading_too_many_clubs(club_leader):\n errors.append(Error(user.username, 'clubs', 'error', '{first_name} {last_name} is leading more than 2 clubs.'.format(first_name=club_leader.first_name, last_name=club_leader.last_name)))\n else:\n #TODO: Try to find a person with a matching first or last name to suggest\n errors.append(Error(user.username, 'clubs', 'error', 'A student with the name {first_name} {last_name} could not be found. Please make sure that the name of the club leader in the clubs spreadsheet matches the student\\'s name in the people spreadsheet.'.format(first_name=club_leader_data['first_name'], last_name=club_leader_data['last_name'])))\n\n for faculty_sponsor_data in club_data['faculty_sponsors']:\n faculty_sponsor = Person.query.filter_by(username=user.username,\n grad_year='faculty',\n first_name=faculty_sponsor_data['first_name'],\n last_name=faculty_sponsor_data['last_name']).first()\n\n if faculty_sponsor is not None:\n club.faculty_sponsors.append(faculty_sponsor)\n\n if len(faculty_sponsor.sponsorships) > 2:\n errors.append(Error(user.username, 'clubs', 'error', '{first_name} {last_name} is sponsoring more than 2 clubs.'.format(first_name=faculty_sponsor.first_name, last_name=faculty_sponsor.last_name)))\n else:\n errors.append(Error(user.username, 'clubs', 'error', 'A faculty member with the name {first_name} {last_name} could not be found. Please make sure that the name of the faculty sponsor in the clubs spreadsheet matches the faculty member\\'s name in the people spreadsheet.'.format(first_name=faculty_sponsor_data['first_name'], last_name=faculty_sponsor_data['last_name'])))\n\n return club, errors\n\ndef _leading_too_many_clubs(leader):\n num_clubs = 0\n\n both_session_clubs_leading = set()\n\n for position in leader.leadership_positions:\n if position.club.meeting_frequency == 'one session':\n num_clubs += 1\n elif position.club.name not in both_session_clubs_leading:\n num_clubs += 1\n\n both_session_clubs_leading.add(position.club.name)\n\n return num_clubs > 2\n\n#uses standard bread-first graph search algorithm to find connected components (called clusters)\ndef _create_club_clusters(clubs):\n user = get_current_user()\n\n errors = []\n\n clubs_not_visited = filter(lambda club: club.meeting_frequency == 'one session', clubs)\n current_cluster = 1\n\n #functionally will be used as a stack\n clubs_to_visit = []\n\n #adds one club to the stack to kick off the search\n first_club = clubs[0]\n first_club.club_week = 'week 1'\n first_club.cluster = current_cluster\n\n clubs_to_visit.append(clubs[0])\n\n while clubs_to_visit:\n current_club = clubs_to_visit.pop()\n\n clubs_not_visited.remove(current_club)\n\n connected_clubs = clubs_connected_to(current_club)\n\n for connected_club in connected_clubs:\n if connected_club in clubs_not_visited and connected_club not in clubs_to_visit:\n connected_club.cluster = current_cluster\n\n if current_club.club_week == 'week 1':\n connected_club.club_week = 'week 2'\n else:\n connected_club.club_week = 'week 1'\n\n scheduling_overlap = _find_scheduling_confict_with(connected_club)\n if scheduling_overlap:\n errors.append(Error(user.username, 'clubs', 'error', 'Due to leadership conflicts, {first_club} and {second_club} \\\n can\\'t meet during the same week. As a result, any people who lead or are a faculty sponsor of both clubs must \\\n pick only one of the two to lead or supervise'.format(first_club=scheduling_overlap[0].name, second_club=scheduling_overlap[1].name)))\n\n clubs_to_visit.append(connected_club)\n\n #if still clubs to visit but no more in current cluster, then add to stack to continue connected-component detection\n if not clubs_to_visit and clubs_not_visited:\n current_cluster += 1\n\n new_cluster_start = clubs_not_visited[0]\n new_cluster_start.club_week = 'week 1'\n new_cluster_start.cluster = current_cluster\n\n clubs_to_visit.append(new_cluster_start)\n\n errors.extend(_check_leader_availability_for_both_session_clubs(user, clubs))\n\n return errors\n\ndef clubs_connected_to(club):\n leader_connections = {leadership_position.club \\\n for leader in club.leaders \\\n for leadership_position in leader.leader.leadership_positions}\n\n faculty_connections = {connected_club \\\n for faculty_sponsor in club.faculty_sponsors \\\n for connected_club in faculty_sponsor.sponsorships}\n\n all_connected_clubs = list(leader_connections | faculty_connections)\n\n # removes the club whose connected clubs are being fetched from the list\n return filter(lambda connected_club: connected_club.name != club.name, all_connected_clubs)\n\ndef _find_scheduling_confict_with(club):\n connected_clubs = clubs_connected_to(club)\n\n for connected_club in connected_clubs:\n #a club leader for a both session club only has to be there for one of them\n if connected_club.meeting_frequency != 'both sessions' and club.club_week == connected_club.club_week:\n return (club, connected_club)\n\n return None\n\ndef _check_leader_availability_for_both_session_clubs(user, clubs):\n errors = []\n\n both_session_clubs = filter(lambda club: club.meeting_frequency == 'both sessions', clubs)\n\n for both_session_club in both_session_clubs:\n connected_clubs = clubs_connected_to(both_session_club)\n unique_clusters = {club.cluster for club in connected_clubs if club.cluster}\n\n connected_clubs_in_same_cluster = len(connected_clubs) > 1 and len(unique_clusters) == 1\n connected_clubs_in_same_week = len({club.club_week for club in connected_clubs if club.cluster}) == 1\n\n if connected_clubs_in_same_cluster and connected_clubs_in_same_week and connected_clubs[0].club_week == both_session_club.club_week:\n errors.append(Error(user.username, 'clubs', 'error', 'Due to leadership conflicts, there are no \\\n leaders or faculty sponsors available to lead {club_week} of {both_session_club}. Please either \\\n remove a student or faculty sponsor from the leadership of {both_session_club}, or remove a leader \\\n or faculty sponsor from the leadership of one of the following clubs: {connected_clubs}'.format(club_week=both_session_club.club_week, both_session_club=both_session_club, connected_clubs=connected_clubs)))\n\n return errors\n\ndef undo_clubs():\n user = get_current_user()\n\n clubs_to_delete = Club.query.filter_by(username=user.username)\n\n map(db.delete, clubs_to_delete)\n\n user.current_scheduling_step = 'clubs'\n user.current_scheduling_step_progress = 'not_started'\n\n db.commit()","sub_path":"server/scheduling/clubs.py","file_name":"clubs.py","file_ext":"py","file_size_in_byte":13598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"351588434","text":"from spider.scheduler.master import Master\r\nimport spider.scheduler.base_scheduler_moudle\r\nfrom spider.define import Context\r\nfrom spider.define import Status\r\nfrom spider.define import Progress\r\nfrom spider.scheduler.base_scheduler_moudle import logger\r\nimport time\r\n\r\n\r\nclass Scheduler(spider.scheduler.base_scheduler_moudle.Scheduler):\r\n\r\n def __init__(self, **kwargs):\r\n super().__init__(**kwargs)\r\n self.options[\"is.init.monitor\"] = False\r\n self.options[\"is.init.timers\"] = False\r\n self.status = Status.WAITCONNECT\r\n self.master = Master(self, self.options[\"init.master.host\"], self.options[\r\n \"init.master.port\"])\r\n\r\n req_ctx_extend = {\r\n Context.CONNECTED: self.__response_connected,\r\n Context.SUBMMIT_TASK: self.__response_submmit_task,\r\n Context.CLOSE_WITH_EXCEPTION: self.__response_close_with_exception,\r\n Context.REQUEST_MODULE: self.__response_request_module,\r\n }\r\n\r\n self.__req_context.update(req_ctx_extend)\r\n\r\n def __response_connected(self):\r\n self.status = Status.IDLE\r\n self.master.do(Context.INFO, self.hostname(), self.system(),\r\n self.machine(), self.version(), self.status.value)\r\n\r\n def __response_task(self):\r\n if self.__tasks.empty():\r\n self.master.do(Context.TASK)\r\n return super().__response_task()\r\n\r\n def __response_submmit_task(self, task):\r\n self.__tasks.put((task, Progress.NEW))\r\n\r\n def __response_request_module(self, name):\r\n self.master.do(Context.MODULE, name)\r\n\r\n def __response_close_with_exception(self):\r\n self.master.join()\r\n logger.info(\"the master connection is close with exception\")\r\n\r\n def exec(self):\r\n count = 0\r\n while self.__quit and(self.options[\"init.reconnect.count\"] < 0 or count < self.options[\"init.reconnect.count\"]):\r\n try:\r\n self.master.connect()\r\n self.master.start()\r\n super().exec()\r\n except Exception as e:\r\n logger.error(\"connect master %s:%s error:%s\", self.options[\r\n \"init.master.host\"], self.options[\"init.master.port\"], e)\r\n time.sleep(1)\r\n count = count + 1\r\n","sub_path":"spider/scheduler/worker_scheduler_moudle.py","file_name":"worker_scheduler_moudle.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"138540783","text":"import Queue\nimport threading\n\nclass StreamsFilter():\n\tdef __init__(self):\n\t\tself.input_queue = Queue.Queue()\n\t\tself.output_queue = Queue.Queue()\n\t\tself.l = threading.Lock()\n\t\tself.in_count = 0\n\t\tself.out_count = 0\n\tdef add_tuple(self, tuple):\n\t\t# Aquire concurent Lock and put tuple in queue\n\t\tself.l.acquire()\n\t\tself.input_queue.put(tuple)\n\t\t\n\t\t# Increment tuple counter\n\t\tself.in_count += 1\n\n\t\t# Release concurrent lock\n\t\tself.l.release()\n\tdef get_tuple(self):\n\t\t# Acquire concurrent lock and get a tuple if the queue is not\n\t\t# empty\n\t\tself.l.acquire()\n\t\tif not self.output_queue.empty():\n\t\t\ttuple = self.output_queue.get()\n\t\t\t\n\t\t\t# Increment Counter and return tuple\n\t\t\tself.out_count += 1\n\t\t\tself.l.release()\n\t\t\treturn tuple\n\t\tself.l.release()\n\tdef process(self):\n\t\t# This is an idenity filter all in all out\n\t\tin_tuple = self.input_queue.get()\n\t\tself.output_queue.put(in_tuple)\n\nclass MyFilter(StreamsFilter):\n\t#Override process method\n\tdef process(self):\n\t\tin_tuple = self.input_queue.get()\n\t\tif len( in_tuple[1].split(\" \") ) > 10:\n\t\t\tself.output_queue.put((in_tuple[0], in_tuple[1].replace(\"e\", \"*!*\")))\n\n","sub_path":"data/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"370373633","text":"import math\nimport numpy as np\nfrom scipy.stats import rv_discrete\nimport threading\nimport time\nimport logging\nimport random\nimport matplotlib.pyplot as plt\nfrom limit_order import *\n#import joystick as jk\nfrom LOB import *\n\ns = np.random.poisson(5, 1000000)\n#print(s)\ncount, bins, ignored = plt.hist(s, 14, normed=True)\n#plt.show()\n\ndef nextTime(rateParameter):\n return -math.log(1.0 - random.random()) / rateParameter\n\ndef nextTime_process(times, index, rateParameter):\n times[index] = -math.log(1.0 - random.random()) / rateParameter[index]\n\n\n\n\n\n#print(nextTime(1/40.0))\n#number of shares will be in unit size\n#Market Orders - Buy/Sell\n#Limit Orders - Buy/Sell\n#Cancellation Orders for for placed limit orders\n#Price scale will be price\n#time-scale will be milliseconds\ndp = 1 #the tick size on the price - unit price difference\norders = 1 #the order size - unit\nmarket_order_rate_buy = 2 #units of shares/ms time\nmarket_order_rate_sell = 2 #units of shares/ms time\nlimit_order_rate_buy = 3 #units of shares/price(log) time(ms)\nlimit_order_rate_sell = 3 #units of shares/price(log) time(ms)\norder_cancellation_rate = 0.2 #units of 1/time(ms) - 1 cancelled every 10 ms on average\n#now make poisson processes for each of the 5 processes -\n#Market Order Buy, Market Order Sell, Limit Order Buy, Limit Order Sell, Order Cancel\n#they will each generate the next time step, and then for the earliest time, if it is a\n#limit order, project it onto the (log) price dimension, spaced at every dp intervals\nbegin_time = time.time() #this is the beginning of the trade simulation process\n#Limit orders - poisson process over time, then poisson process over price, decide on cancellation\n#time through poisson process over time\n#Market Orders - poisson process over time\nid = 0 #the last market/limit order id processed\nmarket_order_buy_ids_queue = () #list of market orders buys - will be in a queue format\nmarket_order_sell_ids_queue = () #list of market orders sells - will be in a queue format\nlimit_order_buy_ids_queue = () #list of limt order buys - will be in a queue format\nlimit_order_sell_ids_queue = () #list of limt order sells - will be in a queue format\n#print(nextTime(order_cancellation_rate))\nnum_possible_orders = 4\nrate_parameters_per_process = [None] * num_possible_orders\nrate_parameters_per_process[0] = market_order_rate_buy #0 - market order buy\nrate_parameters_per_process[1] = market_order_rate_sell #1 - market order sell\nrate_parameters_per_process[2] = limit_order_rate_buy #2 - limit order buy\nrate_parameters_per_process[3] = limit_order_rate_sell #3 - limit order sell\n#first of all, initialize the order book to a reasonable approximation of the steady-state distribution\n#meaning, place limit buy and limit sell orders after choosing the midpoint of the spread\n#they will probably change once they equilibriate\nlowest_ask = 104.00\nhighest_bid = 102.00\nspread = lowest_ask - highest_bid\nmid_spread = (lowest_ask + highest_bid) / 2\n#print(\"Spread = %f, Midpoint = %f\" % (spread, mid_spread))\n#now, fill up the order book\n#bids will be placed from lowest ask to -infinity and asks will be placed from highest bid to +infinity\n#print(begin_time)\nend_time = begin_time + 20 #build initial LOB for 20 seconds\nnum_possible_orders_i = 2\nk = 0\ncurr_time = time.time()\ncurr_time_from_beg = curr_time - begin_time\nlob = LimitOrderBook()\nid = 0\nwhile(curr_time <= end_time):\n#while(k < 10):\n curr_time_from_beg = curr_time - begin_time\n threads = [None] * num_possible_orders_i\n times = [None] * num_possible_orders_i\n for i in range(num_possible_orders_i):\n threads[i] = threading.Thread(target=nextTime_process, args=(times, i, rate_parameters_per_process[2:4]))\n threads[i].start()\n\n for i in range(len(threads)):\n threads[i].join()\n\n min_time = min(times)\n\n '''print(\"Iteration %d, Limit Order Buy Time = %f, Limit Order Sell Time = %f, Minimum Time = %f, \"\n \"Index of minimum time = %d\"\n % (k + 1, times[0], times[1], min_time, times.index(min_time)))'''\n #now, pick a price based on whether or not it was buy or sell\n prices_range = np.ones(1) #only to initialize\n probability = np.ones(1) #only to initialize - uniform distribution\n buy_or_sell = times.index(min_time)\n cancel_time = nextTime(order_cancellation_rate)\n buy_sell = 1 #just an argument to pass to LimitOrder object (-1 is buy, +1 is sell)\n if (buy_or_sell == 0): #buy\n prices_range = np.arange(highest_bid - 5, highest_bid + dp, dp)\n prob = (float) (1.0 / len(prices_range))\n probability = np.full(len(prices_range), prob)\n '''print(\"Highest Bid before = %f\" % highest_bid)\n highest_bid = max(prices_range)\n print(\"Highest Bid now = %f\" % highest_bid)\n print(\"Lowest Ask now = %f\" % lowest_ask)'''\n #lo = LimitOrder(k + 1, -1, time.time() - begin_time, cancel_time, orders)\n buy_sell = -1\n\n else: #sell\n prices_range = np.arange(lowest_ask, lowest_ask + 5 + dp, dp)\n prob = (float) (1.0 / len(prices_range))\n probability = np.full(len(prices_range), prob)\n\n '''print(\"Lowest Ask before = %f\" % lowest_ask)\n lowest_ask = max(prices_range)\n print(\"Lowest Ask now = %f\" % lowest_ask)\n print(\"Highest Bid now = %f\" % highest_bid)'''\n '''print(prices_range)\n print(probability)'''\n distrib = rv_discrete(values=(prices_range, probability))\n price_picked = distrib.rvs(size=1)\n '''print(price_picked)\n print(price_picked[0])'''\n lo = LimitOrder(id + 1, buy_sell, price_picked[0], curr_time + min_time - begin_time, cancel_time, orders, lob) #make a limit order object\n lob.add_limit_order(lo) #add the limit order to the limit order book\n #print(\"Price Picked = %f\" % price_picked)\n '''if (buy_or_sell == 0): #buy\n #check if the highest bid has changed\n if (price_picked > highest_bid): #if spread has changed due to highest bid changing\n print(\"Highest bid has changed. Highest bid before = %f, Highest bid now = %f\"\n % (highest_bid, price_picked))\n highest_bid = price_picked\n spread_new = lowest_ask - highest_bid\n print(\"Spread will also change. Spread before = %f, Spread now = %f\"\n %(spread, spread_new))\n spread = spread_new\n else: #spread remains the same\n print(\"Spread and Highest Bid remain the same. Spread = %f, Highest Bid = %f\"\n % (spread, highest_bid))\n else: #sell\n if (price_picked < lowest_ask):\n print(\"Lowest Ask has changed. Lowest Ask before = %f, Lowest Ask now = %f\"\n % (lowest_ask, price_picked))\n lowest_ask = price_picked\n spread_new = lowest_ask - highest_bid\n print(\"Spread will also change. Spread before = %f, Spread now = %f\"\n % (spread, spread_new))\n spread = spread_new\n else: # spread remains the same\n print(\"Spread and Lowest Ask remain the same. Spread = %f, Lowest Ask = %f\"\n % (spread, lowest_ask))'''\n '''print(\"Price Picked = %f\" % price_picked)\n print(\"Spread before = %f\" % spread)\n spread = lowest_ask - highest_bid\n print(\"Spread now = %f\" % spread)'''\n curr_time = time.time()\n k = k + 1\n id = id + 1 #for the next limit order's id\n\nprint(\"At the end of steady state. Highest Bid = %f, Lowest Ask = %f, Spread = %f\"\n % (highest_bid, lowest_ask, spread))\nlob.show_lob() #to see the contents\n\n\n\ndef generate_next_order(time_started, next_time_to_start, idx, ret_lst, lob):\n while (time.time() - time_started < next_time_to_start):\n i = 0\n\n highest_bid = ret_lst[0]\n lowest_ask = ret_lst[1]\n spread = lowest_ask - highest_bid\n if (idx == 0): #a market buy order was generated, then delete sell side\n print(\"Previous highest bid = %f, Previous lowest ask = %f, Previous spread = %f\"\n %(highest_bid, lowest_ask, spread))\n lob.del_limit_sell()\n #lowest_ask = lob.limit_sells[0][0] #lowest ask has changed\n lowest_ask = lob.get_lowest_ask()\n highest_bid = lob.get_highest_bid()\n spread = lowest_ask - highest_bid\n print(\"Current highest bid = %f, Current lowest ask = %f, Current spread = %f\"\n % (highest_bid, lowest_ask, spread))\n elif (idx == 1): #a market sell order was generated, then delete buy side\n print(\"Previous highest bid = %f, Previous lowest ask = %f, Previous spread = %f\"\n % (highest_bid, lowest_ask, spread))\n lob.del_limit_buy()\n #highest_bid = lob.limit_buys[0][0] #highest bid has changed\n lowest_ask = lob.get_lowest_ask()\n highest_bid = lob.get_highest_bid()\n spread = lowest_ask - highest_bid\n print(\"Current highest bid = %f, Current lowest ask = %f, Current spread = %f\"\n % (highest_bid, lowest_ask, spread))\n\n\n\n #now, if it is a limit order, add this to the limit order book\n elif (idx == 2): #limit buy\n lowest_ask = lob.get_lowest_ask() #the lowest ask currently\n prices_range = np.arange(lowest_ask - 5, lowest_ask + dp, dp) #the price range\n prob = (float)(1.0 / len(prices_range))\n probability = np.full(len(prices_range), prob)\n distrib = rv_discrete(values=(prices_range, probability))\n price_picked = distrib.rvs(size=1) #pick a price from the range\n print(\"Previous highest bid = %f, Previous lowest ask = %f, Previous spread = %f\"\n % (highest_bid, lowest_ask, spread))\n print(\"Limit buy price = %f\" % price_picked)\n lo = LimitOrder(id + 1, -1, price_picked[0], curr_time + min_time - begin_time,\n cancel_time, orders,\n lob) # make a limit order object\n lob.add_limit_order(lo) # add the limit order to the limit order book\n\n #spawn a new thread to check if this limit order has reached cancellation time\n t = threading.Thread(target=poke_per_limitorder, args=(lo, curr_time + min_time))\n t.start()\n\n #check to see if the highest bid has changed due to this buy limit order\n highest_bid = lob.get_highest_bid()\n spread = lowest_ask - highest_bid\n print(\"Current highest bid = %f, Current lowest ask = %f, Current spread = %f\"\n % (highest_bid, lowest_ask, spread))\n\n\n else: #limit sell\n highest_bid = lob.get_highest_bid() #the highest bid currently\n prices_range = np.arange(highest_bid, highest_bid + 5 + dp, dp) #the price range\n prob = (float)(1.0 / len(prices_range))\n probability = np.full(len(prices_range), prob)\n distrib = rv_discrete(values=(prices_range, probability))\n price_picked = distrib.rvs(size=1) #pick a price from the range\n print(\"Previous highest bid = %f, Previous lowest ask = %f, Previous spread = %f\"\n % (highest_bid, lowest_ask, spread))\n print(\"Limit sell price = %f\" % price_picked)\n lo = LimitOrder(id + 1, 1, price_picked[0], curr_time + min_time - begin_time,\n cancel_time, orders,\n lob) # make a limit order object\n lob.add_limit_order(lo) # add the limit order to the limit order book\n\n # spawn a new thread to check if this limit order has reached cancellation time\n t = threading.Thread(target=poke_per_limitorder, args=(lo, curr_time + min_time))\n t.start()\n\n # check to see if the lowest ask has changed due to this ask limit order\n lowest_ask = lob.get_lowest_ask()\n spread = lowest_ask - highest_bid\n print(\"Current highest bid = %f, Current lowest ask = %f, Current spread = %f\"\n % (highest_bid, lowest_ask, spread))\n\n #ret_lst = ()\n #change values for highest bid and lowest ask\n ret_lst[0] = highest_bid\n ret_lst[1] = lowest_ask\n\n\n\nj = 0\ncurr_time = time.time()\n\n\nret_lst = list()\nret_lst.append(highest_bid)\nret_lst.append(lowest_ask)\nwhile(True):\n#while(j < 8):\n #now, spawn 4 threads each for market buy, market sell, limit buy, limit sell\n #see which one has the lowest next time\n threads = [None] * num_possible_orders\n times = [None] * num_possible_orders\n for i in range(num_possible_orders):\n threads[i] = threading.Thread(target=nextTime_process, args=(times, i, rate_parameters_per_process))\n threads[i].start()\n\n for i in range(len(threads)):\n threads[i].join()\n\n min_time = min(times)\n idx = times.index(min_time)\n\n print(\"Iteration %d, Market Order Buy Time = %f, Market Order Sell Time = %f, Limit Order Buy Time = %f, \"\n \"Limit Order Sell Time = %f, Minimum Time = %f, Index of minimum time = %d\"\n % (j + 1, times[0], times[1], times[2], times[3], min_time, idx))\n\n\n th = threading.Thread(target=generate_next_order, args=(curr_time, min_time, idx, ret_lst, lob))\n th.start()\n print(\"Waiting....Iteration %d\" % (j + 1))\n th.join()\n print(\"Finished waiting...Iteration %d\" % (j + 1))\n\n # #now if it is a market order, then access the limit order book object, and extract the opposite\n # #side's market offer, and then change the highest bid and lowest ask, and thereby the spread value\n # #no synchronization needed here\n # if (idx == 0): #a market buy order was generated, then delete sell side\n # print(\"Previous highest bid = %f, Previous lowest ask = %f, Previous spread = %f\"\n # %(highest_bid, lowest_ask, spread))\n # lob.del_limit_sell()\n # #lowest_ask = lob.limit_sells[0][0] #lowest ask has changed\n # lowest_ask = lob.get_lowest_ask()\n # highest_bid = lob.get_highest_bid()\n # spread = lowest_ask - highest_bid\n # print(\"Current highest bid = %f, Current lowest ask = %f, Current spread = %f\"\n # % (highest_bid, lowest_ask, spread))\n # elif (idx == 1): #a market sell order was generated, then delete buy side\n # print(\"Previous highest bid = %f, Previous lowest ask = %f, Previous spread = %f\"\n # % (highest_bid, lowest_ask, spread))\n # lob.del_limit_buy()\n # #highest_bid = lob.limit_buys[0][0] #highest bid has changed\n # lowest_ask = lob.get_lowest_ask()\n # highest_bid = lob.get_highest_bid()\n # spread = lowest_ask - highest_bid\n # print(\"Current highest bid = %f, Current lowest ask = %f, Current spread = %f\"\n # % (highest_bid, lowest_ask, spread))\n #\n #\n #\n # #now, if it is a limit order, add this to the limit order book\n # elif (idx == 2): #limit buy\n # lowest_ask = lob.get_lowest_ask() #the lowest ask currently\n # prices_range = np.arange(lowest_ask - 5, lowest_ask + dp, dp) #the price range\n # prob = (float)(1.0 / len(prices_range))\n # probability = np.full(len(prices_range), prob)\n # distrib = rv_discrete(values=(prices_range, probability))\n # price_picked = distrib.rvs(size=1) #pick a price from the range\n # print(\"Previous highest bid = %f, Previous lowest ask = %f, Previous spread = %f\"\n # % (highest_bid, lowest_ask, spread))\n # print(\"Limit buy price = %f\" % price_picked)\n #\n # lo = LimitOrder(id + 1, -1, price_picked[0], curr_time + min_time - begin_time,\n # cancel_time, orders,\n # lob) # make a limit order object\n # lob.add_limit_order(lo) # add the limit order to the limit order book\n #\n # #spawn a new thread to check if this limit order has reached cancellation time\n # t = threading.Thread(target=poke_per_limitorder, args=(lo, curr_time + min_time))\n # t.start()\n #\n # #check to see if the highest bid has changed due to this buy limit order\n # highest_bid = lob.get_highest_bid()\n # spread = lowest_ask - highest_bid\n # print(\"Current highest bid = %f, Current lowest ask = %f, Current spread = %f\"\n # % (highest_bid, lowest_ask, spread))\n #\n #\n # else: #limit sell\n # highest_bid = lob.get_highest_bid() #the highest bid currently\n # prices_range = np.arange(highest_bid, highest_bid + 5 + dp, dp) #the price range\n # prob = (float)(1.0 / len(prices_range))\n # probability = np.full(len(prices_range), prob)\n # distrib = rv_discrete(values=(prices_range, probability))\n # price_picked = distrib.rvs(size=1) #pick a price from the range\n # print(\"Previous highest bid = %f, Previous lowest ask = %f, Previous spread = %f\"\n # % (highest_bid, lowest_ask, spread))\n # print(\"Limit sell price = %f\" % price_picked)\n # lo = LimitOrder(id + 1, 1, price_picked[0], curr_time + min_time - begin_time,\n # cancel_time, orders,\n # lob) # make a limit order object\n # lob.add_limit_order(lo) # add the limit order to the limit order book\n #\n # # spawn a new thread to check if this limit order has reached cancellation time\n # t = threading.Thread(target=poke_per_limitorder, args=(lo, curr_time + min_time))\n # t.start()\n #\n # # check to see if the lowest ask has changed due to this ask limit order\n # lowest_ask = lob.get_lowest_ask()\n # spread = lowest_ask - highest_bid\n # print(\"Current highest bid = %f, Current lowest ask = %f, Current spread = %f\"\n # % (highest_bid, lowest_ask, spread))\n\n #now, that orders have been generated, we have to service limit order matchings\n highest_bid = ret_lst[0]\n lowest_ask = ret_lst[1]\n if (lowest_ask == highest_bid or lowest_ask < highest_bid): #delete both lowest ask and highest bid indicating they have been fulfilled\n print(\"Matched limit buy with limit sell...\")\n print(\"Deleting Highest bid = %f, Deleting Lowest sell = %f\" %(highest_bid, lowest_ask))\n lob.del_limit_buy()\n lob.del_limit_sell()\n lowest_ask = lob.get_lowest_ask()\n highest_bid = lob.get_highest_bid()\n print(\"New Highest bid = %f, New Lowest sell = %f\" %(highest_bid, lowest_ask))\n #otherwise, no trade took place\n else:\n print(\"No trading took place...\")\n\n\n curr_time = time.time()\n j = j + 1\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Zero-Intelligence-Market/zero-intelligence-market.py","file_name":"zero-intelligence-market.py","file_ext":"py","file_size_in_byte":18342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"481629150","text":"class Solution:\n '''\n 思路1: dfs或bfs遍历,每一层子孩子数为当前number. 时间复杂度mean(nums)**n\n 思路2: dp一维, Time O(n**3), Space O(n)\n 思路3: 贪心,从后往前看,每次都选择距离最远的上一步。O(n**2)\n 思路4: 贪心,从前往后,每次跳时,跳到当前所能跳到范围内所有位置里下一步能跳到最远的\n '''\n def jump(self, nums):\n if len(nums)==1: return 0\n i, res = 0, 0\n while i=len(nums)-1:\n return res+1\n elif nums[i+step]+i+step > furthest:\n furthest = nums[i+step]+i+step\n best_step = step\n i += best_step\n res += 1\n \n def jump_dp(self, nums: List[int]) -> int: # Time Limit Exceeded, 90 / 92 test cases passed.\n dp = [len(nums)]*(len(nums)+1)\n dp[1] = 0\n for i in range(1, len(dp)):\n for j in range(1, i):\n if nums[i-j-1] >= j:\n dp[i] = min(dp[i], dp[i-j] + 1)\n return dp[-1]\n\n def jump1(self, nums): # Time Limit Exceeded, 90 / 92 test cases passed.\n i, res = len(nums)-1, 0\n while i>0:\n for j in range(i):\n if nums[j] + j >= i:\n i = j\n res += 1\n break\n return res\n \n","sub_path":"Greedy/45-JumpGameII.py","file_name":"45-JumpGameII.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"127485449","text":"\"\"\"\nSupport for reading and writing galsim.Image* objects to FITS, via new\nPython-only methods injected into the Image classes.\n\"\"\"\nimport os\nfrom sys import byteorder\nfrom . import _galsim\n\n# Convert sys.byteorder into the notation numpy dtypes use\nnative_byteorder = {'big': '>', 'little': '<'}[byteorder]\n\ndef write(image, fits, add_wcs=True, clobber=True):\n \"\"\"\n Write the image to a FITS file, with details depending on the type of\n the 'fits' argument:\n - If 'fits' is a pyfits.HDUList, the image will be appended as a new HDU.\n The user is responsible for calling fits.writeto(...) afterwards.\n - If 'fits' is a string, it will be interpreted as a filename for a new\n FITS file.\n \n If add_wcs evaluates to True, a 'LINEAR' WCS will be added using the Image's\n bounding box. This is not necessary to ensure an Image can be round-tripped\n through FITS, as the bounding box (and scale) are always saved in custom header\n keys. If add_true is a string, this will be used as the WCS name.\n\n This function called be called directly as \"galsim.fits.write(image, ...)\",\n with the image as the first argument, or as an image method: \"image.write(...)\".\n\n Setting clobber=True when 'fits' is a string will silently overwrite existing files.\n \"\"\"\n import pyfits # put this at function scope to keep pyfits optional\n\n if isinstance(fits, pyfits.HDUList):\n hdus = fits\n else:\n hdus = pyfits.HDUList()\n if len(hdus) == 0:\n hdu = pyfits.PrimaryHDU(image.array)\n else:\n hdu = pyfits.ImageHDU(image.array)\n hdus.append(hdu)\n hdu.header.update(\"GS_SCALE\", image.scale, \"GalSim Image scale\")\n hdu.header.update(\"GS_XMIN\", image.xMin, \"GalSim Image minimum X coordinate\")\n hdu.header.update(\"GS_YMIN\", image.xMin, \"GalSim Image minimum Y coordinate\")\n\n if add_wcs:\n if isinstance(add_wcs, basestring):\n wcsname = add_wcs\n else:\n wcsname = \"\"\n hdu.header.update(\"CTYPE1\" + wcsname, \"LINEAR\", \"name of the coordinate axis\")\n hdu.header.update(\"CTYPE2\" + wcsname, \"LINEAR\", \"name of the coordinate axis\")\n hdu.header.update(\"CRVAL1\" + wcsname, image.xMin, \n \"coordinate system value at reference pixel\")\n hdu.header.update(\"CRVAL2\" + wcsname, image.yMin, \n \"coordinate system value at reference pixel\")\n hdu.header.update(\"CRPIX1\" + wcsname, 1, \"coordinate system reference pixel\")\n hdu.header.update(\"CRPIX2\" + wcsname, 1, \"coordinate system reference pixel\")\n \n if isinstance(fits, basestring):\n if clobber and os.path.isfile(fits):\n os.remove(fits)\n hdus.writeto(fits)\n\n\ndef read(fits):\n \"\"\"\n Construct a new Image from a FITS representation.\n - If 'fits' is a pyfits.HDUList, the Primary HDU will be used.\n - If 'fits' is a pyfits.PrimaryHDU or pyfits.ImageHDU, that HDU will be used.\n - If 'fits' is a string, it will be interpreted as a filename to open;\n the Primary HDU of that file will be used.\n\n If the FITS header has GS_* keywords, these will be used to initialize the\n bounding box and scale. If not, the bounding box will have (xMin,yMin) at\n (1,1) and the scale will be set to 1.0.\n\n Not all FITS pixel types are supported (only those with C++ Image template\n instantiations are: short, int, float, and double).\n\n This function can be called directly as \"galsim.fits.read(...)\", or as a static\n method of an image class: \"ImageD.read(...)\". Note, however, that in the\n latter case the image type returned is determined by the type of the FITS file,\n not the image class (in other words, \"ImageD.read(...)\" might return an ImageF).\n \"\"\"\n import pyfits # put this at function scope to keep pyfits optional\n \n if isinstance(fits, basestring):\n fits = pyfits.open(fits)\n if isinstance(fits, pyfits.HDUList):\n fits = fits[0]\n xMin = fits.header.get(\"GS_XMIN\", 1)\n yMin = fits.header.get(\"GS_YMIN\", 1)\n scale = fits.header.get(\"GS_SCALE\", 1.0)\n pixel = fits.data.dtype.type\n try:\n Class = _galsim.Image[pixel]\n except KeyError:\n raise TypeError(\"No C++ Image template instantiation for pixel type %s\" % pixel)\n # Check through byteorder possibilities, compare to native (used for numpy and our default) and\n # swap if necessary so that C++ gets the correct view.\n if fits.data.dtype.byteorder == '!':\n if native_byteorder == '>':\n pass\n else:\n fits.data.byteswap(True)\n elif fits.data.dtype.byteorder in (native_byteorder, '=', '@'):\n pass\n else:\n fits.data.byteswap(True) # Note inplace is just an arg, not a kwarg, inplace=True throws\n # a TypeError exception in EPD Python 2.7.2\n image = Class(array=fits.data, xMin=xMin, yMin=yMin)\n image.scale = scale\n return image\n\n# inject read/write as methods of Image classes\nfor Class in _galsim.Image.itervalues():\n Class.write = write\n Class.read = staticmethod(read)\ndel Class # cleanup public namespace\n","sub_path":"galsim/fits.py","file_name":"fits.py","file_ext":"py","file_size_in_byte":5156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"421308432","text":"import requests, time, json\n\nstart_time = time.time() # 初始时间戳\n# ================读取剪贴板================\nfrom tkinter import Tk\n\nr = Tk()\nread_text = r.clipboard_get()\ntext_readline = read_text.splitlines() # 对数据分行\nprint(text_readline)\n\nline = []\nfor i in range(len(text_readline)):\n entry_start_time = time.time()\n try:\n # ========================获取对应Hash========================\n html = requests.get('http://api.kanzhihu.com/searchuser/' + text_readline[i])\n data = json.loads(html.text) # 将json字符串转换成python对象\n users = data['users']\n first_user = users[0]\n user_hash = first_user['hash']\n print(user_hash)\n line.append(user_hash)\n except:\n line.append(\"\")\n line_text = '\\r\\n'.join(line)\n # ================每项时间计时================\n entry_run_time = time.time() - entry_start_time\n entry_print = \"耗时:{:.4f}秒\".format(entry_run_time)\n print(entry_print)\n\n# ================写入剪贴板================\nimport pyperclip\n\npyperclip.copy(line_text)\nspam = pyperclip.paste()\n\n# ================写入TXT================\ntxt_file_path = '/Users/alicewish/我的坚果云/批量查询用户Hash.txt' # TXT文件名\nf = open(txt_file_path, 'w')\ntry:\n f.write(line_text)\nfinally:\n f.close()\n# ================运行时间计时================\nrun_time = time.time() - start_time\nif run_time < 60: # 两位小数的秒\n print(\"耗时:{:.2f}秒\".format(run_time))\nelif run_time < 3600: # 分秒取整\n print(\"耗时:{:.0f}分{:.0f}秒\".format(run_time // 60, run_time % 60))\nelse: # 时分秒取整\n print(\"耗时:{:.0f}时{:.0f}分{:.0f}秒\".format(run_time // 3600, run_time % 3600 // 60, run_time % 60))\n","sub_path":"知乎-看知乎-批量查询用户Hash.py","file_name":"知乎-看知乎-批量查询用户Hash.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"48400901","text":"from bs4 import BeautifulSoup as BS\nimport requests, os, time, pprint, json\nimport datetime\n\n\nall_types = ['https://www.limetorrents.info/browse-torrents/Movies/', # Movies\n 'https://www.limetorrents.info/browse-torrents/TV-shows/', # Tv-shows\n 'https://www.limetorrents.info/browse-torrents/Music/', # Music\n 'https://www.limetorrents.info/browse-torrents/Games/', # Games\n 'https://www.limetorrents.info/browse-torrents/Applications/', # Applications\n 'https://www.limetorrents.info/browse-torrents/Anime/', # Anime\n 'https://www.limetorrents.info/browse-torrents/Other/'] # Other\n\ndef make_request(url):\n page = requests.get(url)\n soup = BS(page.text,'html.parser')\n return soup\n\n\ndef create_date(str):\n today = datetime.date.today()\n if 'minutes' or 'hours' in str:\n return today\n elif 'Yesterday' in str:\n yesterday_date = int(today[9:]) - 1\n return today[:9] + yesterday_date\n elif 'days' in str:\n date = int(today[9:]) - int(str.split(' days ago'))\n return toady[:9] + date\n elif 'Month' in str:\n month = int(toady[5:7]) - 1\n return toady[0:5] + month + today[7:]\n\ndef get_links():\n filePath = 'cache/limetorrents/all_links.json'\n if os.path.exists(filePath):\n file = open(filePath)\n read_data = file.read()\n all_urls_list = json.loads(read_data)\n return all_urls_list\n\n all_pages_urls = []\n for type in all_types:\n soup = make_request(type)\n page_div = soup.find('div', class_='search_stat')\n all_links = page_div.find_all('a')\n total_pages_count = int(all_links[-2].get_text())\n page_url = \"https://www.limetorrents.info\"+ all_links[0].get('href')[:-2]\n for i in range(1,total_pages_count+1):\n all_pages_urls.append(page_url + str(i) + '/')\n with open(filePath,'w') as file:\n text = json.dumps(all_pages_urls, sort_keys=True, indent=4)\n file.write(text)\n file.close()\n return all_pages_urls\n\ndef single_page_details(html,count):\n soup = BS(html,'html.parser')\n table = soup.find('table', class_ = 'table2')\n trs = table.find_all('tr')\n trs.pop(0)\n details_list = []\n for tr in trs:\n details_dict = {}\n details_dict['name'] = tr.find('td', class_='tdleft').div.get_text().strip()\n details_dict['hash'] = tr.find('td', class_='tdleft').a['href'].split('/torrent/')[1].split('.torrent')[0]\n date_size_tds = tr.find_all('td', class_='tdnormal')\n date_size = [ td.get_text() for td in date_size_tds]\n seeds = tr.find('td', class_='tdseed').get_text()\n seeds = seeds.replace(',', '')\n if seeds !='0' or seeds != '-':\n details_dict['seeds'] = seeds\n details_dict['added_date'] = create_date(date_size[0]).strftime('%Y/%m/%d')\n details_dict['size'] = date_size[1]\n details_list.append(details_dict)\n path = 'cache/database/lime/'\n if not os.path.exists(path):\n os.mkdir(path)\n with open( path+'limetorrent_' + str(count) + '_.json','w') as file:\n text = json.dumps(details_list,sort_keys=True,indent=4)\n file.write(text)\n file.close()\n return details_list\n","sub_path":"lime_torrent.py","file_name":"lime_torrent.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"198226170","text":"# -*- coding: utf-8 -*-\n\n\"\"\"file module.\"\"\"\n\nimport os\nimport hashlib\n\nBUF_SIZE = 65536 # 64K chunk\n\n\nclass File:\n def __init__(self, path):\n if os.path.isfile(path):\n self.path = os.path.abspath(path)\n else:\n print(f\"\\nException was raised in File.init({path})\")\n raise Exception\n\n def _populate_size(self):\n return os.path.getsize(self.path)\n\n def _populate_hash(self):\n md5 = hashlib.md5()\n with open(self.path, 'rb') as f:\n while True:\n data = f.read(BUF_SIZE)\n if not data:\n break\n md5.update(data)\n f.close()\n return md5.hexdigest()\n\n def _populate(self):\n self.size = self._populate_size()\n self.hash = self._populate_hash()\n\n def get_file_details(self):\n self._populate()\n return (self.path, self.size, self.hash)\n","sub_path":"photopy/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"530124215","text":"import torch.nn as nn\n\n\nclass WGANGP(nn.Module):\n \"\"\"A WGAN-GP network, consisting of a discriminator and generator.\n Both could be any nn, as long as generator exposes the latent dim variable.\n \"\"\"\n def __init__(self, discriminator, generator,):\n super(WGANGP, self).__init__()\n\n self.discriminator = discriminator\n self.generator = generator\n","sub_path":"models/WGANGP.py","file_name":"WGANGP.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"522855939","text":"result = 0\ni = 1\nwhile i <= 1000:\n if i % 3 == 0:\n result += i\n i += 1\n\nprint(result)\n\ni = 0\nwhile True:\n i += 1\n if i > 5: break\n print(\"*\" * i)\n\nfor i in range(1, 101):\n print(i)\n\nA = [70, 60, 55, 75, 95, 90, 80, 80, 85, 100]\ntotal = 0\nfor score in A:\n total += score\naverage = total / len(A)\nprint(average)\n\nnumbers = [1, 2, 3, 4, 5]\n\nresult =[]\nfor n in numbers:\n if n % 2 == 1:\n result.append(n*2)\nprint(result)\n\nnumbers = [1, 2, 3, 4, 5]\nresult = [ n*2 for n in numbers if n % 2 == 1 ]\nprint(result)\n","sub_path":"practice3.py","file_name":"practice3.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"169944750","text":"import copy\nimport math\nimport re\nimport types\n\nimport spidermonkey\nimport instanceactions\nimport instanceproperties\nfrom validator.constants import BUGZILLA_BUG, FENNEC_GUID, FIREFOX_GUID\nfrom validator.decorator import version_range\nfrom jstypes import *\n\n\ndef _get_member_exp_property(traverser, node):\n \"\"\"Return the string value of a member expression's property.\"\"\"\n\n if node[\"property\"][\"type\"] == \"Identifier\" and not node[\"computed\"]:\n return unicode(node[\"property\"][\"name\"])\n else:\n eval_exp = traverser._traverse_node(node[\"property\"])\n return _get_as_str(eval_exp.get_literal_value())\n\n\ndef _expand_globals(traverser, node):\n \"\"\"Expands a global object that has a lambda value.\"\"\"\n\n if (node.is_global and\n \"value\" in node.value and\n isinstance(node.value[\"value\"], types.LambdaType)):\n\n result = node.value[\"value\"](t=traverser)\n if isinstance(result, dict):\n output = traverser._build_global(\"--\", result)\n elif isinstance(result, JSWrapper):\n output = result\n else:\n output = JSWrapper(result, traverser)\n\n # Set the node context.\n if \"context\" in node.value:\n traverser._debug(\"CONTEXT>>%s\" % node.value[\"context\"])\n output.context = node.value[\"context\"]\n else:\n traverser._debug(\"CONTEXT>>INHERITED\")\n output.context = node.context\n\n return output\n\n return node\n\n\ndef trace_member(traverser, node, instantiate=False):\n \"Traces a MemberExpression and returns the appropriate object\"\n\n traverser._debug(\"TESTING>>%s\" % node[\"type\"])\n if node[\"type\"] == \"MemberExpression\":\n # x.y or x[y]\n # x = base\n base = trace_member(traverser, node[\"object\"], instantiate)\n base = _expand_globals(traverser, base)\n\n # Handle the various global entity properties.\n if base.is_global:\n # If we've got an XPCOM wildcard, return a copy of the entity.\n if \"xpcom_wildcard\" in base.value:\n traverser._debug(\"MEMBER_EXP>>XPCOM_WILDCARD\")\n base.value = base.value.copy()\n del base.value[\"xpcom_wildcard\"]\n return base\n\n identifier = _get_member_exp_property(traverser, node)\n test_identifier(traverser, identifier)\n\n traverser._debug(\"MEMBER_EXP>>PROPERTY: %s\" % identifier)\n output = base.get(traverser=traverser,\n instantiate=instantiate,\n name=identifier)\n output.context = base.context\n return output\n\n elif node[\"type\"] == \"Identifier\":\n traverser._debug(\"MEMBER_EXP>>ROOT:IDENTIFIER\")\n test_identifier(traverser, node[\"name\"])\n\n # If we're supposed to instantiate the object and it doesn't already\n # exist, instantitate the object.\n if (instantiate and not (traverser._is_local_variable(node[\"name\"]) or\n traverser._is_global(node[\"name\"]))):\n output = JSWrapper(JSObject(), traverser=traverser)\n traverser.contexts[0].set(node[\"name\"], output)\n else:\n output = traverser._seek_variable(node[\"name\"])\n\n output = _expand_globals(traverser, output)\n\n return output\n else:\n traverser._debug(\"MEMBER_EXP>>ROOT:EXPRESSION\")\n # It's an expression, so just try your damndest.\n traversed = traverser._traverse_node(node)\n if not isinstance(traversed, JSWrapper):\n return JSWrapper(traversed, traverser=traverser)\n return traversed\n\n\ndef test_identifier(traverser, name):\n \"Tests whether an identifier is banned\"\n\n import predefinedentities\n if name in predefinedentities.BANNED_IDENTIFIERS:\n traverser.err.warning((\"testcases_scripting\",\n \"create_identifier\",\n \"banned_identifier\"),\n \"Banned or deprecated JavaScript Identifier\",\n predefinedentities.BANNED_IDENTIFIERS[name],\n filename=traverser.filename,\n line=traverser.line,\n column=traverser.position,\n context=traverser.context)\n\n\ndef _function(traverser, node):\n \"Prevents code duplication\"\n\n me = JSObject()\n\n # Replace the current context with a prototypeable JS object.\n traverser._pop_context()\n traverser._push_context(me)\n traverser._debug(\"THIS_PUSH\")\n traverser.this_stack.append(me) # Allow references to \"this\"\n\n # Declare parameters in the local scope\n params = []\n for param in node[\"params\"]:\n if param[\"type\"] == \"Identifier\":\n params.append(param[\"name\"])\n elif param[\"type\"] == \"ArrayPattern\":\n for element in param[\"elements\"]:\n # Array destructuring in function prototypes? LOL!\n if element is None or element[\"type\"] != \"Identifier\":\n continue\n params.append(element[\"name\"])\n\n local_context = traverser._peek_context(1)\n for param in params:\n var = JSWrapper(lazy=True, traverser=traverser)\n\n # We can assume that the params are static because we don't care about\n # what calls the function. We want to know whether the function solely\n # returns static values. If so, it is a static function.\n #var.dynamic = False\n local_context.set(param, var)\n\n traverser._traverse_node(node[\"body\"])\n\n # Since we need to manually manage the \"this\" stack, pop off that context.\n traverser._debug(\"THIS_POP\")\n traverser.this_stack.pop()\n\n return me\n\n\ndef _define_function(traverser, node):\n \"Makes a function happy\"\n\n me = _function(traverser, node)\n me = JSWrapper(value=me,\n traverser=traverser,\n callable=True)\n traverser._peek_context(2).set(node[\"id\"][\"name\"], me)\n\n return True\n\n\ndef _func_expr(traverser, node):\n \"Represents a lambda function\"\n\n # Collect the result as an object\n results = _function(traverser, node)\n if not isinstance(results, JSWrapper):\n results = JSWrapper(value=results, traverser=traverser)\n results.callable = True\n return results\n\n\ndef _define_with(traverser, node):\n \"Handles `with` statements\"\n\n object_ = traverser._traverse_node(node[\"object\"])\n if isinstance(object_, JSWrapper) and \\\n isinstance(object_.value, JSObject):\n traverser.contexts[-1] = object_.value\n return\n\n\ndef _define_var(traverser, node):\n \"Creates a local context variable\"\n\n traverser._debug(\"VARIABLE_DECLARATION\")\n traverser.debug_level += 1\n\n for declaration in node[\"declarations\"]:\n\n # It could be deconstruction of variables :(\n if declaration[\"id\"][\"type\"] == \"ArrayPattern\":\n\n vars = []\n for element in declaration[\"id\"][\"elements\"]:\n # NOTE : Multi-level array destructuring sucks. Maybe implement\n # it someday if you're bored, but it's so rarely used and it's\n # so utterly complex, there's probably no need to ever code it\n # up.\n if element is None or element[\"type\"] != \"Identifier\":\n vars.append(None)\n continue\n vars.append(element[\"name\"])\n\n # The variables are not initialized\n if declaration[\"init\"] is None:\n # Simple instantiation; no initialization\n for var in vars:\n if not var:\n continue\n traverser._set_variable(var, None)\n\n # The variables are declared inline\n elif declaration[\"init\"][\"type\"] == \"ArrayPattern\":\n # TODO : Test to make sure len(values) == len(vars)\n for value in declaration[\"init\"][\"elements\"]:\n if vars[0]:\n traverser._set_variable(vars[0], JSWrapper(\n traverser._traverse_node(value),\n traverser=traverser))\n vars = vars[1:] # Pop off the first value\n\n # It's being assigned by a JSArray (presumably)\n elif declaration[\"init\"][\"type\"] == \"ArrayExpression\":\n\n assigner = traverser._traverse_node(declaration[\"init\"])\n for value in assigner.value.elements:\n if vars[0]:\n traverser._set_variable(vars[0], value)\n vars = vars[1:]\n\n elif declaration[\"id\"][\"type\"] == \"ObjectPattern\":\n\n init = traverser._traverse_node(declaration[\"init\"])\n\n def _proc_objpattern(init_obj, properties):\n for prop in properties:\n # Get the name of the init obj's member\n if prop[\"key\"][\"type\"] == \"Literal\":\n prop_name = prop[\"key\"][\"value\"]\n elif prop[\"key\"][\"type\"] == \"Identifier\":\n prop_name = prop[\"key\"][\"name\"]\n else:\n continue\n\n if prop[\"value\"][\"type\"] == \"Identifier\":\n traverser._set_variable(prop[\"value\"][\"name\"],\n init_obj.get(traverser,\n prop_name))\n elif prop[\"value\"][\"type\"] == \"ObjectPattern\":\n _proc_objpattern(init_obj.get(traverser, prop_name),\n prop[\"value\"][\"properties\"])\n\n if init is not None:\n _proc_objpattern(init_obj=init,\n properties=declaration[\"id\"][\"properties\"])\n\n else:\n var_name = declaration[\"id\"][\"name\"]\n traverser._debug(\"NAME>>%s\" % var_name)\n\n var_value = traverser._traverse_node(declaration[\"init\"])\n traverser._debug(\"VALUE>>%s\" % (var_value.output()\n if var_value is not None\n else \"None\"))\n\n if not isinstance(var_value, JSWrapper):\n var = JSWrapper(value=var_value,\n const=(node[\"kind\"] == \"const\"),\n traverser=traverser)\n else:\n var = var_value\n var.const = node[\"kind\"] == \"const\"\n traverser._set_variable(var_name, var)\n\n traverser.debug_level -= 1\n\n # The \"Declarations\" branch contains custom elements.\n return True\n\n\ndef _define_obj(traverser, node):\n \"Creates a local context object\"\n\n var = JSObject()\n for prop in node[\"properties\"]:\n var_name = \"\"\n key = prop[\"key\"]\n if key[\"type\"] == \"Literal\":\n var_name = key[\"value\"]\n else:\n var_name = key[\"name\"]\n var_value = traverser._traverse_node(prop[\"value\"])\n var.set(var_name, var_value, traverser)\n\n # TODO: Observe \"kind\"\n\n if not isinstance(var, JSWrapper):\n return JSWrapper(var, lazy=True, traverser=traverser)\n var.lazy = True\n return var\n\n\ndef _define_array(traverser, node):\n \"\"\"Instantiate an array object from the parse tree.\"\"\"\n arr = JSArray()\n arr.elements = map(traverser._traverse_node, node[\"elements\"])\n return arr\n\n\ndef _define_literal(traverser, node):\n \"\"\"\n Convert a literal node in the parse tree to its corresponding\n interpreted value.\n \"\"\"\n value = node[\"value\"]\n if isinstance(value, dict):\n return JSWrapper(JSObject(), traverser=traverser, dirty=True)\n return JSWrapper(value if value is not None else JSLiteral(None),\n traverser=traverser)\n\n\ndef _call_expression(traverser, node):\n args = node[\"arguments\"]\n map(traverser._traverse_node, args)\n\n member = traverser._traverse_node(node[\"callee\"])\n\n if (traverser.filename.startswith(\"defaults/preferences/\") and\n (\"name\" not in node[\"callee\"] or\n node[\"callee\"][\"name\"] not in (u\"pref\", u\"user_pref\"))):\n\n traverser.err.warning(\n err_id=(\"testcases_javascript_actions\",\n \"_call_expression\",\n \"complex_prefs_defaults_code\"),\n warning=\"Complex code should not appear in preference defaults \"\n \"files\",\n description=\"Calls to functions other than 'pref' and 'user_pref' \"\n \"should not appear in defaults/preferences/ files.\",\n filename=traverser.filename,\n line=traverser.line,\n column=traverser.position,\n context=traverser.context)\n\n\n if (member.is_global and\n \"dangerous\" in member.value and\n isinstance(member.value[\"dangerous\"], types.LambdaType)):\n\n dangerous = member.value[\"dangerous\"]\n t = traverser._traverse_node\n result = dangerous(a=args, t=t, e=traverser.err)\n if result and \"name\" in member.value:\n # Generate a string representation of the params\n params = u\", \".join([_get_as_str(t(p).get_literal_value()) for\n p in args])\n traverser.err.warning((\"testcases_javascript_actions\",\n \"_call_expression\",\n \"called_dangerous_global\"),\n \"'%(name)s' function called in potentially dangerous manner\"\n % member.value,\n result if\n isinstance(result, (types.StringTypes, list, tuple)) else\n \"The global %(name)s function was called using a set \"\n \"of dangerous parameters. %(name)s calls of this nature \"\n \"are deprecated.\" % member.value,\n filename=traverser.filename,\n line=traverser.line,\n column=traverser.position,\n context=traverser.context)\n\n elif node[\"callee\"][\"type\"] == \"MemberExpression\" and \\\n node[\"callee\"][\"property\"][\"type\"] == \"Identifier\":\n\n # If we can identify the function being called on any member of any\n # instance, we can use that to either generate an output value or test\n # for additional conditions.\n identifier_name = node[\"callee\"][\"property\"][\"name\"]\n if identifier_name in instanceactions.INSTANCE_DEFINITIONS:\n result = instanceactions.INSTANCE_DEFINITIONS[identifier_name](\n args, traverser, node, wrapper=member)\n return result\n\n if member.is_global and \"return\" in member.value:\n return member.value[\"return\"](wrapper=member, arguments=args,\n traverser=traverser)\n return True\n\n\ndef _call_settimeout(a, t, e):\n \"\"\"\n Handler for setTimeout and setInterval. Should determine whether a[0]\n is a lambda function or a string. Strings are banned, lambda functions are\n ok. Since we can't do reliable type testing on other variables, we flag\n those, too.\n \"\"\"\n\n if a and a[0][\"type\"] != \"FunctionExpression\":\n return (\"In order to prevent vulnerabilities, the setTimeout \"\n \"and setInterval functions should be called only with \"\n \"function expressions as their first argument.\",\n \"Variables referencing function names are acceptable \"\n \"but deprecated as they are not amenable to static \"\n \"source validation.\")\n\n\ndef _call_create_pref(a, t, e):\n \"\"\"\n Handler for pref() and user_pref() calls in defaults/preferences/*.js files\n to ensure that they don't touch preferences outside of the \"extensions.\"\n branch.\n \"\"\"\n\n if not t.im_self.filename.startswith(\"defaults/preferences/\") or len(a) == 0:\n return\n\n value = str(t(a[0]).get_literal_value())\n\n from predefinedentities import BANNED_PREF_BRANCHES, BANNED_PREF_REGEXPS\n for banned in BANNED_PREF_BRANCHES:\n if value.startswith(banned):\n return (\"Extensions should not alter preferences in the '%s' \"\n \"preference branch\" % banned)\n\n for banned in BANNED_PREF_REGEXPS:\n if re.match(banned, value):\n return (\"Extensions should not alter preferences matching /%s/\"\n % banned)\n\n if not value.startswith(\"extensions.\") or value.rindex(\".\") < len(\"extensions.\"):\n return (\"Extensions should not alter preferences outside of the \"\n \"'extensions.' preference branch. Please make sure that \"\n \"all of your extension's preferences are prefixed with \"\n \"'extensions.add-on-name.', where 'add-on-name' is a \"\n \"distinct string unique to and indicative of your add-on.\")\n\n\ndef _readonly_top(t, r, rn):\n \"\"\"Handle the readonly callback for window.top.\"\"\"\n t.err.notice(\n err_id=(\"testcases_javascript_actions\",\n \"_readonly_top\"),\n notice=\"window.top is a reserved variable\",\n description=\"The 'top' global variable is reserved and cannot be \"\n \"assigned any values starting with Gecko 6. Review your \"\n \"code for any uses of the 'top' global, and refer to \"\n \"%s for more information.\" % BUGZILLA_BUG % 654137,\n filename=t.filename,\n line=t.line,\n column=t.position,\n context=t.context,\n for_appversions={FIREFOX_GUID:\n version_range(\"firefox\", \"6.0a1\", \"7.0a1\"),\n FENNEC_GUID:\n version_range(\"fennec\", \"6.0a1\", \"7.0a1\")},\n compatibility_type=\"warning\",\n tier=5)\n\n\ndef _expression(traverser, node):\n \"Evaluates an expression and returns the result\"\n result = traverser._traverse_node(node[\"expression\"])\n if not isinstance(result, JSWrapper):\n return JSWrapper(result, traverser=traverser)\n return result\n\n\ndef _get_this(traverser, node):\n \"Returns the `this` object\"\n if not traverser.this_stack:\n from predefinedentities import GLOBAL_ENTITIES\n return traverser._build_global(\"window\", GLOBAL_ENTITIES[u\"window\"])\n return traverser.this_stack[-1]\n\n\ndef _new(traverser, node):\n \"Returns a new copy of a node.\"\n\n # We don't actually process the arguments as part of the flow because of\n # the Angry T-Rex effect. For now, we just traverse them to ensure they\n # don't contain anything dangerous.\n args = node[\"arguments\"]\n if isinstance(args, list):\n for arg in args:\n traverser._traverse_node(arg)\n else:\n traverser._traverse_node(args)\n\n elem = traverser._traverse_node(node[\"callee\"])\n if not isinstance(elem, JSWrapper):\n elem = JSWrapper(elem, traverser=traverser)\n if elem.is_global:\n traverser._debug(\"Making overwritable\")\n elem.value = copy.deepcopy(elem.value)\n elem.value[\"overwritable\"] = True\n return elem\n\n\ndef _ident(traverser, node):\n \"Initiates an object lookup on the traverser based on an identifier token\"\n\n name = node[\"name\"]\n\n # Ban bits like \"newThread\"\n test_identifier(traverser, name)\n\n if (traverser._is_local_variable(name) or\n traverser._is_global(name)):\n # This function very nicely wraps with JSWrapper for us :)\n found = traverser._seek_variable(name)\n return found\n\n return JSWrapper(JSObject(), traverser=traverser, dirty=True)\n\n\ndef _expr_assignment(traverser, node):\n \"Evaluates an AssignmentExpression node.\"\n\n traverser._debug(\"ASSIGNMENT_EXPRESSION\")\n traverser.debug_level += 1\n\n traverser._debug(\"ASSIGNMENT>>PARSING RIGHT\")\n right = traverser._traverse_node(node[\"right\"])\n right = JSWrapper(right, traverser=traverser)\n\n # Treat direct assignment different than augmented assignment.\n if node[\"operator\"] == \"=\":\n\n global_overwrite = False\n readonly_value = True\n\n node_left = node[\"left\"]\n traverser._debug(\"ASSIGNMENT:DIRECT(%s)\" % node_left[\"type\"])\n\n if node_left[\"type\"] == \"Identifier\":\n # Identifiers just need the ID name and a value to push.\n # Raise a global overwrite issue if the identifier is global.\n global_overwrite = traverser._is_global(node_left[\"name\"])\n\n # Get the readonly attribute and store its value if is_global\n if global_overwrite:\n from predefinedentities import GLOBAL_ENTITIES\n global_dict = GLOBAL_ENTITIES[node_left[\"name\"]]\n readonly_value = (global_dict[\"readonly\"] if\n \"readonly\" in global_dict else\n True)\n\n traverser._set_variable(node_left[\"name\"], right, glob=True)\n elif node_left[\"type\"] == \"MemberExpression\":\n member_object = trace_member(traverser, node_left[\"object\"],\n instantiate=True)\n global_overwrite = (member_object.is_global and\n not (\"overwritable\" in member_object.value and\n member_object.value[\"overwritable\"]))\n member_property = _get_member_exp_property(traverser, node_left)\n traverser._debug(\"ASSIGNMENT:MEMBER_PROPERTY(%s)\" % member_property)\n traverser._debug(\"ASSIGNMENT:GLOB_OV::%s\" % global_overwrite)\n\n # Don't do the assignment if we're facing a global.\n if not global_overwrite:\n if member_object.value is None:\n member_object.value = JSObject()\n\n if not member_object.is_global:\n member_object.value.set(member_property, right, traverser)\n else:\n # It's probably better to do nothing.\n pass\n\n elif \"value\" in member_object.value:\n member_object_value = _expand_globals(traverser,\n member_object).value\n if member_property in member_object_value[\"value\"]:\n\n # If it's a global and the actual member exists, test\n # whether it can be safely overwritten.\n member = member_object_value[\"value\"][member_property]\n readonly_value = (member[\"readonly\"] if\n \"readonly\" in member else\n True)\n\n traverser._debug(\"ASSIGNMENT:DIRECT:GLOB_OVERWRITE %s\" %\n global_overwrite)\n\n if (global_overwrite and\n not traverser.is_jsm and\n readonly_value == True):\n\n traverser.err.warning(\n err_id=(\"testcases_javascript_actions\",\n \"_expr_assignment\",\n \"global_overwrite\"),\n warning=\"Global variable overwrite\",\n description=\"An attempt was made to overwrite a global \"\n \"variable in some JavaScript code.\",\n filename=traverser.filename,\n line=traverser.line,\n column=traverser.position,\n context=traverser.context)\n\n if isinstance(readonly_value, types.LambdaType):\n # The readonly attribute supports a lambda function that accepts\n readonly_value(t=traverser, r=right, rn=node[\"right\"])\n\n return right\n\n lit_right = right.get_literal_value()\n\n traverser._debug(\"ASSIGNMENT>>PARSING LEFT\")\n left = traverser._traverse_node(node[\"left\"])\n traverser._debug(\"ASSIGNMENT>>DONE PARSING LEFT\")\n\n if isinstance(left, JSWrapper):\n lit_left = left.get_literal_value()\n\n # Don't perform an operation on None. Python freaks out\n if lit_left is None:\n lit_left = 0\n if lit_right is None:\n lit_right = 0\n\n if isinstance(lit_left, types.StringTypes) or \\\n isinstance(lit_right, types.StringTypes):\n lit_left = _get_as_str(lit_left)\n lit_right = _get_as_str(lit_right)\n\n gleft = _get_as_num(left)\n gright = _get_as_num(right)\n # All of the assignment operators\n operators = {\"=\": lambda: right,\n \"+=\": lambda: lit_left + lit_right,\n \"-=\": lambda: gleft - gright,\n \"*=\": lambda: gleft * gright,\n \"/=\": lambda: 0 if gright == 0 else (gleft / gright),\n \"%=\": lambda: 0 if gright == 0 else (gleft % gright),\n \"<<=\": lambda: int(gleft) << int(gright),\n \">>=\": lambda: int(gleft) >> int(gright),\n \">>>=\": lambda: float(abs(int(gleft)) >> gright),\n \"|=\": lambda: int(gleft) | int(gright),\n \"^=\": lambda: int(gleft) ^ int(gright),\n \"&=\": lambda: int(gleft) & int(gright)}\n\n token = node[\"operator\"]\n traverser._debug(\"ASSIGNMENT>>OPERATION:%s\" % token)\n if token not in operators:\n traverser._debug(\"ASSIGNMENT>>OPERATOR NOT FOUND\")\n traverser.debug_level -= 1\n return left\n elif token in (\"<<=\", \">>=\", \">>>=\") and gright < 0:\n left.set_value(0, traverser=traverser)\n return left\n elif (token in (\"<<=\", \">>=\", \">>>=\", \"|=\", \"^=\", \"&=\") and\n (abs(gleft) == float('inf') or abs(gright) == float('inf'))):\n # Don't bother handling infinity for integer-converted operations.\n from predefinedentities import GLOBAL_ENTITIES\n left.set_value(traverser._build_global(\"NaN\",\n GLOBAL_ENTITIES[u\"NaN\"]),\n traverser=traverser)\n return left\n\n traverser._debug(\"ASSIGNMENT::L-value global? (%s)\" %\n (\"Y\" if left.is_global else \"N\"))\n new_value = operators[token]()\n traverser._debug(\"ASSIGNMENT::New value >> %s\" % new_value)\n left.set_value(new_value, traverser=traverser)\n traverser.debug_level -= 1\n return left\n\n # Though it would otherwise be a syntax error, we say that 4=5 should\n # evaluate out to 5.\n traverser.debug_level -= 1\n return right\n\n\ndef _expr_binary(traverser, node):\n \"Evaluates a BinaryExpression node.\"\n\n traverser.debug_level += 1\n\n # Select the proper operator.\n operator = node[\"operator\"]\n traverser._debug(\"BIN_OPERATOR>>%s\" % operator)\n\n # Traverse the left half of the binary expression.\n traverser._debug(\"BIN_EXP>>l-value\")\n traverser.debug_level += 1\n\n if (node[\"left\"][\"type\"] == \"BinaryExpression\" and\n \"__traversal\" not in node[\"left\"]):\n # Process the left branch of the binary expression directly. This keeps\n # the recursion cap in line and speeds up processing of large chains\n # of binary expressions.\n left = _expr_binary(traverser, node[\"left\"])\n node[\"left\"][\"__traversal\"] = left\n else:\n left = traverser._traverse_node(node[\"left\"])\n\n traverser.debug_level -= 1\n\n # Traverse the right half of the binary expression.\n traverser._debug(\"BIN_EXP>>r-value\")\n traverser.debug_level += 1\n\n if (operator == \"instanceof\" and\n node[\"right\"][\"type\"] == \"Identifier\" and\n node[\"right\"][\"name\"] == \"Function\"):\n # We make an exception for instanceof's r-value if it's a dangerous\n # global, specifically Function.\n return JSWrapper(True, traverser=traverser)\n else:\n right = traverser._traverse_node(node[\"right\"])\n traverser._debug(\"Is dirty? %r\" % right.dirty)\n\n # Dirty l or r values mean we can skip the expression. A dirty value\n # indicates that a lazy operation took place that introduced some\n # nondeterminacy.\n if left.dirty:\n return left\n elif right.dirty:\n return right\n\n traverser.debug_level -= 1\n\n # Binary expressions are only executed on literals.\n left_wrap = left\n left = left.get_literal_value()\n right_wrap = right\n right = right.get_literal_value()\n\n # Coerce the literals to numbers for numeric operations.\n gleft = _get_as_num(left)\n gright = _get_as_num(right)\n\n operators = {\n \"==\": lambda: left == right or gleft == gright,\n \"!=\": lambda: left != right,\n \"===\": lambda: left == right, # Be flexible.\n \"!==\": lambda: not (type(left) == type(right) or left != right),\n \">\": lambda: left > right,\n \"<\": lambda: left < right,\n \"<=\": lambda: left <= right,\n \">=\": lambda: left >= right,\n \"<<\": lambda: int(gleft) << int(gright),\n \">>\": lambda: int(gleft) >> int(gright),\n \">>>\": lambda: float(abs(int(gleft)) >> int(gright)),\n \"+\": lambda: left + right,\n \"-\": lambda: gleft - gright,\n \"*\": lambda: gleft * gright,\n \"/\": lambda: 0 if gright == 0 else (gleft / gright),\n \"%\": lambda: 0 if gright == 0 else (gleft % gright),\n \"in\": lambda: right_wrap.contains(left),\n # TODO : implement instanceof\n }\n\n traverser.debug_level -= 1\n\n operator = node[\"operator\"]\n output = None\n if (operator in (\">>\", \"<<\", \">>>\") and\n ((left is None or right is None) or\n gright < 0)):\n output = False\n elif operator in operators:\n # Concatenation can be silly, so always turn undefineds into empty\n # strings and if there are strings, make everything strings.\n if operator == \"+\":\n if left is None:\n left = \"\"\n if right is None:\n right = \"\"\n if isinstance(left, types.StringTypes) or \\\n isinstance(right, types.StringTypes):\n left = _get_as_str(left)\n right = _get_as_str(right)\n\n # Don't even bother handling infinity if it's a numeric computation.\n if (operator in (\"<<\", \">>\", \">>>\") and\n (abs(gleft) == float('inf') or abs(gright) == float('inf'))):\n from predefinedentities import GLOBAL_ENTITIES\n return traverser._build_global(\"NaN\", GLOBAL_ENTITIES[u\"NaN\"])\n\n output = operators[operator]()\n\n if not isinstance(output, JSWrapper):\n return JSWrapper(output, traverser=traverser)\n return output\n\n\ndef _expr_unary(traverser, node):\n \"Evaluates a UnaryExpression node\"\n\n expr = traverser._traverse_node(node[\"argument\"])\n expr_lit = expr.get_literal_value()\n expr_num = _get_as_num(expr_lit)\n\n operators = {\"-\": lambda: -1 * expr_num,\n \"+\": lambda: expr_num,\n \"!\": lambda: not expr_lit,\n \"~\": lambda: -1 * (expr_num + 1),\n \"void\": lambda: None,\n \"typeof\": lambda: _expr_unary_typeof(expr),\n \"delete\": lambda: None} # We never want to empty the context\n if node[\"operator\"] in operators:\n output = operators[node[\"operator\"]]()\n else:\n output = None\n\n if not isinstance(output, JSWrapper):\n output = JSWrapper(output, traverser=traverser)\n return output\n\n\ndef _expr_unary_typeof(wrapper):\n \"\"\"Evaluate the \"typeof\" value for a JSWrapper object.\"\"\"\n if (wrapper.callable or\n (wrapper.is_global and \"return\" in wrapper.value and\n \"value\" not in wrapper.value)):\n return \"function\"\n\n value = wrapper.value\n if value is None:\n return \"undefined\"\n elif isinstance(value, JSLiteral):\n value = value.value\n if isinstance(value, bool):\n return \"boolean\"\n elif isinstance(value, (int, long, float)):\n return \"number\"\n elif isinstance(value, types.StringTypes):\n return \"string\"\n return \"object\"\n\n\ndef _get_as_num(value):\n \"\"\"Return the JS numeric equivalent for a value.\"\"\"\n if value is None:\n return 0\n\n if isinstance(value, JSWrapper):\n value = value.get_literal_value()\n\n try:\n if isinstance(value, types.StringTypes):\n if value.startswith(\"0x\"):\n return int(value, 16)\n else:\n return float(value)\n elif isinstance(value, (int, float, long)):\n return value\n elif value is None:\n return 0\n else:\n return int(value)\n except ValueError:\n return 0\n\n\ndef _get_as_str(value):\n \"\"\"Return the JS string equivalent for a literal value.\"\"\"\n if value is None:\n return \"\"\n\n if isinstance(value, bool):\n # .lower() because JS bools are lowercase.\n return unicode(value).lower()\n elif isinstance(value, (int, float, long)):\n if value == float('inf'):\n return \"Infinity\"\n elif value == float('-inf'):\n return \"-Infinity\"\n\n # Try to see if we can shave off some trailing significant figures.\n try:\n if int(value) == value:\n return unicode(int(value))\n except:\n pass\n return unicode(value)\n\n","sub_path":"validator/testcases/javascript/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":33438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"90656695","text":"from django.core.management.base import BaseCommand\nimport mainapp.models as mainapp\nfrom authapp.models import ShopUser\n\nimport json, os\n\nJSON_PATH = 'mainapp/json'\n\n\ndef load_from_json(file_name):\n with open(os.path.join(JSON_PATH, file_name + '.json'), 'r') as infile:\n return json.load(infile)\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n\n # Создаем суперпользователя при помощи менеджера модели\n ShopUser.objects.all().delete()\n super_user = ShopUser.objects.create_superuser('django', 'django@geekshop.local', 'geekbrains')\n\n # категории\n categories = load_from_json('categories')\n mainapp.ProductCategory.objects.all().delete()\n for category in categories:\n if category[\"parent_category\"] is not None:\n category[\"parent_category\"] = mainapp.ProductCategory.objects.get(name=category[\"parent_category\"])\n new_category = mainapp.ProductCategory(**category)\n new_category.save()\n\n # производители\n manufacturers = load_from_json('manufacturers')\n mainapp.ProductManufacturer.objects.all().delete()\n for manufacturer in manufacturers:\n mainapp.ProductManufacturer.objects.create(**manufacturer)\n\n # особенности товаров\n features = load_from_json('product_features')\n mainapp.ProductFeatureName.objects.all().delete()\n for feature in features:\n mainapp.ProductFeatureName.objects.create(**feature)\n\n # продукты\n products = load_from_json('products')\n mainapp.Product.objects.all().delete()\n for product in products:\n # Получаем категорию по имени\n _category = mainapp.ProductCategory.objects.get(name=product[\"category\"])\n _manufacturer = mainapp.ProductManufacturer.objects.get(name=product[\"manufacturer\"])\n\n new_product = mainapp.Product(category=_category, manufacturer=_manufacturer,\n preview_image=product[\"images\"][0], name=product[\"name\"],\n price=product[\"price\"])\n new_product.save()\n for image in product[\"images\"][1:]:\n mainapp.ProductImages.objects.create(product=new_product, image=image)\n\n for product_feature in product[\"features\"]:\n _feature_name = mainapp.ProductFeatureName.objects.get(name=product_feature)\n mainapp.ProductFeatures.objects.create(product=new_product, feature_name=_feature_name,\n feature_value=product[\"features\"][product_feature])\n\n\n","sub_path":"mainapp/management/commands/fill_db.py","file_name":"fill_db.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"598000044","text":"import logging\n\nimport torch.nn as nn\nfrom module.loss import CrossEntropyLabelSmooth, ArcMarginProduct, CenterLoss, TripletLoss\n\n\ndef create_criterions(args, num_classes, device=None):\n criterion = []\n\n # Cross Entropy Loss\n if args.smoothing:\n CELoss = CrossEntropyLabelSmooth(num_classes, device=device)\n else:\n CELoss = nn.NLLLoss()\n\n # Arcface: Arc Large Margin Product loss\n # speacial case when using arcface, need to append CELoss to it.\n if args.arcface:\n criterion += [\n (\n \"ArcFaceLoss\",\n (\n ArcMarginProduct(\n args.feature_dim,\n num_classes,\n False,\n s=args.scale,\n m=args.margin,\n device=device,\n ),\n CELoss,\n ),\n 1.0,\n )\n ]\n else:\n criterion += [(\"CELoss\", CELoss, 1.0)]\n\n # Triple loss\n if args.triplet:\n criterion += [(\"TripletLoss\", TripletLoss(0.3, args.dist), 4.0)]\n\n # Center loss\n if args.center:\n criterion += [\n (\n \"CenterLoss\",\n CenterLoss(num_classes=num_classes, feat_dim=args.feature_dim, device=device,),\n 1.0,\n )\n ]\n\n logging.info(\"criterions: {}\".format(criterion))\n\n return criterion\n","sub_path":"module/loss/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"377620710","text":"# Imports\nimport arcade\nimport random\nimport os\n\n# Declaracion de variables\n\nANCHURA_PANTALLA = 800\nALTURA_PANTALLA = 800\nTITULO = \"El juego de los Muros\"\n\n# Movimiento del personaje\nMOVIMIENTO = 8\n\n# Margen del jugador para moverse y verle\nMARGEN = 40\nMUERTE = 0\n\n# Escalar monedas\nESCALAR_MONEDA = 0.2\n\n# Numero de monedas\nNUMERO_MONEDAS = 75\nPINCHOS_X = 50\nPINCHOS_Y = 50\n\n\nclass MyGame(arcade.Window):\n \"\"\"Clase principal del programa\"\"\"\n\n def __init__(self, anchura, altura, titulo):\n # Inicia el programa\n # Constructor\n super().__init__(anchura, altura, titulo)\n\n self.lista_pinchos = arcade.SpriteList()\n file_path = os.path.dirname(os.path.abspath(__file__))\n os.chdir(file_path)\n\n # Lista de Sprite\n self.lista_moneda = None\n self.lista_muro = None\n self.lista_jugador = None\n self.lista_moneda = None\n\n # Iniciar al jugador\n self.sprite_jugador = None\n self.fisicas = None\n self.contador = 0\n\n # Iniciamos el comando view\n self.view_left = 0\n self.view_bottom = 0\n\n def setup(self):\n # Listas de Sprite, iniciar\n self.lista_jugador = arcade.SpriteList()\n self.lista_muro = arcade.SpriteList()\n self.lista_moneda = arcade.SpriteList()\n self.lista_pinchos = arcade.SpriteList()\n self.sonido_moneda = arcade.load_sound(\"SonidoMoneda.m4a\")\n self.sonido_perder = arcade.load_sound(\"perdedor.mp3\")\n self.sonido_ganar = arcade.load_sound(\"ganador.mp3\")\n\n # Iniciar al jugador\n self.sprite_jugador = arcade.Sprite(\"persona.png\", 0.5)\n\n # Posicion del jugador y se añade a la lista\n self.sprite_jugador.center_x = 120\n self.sprite_jugador.center_y = 120\n self.lista_jugador.append(self.sprite_jugador)\n\n # Creacion de los muros\n # En horizontal\n x = -3000\n for y in range(0, 2):\n x += 3000\n for y in range(0, 3064, 64):\n muro = arcade.Sprite(\"muros.jpg\", 0.04)\n muro.center_x = y\n muro.center_y = x\n self.lista_muro.append(muro)\n\n for y in range(0, 3064, 64):\n muro = arcade.Sprite(\"muros.jpg\", 0.04)\n muro.center_x = x\n muro.center_y = y\n self.lista_muro.append(muro)\n x2 = -1200\n for y in range(0, 3):\n x2 += 1200\n for y in range(0, 1024, 64):\n muro = arcade.Sprite(\"muros.jpg\", 0.04)\n muro.center_x = y\n muro.center_y = 300 + x2\n self.lista_muro.append(muro)\n for y in range(1100, 3064, 64):\n muro = arcade.Sprite(\"muros.jpg\", 0.04)\n muro.center_x = y\n muro.center_y = 300 + x2\n self.lista_muro.append(muro)\n for y in range(0, 2014, 64):\n muro = arcade.Sprite(\"muros.jpg\", 0.04)\n muro.center_x = y\n muro.center_y = 600 + x2\n self.lista_muro.append(muro)\n for y in range(2124, 3064, 64):\n muro = arcade.Sprite(\"muros.jpg\", 0.04)\n muro.center_x = y\n muro.center_y = 600 + x2\n self.lista_muro.append(muro)\n for y in range(0, 760, 64):\n muro = arcade.Sprite(\"muros.jpg\", 0.04)\n muro.center_x = y\n muro.center_y = 900 + x2\n self.lista_muro.append(muro)\n for y in range(860, 3064, 64):\n muro = arcade.Sprite(\"muros.jpg\", 0.04)\n muro.center_x = y\n muro.center_y = 900 + x2\n self.lista_muro.append(muro)\n for y in range(0, 2450, 64):\n muro = arcade.Sprite(\"muros.jpg\", 0.04)\n muro.center_x = y\n muro.center_y = 1200 + x2\n self.lista_muro.append(muro)\n for y in range(2550, 3064, 64):\n muro = arcade.Sprite(\"muros.jpg\", 0.04)\n muro.center_x = y\n muro.center_y = 1200 + x2\n self.lista_muro.append(muro)\n\n # Colocacion de pinchos\n j = 0\n for i in range (0, 9):\n j += 300\n z = 0\n for y in range(0, 6):\n z += 500\n for y in range(0, 1024, 64):\n self.pincho = arcade.Sprite(\"estalagnitas.png\", 0.08)\n self.pincho.center_x = -100 + z\n self.pincho.center_y = 50 + j\n self.lista_pinchos.append(self.pincho)\n for y in range(0, 1024, 64):\n self.pincho = arcade.Sprite(\"estalactitas.png\", 0.08)\n self.pincho.center_x = -300 + z\n self.pincho.center_y = 250 + j\n self.lista_pinchos.append(self.pincho)\n\n # Colocacion de monedas\n for i in range(NUMERO_MONEDAS):\n\n moneda = arcade.Sprite(\"moneda.png\",ESCALAR_MONEDA)\n\n moneda_bien_colocada = False\n while not moneda_bien_colocada:\n moneda.center_x = random.randrange(3000)\n moneda.center_y = random.randrange(3000)\n\n moneda_choca_moneda = arcade.check_for_collision_with_list(moneda, self.lista_moneda)\n muro_choca_moneda = arcade.check_for_collision_with_list(moneda, self.lista_muro)\n moneda_choca_pincho = arcade.check_for_collision_with_list(moneda, self.lista_pinchos)\n\n if len(muro_choca_moneda) == 0 and len(moneda_choca_moneda) == 0 and len(moneda_choca_pincho) == 0:\n moneda_bien_colocada = True\n\n\n self.lista_moneda.append(moneda)\n\n # Son las fisicas del juego por el cual el personaje no puede\n # atravesar los muros\n self.fisicas = arcade.PhysicsEngineSimple(self.sprite_jugador, self.lista_muro)\n\n # Color de fondo\n arcade.set_background_color(arcade.color.AIR_SUPERIORITY_BLUE)\n\n def on_draw(self):\n\n # Renderiza\n arcade.start_render()\n\n # Hace el dibujo\n self.lista_muro.draw()\n self.lista_jugador.draw()\n self.lista_moneda.draw()\n self.lista_pinchos.draw()\n\n if self.contador == 75:\n texto = f\" HAS GANADO \"\n arcade.draw_text(texto, 0, 2000, arcade.color.WHITE, 400)\n texto = f\"Contador: {self.contador}\"\n arcade.draw_text(texto, 50, 1000, arcade.color.WHITE, 400)\n arcade.play_sound(self.sonido_ganar)\n\n if self.MUERTE == 1:\n texto =f\" HAS PERDIDO \"\n arcade.draw_text(texto, 0, 2000, arcade.color.WHITE, 400)\n texto = f\"Contador: {self.contador}\"\n arcade.draw_text(texto, 50, 1000, arcade.color.WHITE, 400)\n arcade.set_viewport(0, 3000, 0, 3000)\n\n def on_key_press(self, tecla, modificador):\n \"\"\"Pulsar tecla para moverse\"\"\"\n\n # La tecla que pulsas hace este movimiento\n if tecla == arcade.key.UP:\n self.sprite_jugador.change_y = MOVIMIENTO\n if tecla == arcade.key.DOWN:\n self.sprite_jugador.change_y = -MOVIMIENTO\n if tecla == arcade.key.LEFT:\n self.sprite_jugador.change_x = -MOVIMIENTO\n if tecla == arcade.key.RIGHT:\n self.sprite_jugador.change_x = MOVIMIENTO\n\n def on_key_release(self, tecla, modificacion):\n\n # Cuando el jugador suelta la tecla para que no se produzca movimiento\n if tecla == arcade.key.UP or tecla == arcade.key.DOWN:\n self.sprite_jugador.change_y = 0\n elif tecla == arcade.key.LEFT or tecla == arcade.key.RIGHT:\n self.sprite_jugador.change_x = 0\n\n def on_update(self, delta_time):\n\n # Actualiza\n self.fisicas.update()\n\n persona_choca_pincho = arcade.check_for_collision_with_list(self.sprite_jugador, self.lista_pinchos)\n monedas_conseguidas = arcade.check_for_collision_with_list(self.sprite_jugador, self.lista_moneda)\n for moneda in monedas_conseguidas:\n moneda.remove_from_sprite_lists()\n self.contador += 1\n arcade.play_sound(self.sonido_moneda)\n\n for self.pincho in persona_choca_pincho:\n self.sprite_jugador.remove_from_sprite_lists()\n self.sprite_jugador.change_x = 0\n self.sprite_jugador.change_y = 0\n self.MUERTE = 1\n\n cambio = False\n\n # Scroll left\n borde_izquierdo = self.view_left + MARGEN\n if self.sprite_jugador.left < borde_izquierdo:\n self.view_left -= borde_izquierdo - self.sprite_jugador.left\n cambio = True\n\n # Scroll right\n borde_derecho = self.view_left + ANCHURA_PANTALLA - MARGEN\n if self.sprite_jugador.right > borde_derecho:\n self.view_left += self.sprite_jugador.right - borde_derecho\n cambio = True\n\n # Scroll up\n borde_arriba = self.view_bottom + ALTURA_PANTALLA - MARGEN\n if self.sprite_jugador.top > borde_arriba:\n self.view_bottom += self.sprite_jugador.top - borde_arriba\n cambio = True\n\n # Scroll down\n borde_abajo = self.view_bottom + MARGEN\n if self.sprite_jugador.bottom < borde_abajo:\n self.view_bottom -= borde_abajo - self.sprite_jugador.bottom\n cambio = True\n\n self.view_left = int(self.view_left)\n self.view_bottom = int(self.view_bottom)\n\n # If we changed the boundary values, update the view port to match\n\n \"\"\"arcade.set_viewport(0, 3000, 0, 3000)\"\"\"\n\n if cambio and self.contador < 75 and MUERTE == 0:\n arcade.set_viewport(self.view_left,\n ANCHURA_PANTALLA + self.view_left - 1,\n self.view_bottom,\n ALTURA_PANTALLA + self.view_bottom - 1)\n\n if cambio and self.contador == 75:\n arcade.set_viewport(0, 3000, 0, 3000)\n if cambio and MUERTE==1:\n arcade.set_viewport(0, 3000, 0, 3000)\n\n\n\ndef main():\n \"\"\"Metodo main\"\"\"\n window = MyGame(ANCHURA_PANTALLA, ALTURA_PANTALLA, TITULO)\n window.setup()\n arcade.run()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"lab09-walls/lab09-walls.py","file_name":"lab09-walls.py","file_ext":"py","file_size_in_byte":10324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"144219447","text":"\nimport asyncio\nfrom contextlib import suppress # context manager to suppress specific Exceptions\nimport time\n\n\nasync def terminator(runtime):\n \"\"\"\n trial for auto shutdown of a loop\n \"\"\"\n s = time.time()\n while True:\n await asyncio.sleep(0)\n if time.time() - s >= runtime:\n raise KeyboardInterrupt\n\nasync def write_out(text):\n \"\"\"\n mock write out to cloud\n \"\"\"\n while True:\n et = time.time()\n print('===== WRITE TO CLOUD STORAGE {: 0.2f}==== '.format(et))\n print(text)\n await asyncio.sleep(1)\n\nasync def main():\n\n futures = (write_out('shite'))\n task = asyncio.Task(futures)\n\n await asyncio.sleep(5)\n\n # cancel task to avoid warning:\n # task.cancel()\n # with suppress(asyncio.CancelledError):\n # await task # await for task cancellation\n\n\nif __name__ == '__main__':\n\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n\n runtime = 10.0 # limit the duration of the run and force exit\n\n # ===============================================================================================================\n # loop.create_task(write_out())\n # loop.create_task(terminator(runtime))\n #\n # try:\n # loop.run_forever()\n # except KeyboardInterrupt: # pragma: no branch\n # print('=========== ASTA LAVISTA BABY !!!!! =============')\n # print('\\n\\n')\n # finally:\n # # Let's also cancel all running tasks:\n # # stackoverflow.com/37278647/37345564\n # pending = asyncio.Task.all_tasks()\n # for task in pending:\n # task.cancel()\n # print('=============================CLEAN UP ============================')\n # # Now we should await task to execute it's cancellation.\n # # Cancelled task raises asyncio.CancelledError that we can suppress:\n # with suppress(asyncio.CancelledError):\n # loop.run_until_complete(task)\n # loop.close()\n # ===============================================================================================================\n\n 'https://stackoverflow.com/questions/37278647/fire-and-forget-python-async-await/37345564'\n\n try:\n loop.run_until_complete(main()) # this is the key difference\n except KeyboardInterrupt: # pragma: no branch\n print('=========== ASTA LAVISTA BABY !!!!! =============')\n print('\\n\\n')\n finally:\n # Let's also cancel all running tasks:\n # stackoverflow.com/37278647/37345564\n pending = asyncio.Task.all_tasks()\n print('=============================CLEAN UP ============================')\n for task in pending:\n task.cancel()\n # Now we should await task to execute it's cancellation.\n # Cancelled task raises asyncio.CancelledError that we can suppress:\n with suppress(asyncio.CancelledError):\n loop.run_until_complete(task)\n loop.close()\n #\n # finally:\n # loop.run_until_complete(loop.shutdown_asyncgens())\n # loop.close()\n\n","sub_path":"Trials/async_trials/terminator_mock.py","file_name":"terminator_mock.py","file_ext":"py","file_size_in_byte":3149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"365565023","text":"import numpy as np\nimport pytest\n\nfrom autocnet.matcher import cpu_ring_matcher as rm\n\n@pytest.mark.parametrize('arr, expected', [\n (np.array([[1,0],[1,1], [2,3]]), (1,2)),\n (np.array([[0,0], [1,1], [2,2]]), (3,2)\n )])\ndef test_check_pidx_duplicates(arr, expected):\n print(arr)\n pidx = rm.check_pidx_duplicates(arr)\n print(pidx)\n assert pidx.shape == expected\n\n@pytest.mark.parametrize(\"a, b, threshold, expected\", [\n # Tests standard call\n (np.array([1,2,3]), \n np.array([[1,2,3], [4,5,6], [7,8,9]]),\n 1.5, \n np.array([0])),\n # Tests call where distances are too close\n (np.array([1,2,3]),\n np.array([[7,8,9], [1,2,4], [1,2,4.1]]),\n 1.5, \n None),\n # Tests call with close distances where the threshold is low\n (np.array([1,2,3]),\n np.array([[7,8,9], [1,2,4], [1,2,4.1]]),\n 1., \n 1),\n # Tests call when np.argmin will fail\n (np.array([np.nan, np.nan]),\n np.array([[np.nan, np.nan], [np.nan, np.nan]]),\n 1.5,\n None),\n # Tests call where descriptors are identical\n (np.array([1,2,3]),\n np.array([[1,2,3], [1,2,3], [1,2,3]]),\n 1.5,\n None)\n])\ndef test_sift_match(a, b, threshold, expected):\n assert rm.sift_match(a, b, thresh=threshold) == expected ","sub_path":"autocnet/matcher/tests/test_cpu_ring_matcher.py","file_name":"test_cpu_ring_matcher.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"217472743","text":"# @author Sumeet Jain\n# @email sumeet.jain44@gmail.com\n# @create date Tue Jul 18 14:12:48 PDT 2017\n# @modify date Tue Jul 18 14:54:03 PDT 2017\n# @desc [https://www.hackerrank.com/challenges/two-characters]\n\nimport sys\nfrom itertools import combinations\n\ns_len = int(input().strip())\ns = input().strip()\nuniques = set(s)\nm = 0\nuc = combinations(uniques,2)\n\ndef is_valid_t(s):\n for i in range(len(s)-1):\n if(s[i]==s[i+1]):\n return False\n return True\n \nfor key in list(uc):\n t1 = key[0]\n t2 = key[1]\n new_s = ''\n for k in s:\n if k==t1 or k==t2:\n new_s += k\n if(is_valid_t(new_s)):\n if(len(new_s)>m):\n m = len(new_s)\n \n \n \nprint(m)\n ","sub_path":"algorithms/easy/two-characters.py","file_name":"two-characters.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"235609097","text":"# Weiner Process Simulation\n\n # Import the 'numpy' library and assign it to the 'np' object\nimport numpy as np\n# From the 'matplotlib' library, import 'pyplot' only, and assign to to 'plt' object\nimport matplotlib.pyplot as plt\n\n# Time steps\nn = 100. # Set the number of steps per unit of time\nT = 1. # Length of [0,T] in time units\nDelta = T/n # Scale each steps to unit of time\n\n# Create a vector for the x-axis\n# Looks like [ 0. 0.01 0.02 0.03 ... 0.98 0.99]\nt = np.arange(1, step=Delta)\n\n# Create an empty vector W of the desired length\n# This gives us an arrary with 'n' zeros.\n# Specify floating point data type, otherwise Python rounds to the nearest integer\nS = np.zeros(n, np.dtype(float))\n\n# Z variable, N(0,1) for Martingale\n# Mean mu and standard devation sig\n# Mu is also know was the drift or growth and sig is also known as volatility or diffusion\n# mu = 0 for Martingale, mu > 0 for Supermartingale and mu < 0 for Submartingale\nmu, sig = 0., 1.\n\n# Create an array which we can iterate over\n# Looks like [1 2 3 ... 98 99]\nx = range(1, len(S))\n\n# Define a function to simulate one path\ndef Wiener():\n\tfor i in x:\n\t\tdW = np.random.normal(mu, sig)\n\t\tdt = np.sqrt(Delta)\n\t\tdS = dW*dt\n\t\tS[i] = S[i-1] + dS\n\n\t# Plot\n\tplt.plot(t,S)\n\n# Call the function many times to simulate many paths\nfor i in range(1,10):\n Wiener()\n\n# Add title\nplt.title('Wiener Process - 10 Paths')\n\n# Display the chart\nplt.show()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"246308326","text":"from django.shortcuts import render\n\n# Create your views here.\nimport serializer as serializer\nfrom rest_framework import serializers\n# from DRF.drf_serailezer.api.models import Employee\nimport json\nfrom django.shortcuts import render\nimport io\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework.renderers import JSONRenderer\nfrom .models import Employee\nfrom .serializers import EmployeeSerializer\nfrom django.http import HttpResponse\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views import View\n@method_decorator(csrf_exempt,name='dispatch')\nclass EmployeeAPI(View):\n def get(self, request, *args, **kwargs):\n json_data = request.body\n print(f\"Json data is {json_data}\")\n id = None\n if json_data:\n stream = io.BytesIO(json_data)\n py_data = JSONParser().parse(stream)\n id = py_data.get('id', None)\n if id:\n emp = Employee.objects.get(id=id)\n print(f\"Employee is {emp}\")\n serializer = EmployeeSerializer(emp)\n json_data = JSONRenderer().render(serializer.data)\n return HttpResponse(json_data, content_type='application/json')\n emp = Employee.objects.all()\n serializer = EmployeeSerializer(emp, many=True)\n json_data = JSONRenderer().render(serializer.data)\n return HttpResponse(json_data, content_type='application/json')\n\n def post(self,request,*args,**kwargs):\n json_data = request.body\n print(f\"Json data is {json_data}\")\n stream = io.BytesIO(json_data)\n py_data = JSONParser().parse(stream)\n serializer = EmployeeSerializer(data=py_data)\n if serializer.is_valid():\n serializer.save()\n res = {'msg': 'New record created.'}\n json_data = JSONRenderer().render(res)\n else:\n json_data = JSONRenderer().render(serializer.errors)\n return HttpResponse(json_data,content_type='application/json')\n\n # return HttpResponse(json_data)\n def put(self,request,*args,**kwargs):\n json_data = request.body\n print(f\"Json data is {json_data}\")\n # deserializing the json data to complex type\n stream = io.BytesIO(json_data)\n py_data = JSONParser().parse(stream)\n id = py_data.get('id')\n emp = Employee.objects.get(id=id)\n # emp.delete()\n serializer = EmployeeSerializer(emp, data=py_data, partial=True)\n if serializer.is_valid():\n serializer.save()\n res = {'msg': 'New record Updated.'}\n json_data = JSONRenderer().render(res)\n else:\n json_data = JSONRenderer().render(serializer.errors)\n return HttpResponse(json_data)\n\n\n def delete(self,request,*args,**kwargs):\n json_data = request.body\n stream = io.BytesIO(json_data)\n py_data = JSONParser().parse(stream)\n id = py_data.get('id')\n emp = Employee.objects.get(id=id)\n emp.delete()\n res = {'msg': 'Data Deleted!!'}\n json_data = JSONRenderer().render(res)\n return HttpResponse(json_data, content_type='application/json')","sub_path":"AJLATICLASS/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"324039843","text":"# coding=utf-8\n\nimport itertools\n\nfrom lxml import etree\n\n\ndef _describe_element(elem):\n root = elem.getroottree()\n if not root:\n return '? [tag name: {}]'.format(elem.tag)\n else:\n return root.getpath(elem)\n\n\ndef _xml_text_compare(t1, t2):\n return (t1 or '').strip() == (t2 or '').strip()\n\n\ndef _xml_tags_compare(a, b):\n # (1): compare tag names\n res = cmp(a.tag, b.tag)\n if res != 0:\n return res\n\n # (2): compare attributes\n res = cmp(dict(a.attrib), dict(b.attrib))\n if res != 0:\n return res\n\n # (3): compare children\n a_children = a.getchildren()\n b_children = b.getchildren()\n a_children.sort(_xml_tags_compare)\n b_children.sort(_xml_tags_compare)\n for a_child, b_child in itertools.izip_longest(a_children, b_children):\n child_res = cmp(a_child, b_child)\n if child_res != 0:\n res = child_res\n break\n\n return res\n\n\ndef _xml_compare_tag_attribs_text(xml1, xml2, reporter, compare_xml2_attribs=True):\n if xml1.tag != xml2.tag:\n reporter('Tags do not match: {tag1} and {tag2} (path: {path})'\n .format(tag1=xml1.tag, tag2=xml2.tag, path=_describe_element(xml1)))\n return False\n\n for attrib, value in xml1.attrib.iteritems():\n if xml2.attrib.get(attrib) != value:\n reporter('Attributes do not match: {attr}={v1!r}, {attr}={v2!r} (path: {path})'\n .format(attr=attrib, v1=value, v2=xml2.attrib.get(attrib), path=_describe_element(xml1)))\n return False\n\n if compare_xml2_attribs:\n for attrib in xml2.attrib:\n if attrib not in xml1.attrib:\n reporter('xml2 has an attribute xml1 is missing: {attrib} (path: {path})'\n .format(attrib=attrib, path=_describe_element(xml2)))\n return False\n\n if not _xml_text_compare(xml1.text, xml2.text):\n reporter('Text: {t1} != {t2} (path: {path})'\n .format(t1=xml1.text.encode('utf-8'), t2=xml2.text.encode('utf-8'), path=_describe_element(xml1)))\n return False\n\n if not _xml_text_compare(xml1.tail, xml2.tail):\n reporter('Tail: {tail1} != {tail2}'.format(\n tail1=xml1.tail.encode('utf-8'), tail2=xml2.tail.encode('utf-8'), path=_describe_element(xml1)))\n return False\n\n return True\n\n\nclass _DownstreamReporter(object):\n\n def __init__(self):\n self.last_error = None\n\n def __call__(self, *args, **kwargs):\n self.last_error = args[0]\n\n\ndef _xml_compare(xml1, xml2, check_tags_order=False, reporter=lambda x: None):\n \"\"\"Compare two etree.Element objects.\n\n Based on https://bitbucket.org/ianb/formencode/src/tip/formencode/doctest_xml_compare.py#cl-70\n \"\"\"\n if not _xml_compare_tag_attribs_text(xml1, xml2, reporter=reporter):\n return False\n\n children1 = xml1.getchildren()\n children2 = xml2.getchildren()\n if len(children1) != len(children2):\n reporter('Children length differs, {len1} != {len2} (path: {path})'\n .format(len1=len(children1), len2=len(children2), path=_describe_element(xml1)))\n return False\n\n if not check_tags_order:\n children1.sort(_xml_tags_compare)\n children2.sort(_xml_tags_compare)\n\n i = 0\n for c1, c2 in zip(children1, children2):\n i += 1\n if not _xml_compare(c1, c2, check_tags_order, reporter):\n reporter('Children not matched (path: {path})'\n .format(n=i, tag1=c1.tag, tag2=c2.tag, path=_describe_element(xml1)))\n return False\n\n return True\n\n\ndef _xml_check_compatibility(old_xml, new_xml, reporter=lambda x: None):\n \"\"\"Check compatibility of two xml documents (new_xml is an extension of old_xml).\n\n new_xml >= old_xml:\n * new_xml should contains all attribs and properties from old_xml\n * new_xml may have any extra attribs\n * new_xml may have any extra properties\n \"\"\"\n pre_cmp = _xml_compare_tag_attribs_text(old_xml, new_xml, reporter=reporter, compare_xml2_attribs=False)\n if not pre_cmp:\n return False\n\n old_children = old_xml.getchildren()\n new_children = new_xml.getchildren()\n\n if len(old_children) == 0:\n return True\n\n elif len(new_children) < len(old_children):\n reporter('Children length differs, {len1} < {len2} (path: {path})'\n .format(len1=len(old_children), len2=len(new_children), path=_describe_element(old_xml)))\n return False\n\n else:\n new_children_index = {}\n for child in new_children:\n tag = child.tag\n if tag not in new_children_index:\n new_children_index[tag] = []\n new_children_index[tag].append(child)\n for tag in new_children_index.iterkeys():\n new_children_index[tag].sort(_xml_tags_compare)\n\n old_children.sort(_xml_tags_compare)\n for child in old_children:\n tag = child.tag\n if tag not in new_children_index or len(new_children_index[tag]) == 0:\n reporter('Tag {tag} not exist in new xml (path: {path})'\n .format(tag=tag, path=_describe_element(old_xml)))\n return False\n\n any_matched = False\n downstream_reporter = _DownstreamReporter()\n for match_child in new_children_index[tag]:\n is_compatible = _xml_check_compatibility(child, match_child, downstream_reporter)\n if is_compatible:\n any_matched = True\n new_children_index[tag].remove(match_child)\n break\n if not any_matched:\n reporter(downstream_reporter.last_error)\n return False\n return True\n\n\nclass XmlTestCaseMixin(object):\n \"\"\"Mixin for L{unittest.TestCase}.\"\"\"\n\n def _assert_xml_compare(self, cmp_func, xml1, xml2, msg, **kwargs):\n if msg is None:\n msg = 'XML documents are not equal'\n if not isinstance(xml1, etree._Element):\n xml1 = etree.fromstring(xml1)\n if not isinstance(xml2, etree._Element):\n xml2 = etree.fromstring(xml2)\n\n def _fail_reporter(err_message):\n self.fail('{0}: {1}'.format(msg, err_message))\n\n cmp_func(xml1, xml2, reporter=_fail_reporter, **kwargs)\n\n def assertXmlEqual(self, expected, real, msg=None, check_tags_order=False):\n \"\"\"Assert that two xml documents are equal (the order of elements and attributes is ignored).\"\"\"\n self._assert_xml_compare(_xml_compare, expected, real, msg, check_tags_order=check_tags_order)\n\n def assertXmlCompatible(self, old, new, msg=None):\n \"\"\"Assert that one xml document is an extension of another.\"\"\"\n self._assert_xml_compare(_xml_check_compatibility, old, new, msg)\n","sub_path":"frontik/testing/xml_asserts.py","file_name":"xml_asserts.py","file_ext":"py","file_size_in_byte":6820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"468104256","text":"import math\nn = int(input())\na = list(map(int, input().split()))\nmod = 10**9 + 7\n\ndef lcm(a, b):\n return (a * b) // math.gcd(a, b)\n\na_lcm = 1\nfor ai in a:\n a_lcm = lcm(a_lcm, ai)\n\nb_sum = 0\nfor i in range(n):\n b_sum += a_lcm // a[i]\n\nprint(b_sum%mod)\n","sub_path":"Python_codes/p02793/s733796267.py","file_name":"s733796267.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"471188493","text":"from django.contrib.auth import get_user_model\nfrom django.db import models\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(\n get_user_model(),\n on_delete=models.CASCADE,\n verbose_name='Профиль пользователя',\n related_name='profile',\n )\n birth_date = models.DateField(\n null=True,\n blank=True,\n verbose_name='Дата рождения'\n )\n avatar = models.ImageField(\n upload_to='avatars',\n null=True,\n blank=True,\n verbose_name='Аватар'\n )\n\n def __str__(self):\n return self.user.username\n\n class Meta:\n db_table = 'profiles'\n verbose_name = 'Профиль пользователя'\n verbose_name_plural = 'Профили пользователей'\n","sub_path":"quotes_project/accounts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"288383002","text":"from django.shortcuts import render\nfrom django.core.paginator import Paginator\nfrom django.http import HttpResponseNotFound\nfrom .models import *\nfrom .utils import get_page_uv, get_subscribe_sites, get_login_user, get_user_sub_feeds, set_user_read_article, \\\n get_similar_article\nfrom .verify import verify_request\nimport logging\nfrom .sql import *\n\nlogger = logging.getLogger(__name__)\n\n\n@verify_request\ndef get_article_detail(request):\n \"\"\"\n 获取文章详情;已登录用户记录已读\n \"\"\"\n uindex = request.POST.get('id')\n user = get_login_user(request)\n mobile = request.POST.get('mobile', False)\n\n try:\n article = Article.objects.get(uindex=uindex, status='active')\n except:\n logger.warning(f\"获取文章详情请求处理异常:`{uindex}\")\n return HttpResponseNotFound(\"Param error\")\n\n if user:\n set_user_read_article(user.oauth_id, uindex)\n\n context = dict()\n context['article'] = article\n context['user'] = user\n\n if mobile:\n return render(request, 'mobile/article.html', context=context)\n else:\n return render(request, 'article/index.html', context=context)\n\n\n@verify_request\ndef get_all_feeds(request):\n \"\"\"\n 获取订阅列表,已登录用户默认展示已订阅内容;区分已订阅、未订阅\n \"\"\"\n user = get_login_user(request)\n \n if user is None:\n # 游客按照推荐和普通\n sub_sites = Site.objects.filter(status='active', star__gte=20).order_by('-star')\n unsub_sites = Site.objects.filter(status='active', star__lt=20).order_by('-star')\n else:\n user_sub_feeds = get_user_sub_feeds(user.oauth_id)\n sub_sites = Site.objects.filter(status='active', name__in=user_sub_feeds).order_by('-star')\n unsub_sites = Site.objects.filter(status='active').exclude(name__in=user_sub_feeds).\\\n exclude(star__lt=8).order_by('-star')\n\n try:\n last_site = Site.objects.filter(status='active', creator='user', star__gte=9).order_by('-ctime')[0]\n submit_tip = f\"「{last_site.cname[:20]}」({last_site.rss[:50]}) 最后被用户提交\"\n except:\n submit_tip = '提交 RSS 源,例如:https://coolshell.cn/feed'\n\n context = dict()\n context['sub_sites'] = sub_sites\n context['unsub_sites'] = unsub_sites\n context['submit_tip'] = submit_tip\n context['user'] = user\n\n return render(request, 'feeds.html', context=context)\n\n\n@verify_request\ndef get_homepage_intro(request):\n \"\"\"\n 获取首页介绍\n \"\"\"\n mobile = request.POST.get('mobile', False)\n\n context = dict()\n context['mobile'] = mobile\n\n return render(request, 'intro.html', context=context)\n\n\n@verify_request\ndef get_recent_articles(request):\n \"\"\"\n 获取最近更新内容\n \"\"\"\n user = get_login_user(request)\n recommend = request.POST.get('recommend', 'recommend')\n\n if recommend == 'unrecommend':\n articles = Article.objects.raw(get_other_articles_sql)\n elif recommend == 'recommend':\n articles = Article.objects.raw(get_recommend_articles_sql)\n else:\n logger.warning(f'未知的类型:{recommend}')\n\n user_sub_feeds = []\n if user:\n user_sub_feeds = get_user_sub_feeds(user.oauth_id)\n\n context = dict()\n context['articles'] = articles\n context['user'] = user\n context['user_sub_feeds'] = user_sub_feeds\n\n return render(request, 'explore/recent_articles.html', context=context)\n\n\n@verify_request\ndef get_explore(request):\n \"\"\"\n 获取发现页面\n \"\"\"\n user = get_login_user(request)\n\n articles = Article.objects.raw(get_recommend_articles_sql)\n\n user_sub_feeds = []\n if user:\n user_sub_feeds = get_user_sub_feeds(user.oauth_id)\n\n context = dict()\n context['articles'] = articles\n context['user'] = user\n context['user_sub_feeds'] = user_sub_feeds\n\n return render(request, 'explore/explore.html', context=context)\n\n\n@verify_request\ndef get_recent_sites(request):\n \"\"\"\n 获取最近提交源\n \"\"\"\n user = get_login_user(request)\n\n user_sub_feeds = []\n if user:\n user_sub_feeds = get_user_sub_feeds(user.oauth_id)\n\n sites = Site.objects.filter(status='active').order_by('-id')[:30]\n context = dict()\n\n context['user'] = user\n context['sites'] = sites\n context['user_sub_feeds'] = user_sub_feeds\n\n return render(request, 'explore/recent_sites.html', context=context)\n\n\n@verify_request\ndef get_faq(request):\n \"\"\"\n 获取FAQ\n \"\"\"\n mobile = request.POST.get('mobile', False)\n\n context = dict()\n context['mobile'] = mobile\n\n return render(request, 'faq.html', context=context)\n\n\n@verify_request\ndef get_homepage_tips(request):\n \"\"\"\n 获取 tips\n \"\"\"\n return render(request, 'tips.html')\n\n\n@verify_request\ndef get_all_issues(request):\n user = get_login_user(request)\n\n msgs = Message.objects.filter(status='active').order_by('-id')[:20]\n\n context = dict()\n context['msgs'] = msgs\n context['user'] = user\n\n return render(request, 'issues.html', context=context)\n\n\n@verify_request\ndef get_articles_list(request):\n \"\"\"\n 获取我的文章列表,游客展示默认推荐内容;登录用户展示其订阅内容\n \"\"\"\n # 请求参数获取\n sub_feeds = request.POST.get('sub_feeds', '').split(',')\n unsub_feeds = request.POST.get('unsub_feeds', '').split(',')\n page_size = int(request.POST.get('page_size', 10))\n page = int(request.POST.get('page', 1))\n mobile = request.POST.get('mobile', False)\n\n user = get_login_user(request)\n\n if user is None:\n visitor_sub_sites = get_subscribe_sites(tuple(sub_feeds), tuple(unsub_feeds))\n\n my_articles = Article.objects.all().prefetch_related('site').filter(\n status='active', is_recent=True, site__name__in=visitor_sub_sites).order_by('-id')[:300]\n else:\n user_sub_feeds = get_user_sub_feeds(user.oauth_id)\n\n if not user_sub_feeds:\n logger.warning(f'用户未订阅任何内容:`{user.oauth_id}')\n\n # TODO 这个 sql 比较耗时\n my_articles = Article.objects.all().prefetch_related('site').filter(\n status='active', is_recent=True, site__name__in=user_sub_feeds).order_by('-id')[:999]\n\n if my_articles:\n # 分页处理\n paginator_obj = Paginator(my_articles, page_size)\n try:\n # 页面及数据\n pg = paginator_obj.page(page)\n num_pages = paginator_obj.num_pages\n uv = get_page_uv(pg)\n\n context = dict()\n context['pg'] = pg\n context['uv'] = uv\n context['num_pages'] = num_pages\n context['user'] = user\n\n if mobile:\n return render(request, 'mobile/list.html', context=context)\n else:\n return render(request, 'list.html', context=context)\n except:\n logger.warning(f\"分页参数错误:`{page}`{page_size}`{sub_feeds}`{unsub_feeds}\")\n return HttpResponseNotFound(\"Page number error\")\n\n return HttpResponseNotFound(\"No Feeds subscribed\")\n\n\n@verify_request\ndef get_recommend_articles(request):\n \"\"\"\n 获取文章推荐的订阅源,只开放登录用户\n :param request:\n :return:\n \"\"\"\n uindex = int(request.POST['id'])\n user = get_login_user(request)\n\n if uindex and user:\n recommend_articles = []\n relative_articles = list(get_similar_article(uindex).keys())\n user_sub_feeds = get_user_sub_feeds(user.oauth_id)\n\n for relative_uindex in relative_articles:\n article = Article.objects.get(uindex=relative_uindex)\n\n if article.site.name not in user_sub_feeds:\n recommend_articles.append(article)\n if len(recommend_articles) >= 2:\n break\n\n if recommend_articles:\n logger.info(f'推荐数据条数:`{len(recommend_articles)}`{user.oauth_name}')\n\n context = dict()\n context['recommend_articles'] = recommend_articles\n\n return render(request, 'recommend/relative_article.html', context=context)\n\n return HttpResponseNotFound(\"No Recommend Data\")\n","sub_path":"web/views_html.py","file_name":"views_html.py","file_ext":"py","file_size_in_byte":8177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"606575494","text":"from tkinter import *\r\nimport tkinter.font as tkFont\r\nfrom tkinter import messagebox\r\nfrom crud_bd import CRUD_DataBase\r\nfrom frm_tablas import mostrarTablas\r\n\r\ndef view_createDatabase():\r\n\r\n def guardar():\r\n name_database = txt.get()\r\n if name_database:\r\n txt.delete(0, END)\r\n crud = CRUD_DataBase()\r\n value = crud.createDatabase(name_database)\r\n if value == 0:\r\n messagebox.showinfo('', 'Operacion Exitosa')\r\n window.destroy()\r\n elif value == 2:\r\n messagebox.showinfo('', 'Base de Datos Existente')\r\n else:\r\n messagebox.showinfo('', 'Error en la Operacion')\r\n\r\n window = Tk()\r\n edicionPantalla(window, \"Create Database\",\"#FCFCFB\", 500, 350)\r\n lbl = Label(window, text= 'Ingrese el Nombre de la Base de Datos', bg=\"#FCFCFB\")\r\n lbl.place(x = 125, y = 125)\r\n txt = Entry(window, width = 35)\r\n txt.place(x = 100, y = 160)\r\n btn = Button(window, text='Guardar', command=guardar)\r\n btn.place(x = 350, y = 200)\r\n\r\ndef view_showDatabase():\r\n list_words = CRUD_DataBase().showDatabases()\r\n var = 0\r\n # Esta es la ventana principal\r\n ventana_principal = Tk()\r\n ventana_principal.title('show Databases')\r\n ventana_principal.geometry(\"550x500\")\r\n\r\n #---------------------------------------------------------------------------------\r\n #---------------------------------------------------------------------------------\r\n # Edicion de la Ventana\r\n ancho_ventana = 550\r\n alto_ventana = 500\r\n x_ventana = ventana_principal.winfo_screenwidth() // 2 - ancho_ventana // 2\r\n y_ventana = ventana_principal.winfo_screenheight() // 2 - alto_ventana // 2\r\n posicion = str(ancho_ventana) + \"x\" + str(alto_ventana) + \"+\" + str(x_ventana) + \"+\" + str(y_ventana)\r\n ventana_principal.geometry(posicion)\r\n\r\n # Edicion de la Ventana\r\n ventana_principal.resizable(0,0)\r\n dimension = str(ancho_ventana)+'x'+str(alto_ventana)\r\n ventana_principal.geometry(dimension)\r\n ventana_principal.configure(bg=\"white\")\r\n #---------------------------------------------------------------------------------\r\n #---------------------------------------------------------------------------------\r\n\r\n # Se crea un marco principal\r\n marco_principal = Frame(ventana_principal)\r\n marco_principal.pack(fill=BOTH, expand=1)\r\n\r\n # Se crea un canvas\r\n var_canvas = Canvas(marco_principal)\r\n var_canvas.config(bg=\"red\")\r\n var_canvas.pack(side=LEFT, fill=BOTH, expand=1)\r\n\r\n # Se agrega un scrollbar al canvas\r\n var_scrollbar = Scrollbar(marco_principal, orient=VERTICAL, command=var_canvas.yview)\r\n var_scrollbar.pack(side=RIGHT, fill=Y)\r\n\r\n # Se configura el canvas\r\n var_canvas.configure(yscrollcommand=var_scrollbar.set)\r\n var_canvas.bind('', lambda e: var_canvas.configure(scrollregion = var_canvas.bbox(\"all\")))\r\n\r\n # Se crea otro marco dentro del canvas\r\n second_frame = Frame(var_canvas)\r\n\r\n # Se agrega ese nuevo marco a la ventana en el canvas\r\n var_canvas.create_window((0,0), window=second_frame, anchor=\"nw\")\r\n var_font = tkFont.Font(size=13, weight=\"bold\", family=\"Arial\")\r\n\r\n for word in list_words:\r\n btn = Button(second_frame, text=word, width=58, height=2, bg=\"#DBE2FC\", font=var_font, command=lambda txt=word:mostrarTablas(txt, ventana_principal))\r\n btn.grid(row=var, column=0, pady=1)\r\n var += 1\r\n\r\n ventana_principal.mainloop()\r\n\r\ndef view_alterDatabase():\r\n\r\n def modificar():\r\n nombre_anterior = txtAnterior.get()\r\n nombre_nuevo= txtNueva.get()\r\n if nombre_anterior and nombre_nuevo:\r\n txtAnterior.delete(0, END)\r\n txtNueva.delete(0, END)\r\n crud = CRUD_DataBase()\r\n value = crud.alterDatabase(nombre_anterior, nombre_nuevo)\r\n if value == 0:\r\n messagebox.showinfo('', 'Operacion Exitosa')\r\n window.destroy()\r\n elif value == 2:\r\n messagebox.showinfo('', 'databaseOld No Existente')\r\n elif value == 3:\r\n messagebox.showinfo('', 'databaseNew Existente')\r\n else:\r\n messagebox.showinfo('', 'Error en la Operacion')\r\n\r\n window = Tk()\r\n edicionPantalla(window, \"Alter Database\",\"#FCFCFB\", 500, 350)\r\n lblAnterior = Label(window, text= 'Nombre de la Base de Datos Anterior', bg=\"#FCFCFB\")\r\n lblAnterior.place(x = 125, y = 75)\r\n txtAnterior = Entry(window, width = 35)\r\n txtAnterior.place(x = 100, y = 115)\r\n lblNueva = Label(window, text= 'Nombre de la Base de Datos Nueva', bg=\"#FCFCFB\")\r\n lblNueva.place(x = 125, y = 150)\r\n txtNueva = Entry(window, width = 35)\r\n txtNueva.place(x = 100, y = 190)\r\n btnModificar = Button(window, text='Modificar', command = modificar)\r\n btnModificar.place(x = 345, y = 240)\r\n\r\ndef view_dropDatabase():\r\n\r\n def eliminar():\r\n name_database = txt.get()\r\n if name_database:\r\n txt.delete(0, END)\r\n crud = CRUD_DataBase()\r\n value = crud.dropDatabase(name_database)\r\n if value == 0:\r\n messagebox.showinfo('', 'Operacion Exitosa')\r\n window.destroy()\r\n elif value == 2:\r\n messagebox.showinfo('', 'Base de Datos No Existente')\r\n else:\r\n messagebox.showinfo('', 'Error en la Operacion')\r\n\r\n window = Tk()\r\n edicionPantalla(window, \"Drop Database\",\"#FCFCFB\", 500, 350)\r\n lbl = Label(window, text= 'Ingrese el Nombre de la Base de Datos', bg=\"#FCFCFB\")\r\n lbl.place(x = 125, y = 125)\r\n txt = Entry(window, width = 35)\r\n txt.place(x = 100, y = 160)\r\n btn = Button(window, text='Eliminar', command=eliminar)\r\n btn.place(x = 350, y = 200)\r\n\r\ndef view_showGraphivz():\r\n CRUD_DataBase().showGraphviz()\r\n\r\ndef edicionPantalla(window, titulo, color, ancho_ventana, alto_ventana):\r\n x_ventana = window.winfo_screenwidth() // 2 - ancho_ventana // 2\r\n y_ventana = window.winfo_screenheight() // 2 - alto_ventana // 2\r\n posicion = str(ancho_ventana) + \"x\" + str(alto_ventana) + \"+\" + str(x_ventana) + \"+\" + str(y_ventana)\r\n window.geometry(posicion)\r\n\r\n # Edicion de la Ventana\r\n window.resizable(0,0)\r\n window.title(titulo)\r\n dimension = str(ancho_ventana)+'x'+str(alto_ventana)\r\n window.geometry(dimension)\r\n window.configure(bg=str(color))\r\n\r\nwindow = Tk()\r\n\r\nedicionPantalla(window,\"Base de Datos\",\"white\", 830, 525)\r\n\r\nvar_width = 25\r\nseparacion = 3\r\nvar_height = int(var_width//2.5)\r\nvar_font = tkFont.Font(size=12, weight=\"bold\", family=\"Arial\")\r\n\r\nbtnGraficarArbol = Button(window, text=\"Graficar Arbol\", bg=\"#AAAFBF\", fg=\"white\", font=var_font, width=60, command=view_showGraphivz)\r\nbtnGraficarArbol.grid(padx=separacion, pady=separacion, row=0, column=1, columnspan = 3)\r\n\r\nizquierda = Label(window, text=\"\", bg=\"white\",width=16)\r\nizquierda.grid(padx=separacion, pady=separacion, row=1, column=0, rowspan =2)\r\n\r\nbtncreateDatabase = Button(window, text=\"CREATE NEW DATABASE\", bg='#4484BC', fg='white', font=var_font, height= var_height, width=var_width, command=view_createDatabase)\r\nbtncreateDatabase.grid(padx=separacion, pady=separacion, row=1, column=1)\r\n\r\nbtnshowDatabases = Button(window, text=\"SHOW DATABASE\", bg='#FCE433', fg='black', font=var_font, height= var_height, width=var_width, command = view_showDatabase)\r\nbtnshowDatabases.grid(padx=separacion, pady=separacion, row=2, column=1)\r\n\r\nbtnalterDatabase = Button(window, text=\"ALTER DATABASE\", bg='#4484BC', fg='white', font=var_font, height= var_height, width=var_width, command = view_alterDatabase)\r\nbtnalterDatabase.grid(padx=separacion, pady=separacion, row=1, column=2)\r\n\r\nbtndropDatabase = Button(window, text=\"DROP DATABASE\", bg='#FCE433', fg='black', font=var_font, height= var_height, width=var_width, command = view_dropDatabase)\r\nbtndropDatabase.grid(padx=separacion, pady=separacion, row=2, column=2)\r\n\r\nwindow.mainloop()","sub_path":"storage/team12/frm_menuprincipal.py","file_name":"frm_menuprincipal.py","file_ext":"py","file_size_in_byte":8021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"519094285","text":"\n\n#calss header\nclass _WARRANT():\n\tdef __init__(self,): \n\t\tself.name = \"WARRANT\"\n\t\tself.definitions = [u'to make a particular activity necessary: ', u'used to say that you are certain about something: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_warrant.py","file_name":"_warrant.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"538650998","text":"#Slef Organising Maps\r\n\r\n#we are making model to for fraud detetction . imagine we are working for a bank and\r\n#we have given this information of customer from thi bank applying for advanced credit card\r\n#this data is customer need to provide while filling the applicn.\r\n#and we need to detect potential fraud in this appn\r\n\r\n\r\n#Importing librabries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#http://archive.ics.uci.edu/ml/datasets/statlog+(australian+credit+approval)\r\n#importing dataset\r\nCCA_data = pd.read_csv('Credit_Card_Applications.csv')\r\nX = CCA_data.iloc[:,:-1].values\r\ny = CCA_data.iloc[:,-1]\r\n\r\n#feature Scaling\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nsc = MinMaxScaler()\r\nX=sc.fit_transform(X)\r\n\r\n#MiniSom 1.O\r\n#trianing the som\r\nfrom minisom import MiniSom\r\nsom=MiniSom(x=10 ,y=10 , input_len=15 ,sigma=1.0 ,learning_rate=0.5)\r\n#here x and y are grid dimension adn i/p len is columns including client id and sigma is radius\r\n\r\nsom.random_weights_init(X)\r\nsom.train_random(data=X,num_iteration=100)\r\n\r\n# Visualizing the results\r\nfrom pylab import bone, pcolor, colorbar, plot, show\r\nbone()\r\npcolor(som.distance_map().T)\r\ncolorbar()\r\nmarkers = ['o', 's']\r\ncolors = ['r', 'g']\r\nfor i, x in enumerate(X):\r\n w = som.winner(x)\r\n plot(w[0] + 0.5,\r\n w[1] + 0.5,\r\n markers[y[i]],\r\n markeredgecolor = colors[y[i]],\r\n markerfacecolor = 'None',\r\n markersize = 10,\r\n markeredgewidth = 2)\r\nshow()\r\n\r\n#Finding the fraud, we will find the customer by mapping MID(mean interneuron distance)\r\n# i.e white outlier\r\n#which are fraud winning node to customer. this winning node is mapped to dic\r\n# and this dic has key which are coordiante in map whic will give us the cliend id\r\n#axis=0 is vertical\r\n# Finding the frauds\r\nmappings = som.win_map(X)\r\nfrauds = np.concatenate((mappings[(3,8)], mappings[(2,8)],mappings[(2,7)]), axis = 0)\r\nfrauds = sc.inverse_transform(frauds)\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"SOM_1.py","file_name":"SOM_1.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"95474286","text":"\r\n\r\n\r\n\"\"\" 使用面向对象的思路实现『停车收费』场景:\r\n1. 车主开车进入停车场,产生停车记录,\r\n2. 车主开车继续向前,将车停到车位上,修改前面的停车记录,\r\n3. 车主停车完成,\r\n一段时间(购物、吃饭...)之后,车主驾车准备离开停车场,\r\n4. 车主开车离开车位,修改停车记录,\r\n5. 车主开车到达出口,系统根据停车的时间生成订单,\r\n6. 车主缴纳停车费,\r\n7. 车主离开停车场。\r\n至此,整个停车收费的场景完成。 \"\"\"\r\n\r\n\r\nimport time\r\nfrom Car import *\r\n\r\n#停车收费类\r\nclass park():\r\n plateNum = ''\r\n #plateNum 车牌号 stopTime停车时间 drivTime出车时间 \r\n def __init__(self,stopTime=0, drivTime=0):\r\n self.stopTime = stopTime\r\n self.drivTime = drivTime\r\n\r\n #计算停车费用方法\r\n def exit(self):\r\n drivTime = time.time() #记录出车时间\r\n tt = drivTime - stopTime #tt 在停车场的停车时间\r\n #计算小于1小时的费用\r\n if tt <3600: \r\n print('您的停车费为5元')\r\n cars.out_park()\r\n #计算大于1小时的费用 \r\n else:\r\n num =((tt//3600)+1) * 5\r\n print('您的停车费为',num,'元')\r\n cars.out_park()\r\n#创建车类实例\r\ncars = car()\r\nwhile True:\r\n #功能选择\r\n module_key = input(\r\n '''\r\n 欢迎进入:\r\n 1.停车\r\n 2.出车\r\n 3.退出系统 \r\n '''\r\n )\r\n if module_key == '3': #退出功能选择\r\n break\r\n elif module_key == '1': #停车功能选择\r\n cars.into_park()\r\n pla = input('输入车牌号:') \r\n #把车牌号存入变量\r\n plateNum = park(pla)\r\n #记录停车时间\r\n stopTime = time.time() \r\n cars.into_stall()\r\n print('停车成功')\r\n #出车功能选项 \r\n elif module_key == '2':\r\n cars.out_stall()\r\n pl = input('输入车牌号:')\r\n #判断出车牌号是否与进车一致\r\n #一致 :计算费用\r\n if pl == pla:\r\n #判断出车车辆\r\n carr = park(pl) \r\n #调用收费方法\r\n carr.exit()\r\n #不一致:从新输入 \r\n else:\r\n print('车牌号不一致,请从新输入')\r\n time.sleep(2)\r\n continue \r\n else:\r\n print('输入错误,请重新选择.')\r\n time.sleep(2)\r\n continue \r\n\r\n ","sub_path":"ParkingCharge/Park.py","file_name":"Park.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"62506704","text":"import math\r\nimport heapq\r\n\r\ndef adjacent(point, N):\r\n x = point[0]\r\n y = point[1]\r\n if x == 0:\r\n if y == 0:\r\n return [(0, 1), (1, 0)]\r\n elif y == N-1:\r\n return [(0, N-2), (1, N-1)]\r\n else:\r\n return [(0, y-1), (0, y+1), (1, y)]\r\n elif x == N-1:\r\n if y == 0:\r\n return [(N-2, 0), (N-1, 1)]\r\n elif y == N-1:\r\n return [(N-2, N-1), (N-1, N-2)]\r\n else:\r\n return [(N-2, y), (N-1, y-1), (N-1, y+1)]\r\n else:\r\n if y == 0:\r\n return [(x - 1, 0), (x, 1), (x+1, 0)]\r\n elif y == N-1:\r\n return [(x-1, N-1), (x, N-2), (x+1, N-1)]\r\n else:\r\n return [(x-1, y), (x, y-1), (x, y+1), (x+1, y)]\r\n\r\n\r\ndef compute_altitude(point1, point2, maze, N):\r\n x_1 = point1[0]\r\n x_2 = point2[0]\r\n y_1 = point1[1]\r\n y_2 = point2[1]\r\n return abs(int(maze[y_1*N+x_1+y_1])-int(maze[y_2*N+x_2+y_2]))\r\n\r\n##USE HEAPS FOR QUEUED\r\n\r\n\r\n\r\ndef path_finder(maze):\r\n maze_len = len(maze)\r\n N = math.floor(maze_len ** 0.5)\r\n weights = [N * [float(\"inf\")] for k in range(N)]\r\n weights[0][0] = 0\r\n priority = []\r\n for i in range(N):\r\n for j in range(N):\r\n if i == j and i == 0:\r\n priority.append((0, (i, j)))\r\n else:\r\n priority.append((float(\"inf\"), (i, j)))\r\n final = (N-1, N-1)\r\n visiting = (0, 0)\r\n visited = set()\r\n while visiting != final:\r\n visited.add(visiting)\r\n x_visiting = visiting[0]\r\n y_visiting = visiting[-1]\r\n for node in adjacent(visiting, N):\r\n x_adjacent = node[0]\r\n y_adjacent = node[-1]\r\n if node not in visited:\r\n update_weight = weights[y_visiting][x_visiting] + compute_altitude(visiting, node, maze, N)\r\n if weights[y_adjacent][x_adjacent] > update_weight:\r\n weights[y_adjacent][x_adjacent] = update_weight\r\n heapq.heappush(priority, (update_weight, node))\r\n visiting = heapq.heappop(priority)[1]\r\n while visiting[1] in visited:\r\n visiting = heapq.heappop(priority)[1]\r\n return weights[N-1][N-1]\r\n\r\n\r\n\r\na = \"\\n\".join([\r\n \"000\",\r\n \"000\",\r\n \"000\"\r\n])\r\n\r\nb = \"\\n\".join([\r\n \"010\",\r\n \"010\",\r\n \"010\"\r\n])\r\n\r\nc = \"\\n\".join([\r\n \"010\",\r\n \"101\",\r\n \"010\"\r\n])\r\n\r\nd = \"\\n\".join([\r\n \"0707\",\r\n \"7070\",\r\n \"0707\",\r\n \"7070\"\r\n])\r\n\r\ne = \"\\n\".join([\r\n \"700000\",\r\n \"077770\",\r\n \"077770\",\r\n \"077770\",\r\n \"077770\",\r\n \"000007\"\r\n])\r\n\r\nf = \"\\n\".join([\r\n \"777000\",\r\n \"007000\",\r\n \"007000\",\r\n \"007000\",\r\n \"007000\",\r\n \"007777\"\r\n])\r\n\r\ng = \"\\n\".join([\r\n \"000000\",\r\n \"000000\",\r\n \"000000\",\r\n \"000010\",\r\n \"000109\",\r\n \"001010\"\r\n])\r\n\r\nprint(path_finder(a))\r\nprint(path_finder(b))\r\nprint(path_finder(c))\r\nprint(path_finder(d))\r\nprint(path_finder(e))\r\nprint(path_finder(f))\r\nprint(path_finder(g))\r\n\r\n\r\n","sub_path":"PathFinder3.py","file_name":"PathFinder3.py","file_ext":"py","file_size_in_byte":2900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"567710897","text":"# -*- coding: utf-8 -*-\nfrom django import forms\n\n\nfrom blogs.models import Post, Blog\nfrom comments.models import Comment\n\n\nclass FilterForm(forms.Form):\n sort = forms.ChoiceField(choices=(\n ('title', u'Заголовок'),\n ('description', u'Описание')\n ), label=u'Сортировать по', required=False)\n\n search = forms.CharField(max_length=255, label=u'Поиск', required=False)\n\n\nclass CreatePostForm(forms.ModelForm):\n class Meta:\n model = Post\n fields = ('blog', 'title', 'content',)\n\n def __init__(self, *args, **kwargs):\n user = kwargs.pop('user')\n super(CreatePostForm, self).__init__(*args, **kwargs)\n self.fields['blog'].queryset = Blog.objects.filter(owner=user)\n\n\nclass UpdatePostForm(forms.ModelForm):\n class Meta:\n model = Post\n fields = ('title', 'content')\n\n\nclass CreateCommentForm(forms.ModelForm):\n class Meta:\n model = Comment\n fields = ('text',)\n\n def __init__(self, *args, **kwargs):\n super(CreateCommentForm, self).__init__(*args, **kwargs)\n\n def is_valid(self):\n return super(CreateCommentForm, self).is_valid()\n\n\nclass CreateBlogForm(forms.ModelForm):\n class Meta:\n model = Blog\n fields = ('title', 'description', 'category')\n widgets = {\n 'category': forms.SelectMultiple(attrs={'class': 'chosen-select'})\n }\n\n\nclass UpdateBlogForm(forms.ModelForm):\n class Meta:\n model = Blog\n fields = ('title', 'description', 'category')\n widgets = {\n 'category': forms.SelectMultiple(attrs={'class': 'chosen-select'})\n }\n","sub_path":"blogs/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"124153326","text":"from flask import Flask\nimport requests\nimport pandas as pd\nimport numpy as np\nimport sqlite3\n\napp = Flask(__name__)\n\n#GET_ALL_TABLE_NAME\n#Funsi API dimulai dari @app.route\n@app.route('/data/get/',methods=['GET'])\n#Fungsi untuk mendapatkan semua nama table pada database\ndef GET_ALL_TABLE_NAME(database_name):\n #definisikan object connection /data/databasename\n conn = sqlite3.connect('data/' + str(database_name))\n #perintah SQL yang digunakan SELECT semua nama pada sqlite_master ambil semua nama table yang tidak ada string sqlite%\n sql_command = \"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'\"\n #simpan pada dataframe data1 hasil SQL Query tersebut\n data1 = pd.read_sql_query(str(sql_command),conn)\n #kembalikan dataframe\n return (data1.to_json())\n\n#GET_ALL_COlUMN_AT_TABLE\n# API ditambahkan adalah dimana object
akan diparsing ke dalam SQL Query\n@app.route('/data/get//
',methods=['GET'])\n#Fungsi untuk mendapatkan semua nama kolom pada table\ndef GET_TABLE_CONTENT(database_name,table):\n #definisikan object connection /data/databasename\n conn = sqlite3.connect('data/' + str(database_name))\n # pilih semua kolom pada
\n sql_command = \"SELECT * FROM \"+table\n #simpan pada dataframe data1 hasil SQL Query tersebut\n data2 = pd.read_sql_query(str(sql_command),conn)\n #kembalikan dataframe\n return (data2.to_json())\n\n#GET_TABLE_AND_NAME\n@app.route('/data/get//
/',methods=['GET'])\ndef GET_TABLE_AND_NAME(database_name,table,column):\n conn = sqlite3.connect('data/' + str(database_name))\n sql_command = \"SELECT \"+column+\" FROM \"+table\n data3 = pd.read_sql_query(str(sql_command),conn)\n return (data3.to_json())\n\n#COMBINED_TABLE\n@app.route('/data/get////',methods=['GET'])\ndef COMBINED_TABLE(database_name,table1,table2,key):\n conn = sqlite3.connect('data/' + str(database_name))\n #Lakukan parsing pada table1, table2 dan key\n sql_command = \"SELECT Customers.Firstname,Customers.LastName,Customers. \\\n City,Customers.Address,Invoices.Total FROM \" +table1+ \" LEFT JOIN \"+table2+\" ON \"+table1+\".\"+key+\"=\"+table2+\".\"+key\n data4 = pd.read_sql_query(str(sql_command),conn)\n #kembalikan dataframe\n return (data4.to_json())\n\n#COMBINED_TABLE_WITH_CONFIGURABLE_COLUMN\n@app.route('/data/get/////',methods=['GET'])\ndef COMBINED_TABLE_WITH_CONFIGURABLE_COLUMN(database_name,table1,table2,key,column):\n conn = sqlite3.connect('data/' + str(database_name))\n # Lakukan parsing pada table 1, table 2 dan key kedalam SQL Query\n sql_command = \"SELECT \"+table1+\".\"+column+\" FROM \" +table1+ \" LEFT JOIN \"+table2+\" ON \"+table1+\".\"+key+\"=\"+table2+\".\"+key\n data5 = pd.read_sql_query(str(sql_command),conn)\n return (data5.to_json())\n\n#COMBINED_TABLE_WITH_CONFIGURABLE_TWO_COLUMN\n@app.route('/data/get//////',methods=['GET'])\ndef COMBINED_TABLE_WITH_CONFIGURABLE_TWO_COLUMN(database_name,table1,table2,key,column1,column2):\n conn = sqlite3.connect('data/' + str(database_name))\n # Lakukan parsing pada table 1, table 2,key, column1,column2 kedalam SQL Query\n sql_command = \"SELECT \"+table1+\".\"+column1+\",\"+table2+\".\"+column2+\" FROM \" +table1+ \" LEFT JOIN \" \\\n +table2+\" ON \"+table1+\".\"+key+\"=\"+table2+\".\"+key\n data6 = pd.read_sql_query(str(sql_command),conn)\n return (data6.to_json())\n\n#COMBINED_TABLE_WITH_CONFIGURABLE_TWO_COLUMN_GET_TOP5\n@app.route('/data/get///////',methods=['GET'])\ndef COMBINED_TABLE_WITH_CONFIGURABLE_TWO_COLUMN_GET_TOP5(database_name,table1,table2,key,column1,column2,command):\n conn = sqlite3.connect('data/' + str(database_name))\n sql_command = \"SELECT \"+table1+\".\"+column1+\",\"+table2+\".\"+column2+\" FROM \" +table1+ \" LEFT JOIN \" \\\n +table2+\" ON \"+table1+\".\"+key+\"=\"+table2+\".\"+key\n if command==\"top5\":\n value=5\n elif command==\"top10\":\n value=10\n elif command==\"top15\":\n value=15\n data7 = pd.read_sql_query(str(sql_command),conn)\n data7 = data7.sort_values(by = 'Total', ascending = False).head(value)\n return (data7.to_json())\n \n \nif __name__ == '__main__':\n app.run(debug=True, port=5000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"77675948","text":"from datetime import datetime\nfrom unittest import TestCase\n\nimport basketball_reference_web_scraper.client as client\nfrom basketball_reference_web_scraper.data import OutputWriteOption, OutputType\n\n\nclass TestClient(TestCase):\n def test_schedules_from_2001(self):\n now = datetime.now()\n current_year = now.year\n\n for year in range(2001, current_year + 1):\n season_schedule = client.season_schedule(season_end_year=year)\n self.assertIsNotNone(season_schedule)\n\n def test_output_json_box_scores_to_file(self):\n client.player_box_scores(\n day=1,\n month=1,\n year=2001,\n output_type=OutputType.JSON,\n output_file_path=\"./foo.json\",\n output_write_option=OutputWriteOption.WRITE\n )\n\n def test_output_json_box_scores_to_memory(self):\n january_first_box_scores = client.player_box_scores(\n day=1,\n month=1,\n year=2001,\n output_type=OutputType.JSON,\n )\n\n self.assertIsNotNone(january_first_box_scores)\n\n def test_2018_player_season_totals(self):\n now = datetime.now()\n current_year = now.year\n\n for year in range(2001, current_year + 1):\n player_season_totals = client.players_season_totals(season_end_year=year)\n self.assertIsNotNone(player_season_totals)","sub_path":"tests/test_integration_client.py","file_name":"test_integration_client.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"190918376","text":"import unittest\nfrom selenium import webdriver\nfrom Pages.Home import HomePage\nimport time\n\n\nclass Challenge2(unittest.TestCase):\n\n def setUp(self):\n self.driver = webdriver.Chrome(\"../chromedriver.exe\")\n self.driver.get(\"https://www.copart.com\")\n\n def tearDown(self):\n self.driver.close()\n\n def test_challenge2(self):\n test_driver = self.driver\n search = HomePage(test_driver)\n search.enter_search_text(\"Porsche\")\n search.click_search_button()\n time.sleep(3)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"challenge2/challenge2.py","file_name":"challenge2.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"156656017","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 21 09:00:40 2018\n\n@author: s.granel\n\"\"\"\n\n#Imports\nimport sys\nimport numpy as np\nimport pandas as pd\nimport psycopg2\nfrom keras.models import load_model\nimport datetime\nimport time\n\nfolder = sys.argv[1]\n#folder = \"\"\nlist_element = sys.argv[2]\n#list_element = \"33600006:1;33600006:2;33600006:3;33600006:4;33600006:5;33600006:6\"\n#idcarburant = 1\nmodel = load_model(folder+'predict_fuel_dep_and_pdv.h5')\n# Jeu d'entrainement\nconn = None\n\nelements = list_element.split(\";\")\n\nconnVPS = None\nidpdv = None\nidcarburant = None\ntry:\n conn = psycopg2.connect(\"dbname='fuelpred' user='fuelpred' host='localhost' password='fuelpred'\")\n cur = conn.cursor()\n\n connVPS = psycopg2.connect(\"dbname='fuelpred' user='postgres' host='51.75.207.51' password='j9lk_hQb'\")\n curVPS = connVPS.cursor()\n \n\n for ele in elements : \n ids = ele.split(\":\")\n idpdv = ids[0]\n idcarburant = ids[1]\n tmps1 = time.time()\n training_set = pd.DataFrame(columns=['A', 'B', 'C', 'D']);\n \n cur.execute(\"SELECT val,date, substring(cp, 1, char_length(cp)-3) as cp From public.pdv_valeurs pv1 INNER JOIN pdv_infos pi ON pv1.idpdv = pi.idpdv WHERE pv1.id in( SELECT pv.id from public.pdv_valeurs pv WHERE pv.idpdv = %s and idcarburant = %s ORDER BY date desc limit 401) ORDER BY date ASC;\", (idpdv,idcarburant))\n rows = cur.fetchall()\n if(len(rows) < 400) : \n #print(\"KO : \" +idpdv + \",\"+ idcarburant + \" : \" + str(len(rows)))\n continue\n for record in rows:\n cur.execute(\"SELECT min(val), avg(val), max(val) from public.pdv_valeurs pv INNER JOIN pdv_infos pi ON pv.idpdv = pi.idpdv WHERE date = %s AND length(cast(cp as varchar)) = 5 and substring(cast(cp as varchar), 1, char_length(cast(cp as varchar))-3) = %s and idcarburant = %s\", (record[1],record[2], 1))\n vals = cur.fetchone()\n training_set = training_set.append({'A' :record[0], 'B' : vals[0], 'C' :vals[1], 'D' : vals[2]}, ignore_index=True)\n \n training_set = training_set[['A', 'B', 'C', 'D']].values \n \n predicted = []\n \n def predict_dep(training_set, model, predicted):\n \n # Création de la structure avec 400 timesteps et 1 sortie\n X_test = []\n nb_pred = 400\n nb_pred_final = len(training_set)-1 -nb_pred # nombre de valeurs précédents celle-là\n if(nb_pred_final < 0):\n return\n for i in range(nb_pred_final, len(training_set)-1) :\n X_test.append(training_set[i, 0])\n \n X_test =np.expand_dims(X_test, axis=1)\n X_test =np.expand_dims(X_test, axis=0)\n \n val = model.predict(X_test)\n temp = val[0][0]\n val[0][0] = val[0][2]\n val[0][2] = temp\n training_set = np.delete(training_set, 0, 0)\n training_set = np.append(training_set, val,axis=0)\n \n return training_set\n \n for i in range(0,5):\n training_set = predict_dep(training_set, model, predicted)\n if(training_set is None):\n training_set = []\n else :\n predicted.append(training_set[400])\n \n date_batch = datetime.date.today()\n date_predict = date_batch\n \n if len(predicted) > 4:\n for i in range(0,5):\n curVPS.execute(\"SELECT valeur_pdv, valeur_min, valeur_max, valeur_avg from public.predict_fuel_dep_pdv_valeurs WHERE date_predict = %(date_predict)s and date_batch = %(date_batch)s and idpdv = %(idpdv)s and idcarburant = %(idcarburant)s\", {'date_predict' : date_predict.isoformat(), 'date_batch' : date_batch.isoformat(), 'idpdv' : idpdv, 'idcarburant' : idcarburant})\n rows = curVPS.fetchall()\n result = 0\n for record in rows:\n result = 1\n if(result == 0):\n curVPS.execute(\"INSERT INTO public.predict_fuel_dep_pdv_valeurs (valeur_pdv, valeur_min, valeur_avg, valeur_max, date_predict, date_batch, idpdv, idcarburant) VALUES(%(val_pdv)s, %(val_min)s, %(val_avg)s, %(val_max)s, %(date_predict)s, %(date_batch)s, %(idpdv)s, %(idcarburant)s)\", {'val_pdv' : predicted[i][0], 'val_min' : predicted[i][1], 'val_avg' : predicted[i][2], 'val_max' : predicted[i][3] ,'date_predict' : date_predict.isoformat(), 'date_batch' : date_batch.isoformat(), 'idpdv' : idpdv, 'idcarburant' : idcarburant})\n else :\n curVPS.execute(\"UPDATE public.predict_fuel_dep_pdv_valeurs SET valeur_pdv = %(val_pdv)s, valeur_min = %(val_min)s, valeur_avg = %(val_avg)s, valeur_max = %(val_max)s WHERE date_predict = %(date_predict)s and date_batch = %(date_batch)s and idpdv = %(idpdv)s and idcarburant = %(idcarburant)s\", {'val_pdv' : predicted[i][0], 'val_min' : predicted[i][1], 'val_avg' : predicted[i][2], 'val_max' : predicted[i][3], 'date_predict' : date_predict.isoformat(), 'date_batch' : date_batch.isoformat(), 'idpdv' : idpdv, 'idcarburant' : idcarburant})\n connVPS.commit()\n date_predict = date_predict + datetime.timedelta(1)\nexcept:\n print(\"I am unable to connect to the database.\")\nfinally:\n if conn is not None:\n conn.close()\n connVPS.close()\n #print('Database connection closed.')\n","sub_path":"fuelPred/predict_fuel_dep_and_pdv.py","file_name":"predict_fuel_dep_and_pdv.py","file_ext":"py","file_size_in_byte":5443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"572923251","text":"#import my.Wlep_sel\n#import my.final_fatjetsel\n\n\n\n#supercut = 'nCleanFatJet==1'\n\n\n\n#-----Variable Deinition-----#\n\n\n\nYear='2018'\neleWP='mvaFall17V1Iso_WP90'\nmuWP='cut_Tight_HWWW'\n\n\n\nLepWPCut='(Lepton_isTightElectron_'+eleWP+'[0]>0.5 || Lepton_isTightMuon_'+muWP+'[0]>0.5)'\nLepPtCut='(Lepton_pt[0] > 35*(abs(Lepton_pdgId[0])==11))'\nLepCut=\"( Lepton_pt[0]>30 \\\n&& ( fabs(Lepton_eta[0]) < 2.1*(abs(Lepton_pdgId[0])==11) \\\n|| fabs(Lepton_eta[0]) < 2.4*(abs(Lepton_pdgId[0])==13))\\\n&& ( ( Alt$( Lepton_pt[1],-1) < 15*( abs( Alt$(Lepton_pdgId[1], 11)) ==11) )\\\n|| ( Alt$( Lepton_pt[1],-1) < 10*( abs( Alt$(Lepton_pdgId[1], 13)) ==13) )\\\n)\\\n)\"\n\n\n\n\n#------End of Variable Definition-----#\nsupercut = LepWPCut+'&&'+LepPtCut+'&&'+LepCut\n\nLepCats={}\nLepCats['']='(1)'\nLepCats['ElectronCh']='(abs(Lepton_pdgId[0])==11)'\nLepCats['MuonCh']='(abs(Lepton_pdgId[0])==13)'\n\n\nBoostCats={}\n#BoostCats['BoostedSR']='IsBoostedSR'\nBoostCats['BoostedSB']='IsBoostedSB'\nBoostCats['BoostedTop']='IsBoostedTopCR'\n \nBoostProcCats={}\nBoostProcCats['']='1'\nBoostProcCats['ggf']='!IsVbfFat'\nBoostProcCats['vbf']='IsVbfFat'\n\n\nResolveCats={}\n#ResolveCats['ResolvedSR']='IsResolvedSR&&(nCleanFatJet==0)'\nResolveCats['ResolvedSB']='IsResolvedSB&&(nCleanFatJet==0)'\nResolveCats['ResolvedTop']='IsResolvedTopCR&&(nCleanFatJet==0)'\n \nResolveProcCats={}\nResolveProcCats['']='1'\nResolveProcCats['ggf']='!IsVbfjj'\nResolveProcCats['vbf']='IsVbfjj'\n\n\n\n\n##===Define cuts===###\nfor Lep in LepCats:\n \n\n\n for BCat in BoostCats: \n for BProcCat in BoostProcCats:\n cuts[Lep+BProcCat+BCat+Year]=BoostCats[BCat]\\\n +'&&'+BoostProcCats[BProcCat]\\\n +'&&'+LepCats[Lep]\n\n for RCat in ResolveCats: \n for RProcCat in ResolveProcCats:\n cuts[Lep+RProcCat+RCat+Year]=ResolveCats[RCat]\\\n +'&&'+ResolveProcCats[RProcCat]\\\n +'&&'+LepCats[Lep]\n\n","sub_path":"Configurations/HWWSemiLepHighMass/nanoAODv5/2018/Mix/cuts_CR.py","file_name":"cuts_CR.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"124572801","text":"import pygame\nfrom pygame.locals import *\n\npygame.init()\n\n#Ouverture de la fenêtre Pygame\nfenetre = pygame.display.set_mode((800, 600))\n\n#Chargement et collage du fond\nfond = pygame.image.load(\"background.jpg\").convert()\nfenetre.blit(fond, (0,0))\n\n#Chargement et collage du personnage\nperso = pygame.image.load(\"mario.png\").convert_alpha()\n\n\nmario_width=18 # 18 pixels for the mario sprite\nnum_image=0\nfenetre.blit(perso, (400,530), (num_image*(mario_width)+80, 0, mario_width, 40))\n\n\n#Rafraîchissement de l'écran\npygame.display.flip()\n\n#BOUCLE INFINIE\ncontinuer = 1\nwhile continuer:\n continuer = int(input())\n","sub_path":"overlay/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"600316977","text":"#!/usr/bin/env python\n\n#pylint: disable=global-statement\n\n'''\nCreate a ROS node that uses rapidly exploring random trees to do driving\n'''\n\nimport rospy\n\nimport math\nimport sys\n\nfrom geometry_msgs.msg import Pose, PoseStamped, Twist\nfrom nav_msgs.msg import Odometry\n# from scaling_waffle.srv import PotentialField, PotentialFieldResponse\nfrom scaling_waffle.srv import Plan\nfrom utils import quaternion_to_heading\n\nDRIVER = None\nPATHVIZ = None\n\npositions = [None]\ngoals = []\n\nstart = None\nend = Pose()\nend.position.x = 32\nend.position.y = 32\n\ncrash_flag = False\n\ncount = 0\n\nget_plan = None\nreset_root = None\n\ndef distance(pose1, pose2):\n # rospy.loginfo(''+str(type(pose1))+' '+str(type(pose2)))\n x1 = pose1.position.x\n y1 = pose1.position.y\n x2 = pose2.position.x\n y2 = pose2.position.y\n return math.sqrt(math.pow(x1-x2,2) + math.pow(y1-y2,2))\n\ndef minimize(dtheta):\n while dtheta >= 2*math.pi:\n dtheta = dtheta - 2*math.pi\n while dtheta <= -2*math.pi:\n dtheta = dtheta + 2*math.pi\n if dtheta > math.pi:\n dtheta = -2*math.pi + dtheta\n if dtheta < -math.pi:\n dtheta = 2*math.pi + dtheta\n return dtheta\n\ndef odom_cb(odom):\n global start\n global count\n global goals\n if start is None:\n start = odom.pose.pose\n return\n\n positions[0] = odom\n if len(goals) <= 0:\n # set speed to 0 and return\n if DRIVER is not None:\n if distance(end, odom.pose.pose) > .01:\n rospy.loginfo('Driver: get a new set of goals')\n if rrt:\n DRIVER.publish(Twist())\n rospy.wait_for_service('/rrt/reset')\n reset_root(positions[0].pose.pose, end)\n goals = get_plan(odom.pose.pose, end).allpoints\n if (len(goals) == 0):\n rospy.loginfo('Driver: arrived at goal')\n DRIVER.publish(Twist())\n global crash_flag\n crash_flag = True\n else:\n for pose in goals:\n ps = PoseStamped()\n ps.pose = pose\n ps.header.frame_id = '/odom'\n if PATHVIZ is not None:\n PATHVIZ.publish(ps)\n else:\n rospy.loginfo('Driver: empty goals list')\n DRIVER.publish(Twist())\n \n goals = get_plan(odom.pose.pose, end).allpoints\n if (len(goals) == 0):\n rospy.loginfo('Driver: arrived at goal')\n DRIVER.publish(Twist())\n \n sys.exit(0)\n return\n elif distance(odom.pose.pose, goals[0]) < .05:\n # if I'm on the goal, remove the current goal, set the speed to 0\n goals.pop(0)\n count += 1\n \n if DRIVER is not None:\n # rospy.loginfo('Driver: next goal')\n DRIVER.publish(Twist())\n return\n else:\n # find the deltas between my position and the angle to the next goal\n # drive towards the goal position\n # rospy.loginfo('odom pose: %s', odom.pose.pose)\n hz = 10.0\n dt = 1.0/hz\n\n rospy.loginfo('Driver: moving on to %d/%d' % (count, len(goals),))\n t = Twist()\n current_position = odom.pose.pose\n next_ = goals[0]\n\n t.angular.z = 0.0\n\n dx = next_.position.x - current_position.position.x\n dy = next_.position.y - current_position.position.y\n\n goal_direction = math.atan2(dy, dx)\n current_direction = quaternion_to_heading(current_position.orientation)\n\n dtheta = goal_direction - current_direction\n dtheta = minimize(dtheta)\n\n t.angular.z = dtheta/(2.0*dt)\n\n if t.angular.z > 0.25:\n t.angular.z = 0.25\n if t.angular.z < -0.25:\n t.angular.z = -0.25\n\n t.linear.x = 0.0\n rospy.loginfo('dtheta %f if.' % (dtheta,))\n if abs(dtheta) < .01:\n # I'm pointing in the right direction, go forward\n dist = distance(next_, end)\n t.linear.x = 0.2 + dist*dist\n rospy.loginfo('if. dist %f' % (t.linear.x,))\n\n if t.linear.x > 0.5:\n t.linear.x = 0.5\n if t.linear.x < -0.5:\n t.linear.x = -0.5\n\n rospy.loginfo('D.p(%f,%f)' % (t.linear.x, t.angular.z,))\n\n DRIVER.publish(t)\n\n\nif __name__ == '__main__':\n rospy.init_node('simple_driver')\n\n ODOM_SUB = rospy.Subscriber('/odom', Odometry, odom_cb)\n\n rrt = True\n if rrt:\n rospy.loginfo('waiting for rrt plan service')\n rospy.wait_for_service('/rrt/plan')\n rospy.wait_for_service('/rrt/reset')\n get_plan = rospy.ServiceProxy('/rrt/plan', Plan)\n reset_root = rospy.ServiceProxy('/rrt/reset', Plan)\n rospy.loginfo('found rrt plan service')\n else:\n rospy.loginfo('waiting for potential plan service')\n rospy.wait_for_service('/potential/plan')\n get_plan = rospy.ServiceProxy('/potential/plan', Plan)\n rospy.loginfo('found potential plan service')\n\n rate_limit = rospy.Rate(2)\n while start is None:\n rate_limit.sleep()\n\n # rospy.loginfo('start and end\\n'+str(start)+'\\n'+str(end))\n\n resp1 = get_plan(start, end)\n goals = resp1.allpoints\n \n PATHVIZ = rospy.Publisher('/pathviz', PoseStamped, queue_size=1)\n for pose in goals:\n ps = PoseStamped()\n ps.pose = pose\n ps.header.frame_id = '/odom'\n if PATHVIZ is not None:\n PATHVIZ.publish(ps)\n \n rospy.loginfo('I got a %d step plan' % (len(goals)))\n if (len(goals) == 0):\n rospy.loginfo('already at goal')\n \n sys.exit(0)\n waiting_for_plan = False\n \n DRIVER = rospy.Publisher('/cmd_vel', Twist, queue_size=1)\n GOALER = rospy.Publisher('/rrt/goal', Odometry, queue_size=1)\n\n rospy.loginfo('Driver: start simple_driver')\n while(not rospy.is_shutdown()):\n odo = Odometry()\n odo.header.frame_id = '/odom'\n odo.pose.pose = end\n GOALER.publish(odo)\n rate_limit.sleep()\n if crash_flag:\n \n sys.exit(0)\n rospy.loginfo('Driver: shutdown')\n","sub_path":"src/rrt_driver.py","file_name":"rrt_driver.py","file_ext":"py","file_size_in_byte":6249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"446744432","text":"import bpy\nimport os\nimport math\nimport bpy.utils.previews\n\nfrom bpy.props import (\n StringProperty,\n BoolProperty,\n IntProperty,\n FloatProperty,\n FloatVectorProperty,\n EnumProperty,\n PointerProperty,\n)\n\nfrom . import gp_draw\nfrom . import modifiers\nfrom . import operators\nfrom . import bundles\nfrom . import settings\nfrom .settings import mode_bundle_types, mode_pivot_types\n\nfrom . import addon_updater_ops\n\n\ndef set_path(self, value):\n # checks if the provided path is inside a subdirectory of the current file to save it as a relative path\n if bpy.data.is_saved:\n value = os.path.realpath(bpy.path.abspath(value))\n file_path = os.path.dirname(os.path.realpath(bpy.path.abspath(bpy.data.filepath)))\n if os.path.commonprefix([os.path.realpath(bpy.path.abspath(value)), file_path]) == file_path:\n value = bpy.path.relpath(value)\n\n self.real_path = value\n\n\ndef get_path(self):\n return self.real_path\n\n\ndef get_preset_enum(self, context):\n prefs = context.preferences.addons[__name__.split('.')[0]].preferences\n presets = settings.get_presets(context.scene.BGE_Settings.export_format)\n if context.scene.BGE_Settings.export_format == prefs.export_format and prefs.export_preset in presets.keys():\n index = list(presets.keys()).index(prefs.export_preset)\n enum = settings.create_preset_enum(presets)\n enum[0], enum[index] = enum[index], enum[0]\n return enum\n else:\n enum = settings.create_preset_enum(presets)\n return enum\n\n return []\n\n\nclass BGE_Settings(bpy.types.PropertyGroup):\n real_path: bpy.props.StringProperty(default=\"\")\n path: bpy.props.StringProperty(\n name=\"Output Path\",\n default=\"\",\n description=\"Define the path where to export or import from\",\n subtype='DIR_PATH',\n get=get_path,\n set=set_path\n )\n padding: bpy.props.FloatProperty(\n name=\"Padding\",\n default=0.15,\n min=0,\n description=\"Padding for fences\",\n subtype='DISTANCE'\n )\n bundles: bpy.props.CollectionProperty(\n type=bundles.Bundle\n )\n bundle_index: bpy.props.IntProperty(\n name=\"Bundles\",\n default=False,\n description=\"Bundles\"\n )\n show_bundle_objects: bpy.props.BoolProperty(\n name=\"Show bundle objects\",\n default=True,\n )\n show_bundle_info: bpy.props.BoolProperty(\n name=\"Show bundle info\",\n default=False,\n )\n\n mode_bundle: bpy.props.EnumProperty(items=mode_bundle_types, name=\"Bundle Mode\", default=bpy.context.preferences.addons[__name__.split('.')[0]].preferences.mode_bundle)\n mode_pivot: bpy.props.EnumProperty(items=mode_pivot_types, name=\"Pivot From\", default=bpy.context.preferences.addons[__name__.split('.')[0]].preferences.mode_pivot)\n\n scene_modifiers: bpy.props.PointerProperty(type=modifiers.BGE_modifiers) # sometimes this variable may point to an old version, maybe force reload modules will fix it\n\n export_format: bpy.props.EnumProperty(items=settings.export_formats, default=bpy.context.preferences.addons[__name__.split('.')[0]].preferences.export_format)\n export_preset: bpy.props.EnumProperty(items=get_preset_enum)\n\n\nclass BGE_PT_core_panel(bpy.types.Panel):\n bl_idname = \"BGE_PT_core_panel\"\n bl_label = \"Main Settings\"\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'UI'\n bl_category = \"Bundle Exporter\"\n\n def draw(self, context):\n addon_updater_ops.check_for_update_background()\n addon_updater_ops.update_notice_box_ui(self, context)\n\n layout = self.layout\n box = layout.box()\n #row = box.row(align=True)\n #row.operator('bge.load_preferences', text='', icon='RECOVER_LAST')\n #row.label(text='Settings', icon='PREFERENCES')\n\n col = box.column(align=False)\n\n row = col.row(align=True)\n if context.scene.BGE_Settings.path == \"\":\n row.alert = True\n row.prop(context.scene.BGE_Settings, \"path\", text=\"\")\n if context.scene.BGE_Settings.path != \"\":\n row = row.row(align=True)\n row.operator(\"wm.path_open\", text=\"\", icon='FILE_TICK').filepath = context.scene.BGE_Settings.path\n\n #row = col.split(factor=0.3, align=True)\n col.prop(context.scene.BGE_Settings, \"export_format\", text='Format', icon='FILE_CACHE')\n col.prop(context.scene.BGE_Settings, \"export_preset\", text='Preset', icon='PRESET')\n\n row = col.row(align=True)\n row.prop(context.scene.BGE_Settings, \"mode_bundle\", text=\"Bundle by\")\n row.operator(\"wm.url_open\", text=\"\", icon='QUESTION').url = \"http://renderhjs.net/fbxbundle/#settings_bundle\"\n\n row = col.row(align=True)\n row.prop(context.scene.BGE_Settings, \"mode_pivot\", text=\"Pivot at\", expand=False)\n row.operator(\"wm.url_open\", text=\"\", icon='QUESTION').url = \"http://renderhjs.net/fbxbundle/#settings_pivot\"\n\n col = box.column(align=True)\n\n row = col.row(align=True)\n row.prop(bpy.context.scene.unit_settings, \"system\", text='')\n row.prop(bpy.context.scene.unit_settings, \"scale_length\", text='')\n\n row = col.row(align=True)\n row.prop(context.scene.BGE_Settings, \"padding\", text=\"Padding\", expand=True)\n\n # Warnings\n col.alert = True\n if context.space_data.local_view:\n box = col.box()\n box.label(text=\"Can't export in local view mode.\", icon='CANCEL')\n\n if context.active_object and context.active_object.mode != 'OBJECT':\n box = col.box()\n box.label(text=\"Requires object mode to export.\", icon='CANCEL')\n\n if context.scene.BGE_Settings.path == \"\":\n box = col.box()\n box.label(text=\"No output path defined.\", icon='CANCEL')\n\n elif context.scene.BGE_Settings.mode_bundle == 'COLLECTION' and len(bpy.data.collections) == 0:\n box = col.box()\n box.label(text=\"No groups available\", icon='CANCEL')\n\n\nclass BGE_PT_modifiers_panel(bpy.types.Panel):\n bl_idname = \"BGE_PT_modifiers_panel\"\n bl_label = \"Export Modifiers\"\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'UI'\n bl_category = \"Bundle Exporter\"\n #bl_context = \"objectmode\"\n\n def draw(self, context):\n self.layout.operator_menu_enum(operators.BGE_OT_add_bundle_modifier.bl_idname, 'option')\n modifiers.draw(self.layout, context, bpy.context.scene.BGE_Settings.scene_modifiers, draw_only_active=True)\n\n\nclass BGE_UL_bundles(bpy.types.UIList):\n def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):\n col = layout.column()\n row = col.row()\n icon = 'RESTRICT_SELECT_ON'\n if item.is_bundle_obj_selected():\n icon = 'RESTRICT_SELECT_OFF'\n row.operator(operators.op_bundles.BGE_OT_select.bl_idname, text='', icon=icon).index = index\n row.alert = not item.is_key_valid()\n row.prop(item, 'key', text='', icon=\"FILE_3D\", emboss=False)\n row.label(text='', icon=next(x[3] for x in mode_bundle_types if x[0] == item.mode_bundle))\n row.label(text='', icon=next(x[3] for x in mode_pivot_types if x[0] == item.mode_pivot))\n\n row.operator(operators.op_bundles.BGE_OT_remove.bl_idname, text='', icon='CANCEL').index = index\n\n def invoke(self, context, event):\n pass\n\n\nclass BGE_PT_files_panel(bpy.types.Panel):\n bl_idname = \"BGE_PT_files_panel\"\n bl_label = \"Bundles\"\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'UI'\n bl_category = \"Bundle Exporter\"\n #bl_context = \"objectmode\"\n # bl_options = {'HIDE_HEADER'}\n\n def draw(self, context):\n layout = self.layout\n\n # Get bundles\n bundle_list = bundles.get_bundles()\n selected_bundles = [x for x in bundle_list if x.is_bundle_obj_selected()]\n\n icon = 'EXPORT'\n\n col = layout.column(align=True)\n row = col.row(align=True)\n row.scale_y = 1.2\n row.operator(operators.BGE_OT_fence_draw.bl_idname, text=\"Draw Fences\", icon='AXIS_TOP')\n row.operator(operators.BGE_OT_fence_clear.bl_idname, text=\"\", icon='PANEL_CLOSE')\n\n col.template_list(\"BGE_UL_bundles\", \"\", bpy.context.scene.BGE_Settings, \"bundles\", bpy.context.scene.BGE_Settings, \"bundle_index\", rows=2)\n\n row = col.row(align=True)\n\n split = row.split(factor=0.2, align=True)\n split.scale_y = 1.4\n\n split.operator(operators.BGE_OT_create_bundle.bl_idname, text=\"\", icon='ADD')\n split.operator(operators.BGE_OT_file_export_scene_selected.bl_idname, text=\"Selected ({}x)\".format(len(selected_bundles)), icon=icon)\n split.operator(operators.BGE_OT_file_export.bl_idname, text=\"All ({}x)\".format(len(bundles.get_bundles(only_valid=True))), icon=icon)\n\n bundle_index = bpy.context.scene.BGE_Settings.bundle_index\n\n if bpy.context.scene.BGE_Settings.bundle_index < len(bundle_list) and len(bundle_list) > 0:\n num_objects = len(bundle_list[bundle_index].objects)\n box = layout.box()\n row = box.row(align=True)\n row.prop(\n bpy.context.scene.BGE_Settings,\n 'show_bundle_info',\n icon=\"TRIA_DOWN\" if bpy.context.scene.BGE_Settings.show_bundle_info else \"TRIA_RIGHT\",\n icon_only=True,\n text='',\n emboss=False\n )\n row.label(text=bundle_list[bundle_index].filename, icon='FILE_3D')\n row = row.row()\n row.alignment = 'RIGHT'\n row.operator(operators.op_bundles.BGE_OT_select.bl_idname, emboss=False, text='x{}'.format(num_objects)).index = bundle_index\n row.prop(bundle_list[bundle_index], 'mode_bundle', icon_only=True, text='', emboss=False)\n row.prop(bundle_list[bundle_index], 'mode_pivot', icon_only=True, text='', emboss=False)\n row.operator(operators.BGE_OT_file_export_selected.bl_idname, text=\"Export\", icon=icon)\n if bpy.context.scene.BGE_Settings.show_bundle_info:\n row = box.row()\n row.separator()\n sub_box = row.column(align=True)\n objs = bundle_list[bundle_index].objects\n for x in objs:\n icon = 'OUTLINER_OB_MESH'\n if x.type == 'ARMATURE':\n icon = 'OUTLINER_OB_ARMATURE'\n elif x.type == 'EMPTY':\n icon = 'OUTLINER_OB_EMPTY'\n sub_box.label(text=x.name, icon=icon)\n\n box.operator_menu_enum(operators.BGE_OT_override_bundle_modifier.bl_idname, 'option')\n modifiers.draw(box, context, bundle_list[bundle_index].override_modifiers, draw_only_active=True)\n\n layout.separator()\n\n\naddon_keymaps = []\nclasses = [BGE_Settings, BGE_UL_bundles, BGE_PT_core_panel, BGE_PT_modifiers_panel, BGE_PT_files_panel]\n\n\ndef register():\n print('--> REGISTER_CORE')\n from bpy.utils import register_class\n register_class(bundles.Bundle)\n\n for cls in classes:\n register_class(cls)\n\n bpy.types.Scene.BGE_Settings = bpy.props.PointerProperty(type=BGE_Settings)\n\n\ndef unregister():\n print('### UNREGISTER CORE')\n from bpy.utils import unregister_class\n unregister_class(bundles.Bundle)\n\n for cls in reversed(classes):\n unregister_class(cls)\n\n del bpy.types.Scene.BGE_Settings\n","sub_path":"addons/bundle_exporter/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":11390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"413391475","text":"# A Pulsator is a Black_Hole; it updates as a Black_Hole\r\n# does, but also by growing/shrinking depending on\r\n# whether or not it eats Prey (and removing itself from\r\n# the simulation if its dimension becomes 0), and displays\r\n# as a Black_Hole but with varying dimensions\r\n\r\n\r\nfrom blackhole import Black_Hole\r\nfrom simulton import Simulton\r\nimport model\r\n\r\n\r\nclass Pulsator(Black_Hole):\r\n counter = 30\r\n def __init__(self, x, y):\r\n Black_Hole.__init__(self, x, y)\r\n self._counter = 30\r\n def update(self):\r\n main = []\r\n x_coor = Simulton.get_dimension(self)\r\n if x_coor[0] == 0:\r\n model.removed.add(self)\r\n else:\r\n if self._counter == 0:\r\n Simulton.set_dimension(self, x_coor[0] - 2, x_coor[1] - 2)\r\n self._counter = 30\r\n else:\r\n item = Black_Hole.update(self)\r\n if len(item) == 0:\r\n self._counter -= 1\r\n else:\r\n main += [pa for pa in item]\r\n self._counter = 30\r\n Simulton.set_dimension(self, x_coor[0] + 2, x_coor[1] + 2)\r\n return set(main)","sub_path":"PacMan using Inheritance and GUIs/pulsator.py","file_name":"pulsator.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"544612311","text":"# Copyright (c) 2020 Software AG,\n# Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA,\n# and/or its subsidiaries and/or its affiliates and/or their licensors.\n# Use, reproduction, transfer, publication or disclosure is prohibited except\n# as specifically provided for in your License Agreement with Software AG.\n\nimport uuid\nimport time\nimport threading\n\nfrom c8y_api import CumulocityDeviceRegistry\nfrom c8y_api.app import CumulocityApi\nfrom c8y_api.model import Device\n\n\ndevice_registry = CumulocityDeviceRegistry(\n base_url='https://eu-latest.cumulocity.com',\n tenant_id='management',\n username='devicebootstrap',\n password='Fhdt1bb1f')\n\ndevice_uuid = str(uuid.uuid1())\napi = CumulocityApi()\n\nprint(f\"Creating a device request for ID {device_uuid}.\")\napi.device_inventory.request(device_uuid)\n# the request can be accepted once there was some communication\n# we will do this asynchronously\ndef await_communication_and_accept():\n for i in range(1, 100):\n try:\n api.device_inventory.accept(device_uuid)\n break\n except:\n print(\"Unable to accept device request. Waiting for device communication.\")\n time.sleep(1)\nthreading.Thread(target=await_communication_and_accept).start()\n\ndevice_api = device_registry.await_connection(device_uuid)\nprint(\"Device request accepted.\")\n\nprint(f\"\\nCreating a new device object ...\")\ndevice = Device(c8y=device_api, name=device_uuid, type='TestDevice').create()\nprint(f\"Object created: #{device.id}\")\nprint(f\" Name: {device.name}\")\nprint(f\" Type: {device.type}\")\nprint(f\" Owner: {device.owner}\")\nprint(f\" Fragments: {', '.join(device.fragments.keys())}\")\nprint(f\" Created: {device.creation_time}\")\n\nprint(f\"\\nChecking the device user ...\")\ndevice_user = api.users.get(device.owner)\nprint(f\" Name: {device_user.username}\")\nprint(f\" Roles: {', '.join([str(x) for x in device_user.global_role_ids])}\")\n\nprint(f\"\\nDeleting the device (and user) ...\")\ndevice.delete()\n\nassert len(api.users.get_all(username=device_user.username)) == 0\n","sub_path":"sample/device_registration.py","file_name":"device_registration.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"40575886","text":"\"\"\"\nhttps://leetcode.com/problems/assign-cookies/description/\n\nAssume you are an awesome parent and want to give your children some cookies.\nBut, you should give each child at most one cookie. Each child i has a greed\nfactor gi, which is the minimum size of a cookie that the child will be content\nwith; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j\nto the child i, and the child i will be content. Your goal is to maximize the\nnumber of your content children and output the maximum number.\n\nNote:\n* You may assume the greed factor is always positive.\n* You cannot assign more than one cookie to one child.\n\nExample 1:\nInput: [1,2,3], [1,1]\n\nOutput: 1\n\nExplanation:\n\nYou have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.\nAnd even though you have 2 cookies, since their size is both 1, you could only\nmake the child whose greed factor is 1 content. You need to output 1.\n\nExample 2:\nInput: [1,2], [1,2,3]\n\nOutput: 2\n\nExplanation:\n\nYou have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.\nYou have 3 cookies and their sizes are big enough to gratify all of the\nchildren, You need to output 2.\n\n---\n\ngreeds = [3,2,1]\n\nsizes = [1,1]\n\ngi g si s h | gi' g' si' s' h'\n0 3 0 1 0 1 2 0 1 0\n1 2 0 1 0 | 2 1 1 1 1\n\n\ns < g !happy, will never satisfy child\n\ng >= s happy\n\n\ngreeds = [2, 1]\nsizes = [3, 2, 1]\n\ngi g si s h | gi' g' si' s' h'\n0 2 0 3 0\n\n\"\"\"\n\n\nclass Solution:\n def findContentChildren(self, greeds, sizes):\n \"\"\"\n :type g: List[int]\n :type s: List[int]\n :rtype: int\n \"\"\"\n num_sizes = len(sizes)\n sizes.sort(reverse=True)\n print(sizes)\n\n num_greeds = len(greeds)\n greeds.sort(reverse=True)\n print(greeds)\n\n happy = 0\n\n gi = 0\n si = 0\n\n while gi < num_greeds and si < num_sizes:\n g = greeds[gi]\n s = sizes[si]\n\n if s >= g:\n # size greater or equal than greed\n gi += 1\n si += 1\n happy += 1\n else:\n # will never satisfy child\n gi += 1\n\n return happy\n","sub_path":"leetcode/python/assign_cookies.py","file_name":"assign_cookies.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"359028686","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n\"\"\"\n链长为零和1时,直接返回。\n先把链表挂到dummy上。分配两个指针,一个prev给dummy,另一个current给head。\n两个需要交换的node始终有指针,不会丢链。\n用两个条件current and current.next保护循环,兼顾奇数链和偶数链的情况. 用一个暂时变量postpost保护需要交换的node. \nprev和current逐步前进.\n最后去掉dummy的头,返回。\n\n\"\"\"\nclass Solution:\n # @param a ListNode\n # @return a ListNode\n def swapPairs(self, head):\n if not head or not head.next:\n return head\n prev = dummy = ListNode(-1)\n dummy.next = head\n current = head\n while current and current.next:\n postpost = current.next.next\n current.next.next = current\n prev.next = current.next\n current.next = postpost\n prev = prev.next.next\n current = current.next\n return dummy.next\n","sub_path":"leetcode/Swap Nodes in Pairs.py","file_name":"Swap Nodes in Pairs.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"490815453","text":"#!/usr/bin/env python\n# emit top documents for a topic (in the order the documents appear in source file)\n# topic_weight_for_document primary_id secondary_id topic_text\n \nimport sys\nif len(sys.argv) != 3:\n print >>sys.stderr, \"usage: cat lda.docToTop.txt | %s topic_id documents\" % (sys.argv[0])\n exit(1)\n \nimport re\nfrom heapq import *\nimport docToTop\n\n# which topic are we getting?\ntarget_topic = int(sys.argv[1])\n\n# parse top docs\ntop_docs = [] # ( doc_id, prob of topic )\nfor line in sys.stdin:\n primary_id, secondary_id, topic_probs = docToTop.parse(line)\n for topic, prob in topic_probs:\n if topic == target_topic:\n heappush(top_docs, (-float(prob), primary_id)) # -ve since we want top values in heap\n\n# take top 10\nprimary_ids = set()\nprimary_id_to_prob = {}\nfor i in xrange(0, 10):\n (neg_prob, primary_id) = heappop(top_docs)\n primary_ids.add(primary_id)\n primary_id_to_prob[primary_id] = -neg_prob\n\n# now grep document looking for these 10 ids\nfor line in open(sys.argv[2]):\n primary_id = line.split(\"\\t\")[0]\n if primary_id in primary_ids:\n sys.stdout.write(\"%s\\t%s\" % (primary_id_to_prob[primary_id], line))\n primary_ids.remove(primary_id)\n if len(primary_id)==0:\n exit(0)\n\n\n","sub_path":"bin/top_docs_for_topic.py","file_name":"top_docs_for_topic.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"408690839","text":"import argparse\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nimport supernnova.utils.logging_utils as lu\nfrom supernnova.validation.validate_onthefly import classify_lcs\n\n\"\"\"\n Example code on how to run on the fly classifications\n - Need to laod a pre-trained model\n - Either provide a list with data or a Pandas DataFrame\n\"\"\"\n\n# Data columns to provide\n# HOSTGAL redshifts only required if classification with redshift is used\nCOLUMN_NAMES = [\n \"SNID\",\n \"MJD\",\n \"FLUXCAL\",\n \"FLUXCALERR\",\n \"FLT\",\n \"HOSTGAL_PHOTOZ\",\n \"HOSTGAL_SPECZ\",\n \"HOSTGAL_PHOTOZ_ERR\",\n \"HOSTGAL_SPECZ_ERR\",\n]\n\n\ndef manual_lc():\n \"\"\"Manually provide data\n \"\"\"\n # this is the format you can use to provide light-curves\n df = pd.DataFrame()\n # supernova IDs\n df[\"SNID\"] = [\"1\", \"1\", \"2\", \"2\"]\n # time in MJD\n df[\"MJD\"] = [57433.4816, 57436.4815, 33444, 33454]\n # FLux and errors\n df[\"FLUXCAL\"] = [2.0, 3, 200, 300]\n df[\"FLUXCALERR\"] = [0.1, 0.2, 0.1, 0.2]\n # bandpasses\n df[\"FLT\"] = [\"g\", \"r\", \"g\", \"r\"]\n # redshift is not required if classifying without it\n df[\"HOSTGAL_SPECZ\"] = [0.12, 0.12, 0.5, 0.5]\n df[\"HOSTGAL_PHOTOZ\"] = [0.1, 0.1, 0.5, 0.5]\n df[\"HOSTGAL_SPECZ_ERR\"] = [0.001, 0.001, 0.001, 0.001]\n df[\"HOSTGAL_PHOTOZ_ERR\"] = [0.01, 0.01, 0.01, 0.01]\n\n return df\n\n\ndef load_lc_csv(filename):\n \"\"\"Read light-curve(s) in csv format\n\n Args:\n filename (str): data file\n \"\"\"\n df = pd.read_csv(filename)\n\n missing_cols = [k for k in COLUMN_NAMES if k not in df.keys()]\n lu.print_red(f\"Missing {len(missing_cols)} columns\", missing_cols)\n lu.print_yellow(f\"filling with zeros\")\n lu.print_yellow(f\"HOSTGAL required only for classification with redshift\")\n for k in missing_cols:\n df[k] = np.zeros(len(df))\n df = df.sort_values(by=[\"MJD\"])\n df[\"SNID\"] = df[\"SNID\"].astype(int).astype(str)\n\n return df\n\n\ndef reformat_to_df(pred_probs, ids=None):\n \"\"\" Reformat SNN predictions to a DataFrame\n\n # TO DO: suppport nb_inference != 1\n \"\"\"\n num_inference_samples = 1\n\n d_series = {}\n for i in range(pred_probs[0].shape[1]):\n d_series[\"SNID\"] = []\n d_series[f\"prob_class{i}\"] = []\n for idx, value in enumerate(pred_probs):\n d_series[\"SNID\"] += [ids[idx]] if len(ids) > 0 else idx\n value = value.reshape((num_inference_samples, -1))\n value_dim = value.shape[1]\n for i in range(value_dim):\n d_series[f\"prob_class{i}\"].append(value[:, i][0])\n preds_df = pd.DataFrame.from_dict(d_series)\n\n # get predicted class\n preds_df[\"pred_class\"] = np.argmax(pred_probs, axis=-1).reshape(-1)\n\n return preds_df\n\n\nif __name__ == \"__main__\":\n \"\"\" Wrapper to get predictions on the fly with SNN\n\n \"\"\"\n\n parser = argparse.ArgumentParser(\n description=\"Classification using pre-trained model\"\n )\n parser.add_argument(\n \"--model_file\",\n type=str,\n default=\"tests/onthefly_model/vanilla_S_0_CLF_2_R_none_photometry_DF_1.0_N_global_lstm_32x2_0.05_128_True_mean.pt\",\n help=\"path to pre-trained SuperNNova model\",\n )\n parser.add_argument(\n \"--device\", type=str, default=\"cpu\", help=\"device to be used [cuda,cpu]\"\n )\n parser.add_argument(\n \"--filename\",\n type=str,\n default=\"tests/onthefly_lc/example_lc.csv\",\n help=\"device to be used [cuda,cpu]\",\n )\n\n args = parser.parse_args()\n\n # Input data\n # options: csv or manual data, choose one\n # df = load_lc_csv(args.filename)\n df = manual_lc()\n\n # Obtain predictions for full light-curve\n # Format: batch, nb_inference_samples, nb_classes\n # Beware, ids are resorted while obtaining predictions!\n ids_preds, pred_probs = classify_lcs(df, args.model_file, args.device)\n\n # ________________________\n # Optional\n #\n # reformat to df\n preds_df = reformat_to_df(pred_probs, ids=df.SNID.unique())\n preds_df.to_csv(f\"Predictions_{Path(args.filename).name}\")\n\n # To implement\n # Early prediction visualization\n","sub_path":"run_onthefly.py","file_name":"run_onthefly.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"75651266","text":"\"\"\" Clarke & Wright savings heuristic sfor the VRP \"\"\"\n\nimport copy\nfrom vrppd_objects import Node, Edge, Route, Solution\nimport math\nimport operator\nimport networkx as nx\n#import matplotlib.pyplot as plt\nimport random\n\n\"\"\" Read instance data fromm txt file \"\"\"\n\nclass HeuristicSequential:\n # Fields\n # instanceName\n # vehCap\n # nodes\n # depot\n # savingsList\n # sol \n\n def __init__(self, instanceName, vehCap, nodeMatrix):\n self.instanceName=instanceName\n self.vehCap = vehCap\n self.nodes = []\n for nodeData in nodeMatrix:\n # array data with node data: ID, x, y, demand, supply\n self.nodes.append(Node(nodeData[0], nodeData[1], nodeData[2], nodeData[3], nodeData[4]))\n\n def runCWSSolGeneral(self, beta = 0.0):\n self.sol = Solution()\n if beta == 0.0:\n self.constructEdges(self.nodes)\n self.constructDummySolution(self.nodes)\n self.edgeSelectionRoutingMerging(self.savingsList)\n else:\n self.constructEdges(self.nodes)\n self.constructDummySolution(self.nodes)\n biasedList = self.generateBiasedSavingsList(beta)\n self.edgeSelectionRoutingMerging(biasedList)\n\n def runCWSSol(self):\n self.sol = Solution()\n self.constructEdges(self.nodes)\n self.constructDummySolution(self.nodes)\n self.edgeSelectionRoutingMerging(self.savingsList)\n\n def runRandomSol(self, beta=0.3):\n self.sol = Solution()\n self.constructEdges(self.nodes)\n self.constructDummySolution(self.nodes)\n biasedList = self.generateBiasedSavingsList(beta)\n self.edgeSelectionRoutingMerging(biasedList)\n\n def generateBiasedSavingsList(self, beta):\n copySavings = self.savingsList.copy()\n biasedSavings = []\n for i in range(len(copySavings)):\n index = int(math.log(random.random()) / math.log(1 - beta) )\n index = index % len(copySavings)\n biasedSavings.append(copySavings[index])\n copySavings.pop(index)\n return biasedSavings\n\n def constructEdges(self, nodes):\n \"\"\" Construct edges with costs and savings list from self.nodes \"\"\"\n self.depot = nodes[0] # node 0 is self.depot\n\n for node in nodes[1:]: # excludes the self.depot\n dnEdge = Edge(self.depot, node) # creates the (self.depot, node) edge (arc)\n ndEdge = Edge(node, self.depot)\n dnEdge.invEdge = ndEdge # sets the inverse edge (arc)\n ndEdge.invEdge = dnEdge\n # compute the Euclidean distance as cost\n dnEdge.cost = math.sqrt((node.x - self.depot.x)**2 + (node.y - self.depot.y)**2)\n ndEdge.cost = dnEdge.cost # assume symmetric costs\n\n # save in node a reference to the (self.depot, node) edge (arc)\n node.dnEdge = dnEdge\n node.ndEdge = ndEdge\n\n self.savingsList = []\n for i in range(1, len(nodes) - 1): # excludes the self.depot\n iNode = nodes[i]\n for j in range(i + 1, len(nodes)):\n jNode = nodes[j]\n ijEdge = Edge(iNode, jNode) # creates the (i, j) edge\n jiEdge = Edge(jNode, iNode)\n ijEdge.invEdge = jiEdge # sets the inverse edge (arc)\n jiEdge.invEdge = ijEdge\n # compute the Euclidean distance as cost\n ijEdge.cost = math.sqrt((jNode.x - iNode.x)**2 + (jNode.y - iNode.y)**2)\n jiEdge.cost = ijEdge.cost # assume symmetric costs\n\n #Data need to take into account number of packages needed at destination\n ijEdge.demandRequired = iNode.demand + jNode.demand\n ijEdge.supplyGiven = iNode.supply + jNode.supply\n jiEdge.demandRequired = 0.0 # back to depot\n jiEdge.supplyGiven = 0.0 # back to depot\n\n # compute savings as proposed by Clark & Wright\n ijEdge.savings = iNode.ndEdge.cost + jNode.dnEdge.cost -ijEdge.cost\n jiEdge.savings = ijEdge.savings\n # save one edge in savings list\n self.savingsList.append(ijEdge)\n # sort the list of edges from higher to lower savings\n self.savingsList.sort(key = operator.attrgetter(\"savings\"), reverse = True)\n\n def constructDummySolution(self, nodes):\n \"\"\" Construct the dummy solution \"\"\"\n\n for node in nodes[1:]: # excludes the self.depot\n dnEdge = node.dnEdge # get the(self.depot, node) edge\n ndEdge = node.ndEdge\n dndRoute = Route(self.vehCap) # construct the route (self.depot, node, self.depot)\n dndRoute.addEdge(dnEdge)\n dndRoute.addEdge(ndEdge)\n # Demand now refers to how many packages contains the vehicle\n # Vehicle will continue until can't serve any more nodes without refilling at depot.\n node.inRoute = dndRoute # save in node a reference to its current route\n node.isInterior = False # this node is currently exterior (connected to self.depot)\n self.sol.routes.append(dndRoute) # add this route to the solution\n self.sol.cost += dndRoute.cost\n\n def checkMergingConditions(self, iNode, jNode, iRoute, jRoute):\n # condition 1 : iRoute and jRoute are not the same route object\n if iRoute == jRoute:\n return False\n # conditions 2: both nodes are exterior nodes in their respective routes\n if iNode.isInterior or jNode.isInterior:\n return False\n # condition 3: demand after merging can be covered by a single vehicle\n # This means that the vehicle still has the right number of\n # packages to pickup and deliver to other nodes before resetting at depot.\n if iRoute.to_serve - jNode.demand < 0 or iRoute.to_pick - jRoute.to_pick < 0:\n return False\n # else, merging is feasible\n return True\n\n def getDepotEdge(self, aRoute, aNode):\n ''' returns the edge in aRoute that contains aNode and the depot \n (it will be the first or the last one) '''\n # check if first edge in aRoute contains aNode and self.depot\n origin = aRoute.edges[0].origin\n end = aRoute.edges[0].end\n if ((origin == aNode and end == self.depot) or\n (origin == self.depot and end == aNode)):\n return aRoute.edges[0]\n else: # return last edge in aRoute\n return aRoute.edges[-1]\n\n def edgeSelectionRoutingMerging(self, savingsList):\n \"\"\" Perform the edge-selection & routing-merging iterative process \"\"\"\n while len(savingsList) > 0: # list is not empty\n ijEdge = savingsList.pop(0) # select the next edge from the list\n # determine the nodes i < j that define the edge\n iNode = ijEdge.origin\n jNode = ijEdge.end\n # determine the routes associated with each node\n iRoute = iNode.inRoute\n jRoute = jNode.inRoute\n # check if merge is possible\n isMergeFeasible = self.checkMergingConditions(iNode, jNode, iRoute, jRoute)\n # if all necessary coditions are satisfied, merge\n if isMergeFeasible == True:\n # iRoute will contain either edge (self.depot, 1) or edge (1, self.depot)\n iEdge = self.getDepotEdge(iRoute, iNode) # iEdge is either (0,1) or (1,0)\n # remove iEdge from iRoute and update iRoute cost\n iRoute.removeEdge(iEdge)\n # if there are multiple edges in iRoute, then i will be interior\n if len(iRoute.edges) > 1: iNode.isInterior = True\n # if new iRoute does not start at 0 it must be reversed\n if iRoute.edges[0].origin != self.depot: iRoute.reverse()\n # jRoute will contain either edge (self.depot, j) or edge (j, self.depot)\n jEdge = self.getDepotEdge(jRoute, jNode) # jEdge is either (0, j) or (j,0)\n # remove jEdge from jRoute and update jRoute cost\n jRoute.removeEdge(jEdge)\n # if there are multiple edges in jRute, the j will be interior\n if len(jRoute.edges) > 1: jNode.isInterior = True\n # if new jRoute starts at 0 it must be reverse()\n if jRoute.edges[0].origin == self.depot : jRoute.reverse()\n # add ijEdge to iRoute\n iRoute.addEdge(ijEdge)\n jNode.inRoute = iRoute\n # add jRoute to new iRoute\n for edge in jRoute.edges:\n iRoute.addEdge(edge)\n iRoute.to_serve += edge.end.demand\n edge.end.inRoute = iRoute\n # delete jRoute from emerging solution\n self.sol.cost -= ijEdge.savings\n self.sol.routes.remove(jRoute)\n\n def getCost(self):\n return self.sol.cost\n\n def printCost(self):\n print('Instance: '+ self.instanceName)\n print('Cost of C&W savings sol=', \"{:{}f}\".format(self.sol.cost, 2))\n\n def printRoute(self, route):\n s = str(0)\n for edge in route.edges:\n s = s + '-' + str(edge.end.ID)\n print('Route: ' + s + ' || cost = ' + \"{:{}f}\".format(route.cost,2))\n\n def printRouteCosts(self):\n print('Instance: '+ self.instanceName)\n for route in self.sol.routes:\n s = str(0)\n for edge in route.edges:\n s = s + '-' + str(edge.end.ID)\n print('Route: ' + s + ' || cost = ' + \"{:{}f}\".format(route.cost,2))\n\n def printRouteCostsBestSolution(self, sol):\n print('Instance: '+ self.instanceName)\n for route in sol.routes:\n s = str(0)\n for edge in route.edges:\n s = s + '-' + str(edge.end.ID)\n print('Route: ' + s + ' || cost = ' + \"{:{}f}\".format(route.cost,2))\n print( \"Solution cost = \" + \"{:{}f}\".format(sol.cost,2))\n\n def getSolution(self):\n return self.sol\n\n def plotGraph(self):\n G = nx.Graph()\n fnode = self.sol.routes[0].edges[0].origin\n G.add_node(fnode.ID, coord=(fnode.x, fnode.y))\n coord = nx.get_node_attributes(G, 'coord')\n #fig, ax = plt.subplots() #Add axes\n #nx.draw_networkx(G, coord, node_size = 60, node_color='white', ax = ax)\n #nx.draw_networkx(G, coord)\n\n #plt.title('Instance: '+ self.instanceName)\n\n j=0\n for route in self.sol.routes:\n #Assign random colors in RGB\n c1 = int(random.uniform(0, 255)) if (j%3 == 2) else (j%3)*int(random.uniform(0, 255))\n c2 = int(random.uniform(0, 255)) if ((j+1)%3 == 2) else ((j+1)%3)*int(random.uniform(0, 255))\n c3 = int(random.uniform(0, 255)) if ((j+2)%3 == 2) else ((j+2)%3)*int(random.uniform(0, 255))\n for edge in route.edges:\n G.add_edge(edge.origin.ID, edge.end.ID)\n G.add_node(edge.end.ID, coord=(edge.end.x, edge.end.y))\n coord = nx.get_node_attributes(G, 'coord')\n nx.draw_networkx_nodes(G, coord, node_size = 60, node_color='white', ax=ax)\n nx.draw_networkx_edges(G, coord, edge_color='#%02x%02x%02x' % (c1,c2,c3))\n nx.draw_networkx_labels(G, coord, font_size = 9)\n G.remove_node(edge.origin.ID)\n j +=1\n #limits=plt.axis('on') #Turn on axes)\n #ax.tick_params(left=True, bottom =True, labelleft=True, labelbottom=True)\n #plt.show()\n\n\n\n\n\n\n","sub_path":"cwsheuristic_vrppd.py","file_name":"cwsheuristic_vrppd.py","file_ext":"py","file_size_in_byte":11589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"322557479","text":"from importlib import import_module\nfrom full_cost import settings\nfrom copy import deepcopy\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required, permission_required\nfrom django.contrib.auth.models import AnonymousUser\nfrom django.utils.decorators import method_decorator\nfrom django.forms import ModelForm\nfrom django.forms import ValidationError\nfrom django.views import View\nfrom django.db.models import Q, QuerySet\nfrom post_office import mail\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom pathlib import Path\nfrom full_cost.utils.filter_stuff import filterset_factory_extra\nfrom django_tables2.config import RequestConfig\nfrom full_cost.utils.facturing import generate_xlsx, create_extraction\nfrom django_tables2.export.export import TableExport\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\nfrom lab.models import User, Extraction\nfrom lab.filters import ProjectFilter, ExtractDisplayFilter, ExtractFilterAll, ExtractFilterForm, FilterSet\nfrom lab.tables import ProjectTable, RecordTableFull, ExtractionTable, RecordTable\nfrom lab.forms import ExtractionForm\nfrom full_cost.utils.constants import ACTIVITIES, BILLINGS, get_activities_from_entity, get_subbillings_from_entity_short\nfrom full_cost.utils.ldap import LDAP\nfrom full_cost.utils.url_stuff import get_field_from_url\nfrom .models import Record, Group\n\nactivity_short = Path(__file__).parts[-2]\nactivity_long = 'CEMES Laboratory'\nactivity={'short': activity_short, 'long': activity_long}\n\n\nclass Index(View):\n activity = activity\n logged = False\n def get(self, request):\n return render(request, 'lab/index.html', {'logged': self.logged,\n 'user': request.user, 'activity': self.activity, })\n\nclass FilterRecord(View):\n extract = False\n thanks = False\n filter_class = None\n table_class = None\n activity = activity\n\n def get(self, request):\n filter = self.filter_class(request.GET)\n table = self.table_class(filter.qs)\n RequestConfig(request).configure(table)\n return render(request, f\"lab/filter_table.html\",\n {'activity': self.activity, 'filter': filter, 'table': table,\n 'export': self.extract, 'thanks': self.thanks})\n\nclass Projects(View):\n filter_class = ProjectFilter\n table_class = ProjectTable\n activity = activity\n\n def get(self, request):\n filt = self.filter_class(request.GET)\n table = self.table_class(filt.qs)\n RequestConfig(request).configure(table)\n return render(request, f\"lab/filter_table.html\",\n {'activity': self.activity, 'filter': filt, 'table': table, })\n\nclass Export(View):\n table_class = RecordTableFull\n activity = activity\n\n def get(self, request):\n table = self.table_class(self.table_class._meta.model.objects.all())\n RequestConfig(request).configure(table)\n export_format = \"xlsx\"\n if TableExport.is_valid_format(export_format):\n exporter = TableExport(export_format, table)\n return exporter.response(f\"{self.activity['short']}.{export_format}\")\n return render(request, f\"{self.activity['short']}/filter_table.html\",\n {'activity': self.activity, 'export': True})\n\nclass GetRecord(View):\n form_class = ModelForm #to subclass by the appropriate class\n record_class = Record\n activity = activity\n\n def response(self, request, form):\n return render(request, \"lab/record.html\",\n {'activity': self.activity, 'form': form})\n\n def validate_record(self, record, form):\n \"\"\"to be subclassed\"\"\"\n validate_state = True\n return form, validate_state #for date range based records: manage_time.check_range_in_range_2_sessions(r, self.record_class, form)\n\n def populate_record(self, data):\n \"\"\"to be eventually subclassed\"\"\"\n # populate a new record\n #billing field should be populated depending on each activity cases (so in subclasses)\n record = self.record_class()\n for key in data:\n if hasattr(self.record_class, key):\n setattr(record, key, data[key])\n\n return record\n\n def check_user(self, data):\n if data['user'].user_last_name == \"OTHER\":\n user = User(user_first_name=data['user_text_name'].capitalize(),\n user_last_name=data['user_text_surname'].upper())\n user.save()\n data['user'] = user\n return data\n\n def get_group(self, user):\n lgroup = None\n ldap = LDAP()\n group = ldap.get_group_ldap(user)\n if group is not None:\n g = Group.objects.filter(group__iexact=group['short'])\n if not g.exists():\n lgroup = Group(group=group['short'].upper(), description=group['long'])\n lgroup.save()\n else:\n lgroup = g[0]\n return lgroup\n\n def get(self, request):\n user = None\n lgroup = None\n project = None\n\n if not isinstance(request.user, AnonymousUser):\n user_qs = User.objects.filter(user_last_name__iexact=request.user.last_name)\n if user_qs.exists():\n user = user_qs[0]\n lgroup = user.group\n if lgroup is None:\n try:\n lgroup = self.get_group(request.user)\n except:\n pass\n user.group = lgroup\n user.save()\n\n else: #add this logged user to the database\n lgroup = self.get_group(request.user)\n u = User(user_last_name=request.user.last_name, user_first_name=request.user.first_name, group = lgroup)\n u.save()\n\n\n ini_dict = {'project': project, 'user': user, 'group': lgroup}\n form = self.form_class_init(request, **ini_dict)\n\n return self.response(request, form)\n\n def form_class_init(self,request, **kwargs):\n \"\"\"\n to subclass\n Parameters\n ----------\n kwargs\n\n Returns\n -------\n\n \"\"\"\n return self.form_class(initial=kwargs)\n\n def post(self, request, *args, **kwargs):\n form = self.form_class(request.POST)\n if form.is_valid():\n data = form.cleaned_data\n data = self.check_user(data)\n\n if form.is_valid():\n # populate a new record\n record = self.populate_record(data)\n\n #automatic attribution of the billing entry from ATIVITIES constant\n\n if record.experiment.exp_type in ACTIVITIES[self.activity['short']]['related_entities']:\n record.billing = ACTIVITIES[self.activity['short']]['related_entities'][record.experiment.exp_type]\n\n # check if this record is compatible with existing records or other issue\n form, valid_state = self.validate_record(record, form)\n\n if form.is_valid() and valid_state:\n # save it to database\n record.save()\n # redirect to a new URL:\n return HttpResponseRedirect(reverse(f\"{self.activity['short']}:thanks\"))\n\n return self.response(request, form)\n\n@method_decorator(login_required, name='dispatch')\n@method_decorator(permission_required(f'lab.add_extraction', raise_exception=True), name='dispatch')\nclass ExtractRecordAll(View):\n filter_class = []\n table_class = RecordTable\n activity = activity\n\n\n def extra_filtration_of_records(self, qs):\n \"\"\"to be subclassed to filter out some records that cannot be extracted, for instance HF2000 for MET\"\"\"\n return qs\n\n def set_filter(self, activities):\n self.filter_class = []\n self.table_class = []\n for act in activities:\n try:\n module = import_module(f\"{act}\")\n ##self.filter_class.append(deepcopy(ExtractFilterAll))\n self.filter_class.append(filterset_factory_extra(module.models.Record, ('billing', 'date_from', 'project'),FilterSet, ExtractFilterForm))\n self.table_class.append(module.tables.RecordTable)\n except ModuleNotFoundError:\n pass #activity defined in constants.py but not yet as a django app\n\n\n def get(self, request):\n entity_previous = None\n url_previous = request.META.get('HTTP_REFERER')\n if url_previous is not None:\n entity_previous = get_field_from_url(url_previous, 'billing')\n\n entity = request.GET.get('billing')\n full_dates = True\n if entity is None:\n entity = 'SPECTRO'\n elif entity == entity_previous:\n full_dates = False\n\n activities = get_activities_from_entity(entity)\n self.set_filter(activities)\n\n\n\n filters = []\n dates_min = []\n dates_max = []\n for ind, filter in enumerate(self.filter_class):\n filters.append(filter(request.GET))\n\n if full_dates:\n module = import_module(f\"{activities[ind]}\")\n sub_billings = get_subbillings_from_entity_short(entity)\n req = Q()\n for sub in sub_billings:\n req = req | Q(experiment__exp_type=sub)\n qs = module.models.Record.objects.filter(req, extraction=None, )\n if qs.exists():\n dates_min.append(qs.earliest('date_from').date_from)\n dates_max.append(qs.latest('date_from').date_from)\n\n if full_dates and dates_min != []:\n filters = []\n date_min = min(dates_min)\n date_max = max(dates_max)\n for filter in self.filter_class:\n filters.append(filter(data={'billing': entity, 'date_from_after': date_min, 'date_from_before': date_max}, request=request.GET))\n\n filter = filters[0]\n\n tables = []\n qss = []\n for ind, filter in enumerate(filters):\n sub_billings = get_subbillings_from_entity_short(entity)\n req = Q()\n for sub in sub_billings:\n req = req | Q(experiment__exp_type=sub)\n qs = filter.qs.filter(req, extraction=None, )\n # if not qs.exists():\n # filters[0].form.add_error('project', ValidationError(('No records to extract'), code='project_error'))\n tables.append(self.table_class[ind](qs))\n qss.append(qs)\n RequestConfig(request).configure(tables[-1])\n\n export = False\n if filter.form.is_valid() and len(request.GET) != 0:\n if 'project' not in request.GET:\n filter.form.add_error('project', ValidationError(('Pick one project to extract from'), code='project_error'))\n elif request.GET['project'] == '':\n filter.form.add_error('project', ValidationError(('Pick one project to extract from'), code='project_error'))\n if 'date_from_before' not in request.GET:\n filter.form.add_error('date_from', ValidationError(('Select dates to extract from'), code='date_error'))\n elif request.GET['date_from_before'] == '':\n filter.form.add_error('date_from', ValidationError(('Select dates to extract from'), code='date_error'))\n\n if 'date_from_after' not in request.GET:\n filter.form.add_error('date_from', ValidationError(('Select dates to extract from'), code='date_error'))\n elif request.GET['date_from_after'] == '':\n filter.form.add_error('date_from', ValidationError(('Select dates to extract from'), code='date_error'))\n\n if filter.form.is_valid():\n export = True\n\n if filter.form.is_valid() and '_export' in request.GET:\n\n\n\n project = filter.form.cleaned_data['project']\n ext = create_extraction(entity, qss, project, filter)\n\n return redirect('lab:fextract_entity_id', entity=entity, id=ext.creation_id, thanks='true')\n\n\n return render(request, f\"{self.activity['short']}/filter_table_lab.html\",\n {'activity': self.activity, 'filter': filter, 'tables':tables, 'activities': activities, 'export':export})\n\n@method_decorator(login_required, name='dispatch')\n@method_decorator(permission_required(f'lab.view_extraction', raise_exception=True), name='dispatch')\nclass ShowSetExtractionAll(View):\n form_class = ExtractionForm\n filter_class = ExtractDisplayFilter\n table_class = ExtractionTable\n activity = activity\n\n def response(self, request, table, form, filter, thanks='', ext=None):\n if thanks == '':\n thanks = False\n else:\n thanks = True\n modification = request.user.has_perm('lab.change_extraction')\n if ext is not None:\n submitting = request.user.has_perm('lab.delete_extraction') and not ext.submitted\n else:\n submitting = request.user.has_perm('lab.delete_extraction')\n return render(request, \"lab/filtered_extractions.html\",\n {'activity': self.activity, 'filter': filter, 'table': table, 'form': form,\n 'thanks': thanks, 'modification': modification, 'submitting': submitting})\n\n\n def set_as_factured(self, ext, factured=True):\n if ext.factured != factured:\n ext.factured = factured\n ext.save()\n p = ext.project\n if factured:\n p.amount_left -= ext.amount\n else:\n p.amount_left += ext.amount\n p.save()\n\n def delete(self, ext):\n if ext.factured:\n self.set_as_factured(ext, False)\n ext.delete()\n\n def submit(self, ext, user):\n \"\"\"\n Extraction(project=project,\n date_after=filter.form.cleaned_data['date_from'].start,\n date_before=filter.form.cleaned_data['date_from'].stop,\n creation_id=ext_id, amount=total, billing=entity)\n\n \"\"\"\n #get pi email\n project = ext.project\n pi = ext.project.project_pi\n ldap = LDAP()\n email_pi = ldap.get_user_info_last_name(pi.user_last_name)['mail'][0].decode()\n\n ext.submitted = True\n ext.save()\n\n try:\n # send email to admin\n mail.send([settings.EMAIL_FROM_EMAIL, 'gestionnaires@cemes.fr', 'sebastien.weber@cemes.fr', email_pi],\n email_pi,\n subject='FULL cost test: An extraction has been submitted',\n message=(f'Hello,\\nThe extraction {ext.billing}-{ext.creation_id:03d} has been made on the project: '\n f'{ext.project} by {user.last_name} {user.first_name}.\\n'\n f'The PI of this project is {pi} belonging to the {pi.group} group\\n'\n f'Please log in to process it:\\n'\n f'http://full-cost.cemes.fr/lab/fextractions/\\n'\n f'Thanks\\n\\nThe full cost administrator!'\n\n ),\n priority='now',\n )\n except:\n pass\n\n def post(self, request, entity=None, id=-1, thanks=''):\n form = self.form_class(request.POST)\n if form.is_valid():\n ext = form.cleaned_data['extractions']\n if 'factured' in request.POST:\n self.set_as_factured(ext, factured=True)\n\n elif 'unfactured' in request.POST:\n self.set_as_factured(ext, factured=False)\n\n elif 'download' in request.POST:\n response = generate_xlsx(ext)\n return response\n\n elif 'delete' in request.POST:\n self.delete(ext)\n\n elif 'submit' in request.POST:\n self.submit(ext, request.user)\n\n filter = self.filter_class(request.GET) # get all objects from the filter model\n table = self.table_class(filter.qs)\n RequestConfig(request).configure(table)\n\n return self.response(request, table, form, filter, ext=ext)\n\n def get(self, request, entity=None, id=-1, thanks=''):\n filter = self.filter_class(request.GET) # get all objects from the filter model\n\n table = self.table_class(filter.qs)\n RequestConfig(request).configure(table)\n if entity is not None and id != -1:\n ext = Extraction.objects.filter(creation_id=id, billing=entity)\n if ext.exists():\n form =self.form_class(initial={'extractions' : ext[0]})\n else:\n form = self.form_class()\n else:\n form = self.form_class()\n\n\n return self.response(request, table, form, filter, thanks)\n\nclass LoadExperiments(View):\n \"\"\"view used to modify dynamically the content of the field experiment in the record form.\n The ajax call to this view is configured within the dedicated javascript file, see static\"\"\"\n def set_experiments(self, request):\n \"\"\"to subclass\"\"\"\n experiments = QuerySet()\n return experiments\n\n def get(self, request):\n experiments = self.set_experiments(request)\n return render(request, 'lab/experiments.html', {'experiments': experiments})\n\nclass LoadSessions(View):\n \"\"\"view used to modify dynamically the content of the field time_to or time_from in the record form.\n The ajax call to this view is configured within the dedicated javascript file, see static\"\"\"\n def set_sessions(self, request):\n \"\"\"to subclass\"\"\"\n sessions = QuerySet()\n return sessions\n\n def get(self, request):\n sessions = self.set_sessions(request)\n return render(request, 'lab/sessions.html', {'sessions': sessions})\n\nclass LoadHTMLData(View):\n \"\"\"view used to modify dynamically the content of a given field in the record form.\n The ajax call to this view is configured within the dedicated javascript file, see static\"\"\"\n template = 'lab/subhtml.html'\n\n def set_values(self, request):\n \"\"\"to subclass\"\"\"\n values = QuerySet()\n return values\n\n def get(self, request):\n values = self.set_values(request)\n return render(request, self.template, {'values': values})","sub_path":"lab/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":18449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"554597768","text":"from rest_framework import viewsets, pagination\n\nfrom dashboard.models import Equipment\nfrom dashboard.serializers import EquipmentSerializer\n\n\nclass MyPagination(pagination.LimitOffsetPagination):\n page_size = 20\n page_size_query_param = 'page_size'\n max_page_size = 50\n\n\nclass EquipmentViewSet(viewsets.ModelViewSet):\n serializer_class = EquipmentSerializer\n queryset = Equipment.objects.all().reverse()\n pagination_class = MyPagination\n","sub_path":"dashboard/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"446998762","text":"import re\n\nclass ListIntoLists:\n\n def split_list_by_regex(input_list):\n regex_pattern = \"\\d\\d:\\d\\d\"\n output_list = []\n temp_list = [\"Header\"]\n for l in input_list:\n if re.match(regex_pattern, l):\n output_list.append(temp_list)\n temp_list = []\n temp_list.append(l)\n output_list.append(temp_list)\n print(output_list)\n\n if __name__ == \"__main__\":\n orig_list = [\"beer\", \"more\", \"09:30\", \"lager\", \"10:20\", \"stout\", \"evil\", \"04:40\", \"boo\", \"radley\"]\n split_list_by_regex(orig_list)\n","sub_path":"ListIntoLists.py","file_name":"ListIntoLists.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"436502451","text":"# -*- coding: utf-8 -*-\n\nimport matplotlib.pyplot as plt\n\n\nfrom matplotlib.colors import ListedColormap\n\n\nN = 4\nreinas = []\nopciones = ['Limpiar', 'Agregar reina', 'Eliminar reina']\ncolumnas = [chr(i) for i in range(ord('A'), ord('A')+N)]\nfilas = [str(i) for i in range(1, N+1)]\ncolores = ['Ivory', 'Wheat', 'Gold', 'FireBrick']\nsolver = []\ninicio = []\n\nprint (\"\")\n\ndef maneja_reinas(reinas, acc, fil, col):\n conflicto = False\n victoria = False\n\n reina = (fil, col)\n\n if acc == 'Limpiar':\n reinas = []\n elif acc == 'Agregar reina':\n if reina not in reinas:\n reinas.append(reina)\n else:\n reinas.remove(reina)\n else:\n if reina in reinas:\n reinas.remove(reina)\n else:\n reinas.append(reina)\n\n # iniciar el tablero como libre\n tablero = [[1 for i in xrange(N)] for i in xrange(N)]\n\n # marcar los campos amenazados\n for x, y in reinas:\n for i in range(N):\n if i != y:\n tablero[x][i] = 2\n if i != x:\n tablero[i][y] = 2\n for i in range(-min(x, y), min(N-x, N-y)):\n if i != 0:\n tablero[x+i][y+i] = 2\n for i in range(max(-x, y-N+1), min(N-x, y+1)):\n if i != 0:\n tablero[x+i][y-i] = 2\n\n # marcar cada reina e informar si es amenazada\n for x, y in reinas:\n if (tablero[x][y] == 2):\n conflicto = True\n tablero[x][y] = 4\n else:\n tablero[x][y] = 3\n\n # verificar la condicion de exito\n if not conflicto and len(reinas) == N:\n victoria = True\n \n return victoria, tablero\n\n\ndef prepara_imagen(tablero, ax):\n img = ax.matshow(tablero, extent=(0, N, 0, N), origin='lower',\n vmin=1, vmax=4, interpolation='none', aspect=1,\n cmap=ListedColormap(colores, 'indexed'))\n\n ax.xaxis.tick_bottom()\n\n ax.xaxis.set_ticks(range(0, N), minor=False)\n ax.xaxis.set_ticklabels([], minor=False)\n ax.xaxis.set_ticks([0.5+i for i in xrange(0, N)], minor=True)\n ax.xaxis.set_ticklabels(columnas, minor=True)\n\n ax.yaxis.set_ticks(range(0, N), minor=False)\n ax.yaxis.set_ticklabels([], minor=False)\n ax.yaxis.set_ticks([0.5+i for i in xrange(0, N)], minor=True)\n ax.yaxis.set_ticklabels(filas, minor=True)\n\n ax.tick_params(axis='both', which='both', length=0)\n ax.grid(color='Gold', linestyle='-', linewidth=1)\n for spine in ax.spines.values():\n spine.set_edgecolor('Gold')\n spine.set_linewidth(3)\n\n return img\n\n\ndef onclose(event):\n global fin\n fig.canvas.stop_event_loop()\n plt.close()\n fin = True\n \n\ndef solver(N):\n \n \n\n \n for i in range(N):\n for j in range(N):\n \n vic, tab = maneja_reinas(reinas, 'Agregar reina', i, j)\n img_reinas.set_data(tab)\n plt.draw()\n plt.ginput()\n if vic:\n fig.text(\n 0.5, 0.5, 'Felicitaciones!', color='orange', size='xx-large',\n family='humor sans', ha='center', va='center', alpha=0.5,\n bbox=dict(facecolor='ivory', edgecolor='orange', boxstyle='round')\n \n )\n plt.draw()\n plt.ginput() \n \n if tab[i][j]==4:\n \n if i in range(N) and j in range(N):\n vic, tab = maneja_reinas(reinas, 'Agregar reina', i, j)\n j=j+1\n print (\"{}{}\".format(i,j))\n \n \n\nif __name__ == \"__main__\":\n plt.ioff()\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n fig.canvas.mpl_connect('close_event', onclose)\n\n (f, c) = ('', '')\n fin, tab = maneja_reinas(reinas, 'Limpiar', f, c)\n img_reinas = prepara_imagen(tab, ax)\n plt.draw()\n\n fin = False\n vic = False\n \n while not fin and not vic:\n \n \n solver(N)\n\n\n \n","sub_path":"Tareas/tarea2.py","file_name":"tarea2.py","file_ext":"py","file_size_in_byte":4106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"419962958","text":"import pandas as pd\nimport numpy as np\nfrom data_params import Data\nfrom pathlib import Path\nimport itertools\nfrom sklearn.metrics import confusion_matrix\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf')\nimport seaborn as sns\n\n\ndef plot_confusion_matrix(\n cm, classes, name, normalize=False, title=\"Confusion matrix\", cmap=plt.cm.Greens\n):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n\n if normalize:\n cm = cm.astype(\"float\") / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print(\"Confusion matrix, without normalization\")\n\n print(cm)\n fig = plt.figure()\n ax = fig.add_subplot(111)\n plt.imshow(cm, interpolation=\"nearest\", cmap=cmap)\n # plt.colorbar(labelsize=16)\n cb = plt.colorbar()\n cb.ax.tick_params(labelsize=16)\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45, fontsize=16)\n plt.yticks(tick_marks, classes, fontsize=16)\n\n fmt = \".2f\" if normalize else \"d\"\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(\n j,\n i,\n format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n fontsize=16,\n color=\"white\" if cm[i, j] > thresh else \"black\",\n )\n\n plt.tight_layout()\n plt.title(title, fontsize=24)\n plt.ylabel(\"Actual Outcome\", fontsize=20)\n plt.xlabel(\"Predicted Outcome\", fontsize=20)\n\n # ax.set_title(title,fontsize= 30) # title of plot\n # ax.set_xlabel(\"Actual Outcome\",fontsize = 20) #xlabel\n # ax.set_ylabel(\"Actual Outcome\", fontsize = 20)#ylabel\n\n # return plt\n np.set_printoptions(precision=2)\n fig.savefig(name, dpi=300, bbox_inches=\"tight\")\n\n return None\n\n\n\ndef print_confusion_matrix(confusion_matrix, class_names, figsize = (8, 5.5), fontsize=14):\n \"\"\"Prints a confusion matrix, as returned by sklearn.metrics.confusion_matrix, as a heatmap.\n\n Arguments\n ---------\n confusion_matrix: numpy.ndarray\n The numpy.ndarray object returned from a call to sklearn.metrics.confusion_matrix.\n Similarly constructed ndarrays can also be used.\n class_names: list\n An ordered list of class names, in the order they index the given confusion matrix.\n figsize: tuple\n A 2-long tuple, the first value determining the horizontal size of the ouputted figure,\n the second determining the vertical size. Defaults to (10,7).\n fontsize: int\n Font size for axes labels. Defaults to 14.\n\n Returns\n -------\n matplotlib.figure.Figure\n The resulting confusion matrix figure\n \"\"\"\n\n # fig_dpi = 400\n # fig_size = (8, 5.5)\n # plt.figure(figsize=fig_size)\n #\n # ax = sns.heatmap(result_precision, annot=True, fmt=\".4f\", cmap=\"Greens_r\", square=True)\n # ax.set(xlabel=\"L2 / ridge = 0 Penalty L1 / lasso = 1\")\n # ax.set(ylabel=\"Regualization (alpha = 1/C)\")\n # fig = ax.get_figure()\n # fig.savefig(\"conf_matrix.png\", dpi=fig_dpi)\n # plt.close()\n\n\n df_cm = pd.DataFrame(\n confusion_matrix, index=class_names, columns=class_names,\n )\n fig = plt.figure(figsize=figsize)\n plt.rcParams['font.family'] = 'sans-serif'\n plt.rcParams['font.sans-serif'] = 'Arial'\n plt.rcParams['mathtext.it'] = 'Arial:italic'\n plt.rcParams['mathtext.bf'] = 'Arial:bold'\n plt.rcParams['mathtext.rm'] = 'Arial'\n try:\n heatmap = sns.heatmap(df_cm, annot=True, fmt=\"d\", cmap=\"Greens\", square=True, annot_kws={\"size\": 20})\n except ValueError:\n raise ValueError(\"Confusion matrix values must be integers.\")\n heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=90, ha='right', fontsize=fontsize)\n heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=0, fontsize=fontsize)\n # plt.ylabel('True outcome', fontsize=16)\n # plt.xlabel('Predicted outcome', fontsize=16)\n plt.xlabel(r\"$\\mathbf{Predicted\\ outcome}$\", fontsize=16)\n plt.ylabel(r\"$\\mathbf{True\\ outcome}$\", fontsize=16)\n fig = heatmap.get_figure()\n fig.savefig(\"conf_matrix_.png\", dpi=400)\n plt.close()\n return None\n\n\n\ndata_par = Data()\ndir_to_saved_data = data_par.dir_to_saved_data\n\n\npath_to_scores = Path(dir_to_saved_data, \"cv_results_.csv\")\ndf_scores = pd.read_csv(path_to_scores)\ndf_scores = df_scores[[\"param_clf__alpha\", \"param_clf__l1_ratio\", \"mean_test_accuracy\", \"std_test_accuracy\", \"mean_test_precision\", \"std_test_precision\"]]\ndf_scores\nresult_precision = df_scores.copy()\nresult_accuracy = df_scores.copy()\nresult_precision = result_precision.pivot(index='param_clf__alpha', columns='param_clf__l1_ratio', values='mean_test_precision')\nresult_accuracy = result_accuracy.pivot(index='param_clf__alpha', columns='param_clf__l1_ratio', values='mean_test_accuracy')\n\n\npath_to_responses = Path(dir_to_saved_data, \"y_test_y_pred.csv\")\ndf_responses = pd.read_csv(path_to_responses)\nprint(df_responses.head())\nclasses = [\"not funded\", \"funded\"]\nconf_mat = confusion_matrix(df_responses[\"test\"], df_responses[\"pred\"])\n\n# hyperparamter grid search heatmap for precision\nfig_dpi = 400\nfig_size = (8, 5.5)\nplt.figure(figsize=fig_size)\nplt.rcParams['font.family'] = 'sans-serif'\nplt.rcParams['font.sans-serif'] = 'Arial'\nplt.rcParams['mathtext.fontset'] = 'custom'\nplt.rcParams['mathtext.it'] = 'Arial:italic'\nplt.rcParams['mathtext.bf'] = 'Arial:bold'\nplt.rcParams['mathtext.rm'] = 'Arial'\nax = sns.heatmap(result_precision, annot=True, fmt=\".4f\", cmap=\"Greens_r\", square=True)\n# ax.set(xlabel=\"L2 / ridge = 0 Penalty L1 / lasso = 1\")\n# ax.set(ylabel=\"Regualization (alpha = 1/C)\")\nplt.xlabel(\"L2 / ridge = 0 \" + r\"$\\mathbf{Penalty}$\" + \" L1 / lasso = 1\", fontsize=16)\nplt.ylabel(r\"$\\mathbf{Regularization\\ multiplier}$\" + \" (\" + r\"$\\alpha$\" + \")\", fontsize=16)\nfig = ax.get_figure()\nfig.savefig(\"hyperparameter_heatmap_precision.png\", dpi=fig_dpi)\nplt.close()\n\n# confusion matrix\nprint_confusion_matrix(conf_mat, classes, figsize=(8,5.5), fontsize=14)\n","sub_path":"cv_results_heatmap.py","file_name":"cv_results_heatmap.py","file_ext":"py","file_size_in_byte":6236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"11064336","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\nimport math\nfrom . import helper\nfrom .models import *\n\n\n# Create your views here.\n\n\ndef courses(request):\n courses = Course.objects.all()\n args = {\n 'courses': courses,\n }\n return render(request, 'course_lesson/courses.html', context=args)\n\n\ndef course(request, course_queue):\n try:\n course = Course.objects.get(queue_number=course_queue)\n modules = Module.objects.filter(course_id=course.id).order_by('queue_number')\n teachers = Teacher.objects.filter(lessons__module__course_id=course.id)\n\n args = {\n 'course': course,\n 'modules': modules,\n 'teachers': teachers,\n\n }\n return render(request, 'course_lesson/course.html', context=args)\n except Course.DoesNotExist:\n return HttpResponse(helper.page_not_found('course', course_queue))\n\n\ndef lesson(request, course_queue, module_queue, lesson_queue):\n try:\n course = Course.objects.get(queue_number=course_queue)\n module = Module.objects.get(course_id=course.id, queue_number=module_queue)\n lesson = Lesson.objects.get(module_id=module.id, queue_number=lesson_queue)\n try:\n next_lesson = Lesson.objects.get(module_id=module.id, queue_number=lesson_queue+1)\n except Lesson.DoesNotExist:\n next_lesson = None\n# might be empty:\n resources = Resource.objects.filter(lesson_id=lesson.id)\n lessons_from_module = Lesson.objects.filter(module_id=module.id).order_by('queue_number')\n\n args = {\n 'lesson': lesson,\n 'module': module,\n 'resources': resources,\n 'lessons_from_module': lessons_from_module,\n 'next_lesson': next_lesson,\n }\n return render(request, 'course_lesson/lesson.html', context=args)\n except Course.DoesNotExist:\n return HttpResponse(helper.page_not_found('course', course_queue))\n except Module.DoesNotExist:\n return HttpResponse(helper.page_not_found('module', module_queue))\n except Lesson.DoesNotExist:\n return HttpResponse(helper.page_not_found('lesson', lesson_queue))\n\n\ndef course_end(request, course_id):\n return render(request, 'course_lesson/course_end.html')\n","sub_path":"course_lesson/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"356502385","text":"import bisect\n\n\nclass Solution:\n def countRectangles(self, rectangles, points):\n d = {}\n for x, y in rectangles:\n if y not in d:\n d[y] = []\n d[y].append(x)\n for k in d:\n d[k].sort()\n a = sorted(d.keys())\n n = len(a)\n res = []\n for x, y in points:\n iy = bisect.bisect_left(a, y)\n v = 0\n for j in range(iy, n):\n k = a[j]\n ix = bisect.bisect_left(d[k], x)\n v += len(d[k]) - ix\n res.append(v)\n return res\n\n\ns = Solution()\nprint(s.countRectangles([[1, 2], [2, 3], [2, 5]], [[2, 1], [1, 4]]))\n","sub_path":"leetcode/2022/contest/weekly-290/Contest3.py","file_name":"Contest3.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"519286655","text":"from condition.bottom import bottom_bc\r\nfrom condition.decorator import formula, Result\r\nfrom condition.down_func import *\r\nfrom condition.support import have_in_day, fall_rate\r\nfrom tdx.func import *\r\nfrom tdx.index import *\r\n\r\n\r\n@formula\r\ndef down_lonely(ctx=None):\r\n res = Result(True)\r\n # # 如果快三线拐头向下,就不考虑\r\n # if turn_down():\r\n # return False\r\n # 必须站上安全线才行\r\n if get_count() > 60 and get_close() < get_ma60():\r\n return False\r\n if not down_lonely_hit():\r\n down_t = BARSLAST(down_lonely_hit, limit=8)\r\n if 0 < down_t <= 8:\r\n res.comments.append(\"缩量大跌ref=%d\" % down_t)\r\n pass\r\n else:\r\n return False\r\n else:\r\n down_t = 0\r\n\r\n jc_t = BARSLAST(cross_macd)\r\n # 如果当天大跌,日线底背驰可以在今天也可以在前几天\r\n if down_t == 0:\r\n if bottom_bc():\r\n res.bull.append(\"同时日线底背驰\")\r\n return res\r\n if jc_t < 8 and REF(bottom_bc, jc_t):\r\n res.comments.append(\"%d日前日线底背驰\" % jc_t)\r\n return res\r\n # 从大跌,包括大跌当天,到现在也没有出现过分钟底背驰\r\n result = have_in_day(bottom_bc, down_t, [\"60min\", \"30min\", \"15min\", \"5min\", ])\r\n if result:\r\n res.comments.append(\"分钟底背驰:\" + result)\r\n return res\r\n else:\r\n # 如果没有底背驰,只有一种情况符合,macd零轴上红\r\n if get_macd() > 0 and REF(get_dif, BARSLAST(cross_macd)) > 0:\r\n res.bear.append(\"缺少底背驰,明天必须新低才考虑\")\r\n return res\r\n # 如果不是当天大跌,底背驰必须在其后\r\n else:\r\n if bottom_bc():\r\n res.bull.append(\"今天日线底背驰\")\r\n return res\r\n # 如果自从缩量下跌已经涨了10个点,就不考虑了\r\n if get_close() / REF(get_close, down_t) > 1.1:\r\n return False\r\n # 涨停板带来的分钟底背驰,失去时效性\r\n if is_ztb():\r\n return False\r\n if down_t <= 1:\r\n result = have_in_day(bottom_bc, down_t, [\"60min\", \"30min\", \"15min\", \"5min\", ])\r\n else:\r\n result = have_in_day(bottom_bc, down_t, [\"60min\", \"30min\", \"15min\", ])\r\n if result:\r\n res.comments.append(\"今天分钟底背驰:\" + result)\r\n return res\r\n return False\r\n\r\n\r\n@formula\r\ndef down(ctx=None):\r\n \"\"\"\r\n 根据传入的g.ENV判断当前情况是否符合condition\r\n :param env: 可选,一般传入时为bottom_bc单元测试\r\n :return: True/False\r\n 典型例子:\r\n \"\"\"\r\n res = Result(True)\r\n\r\n if not qt():\r\n return False\r\n if not ma10hc_hit():\r\n down_t = BARSLAST(ma10hc_hit, limit=10)\r\n if 0 < down_t <= 8:\r\n res.comments.append(\"缩量大跌ref=%d\" % down_t)\r\n pass\r\n else:\r\n return False\r\n else:\r\n down_t = 0\r\n\r\n jc_t = BARSLAST(cross_macd)\r\n # 如果当天大跌,日线底背驰可以在今天也可以在前几天\r\n if down_t == 0:\r\n if bottom_bc():\r\n res.bull.append(\"同时日线底背驰\")\r\n return res\r\n if jc_t < 5 and REF(bottom_bc, jc_t):\r\n res.comments.append(\"%d日前日线底背驰\" % jc_t)\r\n return res\r\n result = have_in_day(bottom_bc, 0, [\"60min\", \"30min\", \"15min\", ])\r\n if result:\r\n res.comments.append(\"分钟底背驰:\" + result)\r\n return res\r\n # 如果不是当天大跌,底背驰必须在其后\r\n else:\r\n if bottom_bc():\r\n res.bull.append(\"今天日线底背驰\")\r\n return res\r\n # 如果自从缩量下跌已经涨了10个点,就不考虑了\r\n if get_close() / REF(get_close, down_t) > 1.1:\r\n return False\r\n # 涨停板带来的分钟底背驰,失去时效性\r\n if is_ztb():\r\n return False\r\n if jc_t <= 8 and REF(bottom_bc, jc_t):\r\n res.comments.append(\"%d日前日线底背驰\" % jc_t)\r\n return res\r\n result = have_in_day(bottom_bc, 0, [\"60min\", \"30min\", \"15min\", ])\r\n if result:\r\n res.comments.append(\"今天分钟底背驰:\" + result)\r\n return res\r\n\r\n return False\r\n\r\n\r\ndef lack_of_slump():\r\n return False\r\n # todo\r\n ma5_turn_str = \"get_ma5()>REF(get_ma5,1) and REF(get_ma5,1) 0\", ma5_turn_t):\r\n high_t, high = FINDHIGH('max(get_close(),get_open())', 0, ma5_turn_t)\r\n _, start = FINDLOW('min(get_close(),get_open())', high_t, ma5_turn_t - high_t)\r\n _, low = FINDLOW('min(get_close(),get_open())', 0, high_t)\r\n\r\n 回调幅度 = (high - low) / (high - start)\r\n # 回调应该在1/3至2/3\r\n if 回调幅度 < 1 / 3:\r\n return True\r\n return False\r\n\r\n\r\ndef qt():\r\n if lack_of_slump():\r\n return False\r\n if COUNT(is_ztb, 20) == 0:\r\n return False\r\n # if COUNT(拉板出货, 7) > 0:\r\n # return False\r\n return True\r\n\r\n\r\ndef wxsx():\r\n sx = get_count() > 120 and get_ma60() < get_ma120() and (\r\n get_ma5() < get_ma10() < get_ma20() or\r\n # ma5在ma10和ma20之下\r\n (get_ma5() < REF(get_ma5, 1) and get_ma10() < REF(get_ma10, 1) and get_ma20() < REF(get_ma20, 1))\r\n )\r\n if sx:\r\n return True\r\n 被压制 = get_close() < min(get_ma10(), get_ma20(), get_ma60(), get_ma120())\r\n\r\n # 恒康医疗20181026,被5线压制,且ma5上升速度小于ma10上升速度\r\n if 被压制 and (REF(get_ma10, 1) - get_ma10()) > (get_ma5() - REF(get_ma5, 1)):\r\n return True\r\n 冷气带 = max(get_ma5(), get_ma10(), get_ma20()) < get_ma60() < get_ma120() < REF(get_ma120, 1) \\\r\n and get_ma60() < REF(get_ma60, 1) \\\r\n and get_close() < min(get_ma60(), get_ma120())\r\n\r\n if 冷气带:\r\n if get_ma20() > REF(get_ma20, 1) and min(get_ma5(), get_ma10()) > get_ma20():\r\n return False\r\n\r\n if (get_ma10() - REF(get_ma10, 1) + get_ma5() - REF(get_ma5, 1) + get_ma20() - REF(get_ma20, 1)) < 0:\r\n return True\r\n return False\r\n\r\n\r\ndef slump_hit():\r\n \"\"\"\r\n 大跌,但是要缩量\r\n :return:\r\n \"\"\"\r\n # 缩量 + 至少下跌5.5个点\r\n s1 = get_vol() < min(get_vol5(), get_vol10()) and get_close() / REF(get_close, 1) < 0.945\r\n if not s1:\r\n return False\r\n s2 = get_low() < get_ma10()\r\n if not s2:\r\n return False\r\n # {一字跌停的不要}\r\n s3 = not (is_dtb() and get_low() == get_high())\r\n if not s3:\r\n return False\r\n return True\r\n\r\n\r\ndef ma10hc_hit():\r\n # 如果不跌够3个点,就不算大跌\r\n if get_close() / REF(get_close, 1) >= 0.97:\r\n return False\r\n if not get_ma5() > get_ma10():\r\n return False\r\n if is_dtb():\r\n return False\r\n # 1. k线碰了MA10\r\n # 2.\r\n h1 = get_low() / get_ma10() < 1 or (get_low() / get_ma20() < 1 and\r\n REF(\"get_close() > get_ma20()\", 1))\r\n if not h1:\r\n return False\r\n # 因为今天下跌,如果放量下跌就不考虑\r\n if get_vol() > max(get_vol5(), get_vol10()):\r\n return False\r\n high_t, high = FINDHIGH(get_close, 0, 5, 1)\r\n h3 = REF(\"get_close() > get_ma5() and get_close() > get_ma10() and \"\r\n \"(get_ma5() > REF(get_ma5, 1) or get_ma10() > REF(get_ma10, 1))\"\r\n , high_t)\r\n if not h3:\r\n return False\r\n h5 = HHV(get_high, high_t + 1) / get_close() > 1.05\r\n if not h5:\r\n return False\r\n # {跌破MA5的那一天必须是缩量的}\r\n h7 = COUNT(\"CROSS(get_ma5, get_close) and get_vol() > max(get_vol5(), get_vol10()) * 1\", high_t) == 0\r\n if not h7:\r\n return False\r\n return True\r\n\r\n\r\n@formula\r\ndef slump(ctx=None):\r\n \"\"\"\r\n 根据传入的g.ENV判断当前情况是否符合condition\r\n :param env: 可选,一般传入时为bottom_bc单元测试\r\n :return: True/False\r\n 典型例子:\r\n \"\"\"\r\n res = Result(True)\r\n if turn_down():\r\n return False\r\n # if COUNT(拉板出货, 3) > 0:\r\n # return False\r\n # 前提是不能五线顺下,除非是次新\r\n if wxsx():\r\n return False\r\n\r\n if not slump_hit():\r\n down_t = BARSLAST(slump_hit, limit=10)\r\n if 0 < down_t < 8:\r\n res.comments.append(\"缩量大跌ref=%d\" % down_t)\r\n pass\r\n else:\r\n return False\r\n else:\r\n down_t = 0\r\n # {跌破MA5的那一天必须是缩量的}\r\n rcross_ma5_t = 0\r\n if not CROSS(get_ma5, get_close):\r\n rcross_ma5_t = BARSLAST(\"CROSS(get_ma5,get_close)\")\r\n if REF(\"get_vol() > max(get_vol5(), get_vol10()) * 0.97\",\r\n rcross_ma5_t):\r\n return False\r\n jc_t = BARSLAST(cross_macd)\r\n # 如果当天大跌,日线底背驰可以在今天也可以在前几天\r\n if down_t == 0:\r\n if bottom_bc():\r\n # 底背驰后的涨幅如果很高,不考虑\r\n if get_close() / LLV(get_close, 6) < 1.15:\r\n res.comments.append(\"同时日线底背驰\")\r\n return res\r\n if jc_t < 8 and REF(bottom_bc, jc_t) and fall_rate(jc_t + 1) > 1 / 3:\r\n res.comments.append(\"%d日前日线底背驰\" % jc_t)\r\n return res\r\n result = 分钟底背驰_均线安全_首次出现(down_t)\r\n if result:\r\n res.comments.append(\"分钟底背驰:\" + result)\r\n return res\r\n # 如果不是当天大跌,底背驰必须在其后\r\n else:\r\n # 当天底背驰\r\n if bottom_bc():\r\n # 底背驰后的涨幅如果很高,不考虑\r\n if get_close() / LLV(get_close, 6) < 1.15:\r\n res.bull.append(\"今天日线底背驰\")\r\n return res\r\n # 如果自从缩量下跌已经涨了10个点,就不考虑了\r\n if get_close() / REF(get_close, down_t) > 1.1:\r\n return False\r\n # 涨停板带来的分钟底背驰,失去时效性\r\n if is_ztb():\r\n return False\r\n\r\n result = 分钟底背驰_均线安全_首次出现(0)\r\n if result:\r\n res.comments.append(\"今天分钟底背驰:\" + result)\r\n return res\r\n\r\n return False\r\n","sub_path":"condition/down.py","file_name":"down.py","file_ext":"py","file_size_in_byte":10599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"124329031","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def getTargetCopy(self, original, cloned, target):\n \"\"\"\n :type original: TreeNode\n :type cloned: TreeNode\n :type target: TreeNode\n :rtype: TreeNode\n \"\"\"\n '''\n Preorder traversal\n '''\n # if original==None:\n # return None\n # if original.val==target.val:\n # return cloned\n\n # res=self.getTargetCopy(original.left,cloned.left,target)\n # if res != None:\n # return res\n \n # res=self.getTargetCopy(original.right,cloned.right,target)\n\n # if res!=None:\n # return res\n # return None\n\n\n #########BFS\n stack = []\n clonedstack = []\n node=original\n clonet = cloned\n\n while node != None or len(stack)!=0:\n if node !=None:\n if node.val == target.val:\n return clonet\n stack.append(node)\n node=node.left\n clonedstack.append(clonet)\n clonet=clonet.left\n else:\n node=stack.pop(0)\n node=node.right\n clonet=clonedstack.pop(0)\n clonet=clonet.right\n\n return None\n\n","sub_path":"Tree/test_1379.py","file_name":"test_1379.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"439443008","text":"import psycopg2\nfrom psycopg2 import OperationalError\n\n\ndef create_connection(db_name, db_user, db_password, db_host, db_port):\n connection = None\n try:\n connection = psycopg2.connect(\n database=db_name,\n user=db_user,\n password=db_password,\n host=db_host,\n port=db_port,\n )\n print(\"Connection to PostgreSQL DB successful\")\n except OperationalError as e:\n print(f\"The error '{e}' occurred\")\n return connection\n\n\nconnection = create_connection(\"eca\", '', '', \"127.0.0.1\", '5432')\n\n\ndef create_database(connection, query):\n connection.autocommit = True\n cursor = connection.cursor()\n try:\n cursor.execute(query)\n print(\"Query executed successfully\")\n except OperationalError as e:\n print(f\"The error '{e}' occurred\")\n\n# create_database_query = \"CREATE DATABASE eca\"\n# create_database(connection, create_database_query)\n\n\ndef execute_query(connection, query):\n connection.autocommit = True\n cursor = connection.cursor()\n try:\n cursor.execute(query)\n print(\"Query executed successfully\")\n except OperationalError as e:\n print(f\"The error '{e}' occurred\")\n\n\nadd_table = \"\"\"\nCREATE TABLE IF NOT EXISTS \"E-Learning\" (\n id SERIAL PRIMARY KEY,\n first TEXT NOT NULL,\n last TEXT NOT NULL,\n school TEXT NOT NULL,\n course TEXT NOT NULL,\n email TEXT,\n address TEXT,\n rep TEXT,\n invoice_number TEXT,\n start_date TEXT,\n amount TEXT\n)\n\"\"\"\n# execute_query(connection, add_table)\n","sub_path":"database/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"245888160","text":"from compressibleflow import *\n\nT1 = 470\nP1 = 500\nv1 = 180\nA1 = 0.05\nair = Air(T1,P1)\n\nM1 = air.mach_number(v1)\nT0 = air.stagnation_temp(M1)\nP0 = air.stagnation_pressure(M1)\n\nr_start = air.diameter(A1)/2\n\nA_star = air.throat_area(A1, air.mach_number(v1))\nr_star = air.diameter(A_star)/2\nm_star = air.m_dot(v1,air.diameter(A1))\n\narea = 0.036\n\nratio = air.throat_area_ratio(area,A1, M1)\n\nMa_upward = air.ma_finder(\"upward\", ratio,True,method=\"golden\")\nMa_downward = air.ma_finder(\"downward\", ratio, True)\n\nT_upward = air.temperature(Ma_upward,T0)\nT_downward = air.temperature(Ma_downward,T0)\n\nP_upward = air.pressure(Ma_upward,P0)\nP_downward = air.pressure(Ma_downward,P0)\n\nexit_p = air.exit_pressure(M1)\n\nair.plot(0.5*A1, A1,M1,'Ma','T')","sub_path":"Fluid_Mechanics_White_7th/white_9_4.py","file_name":"white_9_4.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"505330293","text":"\"\"\"\nTest JSON Patch\n\"\"\"\n\nfrom django.core.urlresolvers import reverse\nfrom rest_framework_json_patch import mixins\nfrom rest_framework import serializers, viewsets\nfrom tests import models\nimport json\nimport pytest\n\npytestmark = pytest.mark.django_db\n\n\nclass TestViewSet(mixins.JsonPatchMixin, viewsets.ModelViewSet):\n model = models.TestModel\n\n\nclass NestedSerializer(serializers.ModelSerializer):\n\n class Meta:\n fields = (\"name\", \"children\", )\n model = models.FullNested\n\n\nclass NestedViewSet(mixins.JsonPatchMixin, viewsets.ModelViewSet):\n model = models.FullNested\n serializer_class = NestedSerializer\n\n\nview = TestViewSet.as_view({\"patch\": \"partial_update\"})\nnested_view = NestedViewSet.as_view({\"patch\": \"partial_update\"})\n\n\ndef test_invalid_data(rf):\n obj = models.TestModel.objects.create(something=\"test\", other=\"test\")\n\n data = json.dumps({\n \"invalid\": \"data\",\n })\n result_data = {\n \"detail\": \"The patch must be supplied as a list\",\n }\n\n request = rf.patch(\n \"testing\",\n data=data,\n content_type=\"application/json\",\n )\n\n response = view(request, pk=obj.pk)\n response.render()\n\n assert response.status_code == 400\n assert response.data == result_data\n\n\ndef test_invalid_operation(rf):\n obj = models.TestModel.objects.create(something=\"test\", other=\"test\")\n\n data = json.dumps([{\n \"op\": \"invalid\",\n }])\n result_data = {\n \"detail\": \"Unknown operation 'invalid'\",\n }\n\n request = rf.patch(\n \"testing\",\n data=data,\n content_type=\"application/json\",\n )\n\n response = view(request, pk=obj.pk)\n response.render()\n\n assert response.status_code == 400\n assert response.data == result_data\n\n\ndef test_replace(rf):\n obj = models.TestModel.objects.create(something=\"test\", other=\"test\")\n\n data = json.dumps([{\n \"op\": \"replace\",\n \"path\": \"/something\",\n \"value\": \"other\"\n }])\n result_data = {\n \"id\": obj.pk,\n \"other\": \"test\",\n \"something\": \"other\",\n }\n\n request = rf.patch(\n \"testing\",\n data=data,\n content_type=\"application/json\",\n )\n\n response = view(request, pk=obj.pk)\n response.render()\n\n assert response.status_code == 200\n assert response.data == result_data\n\n\ndef test_copy(rf):\n obj = models.TestModel.objects.create(something=\"initial\", other=\"test\")\n\n data = json.dumps([{\n \"op\": \"copy\",\n \"path\": \"/other\",\n \"from\": \"/something\"\n }])\n result_data = {\n \"id\": obj.pk,\n \"other\": \"initial\",\n \"something\": \"initial\",\n }\n\n request = rf.patch(\n \"testing\",\n data=data,\n content_type=\"application/json\",\n )\n\n response = view(request, pk=obj.pk)\n response.render()\n\n assert response.status_code == 200\n assert response.data == result_data\n\n\ndef test_add(rf):\n obj = models.FullNested.objects.create(name=\"test\")\n nested = models.ChildNested.objects.create(title=\"test\")\n\n data = json.dumps([{\n \"op\": \"add\",\n \"path\": \"/children\",\n \"value\": [nested.pk],\n }])\n result_data = {\n \"name\": \"test\",\n \"children\": [nested.pk],\n }\n\n request = rf.patch(\n \"testing\",\n data=data,\n content_type=\"application/json\",\n )\n\n response = nested_view(request, pk=obj.pk)\n response.render()\n\n assert response.status_code == 200\n assert response.data == result_data\n\n\ndef test_remove(rf):\n obj = models.FullNested.objects.create(name=\"test\")\n nested = models.ChildNested.objects.create(title=\"test\")\n obj.children.add(nested)\n\n data = json.dumps([{\n \"op\": \"remove\",\n \"path\": \"/children\",\n \"value\": [nested.pk],\n }])\n result_data = {\n \"name\": \"test\",\n \"children\": [],\n }\n\n request = rf.patch(\n \"testing\",\n data=data,\n content_type=\"application/json\",\n )\n\n response = nested_view(request, pk=obj.pk)\n response.render()\n\n assert response.status_code == 200\n assert response.data == result_data\n","sub_path":"tests/test_patch.py","file_name":"test_patch.py","file_ext":"py","file_size_in_byte":4101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"406210960","text":"n1 = input()\n\nnf = \"./\" + n1\n\nfil = open(nf , 'r').readlines()\n\nfor i in range(len(fil)):\n fil[i] = fil[i].lower()\n\n if i != len(fil) - 1:\n fil[i] = fil[i].replace(\"\\n\", \"\")\n\n\nbook_name = []\nbook = []\n\nfor order in fil:\n bk = order.split(\",\")\n\n cur = \"\"\n cur = bk[0]\n\n req = 0\n req = int(bk[1])\n\n if cur not in book_name:\n book_name.append(cur)\n book.append([cur, req])\n\n else:\n for i in range(len(book)):\n if book[i][0] == cur:\n book[i][1] += req\n\n\nbook_name.sort()\n# print(book_name)\n\nfor i in range(len(book_name)):\n cur = \"\"\n cur = book_name[i] + \",\"\n\n tot = 0\n for ii in range(len(book)):\n if book_name[i] == book[ii][0]:\n tot = book[ii][1]\n\n cur += str(tot)\n\n print(cur)\n","sub_path":"HW3/1147.py","file_name":"1147.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"262396837","text":"from core.exceptions import (ModuleNotFoundError, ClassNotFoundError,\n AppNotFoundError)\n\ndef get_class(module_label, classname):\n if '.' not in module_label:\n raise ValueError(\n \"Importing from top-level modules is not supported\")\n label = \"apps.%s\" % module_label\n module = _import_module(label, classname)\n\n return _pluck_classes(module, classname)\n \n\n\ndef _import_module(module_label, classname):\n try:\n return __import__(module_label, classname)\n except ImportError:\n __, __, exc_traceback = sys.exc_info()\n frames = traceback.extract_tb(exc_traceback)\n if len(frames) > 1:\n raise\n\n\ndef _pluck_classes(module, classname):\n klasses = None\n if hasattr(module, classname):\n klass = getattr(module, classname)\n if not klass:\n raise ClassNotFoundError(\"No class '%s' found in %s\" % (\n module))\n return klasses\n\n\n\n","sub_path":"core/loading.py","file_name":"loading.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"244841214","text":"#-------------------------------------------------------------------------------\n# Name: module1\n# Purpose:\n#\n# Author: owner\n#\n# Created: 29/10/2013\n# Copyright: (c) owner 2013\n# Licence: \n#-------------------------------------------------------------------------------\n#!/usr/bin/env python\n\nimport sys, os\nsys.path = [os.path.abspath(os.path.dirname(__file__))] + sys.path\n\nimport unittest\nimport string\nimport random\nimport shutil\nimport hashlib\nimport shutil_rmtree\nimport posixpath\nimport glob\n\nimport exe_wrapper\nimport git_exceptions\nimport custom_path\n\ndef random_string(size=6, chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for x in range(size))\n\ndef make_random_file(in_folder):\n if not os.path.exists(in_folder):\n os.makedirs(in_folder)\n file_name = \"F_{}\".format(random_string(chars=\"ABCDEFGH\"))\n file_path = os.path.join(in_folder, file_name)\n if os.path.exists(file_path):\n return make_random_file(in_folder)\n with open(file_path, mode=\"w\") as f:\n f.write(random_string(size=64))\n return os.path.abspath(file_path)\n\ndef make_random_dir(in_folder):\n folder_path = os.path.join(in_folder, \"D_{}\".format(random_string(chars=\"ABCDEFGH\")))\n if os.path.exists(folder_path):\n return make_random_dir(in_folder)\n os.makedirs(folder_path)\n return os.path.abspath(folder_path)\n\ndef file_hash(f, blocksize=65536):\n hasher = hashlib.sha1()\n with open(f, 'rb') as afile:\n buf = afile.read(blocksize)\n while len(buf) > 0:\n hasher.update(buf)\n buf = afile.read(blocksize)\n return hasher.hexdigest()\n\ndef repos_are_identical(list_of_repos):\n l = os.listdir(list_of_repos[0].full_path)\n p = set()\n p.add(list_of_repos[0].full_path)\n for r in list_of_repos[1:]:\n p.add(r.full_path)\n l += os.listdir(r.full_path)\n l = set(l)\n l.remove(\".git\")\n for x in l:\n fl = []\n for z in p:\n f = os.path.join(z, x)\n if not os.path.exists(f):\n return False\n fl.append(f)\n fh = file_hash(fl[0])\n for z in fl[1:]:\n if not file_hash(z) == fh:\n return False\n return True\n\nclass TestExeWrapper(unittest.TestCase):\n\n main_dir = \"./tests/exe_wrapper\"\n\n def setUp(self):\n if not os.path.exists(self.main_dir):\n os.makedirs(self.main_dir)\n else:\n remove(self.main_dir)\n make_random_file(self.main_dir)\n\n def tearDown(self):\n remove(self.main_dir)\n\n def test_set_wk_dir(self):\n d = os.path.join(self.main_dir, \"test_set_wk_dir\")\n t = exe_wrapper.GitWrapper(d)\n t._set_wkdir(self.main_dir)\n with self.assertRaises(git_exceptions.GitWrapperException):\n t._set_wkdir(\"this_path_does_not_exist\")\n\n def test_set_timeout(self):\n d = os.path.join(self.main_dir, \"test_set_timeout\")\n t = exe_wrapper.GitWrapper(d)\n t.set_timeout(1)\n t.set_timeout(120)\n for x in [\"str\", 0, 121, 1000]:\n with self.assertRaises(git_exceptions.GitWrapperException):\n t.set_timeout(x)\n\n def test_set_cmd(self):\n d = os.path.join(self.main_dir, \"test_set_cmd\")\n t = exe_wrapper.GitWrapper(d)\n t._set_cmd([\"test\"])\n t._set_cmd([\"test\",\"test\",\"test\"])\n for x in [[\"test\",1,\"test\"], [\"test\",None,\"test\"], [\"test\",False,\"test\"], [\"test\",exe_wrapper,\"test\"]]:\n with self.assertRaises(git_exceptions.GitWrapperException):\n t._set_cmd(x)\n\n def test_init(self):\n d = os.path.join(self.main_dir, \"test_init\")\n t = exe_wrapper.GitWrapper(d)\n t.init()\n t = exe_wrapper.GitWrapper(d, git_exe=\"C:/Documents and Settings/owner/My Documents/BORIS/live/git-portable/bin/git.exe\")\n with self.assertRaises(git_exceptions.GitWrapperException):\n exe_wrapper.GitWrapper(d, git_exe=\"this path does not exist\")\n f = make_random_file(d)\n with self.assertRaises(git_exceptions.GitWrapperException):\n t = exe_wrapper.GitWrapper(f)\n t.init()\n with self.assertRaises(git_exceptions.GitWrapperException):\n subd = make_random_dir(d)\n make_random_file(subd)\n t = exe_wrapper.GitWrapper(subd, must_be_empty=True)\n\n def test_status(self):\n d = os.path.join(self.main_dir, \"test_status\")\n t = exe_wrapper.GitWrapper(d)\n with self.assertRaises(git_exceptions.GitWrapperException):\n t.status()\n t.init()\n t.status()\n\n def test_commit(self):\n d = os.path.join(self.main_dir, \"test_commit\")\n files = []\n for x in range(10):\n files.append(make_random_file(d))\n t = exe_wrapper.GitWrapper(d)\n t.init().commit()\n self.assertTrue(t._nothing_to_commit)\n t.init(add_all=True).commit([custom_path.Path(f).basename for f in files[:2]])\n self.assertFalse(t._nothing_to_commit)\n t.commit()\n self.assertFalse(t._nothing_to_commit)\n with self.assertRaises(git_exceptions.GitWrapperException):\n t.commit(files=None)\n t.commit()\n self.assertTrue(t._nothing_to_commit)\n\n def test_clone(self):\n d = os.path.join(self.main_dir, \"test_clone\")\n d1 = make_random_dir(d)\n d2 = make_random_dir(d)\n d3 = make_random_dir(d)\n for x in range(10):\n make_random_file(d1)\n t1 = exe_wrapper.GitWrapper(d1).init(add_all=True).commit()\n self.assertEqual(d1.lower(), t1.full_path)\n t2 = exe_wrapper.GitWrapper(d2).clone(d1)\n self.assertEqual(os.path.join(d2, os.path.basename(d1)).lower(), t2.full_path)\n t3 = exe_wrapper.GitWrapper(\"\").clone(t2.full_path, target_directory=d3)\n self.assertEqual(d3.lower(), t3.full_path)\n with self.assertRaises(git_exceptions.GitRepositoryAlreadyExistsAndIsNotEmpty):\n t4 = exe_wrapper.GitWrapper(d).clone(t3.full_path)\n self.assertTrue(repos_are_identical([t1,t2,t3]))\n\n def test_push(self):\n d = os.path.join(self.main_dir, \"test_push\")\n d1 = make_random_dir(d)\n d2 = make_random_dir(d)\n for x in range(10):\n make_random_file(d1)\n t1 = exe_wrapper.GitWrapper(d1).init(add_all=True).commit()\n self.assertEqual(d1.lower(), t1.full_path)\n t2 = exe_wrapper.GitWrapper(d2).clone(d1)\n self.assertTrue(repos_are_identical([t1,t2]))\n self.assertEqual(os.path.join(d2, os.path.basename(d1)).lower(), t2.full_path)\n for x in range(10):\n make_random_file(d2)\n t2.commit().status().push()\n self.assertTrue(repos_are_identical([t1,t2]))\n\n def test_pull(self):\n d = os.path.join(self.main_dir, \"test_pull\")\n d1 = make_random_dir(d)\n d2 = make_random_dir(d)\n for x in range(10):\n make_random_file(d1)\n t1 = exe_wrapper.GitWrapper(d1).init(add_all=True).commit()\n self.assertEqual(d1.lower(), t1.full_path)\n t2 = exe_wrapper.GitWrapper(d2).clone(d1)\n self.assertTrue(repos_are_identical([t1,t2]))\n self.assertEqual(os.path.join(d2, os.path.basename(d1)).lower(), t2.full_path)\n for x in range(10):\n make_random_file(d1)\n t1.add().commit()\n t2.commit().pull()\n self.assertTrue(repos_are_identical([t1,t2]))\n\n def test_http_clone(self):\n d = os.path.join(self.main_dir, \"test_http_clone\")\n d1 = make_random_dir(d)\n t1 = exe_wrapper.GitWrapper(d1).clone(\"https://github.com/TDC-bob/modlist\")\n\ndef remove(d):\n shutil.rmtree(d, onerror=shutil_rmtree.onerror)\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n\n","sub_path":"exe_wrapper_test.py","file_name":"exe_wrapper_test.py","file_ext":"py","file_size_in_byte":7812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"362268659","text":"__all__ = ['telephone_bill']\n\nfrom dateutil.relativedelta import relativedelta\n\nfrom django.db import connection\nfrom django.utils import timezone\n\nfrom sparrow.call_records.exceptions import CurrentMonthForbiddenError, InvalidReferencePeriodError\n\n\ndef telephone_bill(subscriber, *, reference_period=None):\n \"\"\"\n Returns a bill for the given reference period. If none\n was given, returns a bill for the previous month.\n\n Prices will be given in Brazilian Real (R$)\n\n Example of return (pseudo-JSON):\n {\n 'subscriber': subscriber,\n 'reference_period': 'YYYYMM',\n 'call_records': [\n {'destination': '{destination}', 'start_date': '{start_date}', 'start_time': '{start_time}',\n 'duration': '0h35m42s', 'price': 'R$ 3,96'},\n # ...\n ]\n }\n \"\"\"\n if _reference_period_is_current_month(reference_period):\n raise CurrentMonthForbiddenError(reference_period)\n\n reference_period, start_reference_date, end_reference_date = _calculate_reference_period_bounds(reference_period)\n # NOTE: This has to exist to cover both the following cases:\n # - calls started and ended in the reference period\n # - calls started in the previous month and ended in the reference period\n start_previous_date = start_reference_date - relativedelta(months=1)\n\n call_records = []\n with connection.cursor() as cursor:\n cursor.execute(_TELEPHONE_BILL_QUERY, {\n 'subscriber': subscriber,\n 'start_previous_date': start_previous_date,\n 'start_reference_date': start_reference_date,\n 'end_reference_date': end_reference_date\n })\n\n for destination, start_timestamp, end_timestamp in cursor.fetchall():\n start_date, start_time = start_timestamp.isoformat().replace('+00:00', 'Z').split('T')\n call_records.append({\n 'destination': destination,\n 'start_date': start_date,\n 'start_time': start_time,\n 'duration': _calculate_duration(start_timestamp, end_timestamp),\n 'price': _calculate_price(start_timestamp, end_timestamp),\n })\n\n return {\n 'subscriber': subscriber,\n 'reference_period': reference_period,\n 'call_records': call_records\n }\n\n\n_TELEPHONE_BILL_QUERY = \"\"\"\nWITH\n start_records AS (\n SELECT\n call_id,\n destination,\n timestamp\n FROM\n call_records_callrecord\n WHERE\n type = 'start'\n AND source = %(subscriber)s\n AND timestamp >= %(start_previous_date)s\n AND timestamp < %(end_reference_date)s\n )\n\nSELECT\n start_records.destination AS destination,\n start_records.timestamp AS start,\n end_records.timestamp AS end\nFROM\n call_records_callrecord end_records,\n start_records\nWHERE\n end_records.type = 'end'\n AND end_records.timestamp >= %(start_reference_date)s\n AND end_records.timestamp < %(end_reference_date)s\n AND start_records.call_id = end_records.call_id\nORDER BY\n start_records.timestamp ASC\n\"\"\"\n\n\ndef _reference_period_is_current_month(period):\n if not period:\n # NOTE: if no period is given we'll default to the previous\n # month elsewhere\n return False\n\n try:\n period = timezone.datetime.strptime(period, '%Y%m')\n except (ValueError, TypeError):\n # NOTE: ValueError is for `period` of the right type (string),\n # and TypeError is for other types\n raise InvalidReferencePeriodError(period)\n\n today = timezone.datetime.today()\n return today.year == period.year and today.month == period.month\n\n\ndef _calculate_reference_period_bounds(period):\n \"\"\"\n Returns a pair of datetime objects delimiting the reference period given\n as a string in the format of YYYYMM.\n \"\"\"\n if not period:\n # NOTE: if period is None, consider last month as the period\n period = timezone.datetime.today().replace(day=1, hour=0, minute=0, second=0, microsecond=0)\n period = (period - relativedelta(months=1)).strftime('%Y%m')\n\n start_month = timezone.make_aware(timezone.datetime.strptime(period, '%Y%m'))\n end_month = start_month + relativedelta(months=1)\n\n return (period, start_month, end_month)\n\n\ndef _calculate_duration(start_timestamp, end_timestamp):\n \"\"\"\n Returns duration in a pretty format, like \"32m27s\"\n \"\"\"\n # NOTE: had knowledge of https://gist.github.com/thatalextaylor/7408395\n # so I reused most of it\n seconds = (end_timestamp - start_timestamp).seconds\n days, seconds = divmod(seconds, 86400)\n hours, seconds = divmod(seconds, 3600)\n minutes, seconds = divmod(seconds, 60)\n\n duration = []\n if days > 0:\n duration.append(f'{days}d')\n if hours > 0:\n duration.append(f'{hours}h')\n if minutes > 0:\n duration.append(f'{minutes}m')\n if seconds > 0:\n duration.append(f'{seconds}s')\n\n return ''.join(duration)\n\n\n# NOTE: it is stated that price rules can change\n# from time to time. In this case, it would be better\n# to have multiple functions, one for each price\n# rule, and have _calculate_price select the right\n# function based on the selected period. This way,\n# price calculation will not fluctuate and we'll\n# be able to change price rules whenever needed.\n#\n# Since in this exercise there was no example\n# of that, for the purposes of a POC I've decided\n# to keep this function simple\ndef _calculate_price(start_timestamp, end_timestamp):\n \"\"\"\n Calculates price for the given interval. Values are calculated\n in cents and then converted to Brazilian Real by the end.\n \"\"\"\n standing_charge = 36\n call_charge = 9\n if start_timestamp.hour >= 22 or start_timestamp.hour < 6:\n # reduced tariff, YAY!\n call_charge = 0\n\n minutes = (end_timestamp - start_timestamp).seconds // 60\n price = standing_charge + (call_charge * minutes)\n return 'R$ {:0,.2f}'.format(price / 100).replace('.', ',')\n","sub_path":"sparrow/call_records/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"488761806","text":"def área(a, b):\n mult = a * b\n print(f'A área de um terreno {a}x{b} é de {mult}m².')\n\n\nprint(f'{\"Controle de Terrenos\":^30}')\nprint('-'*30)\nl = float(input('LARGURA (m): '))\nc = float(input('COMPRIMENTO (m): '))\nárea(l, c)\n","sub_path":"mundo-03/ex096.py","file_name":"ex096.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"238908520","text":"import random as r\n# guesses is the times you can guess\nguesses = 3\n\n\ndef play():\n global guesses\n dice = r.randint(1, 6)\n while True:\n guess = int(input(\"Guess the dice number: \"))\n # if the guess is right\n if guess == dice:\n print (\"You win!!!\")\n break\n # if you guess it wrong\n\n if guesses == 1:\n print(\"You lose!!!\")\n print(\"The number was \" + str(dice))\n break\n else:\n print(\"You guessed it wrong!!!\")\n guesses = guesses - 1\n print('You still have ' + str(guesses) + \" lives left!!!\")\n\n\nplay()\n# #LMAO\n","sub_path":"Games-that-I-Made/Dice Games/Dice Guessing Game.py","file_name":"Dice Guessing Game.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"324299260","text":"import autode as ade\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Initialise the electronic structure method and a list of different\n# single point energy keywords\norca = ade.methods.ORCA()\n\nkeywords_list = {'PBE': ade.SinglePointKeywords(['PBE', 'def2-SVP']),\n 'PBE0': ade.SinglePointKeywords(['PBE0', 'def2-SVP']),\n 'B3LYP': ade.SinglePointKeywords(['B3LYP', 'def2-SVP'])}\n\nwater = ade.Molecule(name='H2O', smiles='O')\n\n# For the three different DFT functionals calculate the PES and plot the line\nfor dft_name, keywords in keywords_list.items():\n\n # Create arrays for OH distances and their energies\n rs = np.linspace(0.65, 2.0, num=15)\n energies = []\n\n # Calculate the energy array\n for r in rs:\n\n o_atom, h_atom = water.atoms[:2]\n curr_r = water.distance(0, 1)\n\n vector = (h_atom.coord - o_atom.coord) * (r/curr_r - 1)\n h_atom.translate(vector)\n\n # Set up and run the calculation\n calc = ade.Calculation(name=f'H2O_scan_{r:.2f}',\n molecule=water,\n method=orca,\n keywords=keywords)\n calc.run()\n\n # Get the potential energy from the calculation\n energy = calc.get_energy()\n energies.append(energy)\n\n # Plot the relative energy against the distance. 627.5 kcal mol-1 Ha-1\n min_e_kcal = min(energies).to('kcal mol-1')\n plt.plot(rs,\n [e.to('kcal mol-1') - min_e_kcal for e in energies],\n marker='o',\n label=dft_name)\n\n# Add labels to the plot and save the figure\nplt.ylabel('ΔE / kcal mol$^{-1}$')\nplt.xlabel('r / Å')\nplt.legend()\nplt.tight_layout()\nplt.savefig('OH_PES_unrelaxed2.pdf')\n","sub_path":"doc/common/OH_PES_unrelaxed_DFT.py","file_name":"OH_PES_unrelaxed_DFT.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"464776184","text":"import unittest\nimport torch\nfrom model.bert import BERT\n\n\n# bert_dense_meta_t x_meta(0, false, batch_size, seq_len, hidden_layer_size);\n# bert_dense_meta_t mask_meta(0, false, batch_size, seq_len, seq_len);\n\nbert = BERT()\n\nbatch_size = 1\nseq_len = 20\nhidden_layer_size = 768\n\nfor num_heads in range(12, 40):\n x = torch.rand(batch_size, seq_len, hidden_layer_size)\n mask = torch.rand(batch_size, seq_len, seq_len)\n\n for param_tensor in bert.state_dict():\n print(param_tensor, \"\\t\", bert.state_dict()[param_tensor].size())\n\n torch.save(bert.state_dict(), \"./bert.pth\")\n bert.load_state_dict(torch.load(\"./bert.pth\"))\n bert.eval()\n\n module = torch.jit.trace(bert, (x, mask)).cpu()\n torch.jit.save(module, 'bert-%s-heads-%s-hidden.pt' %\n (num_heads, hidden_layer_size))\n","sub_path":"bert_pytorch/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"451243806","text":"import datetime\n\nfrom django.contrib.auth import get_user_model\nfrom django.db.models import Count, Q\nfrom django.utils import timezone\nfrom django.views.generic import TemplateView\n\nfrom core.lib import sql\nfrom erp.models import Commune, Erp, Vote\n\n\nclass StatsView(TemplateView):\n template_name = \"stats/index.html\"\n\n def get_date_range(self):\n base = timezone.now()\n lst = [base - datetime.timedelta(days=x) for x in range(30)]\n lst.reverse()\n return lst\n\n def get_nb_contributors(self):\n return sql.run_sql(\n \"\"\"--sql\n select count(distinct e.user_id)\n from erp_erp e\n left join erp_accessibilite a on a.erp_id = e.id\n where e.geom is not null and a.id is not null;\n \"\"\"\n )[0].get(\"count\", 0)\n\n def get_top_contributors(self):\n return (\n get_user_model()\n .objects.annotate(\n erp_count_published=Count(\n \"erp\",\n filter=Q(\n erp__published=True,\n erp__accessibilite__isnull=False,\n erp__geom__isnull=False,\n ),\n distinct=True,\n ),\n erp_count_total=Count(\n \"erp\",\n distinct=True,\n ),\n )\n .filter(erp__accessibilite__isnull=False)\n .order_by(\"-erp_count_published\")[:10]\n )\n\n def get_top_voters(self):\n return (\n get_user_model()\n .objects.annotate(vote_count=Count(\"vote\", distinct=True))\n .exclude(vote_count=0)\n .order_by(\"-vote_count\")[:10]\n )\n\n def get_north_star(self):\n vote_qs = Vote.objects\n positive = vote_qs.filter(value=1).count()\n total = vote_qs.count()\n percent = (positive / total * 100) if total != 0 else 100\n return {\n \"positive\": positive,\n \"total\": total,\n \"percent\": percent,\n }\n\n def get_votes_histogram(self):\n results = sql.run_sql(\n \"\"\"--sql\n select\n count(erp_vote.id) as total,\n count(erp_vote.id) filter (where erp_vote.value = 1) as positive,\n date\n from\n erp_vote,\n generate_series(current_date - interval '30 day', current_date, interval '1 day') as date\n where erp_vote.created_at <= date + interval '1 day'\n group by date\n order by date ASC;\n \"\"\"\n )\n return {\n \"labels\": [r[\"date\"].strftime(\"%Y-%m-%d\") for r in results],\n \"totals\": [r[\"total\"] for r in results],\n \"positives\": [r[\"positive\"] for r in results],\n }\n\n def get_erp_counts_histogram(self):\n results = sql.run_sql(\n \"\"\"--sql\n select\n date,\n count(a.id) filter (\n where e.created_at <= date + interval '1 day'\n and e.geom is not null\n and e.published\n ) as total\n from\n generate_series(current_date - interval '30 day', current_date, interval '1 day') as date\n cross join\n erp_accessibilite a\n left join\n erp_erp e on e.id = a.erp_id\n group by date\n order by date asc;\n \"\"\"\n )\n return {\n \"labels\": [r[\"date\"].strftime(\"%Y-%m-%d\") for r in results],\n \"totals\": [r[\"total\"] for r in results],\n }\n\n def get_contributors_histogram(self):\n results = sql.run_sql(\n \"\"\"--sql\n select\n date,\n count(distinct e.user_id) filter (\n where e.created_at <= date + interval '1 day'\n ) as total\n from\n generate_series(current_date - interval '30 day', current_date, interval '1 day') as date\n cross join\n erp_accessibilite a\n left join\n erp_erp e on e.id = a.erp_id\n where e.geom is not null\n group by date\n order by date asc;\n \"\"\"\n )\n return {\n \"labels\": [r[\"date\"].strftime(\"%Y-%m-%d\") for r in results],\n \"totals\": [r[\"total\"] for r in results],\n }\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n erp_qs = Erp.objects.published()\n\n context[\"north_star\"] = self.get_north_star()\n context[\"nb_filled_erps\"] = erp_qs.count()\n context[\"nb_filled_erps_by_users\"] = erp_qs.filter(user__isnull=False).count()\n context[\"communes\"] = Commune.objects.erp_stats()[:10]\n context[\"nb_communes\"] = (\n Commune.objects.erp_stats().filter(erp_access_count__gt=0).count()\n )\n context[\"nb_users\"] = get_user_model().objects.filter(is_active=True).count()\n context[\"nb_contributors\"] = self.get_nb_contributors()\n context[\"top_contributors\"] = self.get_top_contributors()\n context[\"top_voters\"] = self.get_top_voters()\n context[\"votes_histogram\"] = self.get_votes_histogram()\n context[\"erp_counts_histogram\"] = self.get_erp_counts_histogram()\n context[\"contributors_histogram\"] = self.get_contributors_histogram()\n\n return context\n","sub_path":"stats/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"643886056","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 17-6-28 下午6:15\n# @Author : zhe.zhang\n# @Site : http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143186362353505516c5d4e38456fb225c18cc5b54ffb000\n# @File : 安装第三方模块.py\n# @Software: PyCharm Community Edition\n# @Function :\n__author__ = 'zhe.zhang'\n# 在Python中,安装第三方模块,是通过包管理工具pip完成的。\n#\n# 如果你正在使用Mac或Linux,安装pip本身这个步骤就可以跳过了。\n#\n# 如果你正在使用Windows,请参考安装Python一节的内容,确保安装时勾选了pip和Add python.exe to Path。\n#\n# 在命令提示符窗口下尝试运行pip,如果Windows提示未找到命令,可以重新运行安装程序添加pip。\n#\n# 注意:Mac或Linux上有可能并存Python 3.x和Python 2.x,因此对应的pip命令是pip3。\n#\n# 现在,让我们来安装一个第三方库——Python Imaging Library,这是Python下非常强大的处理图像的工具库。不过,PIL目前只支持到Python 2.7,并且有年头没有更新了,因此,基于PIL的Pillow项目开发非常活跃,并且支持最新的Python 3。\n#\n# 一般来说,第三方库都会在Python官方的pypi.python.org网站注册,要安装一个第三方库,必须先知道该库的名称,可以在官网或者pypi上搜索,比如Pillow的名称叫Pillow,因此,安装Pillow的命令就是:\n# pip install Pillow\n# 耐心等待下载并安装后,就可以使用Pillow了。\n# 有了Pillow,处理图片易如反掌。随便找个图片生成缩略图\nfrom PIL import Image\nimport sys\n\n# /usr/lib/python3/dist-packages\nim = Image.open('test.png')\nprint(im.format, im.size, im.mode)\nim.thumbnail((200, 100))\nim.save('thumb.jpg', 'JPEG')\n# 其他常用的第三方库还有MySQL的驱动:mysql-connector-python,用于科学计算的NumPy库:numpy,用于生成文本的模板工具Jinja2,等等。\nprint('=========================================================')\nprint('2---模块搜索路径')\n# 当我们试图加载一个模块时,Python会在指定的路径下搜索对应的.py文件,如果找不到,就会报错:\n# import mymodule\n# Traceback (most recent call last):\n# File \"\", line 1, in \n# ImportError: No module named mymodule\n# 默认情况下,Python解释器会搜索当前目录、所有已安装的内置模块和第三方模块,搜索路径存放在sys模块的path变量中:\nprint(sys.path)\n# 如果我们要添加自己的搜索目录,有两种方法:\n# 一是直接修改sys.path,添加要搜索的目录:\nsys.path.append('/home/zhezhang/workspace/python/learnPython')\n# 这种方法是在运行时修改,运行结束后失效。\n# 第二种方法是设置环境变量PYTHONPATH,该环境变量的内容会被自动添加到模块搜索路径中。设置方式与设置Path环境变量类似。注意只需要添加你自己的搜索路径,Python自己本身的搜索路径不受影响。\n","sub_path":"learnPython/6-28模块/6-28安装第三方模块/安装第三方模块.py","file_name":"安装第三方模块.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"593210311","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author: Yandong\n# Time :2019/10/16 6:51\n# Description: ‘Scheduling of Vehicles from a Central Depot to a Number of Delivery Points’ by G. Clarke\n# Operations Research, Vol. 12, No. 4. (Jul. - Aug., 1964), pp. 568-581\n# (1) running fast\n# (2) near-optimum\n# (3) not least vehicles\n\nimport os, time\nimport import_data\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport three_optimal\n\nBASE_DIR = os.path.abspath('.')\nall_routes = dict()\nroute_id = None\n\n\n\ndef calculate_cost(route, distance_matrix):\n \"\"\"\n calculate the cost of route\n :param route:\n :param distance_matrix:\n :return:\n \"\"\"\n total_cost = 0\n for n1, n2 in zip(route[:-1], route[1:]):\n total_cost += distance_matrix[n1-1][n2-1]\n return total_cost\n\n\nclass Route(object):\n \"\"\"\n The class of route, and the method to create, merge, add ...\n \"\"\"\n\n def __init__(self, id, nodes, demand, vehicle_capacity, vehicle_endurance):\n self.id = id\n self.nodes = nodes\n self.start_end()\n self.demand = demand\n self.merge_mark = False\n self.merge_not_mark = False\n self.vehicle_capacity = vehicle_capacity\n self.vehicle_endurance = vehicle_endurance\n self.add_new(nodes, demand)\n\n def start_end(self):\n if len(self.nodes) == 1:\n self.start = self.nodes[0]\n self.end = self.nodes[0]\n else:\n self.start = self.nodes[0]\n self.end = self.nodes[1]\n\n def add_new(self, nodes, demand):\n self.path = list(nodes)\n self.capacity = sum([demand[i] for i in nodes])\n\n def check_in(self, cand_nodes):\n \"\"\"\n check the node is start/end, merge node or not\n \"\"\"\n global all_routes, route_id\n node_1, node_2 = cand_nodes[0], cand_nodes[1]\n if node_1 in [self.start, self.end] and node_2 in [self.start, self.end]:\n # both nodes are start or end\n return False\n elif node_1 in [self.start, self.end] or node_2 in [self.start, self.end]:\n # one of nodes is start or end\n if node_1 == self.start:\n for key, val in all_routes.items():\n other = val.path\n if node_2 == other[0]:\n self.merge_route(other[::-1], self.path)\n elif node_2 == other[-1]:\n self.merge_route(other, self.path)\n if self.merge_mark:\n # satisfy the capacity and then merge the routes\n del all_routes[key]\n return True\n elif node_1 == self.end:\n for key, val in all_routes.items():\n other = val.path\n if node_2 == other[0]:\n self.merge_route(self.path, other)\n elif node_2 == other[-1]:\n self.merge_route(self.path, other[::-1])\n if self.merge_mark:\n # satisfy the capacity and then merge the routes\n del all_routes[key]\n return True\n elif node_2 == self.start:\n for key, val in all_routes.items():\n other = val.path\n if node_1 == other[0]:\n self.merge_route(other[::-1], self.path)\n elif node_1 == other[-1]:\n self.merge_route(other, self.path)\n if self.merge_mark:\n # satisfy the capacity and then merge the routes\n del all_routes[key]\n return True\n elif node_2 == self.end:\n for key, val in all_routes.items():\n other = val.path\n if node_1 == other[0]:\n self.merge_route(self.path, other)\n elif node_1 == other[-1]:\n self.merge_route(self.path, other[::-1])\n if self.merge_mark:\n # satisfy the capacity and then merge the routes\n del all_routes[key]\n return True\n return True\n else:\n return False\n\n def merge_route(self, one_route, other):\n \"\"\"\n merge the path with another route\n merge path capacity\n \"\"\"\n capacity = sum([self.demand[i] for i in one_route + other])\n part_route = [0] + one_route + other +[0]\n # part_route = three_optimal.three_optimal(part_route, distance_matrix)\n part_distance = calculate_cost(part_route, distance_matrix)\n if (not self.vehicle_endurance or part_distance <= self.vehicle_endurance) and capacity <= self.vehicle_capacity:\n self.merge_mark = True\n self.path = one_route + other\n self.start = self.path[0]\n self.end = self.path[-1]\n self.capacity = capacity\n else:\n self.merge_not_mark = True\n pass\n\n def add_candidate(self, cand_nodes):\n \"\"\"\n Add to the current route\n \"\"\"\n for node_i in cand_nodes:\n if node_i == self.start:\n two_nodes = list(cand_nodes)\n two_nodes.remove(node_i)\n other_node = two_nodes[0]\n if self.check_capacity(other_node):\n tmp_path = [0, other_node] + self.path + [0]\n if self.check_endurance(tmp_path):\n self.path.insert(0, other_node)\n self.start = other_node\n self.capacity += self.demand[other_node]\n return\n elif node_i == self.end:\n two_nodes = list(cand_nodes)\n two_nodes.remove(node_i)\n other_node = two_nodes[0]\n if self.check_capacity(other_node):\n tmp_path = [0] + self.path + [other_node, 0]\n if self.check_endurance(tmp_path):\n self.path.append(other_node)\n self.end = other_node\n self.capacity += self.demand[other_node]\n return\n\n def check_capacity(self, add_node):\n if self.capacity + self.demand[add_node] <= self.vehicle_capacity:\n return True\n else:\n return False\n\n def check_endurance(self, route):\n if not self.vehicle_endurance or calculate_cost(route, distance_matrix) <= self.vehicle_endurance:\n return True\n else:\n return False\n\n\ndef saving_sort(demand_list, distance_matrix, vehicle_capacity, vehicle_endurance):\n \"\"\"\n Get the saving list in increased order.\n d[0][i] + d[0][j] - d[i][j]\n return saving list [(i, j), saving_distance]\n \"\"\"\n node_num = len(distance_matrix)\n saving_matrix = np.zeros([node_num, node_num])\n for i in range(node_num):\n for j in range(node_num):\n if i == j:\n saving_matrix[i][j] = 0\n else:\n if demand_list[i] + demand_list[j] > vehicle_capacity:\n saving_matrix[i][j] = 0\n else:\n if vehicle_endurance == None or (distance_matrix[0][i] + distance_matrix[0][j] + distance_matrix[i][j] <= vehicle_endurance):\n saving_matrix[i][j] = distance_matrix[0][i] + distance_matrix[0][j] - distance_matrix[i][j]\n\n saving_list = list()\n for i in range(1, node_num - 1):\n for j in range(i + 1, node_num):\n if saving_matrix[i][j] == 0:\n pass\n else:\n saving_list.append([(i, j), saving_matrix[i][j]])\n # sorting decrease\n saving_list.sort(key=lambda x: x[1], reverse=False)\n return saving_list\n\n\ndef check_alone_node(remain_nodes):\n \"\"\"\n Node demand is over the capacity constraint and forms route by itself\n \"\"\"\n global all_routes, route_id\n for node in remain_nodes:\n route_id += 1\n new_route = Route(route_id, node, demand_list, vehicle_capacity, vehicle_endurance)\n all_routes[route_id] = new_route\n\n\ndef saving_algorithm(distance_matrix, demand_list, vehicle_capacity, vehicle_endurance):\n \"\"\"\n Clarke and Wright: saving algorithm\n \"\"\"\n # calculate the saving list\n\n global all_routes, route_id\n\n saving_list = saving_sort(demand_list, distance_matrix, vehicle_capacity, vehicle_endurance)\n visited = list()\n interior_nodes = list()\n route_id = 0\n all_routes[route_id] = list()\n current_route = all_routes[route_id]\n start_time = time.time()\n # merge the parts in the saving list\n while saving_list:\n candidate_part = saving_list.pop()\n cand_nodes, _ = candidate_part[0], candidate_part[1]\n # --- the first route --- #\n if not current_route:\n # current route is empty\n current_route = Route(route_id, cand_nodes, demand_list, vehicle_capacity, vehicle_endurance)\n all_routes[route_id] = current_route\n visited.extend(current_route.path)\n continue\n # --- if one of the nodes is the interior node and pass --- #\n if cand_nodes[0] in interior_nodes or cand_nodes[1] in interior_nodes:\n continue\n # --- two nodes are not in the exist routes --- #\n if cand_nodes[0] not in visited and cand_nodes[1] not in visited:\n # create a new route\n route_id += 1\n new_route = Route(route_id, cand_nodes, demand_list, vehicle_capacity, vehicle_endurance)\n all_routes[route_id] = new_route\n visited.extend(new_route.path)\n continue\n else:\n for r_id, current_route in all_routes.items():\n if current_route.check_in(cand_nodes):\n if current_route.merge_mark or current_route.merge_not_mark:\n # -- merge -- #\n current_route.merge_mark = False\n current_route.merge_not_mark = False\n else:\n # -- add -- #\n current_route.add_candidate(cand_nodes)\n interior_nodes.extend(current_route.path[1:-1]) # visited the interior nodes\n visited.extend(current_route.path)\n break\n else:\n pass\n # --- not satisfy the capacity or other reason --- #\n # --- check the remain nodes --- #\n all_nodes = list(range(len(demand_list)))\n all_nodes.remove(0)\n remain_nodes = [all_nodes.remove(i) for i in list(set(visited))]\n if remain_nodes == []:\n check_alone_node(remain_nodes)\n else:\n pass\n\n result_routes = list()\n for key, route in all_routes.items():\n result_routes.append(route.path)\n print('The running time %s'%(time.time() - start_time))\n return result_routes\n\n\n# ---show the result----#\ndef print_result(results, distance_matrix):\n route_cnt = 0\n total_distance = 0\n for route in results:\n route_cnt += 1\n depot_route = [0] + route + [0]\n total_distance += sum(distance_matrix[i][j] for i, j in zip(depot_route[:-1], depot_route[1:]))\n print('Route %s: %s' % (route_cnt, depot_route))\n print('Total distance: %s' % total_distance)\n\n\n# --- plot the graph --- #\ndef show_result(all_routes, coordination):\n for index, route in enumerate(all_routes):\n x = []\n y = []\n # add depot as start and end point\n for j in [0] + route + [0]:\n x.append(coordination[j][0])\n y.append(coordination[j][1])\n random_color = [i[0] for i in np.random.rand(3, 1)]\n plt.scatter(x, y, c=random_color, marker=\"*\")\n plt.plot(x, y, c=random_color)\n # depot\n z = []\n w = []\n z.append(coordination[0][0])\n w.append(coordination[0][1])\n for index in range(len(coordination)):\n plt.text(coordination[index][0], coordination[index][1], index)\n plt.scatter(z, w, s=100, c=\"r\", marker=\"o\", label=\"Depot\")\n plt.xlabel('City x coordination')\n plt.ylabel(\"City y coordination\")\n plt.title(\"The VRP map by saving algorithm\")\n plt.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n file_name = os.path.join(BASE_DIR, 'Christofides1979\\CMT12.vrp')\n vehicle_capacity, vehicle_endurance, demand_list, coordinates, distance_matrix = import_data.init_data(file_name)\n results = saving_algorithm(distance_matrix, demand_list, vehicle_capacity, vehicle_endurance)\n # --- 3-opt --- #\n opt_result = list()\n for route in results:\n three_opt_route = [0] + route[:] # depot\n three_opt_route = three_optimal.three_optimal(three_opt_route, distance_matrix)\n opt_result.append(three_opt_route[1:])\n # print_result(opt_result, distance_matrix)\n # show_result(opt_result, coordinates)\n\n print_result(results, distance_matrix)\n print_result(opt_result, distance_matrix)\n show_result(results, coordinates)\n show_result(opt_result, coordinates)\n\n# capacity constraint\n# CMT1.vrp 582.057\n# CMT2.vrp 891.169\n# CMT3.vrp 881.583\n# CMT4.vrp 1129.703\n# CMT5.vrp 1389.595\n# CMT11.vrp 1046.027\n# CMT12.vrp 824.419\n\n# capacity and distance constraint\n# CMT6.vrp 725.335\n# CMT7.vrp 1168.109\n# CMT8.vrp 1151.701\n# CMT9.vrp 1672.710\n# CMT10.vrp 2070.355\n# CMT13.vrp 1046.027\n# CMT14.vrp 824.419\n","sub_path":"VRP_algorithm/SA_3opt/saving_algorithm.py","file_name":"saving_algorithm.py","file_ext":"py","file_size_in_byte":13587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"19455592","text":"import re\nimport time\nimport json\nimport hashlib\nimport logging\nimport requests\nimport portalocker\nimport platform\nimport os\nimport subprocess\n\nfrom popwatch import config\nfrom popwatch import popProfiles\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime, timedelta\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom operator import itemgetter\n\n# Get Profile From Json Config\ndef profileInit():\n with portalocker.Lock(config.USER_INFO, \"r\", timeout=10) as data_file:\n userProfileVars = json.load(data_file)\n city = userProfileVars.get('city')\n ccNumber = userProfileVars.get('ccNumber')\n f_name = userProfileVars.get('f_name')\n l_name = userProfileVars.get('l_name')\n zipCode = userProfileVars.get('zipCode')\n mm = userProfileVars.get('mm')\n yy = userProfileVars.get('yy')\n phone = userProfileVars.get('phone')\n ad_one = userProfileVars.get('ad_one')\n ad_two = userProfileVars.get('ad_two')\n ccSecurityCode = userProfileVars.get('ccSecurityCode')\n email = userProfileVars.get('email')\n ccOwner = f_name + \" \" + l_name\n expDate = mm + '/' + yy\n\n return popProfiles.Profile(city, ccNumber, f_name, l_name, zipCode, phone, ad_one, ad_two, ccSecurityCode, email, ccOwner, expDate)\n\n# Instantiating Pop Profile\nprofile = profileInit()\n\n_LOG = logging.getLogger(__name__)\n\nHTML_OBJ = {\n \"hottopic\": \"presale-pdp\",\n \"boxlunch\": \"presale-pdp\",\n \"walmart\": \"spin-button-children\",\n \"barnesandnoble\": \"btn-addtocart\",\n \"gamestop\": \"addOnSalesModalEligible\",\n \"blizzard\": \"product-addtocart-button\",\n \"geminicollectibles\": \"add-to-cart\",\n \"hbo\": \"AddToCart-product-template\",\n \"target\": \"h-text-orangeDark\"}\n\ndef get_distro():\n # Checking Distrobution before passing in connection string\n distroName = platform.system()\n return distroName\n\nclass storeStock(object):\n\n def __init__(self, UPDATER):\n self.TIMEOUT = {}\n self.UPDATER = UPDATER\n self.THREAD_ALIVE = False\n self.driver = self.init_driver()\n\n def ht_bl_checkout_process(self, site):\n # Checkout Button then as unregistrated user\n checkoutBtn = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, '//*[@id=\"checkout-form\"]/fieldset/div/button')))\n checkoutBtn.click()\n # Start as an Unregistered User\n checkoutBtnAsGuest = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, '//*[@id=\"primary\"]/div[2]/div[1]/form/fieldset/div/button/span')))\n checkoutBtnAsGuest.click()\n # Fill Out Form for Guest Checkout\n # USER FORM AUTOMATION #\n email_form = self.driver.find_element_by_id(\"dwfrm_singleshipping_email_emailAddress\")\n email_form.send_keys(profile.email)\n first_name_form = self.driver.find_element_by_id(\"dwfrm_singleshipping_shippingAddress_addressFields_firstName\")\n first_name_form.send_keys(profile.f_name)\n last_name_form = self.driver.find_element_by_id(\"dwfrm_singleshipping_shippingAddress_addressFields_lastName\")\n last_name_form.send_keys(profile.l_name)\n country_selection = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, '//*[@id=\"dwfrm_singleshipping_shippingAddress_addressFields_country\"]/option[2]')))\n country_selection.click()\n zip_form = self.driver.find_element_by_id(\"dwfrm_singleshipping_shippingAddress_addressFields_postal\")\n zip_form.send_keys(profile.zipCode)\n ad_one_form = self.driver.find_element_by_id(\"dwfrm_singleshipping_shippingAddress_addressFields_address1\")\n ad_one_form.send_keys(profile.ad_one)\n ad_two_form = self.driver.find_element_by_id(\"dwfrm_singleshipping_shippingAddress_addressFields_address2\")\n ad_two_form.send_keys(profile.ad_two)\n city_form = self.driver.find_element_by_id(\"dwfrm_singleshipping_shippingAddress_addressFields_city\")\n city_form.send_keys(profile.city)\n state_selection = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, '//*[@id=\"dwfrm_singleshipping_shippingAddress_addressFields_states_state\"]/option[5]')))\n state_selection.click()\n phone_form = self.driver.find_element_by_id(\"formatted-phone\")\n phone_form.send_keys(profile.phone)\n # Continue to Billing Button\n continueBillingBtn = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, '//*[@id=\"dwfrm_singleshipping_shippingAddress\"]/div[2]/fieldset/div/button')))\n continueBillingBtn.click()\n # Enter Credit Card Information\n # Credit Card Owner\n creditCardOwner = self.driver.find_element_by_id(\"dwfrm_billing_paymentMethods_creditCard_owner\")\n creditCardOwner.send_keys(profile.ccOwner)\n # Credit Card Number\n creditCardNum = self.driver.find_element_by_id(\"dwfrm_billing_paymentMethods_creditCard_number\")\n creditCardNum.send_keys(profile.ccNumber)\n # Credit Card Expiration Date\n creditCardExp = self.driver.find_element_by_id(\"dwfrm_billing_paymentMethods_creditCard_userexp\")\n creditCardExp.send_keys(profile.expDate)\n # Credit Card Security Code\n creditCardCCV = self.driver.find_element_by_id(\"dwfrm_billing_paymentMethods_creditCard_cvn\")\n creditCardCCV.send_keys(profile.ccSecurityCode)\n # Billing Review Button\n reviewBillingBtn = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, '//*[@id=\"dwfrm_billing\"]/div[3]/button')))\n reviewBillingBtn.click()\n # Place Order Button\n if os.environ['POPENV'] == \"dev\":\n self.UPDATER.bot.send_message(chat_id=config.TELEGRAM_CHAT_ID,\n text=\"Funko Bot in Test Mode. Checkout Not Proceeding\")\n elif os.environ['POPENV'] == \"stg\":\n self.UPDATER.bot.send_message(chat_id=config.TELEGRAM_CHAT_ID,\n text=\"Running Checkout Process Without Headless\")\n placeOrderBtn = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, '//*[@id=\"summarySubmit\"]')))\n placeOrderBtn.click()\n elif os.environ['POPENV'] == \"prd\":\n placeOrderBtn = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, '//*[@id=\"summarySubmit\"]')))\n placeOrderBtn.click()\n\n def hbo_checkout_process(self):\n # # Check if Pop Overlay Exists\n # # popup = self.driver.find_elements_by_xpath(\n # '//*[@id=\"privy-inner-container\"]/div[1]/div/div/div[3]/div[5]/button')\n\n # # Logic to Close Pop when it does exist\n # for popupCloseBtn in popup:\n # popInnerText = popupCloseBtn.get_attribute('innerText')\n # if popInnerText:\n # print('Pop Found Initiating Closer of Pop Up')\n # # Pop Up Found and Needs to be Dismissed\n # popup.click()\n # else:\n # self.driver.refresh()\n # Find quantity element by name\n quantity = self.driver.find_element_by_name(\"quantity\")\n # Reset Default Quantity Value\n self.driver.execute_script(\"arguments[0].value = ''\", quantity)\n # Input to form number of items wanted\n quantity.send_keys(\"2\")\n # Using Javascript to Add Item to Cart\n self.driver.execute_script(\"document.getElementById('AddToCart-product-template').click()\")\n # Checkout Button\n hboCheckoutBtn = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, '//*[@id=\"MiniCart\"]/a[1]')))\n hboCheckoutBtn.click()\n # Enter Coupon Code\n # couponCode = self.driver.find_element_by_id(\"checkout_reduction_code\")\n # couponCode.send_keys(\"WELCOME15\")\n # Start Entering User Information\n hboEmailForm = self.driver.find_element_by_id(\"checkout_email\")\n hboEmailForm.send_keys(profile.email)\n hboFName = self.driver.find_element_by_id(\"checkout_shipping_address_first_name\")\n hboFName.send_keys(profile.f_name)\n hboLName = self.driver.find_element_by_id(\"checkout_shipping_address_last_name\")\n hboLName.send_keys(profile.l_name)\n hboADOne = self.driver.find_element_by_id(\"checkout_shipping_address_address1\")\n hboADOne.send_keys(profile.ad_one)\n hboADTwo = self.driver.find_element_by_id(\"checkout_shipping_address_address2\")\n hboADTwo.send_keys(profile.ad_two)\n hboCity = self.driver.find_element_by_id(\"checkout_shipping_address_city\")\n hboCity.send_keys(profile.city)\n hboCountrySelection = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, '//*[@id=\"checkout_shipping_address_country\"]/option[1]')))\n hboCountrySelection.click()\n hboStateSelection = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, '//*[@id=\"checkout_shipping_address_province\"]/option[5]')))\n hboStateSelection.click()\n hboZipCode = self.driver.find_element_by_id(\"checkout_shipping_address_zip\")\n hboZipCode.send_keys(profile.zipCode)\n hboPhone = self.driver.find_element_by_id(\"checkout_shipping_address_phone\")\n hboPhone.send_keys(profile.phone)\n # Go to Shipping Method Page\n hboShippingMethodBtn = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, '/html/body/div[2]/div/div[1]/div[2]/div/form/div[2]/button')))\n hboShippingMethodBtn.click()\n # Go to Payment Method Page\n hboPaymentMethodBtn = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, '/html/body/div[2]/div/div[1]/div[2]/div/form/div[2]/button')))\n hboPaymentMethodBtn.click()\n # Credit Card Information Form Fill Out\n # Credit Card Number\n hbocreditCardNumIframe = self.driver.switch_to.frame(\n self.driver.find_element_by_class_name(\"card-fields-iframe\"))\n self.driver.switch_to.frame(hbocreditCardNumIframe)\n hbocreditCardNum = self.driver.find_element_by_name('number')\n hbocreditCardNum.send_keys(profile.ccNumber)\n self.driver.switch_to_default_content\n # Credit Card Owner\n # hbocreditCardOwner = self.driver.find_element_by_id(\"name\")\n # hbocreditCardOwner.send_keys(profile.ccOwner)\n # # Credit Card Expiration Date\n # hbocreditCardExp = self.driver.find_element_by_id(\"expiry\")\n # hbocreditCardExp.send_keys(profile.expDate)\n # # # Credit Card Security Code\n # hbocreditCardCCV = self.driver.find_element_by_id(\"verification_value\")\n # hbocreditCardCCV.send_keys(profile.ccSecurityCode)\n # # Complete Order Button\n # hboCompleteOrderBtn = WebDriverWait(self.driver, 20).until(\n # EC.element_to_be_clickable((By.XPATH, '/html/body/div[2]/div/div[1]/div[2]/div/div/form/div[3]/div[1]/button')))\n # hboCompleteOrderBtn.click()\n\n # def walmart_checkout_process(self):\n # quantity = WebDriverWait(self.driver, 20).until(\n # EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div/div/div[2]/div/div[1]/div/div[1]/div/div/div/div/div[3]/div[4]/div[2]/div[1]/div/div/div/div[10]/div/div/div[1]/select/option[1]')))\n # quantity.click()\n # walmartACOBtn = WebDriverWait(self.driver, 20).until(\n # EC.element_to_be_clickable((By.XPATH, '/ html/body/div[1]/div/div/div[2]/div/div[1]/div/div[1]/div/div/div/div/div[3]/div[4]/div[2]/div[1]/div/div/div/div[10]/div/div/div[2]/button'))\n # walmartACOBtn.click()\n\n def init_driver(self):\n chrome_options = Options()\n if os.environ['POPENV'] == \"dev\":\n print('Not Setting Headless for Development Purposes')\n elif os.environ['POPENV'] == \"stg\":\n print(\"Will run checkout process without headless chrome option enabled\")\n elif os.environ['POPENV'] == \"prd\":\n chrome_options.add_argument(\"--headless\")\n chrome_options.add_argument(\"--credentials_enable_service=false\")\n chrome_options.add_argument(\"--profile.password_manager_enabled=false\")\n chrome_options.add_argument(\"--no-sandbox\")\n chrome_options.add_argument(\"--credentials_enable_service=false\")\n chrome_options.add_argument('--no-default-browser-check')\n chrome_options.add_argument('--disable-gpu')\n chrome_options.add_argument('--disable-extensions')\n chrome_options.add_argument('--disable-default-apps')\n\n # Rasberry Pi Support\n if get_distro() == \"Linux\":\n driver = webdriver.Chrome(executable_path=config.DRIVER_LOCATION, chrome_options=chrome_options)\n driver.wait = WebDriverWait(driver, 3)\n _LOG.info('Initialized Chrome Driver.')\n return driver\n # Windows Support\n elif get_distro() == \"Windows\":\n driver = webdriver.Chrome(executable_path=config.DRIVER_LOCATION, chrome_options=chrome_options)\n driver.wait = WebDriverWait(driver, 3)\n _LOG.info('Initialized Chrome Driver.')\n return driver\n # Darwin AKA: macOS Support\n else:\n driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)\n driver.wait = WebDriverWait(driver, 3)\n _LOG.info('Initialized Chrome Driver.')\n return driver\n\n def check_funko(self, site, url):\n status = False\n\n _LOG.info('Checking: {0}'.format(site + \" \" + url))\n\n if site in ['hottopic', 'boxlunch']:\n status = self.in_stock(site, url)\n elif site in ['walmart', 'barnesandnoble', 'gamestop', 'blizzard', 'geminicollectibles', 'hbo']:\n status = self.add_to_cart(site, url)\n elif site in ['target']:\n status = self.out_of_stock(site, url)\n\n # Report from Bot When in Stock\n if status:\n msg = site + \" - In Stock: \" + \":\\n\" + url\n self.UPDATER.bot.send_message(chat_id=config.TELEGRAM_CHAT_ID,\n text=msg)\n\n # Setting Timout for Search Item\n url_md5 = hashlib.md5(url.encode('utf-8')).hexdigest()\n # When set prevents lookup until TIMEOUT Expires\n self.TIMEOUT[url_md5] = datetime.today().date()\n _LOG.info('Timeout Set: {0}'.format(url_md5))\n\n if site in ['hottopic', 'boxlunch']:\n # Adds Item to the Cart\n self.driver.get(url)\n # Check if Pop Overlay Exists\n popup = self.driver.find_elements_by_xpath('//*[@id=\"acsFocusFirst\"]')\n\n # Logic to Close Pop when it does exist\n for popupCloseBtn in popup:\n popInnerText = popupCloseBtn.get_attribute('innerText')\n if popInnerText:\n print('Pop Found Initiating Closer of Pop Up')\n # Pop Up Found and Needs to be Dismissed\n popup.click()\n else:\n self.driver.refresh()\n\n # TODO: Add Quantity Input for the Check Funko Function\n # A. This will also dictate the original message sent to channel\n # B. This will dictate number to buy\n # NOTE: May want to run multiple instances and buy in singles.\n # Setup Quantity Sudo Dynamic\n if os.environ['POPENV'] == \"dev\":\n amount = \"1\"\n quantitySelectorString = '//*[@id=\"Quantity\"]/option[' + amount + ']'\n elif os.environ['POPENV'] == \"stg\":\n amount = \"3\"\n quantitySelectorString = '//*[@id=\"Quantity\"]/option[' + amount + ']'\n elif os.environ['POPENV'] == \"prd\":\n amount = \"5\"\n quantitySelectorString = '//*[@id=\"Quantity\"]/option[' + amount + ']'\n # Select Quantity\n quantity = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, quantitySelectorString)))\n quantity.click()\n # Add to Cart Button\n atcBtn = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, '//button[contains(string(), \"Add to Bag\")]')))\n atcBtn.click()\n # Logic to Decide Sites Cart Link\n if site in ['hottopic']:\n cartLink = \"https://www.hottopic.com/cart\"\n # Checkout Button\n self.driver.get(cartLink)\n # Function to do Checkout Process\n self.ht_bl_checkout_process(site)\n # Check if Pop Overlay Exists Again\n # This is to allow for Clean Order Screenshot\n popup = self.driver.find_elements_by_xpath('//*[@id=\"acsFocusFirst\"]')\n\n # Logic to Close Pop when it does exist\n for popupCloseBtn in popup:\n popInnerText = popupCloseBtn.get_attribute('innerText')\n if popInnerText:\n print('Pop Found Initiating Closer of Pop Up')\n # Pop Up Found and Needs to be Dismissed\n popup.click()\n else:\n self.driver.refresh()\n # Take Screen Shot of Order\n self.driver.save_screenshot(\"order.png\")\n self.UPDATER.bot.send_message(chat_id=config.TELEGRAM_CHAT_ID,\n text=\"Checkout was SUCCESSFUL! Order Screenshot Below\")\n self.UPDATER.bot.send_photo(chat_id=config.TELEGRAM_CHAT_ID, photo=open('./order.png', 'rb'))\n # Quit After Checkout\n self.driver.quit()\n # Remove Order Image from Disk\n subprocess.Popen('rm -rf ./order.png', shell=True, stdout=subprocess.PIPE)\n elif site in ['boxlunch']:\n cartLink = \"https://www.boxlunch.com/cart\"\n # Checkout Button\n self.driver.get(cartLink)\n # Function to do Checkout Process\n self.ht_bl_checkout_process(site)\n # Check if Pop Overlay Exists Again\n # This is to allow for Clean Order Screenshot\n popup = self.driver.find_elements_by_xpath('//*[@id=\"acsFocusFirst\"]')\n\n # Logic to Close Pop when it does exist\n for popupCloseBtn in popup:\n popInnerText = popupCloseBtn.get_attribute('innerText')\n if popInnerText:\n print('Pop Found Initiating Closer of Pop Up')\n # Pop Up Found and Needs to be Dismissed\n popup.click()\n else:\n self.driver.refresh()\n # Take Screen Shot of Order\n self.driver.save_screenshot(\"order.png\")\n self.UPDATER.bot.send_message(chat_id=config.TELEGRAM_CHAT_ID,\n text=\"Checkout was SUCCESSFUL! Order Screenshot Below\")\n self.UPDATER.bot.send_photo(chat_id=config.TELEGRAM_CHAT_ID, photo=open('./order.png', 'rb'))\n # Quit After Checkout\n self.driver.quit()\n # Remove Order Image from Disk\n subprocess.Popen('rm -rf ./order.png', shell=True, stdout=subprocess.PIPE)\n elif site in ['walmart', 'barnesandnoble', 'gamestop', 'blizzard', 'geminicollectibles', 'hbo']:\n # Checkout Process for Other Sites\n if site in ['hbo']:\n self.hbo_checkout_process()\n # elif site in ['walmart']:\n # self.walmart_checkout_process()\n else:\n print(\"Still Work In Progress - Site(s): B&N, Gamestop, Blizzard, Gemini Collectibles\")\n elif site in ['target']:\n print(\"Still Work In Progress - Site(s): Target\")\n\n\n def set_cookies(self):\n self.driver.get('https://www.hottopic.com')\n self.driver.get('https://www.boxlunch.com')\n\n def pop_search(self, sleep_interval=2):\n self.set_cookies()\n # Set Bot to Auto Start\n self.THREAD_ALIVE = True\n # Start Infinite Loop to Check if Funko Pop is Available\n while True:\n # Load in items from pops.json\n if self.THREAD_ALIVE:\n with portalocker.Lock(config.FUNKO_POP_LIST, \"r\", timeout=10) as data_file:\n funkopop_links = json.load(data_file)\n\n for funko in funkopop_links:\n url_md5 = hashlib.md5(funko['url'].encode('utf-8')).hexdigest()\n try:\n if url_md5 not in self.TIMEOUT:\n self.check_funko(funko['store'], funko['url'])\n elif url_md5 in self.TIMEOUT and self.TIMEOUT[url_md5] < datetime.today().date():\n if datetime.now().hour > 7:\n self.check_funko(funko['store'], funko['url'])\n except Exception as excp:\n _LOG.error('Exception {0}'.format(excp))\n import traceback\n traceback.print_exc()\n\n time.sleep(sleep_interval)\n\n def in_stock(self, site, url):\n self.driver.get(url)\n\n try:\n inStock = self.driver.wait.until(\n EC.presence_of_element_located((By.CLASS_NAME, HTML_OBJ[site])))\n except TimeoutException:\n _LOG.error('Failed to locate element for \"In Stock\".')\n return False\n\n if inStock and inStock.text.lower() == \"in stock\":\n return True\n\n return False\n\n def out_of_stock(self, site, url):\n self.driver.get(url)\n\n try:\n outOfStock = self.driver.wait.until(\n EC.presence_of_element_located((By.CLASS_NAME, HTML_OBJ[site])))\n except TimeoutException:\n _LOG.error('Failed to locate element for \"Out of Stock\".')\n return False\n\n if outOfStock and \"out of stock\" in outOfStock.text.lower():\n return False\n\n return True\n\n def add_to_cart(self, site, url):\n response = False\n self.driver.get(url)\n\n try:\n if site == 'blizzard':\n addToCart = self.driver.wait.until(\n EC.presence_of_element_located((By.ID, HTML_OBJ[site])))\n elif site == 'hbo':\n addToCart = self.driver.wait.until(\n EC.presence_of_element_located((By.ID, HTML_OBJ[site])))\n else:\n addToCart = self.driver.wait.until(\n EC.presence_of_element_located((By.CLASS_NAME, HTML_OBJ[site])))\n except TimeoutException:\n _LOG.warning('Failed to locate element for \"Add to Cart\".')\n return False\n\n if addToCart and addToCart.text.lower() == \"add to cart\":\n response = True\n elif addToCart and addToCart.get_attribute('value') in [\"ADD TO CART\", \"Add To Cart\"]:\n response = True\n\n return response\n","sub_path":"popwatch/storeStock.py","file_name":"storeStock.py","file_ext":"py","file_size_in_byte":24010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"224735711","text":"import cv2\nimport os\nimport glob\nfrom matplotlib.pyplot import imread\ndata_dir = \"/home/atipa/Project/motionArtifact/motionArtRed/Motion_Artifact/data/gt\"\ndata_path = os.path.join(data_dir,'*g')\nfiles = glob.glob(data_path)\ndef load_images_from_folder(folder):\n images = []\n for filename in os.listdir(folder):\n img = imread(os.path.join(folder,filename))\n if img is not None:\n images.append(img)\n return images\nimages = load_images_from_folder(data_dir)\n#Load data set\ndef read_dataset(path):\n images_path = f\"{data_dir}/images\"\n labels_path = f\"{data_dir}/labels\"\n\n images = np.zeros((320, 180, 180))\n labels = np.zeros((320, 180, 180))\nimages_train = np.zeros((320, 180, 180))\nlabels_train = np.zeros((320, 180, 180))\nfor i in range(320):\n img_file_path = f\"sample_data/train/noisy/{i+1}.png\"\n lbl_file_path = f\"sample_data/train/groundtruth/{i+1}.png\"\n \n images_train[i] = imread(img_file_path)\n labels_train[i] = imread(lbl_file_path)\nimages_test = np.zeros((80, 180, 180))\nlabels_test = np.zeros((80, 180, 180))\nfor i in range(321,400):\n img_file_path = f\"sample_data/test/noisy/{i}.png\"\n lbl_file_path = f\"sample_data/test/groundtruth/{i}.png\"\n \n images_test[i] = imread(img_file_path)\n labels_test[i] = imread(lbl_file_path)\ntrain_groundtruth_path = 'sample_data/train/groundtruth'\ntrain_noisy_path = 'sample_data/train/noisy'\n\ntest_groundtruth_path = 'sample_data/test/groundtruth'\ntest_noisy_path = 'sample_data/test/noisy'\n\ntrain_label = os.listdir(train_groundtruth_path)\ntrain_input = os.listdir(train_noisy_path)\n\ntest_label = os.listdir(test_groundtruth_path)\ntest_input = os.listdir(test_noisy_path)\n","sub_path":"temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"614049836","text":"# -*- coding: utf-8 -*-\n\"\"\"\nWrite a function that takes a string as input and reverse only the vowels of a string.\n\"\"\"\ndef reverseVowels(s):\n vowels = 'aeiouAEIOU'\n left = 0 \n right = len(s)-1\n s = list (s)\n while left < right:\n if s[left] in vowels and s[right] in vowels:\n s[left], s[right] = s[right], s[left]\n left += 1\n right -=1\n elif s[left] in vowels:\n right -=1\n elif s[right] in vowels:\n left +=1\n else:\n right -=1\n left +=1\n return \"\".join(s)\n\nreverseVowels(\"leetcode\")","sub_path":"Leetcode/345_Reverse_Vowels_of_a_String.py","file_name":"345_Reverse_Vowels_of_a_String.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"383191965","text":"\nfrom django import template\n\nregister = template.Library()\n\n@register.filter\ndef add_space(word):\n \"\"\"this will add a new space like NewConfirmed to New Confirmed\"\"\"\n if word.startswith(\"N\"):\n word = word[:3] + \" \" + word[3:]\n return word\n else:\n word = word[:5] + \" \" + word[5:]\n return word\n\n@register.filter\ndef increment(color_list,index_value):\n \"\"\"this will return the list with specified index\"\"\"\n return color_list[index_value]\n\n@register.filter\ndef format_date(date):\n \"\"\"this is will format data like 2021-02-27T00:00:00Z to 2021-02-27\"\"\"\n get_index = date.index('T')\n new_date = date[:get_index]\n return new_date\n","sub_path":"Covid_19_App/templatetags/custom_filters.py","file_name":"custom_filters.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"458242512","text":"import array\nimport random\n\nimport numpy\n\nfrom deap import algorithms\nfrom deap import base\nfrom deap import creator\nfrom deap import tools\nimport math\nimport copy\nfrom .simulator import Simulator\n\n\nclass GA1:\n def __init__(self, params):\n self.crossover = copy.deepcopy(params[\"crossover\"])\n self.mutate = copy.deepcopy(params[\"mutate\"])\n self.select = copy.deepcopy(params[\"select\"])\n self.population = params[\"populationGA1\"]\n self.numGeneration = params[\"numGeneration1\"]\n self.crossroads = params[\"crossroads\"]\n self.timeSteps = params[\"timeSteps\"]\n minLim = params[\"minLim\"]\n maxLim = params[\"maxLim\"]\n self.numIndividuals = params[\"numIndividuals1\"]\n self.simulator = params[\"simulator\"]\n self.fitness = params[\"fitnessGA1\"]\n creator.create(\"FitnessMin\", base.Fitness, weights=(-1.0,))\n creator.create(\"Individual\", array.array, typecode='b',\n fitness=creator.FitnessMin)\n\n self.toolbox = base.Toolbox()\n\n # Attribute generator\n self.toolbox.register(\"random\", random.randint, minLim, maxLim)\n\n # Structure initializers\n self.toolbox.register(\"individual\", tools.initRepeat, creator.Individual,\n self.toolbox.random, self.crossroads*self.timeSteps)\n self.toolbox.register(\"small_individual\", tools.initRepeat,\n creator.Individual, self.toolbox.random, self.crossroads)\n self.toolbox.register(\"population\", tools.initRepeat,\n list, self.toolbox.individual)\n self.toolbox.register(\n \"small_population\", tools.initRepeat, list, self.toolbox.small_individual)\n self.toolbox.register(\"mate\", self.crossover[\"operator\"])\n del self.crossover[\"operator\"]\n self.toolbox.register(\"mutate\", self.mutate[\"operator\"])\n del self.mutate[\"operator\"]\n self.toolbox.register(\"select\", self.select[\"operator\"])\n del self.select[\"operator\"]\n self.toolbox.register(\"selectBest\", tools.selBest)\n\n def fitnessFunction(self, population):\n self.simulator.clear()\n fitnesses = [(3, )]*self.numIndividuals\n signals = numpy.ndarray(\n (self.numIndividuals, self.timeSteps, self.crossroads), dtype=numpy.uint8)\n for individual in range(self.numIndividuals):\n for timeStep in range(self.timeSteps):\n timings = population[individual][self.crossroads *\n timeStep:self.crossroads*(timeStep+1)]\n signals[individual][timeStep] = timings\n if self.fitness == \"1\":\n fitnesses = self.simulator.getFitness1(signals, rm=True)\n elif self.fitness == \"2\":\n fitnesses = self.simulator.getFitness2(signals, rm=True)\n for ind, fit in zip(population, fitnesses):\n print(ind, fit)\n ind.fitness.values = fit\n return fitnesses\n\n def getTimings(self, timeStep):\n signalTimings = self.toolbox.small_population(n=self.numIndividuals)\n index = 0\n for individual in self.population:\n temp = individual[self.crossroads *\n timeStep:self.crossroads*(timeStep+1)]\n small_individual = self.toolbox.small_individual()\n for i in range(len(temp)):\n small_individual[i] = temp[i]\n signalTimings[index] = small_individual\n index += 1\n return signalTimings\n\n def getDensities(self, timeStep):\n pass\n\n def makePopulation(self, bestIndividuals):\n offspring = self.toolbox.population(n=self.numIndividuals)\n index = 0\n for child1 in bestIndividuals:\n for child2 in bestIndividuals:\n temp1 = child1.__deepcopy__({})\n temp2 = child2.__deepcopy__({})\n if(temp1 == temp2):\n offspring[index] = temp1\n index += 1\n else:\n params_crossover = copy.deepcopy(self.crossover)\n params_crossover[\"ind1\"] = temp1\n params_crossover[\"ind2\"] = temp2\n self.toolbox.mate(**params_crossover)\n del params_crossover\n offspring[index] = temp1\n offspring[index+1] = temp2\n index += 2\n if (index >= len(offspring)-2):\n break\n if (index >= len(offspring)-2):\n break\n# for mutant in offspring:\n## params_mutate = copy.deepcopy(self.mutate)\n## params_mutate[\"individual\"] = mutant\n# self.toolbox.mutate(**params_mutate)\n## del params_mutate\n return offspring\n\n def selectIndividuals(self, pop):\n params_select = copy.deepcopy(self.select)\n params_select[\"individuals\"] = pop\n bestIndividual = self.toolbox.selectBest(k=1, individuals=pop)\n bestIndividuals = self.toolbox.select(**params_select)\n bestIndividuals[0] = bestIndividual[0]\n print(\"Selected individuals:\")\n print(bestIndividuals)\n del params_select\n return bestIndividuals\n\n def printStats(self, worst, pop, generation):\n length = len(pop)\n fits = [ind.fitness.values[0] for ind in pop]\n mean = sum(fits) / length\n sum2 = sum(x*x for x in fits)\n std = abs(sum2 / length - mean**2)**0.5\n improvement = ((worst-min(fits))*100)/worst\n bestFitness = min(fits)\n toPrint = \"-\"*30\n toPrint += (\"\\nGeneration %s statistics\" % str(generation+1))\n toPrint += (\"\\n Min: %s\" % min(fits))\n toPrint += (\"\\n Max: %s\" % max(fits))\n toPrint += (\"\\n Avg: %s\" % mean)\n toPrint += (\"\\n Std: %s\" % std)\n toPrint += (\"\\n Improvement: %s \\n\" % improvement)\n toPrint += (\"-\"*30)\n return toPrint\n\n def removeDuplicates(self, pop):\n toRemove = []\n for i in range(len(pop)):\n for j in range(len(pop)):\n if i != j and i not in toRemove and j not in toRemove:\n matches = len(\n [a for a, b in zip(pop[i], pop[j]) if a == b])\n if (matches*100)/(self.crossroads*self.timeSteps) > 70:\n toRemove.append(j)\n toRemove.sort(reverse=True)\n print(toRemove)\n for j in range(len(toRemove)):\n del pop[toRemove[j]]\n return pop\n\n def run(self):\n if self.population is None:\n pop = self.toolbox.population(n=self.numIndividuals)\n else:\n pop = self.population\n\n fitnesses = self.fitnessFunction(pop)\n\n results = \"\"\n bestFitnesses = []\n\n worst = min([ind.fitness.values[0] for ind in pop])\n bestFitness = 0\n bestIndividuals = None\n\n for generation in range(self.numGeneration):\n results += self.printStats(worst, pop, generation)\n## pop = self.removeDuplicates(pop)\n bestIndividuals = self.selectIndividuals(pop)\n bestFitnesses.append(bestIndividuals[0].fitness.values[0])\n if (generation == self.numGeneration-1):\n break\n offspring = self.makePopulation(bestIndividuals)\n fitnesses = self.fitnessFunction(offspring)\n pop[:] = offspring\n fits = [ind.fitness.values[0] for ind in pop]\n self.population = pop\n return bestFitnesses, results, bestIndividuals\n","sub_path":"traffic/genetic_algorithm/long.py","file_name":"long.py","file_ext":"py","file_size_in_byte":7630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"415126974","text":"\n\"\"\"\nWrap the Lame encoder shared library using the CTypes module. The Lame library should\nbe installed with: \n\n Using ~2,477 kB:\n\n sudo apt install lame \n \n Or using ~1,063 kB:\n\n sudo apt install libmp3lame-dev\n\n Or using ~ 478 kB:\n\n sudo apt install libmp3lame0\n\"\"\"\n\nimport ctypes\nfrom ctypes.util import find_library\n\nSTEREO = int(0)\nJOINT_STEREO = int(1)\nMONO = int(3)\n\n# Load the library\n_lib = ctypes.CDLL(find_library('mp3lame'))\nif _lib == None:\n raise ImportError('Unable to load shared library: mp3lame')\n\n# Init. The default is a Joint-Stereo, 44.1khz, 128kbps CBR at Quality 5\n_lib.lame_init.argtypes = []\n_lib.lame_init.restype = ctypes.c_void_p\n# Get a pointer to the internal Global Flags structure\n_gfp = _lib.lame_init()\n\n\ndef init_parameters():\n \"\"\"\n Apply the settings in the global flags. MUST be invoked before encoding!!!\n \"\"\"\n _lib.lame_init_params.argtypes = [ctypes.c_void_p]\n _lib.lame_init_params.restype = ctypes.c_int\n _lib.lame_init_params(_gfp)\n\n\ndef get_version():\n \"\"\"\n Return the version number of libmp3lame.so/dll as a string.\n \"\"\"\n _lib.get_lame_version.argtypes = []\n _lib.get_lame_version.restype = ctypes.c_char_p\n return _lib.get_lame_version().decode('ascii')\n\n\ndef set_sample_rate(sample_rate):\n \"\"\"\n Tell lame what sample rate the PCM buffer was encoded at. Default is 44100hz.\n \"\"\"\n _lib.lame_set_in_samplerate.argtypes = [ctypes.c_void_p, ctypes.c_int]\n _lib.lame_set_in_samplerate.restype = ctypes.c_int\n _lib.lame_set_in_samplerate(_gfp, sample_rate)\n\n\ndef get_sample_rate():\n \"\"\"\n Return the current sample setting from Lame's global flags.\n \"\"\"\n _lib.lame_get_in_samplerate.argtypes = [ctypes.c_void_p]\n _lib.lame_get_in_samplerate.restype = ctypes.c_int\n return _lib.lame_get_in_samplerate(_gfp)\n\n\ndef set_num_channels(chan_count):\n \"\"\"\n Set the number of channels, 1 = mono, 2 = stereo. Stereo is not currently working.\n \"\"\"\n _lib.lame_set_num_channels.argtypes = [ctypes.c_void_p, ctypes.c_int]\n _lib.lame_set_num_channels.restype = ctypes.c_int\n _lib.lame_set_num_channels(_gfp, chan_count)\n\n\ndef get_num_channels():\n \"\"\"\n Return the current number of channels from Lame's global flags.\n \"\"\"\n _lib.lame_get_num_channels.arttypes = [ctypes.c_void_p]\n _lib.lame_get_num_channels.restype = ctypes.c_int\n return _lib.lame_get_num_channels(_gfp)\n\n\ndef set_mode(mode):\n \"\"\"\n Set the encoding mode; 0 = Stereo, 1 = Joint Stereo, 3 = Mono.\n Mode 2 (dual channel) is not supported by Lame.\n \"\"\"\n _lib.lame_set_mode.argtypes = [ctypes.c_void_p, ctypes.c_int]\n _lib.lame_set_mode.restype = ctypes.c_int\n _lib.lame_set_mode(_gfp, mode)\n\n\ndef get_mode():\n \"\"\"\n Return the encoding mode from Lame's global flags.\n \"\"\"\n _lib.lame_get_mode.argtypes = [ctypes.c_void_p]\n _lib.lame_get_mode.restype = ctypes.c_int\n return _lib.lame_get_mode(_gfp)\n\n\ndef set_bit_rate(bit_rate):\n \"\"\"\n Set the encoding bit rate (in Khz). Default is 128.\n Probably the most important Lame setting as the encoder will overrride other settings to comply.\n \"\"\"\n _lib.lame_set_brate.argtypes = [ctypes.c_void_p]\n _lib.lame_set_brate.restype = ctypes.c_int\n _lib.lame_set_brate(_gfp, bit_rate)\n\n\ndef get_bit_rate():\n \"\"\"\n Return the encoding bit rate (in Khz) from Lame's global flags.\n \"\"\"\n _lib.lame_get_brate.argtypes = [ctypes.c_void_p]\n _lib.lame_get_brate.restype = ctypes.c_int\n return _lib.lame_get_brate(_gfp)\n\n\ndef set_quality(quality):\n \"\"\"\n Set the quality on the encoding process 0 - 9. Lower is better quality.\n This is about encoding speed, not file size. Default is 5.\n \"\"\"\n if quality < 0 or quality > 9:\n raise ValueError('Quality must be 0-9.')\n _lib.lame_set_quality.argtypes = [ctypes.c_void_p]\n _lib.lame_set_quality.restype = ctypes.c_int\n _lib.lame_set_quality(_gfp, quality)\n\n\ndef get_quality():\n \"\"\"\n Return the encoding quality from Lame's global flags.\n \"\"\"\n _lib.lame_get_quality.argtypes = [ctypes.c_void_p]\n _lib.lame_get_quality.restype = ctypes.c_int\n return _lib.lame_get_quality(_gfp)\n\n\ndef encode_buffer_interleaved(pcm_data):\n \"\"\"\n I am a broken monster that will kill your eardrums.\n \"\"\"\n _lib.lame_encode_buffer_interleaved.argtypes = [ctypes.c_void_p, ctypes.c_void_p,\n ctypes.c_int, ctypes.POINTER(ctypes.c_char), ctypes.c_int]\n _lib.lame_encode_buffer_interleaved.restype = ctypes.c_int\n num_samples = int(len(pcm_data) / 2)\n mp3buffer_size = int(1.25 * num_samples + 7200)\n mp3buffer = (ctypes.c_char * mp3buffer_size)()\n mp3buffer_used = _lib.lame_encode_buffer_interleaved(\n _gfp, pcm_data, num_samples, mp3buffer, mp3buffer_size)\n print(mp3buffer_used)\n return mp3buffer[0:int(mp3buffer_used)]\n\n\ndef encode_buffer(pcm_data):\n \"\"\"\n Given a buffer of 16 bit PCM data, encode it to a block of MP3. \n Currently, I only work in mono.\n \"\"\"\n _lib.lame_encode_buffer.argtypes = [ctypes.c_void_p, ctypes.c_void_p,\n ctypes.c_void_p, ctypes.c_int, ctypes.POINTER(ctypes.c_char), ctypes.c_int]\n _lib.lame_encode_buffer.restype = ctypes.c_int\n num_samples = int(len(pcm_data) / 2) # 16 bits per Sample\n mp3buffer_size = int(1.25 * num_samples + 7200)\n mp3buffer = (ctypes.c_char * mp3buffer_size)()\n # Seems hacky to pass the same PCM data in both channels but the second\n # channel seems to be mandatory even when mono encoding from mono sources.\n # Looking at the lame header, it appears that Lame averages both into a mono channel.\n mp3buffer_used = _lib.lame_encode_buffer(\n _gfp, pcm_data, pcm_data, num_samples, mp3buffer, mp3buffer_size)\n # print(mp3buffer_used)\n return mp3buffer[0:mp3buffer_used]\n\n\ndef encode_flush():\n \"\"\"\n Flush the encoding buffers and return final frames (if any).\n \"\"\"\n _lib.lame_encode_flush.argtypes = [\n ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int]\n _lib.lame_encode_flush.restype = ctypes.c_int\n mp3buffer = (ctypes.c_char * 7200)()\n mp3buffer_used = _lib.lame_encode_flush(_gfp, mp3buffer, int(7200))\n # print(mp3buffer_used)\n return mp3buffer[0:mp3buffer_used]\n\n\ndef close():\n \"\"\"\n Free internal data structures.\n \"\"\"\n _lib.lame_close.restype = ctypes.c_int\n _lib.lame_close.argtypes = [ctypes.c_void_p]\n _lib.lame_close(_gfp)\n","sub_path":"solame/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"416951071","text":"#!/usr/bin/python3\r\n\r\n# Import Libraries\r\n#from openpyxl import load_workbook\r\nimport csv\r\nimport os\r\n#import requests\r\nimport urllib\r\nimport cgi\r\nimport re\r\n#import urllib.request\r\n#from urllib.request import urlopen\r\n#from urllib.request import urlretrieve\r\nimport base64\r\nimport uuid\r\nimport http.client\r\nfrom http.client import HTTPSConnection\r\nimport json\r\nfrom datetime import datetime, date, timedelta\r\nimport dateutil\r\nfrom dateutil import parser\r\nfrom dateutil.parser import parse\r\nimport couchdb\r\n\r\n# Global Variables\r\nunplannedIncidents_list = []\r\ncurrentImpactsID_list = []\r\ncgwImpact_list = []\r\nrowList_list = []\r\n\r\n# Current Incident Variables\r\ncurrentCustomer = \"-\"\r\ncurrentEventDuration = \"-\"\r\ncurrentEventStart = \"-\"\r\ncurrentEventEnd = \"-\"\r\ncurrentReason = \"-\"\r\ncurrentStatus = \"-\"\r\ncurrentArea = \"-\"\r\n#global lastUpdate\r\nlastUpdate = \"-\"\r\n\r\n# Database setup\r\ncouch = couchdb.client.Server('http://tailsdb.vocusgroup.co.nz:5984')\r\ntailsDB = couch['tails']\r\noutageDB = couch['outage']\r\nservicesDB = couch['services']\r\n\r\n# Chorus Events Overview Pull\r\ndef vocusOverview(event_id):\r\n # Generate X-ID\r\n xID = uuid.uuid4()\r\n # Encode userID and client secret\r\n encode = base64.b64encode(b'9ddf0e5cebee45d89458ef782ce73d2e:2f70008670Ac4a409e7811468459b859')\r\n\r\n headers = {'Authorization': 'basic' + str(encode), 'X-Transaction-Id': str(xID)}\r\n\r\n # This sets up the https connection\r\n conn = http.client.HTTPSConnection(\"api.chorus.co.nz\")\r\n\r\n conn.request('GET', '/network-events/v1/events/'+event_id, headers=headers)\r\n\r\n res = conn.getresponse()\r\n\r\n data = res.read()\r\n #print(res.status, res.reason)\r\n #print(data.decode('utf-8'))\r\n #print(res.getheaders())\r\n jsonParsed = json.loads(data.decode('utf-8'))\r\n global currentEvent\r\n currentEvent = event_id\r\n if res.status == 404:\r\n print(\"No Vocus Impact\")\r\n ## Needed for table\r\n global currentEventDuration\r\n currentEventDuration = \"N/A\"\r\n global currentEventStart\r\n currentEventStart = \"N/A\"\r\n global currentEventEnd\r\n currentEventEnd = \"N/A\"\r\n global currentReason\r\n currentReason = \"N/A\"\r\n #start_List.append(dateConverter(currentEventStart))\r\n #start_List.append(currentEventStart)\r\n #end_List.append(dateConverter(currentEventEnd))\r\n #end_List.append(currentEventEnd)\r\n #duration_List.append(currentEventDuration)\r\n #reason_List.append(currentReason)\r\n\r\n else:\r\n currentEventDuration = jsonParsed[\"outageDuration\"]\r\n currentEventStart = dateConverter(jsonParsed[\"startTime\"]) #convert date/time\r\n currentEventEnd = dateConverter(jsonParsed[\"endTime\"]) #convert date/time\r\n currentReason = jsonParsed[\"updates\"]\r\n global currentStatus\r\n currentStatus = jsonParsed[\"status\"]\r\n #currentNetworkImpactSummary = jsonParsed[\"networkImpactSummary\"]\r\n global currentArea\r\n currentArea = jsonParsed[\"networkImpactSummary\"][0][\"location\"] ## Won't work for events an multiple locations. Will use this for now.\r\n\r\ndef vocusUnplanned():\r\n # Generate X-ID\r\n xID = uuid.uuid4()\r\n # Encode userID and client secret\r\n encode = base64.b64encode(b'9ddf0e5cebee45d89458ef782ce73d2e:2f70008670Ac4a409e7811468459b859')\r\n\r\n headers = {'Authorization': 'basic' + str(encode), 'X-Transaction-Id': str(xID)}\r\n\r\n # This sets up the https connection\r\n conn = http.client.HTTPSConnection(\"api.chorus.co.nz\")\r\n\r\n conn.request('GET', '/network-events/v1/events/', headers=headers)\r\n\r\n res = conn.getresponse()\r\n\r\n #Output\r\n data = res.read()\r\n #print(res.status, res.reason)\r\n #print(data.decode('utf-8'))\r\n #print(res.getheaders())\r\n\r\n jsonParsed = json.loads(data.decode('utf-8'))\r\n\r\n for i in jsonParsed:\r\n if i[\"eventType\"] == \"Unplanned\":\r\n startDate = i[\"startTime\"]\r\n datetime_object_start = datetime.strptime(startDate, '%Y-%m-%dT%H:%M:%S+12:00')\r\n datetime_object_past = datetime.now() - timedelta(days=1)\r\n if(datetime_object_start > datetime_object_past ):\r\n unplannedIncidents_list.append(i[\"eventId\"])\r\n #print(i[\"eventId\"])\r\n #print(datetime_object)\r\n #print(i[\"eventType\"]+\" \"+i[\"eventId\"])\r\n #print(i[\"eventId\"])\r\n\r\ndef vocusImpacts(event_id):\r\n # Generate X-ID\r\n xID = uuid.uuid4()\r\n # Encode userID and client secret\r\n encode = base64.b64encode(b'9ddf0e5cebee45d89458ef782ce73d2e:2f70008670Ac4a409e7811468459b859')\r\n\r\n headers = {'Authorization':'basic'+str(encode), 'X-Transaction-Id':str(xID)}\r\n #headers = {'Basic OWRkZjBlNWNlYmVlNDVkODk0NThlZjc4MmNlNzNkMmU6MmY3MDAwODY3MEFjNGE0MDllNzgxMTQ2ODQ1OWI4NTk=': '', '14878r9hkjabdnfkajnfvp01834': ''}\r\n\r\n # This sets up the https connection\r\n #conn = http.client.HTTPSConnection(\"api.sandbox.chorus.co.nz\")\r\n conn = http.client.HTTPSConnection(\"api.chorus.co.nz\")\r\n\r\n # then connect\r\n # Impact Download\r\n conn.request('GET','/network-events/v1/events/'+event_id+'/impactDownload?organisation=Vocus+Communications+Ltd&impactType=Direct', headers=headers)\r\n # Impact\r\n #conn.request('GET', '/network-events/v1/events/INC000003709818/impact', headers = headers)\r\n\r\n # get the response back\r\n res = conn.getresponse()\r\n\r\n # Output\r\n data = res.read()\r\n #print(res.status, res.reason)\r\n #print(data.decode('utf-8'))\r\n #print(res.getheaders())\r\n\r\n output = str(data.decode('utf-8'))\r\n output2 = output.replace(\",\", \" \")\r\n\r\n # Add to CurrentImpacts List\r\n if data.decode('utf-8') != '':\r\n for i,line in enumerate(output2.splitlines()):\r\n #print(line)\r\n if i != 0:\r\n for i2,word in enumerate(line.split()):\r\n if i2 == 0:\r\n currentImpactsID_list.append(stripID(word))\r\n #print(word)\r\n break\r\n\r\ndef fxNetworksImpacts(event_id):\r\n # Generate X-ID\r\n xID = uuid.uuid4()\r\n # Encode userID and client secret\r\n encode = base64.b64encode(b'78d96f4de7084c45ba9c60b6d1a717b1:328eD749f184463f9a492DABF924614f')\r\n\r\n headers = {'Authorization':'basic'+str(encode), 'X-Transaction-Id':str(xID)}\r\n\r\n # This sets up the https connection\r\n # conn = http.client.HTTPSConnection(\"api.sandbox.chorus.co.nz\")\r\n conn = http.client.HTTPSConnection(\"api.chorus.co.nz\")\r\n\r\n # then connect\r\n # Impact Download\r\n conn.request('GET','/network-events/v1/events/'+event_id+'/impactDownload?organisation=FX+Networks+Ltd&impactType=Direct', headers=headers)\r\n #conn.request('GET', '/network-events/v1/events/'+event_id+'/impact', headers=headers)\r\n\r\n # get the response back\r\n res = conn.getresponse()\r\n\r\n # Output\r\n data = res.read()\r\n #print(res.status, res.reason)\r\n #print(data.decode('utf-8'))\r\n #print(res.getheaders())\r\n\r\n output = str(data.decode('utf-8'))\r\n output2 = output.replace(\",\", \" \")\r\n\r\n # Add to CurrentImpacts List\r\n if data.decode('utf-8') != '':\r\n for i, line in enumerate(output2.splitlines()):\r\n # print(line)\r\n if i != 0:\r\n for i2, word in enumerate(line.split()):\r\n if i2 == 0:\r\n currentImpactsID_list.append(stripID(word))\r\n # print(word)\r\n break\r\n\r\ndef maxnetImpacts(event_id):\r\n # Generate X-ID\r\n xID = uuid.uuid4()\r\n # Encode userID and client secret\r\n encode = base64.b64encode(b'8e6550a89af740439ab963f7c9dd3d3e:51a898F04B49420792f462c0B272672D')\r\n\r\n headers = {'Authorization': 'basic' + str(encode), 'X-Transaction-Id': str(xID)}\r\n\r\n # This sets up the https connection\r\n # conn = http.client.HTTPSConnection(\"api.sandbox.chorus.co.nz\")\r\n conn = http.client.HTTPSConnection(\"api.chorus.co.nz\")\r\n\r\n # then connect\r\n # Impact Download\r\n conn.request('GET',\r\n '/network-events/v1/events/' + event_id + '/impactDownload?organisation=Maxnet&impactType=Direct',\r\n headers=headers)\r\n\r\n # get the response back\r\n res = conn.getresponse()\r\n\r\n # Output\r\n data = res.read()\r\n #print(res.status, res.reason)\r\n #print(data.decode('utf-8'))\r\n #print(res.getheaders())\r\n\r\n output = str(data.decode('utf-8'))\r\n output2 = output.replace(\",\", \" \")\r\n\r\n # Add to CurrentImpacts List\r\n if data.decode('utf-8') != '':\r\n for i, line in enumerate(output2.splitlines()):\r\n # print(line)\r\n if i != 0:\r\n for i2, word in enumerate(line.split()):\r\n if i2 == 0:\r\n currentImpactsID_list.append(stripID(word))\r\n # print(word)\r\n break\r\n\r\ndef callplusImpacts(event_id):\r\n # Generate X-ID\r\n xID = uuid.uuid4()\r\n # Encode userID and client secret\r\n encode = base64.b64encode(b'59fc1749a8054a5bb2b2a9c050dc85d0:AD43cDED844F43F6983DC133acadb957')\r\n\r\n headers = {'Authorization':'basic'+str(encode), 'X-Transaction-Id': str(xID)}\r\n\r\n # This sets up the https connection\r\n # conn = http.client.HTTPSConnection(\"api.sandbox.chorus.co.nz\")\r\n conn = http.client.HTTPSConnection(\"api.chorus.co.nz\")\r\n\r\n # then connect\r\n # Impact Download\r\n conn.request('GET','/network-events/v1/events/'+event_id+'/impactDownload?organisation=Callplus+Limited&impactType=Direct',headers=headers)\r\n #conn.request('GET', '/network-events/v1/events/'+event_id+'/impact', headers = headers)\r\n\r\n # get the response back\r\n res = conn.getresponse()\r\n\r\n # Output\r\n data = res.read()\r\n #print(res.status, res.reason)\r\n #print(data.decode('utf-8'))\r\n #print(res.getheaders())\r\n\r\n output = str(data.decode('utf-8'))\r\n output2 = output.replace(\",\", \" \")\r\n\r\n # Add to CurrentImpacts List\r\n if data.decode('utf-8') != '':\r\n for i, line in enumerate(output2.splitlines()):\r\n # print(line)\r\n if i != 0:\r\n for i2, word in enumerate(line.split()):\r\n if i2 == 0:\r\n currentImpactsID_list.append(stripID(word))\r\n # print(word)\r\n break\r\n\r\ndef orconImpacts(event_id):\r\n # Generate X-ID\r\n xID = uuid.uuid4()\r\n # Encode userID and client secret\r\n encode = base64.b64encode(b'clientID:clientSecret')\r\n\r\n headers = {'Authorization': 'basic' + str(encode), 'X-Transaction-Id': str(xID)}\r\n\r\n # This sets up the https connection\r\n # conn = http.client.HTTPSConnection(\"api.sandbox.chorus.co.nz\")\r\n conn = http.client.HTTPSConnection(\"api.chorus.co.nz\")\r\n\r\n # then connect\r\n # Impact Download\r\n conn.request('GET',\r\n '/network-events/v1/events/' + event_id + '/impactDownload?organisation=Orcon&impactType=Direct',\r\n headers=headers)\r\n\r\n # get the response back\r\n res = conn.getresponse()\r\n\r\n # Output\r\n data = res.read()\r\n # print(res.status, res.reason)\r\n # print(data.decode('utf-8'))\r\n # print(res.getheaders())\r\n output = str(data.decode('utf-8'))\r\n output2 = output.replace(\",\", \" \")\r\n\r\n # Add to CurrentImpacts List\r\n if data.decode('utf-8') != '':\r\n for i, line in enumerate(output2.splitlines()):\r\n # print(line)\r\n if i != 0:\r\n for i2, word in enumerate(line.split()):\r\n if i2 == 0:\r\n currentImpactsID_list.append(stripID(word))\r\n # print(word)\r\n break\r\n\r\ndef loopImpactsUnplanned():\r\n # Stamp Last Update\r\n global lastUpdate\r\n lastUpdate = datetime.now().strftime(\"%d-%m-%Y %H:%M:%S\")\r\n #print(\"lastupdate form loopImpacts: \"+lastUpdate)\r\n for event in unplannedIncidents_list:\r\n currentCGWImpact_List = []\r\n CGW_Count = 0\r\n\r\n # Clear id list\r\n currentImpactsID_list.clear()\r\n # Load Change Details\r\n vocusOverview(event)\r\n # Call each entity for impacts\r\n vocusImpacts(event)\r\n fxNetworksImpacts(event)\r\n callplusImpacts(event)\r\n # orconImpacts(event)\r\n\r\n # CGW Impact Yes or No?\r\n for id in currentImpactsID_list:\r\n CGW = False\r\n currentCID = id.strip()\r\n ############################\r\n # Using couchDB\r\n ############################\r\n rows = tailsDB.view(\"_design/reconcile/_view/tails_by_service_id\", key=currentCID.lower()).rows\r\n #rows = 1 # for testing without couchDB\r\n # Checking for customer name\r\n if len(rows) > 0:\r\n currentCustomer = rows[0].value['customer']['name']\r\n\r\n if len(rows) >= 1:\r\n #if rows >= 1:\r\n CGW = True\r\n currentCGWImpact_List.append(id)\r\n CGW_Count += 1\r\n #break # break out of for loop if CID found\r\n\r\n ## Create row object(list of list))\r\n #row = (\"test cust\", currentCID, currentStatus, currentEventStart, currentEventEnd, currentEventDuration, currentArea, event)\r\n row = (currentCustomer, currentCID, currentStatus, currentEventStart, currentEventEnd, currentEventDuration, currentArea, event)\r\n rowList_list.append(row)\r\n #print(row)\r\n\r\n # print(currentEvent)\r\n # print(currentEventDuration)\r\n # print(currentEventStart)\r\n # print(currentEventEnd)\r\n # print(currentCGWImpact_List)\r\n\r\n# Helper Methods\r\ndef stripID(input):\r\n stripped = input.replace('PDL', '').replace('IDA', '').replace('POL', '')\r\n return stripped.strip()\r\n\r\ndef dateConverter(input):\r\n if is_date(input) == True:\r\n datetime_object = datetime.strptime(input, '%Y-%m-%dT%H:%M:%S+12:00')\r\n converted = datetime_object.strftime(\"%d-%m-%Y %H:%M:%S\")\r\n return converted\r\n else:\r\n return \"-\"\r\n\r\ndef is_date(string, fuzzy=False):\r\n \"\"\"\r\n Return whether the string can be interpreted as a date.\r\n\r\n :param string: str, string to check for date\r\n :param fuzzy: bool, ignore unknown tokens in string if True\r\n \"\"\"\r\n # Check for None type / null\r\n if string is None:\r\n return False\r\n else:\r\n try:\r\n parse(string, fuzzy=fuzzy)\r\n return True\r\n\r\n except ValueError:\r\n return False\r\n\r\ndef clearUnplanned():\r\n unplannedIncidents_list.clear()\r\n currentImpactsID_list.clear()\r\n cgwImpact_list.clear()\r\n rowList_list.clear()\r\n\r\n\r\n# Function Call\r\n#vocusUnplanned()\r\n#loopImpacts()\r\n#print(len(rowList_list))\r\n#print(dateConverter('2019-04-23T20:51:16+12:00'))\r\n\r\n#datetime_object_start = datetime.strptime('2019-04-23T20:51:16+12:00', '%Y-%m-%dT%H:%M:%S+12:00')\r\n#test = datetime_object_start.strftime(\"%d/%m/%Y %H:%M:%S\")\r\n#print(datetime_object_start,\" \",test)\r\n\r\n# datetime object containing current date and time\r\n#now = datetime.now()\r\n#print(\"now =\", now)\r\n\r\n# dd/mm/YY H:M:S\r\n#dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\r\n#print(\"date and time =\", dt_string)","sub_path":"chorusDashboard/unplannedEngine.py","file_name":"unplannedEngine.py","file_ext":"py","file_size_in_byte":15165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"381085039","text":"# watching_real_time_data_source.py\n\n# Watch a log file\n\nimport os\nimport time\n\nf = open('Data/somelogfile.log', 'r')\nf.seek(0, os.SEEK_END)\n\nwhile True:\n line = f.readline()\n if not line:\n time.sleep(0.1)\n continue # Retry\n print('Got:', line)","sub_path":"iterator_n_generator/watching_real_time_data_source.py","file_name":"watching_real_time_data_source.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"480749168","text":"# imported Flask and jsonify from flask\n# imported SQLAlchemy from flask_sqlalchemy\nfrom flask import Flask, render_template, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\n\n# initialized new flask app\napp = Flask(__name__)\n# added configurations and database\napp.config['DEBUG'] = True\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n# connected flask_sqlalchemy to the configured flask app\ndb = SQLAlchemy(app)\n\n# created models for application\nclass User(db.Model):\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(20), nullable=False)\n tweets = db.relationship('Tweet', backref='users', lazy=True)\n def to_dict(self):\n user = {'id': self.id, 'username': self.username, 'tweets': [tweet.to_dict() for tweet in self.tweets]}\n return user\n\nclass Tweet(db.Model):\n __tablename__ = 'tweets'\n id = db.Column(db.Integer, primary_key=True)\n text = db.Column(db.Text, nullable=False)\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)\n user = db.relationship('User', back_populates=\"tweets\")\n def to_dict(self):\n tweet = {'id': self.id, 'text': self.text, 'user_id': self.user.id, 'user': self.user.username}\n return tweet\n\n\n# DEFINE ROUTES THAT RETURN APPROPRIATE HTML TEMPLATES HERE\n@app.route('/users')\ndef users():\n users_dict = [user.to_dict() for user in User.query.all()]\n return render_template('users.html',users = users_dict)\n\n@app.route('/users/')\ndef user_id(id):\n users_dict = [user.to_dict() for user in User.query.all() if user.id == id][0]\n return render_template('user_show.html', user=users_dict)\n\n@app.route('/users/')\ndef username(username):\n users_dict = [user.to_dict() for user in User.query.all() if user.username.lower()==username.lower()][0]\n return render_template('user_show.html', user=users_dict)\n\n@app.route('/tweets')\ndef tweets():\n tweets_dict = [tweet.to_dict() for tweet in Tweet.query.all()]\n return render_template('tweets.html',tweets = tweets_dict)\n\n@app.route('/tweets/')\ndef tweet_id(id):\n tweets_dict = [tweet.to_dict() for tweet in Tweet.query.all() if tweet.id ==id][0]\n return render_template('tweet_show.html',tweet = tweets_dict)\n\n#Tweets that belong to a user by user_id\n@app.route('/users//tweets')\ndef tweets_user_id(id):\n users_dict = [user.to_dict() for user in User.query.all() if user.id==id][0]\n return render_template('tweets.html', tweets=users_dict['tweets'])\n\n#Tweets that belong to a user by a user's name\n@app.route('/users//tweets')\ndef tweets_username(username):\n users_dict = [user.to_dict() for user in User.query.all() if user.username.lower()==username.lower()][0]\n return render_template('tweets.html', tweets=users_dict['tweets'])\n\n#A single User that is associated to a tweet by its id\n@app.route('/tweets//user')\ndef user_tweet_id(id):\n tweet_with_id = [tweet.to_dict() for tweet in Tweet.query.all() if tweet.id ==id][0]\n user_id = tweet_with_id['user_id']\n user_with_tweet = [user.to_dict() for user in User.query.all() if user.id == user_id][0]\n return render_template('user_show.html', user=user_with_tweet)\n\n# run flask application\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"74348438","text":"import random\nimport os\nimport json\nfrom numpy.lib.type_check import common_type\nfrom scp import SCPClient\nfrom box import box\nimport pandas as pd\n\n# id l w g rotx roty rotz nn\n# 1\t 108 0 76 0\t 30\t1\t 7\n\ndef load_BRinstance(filename, inst=1, nbox = 1):\n boxes={}; id2box={}\n with open(filename) as f:\n n = int(next(f))\n for i in range(n):\n next(f)\n L, W, H = [int(x) for x in next(f).split()]\n n_boxes = int(next(f))\n for it in range(n_boxes):\n id, l, rotx, w, roty, h, rotz, nn = [int(x) for x in next(f).split()] \n if i == inst-1:\n b = box(id, l, w, h, rotx, roty, rotz)\n # Multiplicar nn para complejizar el problema\n boxes[b]=nn*nbox;\n id2box[id]=b\n if i == inst-1: \n return L,W,H,boxes,id2box\n\ndef load_BRKGAinstance(filename, inst=1, nbox = 1, rot_allowed=False):\n boxes={}; id2box={}\n with open(filename) as f:\n for i in range(inst):\n next(f)\n n_boxes, L, W, H = [int(x) for x in next(f).split()]\n for it in range(n_boxes):\n l, w, h = [int(x) for x in next(f).split()] \n if i == inst-1:\n if rot_allowed:\n b = box(it+1, l, w, h, 1, 1, 1)\n else:\n b = box(it+1, l, w, h, 0, 0, 0)\n # Multiplicar nn para complejizar el problema\n boxes[b]=nbox;\n id2box[it+1]=b\n #next(f)\n if i == inst-1: \n return L,W,H,boxes,id2box\n\nimport re\ndef load_LargeInstance(filename, nbox = 1, rot_allowed=False):\n boxes={}; id2box={}\n try:\n with open(filename) as f:\n #n_boxes, L, W, H = [int(x) for x in next(f).split()]\n L,W,H = 609,243,243 \n line = next(f)\n id=0\n while line is not None:\n values = re.findall(\"\\d+\", line)\n values = [int(v) for v in values]\n for i in range(int(len(values)/3)):\n id +=1\n l,w,h = values[i*3:i*3+3]\n if rot_allowed:\n b = box(id, l, w, h, 1, 1, 1)\n else:\n b = box(id, l, w, h, 0, 0, 0) \n boxes[b]=nbox;\n id2box[id]=b\n line = next(f)\n except StopIteration:\n return L,W,H,boxes,id2box\n\ndef load_productInstance(filename, nbox = 1, rot_allowed=False):\n boxes = {}; id2box={}\n # Dataset and dimension on mm\n L,W,H = 12000,2330,2200\n try:\n df = pd.read_csv(filename)\n except FileNotFoundError:\n print(\"La ruta {} no coincide\".format(filename))\n return L,W,H,{},{},\n\n print(df)\n id = 0\n for index,row in df.iterrows():\n id += 1\n l,w,h = int(row['depth']), int(row['width']), int(row['height'])\n# print(\"{}, {}, {}\".format(l,w,h))\n if rot_allowed:\n b = box(id, l, w, h, 1, 1, 1)\n else:\n b = box(id, l, w, h, 0, 0, 0)\n\n boxes[b] = nbox\n id2box[id] = b\n\n return L,W,H, boxes, id2box\n\ndef load_instances_elhedhli(filename, rot_allowed=False):\n boxes = {}\n id2box = {}\n try:\n with open(filename) as f:\n L,W,H = 1200,800,2055\n line = next(f)\n id = 0\n while line:\n id +=1\n # \"Width\" \"Depth\" \"Height\" \"Weight\" \"Load Capacity\" \"Width Reduce\" \"Depth Reduce\" \"Shape Type\" \"Repetition\" \"Sequence Number\n w, l, h, _, _, _, _, _, nbox, _ = line.split(\"\\t\")\n w, l, h, nbox = int(w), int(l), int(h),int(nbox)\n \n if rot_allowed:\n b = box(id, l, w, h, 1, 1, 1)\n else:\n b = box(id, l, w, h, 0, 0, 0) \n \n boxes[b]=nbox;\n id2box[id]=b\n line = next(f)\n\n except StopIteration:\n return L,W,H, boxes, id2box\n\ndef write_instance(L,W,H,boxes,filename) :\n txt = \"1\\n1 0\\n\"+str(L)+\" \"+str(W)+\" \"+str(H)+\"\\n\";\n txt += str(len(boxes)) + \"\\n\"\n for box in boxes:\n txt += str(box.id) + ' ' + str(box.l) + ' ' + str(box.rotx) \\\n + ' ' + str(box.w) + ' ' + str(box.roty) \\\n + ' ' + str(box.h) + ' ' + str(box.rotz) + ' ' + str(boxes[box]) + '\\n'\n txt += '\\n'\n\n text_file = open(filename, \"w\")\n text_file.write(txt)\n text_file.close()\n \n\ndef bsg_solve(ssh,L,W,H,boxes,id2box, time=1, args=\"\", verbose=False, remove_instance=True):\n filename=\"tmp_instance_\"+ str(random.randint(10000, 99999))\n \n write_instance(L,W,H,boxes,filename)\n \n scp = SCPClient(ssh.get_transport())\n scp.put(filename, \"/home/iaraya/clp/\"+filename)\n if remove_instance:\n os.remove(filename)\n\n command = \"/home/iaraya/clp/BSG_CLP /home/iaraya/clp/\"+filename+\" -i 0 -t \"+str(time)+\" --json \" + args\n if verbose==True: print(command)\n \n stdin, stdout, stderr = ssh.exec_command(command)\n lines = stdout.readlines()\n json_data = json.loads(lines[-1])\n loaded={}; remaining={}\n for item in json_data[\"loaded\"]:\n loaded[id2box[item[0]]]=item[1]\n for item in json_data[\"remaining\"]:\n remaining[id2box[item[0]]]=item[1]\n \n ssh.exec_command(\"rm /home/iaraya/clp/\"+filename)\n \n return remaining, loaded, json_data #json_data[\"utilization\"], json_data[\"tot_support\"], json_data[\"full_supported_items\"]\n","sub_path":"base/bsg.py","file_name":"bsg.py","file_ext":"py","file_size_in_byte":5620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"487996933","text":"import sqlalchemy as sa\n\nfrom pr.db import models\n\n\nPersonTag = sa.Table(\n 'persons_tags',\n models.DeclarativeBase.metadata,\n sa.Column('person_id', sa.Integer, sa.ForeignKey('persons.id')),\n sa.Column('tag_id', sa.Integer, sa.ForeignKey('tags.id'))\n)\n","sub_path":"pr/db/models/person_tag.py","file_name":"person_tag.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"7218337","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\nfrom django.contrib.sites.models import Site\nfrom django.conf.urls.static import static\nfrom templateModule import views as template_views\nfrom user import views as user_views\n\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^', include('Catalog.urls')),\n url(r'^accounts/', include('allauth.urls')),\n url(r'^contact/', include('contact.urls')),\n url(r'^history/', include('history.urls')),\n url(r'^signup/$', user_views.signup, name='signup'),\n url(r'^login/$', user_views.login, name='login'),\n url(r'^logout/$', user_views.logout, name='logout'),\n url(r'^profile/$', user_views.profile, name='profile'),\n url(r'^activate/(?P[0-9A-Za-z_\\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',\n user_views.activate, name='activate'),\n url(r'^cart/' , include('cart.urls')),\n]\n","sub_path":"Kindlekuniya/Kindlekuniya/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"292804465","text":"from pyspark.sql import SparkSession\nimport operator\n\n\ndef create_spark_session():\n \"\"\"\n set up a spark session.\n params:\n None\n return:\n spark(SparkSession): SparkSession\n \"\"\"\n spark = SparkSession \\\n .builder \\\n .appName(\"Udacity Data Engineering Capstone\") \\\n .getOrCreate()\n return spark\n\n\ndef table_validate(spark, check_path, check_type, table_name, check_sql, expected_result, comparison):\n \"\"\"\n check whether the data passes certain `check_type`.\n params:\n spark (SparkSession): SparkSession\n check_path(str): hdfs path where contains check files.\n check_type (str): data validate type name.\n table_name(str): table name needed to check\n check_sql (str): sql used to validate the target table\n expected_result (int): after run the sql, the expected returned rows.\n comparison (operator.function):\n python operator.function, used to do comparison between sql returns and expected_result.\n return:\n None\n \"\"\"\n validation_path = check_path + '/' + table_name + '.parquet'\n validation_data = spark.read.parquet(validation_path)\n validation_data.createOrReplaceTempView(table_name)\n records = spark.sql(check_sql).take(1)\n # check results\n if len(records) < 1 or len(records[0]) < 1:\n raise ValueError(f\"{check_type} check failed.\\n '{check_sql}' returned no results. \")\n num_records = records[0][0]\n is_check_pass = comparison(num_records, expected_result)\n if not is_check_pass:\n raise ValueError(f\"{check_type} check failed.\\n \"\n f\"'{check_sql}' returned {num_records} rows,\\n \"\n f\"expected {str(comparison)} {expected_result} rows\")\n\n\ndef main():\n \"\"\"\n execute all the functions to build a data lake on AMS s3.\n - create spark session\n - process fucntion `table_validate()`\n params:\n None\n return:\n None\n \"\"\"\n spark = create_spark_session()\n output = '/hdfs_output'\n # check whether the parquet has result\n tables_check = [\n {'check_type': 'is_null','table_name': 'bikeshare_fact_table',\n 'check_sql': \"SELECT COUNT(*) FROM bikeshare_fact_table WHERE id IS NULL\",\n 'expected_result': 0,\n 'comparison': operator.eq},\n {'check_type': 'is_empty', 'table_name': 'bikeshare_fact_table',\n 'check_sql': \"SELECT COUNT(*) FROM bikeshare_fact_table\", 'expected_result': 0,\n 'comparison': operator.gt},\n {'check_type': 'is_empty', 'table_name': 'dim_weather_table',\n 'check_sql': \"SELECT COUNT(*) FROM dim_weather_table\", 'expected_result': 0,\n 'comparison': operator.gt},\n {'check_type': 'is_empty', 'table_name': 'dim_covid_table',\n 'check_sql': \"SELECT COUNT(*) FROM dim_covid_table\", 'expected_result': 0,\n 'comparison': operator.gt},\n {'check_type': 'is_empty', 'table_name': 'dim_user_agg_table',\n 'check_sql': \"SELECT COUNT(*) FROM dim_user_agg_table\", 'expected_result': 0,\n 'comparison': operator.gt},\n {'check_type': 'is_empty', 'table_name': 'dim_time_table',\n 'check_sql': \"SELECT COUNT(*) FROM dim_time_table\", 'expected_result': 0,\n 'comparison': operator.gt},\n {'check_type': 'is_empty', 'table_name': 'dim_bike_table',\n 'check_sql': \"SELECT COUNT(*) FROM dim_bike_table\", 'expected_result': 0,\n 'comparison': operator.gt}]\n for check in tables_check:\n table_validate(spark, check_path=output, **check)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"dags/script_emr/spark_check_emr.py","file_name":"spark_check_emr.py","file_ext":"py","file_size_in_byte":3608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"138559795","text":"# Authors: Rob Crittenden \n#\n# Copyright (C) 2009 Red Hat\n# see file 'COPYING' for use and warranty information\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#\n\nimport collections\nimport xml.dom.minidom\n\nimport nss.nss as nss\nimport six\nfrom six.moves.urllib.parse import urlencode\n\nfrom ipalib import api, errors\nfrom ipalib.errors import NetworkError\nfrom ipalib.text import _\nfrom ipapython import nsslib, ipautil\nfrom ipapython.ipa_log_manager import *\n\n# Python 3 rename. The package is available in \"six.moves.http_client\", but\n# pylint cannot handle classes from that alias\ntry:\n import httplib\nexcept ImportError:\n import http.client as httplib\n\nif six.PY3:\n unicode = str\n\nProfile = collections.namedtuple('Profile', ['profile_id', 'description', 'store_issued'])\n\nINCLUDED_PROFILES = {\n Profile(u'caIPAserviceCert', u'Standard profile for network services', True),\n Profile(u'IECUserRoles', u'User profile that includes IECUserRoles extension from request', True),\n }\n\nDEFAULT_PROFILE = u'caIPAserviceCert'\n\n\ndef error_from_xml(doc, message_template):\n try:\n item_node = doc.getElementsByTagName(\"Error\")\n reason = item_node[0].childNodes[0].data\n return errors.RemoteRetrieveError(reason=reason)\n except Exception as e:\n return errors.RemoteRetrieveError(reason=message_template % e)\n\n\ndef get_ca_certchain(ca_host=None):\n \"\"\"\n Retrieve the CA Certificate chain from the configured Dogtag server.\n \"\"\"\n if ca_host is None:\n ca_host = api.env.ca_host\n chain = None\n conn = httplib.HTTPConnection(\n ca_host,\n api.env.ca_install_port or 8080)\n conn.request(\"GET\", \"/ca/ee/ca/getCertChain\")\n res = conn.getresponse()\n doc = None\n if res.status == 200:\n data = res.read()\n conn.close()\n try:\n doc = xml.dom.minidom.parseString(data)\n try:\n item_node = doc.getElementsByTagName(\"ChainBase64\")\n chain = item_node[0].childNodes[0].data\n except IndexError:\n raise error_from_xml(\n doc, _(\"Retrieving CA cert chain failed: %s\"))\n finally:\n if doc:\n doc.unlink()\n else:\n raise errors.RemoteRetrieveError(\n reason=_(\"request failed with HTTP status %d\") % res.status)\n\n return chain\n\n\ndef _parse_ca_status(body):\n doc = xml.dom.minidom.parseString(body)\n try:\n item_node = doc.getElementsByTagName(\"XMLResponse\")[0]\n item_node = item_node.getElementsByTagName(\"Status\")[0]\n return item_node.childNodes[0].data\n except IndexError:\n raise error_from_xml(doc, _(\"Retrieving CA status failed: %s\"))\n\n\ndef ca_status(ca_host=None, use_proxy=True):\n \"\"\"Return the status of the CA, and the httpd proxy in front of it\n\n The returned status can be:\n - running\n - starting\n - Service Temporarily Unavailable\n \"\"\"\n if ca_host is None:\n ca_host = api.env.ca_host\n if use_proxy:\n # Use port 443 to test the proxy as well\n ca_port = 443\n else:\n ca_port = 8443\n status, headers, body = unauthenticated_https_request(\n ca_host, ca_port, '/ca/admin/ca/getStatus')\n if status == 503:\n # Service temporarily unavailable\n return status\n elif status != 200:\n raise errors.RemoteRetrieveError(\n reason=_(\"Retrieving CA status failed with status %d\") % status)\n return _parse_ca_status(body)\n\n\ndef https_request(host, port, url, secdir, password, nickname,\n method='POST', headers=None, body=None, **kw):\n \"\"\"\n :param method: HTTP request method (defalut: 'POST')\n :param url: The path (not complete URL!) to post to.\n :param body: The request body (encodes kw if None)\n :param kw: Keyword arguments to encode into POST body.\n :return: (http_status, http_headers, http_body)\n as (integer, dict, str)\n\n Perform a client authenticated HTTPS request\n \"\"\"\n\n def connection_factory(host, port):\n no_init = secdir == nsslib.current_dbdir\n conn = nsslib.NSSConnection(host, port, dbdir=secdir, no_init=no_init,\n tls_version_min=api.env.tls_version_min,\n tls_version_max=api.env.tls_version_max)\n conn.set_debuglevel(0)\n conn.connect()\n conn.sock.set_client_auth_data_callback(\n nsslib.client_auth_data_callback,\n nickname, password, nss.get_default_certdb())\n return conn\n\n if body is None:\n body = urlencode(kw)\n return _httplib_request(\n 'https', host, port, url, connection_factory, body,\n method=method, headers=headers)\n\n\ndef http_request(host, port, url, **kw):\n \"\"\"\n :param url: The path (not complete URL!) to post to.\n :param kw: Keyword arguments to encode into POST body.\n :return: (http_status, http_headers, http_body)\n as (integer, dict, str)\n\n Perform an HTTP request.\n \"\"\"\n body = urlencode(kw)\n return _httplib_request(\n 'http', host, port, url, httplib.HTTPConnection, body)\n\n\ndef unauthenticated_https_request(host, port, url, **kw):\n \"\"\"\n :param url: The path (not complete URL!) to post to.\n :param kw: Keyword arguments to encode into POST body.\n :return: (http_status, http_headers, http_body)\n as (integer, dict, str)\n\n Perform an unauthenticated HTTPS request.\n \"\"\"\n body = urlencode(kw)\n return _httplib_request(\n 'https', host, port, url, httplib.HTTPSConnection, body)\n\n\ndef _httplib_request(\n protocol, host, port, path, connection_factory, request_body,\n method='POST', headers=None):\n \"\"\"\n :param request_body: Request body\n :param connection_factory: Connection class to use. Will be called\n with the host and port arguments.\n :param method: HTTP request method (default: 'POST')\n\n Perform a HTTP(s) request.\n \"\"\"\n if isinstance(host, unicode):\n host = host.encode('utf-8')\n uri = '%s://%s%s' % (protocol, ipautil.format_netloc(host, port), path)\n root_logger.debug('request %s %s', method, uri)\n root_logger.debug('request body %r', request_body)\n\n headers = headers or {}\n if (\n method == 'POST'\n and 'content-type' not in (str(k).lower() for k in headers)\n ):\n headers['content-type'] = 'application/x-www-form-urlencoded'\n\n try:\n conn = connection_factory(host, port)\n conn.request(method, uri, body=request_body, headers=headers)\n res = conn.getresponse()\n\n http_status = res.status\n http_headers = res.msg.dict\n http_body = res.read()\n conn.close()\n except Exception as e:\n raise NetworkError(uri=uri, error=str(e))\n\n root_logger.debug('response status %d', http_status)\n root_logger.debug('response headers %s', http_headers)\n root_logger.debug('response body %r', http_body)\n\n return http_status, http_headers, http_body\n","sub_path":"ipapython/dogtag.py","file_name":"dogtag.py","file_ext":"py","file_size_in_byte":7647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"391725684","text":"import numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.models import Model\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.models import load_model\nfrom tcn import TCN\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom scipy.spatial.transform import Rotation as R\nimport json, os, sys\nfrom fastdtw import fastdtw\nfrom scipy.spatial.distance import euclidean\n\ncurrent_dir = os.getcwd()\nsys.path.insert(1, current_dir)\nfrom config import *\nfrom utils import *\n\nwith tf.device('/cpu:0'):\n dataset = []\n\n T=300\n n_trajectory = 31\n last_num = 0\n\n for n_samples in range(1,n_trajectory+1):\n ysamples1, time = path(n_samples,1)\n time_norm = (time-time[0])/(time[-1]-time[0])\n tsamples1 = np.linspace(0,1, T)\n #yinterp = np.interp(tsamples1, time_norm, ysamples1)\n yinterp = ysamples1\n last_num = yinterp[-1]\n\n # print(len(yinterp), 'lunghezza trajectory %s' %(n_samples))\n for j in yinterp:\n dataset.append(np.expand_dims(j,axis=0))\n\n dataset = np.array(dataset)\n print(np.shape(dataset))\n\n # split into train and test sets\n train_size = int(len(dataset) * 0.67)\n test_size = len(dataset) - train_size\n\n train, test = np.array(dataset[0:train_size]), np.array(dataset[train_size:len(dataset)])\n print('train shape',len(train),'test shape', len(test))\n\n validation_set_size = 700\n\n train_set = train[0:train.shape[0]-validation_set_size , : ]\n validation_set = train[train.shape[0]-validation_set_size: , : ]\n test_set = test[: , :]\n\n #test_set[:,-1] = test_set[:,-1]-test_set[0,-1]\n timeWindow = 50\n timeprediction = 50\n\n # reshape into X=t and Y=t+1\n trainX, trainY = create_dataset(train_set, timeWindow,timeprediction)\n validationX, validationY = create_dataset(validation_set,timeWindow,timeprediction)\n testX, testY = create_dataset(test_set, timeWindow,timeprediction)\n\n print('validation',validationX.shape)\n print('trainX',trainX.shape)\n print('trainY',trainY.shape)\n print('testX',testX.shape)\n print('testY',testY.shape)\n\n monitor = EarlyStopping(monitor='loss', min_delta=1e-4, patience=5, verbose=1, mode='auto', restore_best_weights=True)\n\n \"\"\"\n TCN\n \"\"\"\n inputState = keras.layers.Input(shape=(timeWindow,1))\n z = keras.layers.TimeDistributed(keras.layers.Dense(150, activation=\"relu\"))(inputState)\n z = Model(inputs=inputState, outputs=z)\n TCN_Model = TCN(nb_filters=150, kernel_size=2, nb_stacks=1, dilations=[1, 2, 4, 8],return_sequences=True, activation='relu')(z.output)\n TCN_Model = keras.layers.TimeDistributed(keras.layers.Dense(1,activation=\"linear\"))(TCN_Model)\n\n model4 = Model(inputs=inputState, outputs=TCN_Model)\n model4.compile(loss=tf.keras.losses.MeanAbsoluteError(), optimizer=keras.optimizers.Adam())\n history4 = model4.fit(trainX ,trainY, epochs=15, validation_data=(validationX[:,:,-1], validationY), verbose=2)\n\n \"\"\"\n LSTM\n \"\"\"\n inputState1 = keras.layers.Input(shape=(timeWindow,1))\n z1 = keras.layers.TimeDistributed(keras.layers.Dense(150, activation=\"relu\"))(inputState1)\n z1 = Model(inputs=inputState1, outputs=z1)\n LSTM_Model = keras.layers.LSTM(150, return_sequences=True, activation='relu')(z1.output)\n LSTM_Model = keras.layers.TimeDistributed(keras.layers.Dense(1,activation=\"linear\"))(LSTM_Model)\n\n model1 = Model(inputs=inputState1, outputs=LSTM_Model)\n model1.compile(loss=tf.keras.losses.MeanAbsoluteError(), optimizer=keras.optimizers.Adam())\n history1 = model1.fit(trainX ,trainY, epochs=15, validation_data=(validationX[:,:,-1], validationY), verbose=2)\n\n \"\"\"\n GRU\n \"\"\"\n inputState2 = keras.layers.Input(shape=(timeWindow,1))\n z2 = keras.layers.TimeDistributed(keras.layers.Dense(150, activation=\"relu\"))(inputState2)\n z2 = Model(inputs=inputState2, outputs=z2)\n GRU_Model = keras.layers.GRU(150, return_sequences=True, activation='relu')(z2.output)\n GRU_Model = keras.layers.TimeDistributed(keras.layers.Dense(1,activation=\"linear\"))(GRU_Model)\n\n model2 = Model(inputs=inputState2, outputs=GRU_Model)\n model2.compile(loss=tf.keras.losses.MeanAbsoluteError(), optimizer=keras.optimizers.Adam())\n history2 = model2.fit(trainX ,trainY, epochs=15, validation_data=(validationX[:,:,-1], validationY), verbose=2)\n\n \"\"\"\n RNN\n \"\"\"\n inputState3 = keras.layers.Input(shape=(timeWindow,1))\n z3 = keras.layers.TimeDistributed(keras.layers.Dense(150, activation=\"relu\"))(inputState3)\n z3 = Model(inputs=inputState3, outputs=z3)\n RNN_model = keras.layers.SimpleRNN(150, return_sequences=True, activation='relu')(z3.output)\n RNN_model = keras.layers.TimeDistributed(keras.layers.Dense(1,activation=\"linear\"))(RNN_model)\n\n model3 = Model(inputs=inputState3, outputs=RNN_model)\n model3.compile(loss=tf.keras.losses.MeanAbsoluteError(), optimizer=keras.optimizers.Adam())\n history3 = model3.fit(trainX ,trainY, epochs=15, validation_data=(validationX[:,:,-1], validationY), verbose=2)\n\n \"\"\"\n PLOTS\n \"\"\"\n\n plt.plot(history4.history['loss'])\n plt.plot(history4.history['val_loss'])\n plt.title('model loss Y axis')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.savefig(PLOTS + '/Y_loss.png')\n\n test_predict = model4.predict(testX[:,:,-1]) # TCN\n test_predict1 = model1.predict(testX[:,:,-1]) # LSTM\n test_predict2 = model2.predict(testX[:,:,-1]) # GRU\n test_predict3 = model3.predict(testX[:,:,-1]) # RNN\n\n target = np.zeros(shape=(np.shape(test_predict)[0]))\n\n predict = np.zeros(shape=(np.shape(test_predict)[0]))\n predict1 = np.zeros(shape=(np.shape(test_predict)[0]))\n predict2 = np.zeros(shape=(np.shape(test_predict)[0]))\n predict3 = np.zeros(shape=(np.shape(test_predict)[0]))\n\n for i in range(np.shape(test_predict)[0]):\n target[i] = testY[i,0]\n\n predict[i] = test_predict[i,0]\n predict1[i] = test_predict1[i,0]\n predict2[i] = test_predict2[i,0]\n predict3[i] = test_predict3[i,0]\n\n print('target shape:', np.shape(target))\n print('predict shape:', np.shape(predict))\n\n distance, path = fastdtw(predict, target, dist=euclidean)\n distance1, path = fastdtw(predict1, target, dist=euclidean)\n distance2, path = fastdtw(predict2, target, dist=euclidean)\n distance3, path = fastdtw(predict3, target, dist=euclidean)\n\n print('TCN',distance,'LSTM', distance1,'GRU',distance2,'RNN',distance3)\n\n plt.figure()\n plt.plot(predict[:500], '--r', label='Prediction TCN')\n plt.plot(predict1[:500], '--b', label='Prediction LSTM')\n plt.plot(predict2[:500], '--k', label='Prediction GRU')\n plt.plot(predict3[:500], '--', label='Prediction RNN')\n\n plt.plot(target[:500], '--g' , label='GT' )\n plt.ylabel('Y axis')\n plt.xlabel('n_samples')\n plt.title('Prediction in test phase Y axis')\n plt.legend(loc='upper left')\n plt.legend()\n\n plt.savefig(PLOTS + '/Y_TCN_new2.png')\n\n plt.figure()\n plt.plot(predict[150:250], '--r', label='Prediction TCN')\n plt.plot(predict1[150:250], '--b', label='Prediction LSTM')\n plt.plot(predict2[150:250], '--k', label='Prediction GRU')\n plt.plot(predict3[150:250], '--', label='Prediction RNN')\n\n plt.plot(target[150:250], '--g' , label='GT' )\n plt.ylabel('Y axis')\n plt.xlabel('n_samples')\n plt.title('Prediction in test phase Y axis')\n plt.legend( loc='upper left')\n plt.legend()\n\n plt.savefig(PLOTS + '/Y_TCN_new2zoom.png')\n\n error = np.mean(abs(predict-target))\n print(error)\n\n model1.save(TCN_MODEL + '/Y_LSTM.h5')\n model2.save(TCN_MODEL + '/Y_GRU.h5')\n model3.save(TCN_MODEL + '/Y_RNN.h5')\n model4.save(TCN_MODEL + '/Y_TCN.h5')\n","sub_path":"deep_model/Y.py","file_name":"Y.py","file_ext":"py","file_size_in_byte":7861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"433806845","text":"import pyximport\npyximport.install()\nimport json\nfrom evals.src.crannRec.crannrec import CrannRecModel\nimport cv2\nimport numpy as np\nimport base64\nimport config\nimport time\nimport traceback\nimport sys\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nfrom evals.utils import create_net_handler, net_preprocess_handler, net_inference_handler, CTX, \\\n monitor_rt_load, monitor_rt_forward, monitor_rt_post\nfrom evals.utils.error import *\nfrom evals.utils.image import load_image\n\n\n@create_net_handler\ndef create_net(configs):\n CTX.logger.info(\"load configs: %s\", configs)\n # crann_recog = CrannRecModel(config.MODELFILE_CRANN_URL, config.MODELFILE_CRANN_YML_URL)\n crann_recog = CrannRecModel(str(configs['model_files']['crann_exp3_11_9_5.pth']), str(configs['model_files']['crann.yml']))\n return {\"crann_recog\": crann_recog, \"batch_size\": configs['batch_size']}, 0, ''\n\n\n@net_preprocess_handler\ndef net_preprocess(model, req):\n CTX.logger.info(\"PreProcess...\")\n return req, 0, ''\n\n\n@net_inference_handler\ndef net_inference(model, reqs):\n crann_recog = model['crann_recog']\n batch_size = model['batch_size']\n CTX.logger.info(\"inference begin ...\")\n\n try:\n images_with_bboxes = pre_eval(batch_size, reqs)\n output = eval(crann_recog, images_with_bboxes)\n ret = post_eval(output)\n \n except ErrorBase as e:\n return [], e.code, str(e)\n except Exception as e:\n CTX.logger.error(\"inference error: %s\", traceback.format_exc())\n return [], 599, str(e)\n\n return ret, 0, ''\n\ndef pre_eval(batch_size, reqs):\n cur_batchsize = len(reqs)\n if cur_batchsize > batch_size:\n raise ErrorOutOfBatchSize(batch_size)\n\n ret = []\n _t1 = time.time()\n for req in reqs:\n img = load_image(req[\"data\"][\"uri\"], body=req['data']['body'])\n bboxes = req[\"params\"][\"bboxes\"]\n if len(bboxes[0]) == 8:\n # transform from [x0,y0,x1,y1,x2,y2,x3,y3] to [[x0,y0],[x1,y1],[x2,y2],[x3,y3]]\n bboxes = list(map(lambda x:[[x[0],x[1]],[x[2],x[3]],[x[4],x[5]],[x[6],x[7]]],bboxes))\n ret.append((img, bboxes))\n\n _t2 = time.time()\n CTX.logger.info(\"image load cost: %f\", _t2 - _t1)\n # monitor_rt_load().observe(_t2 - _t1)\n\n return ret\n\n\ndef eval(crann_recog, imges_with_bboxes):\n output = []\n _t1 = time.time()\n for img, rects in imges_with_bboxes:\n imglist = crann_recog.cutimagezz(img,rects)\n res = crann_recog.deploy(imglist)\n output.append((res, rects))\n _t2 = time.time()\n CTX.logger.info(\"forward: %f\", _t2 - _t1)\n monitor_rt_forward().observe(_t2 - _t1)\n return output\n\n\ndef post_eval(output):\n resps = []\n\n _t1 = time.time()\n for res, bboxes in output:\n result = {}\n result[\"text\"] = res\n result[\"bboxes\"] = bboxes\n resps.append({\"code\": 0, \"message\": \"\", \"result\": result})\n _t2 = time.time()\n CTX.logger.info(\"post: %f\", _t2 - _t1)\n monitor_rt_post().observe(_t2 - _t1)\n return resps\n\n\nif __name__ == '__main__':\n # init model\n pass","sub_path":"ataraxia/inference/ocr/recognition/crann/main_vat.py","file_name":"main_vat.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"87126671","text":"#5! = 5 * 4!\n#4! = 4 * 3! \n#3! = 3* 2!\n#2! = 2 * 1!\n#1! = 1 * 0!\n#0! = 1\n#this program is factorial recursive function\ndef factorial(number):\n if number == 0:\n return 1\n else:\n return number * factorial(number-1)\n\nprint(factorial(5))\nprint(factorial(10))","sub_path":"3/factorial.py","file_name":"factorial.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"325930246","text":"# This program takes two numbers and prints their LCM....\r\n\r\n# Solution :\r\n\r\n# Take two numbers....\r\n\r\nn1=int(input(\"Enter first number... \"))\r\nn2=int(input(\"Enter second number... \"))\r\n\r\n# Find the smaller one and store it in anothe r variable...\r\n\r\nsmaller=min(n1 , n2)\r\n\r\n# Use a loop to find common multiple of both nu,bers...\r\n# Loop will range from 1 to n1*n2 bcoz...\r\nfor c in range(1,n1*n2):\r\n if c%n1==0 and c%n2==0:\r\n break\r\n# Print the final result...\r\n\r\nprint(\"LCM of \",n1,\" and \",n2,\" is \",c)","sub_path":"maths10_LCM.py","file_name":"maths10_LCM.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"635653293","text":"\"\"\"\nMini Project 5--Re-editing of Mini Project 3 (Text Mining)\nAuthor: Nicholas Sherman\nDate: 4/22/2017\nClass: Software Design\n\nThis project markov chains Family Guy scripts with Donald Trump speeches for entertainment purposes.\n\"\"\"\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\nimport pickle\nimport os.path\nfrom pathlib import Path\nimport random\n\ndef dict_creation_one(script, things = dict()):\n '''Create the base dictionary for ONE word; only to be called if there is no dicts1.p already.\n Basically, this is a one-off dictionary in order to determine the first words. It also allows\n for the possibility of more randomness at some point.\n inputs: a single string containing all scripts, a dictionary can be overloaded to help shorten the creation time of the dictionary\n outputs: a dictionary of one word keys for markov chaining'''\n entiredict = things\n everything = script\n newstring = ''\n for x in script: #get rid of symbols that I don't want in my speech\n if x not in ('[', ']', '@', '#', '$', '%', '^', '&', '*', '(', ')', ':', '\"', '\\\\', '—', '|', '-'):\n newstring += (x)\n newstring = newstring.lower()\n listowords = newstring.split()\n index = 0\n for y in listowords: #run through all of the words in the speech and create a dictionary with them; this is a single word dictionary\n index += 1\n if index != len(listowords):\n if y not in entiredict:\n entiredict[y] = [listowords[index]]\n else:\n entiredict[y].append(listowords[index])\n return entiredict\n\ndef dict_creation_two(script, things = dict()):\n '''Create the base dictionary for TWO words; only to be called if there is no dicts.p already.\n This is the dictionary that is referenced for most of the project.\n inputs: a single string containing all scripts, a dictionary can be overloaded to help shorten the creation time of the dictionary\n outputs: a dictionary with two word keys for markov chaining'''\n entiredict = things\n everything = script\n newstring = ''\n for x in script: #get rid of symbols that I don't want in my speech\n if x not in ('[', ']', '@', '#', '$', '%', '^', '&', '*', '(', ')', ':', '\"', '\\\\', '—', '|', '-'):\n if x in ('!', '.', '?'):\n newstring += (x)\n else:\n newstring += (x)\n newstring = newstring.lower()\n listowords = newstring.split()\n index = 0\n for x in range(0, len(listowords)-3): #run through all of the words and create a dictionary with them; the keys are tuples.\n index = tuple((listowords[x], listowords[x+1]))\n if index not in entiredict:\n entiredict[index] = [listowords[x+2]]\n else:\n entiredict[index].append(listowords[x+2])\n return entiredict\n\ndef markov_chain_two(yup, yup2, allwordss):\n \"\"\"The markov chain function that actually generates the speech\n inputs: a two key-word dictionary, a one key-word dictionary, and a string of all scripts\n outputs: a string that is the \"final\" speech that Trump would make\"\"\"\n spech = random.randrange(300, 500) #generates a random speech of length randomly selected in this range (in words)\n speech = []\n listowords = allwordss.split()\n speech.append(random.choice(listowords).lower())\n speech.append(random.choice(yup2[speech[0]]))\n speech[0] = speech[0].capitalize()\n for i in range(2, spech-1): #Make a speech of length spech through referencing the dictionaries yup and yup2\n checker = (speech[i-2].lower(), speech[i-1].lower())\n if '.' in (speech[i-1]) or ('?' in (speech[i-1])) or ('!' in (speech[i-1])):\n speech.append(random.choice(yup[checker]).capitalize())\n else:\n appendix = random.choice(yup[checker])\n if appendix in \"i'm i i'll i've\": #capitalize I\n appendix = appendix.capitalize()\n speech.append(appendix)\n index = 0\n for x in speech: #A variety of statements that change Family Guy specific phrases to those that Trump could use\n xl = x.lower()\n if \"peter\" in xl:\n speech[index] = \"Trump\"\n elif \"lois\" in xl:\n speech[index] = \"Ivanka\"\n elif \"brian\" in xl:\n speech[index] = \"Pence\"\n elif \"stewie\" in xl:\n speech[index] = \"Obama\"\n elif \"quagmire\" in xl:\n speech[index] = \"ISIS\"\n elif \"meg\" in xl:\n speech[index] = \"Mexico\"\n elif \"chris\" in xl:\n speech[index] = \"China\"\n elif \"quahog\" in xl:\n speech[index] = \"MURICA\" #This is more likely to sound like Trump than \"America\"\n elif \"griffin\" in xl:\n speech[index] = \"President\"\n if '.' in x:\n temp = x\n mini = temp.split('.')\n speech[index] = mini[0]\n speech.insert(index, mini[1].capitalize())\n index += 1\n index = 0\n for y in speech: #Fixes some of the spacing issues\n if \" \" in y:\n speech[index] = y.replace(' ', '')\n index += 1\n if ('.' in speech[-1]) or ('!' in speech[-1]) or ('?' in speech[-1]): #how to determine if punctuation needs to be added at the end\n product = ' '.join(speech)\n else:\n product = ' '.join(speech) + '.'\n product = product.replace(' ', ' ') #replace all double spaces with single spaces.\n return product\n\nif __name__ == '__main__':\n max_season = 3\n allscripts = ''\n my_file = Path(\"dict1.p\")\n my_file2 = Path(\"dict2.p\")\n my_file3 = Path(\"allwords.p\")\n remake = False\n y = input(\"Do you want to customize the number of seasons (y/n)?: \")\n if y.lower() == 'y':\n max_seasons = input(\"How many seasons do you want?: \")\n remake = True\n # print(not my_file.is_file()) #For testing purposes\n # print(not my_file2.is_file()) #For testing purposes\n # print(not my_file3.is_file()) #For testing purposes\n if (not my_file.is_file()) or (not my_file2.is_file()) or (not my_file3.is_file()) or remake: #check to see if there are already dictionaries; if there aren't then dictionaries are created.\n basehtml = 'http://www.springfieldspringfield.co.uk/view_episode_scripts.php?tv-show=family-guy&episode=s'\n temptml = basehtml\n episodes_in_season = [-1, 8, 22, 23, 28, 19, 13, 17, 22, 19, 24, 23, 22, 19, 21, 14]\n for season in range (1, max_season):\n for i in range (1,episodes_in_season[season]): #rewritten for all seasons; writes the link in a way to grab the seasons correctly\n if season < 10:\n if i < 10:\n temp = temptml + '0%de' % season + '0%d' % (i)\n else:\n temp = temptml + '0%de' % season + '%d' % (i)\n else:\n if i < 10:\n temp = temptml + '%de' % season + '0%d' % (i)\n else:\n temp = temptml + '%de' % season + '%d' % (i)\n html = BeautifulSoup(requests.get(temp).text, 'lxml')\n thing = html.find(\"div\", class_ = 'scrolling-script-container')\n allscripts = allscripts + \" \" + str(thing.text)\n\n #gather the trump speeches\n html = BeautifulSoup(requests.get('https://github.com/PedramNavid/trump_speeches/blob/master/data/full_speech.txt').text, 'lxml')\n thing = html.find(\"table\", class_ = 'highlight tab-size js-file-line-container')\n allscripts += thing.text\n\n #pickle the necessary information\n pickle.dump(allscripts, open(\"allwords.p\", \"wb\"))\n pickle.dump(dict_creation_one(allscripts), open(\"dict1.p\", \"wb\"))\n pickle.dump(dict_creation_two(allscripts), open(\"dict2.p\", \"wb\"))\n pickle.dump(allscripts, open(\"backup.p\", \"wb\"))\n\n #call the dictionaries/all words to run the program with\n oneworddict = pickle.load( open( \"dict1.p\", \"rb\"))\n twoworddict = pickle.load( open(\"dict2.p\", \"rb\"))\n allwords = pickle.load( open(\"allwords.p\", \"rb\"))\n blah2 = markov_chain_two(twoworddict, oneworddict, allwords) #create the markov chain\n print(blah2) #print the markov chaining\n","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":8248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"1472724","text":"from archivo import abrirArchivo\nfrom archivo import escribirArchivo\nfrom archivo import leer_archivo\nfrom functools import reduce\nfrom math import gcd\nimport re\n\n\ndef frecuencia(texto, long_palabra):\n lista_palabras = []\n\n for i in range(len(texto)):\n if len(texto[i:i+long_palabra]) == long_palabra:\n palabra = texto[i:i+long_palabra]\n dic = buscar(palabra, i, texto, long_palabra)\n if not dic.get('repeticion') == 0:\n if len(lista_palabras) == 0:\n lista_palabras.append(dic)\n else:\n dic_repetido = 0\n for dic_temp in lista_palabras:\n if dic_temp.get('palabra') == palabra:\n dic_repetido += 1\n if dic_repetido == 0:\n lista_palabras.append(dic)\n\n return lista_palabras\n\n\ndef calcular_llave_criptografica(lista_palabras):\n distancias = []\n for i in lista_palabras:\n for j in i.get('distancias'):\n distancias.append(j)\n llave = reduce(gcd, tuple(distancias))\n\n return llave\n\n\ndef buscar(palabra, distancia, texto, longitud_palabra):\n dic = {'palabra': palabra, 'repeticion': 0, 'distancias': []}\n for i in range(len(texto)):\n #if palabra == texto[i:i+longitud_palabra] and not i - distancia == 0 and i > distancia:\n if palabra == texto[i:i+longitud_palabra] and not i - distancia == 0:\n dic['repeticion'] += 1\n dic['distancias'].append(i - distancia)\n distancia = i\n return dic\n\n\ndef subcriptogramas(texto, long_clave):\n # Almacenamiento de los subcriptogramas con la longitud de la clave\n dic = {}\n for i in range(long_clave):\n dic[i] = ''\n\n i = 0\n for letra in texto:\n dic[i] += letra\n i += 1\n if i == long_clave:\n i = 0\n return dic\n\n\ndef num_letras_repetidas(subcriptograma):\n dic = {}\n for letra in subcriptograma:\n dic[letra] = subcriptograma.count(letra)\n return dic\n\n\ndef letra_mas_repetida(dic_letras):\n mayores = {}\n for i in range(len(dic_letras)):\n letra = max(dic_letras, key=dic_letras.get)\n # Numero de veces que se repite una letra en el criptograma\n if dic_letras.get(letra) > 5:\n mayores[letra] = dic_letras.pop(letra)\n return mayores\n\n\nalfabeto = {\n 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8,\n 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'Ñ': 14, 'O': 15, 'P': 16,\n 'Q': 17, 'R': 18, 'S': 19, 'T': 20, 'U': 21, 'V': 22, 'W': 23, 'X': 24,\n 'Y': 25, 'Z': 26\n}\n\n# alfabeto = {\n# 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8,\n# 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15,\n# 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23,\n# 'Y': 24, 'Z': 25\n# }\n\n\ndef descifrar_clave(letra_1, letra_2):\n # print('letras ------', letra_1,':', letra_2)\n letra_mas_repetida_1 = 'A'\n letra_mas_repetida_2 = 'E'\n for posicion in range(2):\n valor_clave_1 = (alfabeto.get(letra_1) - alfabeto.get(letra_mas_repetida_1)) % len(alfabeto)\n valor_clave_2 = (alfabeto.get(letra_2) - alfabeto.get(letra_mas_repetida_2)) % len(alfabeto)\n if valor_clave_1 == valor_clave_2:\n for letra_alfabeto, valor_alfabeto in alfabeto.items():\n if valor_alfabeto == valor_clave_1:\n # print('valor -----------', valor_alfabeto, ':', letra_alfabeto)\n return letra_alfabeto\n else:\n letra_mas_repetida_1 = 'E'\n letra_mas_repetida_2 = 'A'\n\n\ndef descifrar_letra(letra, clave):\n # Aplica la formula para obtener el texto en claro\n valor_descifrado = (alfabeto.get(letra) - alfabeto.get(clave)) % len(alfabeto)\n for letra_alfabeto, valor_alfabeto in alfabeto.items():\n if valor_alfabeto == valor_descifrado:\n return letra_alfabeto\n\n\ndef metodo_kasiski(ruta_archivo):\n texto_completo = leer_archivo(ruta_archivo)\n texto = texto_completo[:215]\n\n longitud_palabra = 3\n lista_palabras = frecuencia(texto, longitud_palabra)\n # print('lista', lista_palabras)\n longitud_clave = calcular_llave_criptografica(lista_palabras)\n print('longitud clave', longitud_clave)\n print()\n\n criptograma = subcriptogramas(texto, longitud_clave)\n\n lista_subcriptogramas = []\n for subcriptograma in criptograma.values():\n lista_subcriptogramas.append(num_letras_repetidas(subcriptograma))\n print('subs:', subcriptograma)\n\n letras_mas_repetidas = []\n for letras in lista_subcriptogramas:\n # print('lista sub:', letras)\n letras_mas_repetidas.append(letra_mas_repetida(letras))\n print()\n print('letra mas repetida', letras_mas_repetidas)\n print()\n\n clave_criptografica = []\n for letras in letras_mas_repetidas:\n l = letras.keys()\n for letra_1 in l:\n for letra_2 in l:\n clave_criptografica.append(descifrar_clave(letra_1, letra_2))\n else:\n break\n\n clave_cadena = ''\n for letra in clave_criptografica:\n if letra:\n clave_cadena += letra\n print('Clave criptografica:', clave_cadena)\n\n\n texto_clave = clave_cadena * len(texto_completo)\n\n texto_clave = texto_clave[:len(texto_completo)]\n\n for letra in clave_criptografica:\n texto_descifrado = []\n for i in range(len(texto_completo)):\n texto_descifrado.append(descifrar_letra(texto_completo[i], texto_clave[i]))\n # print()\n # print(texto_descifrado)\n # print()\n\n mensaje_claro = ''\n for letra in texto_descifrado:\n mensaje_claro += letra\n\n print(\"Archivo generado\")\n escribirArchivo('texto_claro.txt.dec', mensaje_claro)\n\n\nif __name__ == '__main__':\n texto_completo = leer_archivo()\n texto = texto_completo[:215]\n\n longitud_palabra = 3\n lista_palabras = frecuencia(texto, longitud_palabra)\n # print('lista', lista_palabras)\n longitud_clave = calcular_llave_criptografica(lista_palabras)\n print('longitud clave', longitud_clave)\n print()\n\n criptograma = subcriptogramas(texto, longitud_clave)\n\n lista_subcriptogramas = []\n for subcriptograma in criptograma.values():\n lista_subcriptogramas.append(num_letras_repetidas(subcriptograma))\n print('subs:', subcriptograma)\n\n letras_mas_repetidas = []\n for letras in lista_subcriptogramas:\n # print('lista sub:', letras)\n letras_mas_repetidas.append(letra_mas_repetida(letras))\n print()\n print('letra mas repetida', letras_mas_repetidas)\n print()\n\n clave_criptografica = []\n for letras in letras_mas_repetidas:\n l = letras.keys()\n for letra_1 in l:\n for letra_2 in l:\n clave_criptografica.append(descifrar_clave(letra_1, letra_2))\n else:\n break\n\n clave_cadena = ''\n for letra in clave_criptografica:\n if letra:\n clave_cadena += letra\n print('Clave criptografica:', clave_cadena)\n\n\n texto_clave = clave_cadena * len(texto_completo)\n\n texto_clave = texto_clave[:len(texto_completo)]\n\n for letra in clave_criptografica:\n texto_descifrado = []\n for i in range(len(texto_completo)):\n texto_descifrado.append(descifrar_letra(texto_completo[i], texto_clave[i]))\n # print()\n # print(texto_descifrado)\n # print()\n\n mensaje_claro = ''\n for letra in texto_descifrado:\n mensaje_claro += letra\n\n print(\"Archivo generado\")\n escribirArchivo('textos_prueba/texto_claro.txt.dec', mensaje_claro)\n","sub_path":"kasiski.py","file_name":"kasiski.py","file_ext":"py","file_size_in_byte":7722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"35953980","text":"### Alban et Totor\n\n# exec(open('C:/Users/Victor/Documents/programmes/Github/blemais/main.py').read())\n\n\n#### 1. loading packages\n\n# 1.1) import non homemade modules\n#import numpy as np\n#import pandas as pd\nimport os\nimport sys\nimport random\nfrom sklearn import preprocessing\nfrom copy import copy\n#import warnings\n#if os.name == 'posix':\n# from sklearn.exceptions import ConvergenceWarning\n#from sklearn.exceptions import FutureWarning\n\n# 1.2) need to change PATH here\nif os.name == 'posix':\n project_path = os.getcwd()\n # project_path_regressions = os.path.join(project_path, \"regressions\")\nelse:\n project_path = 'C:/Users/Victor/Documents/programmes/Github/blemais'\n sys.path.append(project_path)\n sys.path.append(os.path.join(project_path, \"regressions\"))\n project_path_regressions = os.path.join(project_path, \"regressions\")\n\n# 1.3) import our homemade modules\nfrom tools import *\nfrom regressions.regressions import *\nfrom multi_armed_bandit.multi_armed_bandit import *\n\n\n\n#### 2. Other boring parameters for code execution\n\nif os.name == 'posix':\n warnings.filterwarnings(\"ignore\", category=ConvergenceWarning)\n warnings.filterwarnings(\"ignore\", category=FutureWarning)\n\n \n#### 3. Processing data\n\n# 3.1) loading data\n\nmaize, ind2name, name2ind = loadData(\"TrainingDataSet_Maize.txt\")\n\n\n# 3.2) creating variables\n\nmaize, ind2name, name2ind = addDE(maize, ind2name, name2ind)\nmaize, ind2name, name2ind = addTm(maize, ind2name, name2ind)\nmaize, ind2name, name2ind = addGDD(maize, ind2name, name2ind)\nmaize, ind2name, name2ind = addVarAn(maize, ind2name, name2ind)\n\n\nmaize_squared = copy(maize)\nind2name_squared = copy(ind2name)\nname2ind_squared = copy(name2ind)\n\nmaize_squared = np.concatenate([maize_squared, maize_squared*maize_squared], axis=1)\nmaize_squaredind2name = ind2name+[ n+\"_sqrd\" for n in ind2name]\nmaize_squaredname2ind = {j:i for i,j in enumerate(maize_squaredind2name)}\n\nmaize_squared, maize_squaredind2name, maize_squaredname2ind = delVar(maize_squared, maize_squaredind2name, maize_squaredname2ind, \"NUMD_sqrd\")\nmaize_squared, maize_squaredind2name, maize_squaredname2ind = delVar(maize_squared, maize_squaredind2name, maize_squaredname2ind, \"yield_anomaly_sqrd\")\nmaize_squared, maize_squaredind2name, maize_squaredname2ind = delVar(maize_squared, maize_squaredind2name, maize_squaredname2ind, \"year_harvest_sqrd\")\nmaize_squared, maize_squaredind2name, maize_squaredname2ind = delVar(maize_squared, maize_squaredind2name, maize_squaredname2ind, \"IRR_sqrd\")\n\n# 3.3) creating other datasets from mai one (maize)\n\nmaize_scaled = preprocessing.scale(maize)\nmaize_squared = preprocessing.scale(maize_squared)\nind2name_scaled = copy(ind2name)\nname2ind_scaled = copy(name2ind)\n\ny = maize_scaled[:, name2ind_scaled[\"yield_anomaly\"]]\n\n\nyear = maize[:, name2ind[\"year_harvest\"]]\ndep = maize[:, name2ind[\"NUMD\"]]\n\nx = copy(maize_scaled)\nxind2name = copy(ind2name_scaled)\nxname2ind = copy(name2ind_scaled)\n\n\n# mapping = {i[8] + i[7]:i[0] for i in x[:,:]}\n# mapping_y = {i[8] + i[7]:i[0] for i in x[:,:]}\n# yr = x[:,0]\n\n#x,xind2name,xname2ind = delVar(x, xind2name, xname2ind, [\"year_harvest\", \"yield_anomaly\"])\n\nx,xind2name,xname2ind = delVar(x, xind2name, xname2ind, \"year_harvest\")\nx,xind2name,xname2ind = delVar(x, xind2name, xname2ind, \"yield_anomaly\")\nx,xind2name,xname2ind = delVar(x, xind2name, xname2ind, \"NUMD\")\n\n\n\n#x,xind2name,xname2ind = delVar(x, xind2name, xname2ind, \"IRR\")\n\nx_squared = copy(maize_squared)\nx_squaredind2name = copy(maize_squaredind2name)\nx_squaredname2ind = copy(maize_squaredname2ind)\nx_squared,x_squaredind2name,x_squaredname2ind = delVar(x_squared, x_squaredind2name, x_squaredname2ind, \"year_harvest\")\nx_squared,x_squaredind2name,x_squaredname2ind = delVar(x_squared, x_squaredind2name, x_squaredname2ind, \"yield_anomaly\")\nx_squared,x_squaredind2name,x_squaredname2ind = delVar(x_squared, x_squaredind2name, x_squaredname2ind, \"NUMD\")\n\n# aa = [mapping[i[5]+i[6]] for i in x[:,:]]\n# 1/0\nx_reduced = copy(maize_scaled)\nx_reducedind2name = copy(ind2name_scaled)\nx_reducedname2ind = copy(name2ind_scaled)\nx_reduced,x_reducedind2name,x_reducedname2ind = delVar(x_reduced, x_reducedind2name, x_reducedname2ind, [\"year_harvest\",\"yield_anomaly\"])\nsel1 = ['ETP_5','ETP_6','ETP_7','ETP_8','ETP_9','PR_4','PR_5','SeqPR_8','SeqPR_9','Tm_5','Tm_6','Tm_7','Tm_8','Tm_9']\nx_reduced,x_reducedind2name,x_reducedname2ind = selVar(x_reduced, x_reducedind2name, x_reducedname2ind, sel1)\n\n\nx_lobell = copy(x_squared)\nx_lobellind2name = copy(x_squaredind2name)\nx_lobellname2ind = copy(x_squaredname2ind)\nsel_lobell = ['Tm_4_9','PR_4_9','Tm_4_9_sqrd','PR_4_9_sqrd']\nx_lobell,x_lobellind2name,x_lobellname2ind = selVar(x_lobell, x_lobellind2name, x_lobellname2ind, sel_lobell)\n\nx_lobell2 = copy(x_squared)\nx_lobell2ind2name = copy(x_squaredind2name)\nx_lobell2name2ind = copy(x_squaredname2ind)\nsel_lobell2 = ['Tm_4_9','PR_4_9','Tm_4_9_sqrd','PR_4_9_sqrd','DE_4_9','DE_4_9_sqrd']\nx_lobell2,x_lobell2ind2name,x_lobell2name2ind = selVar(x_lobell2, x_lobellind2name, x_lobell2name2ind, sel_lobell2)\n\nx_an = copy(x_squared)\nx_anind2name = copy(x_squaredind2name)\nx_anname2ind = copy(x_squaredname2ind)\nsel_an = ['Tm_4_9','PR_4_9','Tm_4_9_sqrd','PR_4_9_sqrd','DE_4_9','DE_4_9_sqrd','RV_4_9','RV_4_9_sqrd']\nx_an,x_anind2name,x_anname2ind = selVar(x_an, x_anind2name, x_anname2ind, sel_an)\n\n\nx_origin = copy(x_squared)\nx_originind2name = copy(x_squaredind2name)\nx_originname2ind = copy(x_squaredname2ind)\nsel_origin = ['ETP_1','ETP_2','ETP_3','ETP_4','ETP_5','ETP_6','ETP_7','ETP_8','ETP_9',\n'PR_1','PR_2','PR_3','PR_4','PR_5','PR_6','PR_7','PR_8','PR_9','RV_1','RV_2','RV_3','RV_4','RV_5','RV_6','RV_7','RV_8','RV_9',\n'SeqPR_1','SeqPR_2','SeqPR_3','SeqPR_4','SeqPR_5','SeqPR_6','SeqPR_7','SeqPR_8','SeqPR_9',\n'Tn_1','Tn_2','Tn_3','Tn_4','Tn_5','Tn_6','Tn_7','Tn_8','Tn_9',\n'Tx_1','Tx_2','Tx_3','Tx_4','Tx_5','Tx_6','Tx_7','Tx_8','Tx_9',\n'IRR']\nx_origin,x_originind2name,x_originname2ind = selVar(x_origin, x_originind2name, x_originname2ind, sel_origin)\n\nx_originsqrd = copy(x_squared)\nx_originsqrdind2name = copy(x_squaredind2name)\nx_originsqrdname2ind = copy(x_squaredname2ind)\nsel_originsqrd = sel_origin + [\n'ETP_1_sqrd','ETP_2_sqrd','ETP_3_sqrd','ETP_4_sqrd','ETP_5_sqrd','ETP_6_sqrd','ETP_7_sqrd','ETP_8_sqrd','ETP_9_sqrd',\n'PR_1_sqrd','PR_2_sqrd','PR_3_sqrd','PR_4_sqrd','PR_5_sqrd','PR_6_sqrd','PR_7_sqrd','PR_8_sqrd','PR_9_sqrd',\n'RV_1_sqrd','RV_2_sqrd','RV_3_sqrd','RV_4_sqrd','RV_5_sqrd','RV_6_sqrd','RV_7_sqrd','RV_8_sqrd','RV_9_sqrd',\n'SeqPR_1_sqrd','SeqPR_2_sqrd','SeqPR_3_sqrd','SeqPR_4_sqrd','SeqPR_5_sqrd','SeqPR_6_sqrd','SeqPR_7_sqrd','SeqPR_8_sqrd','SeqPR_9_sqrd',\n'Tn_1_sqrd','Tn_2_sqrd','Tn_3_sqrd','Tn_4_sqrd','Tn_5_sqrd','Tn_6_sqrd','Tn_7_sqrd','Tn_8_sqrd','Tn_9_sqrd',\n'Tx_1_sqrd','Tx_2_sqrd','Tx_3_sqrd','Tx_4_sqrd','Tx_5_sqrd','Tx_6_sqrd','Tx_7_sqrd','Tx_8_sqrd','Tx_9_sqrd']\nx_originsqrd,x_originsqrdind2name,x_originsqrdname2ind = selVar(x_originsqrd, x_originsqrdind2name, x_originsqrdname2ind, sel_originsqrd)\n\n\n\n\nx_year = copy(x)\nxind2name_year = copy(xind2name)\nxname2ind_year = copy(xname2ind)\nyear[:,np.newaxis].shape\nmat_year = np.repeat(year[:,np.newaxis],np.unique(year).shape[0],axis=1)\nmat_year.shape\nmat_year = mat_year == np.unique(year[:,np.newaxis])\nmat_year = mat_year.T\n#mat_year.shape\n#np.sum(mat_year,axis = 1)[:,np.newaxis].shape\n#np.sum(mat_year,axis = 1)\nmat_year = mat_year.astype(float)/(np.sum(mat_year,axis = 1)[:,np.newaxis])\nx_year = mat_year.dot(x_year)\n\n#x_dep.shape\n#x.shape\n#x_dep\n\ny_year = copy(y)\ny_year = mat_year.dot(y_year)\n\nyear_year = copy(year)\nyear_year = mat_year.dot(year_year)\nyear_year = np.asarray([int(round(i)) for i in year_year])\n\n\n# all_data = [(x,y,year), (x_reduced,y,year), (x_lobell,y,year), (x_lobell2,y,year), (x_an,y,year), (x_squared,y,year)]\n\n\n#### 4) Runing regressions\n\n#err = run_all_regressions(x, y, regs=0, verbose=True, show=False, x_test=0.1, final_verbose=range(5))\n\n# err = run_all_regressions(x, y, regs=\"regressions/reg_lists/features.py\", verbose=True, show=False, x_test=0.1, final_verbose=range(15))\n# err = run_all_regressions(x, y, regs=\"regressions/reg_lists/five_best.py\", verbose=True, show=False, x_test=0.1, final_verbose=range(15))\n\n# sel = Uniform_MAB(1, 370)\n# err = run_all_regressions(x, y, regs=0, verbose=True, show=False, x_test=0.1, final_verbose=range(15),selection_algo=sel)\n# err = run_all_regressions(x, y, regs=0, verbose=True, show=False, x_test=0.1, final_verbose=range(5))\n#err = run_all_regressions(x, y, regs=\"regressions/reg_lists/features.py\", verbose=True, show=False, x_test=0.1, final_verbose=range(15))\nsel = Uniform_MAB(1, 1)#12*5)\n#err = run_all_regressions(x, y, regs=\"regressions/reg_lists/five_best.py\", verbose=True, show=False, x_test=0.1, final_verbose=range(15), selection_algo=sel, seed=3, split_func=split_func_for_reg(year))\n# err = run_all_regressions(x, y, regs=[SVR()], verbose=True, show=False, x_test=0.1,selection_algo=sel)\n\n\n\n# from sklearn.decomposition import PCA\n# pca = PCA(n_components=2)\n# pca.fit(x)\n# import copy\n# a = copy.deepcopy(pca.components_)\n# ia = np.argsort(a[1,:])\n# [(round(a[1,i],3), ind2name[i]) for i in ia]\n# plt.plot(a[:,ia].transpose())\n\n\n#err = run_all_regressions(x, y, regs=0, verbose=True, show=False, x_test=0.1, final_verbose=range(15), selection_algo=sel, seed=5, split_func=split_func_for_reg(year))\n\n#err = run_all_regressions(x, y, regs=\"regressions/reg_lists/five_best.py\", verbose=True, show=False, x_test=0.1, final_verbose=range(15), selection_algo=sel, seed=5, split_func=split_func_for_reg(year))\n\n#err = run_all_regressions(x, y, regs=\"regressions/reg_lists/five_best.py\", verbose=True, show=False, x_test=0.1, final_verbose=False, selection_algo=sel, seed=0, split_func=split_func_for_reg(year))\n\n\n# s = split_func_for_reg(year)\n# x_train, x_test, y_train, y_test = s(x, y)\n\n# x = x_train\n# y = y_train\n\nimport sklearn\n# d = sklearn.metrics.pairwise.euclidean_distances(x_train, x_test)\n\n# means = []\n# for i,v in enumerate(x_test):\n# ind = np.argsort(d[:,i])\n# means += [ np.mean(y_train[ind[1:4]]) ]\n\n# np.mean((y_test - means)**2)\n\n\n# a = sorted(range(d.shape[0]), key=lambda x:np.sum(d[x,:]))\n# x1 = x[a,:]\n# y1 = y[a]\n# d1 = d[a,:][:,a]\n# year1 = year[a]\n\n\n# err = run_all_regressions(x, y, regs=\"regressions/reg_lists/five_best.py\", verbose=True, show=False, x_test=0.1, final_verbose=False, selection_algo=sel, seed=0, save_all_fit_regs=True, split_func=split_func_for_reg(year))\n\n# reg = err[0]['reg'][1]\n\n# c = 0+reg.coef_\n# c = c/np.linalg.norm(c)\n# ind = np.argsort(np.abs(c))[::-1]\n# x2 = np.concatenate([x_lobell, x[:,ind[:0]]], axis=1)\n# xx = np.dot(x, np.diag(c))\n\n# x = xx\n\n\n#x = preprocessing.scale(np.concatenate([x, x*x], axis=1))\n\n#s = split_func_for_reg_2(year)\n\n\nsel = Uniform_MAB(1, 3)\n#err = run_all_regressions(x, y, regs=\"regressions/reg_lists/one_of_each.py\", verbose=True, show=False, x_test=0.1, final_verbose=True, selection_algo=sel, seed=0, save_all_fit_regs=True, split_func=split_func_for_reg(year))\nerr = run_all_regressions(x, y, regs=\"regressions/reg_lists/one_of_each.py\", verbose=True, show=False, x_test=0.1, final_verbose=True, selection_algo=sel, seed=0, save_all_fit_regs=True, split_func=split_func_for_reg(year))\n1/0\n\n\nd = sklearn.metrics.pairwise.euclidean_distances(x, x)\na = sorted(range(d.shape[0]), key=lambda x:np.sum(d[x,:]))\nx = x[a,:]\ny = y[a]\nyear = year[a]\n\n\na = np.argsort(year)\nx = x[a,:]\ny = y[a]\n\nd = sklearn.metrics.pairwise.euclidean_distances(x, x)\nplt.imshow(d)\nplt.show()\n1/0\ncolors = 'bkrgmc'\n\nfor i,c in enumerate(colors):\n years = list(set(year))\n indexes = (year == years[i])\n iindexes = (year != years[i])\n\n xx = x[indexes]\n xxi = x[iindexes] \n yy = y[indexes]\n yyi = y[iindexes]\n \n d = sklearn.metrics.pairwise.euclidean_distances(xx, xxi)\n \n y1 = np.repeat(yy[:,np.newaxis], yy.shape[0], axis=1)\n y2 = np.repeat(yy[np.newaxis,:], yy.shape[0], axis=0)\n yy = y1 - y2\n \n indexes = np.concatenate([np.ones(20000), np.zeros(3394**2)])[:yy.shape[0]**2]\n np.random.shuffle(indexes)\n indexes = indexes == 1\n \n p_x = yy.flatten()[indexes]\n p_y = d.flatten()[indexes]\n \n plt.scatter(p_x, p_y, s=1, c=c)\nplt.show()\n\n\n1/0\n\n# err = run_all_regressions(x, y, regs=\"regressions/reg_lists/five_best.py\", verbose=True, show=False, x_test=0.1, final_verbose=False, selection_algo=sel, seed=0, save_all_fit_regs=True, split_func=split_func_for_reg(year))\n\n# reg = err[0]['reg'][1]\n\n# c = 0+reg.coef_\n# c = c/np.linalg.norm(c)\n# xx = np.dot(x, np.diag(c))\n\n# x = xx\n\n\nsel = Uniform_MAB(1, 3)\nerr = run_all_regressions(x, y, regs=\"regressions/reg_lists/five_best.py\", verbose=True, show=False, x_test=0.1, final_verbose=True, selection_algo=sel, seed=0, save_all_fit_regs=True, split_func=split_func_for_reg(year))\n\n\n1/0\n\nxx_test = np.dot(x_test, np.diag(c))\ndd = sklearn.metrics.pairwise.euclidean_distances(xx, xx)\n\nmeans = []\nfor i,v in enumerate(xx_test):\n ind = np.argsort(dd[:,i])\n means += [ np.mean(y_train[ind[1:4]]) ]\n\nnp.mean((y_test - means)**2)\n\n\n\n\n1/0\ndd = sklearn.metrics.pairwise.euclidean_distances(xx, xx)\naa = sorted(range(dd.shape[0]), key=lambda x:np.sum(dd[x,:]))\ndd1 = dd[aa,:][:,aa]\nyy1 = y[aa]\ny1 = np.repeat(yy1[:,np.newaxis], 3394, axis=1)\ny2 = np.repeat(yy1[np.newaxis,:], 3394, axis=0)\nyy2 = y1 - y2\n\npoints = [(i,j) for i,j in zip(yy2.flatten(),dd1.flatten())]\n\npoints_x = yy2.flatten()\npoints_y = dd1.flatten()\n\n\n\n\nfor b in np.unique(year):\n print(b)\n x2 = x[year==b,:]\n y2 = y[year==b]\n err = run_all_regressions(x2, y2, regs=\"regressions/reg_lists/five_best.py\", verbose=True, show=False, x_test=0.1, final_verbose=False, selection_algo=sel, seed=None, save_all_fit_regs=True)\n\n\n# err = run_all_regressions(x, y, regs=\"regressions/reg_lists/five_best.py\", verbose=True, show=False, x_test=0.1, final_verbose=range(4), selection_algo=sel, seed=None, split_func=split_func_for_reg(year), save_all_fit_regs=True)\n\n\ny_pred = err[0]['reg'][1].predict(x)\n\nexport = np.column_stack((x,y,y_pred))\nxind2name+[\"yield_anomaly_real\",\"yield_anomaly_SVR\"]\ndf = pd.DataFrame(export,columns = xind2name+[\"yield_anomaly_real\",\"yield_anomaly_SVR\"])\ndf.to_csv(project_path+\"/data/predict.csv\")\n\n\n#err = run_all_regressions(x_squared, y, regs=\"regressions/reg_lists/five_best.py\", verbose=True, show=False, x_test=0.1, final_verbose=False, selection_algo=sel, seed=5, split_func=split_func_for_reg(year))\n\n\n#err = run_all_regressions(x, y, regs=\"C:/Users/Victor/Documents/programmes/Github/blemais/regressions/reg_lists/five_best.py\", verbose=True, show=False, x_test=0.1, final_verbose=range(15))\n\n# from sklearn.preprocessing import PolynomialFeatures\n# poly = PolynomialFeatures(2)#, interaction_only=True)\n# poly.fit(x)\n# xx = poly.transform(x)\n\n# xx = np.concatenate([x, x*x], axis=1)\n\n#x=np.array([[0,1,2,3,4,5,6],[7,8,9,10,11,12,13]])\n\n\nerr = run_all_regressions(x_year, y_year, regs=\"regressions/reg_lists/one_of_each.py\", verbose=True, show=False, x_test=0.1, final_verbose=False, selection_algo=sel, seed=5, split_func=split_func_for_reg(year_year))\n\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"374300989","text":"import matplotlib.pyplot as plt \nimport numpy as np\n\nx = [0, 1, 2, 3 ,4, 5, 6, 7, 8]\ny1 = [0, 0, 1, 1, 0, 1, 0, 1, 1]\ny2 = [0, 1, 2, 3, 1, 0, 2, 1, 0]\n\nfig, ax = plt.subplots(1, 2, figsize=(10, 4), sharey=True)\n\nax[0].set_ylim(-1, 4)\nax[0].step(x, y1, where='pre')\nfor i in range(1, len(x)):\n\tax[0].text(x[i]-0.5, y1[i], y1[i], ha='center', va='bottom')\n\tax[1].text(x[i]-0.5, y2[i], y2[i], ha='center', va='bottom')\nax[1].step(x, y2, where='pre')\n\nax[0].set_title('2进制码元(1bit)', fontfamily='STSong')\nax[1].set_title('4进制码元(1bit)', fontfamily='STSong')\nplt.savefig(\"码元.png\")\nplt.show()","sub_path":"计算机基础/计算机网络/images/码元.py","file_name":"码元.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"581115324","text":"import os\n\nfrom absl import app\nfrom absl import logging\nfrom absl import flags\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow import distribute\n\nfrom model.albert import ALBERT_CONFIG\nfrom model.bert import Bert, PreTrainLMPredictor, PreTrainNextSentencePredictor\nfrom model.loss import sparse_categorical_crossentropy\nfrom model.util import create_attention_mask\n\nfrom lamb import Lamb\n\nFLAGS = flags.FLAGS\nflags.DEFINE_string('strategy', 'mirror', 'Distribution strategy, `mirror` or `tpu`')\nflags.DEFINE_string('tpu_addr', None, 'tpu address')\nflags.DEFINE_list('train_files', None, 'Training tfrecord files')\nflags.DEFINE_integer('train_batch_size', 2, 'Training data batch size')\nflags.DEFINE_list('eval_files', None, 'Training tfrecord files')\nflags.DEFINE_integer('eval_batch_size', 1, 'Evaluating data batch size')\nflags.DEFINE_integer('eval_steps', 1, 'Steps per evaluation')\n# flags.DEFINE_integer('max_seq_length', 512, 'Maximum sequence length of an example')\n# flags.DEFINE_integer('max_mask_length', 20, 'Maximum sequence length of predictable mask token [MASK]')\nflags.DEFINE_integer('shuffle_buffer_size', 4, 'Buffer size for shuffling')\nflags.DEFINE_string('model_type', 'base', 'Albert model type')\nflags.DEFINE_integer('epochs', 4, 'Epochs')\nflags.DEFINE_integer('steps_per_epoch', 5, 'Steps per epoch')\nflags.DEFINE_integer('steps_per_loop', 1, 'Steps per loop')\nflags.DEFINE_float('learning_rate', 5e-5, 'The initial learning rate for Adam.')\n\nflags.DEFINE_string(\n 'model_dir', './model-out', 'The output directory where the model checkpoints will be written.'\n)\nflags.DEFINE_integer('max_checkpoint_to_keep', 5, 'How many checkpoints to keep')\nflags.DEFINE_string('init_checkpoint', None, 'Initial checkpoint')\n\n\ndef _init(max_seq_length, max_mask_length):\n global NAME_TO_FEATURES\n NAME_TO_FEATURES = {\n 'input_ids': tf.io.FixedLenFeature(shape=(max_seq_length,), dtype=tf.int64),\n 'input_mask': tf.io.FixedLenFeature(shape=(max_seq_length,), dtype=tf.int64),\n 'segment_ids': tf.io.FixedLenFeature(shape=(max_seq_length,), dtype=tf.int64),\n 'mask_positions': tf.io.FixedLenFeature(shape=(max_mask_length,), dtype=tf.int64),\n 'mask_label_ids': tf.io.FixedLenFeature(shape=(max_mask_length,), dtype=tf.int64),\n 'mask_weights': tf.io.FixedLenFeature(shape=(max_mask_length,), dtype=tf.int64),\n 'next_id': tf.io.FixedLenFeature(shape=(1,), dtype=tf.int64),\n }\n\n\ndef _float_metric_value(metric):\n return metric.result().numpy().astype(float)\n\n\ndef init_tpu(tpu_addr):\n \"\"\"Initializes TPU for TF 2.0 training.\n Args:\n tpu_address: string, bns address of master TPU worker.\n Returns:\n A TPUClusterResolver.\n \"\"\"\n cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu=tpu_addr)\n if tpu_addr not in ('', 'local'):\n tf.config.experimental_connect_to_cluster(cluster_resolver)\n tf.tpu.experimental.initialize_tpu_system(cluster_resolver)\n return cluster_resolver\n\n\ndef save_model(checkpoint, model_dir, path):\n checkpoint_path = os.path.join(model_dir, path)\n checkpoint.save(checkpoint_path)\n\n\ndef steps_to_run(current_step, steps_per_epoch, steps_per_loop):\n if steps_per_loop == 1:\n return steps_per_loop\n if current_step + steps_per_loop < steps_per_epoch:\n return steps_per_loop\n else:\n return steps_per_epoch - current_step\n\n\ndef dump_example(raw_example):\n example = tf.io.parse_single_example(raw_example, NAME_TO_FEATURES)\n return example\n\n\ndef gather_indexes(logits, mask_positions):\n # logits = [batch_size, max_seq_length, vocab_size]\n # mask_positions = [batch_size, max_mask_length]\n vocab_size = logits.shape[-1]\n masks_features = tf.gather(logits, mask_positions, batch_dims=1)\n # [batch_size * max_mask_length, vocab_size]\n return tf.reshape(masks_features, [-1, vocab_size])\n\n\ndef model_fn(config):\n max_seq_length = config['max_seq_length']\n input_ids = keras.Input(shape=(max_seq_length,), name='input_ids')\n attention_mask = keras.Input(shape=(max_seq_length,), name='attention_mask')\n segment_ids = keras.Input(shape=(max_seq_length,), name='segment_ids')\n\n albert = Bert(config)\n first_tokens, output = albert([input_ids, attention_mask, segment_ids])\n\n # albert_model = keras.Model(inputs=[input_ids, attention_mask, segment_ids], outputs=output)\n albert_model = keras.Model(\n inputs={\n 'input_ids': input_ids,\n 'attention_mask': attention_mask,\n 'segment_ids': segment_ids\n },\n outputs=[first_tokens, output]\n )\n\n lm_predictor = PreTrainLMPredictor(\n config['input_hidden'],\n config['vocab_size'],\n max_seq_length,\n )\n lm_predict_outputs = lm_predictor([output, albert.embedding.embeddings, albert.projection])\n next_sentence_predictor = PreTrainNextSentencePredictor(2)\n next_sentence_predict_outputs = next_sentence_predictor(first_tokens)\n\n classifier_model = keras.Model(\n inputs={\n 'input_ids': input_ids,\n 'attention_mask': attention_mask,\n 'segment_ids': segment_ids\n },\n outputs=[lm_predict_outputs, next_sentence_predict_outputs]\n )\n\n # Optimizer\n lamb_optimizer = Lamb()\n return classifier_model, albert_model, lamb_optimizer\n\n\ndef main(_):\n config = ALBERT_CONFIG[FLAGS.model_type]\n _init(config['max_seq_length'], config['max_mask_length'])\n\n # Make strategy\n assert FLAGS.strategy, 'Strategy can not be empty'\n if FLAGS.strategy == 'mirror':\n strategy = distribute.MirroredStrategy()\n elif FLAGS.strategy == 'tpu':\n cluster_resolver = init_tpu(FLAGS.tpu_addr)\n strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)\n else:\n raise ValueError('The distribution strategy type is not supported: %s' % FLAGS.strategy)\n\n # Prepare training dataset\n file_list = tf.data.Dataset.list_files(FLAGS.train_files)\n train_dataset = tf.data.TFRecordDataset(filenames=file_list)\n train_dataset = train_dataset.shuffle(buffer_size=FLAGS.shuffle_buffer_size)\n train_dataset = train_dataset.map(\n dump_example, num_parallel_calls=tf.data.experimental.AUTOTUNE\n ).cache()\n train_dataset = train_dataset.shuffle(100)\n train_dataset = train_dataset.repeat() # loop\n train_dataset = train_dataset.batch(FLAGS.train_batch_size)\n train_dataset = train_dataset.prefetch(FLAGS.train_batch_size)\n\n # Prepare evaluation dataset\n file_list = tf.data.Dataset.list_files(FLAGS.eval_files)\n eval_dataset = tf.data.TFRecordDataset(filenames=file_list)\n eval_dataset = eval_dataset.map(\n dump_example, num_parallel_calls=tf.data.experimental.AUTOTUNE\n ).cache()\n eval_dataset = eval_dataset.batch(FLAGS.eval_batch_size)\n eval_dataset = eval_dataset.prefetch(FLAGS.eval_batch_size)\n\n def make_iter_dataset(dataset):\n iter_dataset = iter(strategy.experimental_distribute_dataset(train_dataset))\n return iter_dataset\n\n # Training\n with strategy.scope():\n # Build Albert model\n logging.info('Build albert: config: %s', config)\n classifier_model, albert_model, optimizer = model_fn(config)\n\n if FLAGS.init_checkpoint:\n logging.info('Restore albert_model from initial checkpoint: %s', FLAGS.init_checkpoint)\n checkpoint = tf.train.Checkpoint(albert_model=albert_model)\n checkpoint.restore(FLAGS.init_checkpoint)\n\n # Make metric functions\n train_loss_metric = keras.metrics.Mean('training_loss', dtype=tf.float32)\n eval_metrics = [\n keras.metrics.SparseCategoricalAccuracy('test_accuracy', dtype=tf.float32),\n ]\n train_metrics = [\n keras.metrics.SparseCategoricalAccuracy('test_accuracy', dtype=tf.float32),\n ]\n\n # Make summary writers\n summary_dir = os.path.join(FLAGS.model_dir, 'summaries')\n eval_summary_writer = tf.summary.create_file_writer(os.path.join(summary_dir, 'eval'))\n train_summary_writer = tf.summary.create_file_writer(os.path.join(summary_dir, 'train'))\n\n def step_fn(batch):\n input_ids = batch['input_ids']\n input_mask = batch['input_mask']\n segment_ids = batch['segment_ids']\n mask_positions = batch['mask_positions']\n mask_label_ids = batch['mask_label_ids']\n mask_weights = batch['mask_weights']\n next_id = batch['next_id']\n attention_mask = create_attention_mask(input_mask)\n\n train_inputs = {\n 'input_ids': input_ids,\n 'attention_mask': attention_mask,\n 'segment_ids': segment_ids,\n }\n\n with tf.GradientTape() as tape:\n train_outputs = classifier_model(train_inputs)\n lm_logits = gather_indexes(train_outputs[0], mask_positions)\n loss_lm = sparse_categorical_crossentropy(\n mask_label_ids,\n lm_logits,\n weights=mask_weights,\n from_logits=True,\n )\n next_logits = train_outputs[1]\n loss_next = sparse_categorical_crossentropy(\n next_id,\n next_logits,\n from_logits=True,\n )\n loss = loss_lm + loss_next\n\n grads = tape.gradient(loss, classifier_model.trainable_weights)\n optimizer.apply_gradients(list(zip(grads, classifier_model.trainable_weights)))\n\n # metric\n train_loss_metric.update_state(loss)\n for metric in train_metrics:\n # mask_label_ids = [batch_size * max_mask_length, 1]\n mask_label_ids = tf.reshape(mask_label_ids, [-1, 1])\n\n metric.update_state(mask_label_ids, lm_logits)\n metric.update_state(next_id, next_logits)\n\n return loss\n\n @tf.function\n def train_steps(iterator, steps):\n for step in tf.range(steps):\n strategy.experimental_run_v2(step_fn, args=(next(iterator),))\n\n @tf.function\n def test_step(iterator):\n\n def test_step_fn(batch):\n input_ids = batch['input_ids']\n input_mask = batch['input_mask']\n segment_ids = batch['segment_ids']\n mask_positions = batch['mask_positions']\n mask_label_ids = batch['mask_label_ids']\n next_id = batch['next_id']\n attention_mask = create_attention_mask(input_mask)\n\n eval_inputs = {\n 'input_ids': input_ids,\n 'attention_mask': attention_mask,\n 'segment_ids': segment_ids,\n }\n eval_outputs = classifier_model(eval_inputs)\n lm_logits = gather_indexes(eval_outputs[0], mask_positions)\n next_logits = eval_outputs[1]\n\n for metric in eval_metrics:\n # mask_label_ids = [batch_size * max_mask_length, 1]\n mask_label_ids = tf.reshape(mask_label_ids, [-1, 1])\n\n metric.update_state(mask_label_ids, lm_logits)\n metric.update_state(next_id, next_logits)\n\n strategy.experimental_run_v2(test_step_fn, args=(next(iterator),))\n\n def _run_evaluation(current_step, iterator):\n for _ in range(FLAGS.eval_steps):\n test_step(iterator)\n\n log = f'eval step: {current_step}, '\n with eval_summary_writer.as_default():\n for metric in eval_metrics:\n metric_value = _float_metric_value(metric)\n tf.summary.scalar(metric.name, metric_value, step=current_step)\n log += f'metric: {metric.name} = {metric_value}, '\n eval_summary_writer.flush()\n logging.info(log)\n\n # Restore classifier_model\n checkpoint = tf.train.Checkpoint(model=classifier_model, optimizer=optimizer)\n latest_checkpoint_file = tf.train.latest_checkpoint(FLAGS.model_dir)\n if latest_checkpoint_file:\n logging.info(\n 'Restore classifier_model from the latest checkpoint file: %s',\n latest_checkpoint_file\n )\n checkpoint.restore(latest_checkpoint_file)\n\n train_iter_dataset = make_iter_dataset(train_dataset)\n total_training_steps = FLAGS.epochs * FLAGS.steps_per_epoch\n current_step = optimizer.iterations.numpy()\n while current_step < total_training_steps:\n steps = steps_to_run(current_step, FLAGS.steps_per_epoch, FLAGS.steps_per_loop)\n # Converts steps to a Tensor to avoid tf.function retracing.\n train_steps(train_iter_dataset, tf.convert_to_tensor(steps, dtype=tf.int32))\n current_step += steps\n logging.info('Step: %s', current_step)\n\n log = f'training step: {current_step}, '\n with train_summary_writer.as_default():\n for metric in train_metrics + [train_loss_metric]:\n metric_value = _float_metric_value(metric)\n tf.summary.scalar(metric.name, metric_value, step=current_step)\n log += f'metric: {metric.name} = {metric_value}, '\n train_summary_writer.flush()\n\n if current_step % FLAGS.steps_per_epoch:\n checkpoint_path = os.path.join(FLAGS.model_dir, f'model_step_{current_step}.ckpt')\n checkpoint.save(checkpoint_path)\n logging.info('Save model to {checkpoint_path}')\n\n eval_iter_dataset = make_iter_dataset(eval_dataset)\n _run_evaluation(current_step, eval_iter_dataset)\n\n\nif __name__ == '__main__':\n app.run(main)\n","sub_path":"run_pretraining.py","file_name":"run_pretraining.py","file_ext":"py","file_size_in_byte":13927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"476247604","text":"# !/usr/bin/env python2\n# -*- coding:utf-8 -*-\n\nimport tensorflow as tf\nfrom utils import AverageMeter, read_ann_file, \\\n loadvocab, gen_whole_tags, gen_dataset_item, \\\n loadw2v, edu_tag, get_val_datalist, \\\n switch_vocab_keyval, merge_cont_and_tag\n\nimport numpy as np\n\nMAX_SENTENCES = 20\nMAX_CHARS = 40\n\ntrain_file = './data/eduexpr_x_ann.txt'\ndocs_train = read_ann_file(train_file)\n\nchar_vocab = {}\nchar_vocab_file = '../extsrc/ttt_vocab.txt'\nloadvocab(char_vocab_file, char_vocab)\n\ntag_vocab = {}\ngen_whole_tags(edu_tag, tag_vocab)\n\ndef gen_tfitem(cont_o_arr, tag_o_arr):\n assert (len(cont_o_arr)) == MAX_SENTENCES * MAX_CHARS\n example = tf.train.Example(\n features = tf.train.Features(\n feature={\n 'target': tf.train.Feature(\n int64_list = tf.train.Int64List(value=tag_o_arr)\n ),\n 'chars': tf.train.Feature(\n int64_list = tf.train.Int64List(value=cont_o_arr)\n )\n }\n )\n )\n return example\n\nimport os\n\noutdir = './tfdata'\nif not os.path.isdir(outdir):\n os.makedirs(outdir)\n\ntrain_writer = tf.python_io.TFRecordWriter('./tfdata/tfrecord.train')\ntest_writer = tf.python_io.TFRecordWriter('./tfdata/tfrecord.test')\n\nwriter = train_writer\n\nfor doc in docs_train:\n cont_o_arr, tag_o_arr = \\\n gen_dataset_item(doc, 20, 40, char_vocab, tag_vocab)\n cont_o_arr = cont_o_arr.astype(np.int64).reshape([-1])\n tag_o_arr = tag_o_arr.astype(np.int64).reshape([-1])\n if np.random.random() < 0.8:\n writer = train_writer\n else:\n writer = test_writer\n record = gen_tfitem(cont_o_arr, tag_o_arr)\n writer.write(record.SerializeToString())\n\ntrain_writer.close()\ntest_writer.close()\n\n","sub_path":"try/gen_edu_tfrecord.py","file_name":"gen_edu_tfrecord.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"418288033","text":"# coding=utf-8\n# @Author : bamtercelboo\n# @Datetime : 2018/07/19 22:35\n# @File : train_ALL_LSTM.py\n# @Last Modify Time : 2018/07/19 22:35\n# @Contact : bamtercelboo@{gmail.com, 163.com}\n\nimport os\nimport sys\nimport torch\nimport torch.autograd as autograd\nimport torch.nn.functional as F\nimport torch.nn.utils as utils\n\nimport random\nfrom DataUtils.Common import seed_num\nfrom DataUtils.Evaluate import evaluate_b\ntorch.manual_seed(seed_num)\nrandom.seed(seed_num)\n\n\n\ndef train(train_iter, dev_iter, test_iter, model, args):\n if args.cuda:\n model.cuda()\n\n if args.Adam is True:\n print(\"Adam Training......\")\n optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.init_weight_decay)\n elif args.SGD is True:\n print(\"SGD Training.......\")\n optimizer = torch.optim.SGD(model.parameters(), lr=args.lr, weight_decay=args.init_weight_decay,\n momentum=args.momentum_value)\n elif args.Adadelta is True:\n print(\"Adadelta Training.......\")\n optimizer = torch.optim.Adadelta(model.parameters(), lr=args.lr, weight_decay=args.init_weight_decay)\n\n model_count = 0\n best_accuracy = Best_Result()\n model.train()\n for epoch in range(1, args.epochs+1):\n steps = 0\n print(\"\\n## The {} Epoch, All {} Epochs ! ##\".format(epoch, args.epochs))\n for batch in train_iter:\n feature, target = batch.text, batch.label\n feature.data.t_(), target.data.sub_(1) # batch first, index align\n if args.cuda is True:\n feature, target = feature.cuda(), target.cuda()\n\n target = autograd.Variable(target) # question 1\n optimizer.zero_grad()\n logit = model(feature)\n loss = F.cross_entropy(logit, target, weight=torch.tensor([1,125]).float().cuda())\n loss.backward()\n if args.init_clip_max_norm is not None:\n utils.clip_grad_norm(model.parameters(), max_norm=args.init_clip_max_norm)\n optimizer.step()\n\n steps += 1\n if steps % args.log_interval == 0:\n train_size = len(train_iter.dataset)\n y_pred = torch.max(logit, 1)[1].cpu().data.numpy().tolist()\n try:\n result=evaluate_b(target.cpu().data.numpy().tolist(),y_pred)\n sys.stdout.write(\n '\\rBatch[{}/{}] - loss: {:.6f} g-measure: {:.2f})'.format(steps,train_size,loss.item(),result[-1]))\n except Exception:\n # print('\\nValueError: Number of classes, 1, does not match size of target_names, 2')\n print('\\n')\n if steps % args.test_interval == 0:\n print(\"\\nDev Accuracy: \", \"end=\")\n eval(dev_iter, model, args, best_accuracy, epoch, test=False)\n print(\"\\nTest Accuracy: \", \"end=\")\n eval(test_iter, model, args, best_accuracy, epoch, test=True)\n if steps % args.save_interval == 0:\n if not os.path.isdir(args.save_dir): os.makedirs(args.save_dir)\n save_prefix = os.path.join(args.save_dir, 'snapshot')\n save_path = '{}_steps{}.pt'.format(save_prefix, steps)\n torch.save(model.state_dict(), save_path)\n if os.path.isfile(save_path) and args.rm_model is True:\n os.remove(save_path)\n model_count += 1\n return model_count\n\n\ndef eval(data_iter, model, args, best_accuracy, epoch, test=False):\n model.eval()\n y_pred = []\n y_true = []\n corrects, avg_loss = 0, 0\n for batch in data_iter:\n feature, target = batch.text, batch.label\n feature.data.t_(), target.data.sub_(1) # batch first, index align\n\n if args.cuda is True:\n feature, target = feature.cuda(), target.cuda()\n logit = model(feature)\n loss = F.cross_entropy(logit, target, weight=torch.tensor([1,125]).float().cuda(), size_average=True)\n\n avg_loss += loss.item()\n y_pred.extend(torch.max(logit, 1)[1].cpu().data.numpy().tolist())\n y_true.extend(target.cpu().numpy().tolist())\n result = evaluate_b(y_true, y_pred)\n g_measure=result[-1]\n size = len(data_iter.dataset)\n avg_loss = loss.item()/size\n model.train()\n print(' Evaluation - loss: {:.6f} g-measure: {:.2f} '.format(avg_loss, g_measure))\n if test is False:\n if g_measure >= best_accuracy.best_dev_gmeasure:\n best_accuracy.best_dev_gmeasure = g_measure\n best_accuracy.best_epoch = epoch\n best_accuracy.best_test = True\n if test is True and best_accuracy.best_test is True:\n best_accuracy.gmeasure = g_measure\n\n if test is True:\n print(\"The Current Best Dev g-measure: {:.2f}, and Test g-measure is :{:.2f}, locate on {} epoch.\\n\".format(\n best_accuracy.best_dev_gmeasure, best_accuracy.gmeasure, best_accuracy.best_epoch))\n if test is True:\n best_accuracy.best_test = False\n\nclass Best_Result:\n def __init__(self):\n self.best_dev_gmeasure = -1\n self.best_gmeasure = -1\n self.best_epoch = 1\n self.best_test = False\n self.gmeasure = -1\n\n\n","sub_path":"Train/train_ALL_CNN.py","file_name":"train_ALL_CNN.py","file_ext":"py","file_size_in_byte":5240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"587454386","text":"from fac.commands import Command, Arg\nfrom fac.utils import prompt, Version, match_game_version\n\nclass UpdateCommand(Command):\n \"\"\"Update installed mods.\"\"\"\n\n name = \"update\"\n arguments = [\n Arg(\"-s\", \"--show\", action=\"store_true\",\n help=\"only show what would be updated\"),\n\n Arg(\"-y\", \"--yes\", action=\"store_true\",\n help=\"automatic yes to confirmation prompt\"),\n\n Arg(\"-U\", \"--unpacked\", action=\"store_true\",\n help=\"allow updating unpacked mods\"),\n\n Arg(\"-H\", \"--held\", action=\"store_true\",\n help=\"allow updating held mods\"),\n ]\n\n def run(self, args):\n installed = self.manager.find_mods()\n updates = []\n\n if args.ignore_game_ver:\n game_ver = None\n else:\n game_ver = self.config.game_version_major\n\n self.db.update()\n\n for local_mod in installed:\n print(\"Checking: %s %s\" % (local_mod.name, local_mod.version))\n\n found_update = False\n local_ver = local_mod.version\n latest_ver = local_ver\n latest_release = None\n\n try:\n releases = self.manager.get_releases(local_mod.name, game_ver)\n except StopIteration:\n print(\"Cannot get_releases for mod %s with game version %s\" % (local_mod.name, game_ver))\n continue\n\n for release in releases:\n if not args.ignore_game_ver and not match_game_version(release, game_ver):\n continue\n\n release_ver = Version(release.version)\n\n if release_ver > latest_ver:\n found_update = True\n latest_ver = release_ver\n latest_release = release\n\n\n update_mod = True\n if found_update:\n print(\"Found update: %s %s\" % (\n local_mod.name, latest_ver)\n )\n\n if not args.unpacked and not local_mod.packed:\n print(\n \"%s is unpacked. \"\n \"Use -U to update it anyway.\" % (\n local_mod.name\n )\n )\n update_mod = False\n \n\n if not args.held and local_mod.name in self.config.hold:\n print(\"%s is held. \"\n \"Use -H to update it anyway.\" %\n local_mod.name)\n update_mod = False\n\n if update_mod:\n updates.append((local_mod, latest_release))\n \n if not updates:\n print(\"No updates were found\")\n return\n\n print(\"Found %d update%s:\" % (\n len(updates),\n \"s\" if len(updates) != 1 else \"\",\n ))\n\n for local_mod, release in updates:\n print(\" %s %s -> %s\" % (\n local_mod.name, local_mod.version, release.version\n ))\n\n if not args.show:\n if not args.yes and prompt(\"Continue?\", \"Y/n\") != \"y\":\n return\n\n for local_mod, release in updates:\n self.manager.install_mod(local_mod.name, release)\n","sub_path":"fac/commands/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"415393488","text":"import requests\r\nimport datetime\r\nimport discord\r\nimport asyncio\r\nimport random\r\nimport logging\r\nimport os.path\r\nimport nekos\r\nimport hentai\r\nfrom hentai import Hentai\r\nimport json\r\nfrom hentai import Format\r\nfrom urllib.parse import urlparse\r\nfrom os.path import splitext\r\nimport random\r\nfrom discord.ext import commands\r\nfrom discord.ext.commands import Bot\r\nfrom discord.utils import get\r\nfrom discord.ext.commands.cooldowns import BucketType\r\nfrom asyncio import sleep\r\nimport json\r\nimport rule34\r\nfrom dateutil.parser import parse\r\n\r\nnow = datetime.datetime.now()\r\nclient = commands.Bot(command_prefix=\"-\")\r\nclient.remove_command(\"help\")\r\n\r\n\r\n@client.event\r\nasync def on_ready():\r\n print(f\"The time is {now.strftime('%B %d, %Y %H:%M:%S')}\")\r\n print(f\"Logged into {client.user}\")\r\n activity = discord.Activity(\r\n name=\"coded by wizard#5236 /-/ Prefix: - \", type=discord.ActivityType.watching\r\n )\r\n await client.change_presence(activity=activity)\r\n\r\n\r\n@commands.cooldown(1, 3, commands.BucketType.user)\r\n@client.command()\r\nasync def bllist(ctx):\r\n with open(\"blacklist.json\") as json_file:\r\n first = json_file.read(1)\r\n if not first:\r\n json_file.close()\r\n pass\r\n\r\n with open(\"blacklist.json\") as json_file:\r\n data = json.load(json_file)\r\n for id in data[\"users\"]:\r\n if str(ctx.author.id) == str(id[\"id\"]):\r\n await ctx.send(\"You're blacklisted from using commands!\")\r\n return\r\n\r\n embed = discord.Embed(title=\" \", color=0x659F67)\r\n embed.set_author(name=f\"Wiz Bot's Blacklist\", icon_url=ctx.author.avatar_url)\r\n embed.add_field(\r\n name=\"Blacklisted Users\",\r\n value=f\"\"\"\r\n```json\\n\r\n{json.dumps(data, indent=1)}\r\n```\r\n\"\"\",\r\n inline=True,\r\n )\r\n embed.set_footer(text=\"coded by wizard#5236\")\r\n await ctx.send(embed=embed)\r\n\r\n\r\n@client.group()\r\nasync def help(ctx):\r\n if ctx.invoked_subcommand is None:\r\n await ctx.send(\r\n \"NSFW: `-help nsfw` Administration: `-help admin` General: `-help general`\"\r\n )\r\n\r\n\r\n@help.command()\r\nasync def nsfw(ctx):\r\n await ctx.send(\"Commands: -dentai, -gentai, -r34, -keywords, -rantai, -search\")\r\n\r\n\r\n@help.command()\r\nasync def admin(ctx):\r\n await ctx.send(\"Commands: -blacklist, -ban\")\r\n\r\n\r\n@help.command()\r\nasync def general(ctx):\r\n await ctx.send(\"Commands: -ping, -info\")\r\n\r\n\r\n@client.command()\r\nasync def keywords(ctx):\r\n with open(\"blacklist.json\") as json_file:\r\n first = json_file.read(1)\r\n if not first:\r\n json_file.close()\r\n pass\r\n\r\n with open(\"blacklist.json\") as json_file:\r\n data = json.load(json_file)\r\n for id in data[\"users\"]:\r\n if str(ctx.author.id) == str(id[\"id\"]):\r\n await ctx.send(\"You're blacklisted from using commands!\")\r\n return\r\n\r\n possible = [\r\n \"feet\",\r\n \"yuri\",\r\n \"trap\",\r\n \"futanari\",\r\n \"hololewd\",\r\n \"lewdkemo\",\r\n \"solog\",\r\n \"feetg\",\r\n \"cum\",\r\n \"erokemo\",\r\n \"les\",\r\n \"wallpaper\",\r\n \"lewdk\",\r\n \"ngif\",\r\n \"tickle\",\r\n \"lewd\",\r\n \"feed\",\r\n \"gecg\",\r\n \"eroyuri\",\r\n \"eron\",\r\n \"cum_jpg\",\r\n \"bj\",\r\n \"nsfw_neko_gif\",\r\n \"solo\",\r\n \"kemonomimi\",\r\n \"nsfw_avatar\",\r\n \"gasm\",\r\n \"poke\",\r\n \"anal\",\r\n \"slap\",\r\n \"hentai\",\r\n \"avatar\",\r\n \"erofeet\",\r\n \"holo\",\r\n \"keta\",\r\n \"blowjob\",\r\n \"pussy\",\r\n \"tits\",\r\n \"holoero\",\r\n \"lizard\",\r\n \"pussy_jpg\",\r\n \"pwankg\",\r\n \"classic\",\r\n \"kuni\",\r\n \"waifu\",\r\n \"pat\",\r\n \"8ball\",\r\n \"kiss\",\r\n \"femdom\",\r\n \"neko\",\r\n \"spank\",\r\n \"cuddle\",\r\n \"erok\",\r\n \"fox_girl\",\r\n \"boobs\",\r\n \"random_hentai_gif\",\r\n \"smallboobs\",\r\n \"hug\",\r\n \"ero\",\r\n \"smug\",\r\n \"goose\",\r\n \"baka\",\r\n \"woof\",\r\n ]\r\n member = ctx.author\r\n possible = \" \".join(possible[:])\r\n possible = str(possible).replace(\" \", \", \")\r\n embed = discord.Embed(title=\" \", color=0xFF0000)\r\n embed.set_author(name=\" \", icon_url=member.avatar_url)\r\n embed.timestamp = datetime.datetime.utcnow()\r\n embed.add_field(name=\"Keywords\", value=f\"```{possible}```\", inline=False)\r\n embed.set_footer(text=\"powered by nekos.life\")\r\n await ctx.send(embed=embed)\r\n\r\n\r\n@client.command()\r\nasync def ping(ctx):\r\n with open(\"blacklist.json\") as json_file:\r\n first = json_file.read(1)\r\n if not first:\r\n json_file.close()\r\n pass\r\n\r\n with open(\"blacklist.json\") as json_file:\r\n data = json.load(json_file)\r\n for id in data[\"users\"]:\r\n if str(ctx.author.id) == str(id[\"id\"]):\r\n await ctx.send(\"You're blacklisted from using commands!\")\r\n return\r\n\r\n now = datetime.datetime.now()\r\n embed = discord.Embed(colour=discord.Colour.red())\r\n embed.set_author(name=\"Pong!\")\r\n embed.set_footer(text=f\"{round(client.latency * 1000)}ms\")\r\n embed.timestamp = datetime.datetime.now()\r\n await ctx.send(embed=embed)\r\n\r\n\r\n@client.command()\r\nasync def rantai(ctx):\r\n with open(\"blacklist.json\") as json_file:\r\n first = json_file.read(1)\r\n if not first:\r\n json_file.close()\r\n pass\r\n\r\n with open(\"blacklist.json\") as json_file:\r\n data = json.load(json_file)\r\n for id in data[\"users\"]:\r\n if str(ctx.author.id) == str(id[\"id\"]):\r\n await ctx.send(\"You're blacklisted from using commands!\")\r\n return\r\n\r\n pictures = [\r\n \"feet\",\r\n \"yuri\",\r\n \"trap\",\r\n \"futanari\",\r\n \"hololewd\",\r\n \"lewdkemo\",\r\n \"erokemo\",\r\n \"les\",\r\n \"lewdk\",\r\n \"lewd\",\r\n \"eroyuri\",\r\n \"eron\",\r\n \"cum_jpg\",\r\n \"bj\",\r\n \"solo\",\r\n \"kemonomimi\",\r\n \"nsfw_avatar\",\r\n \"erofeet\",\r\n \"holo\",\r\n \"keta\",\r\n \"blowjob\",\r\n \"tits\",\r\n \"holoero\",\r\n \"pussy_jpg\",\r\n \"kuni\",\r\n \"femdom\",\r\n \"neko\",\r\n \"erok\",\r\n \"boobs\",\r\n \"smallboobs\",\r\n \"ero\",\r\n ]\r\n embed = discord.Embed(colour=discord.Colour.red())\r\n\r\n randomChoice = random.choice(pictures)\r\n embed.set_author(name=f'Sent an random NSFW picture with the tag \"{randomChoice}\"!')\r\n embed.set_image(url=nekos.img(randomChoice))\r\n embed.timestamp = datetime.datetime.now()\r\n embed.set_footer(text=\"Powered by nekos.life!\")\r\n await ctx.send(embed=embed)\r\n\r\n\r\n@client.command()\r\nasync def search(ctx, word):\r\n with open(\"blacklist.json\") as json_file:\r\n first = json_file.read(1)\r\n if not first:\r\n json_file.close()\r\n pass\r\n\r\n with open(\"blacklist.json\") as json_file:\r\n data = json.load(json_file)\r\n for id in data[\"users\"]:\r\n if str(ctx.author.id) == str(id[\"id\"]):\r\n await ctx.send(\"You're blacklisted from using commands!\")\r\n return\r\n\r\n possible = [\r\n \"feet\",\r\n \"yuri\",\r\n \"trap\",\r\n \"futanari\",\r\n \"hololewd\",\r\n \"lewdkemo\",\r\n \"solog\",\r\n \"feetg\",\r\n \"cum\",\r\n \"erokemo\",\r\n \"les\",\r\n \"wallpaper\",\r\n \"lewdk\",\r\n \"ngif\",\r\n \"tickle\",\r\n \"lewd\",\r\n \"feed\",\r\n \"gecg\",\r\n \"eroyuri\",\r\n \"eron\",\r\n \"cum_jpg\",\r\n \"bj\",\r\n \"nsfw_neko_gif\",\r\n \"solo\",\r\n \"kemonomimi\",\r\n \"nsfw_avatar\",\r\n \"gasm\",\r\n \"poke\",\r\n \"anal\",\r\n \"slap\",\r\n \"hentai\",\r\n \"avatar\",\r\n \"erofeet\",\r\n \"holo\",\r\n \"keta\",\r\n \"blowjob\",\r\n \"pussy\",\r\n \"tits\",\r\n \"holoero\",\r\n \"lizard\",\r\n \"pussy_jpg\",\r\n \"pwankg\",\r\n \"classic\",\r\n \"kuni\",\r\n \"waifu\",\r\n \"pat\",\r\n \"8ball\",\r\n \"kiss\",\r\n \"femdom\",\r\n \"neko\",\r\n \"spank\",\r\n \"cuddle\",\r\n \"erok\",\r\n \"fox_girl\",\r\n \"boobs\",\r\n \"random_hentai_gif\",\r\n \"smallboobs\",\r\n \"hug\",\r\n \"ero\",\r\n \"smug\",\r\n \"goose\",\r\n \"baka\",\r\n \"woof\",\r\n ]\r\n\r\n if word in possible:\r\n embed = discord.Embed(colour=discord.Colour.red())\r\n embed.set_author(name=f'Sent with the tag: \"{word}\"!')\r\n embed.set_image(url=nekos.img(word))\r\n embed.timestamp = datetime.datetime.now()\r\n embed.set_footer(text=\"Powered by nekos.life!\")\r\n await ctx.send(embed=embed)\r\n else:\r\n await ctx.send(\"Invalid keyword.\")\r\n\r\n\r\n@client.command()\r\nasync def gentai(ctx):\r\n with open(\"blacklist.json\") as json_file:\r\n first = json_file.read(1)\r\n if not first:\r\n json_file.close()\r\n pass\r\n\r\n with open(\"blacklist.json\") as json_file:\r\n data = json.load(json_file)\r\n for id in data[\"users\"]:\r\n if str(ctx.author.id) == str(id[\"id\"]):\r\n await ctx.send(\"You're blacklisted from using commands!\")\r\n return\r\n\r\n pictures = [\"random_hentai_gif\", \"solog\", \"feetg\", \"cum\", \"pussy\"]\r\n\r\n embed = discord.Embed(colour=discord.Colour.red())\r\n\r\n randomChoice = random.choice(pictures)\r\n embed.set_author(name=f'Sent with the tag: \"{randomChoice}\"!')\r\n embed.set_image(url=nekos.img(randomChoice))\r\n embed.timestamp = datetime.datetime.now()\r\n embed.set_footer(text=\"Powered by nekos.life!\")\r\n await ctx.send(embed=embed)\r\n\r\n\r\n@client.command()\r\nasync def dentai(ctx, number):\r\n with open(\"blacklist.json\") as json_file:\r\n first = json_file.read(1)\r\n if not first:\r\n json_file.close()\r\n pass\r\n\r\n with open(\"blacklist.json\") as json_file:\r\n data = json.load(json_file)\r\n for id in data[\"users\"]:\r\n if str(ctx.author.id) == str(id[\"id\"]):\r\n await ctx.send(\"You're blacklisted from using commands!\")\r\n return\r\n\r\n cur_page = 1\r\n doujin = Hentai(number)\r\n pages = doujin.num_pages\r\n pages2 = doujin.num_pages - 1\r\n member = ctx.author\r\n embed = discord.Embed(colour=discord.Colour.red())\r\n embed2 = discord.Embed(colour=discord.Colour.red())\r\n embed.set_author(name=\"Would you like to read this Doujinshii?\")\r\n embed.add_field(\r\n name=f\"Doujin:\", value=f\"{doujin.title(Format.Pretty)}\", inline=False\r\n )\r\n embed.add_field(name=\"Tags:\", value=[tag.name for tag in doujin.tag], inline=False)\r\n embed.set_image(url=doujin.image_urls[0])\r\n message = await ctx.send(embed=embed)\r\n await message.add_reaction(\"✅\")\r\n await message.add_reaction(\"🚫\")\r\n\r\n def check(reaction, user):\r\n return user == ctx.author and str(reaction.emoji) in [\"✅\", \"🚫\"]\r\n\r\n try:\r\n reaction, user = await client.wait_for(\r\n \"reaction_add\", timeout=60.0, check=check\r\n )\r\n except asyncio.TimeoutError:\r\n await member.send(\"You didn't respond.\")\r\n await message.delete()\r\n else:\r\n if reaction.emoji == \"🚫\":\r\n await ctx.send(\"Ok.\")\r\n await message.delete()\r\n await message.clear_reactions()\r\n if reaction.emoji == \"✅\":\r\n await message.delete()\r\n embed2.set_author(\r\n name=f\"Doujin: {doujin.title(Format.Pretty)} [Page: {cur_page}/{pages}]\"\r\n )\r\n embed2.add_field(\r\n name=\"Tags:\", value=[tag.name for tag in doujin.tag], inline=False\r\n )\r\n embed2.set_image(url=doujin.image_urls[0])\r\n embed2.timestamp = datetime.datetime.now()\r\n embed2.set_footer(text=\"Powered by NHentai\")\r\n message = await ctx.send(embed=embed2)\r\n await message.add_reaction(\"◀\")\r\n await message.add_reaction(\"▶\")\r\n await message.add_reaction(\"✅\")\r\n\r\n def check2(reaction, user):\r\n return user == ctx.author and str(reaction.emoji) in [\"◀\", \"▶\", \"✅\"]\r\n\r\n while True:\r\n try:\r\n reaction, user = await client.wait_for(\r\n \"reaction_add\", timeout=60.0, check=check2\r\n )\r\n except asyncio.TimeoutError:\r\n await member.send(\r\n \"You didn't read the next page of your doujinshii within 1 minute! Deleted your doujin.\"\r\n )\r\n await message.delete()\r\n break\r\n else:\r\n if reaction.emoji == \"▶\" and cur_page != pages:\r\n cur_page += 1\r\n\r\n embed3 = discord.Embed(colour=discord.Colour.red())\r\n\r\n embed3.set_author(\r\n name=f\"Doujin: {doujin.title(Format.Pretty)} [Page: {cur_page}/{pages}]\"\r\n )\r\n embed3.add_field(\r\n name=\"Tags:\",\r\n value=[tag.name for tag in doujin.tag],\r\n inline=False,\r\n )\r\n embed3.set_image(url=doujin.image_urls[cur_page - 1])\r\n embed3.timestamp = datetime.datetime.now()\r\n embed3.set_footer(text=\"Powered by NHentai!\")\r\n await message.edit(embed=embed3)\r\n await message.remove_reaction(reaction, user)\r\n if reaction.emoji == \"✅\":\r\n embed5 = discord.Embed(colour=discord.Colour.red())\r\n\r\n if cur_page != pages:\r\n embed5.set_author(name=f\"Doujin stopped at Page {cur_page}\")\r\n embed5.add_field(\r\n name=\"Tags:\",\r\n value=[tag.name for tag in doujin.tag],\r\n inline=False,\r\n )\r\n embed5.add_field(name=f\"ID:\", value=doujin.id, inline=False)\r\n embed5.timestamp = datetime.datetime.now()\r\n embed5.set_footer(text=f\"{round(client.latency * 1000)}ms\")\r\n await message.edit(embed=embed5)\r\n await message.clear_reactions()\r\n break\r\n else:\r\n embed5.set_atuhor(name=f\"Finished Doujin!\")\r\n embed5.add_field(\r\n name=\"Tags:\",\r\n value=[tag.name for tag in doujin.tag],\r\n inline=False,\r\n )\r\n embed5.add_field(name=f\"ID:\", value=doujin.id, inline=False)\r\n embed5.timestamp = datetime.datetime.now()\r\n embed5.set_footer(text=f\"{round(client.latency * 1000)}ms\")\r\n await message.edit(embed=embed5)\r\n await message.clear_reactions()\r\n break\r\n elif reaction.emoji == \"◀\" and cur_page != 0:\r\n cur_page -= 1\r\n\r\n embed4 = discord.Embed(colour=discord.Colour.red())\r\n\r\n embed4.set_author(\r\n name=f\"Doujin: {doujin.title(Format.Pretty)} [Page: {cur_page}/{pages}]\"\r\n )\r\n embed4.add_field(\r\n name=\"Tags:\",\r\n value=[tag.name for tag in doujin.tag],\r\n inline=False,\r\n )\r\n embed4.set_image(url=doujin.image_urls[cur_page - 1])\r\n embed4.timestamp = datetime.datetime.now()\r\n embed4.set_footer(text=\"Powered by NHentai!\")\r\n await message.edit(embed=embed4)\r\n await message.remove_reaction(reaction, user)\r\n\r\n\r\n@commands.cooldown(1, 3, commands.BucketType.user)\r\n@client.command()\r\nasync def blacklist(ctx, members: commands.Greedy[discord.Member], *reason, time):\r\n reason = \" \".join(reason[:])\r\n if ctx.author.id == 325849904570302469:\r\n bldata = {}\r\n bldata[\"users\"] = []\r\n embed = discord.Embed(title=\" \", color=0xFF0000)\r\n embed.set_author(name=\"You've been blacklisted!\")\r\n embed.add_field(name=\"Reason:\", value=reason, inline=True)\r\n embed.add_field(name=\"Time:\", value=time, inline=True)\r\n for member in members:\r\n bldata[\"users\"].append({\"user\": str(member), \"id\": str(member.id)})\r\n await ctx.send(f\"{member.mention} has been blacklisted!\")\r\n await member.send(embed=embed)\r\n with open(\r\n \"C:/Users/archmage/Documents/projection/blacklist.json\", \"w\"\r\n ) as blacklist:\r\n json.dump(bldata, blacklist)\r\n else:\r\n await ctx.send(\r\n \"You cannot blacklist users as you are not the owner of the bot!\"\r\n )\r\n\r\n\r\n@commands.cooldown(1, 3, commands.BucketType.user)\r\n@client.command()\r\nasync def info(ctx, user: discord.Member):\r\n with open(\"blacklist.json\") as json_file:\r\n first = json_file.read(1)\r\n if not first:\r\n json_file.close()\r\n pass\r\n\r\n with open(\"blacklist.json\") as json_file:\r\n data = json.load(json_file)\r\n for id in data[\"users\"]:\r\n if str(ctx.author.id) == str(id[\"id\"]):\r\n await ctx.send(\"You're blacklisted from using commands!\")\r\n return\r\n\r\n embed = discord.Embed(title=\" \", color=0x659F67)\r\n embed.set_author(name=f\"Details of {user.name}\", icon_url=user.avatar_url)\r\n embed.add_field(name=\"Name\", value=user.name, inline=True)\r\n embed.add_field(name=\"ID\", value=user.id, inline=True)\r\n embed.add_field(name=\"Highest Role\", value=user.top_role, inline=True)\r\n embed.add_field(name=\"Join Date\", value=user.joined_at, inline=True)\r\n embed.add_field(name=\"Created Account\", value=user.created_at, inline=True)\r\n embed.set_footer(text=\"coded by wizard#5236\")\r\n await ctx.send(embed=embed)\r\n\r\n\r\n@commands.cooldown(1, 3, commands.BucketType.user)\r\n@client.command()\r\nasync def r34(ctx, *tag):\r\n with open(\"blacklist.json\") as json_file:\r\n first = json_file.read(1)\r\n if not first:\r\n json_file.close()\r\n pass\r\n\r\n with open(\"blacklist.json\") as json_file:\r\n data = json.load(json_file)\r\n for id in data[\"users\"]:\r\n if str(ctx.author.id) == str(id[\"id\"]):\r\n await ctx.send(\"You're blacklisted from using commands!\")\r\n return\r\n\r\n tag = \" \".join(tag[:])\r\n tag = str(tag).replace(\" \", \"+\")\r\n r34 = rule34.Rule34(asyncio.get_running_loop())\r\n total_images = await r34.totalImages(str(tag))\r\n get_images = await r34.getImages(tags=str(tag), singlePage=True)\r\n image = get_images[int(1)] # idfk man\r\n await ctx.send(\r\n f\"\"\"```Total images: {total_images}```\r\n ```Tags: {image.tags}``` \r\n ```Created at {image.created_at}```\"\"\"\r\n )\r\n await ctx.send(image.file_url)\r\n\r\n\r\n@commands.cooldown(1, 3, commands.BucketType.user)\r\n@client.command()\r\nasync def ban(ctx, member: discord.Member, bantime, *reason):\r\n with open(\"blacklist.json\") as json_file:\r\n first = json_file.read(1)\r\n if not first:\r\n json_file.close()\r\n pass\r\n\r\n with open(\"blacklist.json\") as json_file:\r\n data = json.load(json_file)\r\n for id in data[\"users\"]:\r\n if str(ctx.author.id) == str(id[\"id\"]):\r\n await ctx.send(\"You're blacklisted from using commands!\")\r\n return\r\n\r\n reason = \" \".join(reason[:])\r\n if member.bot == False or member == ctx.author or member == None:\r\n embed = discord.Embed(title=\" \", color=0xFF0000)\r\n embed.set_author(name=\"Confirmation\")\r\n embed.add_field(name=\"User:\", value=f\"<@{member.id}>\", inline=True)\r\n embed.add_field(name=\"Time Banned for\", value=bantime, inline=True)\r\n embed.add_field(name=\"Reason of ban\", value=reason, inline=False)\r\n embed.set_footer(text=f\"ID: {member.id}\")\r\n message = await ctx.send(embed=embed)\r\n await message.add_reaction(\"✅\")\r\n await message.add_reaction(\"🚫\")\r\n\r\n def check(reaction, user):\r\n return user == ctx.author and str(reaction.emoji) in [\"✅\", \"🚫\"]\r\n\r\n try:\r\n reaction, user = await client.wait_for(\r\n \"reaction_add\", timeout=60.0, check=check\r\n )\r\n except asyncio.TimeoutError:\r\n await member.send(\r\n \"asyncio.TimeoutError | You didn't react within 60 seconds. \"\r\n )\r\n await message.delete()\r\n else:\r\n if reaction.emoji == \"🚫\":\r\n await message.delete()\r\n await message.clear_reactions()\r\n if reaction.emoji == \"✅\":\r\n await ctx.guild.ban(member, reason=reason, delete_message_days=1)\r\n await message.clear_reactions()\r\n embed2 = discord.Embed(title=\" \", color=0xFF0000)\r\n embed2.set_author(name=\"User banned!\")\r\n embed2.add_field(name=\"User:\", value=f\"<@{member.id}>\", inline=True)\r\n embed2.add_field(name=\"Time Banned for\", value=bantime, inline=True)\r\n embed2.add_field(name=\"Reason of ban\", value=reason, inline=False)\r\n embed3 = discord.Embed(title=\" \", color=0xFF0000)\r\n embed3.set_author(name=\"You've gotten banned!\")\r\n embed3.add_field(name=\"User:\", value=f\"<@{member.id}>\", inline=True)\r\n embed3.add_field(name=\"Time Banned for\", value=bantime, inline=True)\r\n embed3.add_field(name=\"Reason of ban\", value=reason, inline=False)\r\n await message.edit(embed=embed2)\r\n await member.send(embed=embed3) # add server name later etc\r\n else:\r\n await ctx.send(\"An error occured while trying to ban this user.\")\r\n\r\n\r\n@client.event\r\nasync def on_command_error(ctx, error):\r\n if isinstance(error, commands.CommandOnCooldown):\r\n embed = discord.Embed(title=\"\", color=0xA4CBFE)\r\n embed.set_author(name=\"Command Cooldown\")\r\n embed.add_field(\r\n name=\"You can use this command in\",\r\n value=f\"{round(error.retry_after, 2)}s\",\r\n inline=False,\r\n )\r\n embed.set_footer(text=\"coded by wizard#5236\")\r\n await ctx.send(embed=embed)\r\n\r\n\r\nclient.run(\"\")\r\n","sub_path":"Wiz Bot.py","file_name":"Wiz Bot.py","file_ext":"py","file_size_in_byte":23137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"570302193","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nimport os\nle = LabelEncoder()\n\ndata = pd.read_csv(\"Files/Titanic_Survivor/Dataset/train.csv\")\n\n#print(data.head(n=10))\n\n#print(data.info())\n\ncolumns_to_drop=[\"PassengerId\",\"Name\",\"Ticket\",\"Cabin\",\"Embarked\"]\ndata_clean=data.drop(columns_to_drop,axis=1)\n#print(data_clean.head(n=10))\ndata_clean[\"Sex\"]=le.fit_transform(data_clean[\"Sex\"])\n#print(data_clean.head(n=10))\n\n#print(data_clean.info())\n\ndata_clean=data_clean.fillna(data_clean[\"Age\"].mean())\ninput_cols = [\"Pclass\",\"Sex\",\"Age\",\"SibSp\",\"Parch\",\"Fare\"]\noutput_cols=[\"Survived\"]\n\nX=data_clean[input_cols]\nY=data_clean[output_cols]\n\n#print(X.shape,Y.shape)\n#print(type(X))\n\n\ndef entropy(col):\n counts = np.unique(col, return_counts=True)\n N = float(col.shape[0])\n\n entr = 0.0\n\n for ix in counts[1]:\n p = ix / N\n entr += (-1.0 * p * np.log2(p))\n return entr\n\n\ncols=np.array([1,1,1,1,1,1,1,1,1])\nprint(entropy(cols))\n\n\ndef divide_data(x_data, fkey, fval):\n x_right = pd.DataFrame([], columns=x_data.columns)\n x_left = pd.DataFrame([], columns=x_data.columns)\n\n for ix in range(x_data.shape[0]):\n\n val = x_data[fkey].loc[ix]\n\n if val > fval:\n x_right = x_right.append(x_data.loc[ix])\n\n else:\n x_left = x_left.append(x_data.loc[ix])\n\n return x_left, x_right\n\nx_left,x_right = divide_data(data_clean[:10],'Sex' , 0.5)\n#print(x_left)\n#print(x_right)\n\n\ndef information_gain(x_data, fkey, fval):\n left, right = divide_data(x_data, fkey, fval)\n\n l = float(left.shape[0]) / x_data.shape[0]\n\n r = float(right.shape[0]) / x_data.shape[0]\n\n if left.shape[0] == 0 or right.shape[0] == 0:\n return -10000\n i_gain = entropy(x_data.Survived) - (l * entropy(left.Survived) + r * entropy(right.Survived))\n\n return i_gain\n\n\nfor fx in X.columns:\n #print(fx)\n\n #print(information_gain(data_clean, fx, data_clean[fx].mean()))\n\n\n class DecisionTree:\n def __init__(self, depth=0, max_depth=4):\n self.left = None\n self.right = None\n self.fkey = None\n self.fval = None\n self.max_depth = max_depth\n self.depth = depth\n self.target = None\n\n def train(self, X_train):\n features = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare']\n info_gains = []\n\n for ix in features:\n i_gain = information_gain(X_train, ix, X_train[ix].mean())\n info_gains.append(i_gain)\n\n self.fkey = features[np.argmax(info_gains)]\n self.fval = X_train[self.fkey].mean()\n\n # print(\"Making tree features is\",self.fkey)\n\n data_left, data_right = divide_data(X_train, self.fkey, self.fval)\n data_left = data_left.reset_index(drop=True)\n data_right = data_right.reset_index(drop=True)\n\n if data_left.shape[0] == 0 or data_right.shape[0] == 0:\n if X_train.Survived.mean() >= 0.5:\n self.target = \"Survive\"\n\n else:\n self.target = \"Dead\"\n\n return\n\n if (self.depth >= self.max_depth):\n if X_train.Survived.mean() >= 0.5:\n self.target = \"Survive\"\n\n else:\n self.target = \"Dead\"\n\n return\n self.left = DecisionTree(depth=self.depth + 1, max_depth=self.max_depth)\n\n self.left.train(data_left)\n\n self.right = DecisionTree(depth=self.depth + 1, max_depth=self.max_depth)\n\n self.right.train(data_right)\n\n if X_train.Survived.mean() >= 0.5:\n self.target = \"Survive\"\n\n else:\n self.target = \"Dead\"\n return\n\n def predict(self, test):\n\n if test[self.fkey] > self.fval:\n\n if self.right is None:\n return self.target\n\n return self.right.predict(test)\n\n else:\n\n if self.left is None:\n return self.target\n\n return self.left.predict(test)\n\n\nd=DecisionTree()\nd.train(data_clean)\n\n# y_pred = []\n# for ix in range(data_clean.shape[0]):\n# y_pred.append(d.predict(data_clean.loc[ix]))\n\n#print(y_pred)\n\n#data4 = pd.read_csv(\"datasets/file_name3.csv\")\n#y_pred = []\n#for ix in range(data4.shape[0]):\n #y_pred.append(d.predict(data4.loc[ix]))\n\n#print(y_pred)\ndef survivor(sent1,sent2,sent3,sent4,sent5,sent6):\n name_dict = {\n 'Survived': [1],\n 'Pclass': [sent1],\n 'Sex': [sent2],\n 'Age': [sent3],\n 'SibSp': [sent4],\n 'Parch': [sent5],\n 'Fare': [sent6]\n }\n\n df = pd.DataFrame(name_dict)\n df.to_csv('titanic.csv')\n data = pd.read_csv(\"titanic.csv\")\n y_pred = []\n for ix in range(data.shape[0]):\n y_pred.append(d.predict(data.loc[ix]))\n\n os.remove('titanic.csv')\n\n return y_pred\n\n\n\n\n","sub_path":"Titanic_Survivor/Titanic.py","file_name":"Titanic.py","file_ext":"py","file_size_in_byte":4825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"225592348","text":"from __future__ import print_function\nimport os \nimport numpy as np\nimport tensorflow as tf\nimport pandas as pd \nimport matplotlib.pyplot as plt \nimport sys\n#You have freedom of using eager execution in tensorflow\nplt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\n'''\n\nIST 597: Foundations of Deep Learning\n\nProblem 2a: 1-Layer MLP for IRIS\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 \n /////////******************/////////\n //// Umar Farooq Mohammad /////////\n //// ubm5020@psu.edu /////////\n /////////******************/////////\n'''\ndef computeCost(X,y,theta,reg):\n scores,probs = predict(X,theta)\n probs = probs.numpy()\n size = X.shape[0]\n probs = -np.log(probs)\n cost = 0 # initialization to zero at first\n for i in range(len(y)):\n temp = y[i]\n cost = cost + probs[i][temp]\n cost = cost/size\n W = theta[0]\n W2 = theta[2]\n res =((reg/2)*np.sum(np.power(W.numpy(),2))) + ((reg/2)*np.sum(np.power(W2.numpy(),2))) + cost\n return res\n\t# WRITEME: write your code here to complete the routine\t\n\t\t\t\ndef computeGrad(X,y,theta,reg):# returns nabla\n\n scores,probs = predict(X,theta)\n probs = probs.numpy()\n size = X.shape[0]\n for i in range(len(y)):\n temp = y[i]\n probs[i][temp] -= 1\n\n W = theta[0].numpy()\n W2 = theta[2].numpy()\n Pred = np.matmul(X,W) + theta[1].numpy() # b\n res = np.multiply(Pred,(Pred>0))\n dLdf = probs\n dLdh = (1/size)*np.matmul(probs,W2.transpose())\n dLdPred = np.multiply(dLdh,Pred>0)\n \n \n dW2 = np.matmul(res.transpose(),(1/size)*dLdf) + (reg*W2)\n db2 = np.sum((1/size)*dLdf,axis=0)\n dW = np.matmul(X.transpose(),dLdPred) + (reg*W)\n db = np.sum(dLdPred,axis=0)\n return (dW,db,dW2,db2)\n\n\ndef predict(X,theta):# WRITEME: write your code here to complete the routine\n\tW = theta[0].numpy()\n\tb = theta[1].numpy()\n\tW2 = theta[2].numpy()\n\tb2 = theta[3].numpy()\n\tPred = np.matmul(X,W) + b\n\tres = np.multiply(Pred,(Pred>0))\n\t#scores and probability\n\tscores = np.matmul(res,W2) + b2\n\tA = tf.exp(scores)\n\tB = tf.math.reduce_sum(A,axis=1)\n\tprobs = tf.transpose((tf.transpose(A)/B))\n\treturn (scores,probs)\n\n\t\ndef create_mini_batch(X, y, start, end):\n\t# WRITEME: write your code here to complete the routine\n\tA = X[start:end]\n\tB = y[start:end]\n\treturn (A, B)\n\t\t\n\"\"\"def shuffle(X,y):\n\tii = np.arange(X.shape[0])\n\tii = np.random.shuffle(ii)\n\tX_rand = X[ii]\n\ty_rand = y[ii]\n\tX_rand = X_rand.reshape(X_rand.shape[1:])\n\ty_rand = y_rand.reshape(y_rand.shape[1:])\n\treturn (X_rand,y_rand)\"\"\"\n\t\nnp.random.seed(21131186)\n# Load in the data from disk\npath = os.getcwd() + '/data/iris_train.dat' \ndata = pd.read_csv(path, header=None) \n\n# set X (training data) and y (target variable)\ncols = data.shape[1] \nX = data.iloc[:,0:cols-1] \ny = data.iloc[:,cols-1:cols] \n\n# convert from data frames to numpy matrices\nX = np.array(X.values) \ny = np.array(y.values)\ny = y.flatten()\nX_tf = tf.constant(X)\nY_tf = tf.constant(y)\n# load in validation-set\npath = os.getcwd() + '/data/iris_test.dat'\ndata = pd.read_csv(path, header=None) \ncols = data.shape[1] \nX_v = data.iloc[:,0:cols-1] \ny_v = data.iloc[:,cols-1:cols] \n\nX_v = np.array(X_v.values) \ny_v = np.array(y_v.values)\ny_v = y_v.flatten()\n\nX_V_tf = tf.constant(X_v)\nY_V_tf = tf.constant(y_v)\n\n\n# initialize parameters randomly\nD = X.shape[1]\nK = np.amax(y) + 1\n\n# initialize parameters randomly\nh = 100 # size of hidden layer\ninitializer = tf.random_normal_initializer(mean=0.0, stddev=0.01, seed=21131186)\nW = tf.Variable(initializer([D, h]))\nb = tf.Variable(tf.random.normal([h]))\nW2 = tf.Variable(initializer([h, K]))\nb2 = tf.Variable(tf.random.normal([K]))\ntheta = (W,b,W2,b2)\n\n# some hyperparameters\nn_e = 50\nn_b = 10\nstep_size = 0.001 #1e-0\nreg = 1e-4 #1e-3 # regularization strength\n\ntrain_cost = []\nvalid_cost = []\n# gradient descent loop\nnum_examples = X.shape[0]\ncheck = 100\n\nfor i in range(n_e):\n\tshuffler = np.random.permutation(len(X))\n\tShuffledX = X[shuffler]\n\tShuffledY = y[shuffler]\n\t#X, y = tf.random_shuffle([X_tf,Y_tf])# re-shuffle the data at epoch start to avoid correlations across mini-batches\n\t# WRITEME: write your code here to perform a step of gradient descent & record anything else desired for later\n\t# you can use the \"check\" variable to decide when to calculate losses and record/print to screen (as in previous sub-problems)\n\n\t# WRITEME: write the inner training loop here (1 full pass, but via mini-batches instead of using the full batch to estimate the gradient)\n\ts = 0\n\t\n\t\n\ttrain_res = computeCost(ShuffledX,ShuffledY,theta,reg)\n\t#print(train_res)\n\ttrain_cost.append(train_res)\n\tval_res = computeCost(X_v,y_v,theta,reg)\n\tvalid_cost.append(val_res)\n\t\n\t\n\tprint('loss at iteration %i is %f'%(i,train_res))\n\t\n\twhile (s < num_examples):\n\t\t# build mini-batch of samples\n\t\tX_mb, y_mb = create_mini_batch(ShuffledX,ShuffledY,s,s + n_b)\n\t\t\n\t\t# WRITEME: gradient calculations and update rules go here\n\t\t\n\t\ts += n_b\n\t\tdW,db,dW2,db2 = computeGrad(X_mb,y_mb,theta,reg) \n\t\tW = W - (step_size*dW)\n\t\tb = b - (step_size*db)\n\t\tW2 = W2 - (step_size*dW2)\n\t\tb2 = b2 - (step_size*db2)\n\t\ttheta = (W,b,W2,b2)\n\nprint(' > Training loop completed!')\n# TODO: remove this line below once you have correctly implemented/gradient-checked your various sub-routines\n\nplt.figure()\nplt.title(\"Training and Validation cost per epoch\")\nplt.xlabel(\"epoch number\")\nplt.ylabel(\"cost for this epoch\")\nplt.plot(train_cost,label = 'Training')\nplt.plot(valid_cost,label = 'validation')\nplt.legend()\nplt.show()\n#sys.exit(0) \n\nscores, probs = predict(X,theta)\npredicted_class = (tf.argmax(scores, axis=1))\nprint('training accuracy: %f '%((np.mean(predicted_class == y))))\n\nscores, probs = predict(X_v,theta)\npredicted_class = (tf.argmax(scores, axis=1))\nprint('validation accuracy: %f' % ((np.mean(predicted_class == y_v))))\n\n# NOTE: write your plot generation code here (for example, using the \"train_cost\" and \"valid_cost\" list variables)\n","sub_path":"HW2/prob2a.py","file_name":"prob2a.py","file_ext":"py","file_size_in_byte":6646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"314274557","text":"from collections import defaultdict\nfrom concurrent.futures import ThreadPoolExecutor\nfrom datetime import datetime\nimport time\nimport traceback\nfrom uuid import uuid4\n\nfrom bioweb_api.utilities.logging_utilities import APP_LOGGER, VERSION\nfrom bioweb_api import FA_PROCESS_COLLECTION, SA_GENOTYPER_COLLECTION, \\\n SA_ASSAY_CALLER_COLLECTION, SA_IDENTITY_COLLECTION, PA_PROCESS_COLLECTION, \\\n SA_EXPLORATORY_COLLECTION\nfrom bioweb_api.apis.ApiConstants import PICO2_DYE, ASSAY_DYE, SUBMIT_DATESTAMP, \\\n MAJOR, MINOR, USE_IID, DYES, DEVICE, ARCHIVE, UUID, JOB_NAME, \\\n OFFSETS, NUM_PROBES, ID_TRAINING_FACTOR, DYE_LEVELS, IGNORED_DYES, FILTERED_DYES, \\\n UI_THRESHOLD, AC_TRAINING_FACTOR, REQUIRED_DROPS, EXP_DEF, JOB_TYPE_NAME, JOB_TYPE, \\\n STATUS, JOB_STATUS, START_DATESTAMP, SUCCEEDED, PA_PROCESS_UUID, CTRL_THRESH, \\\n SA_IDENTITY_UUID, SA_ASSAY_CALLER_UUID, SA_GENOTYPER_UUID, URL, DEFAULT_DEV_MODE, \\\n CONFIG_URL, ERROR, PA_DOCUMENT, ID_DOCUMENT, AC_DOCUMENT, GT_DOCUMENT, REPORT_URL, \\\n PLOT_URL, SCATTER_PLOT_URL, PDF_URL, PNG_URL, PNG_SUM_URL, DEV_MODE, \\\n FINISH_DATESTAMP, TRAINING_FACTOR, VARIANT_MASK, CONTINUOUS_PHASE, PLATE_PLOT_URL, \\\n IS_HDF5, KDE_PNG_URL, KDE_PNG_SUM_URL, MAX_UNINJECTED_RATIO, TEMPORAL_PLOT_URL, \\\n IGNORE_LOWEST_BARCODE, CTRL_FILTER, AC_METHOD, PICO1_DYE, USE_PICO1_FILTER, \\\n HOTSPOT, SEQUENCING, EXPLORATORY, EP_DOCUMENT, SQ_DOCUMENT, SA_EXPLORATORY_UUID, \\\n AC_MODEL, DYES_SCATTER_PLOT_URL, DRIFT_COMPENSATE, DEFAULT_DRIFT_COMPENSATE, \\\n USE_PICO2_FILTER, API_VERSION, BEST_EXIST_JOB, DROP_COUNT_PLOT_URL\nfrom bioweb_api.apis.full_analysis.FullAnalysisUtils import is_param_diff, generate_random_str, \\\n add_unified_pdf\nfrom bioweb_api.apis.primary_analysis.ProcessPostFunction import PaProcessCallable, PROCESS\nfrom bioweb_api.apis.secondary_analysis.IdentityPostFunction import SaIdentityCallable, IDENTITY\nfrom bioweb_api.apis.secondary_analysis.AssayCallerPostFunction import SaAssayCallerCallable, ASSAY_CALLER\nfrom bioweb_api.apis.secondary_analysis.GenotyperPostFunction import SaGenotyperCallable, GENOTYPER\nfrom bioweb_api.apis.secondary_analysis.ExploratoryPostFunction import SaExploratoryCallable\nfrom bioweb_api.apis.primary_analysis.ProcessPostFunction import make_process_callback as pa_make_process_callback\nfrom bioweb_api.apis.secondary_analysis.IdentityPostFunction import make_process_callback as id_make_process_callback\nfrom bioweb_api.apis.secondary_analysis.AssayCallerPostFunction import make_process_callback as ac_make_process_callback\nfrom bioweb_api.apis.secondary_analysis.GenotyperPostFunction import make_process_callback as gt_make_process_callback\nfrom bioweb_api.apis.secondary_analysis.ExploratoryPostFunction import make_process_callback as ep_make_process_callback\nfrom gbutils.exp_def.exp_def_handler import ExpDefHandler\n\n\n# lookup dictionary for last step in workflow\nWORKFLOW_LOOKUP = {HOTSPOT: GENOTYPER, EXPLORATORY: EXPLORATORY, SEQUENCING: SEQUENCING}\n# lookup dictionary for last element in document list\nDOCUMENT_LOOKUP = {HOTSPOT: GT_DOCUMENT, EXPLORATORY: EP_DOCUMENT, SEQUENCING: SQ_DOCUMENT}\n\nclass FullAnalysisWorkFlowCallable(object):\n def __init__(self, parameters, db_connector):\n \"\"\"\n @param parameters: Dictionary containing parameters for all arguments\n for the full analysis job.\n @param db_connector: A DbConnector object.\n \"\"\"\n self.uuid = str(uuid4())\n self.parameters = parameters\n self.db_connector = db_connector\n self.query = {UUID: self.uuid}\n self.document = {\n UUID: self.uuid,\n STATUS: JOB_STATUS.submitted,\n JOB_NAME: parameters[JOB_NAME],\n JOB_TYPE_NAME: JOB_TYPE.full_analysis,\n SUBMIT_DATESTAMP: datetime.today(),\n ARCHIVE: parameters[ARCHIVE],\n IS_HDF5: parameters[IS_HDF5],\n EXP_DEF: parameters[EXP_DEF],\n API_VERSION: VERSION,\n }\n\n self.uuid_container = [None]\n self.db_connector.insert(FA_PROCESS_COLLECTION, [self.document])\n\n def __call__(self):\n self.set_defaults()\n # check if a run needs to be resumed.\n if BEST_EXIST_JOB in self.parameters:\n self.resume_workflow()\n\n update_query = {STATUS: JOB_STATUS.running,\n START_DATESTAMP: datetime.today()}\n\n update = {\"$set\": update_query}\n self.db_connector.update(FA_PROCESS_COLLECTION, self.query, update)\n if self.workflow:\n self.run_analysis()\n\n def set_defaults(self):\n \"\"\"\n There are certain parameters that the user may not have sent\n but that can come from the experiment definition, set them here.\n\n Set workflow based on experiment type. The first 3 stages in each workflow are\n primary analysis, identity, and assay caller. The 4th stage depends on the\n type of experiment, i.e., genotyper API for hotspot experiment, exploratory API\n for exploratory experiment, and sequencing API for sequencing experiment.\n \"\"\"\n try:\n exp_def_fetcher = ExpDefHandler()\n experiment = exp_def_fetcher.get_experiment_definition(self.parameters[EXP_DEF])\n\n self.exp_type = experiment.exp_type\n self.workflow = [PROCESS, IDENTITY, ASSAY_CALLER] + [WORKFLOW_LOOKUP[self.exp_type]]\n self.document_list = [PA_DOCUMENT, ID_DOCUMENT, AC_DOCUMENT] + \\\n [DOCUMENT_LOOKUP[self.exp_type]]\n\n if DYES not in self.parameters or \\\n DYE_LEVELS not in self.parameters or \\\n NUM_PROBES not in self.parameters or \\\n PICO1_DYE not in self.parameters:\n # get dyes and number of levels\n dye_levels = defaultdict(int)\n for barcode in experiment.barcodes:\n for dye_name, lvl in barcode.dye_levels.items():\n dye_levels[dye_name] = max(dye_levels[dye_name], int(lvl+1))\n if DYES not in self.parameters:\n self.parameters[DYES] = dye_levels.keys()\n if DYE_LEVELS not in self.parameters:\n self.parameters[DYE_LEVELS] = dye_levels.items()\n if NUM_PROBES not in self.parameters:\n self.parameters[NUM_PROBES] = len(experiment.barcodes)\n if PICO1_DYE not in self.parameters:\n self.parameters[PICO1_DYE] = None\n except:\n APP_LOGGER.exception(traceback.format_exc())\n\n # set parameters for anything user might not have set\n if FILTERED_DYES not in self.parameters:\n self.parameters[FILTERED_DYES] = list()\n\n if IGNORED_DYES not in self.parameters:\n self.parameters[IGNORED_DYES] = list()\n\n if CONTINUOUS_PHASE not in self.parameters:\n self.parameters[CONTINUOUS_PHASE] = False\n\n if DEV_MODE not in self.parameters:\n self.parameters[DEV_MODE] = DEFAULT_DEV_MODE\n\n if DRIFT_COMPENSATE not in self.parameters:\n self.parameters[DRIFT_COMPENSATE] = DEFAULT_DRIFT_COMPENSATE\n\n def resume_workflow(self):\n \"\"\"\n User may be trying to resume an old workflow were something failed. Look\n for the subjob it failed on and resume from there. Update the document with\n the succeeded subjobs and resume the workflow from the failed subjobs.\n \"\"\"\n # find the full analysis job\n previous_fa_job_document = self.parameters[BEST_EXIST_JOB]\n\n # if no previous job is found or experiment definition of previous job is\n # different from the current one, start from beginning\n if previous_fa_job_document is None or previous_fa_job_document[EXP_DEF] != self.parameters[EXP_DEF]:\n return\n\n # find the job it failed on\n failed_subjob = None\n last_successful_subjob_uuid = None\n for subjob_name in self.document_list:\n if subjob_name not in previous_fa_job_document or \\\n previous_fa_job_document[subjob_name].get(STATUS, None) != SUCCEEDED or \\\n is_param_diff(previous_fa_job_document[subjob_name], subjob_name, self.parameters):\n failed_subjob = subjob_name\n break\n else:\n last_successful_subjob_uuid = previous_fa_job_document[subjob_name][UUID]\n\n # append last successful uuid to uuid manager\n if last_successful_subjob_uuid is not None:\n self.uuid_container.append(last_successful_subjob_uuid)\n\n\n if failed_subjob is None:\n self.workflow = []\n succeeded_subjobs = self.document_list\n else:\n self.workflow = self.workflow[self.document_list.index(failed_subjob):]\n succeeded_subjobs = self.document_list[:self.document_list.index(failed_subjob)]\n\n update_query = dict()\n for subjob_name in succeeded_subjobs:\n update_query[subjob_name] = previous_fa_job_document[subjob_name]\n\n if update_query:\n update = {\"$set\": update_query}\n self.db_connector.update(FA_PROCESS_COLLECTION, self.query, update)\n\n def primary_analysis_job(self, _):\n \"\"\"\n Create and run a primary analysis job.\n\n @param _: Placeholder, isn't used it's here because all jobs run in this\n callable must have a uuid from the previous job. A primary analysis\n job is the only exception because it doesn't need a uuid to start.\n @return: String, uuid of job, String, status of job\n \"\"\"\n dyes = self.parameters[DYES] + [self.parameters[ASSAY_DYE], self.parameters[PICO2_DYE]]\n if self.parameters[PICO1_DYE] is not None and self.parameters[PICO1_DYE] not in dyes:\n dyes.append(self.parameters[PICO1_DYE])\n\n job_name = self.parameters[JOB_NAME] + generate_random_str(5)\n # create a callable and a callback\n callable = PaProcessCallable(archive=self.parameters[ARCHIVE],\n is_hdf5=self.parameters[IS_HDF5],\n dyes=dyes,\n device=self.parameters[DEVICE],\n major=self.parameters[MAJOR],\n minor=self.parameters[MINOR],\n offset=self.parameters[OFFSETS],\n use_iid=self.parameters[USE_IID],\n job_name=job_name,\n db_connector=self.db_connector)\n callback = pa_make_process_callback(uuid=callable.uuid,\n outfile_path=callable.outfile_path,\n config_path=callable.config_path,\n db_connector=self.db_connector)\n\n # enter primary analysis uuid into full analysis database entry\n self.db_connector.update(FA_PROCESS_COLLECTION, self.query,\n {\"$set\": {PA_DOCUMENT: {START_DATESTAMP: datetime.today(),\n PA_PROCESS_UUID: callable.uuid,\n OFFSETS: self.parameters[OFFSETS]}}})\n\n # run primary analysis job\n with ThreadPoolExecutor(max_workers=1) as executor:\n future = executor.submit(callable)\n future.add_done_callback(callback)\n\n # update full analysis entry with results from primary analysis\n result = self.db_connector.find_one(PA_PROCESS_COLLECTION, UUID, callable.uuid)\n keys = [UUID, URL, CONFIG_URL, STATUS, ERROR, START_DATESTAMP, FINISH_DATESTAMP,\n MAJOR, MINOR, OFFSETS]\n document = {key: result[key] for key in keys if key in result}\n update = {\"$set\": {PA_DOCUMENT: document}}\n self.db_connector.update(FA_PROCESS_COLLECTION, {UUID: self.uuid}, update)\n\n # return primary analysis status and uuid\n return callable.uuid, result[STATUS], 'primary_analysis'\n\n def identity_job(self, primary_analysis_uuid):\n \"\"\"\n Create and run a identity job.\n\n @param primary_analysis_uuid: String indicating primary analysis uuid which\n will be used as an input for identity.\n @return: String, uuid of job, String, status of job\n \"\"\"\n job_name = self.parameters[JOB_NAME] + generate_random_str(5)\n # create a callable and a callback\n callable = SaIdentityCallable(primary_analysis_uuid=primary_analysis_uuid,\n num_probes=self.parameters[NUM_PROBES],\n training_factor=self.parameters[ID_TRAINING_FACTOR],\n assay_dye=self.parameters[ASSAY_DYE],\n use_pico1_filter=self.parameters[USE_PICO1_FILTER],\n use_pico2_filter=self.parameters[USE_PICO2_FILTER],\n pico1_dye=self.parameters[PICO1_DYE],\n pico2_dye=self.parameters[PICO2_DYE],\n dye_levels=self.parameters[DYE_LEVELS],\n ignored_dyes=self.parameters[IGNORED_DYES],\n filtered_dyes=self.parameters[FILTERED_DYES],\n ui_threshold=self.parameters[UI_THRESHOLD],\n max_uninj_ratio=self.parameters[MAX_UNINJECTED_RATIO],\n db_connector=self.db_connector,\n job_name=job_name,\n use_pico_thresh=self.parameters[CONTINUOUS_PHASE],\n ignore_lowest_barcode=self.parameters[IGNORE_LOWEST_BARCODE],\n dev_mode=self.parameters[DEV_MODE],\n drift_compensate=self.parameters[DRIFT_COMPENSATE])\n callback = id_make_process_callback(uuid=callable.uuid,\n outfile_path=callable.outfile_path,\n plot_path=callable.plot_path,\n report_path=callable.report_path,\n plate_plot_path=callable.plate_plot_path,\n temporal_plot_path=callable.temporal_plot_path,\n drop_count_plot_path=callable.drop_count_plot_path,\n db_connector=self.db_connector)\n\n # enter identity uuid into full analysis database entry\n self.db_connector.update(FA_PROCESS_COLLECTION, self.query,\n {\"$set\": {ID_DOCUMENT: {START_DATESTAMP: datetime.today(),\n SA_IDENTITY_UUID: callable.uuid,\n TRAINING_FACTOR: self.parameters[ID_TRAINING_FACTOR],\n UI_THRESHOLD: self.parameters[UI_THRESHOLD],\n IGNORE_LOWEST_BARCODE: self.parameters[IGNORE_LOWEST_BARCODE],\n PICO1_DYE: self.parameters[PICO1_DYE],\n MAX_UNINJECTED_RATIO: self.parameters[MAX_UNINJECTED_RATIO],\n USE_PICO1_FILTER: self.parameters[USE_PICO1_FILTER],\n USE_PICO2_FILTER: self.parameters[USE_PICO2_FILTER],\n DEV_MODE: self.parameters[DEV_MODE],\n DRIFT_COMPENSATE: self.parameters[DRIFT_COMPENSATE]}}})\n\n # run identity job\n with ThreadPoolExecutor(max_workers=1) as executor:\n future = executor.submit(callable)\n future.add_done_callback(callback)\n\n # update full analysis entry with results from identity\n result = self.db_connector.find_one(SA_IDENTITY_COLLECTION, UUID, callable.uuid)\n keys = [UUID, URL, REPORT_URL, PLOT_URL, STATUS, ERROR, START_DATESTAMP,\n FINISH_DATESTAMP, TRAINING_FACTOR, UI_THRESHOLD, MAX_UNINJECTED_RATIO,\n PLATE_PLOT_URL, TEMPORAL_PLOT_URL, IGNORE_LOWEST_BARCODE, PICO1_DYE,\n USE_PICO1_FILTER, DEV_MODE, DRIFT_COMPENSATE, USE_PICO2_FILTER,\n DROP_COUNT_PLOT_URL]\n document = {key: result[key] for key in keys if key in result}\n update = {\"$set\": {ID_DOCUMENT: document}}\n self.db_connector.update(FA_PROCESS_COLLECTION, {UUID: self.uuid}, update)\n\n # return identity status and uuid\n return callable.uuid, result[STATUS], 'identity'\n\n def assay_caller_job(self, identity_uuid):\n \"\"\"\n Create and run a assay caller job.\n\n @param identity_uuid: String indicating identity uuid which\n will be used as an input for assay caller.\n @return: String, uuid of job, String, status of job\n \"\"\"\n job_name = self.parameters[JOB_NAME] + generate_random_str(5)\n ac_model = None\n if AC_MODEL in self.parameters:\n ac_model = self.parameters[AC_MODEL]\n\n # create a callable and a callback\n callable = SaAssayCallerCallable(identity_uuid=identity_uuid,\n exp_def_name=self.parameters[EXP_DEF],\n training_factor=self.parameters[AC_TRAINING_FACTOR],\n ctrl_thresh=self.parameters[CTRL_THRESH],\n db_connector=self.db_connector,\n job_name=job_name,\n ctrl_filter=self.parameters[CTRL_FILTER],\n ac_method=self.parameters[AC_METHOD],\n ac_model=ac_model)\n callback = ac_make_process_callback(uuid=callable.uuid,\n outfile_path=callable.outfile_path,\n scatter_plot_path=callable.scatter_plot_path,\n dyes_scatter_plot_path=callable.dyes_plot_path,\n db_connector=self.db_connector)\n\n # enter assay caller uuid into full analysis database entry\n self.db_connector.update(FA_PROCESS_COLLECTION, self.query,\n {\"$set\": {AC_DOCUMENT: {START_DATESTAMP: datetime.today(),\n SA_ASSAY_CALLER_UUID: callable.uuid,\n TRAINING_FACTOR: self.parameters[AC_TRAINING_FACTOR],\n CTRL_THRESH: self.parameters[CTRL_THRESH],\n CTRL_FILTER: self.parameters[CTRL_FILTER],\n AC_METHOD: self.parameters[AC_METHOD],\n AC_MODEL: ac_model}}})\n\n # run assay caller job\n with ThreadPoolExecutor(max_workers=1) as executor:\n future = executor.submit(callable)\n future.add_done_callback(callback)\n\n # update full analysis entry with results from assay caller\n result = self.db_connector.find_one(SA_ASSAY_CALLER_COLLECTION, UUID, callable.uuid)\n keys = [UUID, URL, SCATTER_PLOT_URL, STATUS, ERROR, START_DATESTAMP,\n FINISH_DATESTAMP, TRAINING_FACTOR, CTRL_THRESH, CTRL_FILTER,\n AC_METHOD, DYES_SCATTER_PLOT_URL, AC_MODEL]\n document = {key: result[key] for key in keys if key in result}\n update = {\"$set\": {AC_DOCUMENT: document}}\n self.db_connector.update(FA_PROCESS_COLLECTION, {UUID: self.uuid}, update)\n\n # return assay caller status and uuid\n return callable.uuid, result[STATUS], 'assay_caller'\n\n def genotyper_job(self, assay_caller_uuid):\n \"\"\"\n Create and run a genotyper job.\n\n @param assay_caller_uuid: String indicating assay caller uuid which\n will be used as an input for genotyper.\n @return: String, uuid of job, String, status of job\n \"\"\"\n job_name = self.parameters[JOB_NAME] + generate_random_str(5)\n mask_code = self.parameters[VARIANT_MASK] if VARIANT_MASK in self.parameters else None\n # create a callable and a callback\n callable = SaGenotyperCallable(assay_caller_uuid=assay_caller_uuid,\n exp_def_name=self.parameters[EXP_DEF],\n required_drops=self.parameters[REQUIRED_DROPS],\n db_connector=self.db_connector,\n job_name=job_name,\n mask_code=mask_code,\n combine_alleles=True)\n callback = gt_make_process_callback(uuid=callable.uuid,\n exp_def_name=self.parameters[EXP_DEF],\n ac_result_path=callable.ac_result_path,\n ignored_dyes=callable.ignored_dyes,\n outfile_path=callable.outfile_path,\n db_connector=self.db_connector,\n cur_job_name=job_name)\n\n # enter genotyper uuid into full analysis database entry\n self.db_connector.update(FA_PROCESS_COLLECTION, self.query,\n {\"$set\": {GT_DOCUMENT: {START_DATESTAMP: datetime.today(),\n SA_GENOTYPER_UUID: callable.uuid,\n REQUIRED_DROPS: self.parameters[REQUIRED_DROPS]}}})\n\n # run genotyper job\n with ThreadPoolExecutor(max_workers=1) as executor:\n future = executor.submit(callable)\n future.add_done_callback(callback)\n\n # update full analysis entry with results from genotyper\n result = self.db_connector.find_one(SA_GENOTYPER_COLLECTION, UUID, callable.uuid)\n keys = [UUID, URL, PDF_URL, PNG_URL, PNG_SUM_URL, KDE_PNG_URL,\n KDE_PNG_SUM_URL, STATUS, ERROR, START_DATESTAMP, FINISH_DATESTAMP,\n REQUIRED_DROPS, VARIANT_MASK]\n document = {key: result[key] for key in keys if key in result}\n update = {\"$set\": {GT_DOCUMENT: document}}\n self.db_connector.update(FA_PROCESS_COLLECTION, {UUID: self.uuid}, update)\n\n # return genotyper status and uuid\n return callable.uuid, result[STATUS], 'genotyper'\n\n def exploratory_job(self, assay_caller_uuid):\n \"\"\"\n Create and run an exploratory job.\n\n @param assay_caller_uuid: String indicating assay caller uuid which\n will be used as an input for genotyper.\n @return: String, uuid of job, String, status of job\n \"\"\"\n job_name = self.parameters[JOB_NAME] + generate_random_str(5)\n # create a callable and a callback\n callable = SaExploratoryCallable(assay_caller_uuid=assay_caller_uuid,\n exp_def_name=self.parameters[EXP_DEF],\n required_drops=self.parameters[REQUIRED_DROPS],\n db_connector=self.db_connector,\n job_name=job_name)\n callback = ep_make_process_callback(uuid=callable.uuid,\n outfile_path=callable.tsv_path,\n db_connector=self.db_connector)\n\n # enter genotyper uuid into full analysis database entry\n self.db_connector.update(FA_PROCESS_COLLECTION, self.query,\n {\"$set\": {EP_DOCUMENT: {START_DATESTAMP: datetime.today(),\n SA_EXPLORATORY_UUID: callable.uuid,\n REQUIRED_DROPS: self.parameters[REQUIRED_DROPS]}}})\n\n # run genotyper job\n with ThreadPoolExecutor(max_workers=1) as executor:\n future = executor.submit(callable)\n future.add_done_callback(callback)\n\n # update full analysis entry with results from genotyper\n result = self.db_connector.find_one(SA_EXPLORATORY_COLLECTION, UUID, callable.uuid)\n keys = [UUID, URL, PNG_URL, PNG_SUM_URL, KDE_PNG_URL, KDE_PNG_SUM_URL, STATUS,\n ERROR, START_DATESTAMP, FINISH_DATESTAMP]\n document = {key: result[key] for key in keys if key in result}\n update = {\"$set\": {EP_DOCUMENT: document}}\n self.db_connector.update(FA_PROCESS_COLLECTION, {UUID: self.uuid}, update)\n\n # return genotyper status and uuid\n return callable.uuid, result[STATUS], 'exploratory'\n\n def run_analysis(self):\n \"\"\"\n Initialize a list of jobs that will be run in order\n \"\"\"\n job_map = {PROCESS: self.primary_analysis_job,\n IDENTITY: self.identity_job,\n ASSAY_CALLER: self.assay_caller_job,\n GENOTYPER: self.genotyper_job,\n EXPLORATORY: self.exploratory_job}\n # run jobs in the order specified by self.workflow\n while self.workflow:\n job = job_map[self.workflow.pop(0)]\n job_uuid, status, name = job(self.uuid_container[-1])\n if status != SUCCEEDED:\n raise Exception('failed at %s' % name)\n\n self.uuid_container.append(job_uuid)\n\n # add unified pdf\n fa_job = self.db_connector.find_one(FA_PROCESS_COLLECTION, UUID, self.uuid)\n last_doc = DOCUMENT_LOOKUP[self.exp_type]\n\n while STATUS not in fa_job[last_doc] or fa_job[last_doc][STATUS] == JOB_STATUS.running:\n time.sleep(10)\n fa_job = self.db_connector.find_one(FA_PROCESS_COLLECTION, UUID, self.uuid)\n add_unified_pdf(fa_job, [PA_DOCUMENT, ID_DOCUMENT, AC_DOCUMENT, last_doc])\n","sub_path":"bioweb_api/apis/full_analysis/FullAnalysisWorkflow.py","file_name":"FullAnalysisWorkflow.py","file_ext":"py","file_size_in_byte":26905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"173869575","text":"from bson import ObjectId\nfrom flask import request, jsonify, send_file, after_this_request\nfrom pymongo import ReturnDocument\nimport boto3\nimport re\nimport os\n\ns3 = boto3.client('s3', aws_access_key_id=\"AKIA5WCCAKRFZNMK4DEB\",\n aws_secret_access_key=\"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\")\n\nbucket_name = \"job-tracker-resume-upload\"\n\n\ndef upload_file(UserRecords, Files):\n \n '''\n ```\n Request:\n {\n email: string,\n start: string,\n file: file,\n end: string,\n filename: string\n \n }\n Response:\n {\n status: 200\n data: Success message\n \n status: 500\n data: Error message\n \n }\n ```\n '''\n \n try:\n file = request.files['file']\n email = str(request.files['email'].read())\n start = email.find(\"'\")\n end = email.rfind(\"'\")\n email = email[start+1:end].strip()\n email_found = UserRecords.find_one({\"email\": email})\n if email_found:\n _id = str(email_found[\"_id\"])\n else:\n return jsonify({'error': \"Email not found\"}), 500\n if file:\n filename = _id+\"--;--\"+file.filename\n file.save(filename)\n s3.upload_file(\n Bucket=bucket_name,\n Filename=filename,\n Key=filename\n )\n Files.insert_one({\n \"email\": email,\n \"filename\": filename,\n })\n os.remove(filename)\n return jsonify({\"message\": \"File Uploaded Successfully\"}), 200\n else:\n return jsonify({'error': \"Found Empty File\"}), 500\n except:\n return jsonify({'error': \"Something went wrong\"}), 500\n\n\ndef view_files(Files):\n \n '''\n ```\n Request:\n {\n email: string \n }\n Response:\n {\n status: 200\n data: Success message\n \n status: 500\n data: Error message\n \n }\n ```\n '''\n \n try:\n if request:\n email = request.args.get(\"email\")\n out = Files.find({\"email\": email})\n if out:\n files = []\n for i in out:\n i['filename'] = i['filename']\n i['_id'] = str(i['_id'])\n files.append(i)\n if files:\n return jsonify({'message': 'Files found', 'files': files}), 200\n else:\n return jsonify({'message': 'No Files found', 'files': files}), 200\n else:\n return jsonify({'message': 'Email Doesnt Exist'}), 400\n except Exception as e:\n print(e)\n return jsonify({'error': \"Something went wrong\"}), 500\n\n\ndef download_file(Files):\n \n '''\n ```\n Request:\n {\n \n }\n Response:\n {\n status: 200\n data: Success message\n \n status: 500\n data: Error message\n \n status: 501\n data: Authorization required\n \n }\n ```\n '''\n \n try:\n if request:\n req = request.get_json()\n file = Files.find_one({\"filename\": req[\"filename\"]})\n if file:\n if file[\"email\"] == req[\"email\"]:\n s3.download_file(\n bucket_name, file[\"filename\"], req[\"filename\"].split(\"--;--\")[1])\n return send_file(req[\"filename\"].split(\"--;--\")[1])\n else:\n return jsonify({'message': 'You are not authorized to view this file'}), 501\n\n return jsonify({'message': 'Files found'}), 200\n except Exception:\n return jsonify({'error': 'Something went wrong'}), 500\n\n\ndef delete_file(Files):\n \n '''\n ```\n Request:\n { \n }\n Response:\n {\n status: 200\n data: Success message\n \n status: 500\n data: Error message\n \n }\n ```\n '''\n \n try:\n if request:\n req = request.get_json()\n df = Files.find_one_and_delete({\"filename\": req[\"filename\"]})\n if df == None:\n return jsonify({\"error\": \"No such Job ID found for this user's email\"}), 500\n else:\n try:\n s3.delete_object(Bucket=bucket_name, Key=req[\"filename\"])\n except:\n pass\n return jsonify({\"message\": \"File Deleted Successfully\"}), 200\n except Exception:\n return jsonify({'error': 'Something went wrong'}), 500\n","sub_path":"backend/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":4552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"364244091","text":"from django.http import Http404\n\nfrom iasip_api.models import CharacterCrime, Character, Crime\nfrom iasip_api.serializers import CharacterSerializer, CrimeSerializer, CharacterCrimeSerializer\nfrom rest_framework import generics\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\n\n# Create your views here.\nclass CharacterList(generics.ListAPIView):\n queryset = Character.objects.all()\n serializer_class = CharacterSerializer\n\n\nclass CharacterDetail(APIView):\n \"\"\"\n Retrieve a character instance\n \"\"\"\n def get_object(self, pk):\n try:\n return Character.objects.get(pk=pk)\n except Character.DoesNotExist:\n raise Http404\n\n def get(self, request, pk, format=None):\n character = self.get_object(pk)\n serializer = CharacterSerializer(character)\n return Response(serializer.data)\n\n\nclass CrimeList(generics.ListAPIView):\n queryset = Crime.objects.all()\n serializer_class = CrimeSerializer\n\n\nclass CrimeDetail(APIView):\n \"\"\"\n Retrieve a crime definition\n \"\"\"\n def get_object(self, pk):\n try:\n return Crime.objects.get(pk=pk)\n except Crime.DoesNotExist:\n raise Http404\n\n def get(self, request, pk, format=None):\n crime = self.get_object(pk=pk)\n serializer = CrimeSerializer(crime)\n return Response(serializer.data)\n\n\nclass CharacterCrimeList(generics.ListAPIView):\n queryset = CharacterCrime.objects.all()\n serializer_class = CharacterCrimeSerializer\n\n\nclass CharacterCrimeDetail(APIView):\n \"\"\"\n Retrieve a specific Character Crime\n \"\"\"\n def get_object(self, pk):\n try:\n return CharacterCrime.objects.filter(character__id=pk)\n except CharacterCrime.DoesNotExist:\n raise Http404\n\n def get(self, request, pk, format=None):\n character_crimes = self.get_object(pk=pk)\n serializer = CharacterCrimeSerializer(character_crimes, many=True)\n return Response(serializer.data)\n\n\nclass CharacterCrimeListByCharacter(APIView):\n \"\"\"\n Get a list of Character Crimes for a specific character\n \"\"\"\n def get_object(self, name):\n try:\n return CharacterCrime.objects.filter(character__url_name=name)\n except CharacterCrime.DoesNotExist:\n raise Http404\n\n def get(self, request, name):\n character_crime_by_character = self.get_object(name=name)\n serializer = CharacterCrimeSerializer(character_crime_by_character, many=True)\n return Response(serializer.data)","sub_path":"iasip_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"153200381","text":"from pdb import set_trace\nfrom typing import Dict, Tuple, Union\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport plotly.graph_objects as go\nfrom matplotlib.figure import Figure as matplotlibFigure\nfrom plotly.graph_objs._figure import Figure as plotlyFigure\nfrom plotly.subplots import make_subplots\n\nimport stickleback.util as sb_util\nfrom stickleback.types import *\n\nfigure_T = Union[plotlyFigure, matplotlibFigure]\n\ndef plot_sensors_events(\n deployid: str, sensors: sensors_T, events: events_T, interactive=True\n) -> figure_T:\n _sensors = sensors[deployid]\n _events = _sensors.loc[events[deployid]]\n\n if interactive:\n return __plot_sensors_events_interactive(_sensors, _events)\n else:\n return __plot_sensors_events_static(_sensors, _events)\n\n\ndef __plot_sensors_events_interactive(sensors, event_sensors) -> plotlyFigure:\n fig = make_subplots(\n rows=len(sensors.columns),\n cols=1,\n shared_xaxes=True,\n )\n for i, col in enumerate(sensors.columns):\n fig.append_trace(\n go.Scatter(x=sensors.index, y=sensors[col], mode=\"lines\"), row=i + 1, col=1\n )\n fig.append_trace(\n go.Scatter(x=event_sensors.index, y=event_sensors[col], mode=\"markers\"),\n row=i + 1,\n col=1,\n )\n fig.update_yaxes(title_text=col, row=i + 1, col=1)\n\n fig.update_layout(showlegend=False)\n return fig\n\n\n# FIXME (maybe? might still work)\ndef __plot_sensors_events_static(sensors, event_sensors) -> matplotlibFigure:\n fig, axs = plt.subplots(len(sensors.columns), 1)\n for i, col in enumerate(sensors.columns):\n # sensor data\n axs[i].plot(sensors.index, sensors[col], \"-\", zorder=1)\n # events\n axs[i].scatter(\n event_sensors.index,\n event_sensors[col],\n facecolors=\"none\",\n edgecolors=\"r\",\n zorder=2,\n )\n axs[i].set_ylabel(col)\n if col == \"depth\":\n axs[i].invert_yaxis()\n\n return fig\n\n\ndef plot_predictions(\n deployid: str,\n sensors: sensors_T,\n predictions: prediction_T,\n outcomes: outcomes_T = None,\n interactive: bool = True,\n) -> figure_T:\n lcl, gbl = predictions[deployid]\n data = sensors[deployid].join(lcl)\n\n predicted_only = data.loc[gbl]\n actual_only = None\n if outcomes is not None:\n predicted_only = predicted_only.join(outcomes[deployid])\n is_actual = outcomes[deployid].isin([\"TP\", \"FN\"])\n actual_idx = outcomes[deployid].index[is_actual]\n actual_only = data.loc[actual_idx].join(outcomes[deployid])\n\n if interactive:\n return __plot_predictions_interactive(data, predicted_only, actual_only)\n else:\n return __plot_predictions_static(data, predicted_only, actual_only)\n\n\ndef __plot_predictions_interactive(\n data: pd.DataFrame, predicted: pd.DataFrame, actual: pd.DataFrame\n) -> plotlyFigure:\n fig = make_subplots(\n rows=len(data.columns),\n cols=1,\n shared_xaxes=True,\n )\n\n pred_color = \"purple\"\n if \"outcome\" in predicted.columns:\n pred_color = [\"blue\" if o == \"TP\" else \"red\" for o in predicted[\"outcome\"]]\n if actual is not None:\n actual_color = [\"blue\" if o == \"TP\" else \"red\" for o in actual[\"outcome\"]]\n\n for i, col in enumerate(data):\n # Line plot\n fig.append_trace(\n go.Scatter(x=data.index, y=data[col], mode=\"lines\"), row=i + 1, col=1\n )\n # Predicted events\n fig.append_trace(\n go.Scatter(\n x=predicted.index,\n y=predicted[col],\n marker_color=pred_color,\n mode=\"markers\",\n ),\n row=i + 1,\n col=1,\n )\n # Actual events\n if actual is not None:\n fig.append_trace(\n go.Scatter(\n x=actual.index,\n y=actual[col],\n mode=\"markers\",\n marker_symbol=\"circle-open\",\n marker_size=10,\n marker_color=actual_color,\n ),\n row=i + 1,\n col=1,\n )\n fig.update_yaxes(title_text=col, row=i + 1, col=1)\n\n fig.update_layout(showlegend=False)\n return fig\n\n\n# FIXME\ndef __plot_predictions_static(data, predicted, actual) -> matplotlibFigure:\n fig, axs = plt.subplots(len(data.columns), 1)\n for i, col in enumerate(data):\n # sensor data\n axs[i].plot(data.index, data[col], \"-\", zorder=1)\n axs[i].set_ylabel(col)\n # predicted events\n axs[i].scatter(\n predicted.index,\n predicted[col],\n c=[\"blue\" if o == \"TP\" else \"red\" for o in predicted[\"outcome\"]],\n zorder=2,\n )\n # actual events\n axs[i].scatter(\n actual.index,\n actual[col],\n edgecolors=[\"blue\" if o == \"TP\" else \"red\" for o in actual[\"outcome\"]],\n facecolors=\"none\",\n zorder=3,\n )\n if col == \"depth\":\n axs[i].invert_yaxis()\n\n return fig\n\ndef outcome_table(outcomes: Dict[str, pd.Series],\n sensors: sensors_T) -> pd.DataFrame:\n def add_deployid(d, o):\n result = pd.DataFrame(o)\n result.insert(0, \"deployid\", np.full(len(o), [d]))\n return result\n\n counts = pd.concat([add_deployid(d, o) for d, o in outcomes.items()])\n result = (counts\n .groupby([\"deployid\", \"outcome\"])\n .size()\n .unstack(fill_value=0))\n \n result[\"F1\"] = sb_util.f1(result[\"TP\"], result[\"FP\"], result[\"FN\"])\n \n dur_dict = {k: (v.index[-1] - v.index[0]) / pd.Timedelta(hours=1) \n for k, v in sensors.items()}\n durations = pd.DataFrame.from_dict(dur_dict, \"index\")\n durations.columns = [\"Duration (hours)\"]\n result = result.join(durations)\n \n true_rate = (result[\"TP\"] + result[\"FN\"]) / result[\"Duration (hours)\"]\n result[\"True rate (events/hr)\"] = true_rate\n pred_rate = (result[\"TP\"] + result[\"FP\"]) / result[\"Duration (hours)\"]\n result[\"Pred. rate (events/hr)\"] = pred_rate\n \n result = result[[\"F1\", \n \"TP\", \n \"FP\", \n \"FN\", \n \"True rate (events/hr)\",\n \"Pred. rate (events/hr)\",\n \"Duration (hours)\"]]\n return result\n","sub_path":"stickleback/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":6458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"563389747","text":"import ctranslate2\nimport pyonmttok\nfrom typing import List\nimport jieba\nimport time\nfrom tools.apply_bpe import BPE\nfrom process_tag import process_tag\nimport re\nfrom collections import defaultdict\n\nCONFIG_TRANSLATOR = {\n 'device':\"auto\", # The device to use: \"cpu\", \"cuda\", or \"auto\".\n \"device_index\":0, # The index of the device to place this translator on.\n \"compute_type\":\"default\", # The computation type: \"default\", \"int8\", \"int16\", or \"float\".\n \"inter_threads\":1, # Maximum number of concurrent translations (CPU only).\n \"intra_threads\":20 # Threads to use per translation (CPU only). \n}\n\nCONFIG_TRANSLATE = {\n \"target_prefix\":None, # An optional list of list of string.\n \"max_batch_size\":0, # Maximum batch size to run the model on.\n \"batch_type\":\"examples\", # Whether max_batch_size is the number of examples or tokens.\n \"beam_size\":5, # Beam size (set 1 to run greedy search).\n \"num_hypotheses\":1, # Number of hypotheses to return (should be <= beam_size).\n \"length_penalty\":0, # Length penalty constant to use during beam search.\n \"coverage_penalty\":0, # Converage penalty constant to use during beam search.\n \"max_decoding_length\":250, # Maximum prediction length.\n \"min_decoding_length\":1, # Minimum prediction length.\n \"use_vmap\":False, # Use the vocabulary mapping file saved in this model.\n \"return_scores\":True, # Include the prediction scores in the output.\n \"return_attention\":False, # Include the attention vectors in the output.\n \"return_alternatives\":False, # Return alternatives at the first unconstrained decoding position.\n \"sampling_topk\":1, # Randomly sample predictions from the top K candidates (with beam_size=1).\n \"sampling_temperature\":1 # Sampling temperature to generate more random samples.\n}\n\n\ndef remove_repeat_token(sentence, max_ngram_length = 4):\n final_merge_sent = sentence.split(' ')\n if len(final_merge_sent) < 3:\n return sentence\n max_ngram_length = min(max_ngram_length, len(sentence))\n for i in range(max_ngram_length, 0, -1):\n start = 0\n end = len(final_merge_sent) - i + 1\n ngrams = []\n while start < end:\n ngrams.append(final_merge_sent[start: start + i])\n start += 1\n result = []\n for cur_word in ngrams:\n result.append(cur_word)\n if len(result) > i:\n pre_word = result[len(result) - i - 1]\n if pre_word == cur_word:\n for k in range(i):\n result.pop()\n\n cur_merge_sent = []\n for word in result:\n if not cur_merge_sent:\n cur_merge_sent.extend(word)\n else:\n cur_merge_sent.append(word[-1])\n final_merge_sent = cur_merge_sent\n\n return ' '.join(final_merge_sent)\n\ndef cut_sent(text:str, pattern=\"([。])\"):\n sents = re.split(pattern, text) + [\"\"]\n sents = [\"\".join(i) for i in zip(sents[0::2],sents[1::2])]\n return sents\n\n\nclass Server:\n def __init__(self, path_translator, path_bpe):\n self.translator = ctranslate2.Translator(path_translator, **CONFIG_TRANSLATOR)\n self.bpe = BPE(open(path_bpe, 'r'))\n\n def predict(self, text_list: List[str]) -> List[str]:\n t1 = time.time()\n _text_list, _id = [], []\n for i, text in enumerate(text_list):\n text = cut_sent(text)\n _id.extend([i] * len(text))\n _text_list.extend(text)\n \n text_list = _text_list\n\n text_list = [' '.join([e.strip() for e in jieba.lcut(line) if e.strip()]) for line in text_list]\n t2 = time.time()\n text_list = [process_tag(self.bpe.segment(text).strip()).split(' ') for text in text_list]\n totol_tokens = sum([len(e) for e in text_list])\n t3 = time.time()\n print(f'input: {text_list}')\n result = self.translator.translate_batch(text_list, **CONFIG_TRANSLATE)\n t4 = time.time()\n result = [' '.join(d[0][\"tokens\"]).replace('@@ ', '') for d in result]\n print(f'output: {result}')\n result = [remove_repeat_token(text) for text in result]\n print(f'remove repeat: {result}')\n \n _result = defaultdict(list)\n for i, text in zip(_id, result):\n print(i, text)\n _result[i].append(text)\n \n result = [\" \".join(v) for k, v in _result.items()]\n\n t5 = time.time()\n \n report = f'''\n jieba: {t2-t1}s\n bpe: {t3-t2}s\n trans: {t4-t3}s {totol_tokens/(t4-t3)} tokens/s \n post: {t5-t4}s\n '''\n #print(text_list)\n print(report)\n return result\n\n\n\nif __name__ == '__main__':\n from tqdm import tqdm\n def cut_list(data, batch_size):\n return [data[x:x+batch_size] for x in range(0, len(data), batch_size)]\n\n path_translator = \"zh2en_ctranslate2\"\n path_bpe=\"zh.bpe\"\n \n server = Server(path_translator, path_bpe)\n\n dataset = open('../data/zh-val.txt').read().split('\\n')\n outf = open('server_val.out', 'w')\n\n for text in tqdm(cut_list(dataset, 100)):\n result = server.predict(text)\n print('\\n'.join(result), file=outf)\n","sub_path":"CTranslate2/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"551831618","text":"import base64\nfrom asyncio import AbstractEventLoop\nfrom concurrent.futures import Executor\nfrom imgurpython import ImgurClient\n\nfrom logger import init_logger\nfrom storage import Storage\n\n_logger = init_logger(__name__)\n\n\nclass StorageImgur(Storage):\n \"\"\"\n >>> from logging import CRITICAL\n >>> _ = init_logger(__name__, CRITICAL)\n >>> from PIL import Image\n >>> from io import BytesIO\n >>> img = Image.new('RGB', (100, 100), 255)\n >>> img_output = BytesIO()\n >>> img.save(img_output, format='JPEG')\n\n >>> import configparser\n >>> config = configparser.ConfigParser()\n >>> _ = config.read('config.ini')\n\n >>> import asyncio\n >>> loop = asyncio.get_event_loop()\n >>> storage = loop.run_until_complete(StorageImgur.create(config, loop))\n >>> cb = lambda _, url_new: print(url_new)\n\n >>> loop.run_until_complete(storage.store_batch([img_output.getvalue()]*2, cb)) # doctest: +ELLIPSIS\n http...\n http...\n >>> loop.run_until_complete(storage.store_batch(['abc'.encode()], cb))\n None\n >>> loop.run_until_complete(storage.store_batch([None], cb))\n None\n >>> loop.close()\n \"\"\"\n @classmethod\n async def create(cls, config, loop: AbstractEventLoop, executor: Executor = None):\n client_id = config.get('credentials_imgur', 'client_id')\n client_secret = config.get('credentials_imgur', 'client_secret')\n\n client = await loop.run_in_executor(executor, ImgurClient, client_id, client_secret)\n\n return cls(client, loop, executor)\n\n def __init__(self, client, loop, executor):\n self._client = client\n self._executor = executor\n super().__init__(loop)\n\n async def _store(self, content):\n try:\n b64 = base64.b64encode(content)\n data = {\n 'image': b64,\n 'type': 'base64',\n }\n response = await self._loop.run_in_executor(self._executor, self._client.make_request, 'POST', 'upload', data)\n url = response['link']\n except Exception as e:\n _logger.error(str(e))\n return None\n\n return url if url else None\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","sub_path":"storage_imgur.py","file_name":"storage_imgur.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"511802536","text":"from django.shortcuts import render\nfrom .models import interimTable, CarParts, carModel,carMark\nfrom django.db.models import Q\nfrom .serializers import carModelSerializer\nfrom rest_framework import generics\n\n# Create your views here.\n\ndef carinfo_list(request):\n car_marks = carMark.objects.all()\n car_models = carModel.objects.all()\n parts = CarParts.objects.all()\n marka = request.GET.get('mark')\n modelka = request.GET.get('model')\n if marka:\n car_models = carModel.objects.filter(id_car_mark = marka)\n print(car_models)\n parts = CarParts.objects.filter(\n Q(id_car_mark=marka) | Q(id_car_model=modelka) \n ).values('id_car_mark','vendor_code','subgroup','title','side','description','id_car_model','trade_mark','original_number','request','price','sum','availability').distinct()\n\n return render(request, 'carinfo/carinfo_list.html', {'parts': parts, 'car_models':car_models, 'car_marks':car_marks})\n\nclass ListParts(generics.ListCreateAPIView):\n queryset = carModel.objects.all()\n serializer_class = carModelSerializer\n\n\nclass DetailParts(generics.RetrieveUpdateDestroyAPIView):\n queryset = carModel.objects.all()\n serializer_class = carModelSerializer\n ","sub_path":"carinfo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"492903952","text":"# creating an empty list\nlst = []\nn = int(input(\"Enter number of elements : \"))\nfor i in range(0, n):\n ele = input()\n lst.append(ele)\nprint(lst)\n\n\nnmr = input('Schreibe Nummern mit Komma Dazwischen:')\ntuple = nmr.split(\",\")\nlst = nmr.split(\",\")\nprint(lst)\nprint(tuple)\n","sub_path":"PY/AUFG_4.py","file_name":"AUFG_4.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"452821363","text":"import queue\n\nN, M = list(map(int, input().split()))\nvisit = [False for i in range(N+1)]\nedge = [[] for i in range(N+1)]\nvisited = []\n\ndef link(node):\n for i in range(node+1, N+1):\n edge[node].append(i)\n\ndef set_visit(vertex):\n for i in range(N+1):\n visit[i] = False\n visit[vertex] = True\n\ndef print_result(r_list):\n for i in r_list:\n print(i, end =\" \")\n print(end =\"\\n\")\n\ndef dfs(vertex, cnt):\n global visited\n\n if(visit[vertex]):\n return\n\n visit[vertex] = True\n visited.append(vertex)\n\n if(cnt == M):\n print_result(visited)\n\n visited = visited[:-1]\n return\n \n for node in edge[vertex]:\n if(not visit[node]):\n dfs(node, cnt+1)\n \n for i in range(node+1, N+1):\n visit[i] = False\n visited = visited[:-1]\n\n\ndef main():\n global visit, visited\n\n ## M이 1일때\n if(M == 1):\n [print(i) for i in range(1, N+1)]\n\n ## M이 1이 아닐때\n else:\n ## 1. 자기보다 큰 수 연결\n [link(i) for i in range(1, N+1)]\n \n ## 2. dfs 로 방문\n for vertex in range(1, N+1):\n if(not visit[vertex]):\n dfs(vertex, 1)\n visit = [False for i in range(N+1)]\n visited = []\n\nif(__name__ == \"__main__\"):\n main()","sub_path":"by date/2021.01.17/15650.py","file_name":"15650.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"567827754","text":"from room import Room\nfrom player import Player\nfrom direction import Direction\nfrom item import Item\n\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n \"North of you, the cave mount beckons\"),\n\n 'foyer': Room(\"Foyer\", \"\"\"Dim light filters in from the south. Dusty\npassages run north and east.\"\"\"),\n\n 'overlook': Room(\"Grand Overlook\", \"\"\"A steep cliff appears before you, falling\ninto the darkness. Ahead to the north, a light flickers in\nthe distance, but there is no way across the chasm.\"\"\"),\n\n 'narrow': Room(\"Narrow Passage\", \"\"\"The narrow passage bends here from west\nto north. The smell of gold permeates the air.\"\"\"),\n\n 'treasure': Room(\"Treasure Chamber\", \"\"\"You've found the long-lost treasure\nchamber! Sadly, it has already been completely emptied by\nearlier adventurers. The only exit is to the south.\"\"\"),\n}\n\n\n# Link rooms together\n\nroom['outside' ].n_to = room['foyer']\nroom['foyer' ].s_to = room['outside']\nroom['foyer' ].n_to = room['overlook']\nroom['foyer' ].e_to = room['narrow']\nroom['overlook'].s_to = room['foyer']\nroom['narrow' ].w_to = room['foyer']\nroom['narrow' ].n_to = room['treasure']\nroom['treasure'].s_to = room['narrow']\n\n# Add items to room\n\nroom['foyer'].items = [\n Item(\"Silver Sword\", \"A magical sword\")\n]\n\nroom['overlook'].items = [\n Item(\"Binoculars\", \"Multicoated eco-glass lenses\"),\n Item(\"Tent\", \"6 Person Dome Tent\")\n]\n\nroom['narrow'].items = [\n Item(\"Book\", \"Spell book\"),\n Item(\"Toy Car\", \"Hot Wheel drag racing car\"),\n Item(\"Laptop\", \"16\\\" MacBoo Pro\")\n]\n\n#\n# Main\n#\n\n# Make a new player object that is currently in the 'outside' room.\nplayer = Player(room['outside'])\n\n# Write a loop that:\n#\n# * Prints the current room name\n# * Prints the current description (the textwrap module might be useful here).\n# * Waits for user input and decides what to do.\n#\n# If the user enters a cardinal direction, attempt to move to the room there.\n# Print an error message if the movement isn't allowed.\n#\n# If the user enters \"q\", quit the game.\n\nuser_input: str = \"\"\nverb: str = None\nobject: str = None\n\nwhile verb != \"Q\":\n print(player.current_room)\n user_input = input(\"What direction do you want to go? \")\n\n # Break user input down into a verb and object\n first_space = user_input.find(\" \")\n if first_space > 0:\n verb = user_input[:first_space].strip().upper()\n object = user_input[first_space:].strip()\n else:\n verb = user_input.strip().upper()\n object = None\n\n print(f\"verb: \\'{verb}\\', object: \\'{object}\\'\")\n\n valid_input = False \n for direction in Direction:\n if verb == direction.value:\n player.move(direction)\n valid_input = True\n\n found = False \n\n if valid_input == False:\n if verb == \"G\" or verb == \"GET\" or verb == \"T\" or verb == \"TAKE\":\n for item in player.current_room.items:\n if object.lower() == item.name.lower():\n player.get(item)\n found = True \n\n if found == False: \n print(f\"I couldn't find a {object} in the {player.current_room.name}.\")\n\n valid_input = True\n\n elif verb == \"D\" or verb == \"DROP\":\n for item in player.items:\n if object.lower() == item.name.lower():\n player.drop(item)\n found = True \n\n if found == False: \n print(f\"I couldn't find a {object} in your satchel.\")\n\n valid_input = True\n\n elif verb == \"I\" or verb == \"INVENTORY\":\n player.invetory()\n valid_input = True\n\n if verb == \"H\" or valid_input == False:\n print(\"[N]orth, [S]outh, [E]ast, [W]est, [G]et, [T]ake, [D]rop, [I]nventory, [Q]uit, [H]elp\\n\") \n\nprint(\"Thank you for playing.\")\n","sub_path":"src/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"93716555","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jun 10 09:20:09 2018\r\n\r\n@author: manoj\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport cv2\r\n\r\ncanvas = np.zeros((300,300,3), dtype = \"uint8\")\r\ngreen = (0,255,0)\r\ncv2.line(canvas,(0,0),(300,300),green)\r\ncv2.imshow(\"Line_green\",canvas)\r\ncv2.waitKey(0)\r\n\r\nred = (0,0,255)\r\ncv2.line(canvas,(0,300),(300,0),red,4) #drawing red line with thickness 4 \r\ncv2.imshow(\"Line_red\",canvas)\r\ncv2.waitKey(0)\r\n\r\nred = (0,0,255)\r\ncv2.rectangle(canvas,(10,10),(50,50),red) #drawing red rectangle \r\ncv2.imshow(\"Rect_red\",canvas)\r\ncv2.waitKey(0)\r\n\r\nblue = (255,0,0)\r\ncv2.rectangle(canvas,(60,60),(120,120),blue,4) #drawing blue rectangle with thickness 4 \r\ncv2.imshow(\"Rect_blue\",canvas)\r\ncv2.waitKey(0)\r\n\r\n\r\nblue = (255,0,0)\r\ncv2.rectangle(canvas,(120,120),(200,200),blue,-1) #drawing blue rectangle with rectangle filled with blue \r\ncv2.imshow(\"Rect_blue_filled\",canvas)\r\ncv2.waitKey(0)","sub_path":"canvas.py","file_name":"canvas.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"631581597","text":"import sys\nimport ujson as json\nfrom collections import defaultdict\n\nwith open(sys.argv[1]) as f:\n transcript = json.load(f)\n \n speaker_lines = defaultdict(list)\n \n for line in transcript:\n speaker_lines[line[\"speaker\"]].append(line)\n\nif len(speaker_lines.keys()) > 1:\n\n for k, v in speaker_lines.iteritems():\n ext = sys.argv[1].split('.')[-1]\n fn = \".\".join(sys.argv[1].split('.')[:-1])\n with open(fn + '-' + k + '.' + ext, \"w\") as f:\n json.dump(v, f)\n\n","sub_path":"utilities/split_transcript.py","file_name":"split_transcript.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"531514238","text":"from keras.callbacks import ModelCheckpoint\n\nfrom bi_lstm_crf_model import *\nfrom process_data import *\nimport numpy as np\nimport argparse\nimport os\n\n\ndef random_split(x, y, split=0.2):\n indices = np.arange(x.shape[0])\n np.random.shuffle(indices)\n\n x = x[indices]\n y = y[indices]\n num_validation_samples = int(split * x.shape[0])\n\n x_train = x[: -num_validation_samples]\n y_train = y[: -num_validation_samples]\n x_val = x[-num_validation_samples:]\n y_val = y[-num_validation_samples:]\n return x_train, y_train, x_val, y_val\n\n\nif __name__ == '__main__':\n parse = argparse.ArgumentParser(description=\"进行模型的训练。\")\n parse.add_argument(\"--data_path\", help=\"训练数据文件路径\", default=\"./data/train.data\")\n parse.add_argument(\"--val_split\", type=float, help=\"验证集所占比例\", default=0.2)\n parse.add_argument(\"--save_dir\", help=\"模型保存目录\", default=\"./model\")\n parse.add_argument(\"--model_dir\", help=\"指定预训练的模型文件路径\", default=None)\n parse.add_argument(\"--epochs\", help=\"指定迭代几次\", type=int, default=10)\n parse.add_argument(\"--embedding_file_path\", help=\"词嵌入文件路径,��不指定,则会随机初始化词向量\", default=None)\n\n args = parse.parse_args()\n DATA_PATH = args.data_path\n VAL_SPLIT = args.val_split\n SAVE_DIR = args.save_dir\n EMBEDDING_FILE_PATH = args.embedding_file_path\n MODEL_DIR = args.model_dir\n EPOCHS = args.epochs\n\n x, y, word_index, chunk_index = process_data(DATA_PATH)\n x_train, y_train, x_val, y_val = random_split(x, y, VAL_SPLIT)\n\n if MODEL_DIR is not None:\n word_index, chunk_index = load_dict(os.path.join(MODEL_DIR, \"model.dict\"))\n model_configure = load_model_config(os.path.join(MODEL_DIR, \"model.cfg\"))\n model = model_configure.build_model()\n model.load_weights(os.path.join(MODEL_DIR, \"model.final.h5\"))\n else:\n model_configure = BiLSTMCRFModelConfigure(len(word_index) + 1, len(chunk_index) + 1)\n # 保存模型配置\n save_model_config(model_configure, os.path.join(SAVE_DIR, 'model.cfg'))\n # 保存词汇表\n save_dict((word_index, chunk_index), os.path.join(SAVE_DIR, 'model.dict'))\n # 载入词向量\n embedding_matrix = None\n if EMBEDDING_FILE_PATH is not None:\n embedding_matrix = create_embedding_matrix(get_embedding_index(EMBEDDING_FILE_PATH), word_index,\n model_configure)\n\n model = model_configure.build_model(embedding_matrix)\n\n model.summary()\n\n ck = ModelCheckpoint(os.path.join(SAVE_DIR, 'weights.{epoch:02d}-{val_loss:.2f}.h5')\n , monitor='loss', verbose=0)\n\n model.fit(x_train, y_train, batch_size=512, epochs=EPOCHS,\n validation_data=(x_val, y_val), callbacks=[ck])\n\n # 保存最终的权重\n model.save(os.path.join(SAVE_DIR, 'model.final.h5'))\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"586471822","text":"# Copyright (c) 2016 Huawei, 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\nfrom django.core.urlresolvers import reverse\nfrom django.utils.translation import pgettext_lazy\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ungettext_lazy\n\nfrom horizon import tables\n\nfrom karbor_dashboard.api import karbor as karborclient\n\n\nclass RestoreCheckpointLink(tables.LinkAction):\n name = \"restore\"\n verbose_name = _(\"Restore Checkpoint\")\n url = \"horizon:karbor:checkpoints:restore\"\n classes = (\"ajax-modal\",)\n icon = \"plus\"\n\n def get_link_url(self, checkpoint):\n checkpoint_id = checkpoint.id\n return reverse(self.url, args=(checkpoint.provider_id, checkpoint_id))\n\n def allowed(self, request, checkpoint):\n return checkpoint.status == 'available'\n\n\nclass DeleteCheckpointsAction(tables.DeleteAction):\n @staticmethod\n def action_present(count):\n return ungettext_lazy(u\"Delete Checkpoint\",\n u\"Delete Checkpoints\",\n count)\n\n @staticmethod\n def action_past(count):\n return ungettext_lazy(u\"Scheduled deletion of Checkpoint\",\n u\"Scheduled deletion of Checkpoints\",\n count)\n\n def allowed(self, request, checkpoint):\n return checkpoint.status == 'available'\n\n def delete(self, request, obj_id):\n datum = self.table.get_object_by_id(obj_id)\n provider_id = datum.provider_id\n karborclient.checkpoint_delete(request,\n provider_id=provider_id,\n checkpoint_id=obj_id)\n\n\ndef get_provider_link(obj):\n return reverse('horizon:karbor:protectionproviders:detail',\n args=(obj.provider_id, ))\n\n\ndef get_checkpoint_link(obj):\n \"\"\"url Two args\"\"\"\n return reverse(\"horizon:karbor:checkpoints:detail\",\n args=(obj.provider_id, obj.id))\n\n\ndef get_plan_name(obj):\n name = \"\"\n plan = getattr(obj, 'protection_plan')\n if plan is not None:\n name = plan.get(\"name\")\n return name\n\n\nclass UpdateRow(tables.Row):\n ajax = True\n\n def __init__(self, table, datum=None):\n super(UpdateRow, self).__init__(table, datum)\n self.provider_id = getattr(table, 'provider_id')\n\n def get_data(self, request, obj_id):\n provider = karborclient.provider_get(request, self.provider_id)\n checkpoint = karborclient.checkpoint_get(request,\n self.provider_id,\n obj_id)\n setattr(checkpoint, \"provider_name\", provider.name)\n setattr(checkpoint, \"provider_id\", provider.id)\n return checkpoint\n\n\nTASK_DISPLAY_CHOICES = (\n (\"error\", pgettext_lazy(\"Task status of an Checkpoint\", u\"Error\")),\n (\"protecting\", pgettext_lazy(\"Task status of an Checkpoint\",\n u\"Protecting\")),\n (\"available\", pgettext_lazy(\"Task status of an Checkpoint\", u\"Available\")),\n (\"deleting\", pgettext_lazy(\"Task status of an Checkpoint\", u\"Deleting\")),\n (\"deleted\", pgettext_lazy(\"Task status of an Checkpoint\", u\"Deleted\")),\n (\"error-deleting\", pgettext_lazy(\"Task status of an Checkpoint\",\n u\"Error Deleting\")),\n)\n\n\nclass CheckpointsTable(tables.DataTable):\n TASK_STATUS_CHOICES = (\n (\"error\", False),\n (\"available\", True),\n (\"deleted\", True),\n (\"error-deleting\", False),\n )\n checkpointId = tables.Column(\n \"id\",\n link=get_checkpoint_link,\n verbose_name=_('Checkpoint ID'))\n protectionProvider = tables.Column(\n \"provider_name\",\n link=get_provider_link,\n verbose_name=_('Protection Provider'))\n protectPlan = tables.Column(\n get_plan_name,\n verbose_name=_('Protection Plan'))\n status = tables.Column(\n 'status',\n verbose_name=_('Status'),\n status=True,\n status_choices=TASK_STATUS_CHOICES,\n display_choices=TASK_DISPLAY_CHOICES)\n\n class Meta(object):\n name = 'checkpoints'\n verbose_name = _('Checkpoints')\n status_columns = [\"status\", ]\n row_class = UpdateRow\n row_actions = (RestoreCheckpointLink, DeleteCheckpointsAction)\n\n\nclass DetailTable(tables.DataTable):\n\n class Meta(object):\n name = \"protectionresources\"\n verbose_name = _(\"Protection Resources\")\n hidden_title = False\n","sub_path":"karbor_dashboard/checkpoints/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":5061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"540891064","text":"#!/usr/bin/env python\r\n#Script does self blast of those with multiple species/gene hits to make sure the top hit is the rejected hit\r\n\r\ndef test_resolved_seqs(infile, blastdb, taxdb):\r\n import sqlite3, sys, time\r\n from Bio.Blast import NCBIWWW, NCBIXML\r\n from blastlib.clean_seq_funcs import resolve_seqs, alignment_comp, alignment_reg, alignment_rev_comp, blast, blast_all, identity_calc, tiling\r\n conn = sqlite3.connect(blastdb)\r\n c = conn.cursor()\r\n c.execute(\"ATTACH '\" + taxdb + \"' as 'tax'\")\r\n error_dic = {}\r\n blast_dic_nums = {}\r\n blast_dic_tcids = {}\r\n seqs_to_blast = []\r\n finalseqs = set()\r\n multseqs = []\r\n #do self blast and print to file\r\n with open(infile) as fasta_file:\r\n print(\"Blasting \" + infile)\r\n records = fasta_file.read()\r\n numqueries = records.count('>')\r\n error = True\r\n while error == True: \r\n try:\r\n result_handle = NCBIWWW.qblast(\"blastn\", \"nt\", records, entrez_query='((Papilionoidea[Organism]) OR Hedylidae[Organism]) OR Hesperiidae[Organism]', word_size=28, hitlist_size=100)\r\n error = False\r\n except:\r\n error = True\r\n #get rid of this extra step of printing xml using NCBIXML\r\n with open(infile+\".xml\", \"w\") as save_file:\r\n save_file.write(result_handle.read())\r\n result_handle.close()\r\n #open self blast file for parsing\r\n #make dictionary of query species: query GI of those that don't have the top hit as the same species\r\n \r\n with open(infile+\".xml\") as p:\r\n print(\"Parsing blast output\")\r\n blast_recs=NCBIXML.parse(p)\r\n count = 0\r\n for rec in blast_recs:\r\n count += 1\r\n print(str(round(float(count)/float(numqueries)*100, 2))+ \"%\")\r\n#figure out a new way to do this\r\n queryAcc = str(rec.query.split()[0])\r\n for iter in c.execute(\"SELECT GI FROM blast WHERE accession='\" + queryAcc + \"'\"):\r\n queryGI = (str(iter[0]))\r\n hitdic = {}\r\n hitSp = set()\r\n for alignment in rec.alignments:\r\n for hsp in alignment.hsps:\r\n identity=float(hsp.identities)/float(hsp.align_length)\r\n if alignment.title.split(\"|\")[1] == queryGI:\r\n pass\r\n else:\r\n hitdic[str(alignment.title.split(\"|\")[1])] = identity\r\n maxiden = max(hitdic.values())\r\n hitGIs = [GI for GI, iden in hitdic.iteritems() if iden == maxiden]\r\n for iter in c.execute(\"SELECT tc_id FROM blast WHERE GI='\" + queryGI + \"'\"):\r\n querySp = (str(iter[0]))\r\n for i in hitGIs:\r\n for iter in c.execute(\"SELECT tc_id FROM blast WHERE GI='\" + i + \"'\"):\r\n hitSp.add(str(iter[0]))\r\n #only look at top 5 if it doesnt hit the top hit - faster\r\n if querySp not in hitSp:\r\n hitSp = set()\r\n if len(hitdic.values()) > 5:\r\n maxiden = sorted(hitdic.values(), reverse = True)[0:5]\r\n else:\r\n maxiden = hitdic.values()\r\n hitGIs = [GI for GI, iden in hitdic.iteritems() if iden in maxiden]\r\n for i in hitGIs:\r\n for iter in c.execute(\"SELECT tc_id FROM blast WHERE GI='\" + i + \"'\"):\r\n hitSp.add(str(iter[0]))\r\n if querySp not in hitSp:\r\n error_dic[querySp] = queryGI\r\n else:\r\n finalseqs.add(queryGI)\r\n else:\r\n finalseqs.add(queryGI)\r\n count = 0\r\n #error_dic['21204'] = '316994286'\r\n ##go through error dictionary and align the 'same' gene/species to see if they're weird looking\r\n newseqs=set()\r\n print(\"Checking nonmatching sequences\")\r\n for tc_id in error_dic:\r\n count += 1\r\n print(str(round(float(count)/float(len(error_dic))*100, 2))+\"%\")\r\n list_of_GIs = []\r\n for iter in c.execute(\"SELECT Gene_name FROM blast WHERE GI ='\" + error_dic[tc_id] + \"'\"):\r\n gene_name = str(iter[0])\r\n for iter in c.execute(\"SELECT GI FROM blast WHERE tc_id = '\" + tc_id + \"' and Gene_name = '\" + gene_name + \"'\"): \r\n list_of_GIs.append(str(iter[0]))\r\n first_GI = list_of_GIs[0]\r\n other_GIs = list_of_GIs[1:]\r\n pair_check = []\r\n #align each seq to the first one - first one acts as the 'default' direction\r\n for x, GI in enumerate(other_GIs):\r\n GI_pair = [first_GI, GI]\r\n alignment = alignment_reg(GI_pair)\r\n iden = identity_calc(alignment)\r\n if iden < 90:\r\n# print(\"Low Aligned Identity: \" + str(iden))\r\n alignment = alignment_rev_comp(GI_pair)\r\n iden = identity_calc(alignment)\r\n if iden < 90: \r\n# print(\"Low Reverse Complement Aligned Identity: \" + str(iden))\r\n alignment = alignment_comp(GI_pair)\r\n iden = identity_calc(alignment)\r\n if iden < 90:\r\n# print(\"Low Complement Aligned Identity: \" + str(iden))\r\n pair_check.append(0)\r\n else:\r\n pair_check.append(1)\r\n# print(\"Complement iden: \" + str(iden) + \" so pair is fine\")\r\n else:\r\n pair_check.append(1)\r\n# print(\"Reverse Complement iden: \" + str(iden) + \" so pair is fine\")\r\n else:\r\n pair_check.append(1)\r\n# print(\"High Aligned Identity: \" + str(iden) + \" so pair is fine\")\r\n# print(pair_check)\r\n if all(i == 1 for i in pair_check):\r\n finalseqs.add(error_dic[tc_id])\r\n newseqs.add(error_dic[tc_id])\r\n else:\r\n idens, start_stop = tiling(list_of_GIs, gene_name)\r\n current_start = -1\r\n current_stop = -1 \r\n result = []\r\n if all(i > 70 for i in idens):\r\n for start, stop in sorted(start_stop):\r\n if start > current_stop:\r\n result.append((start, stop))\r\n current_start, current_stop = start, stop\r\n else:\r\n current_stop = max(current_stop, stop)\r\n result[-1] = (current_start, current_stop)\r\n if len(result) == len(start_stop):\r\n# print(\"Seqs align to different regions of probe, choosing all\")\r\n for x in list_of_GIs:\r\n finalseqs.add(x)\r\n newseqs.add(x)\r\n else:\r\n# print('Seqs overlap: Printing to file for hand checking')\r\n with open('these_seqs_overlap.txt' , 'a') as a:\r\n a.write(str(list_of_GIs) + '\\n') \r\n else:\r\n# print('Somethings up with a sequence - printing to check - will blast')\r\n pair_check.append(0)\r\n blast_dic_nums[list_of_GIs[0]] = len(list_of_GIs)\r\n blast_dic_tcids[list_of_GIs[0]] = tc_id\r\n seqs_to_blast.append(list_of_GIs)\r\n with open('seqs_to_be_blasted.txt', 'a') as a:\r\n a.write(str(list_of_GIs) + '\\n')\r\n if len(seqs_to_blast) > 0:\r\n print(\"Blasting error seqeuences (seqs don't align together and one doesn't align to whole)\") \r\n seqs_to_blast_flat = [item for sublist in seqs_to_blast for item in sublist]\r\n try:\r\n hits_all = blast_all(seqs_to_blast_flat, blast_dic_nums, blast_dic_tcids, c)\r\n except:\r\n time.sleep(5)\r\n hits_all = blast_all(seqs_to_blast_flat, blast_dic_nums, blast_dic_tcids, c)\r\n# print(hits_all)\r\n print(\"Parsing taxonomy for error sequences\")\r\n for x, list_of_GIs in enumerate(seqs_to_blast):\r\n hits = hits_all[x]\r\n tc_id = blast_dic_tcids[list_of_GIs[0]]\r\n #if theres only one lowest taxonomy hit and its not itself, change\r\n if hits.count(min(hits)) == 1 and error_dic[tc_id] != list_of_GIs[hits.index(min(hits))]:\r\n finalseqs.add(list_of_GIs[hits.index(min(hits))])\r\n# print(str(list_of_GIs[hits.index(min(hits))]) + \" had closer taxonomy hit\")\r\n elif hits.count(min(hits)) == 1 and error_dic[tc_id] == list_of_GIs[hits.index(min(hits))]:\r\n finalseqs.add(error_dic[tc_id])\r\n# print(str(list_of_GIs[hits.index(min(hits))]) + \" was previously chosen\")\r\n else: #there are multiple lowest taxonomy hits\r\n# print('Taxonomies had multiple closest hits')\r\n index_pos = []\r\n count = 0\r\n for x in hits:\r\n if x == min(hits):\r\n index_pos.append(count)\r\n count+=1\r\n mult_GIs = [list_of_GIs[x] for x in index_pos]\r\n GI_to_pick = resolve_seqs(mult_GIs)\r\n #if theres only one chosen and it wasnt the one already picked...add to change dic\r\n if len(GI_to_pick) == 1 and error_dic[tc_id]!=GI_to_pick[0]:\r\n finalseqs.add(GI_to_pick[0])\r\n# print(str(GI_to_pick) + \" chosen\")\r\n #if theres only one max length and it was already picked\r\n elif len(GI_to_pick) == 1 and error_dic[tc_id]==GI_to_pick[0]:\r\n# print(str(GI_to_pick) + \" was previously chosen\")\r\n finalseqs.add(GI_to_pick[0])\r\n else:\r\n #this only happens if the originally picked one is crappy and the rest are the same\r\n# print(\"Multiple choices: \" + str(GI_to_pick))\r\n multseqs.append(error_dic[tc_id])\r\n #Go to cluster analysis\r\n \r\n print('length of resolved=' + str(len(finalseqs)))\r\n print('length of not resolved = ' + str(len(multseqs)))\r\n \r\n with open(\"final_GIs.txt\", \"a\") as o:\r\n for m in finalseqs:\r\n o.write(str(m)+\"\\n\")\r\n \r\n #to cluster\r\n with open(\"multiple_gene_choices.txt\", \"a\") as o:\r\n for m in multseqs:\r\n o.write(str(m)+\"\\n\")\r\n \r\n \r\n \r\n \r\n conn.close()\r\n","sub_path":"cleanlib/blast_sp_parse.py","file_name":"blast_sp_parse.py","file_ext":"py","file_size_in_byte":10443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"347712245","text":"import requests\nimport re\nimport time\nfrom bs4 import BeautifulSoup\nimport spider_proxy_requests as ips\nimport random\nimport pymongo\nimport json\n\n# 定义全局信息\n\n# 1.读取请求头\nuserAgents = ips.getUserAget()\n\nua = random.choice(userAgents)\n\n# 2. 请求头信息,更换user-agent防止被禁\nheader={\n 'user-agent':ua,\n 'Referer':'https://space.bilibili.com'\n}\n\n# 3. 获取代理ip\nproxyIps = ips.getProxyIps()\n\npi = random.choice(proxyIps)\n\n\n\n# 4.url\n# 用户信息url\nuser_info_url = 'https://api.bilibili.com/x/space/acc/info?mid={0}&jsonp=jsonp'\n\nuser_sta_url = 'https://api.bilibili.com/x/relation/stat?vmid={0}&jsonp=jsonp'\n\n# 关注列表url\nfollowing_url = 'https://api.bilibili.com/x/relation/followings?vmid={0}&pn={1}&ps=20&order=desc&jsonp=jsonp&callback=__jp3'\n\n# 初始用户id\nstart_user_id = '25105113'\n\n# 无密码连接mongodb\nmongo_client = pymongo.MongoClient('127.0.0.1',27017)\n\n# 连接指定db\nbiliUserDB = mongo_client.biliUsers\n\n# 打印db下的所有集合\nprint(biliUserDB.collection_names)\n# 连接聚集\nbiliUserTab = biliUserDB.userInfo\n\n# 获取关注列表\ndef getFollows(userId):\n proip = random.choice(proxyIps)\n proxy={\n 'http': 'http://'+ proip,\n # 'https': 'http://'+ proip\n }\n header={\n 'user-agent':random.choice(userAgents),\n 'Referer':'https://space.bilibili.com'\n }\n time.sleep(2)\n resp = requests.get(following_url.format(userId,1),headers=header,proxies=proxy)\n\n if requests.codes.ok == resp.status_code:\n content = resp.text[6:-1]\n user_follows_resp = json.loads(content)['data']\n follows = user_follows_resp['list']\n if 0 == user_follows_resp['total']:\n return\n total_page = round(user_follows_resp['total'] / 20)\n\n for page_num in range(1,total_page+1):\n try:\n # 所关注人id\n follow_ids = []\n parseRespToList(follow_ids,userId,page_num,header,proxy)\n for fid in follow_ids:\n # 首先检查是否已保存用户\n find_condition = {\n '_id' : fid,\n }\n find_result = biliUserTab.find_one(find_condition)\n if None == find_result:\n saveUserInfo(fid)\n getFollows(fid)\n\n except Exception as e:\n print('获取当前用户:{0} 关注列表第{1}页失败:{2}'.format(userId,page_num,e))\n \n\n# 解析请求关注列表相应信息保存关注列表id\ndef parseRespToList(follow_ids,userId,pageNum,header,proxy):\n\n proip = random.choice(proxyIps)\n proxy={\n 'http': 'http://'+ proip,\n # 'https': 'http://'+ proip\n }\n header={\n 'user-agent':random.choice(userAgents),\n 'Referer':'https://space.bilibili.com'\n }\n resp = requests.get(following_url.format(userId,pageNum),headers=header,proxies=proxy)\n\n if requests.codes.ok == resp.status_code:\n content = resp.text[6:-1]\n user_follows_resp = json.loads(content)\n follows = user_follows_resp['data']['list']\n\n # 保存第一页关注者id\n for follow in follows:\n follow_ids.append(follow['mid']) \n\n\ndef saveUserInfo(userId):\n proip = random.choice(proxyIps)\n proxy={\n 'http': 'http://'+ proip,\n # 'https': 'http://'+ proip\n }\n header={\n 'user-agent':random.choice(userAgents),\n 'Referer':'https://space.bilibili.com'\n }\n time.sleep(2)\n resp = requests.get(user_info_url.format(userId),headers=header,proxies=proxy)\n\n time.sleep(2)\n\n response = requests.get(user_sta_url.format(userId),headers=header,proxies=proxy)\n\n if requests.codes.ok == resp.status_code and requests.codes.ok == response.status_code:\n user_info = json.loads(resp.text)['data']\n user_sta = json.loads(response.text)['data']\n userInfo = {\n '_id': user_info['mid'],\n 'birthday':user_info['birthday'],\n 'coins':user_info['coins'],\n 'faceUrl':user_info['face'],\n 'level':user_info['level'],\n 'name':user_info['name'],\n 'sex':user_info['sex'],\n 'sign':user_info['sign'],\n 'follower':user_sta['follower'],\n 'following':user_sta['following']\n }\n try:\n biliUserTab.insert_one(userInfo)\n print('保存用户信息:{0}',userInfo)\n except Exception as e:\n print('插入用户{0}信息失败:{1}'.format(userId,e))\n\n\nif __name__ == '__main__':\n\n saveUserInfo(start_user_id)\n\n getFollows(start_user_id)\n\n\n\n ","sub_path":"spider_proxy_request_bilibili.py","file_name":"spider_proxy_request_bilibili.py","file_ext":"py","file_size_in_byte":4694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"409572960","text":"import tushare as ts\nimport pandas as pd\nimport random,time\n\n'''使用tushare API需要提供的指令'''\ntushare_token='9d318f4f16fc290756e756ddca50bdaabda9d3d98698345f4e505768'\n\ndef get_stock_symbol():\n '''获取当日所有上市股票信息,并存于文件中'''\n pro=ts.pro_api(tushare_token)\n stocks_info=pro.query('stock_basic',exchange='',list_status='L', fields='ts_code,symbol,name,area,industry,list_date')\n stocks_info.to_csv('Data\\\\stocks_info.csv')\n return stocks_info\n\n\ndef random_download_stocks(stock_count):\n '''\n 该函数用来随机下载stock_count数量的股票\n :param stock_count: 是要下载的股票数量\n '''\n ts.set_token(tushare_token)\n Stocks=pd.DataFrame.from_csv('Data\\\\stocks_info.csv')\n length=len(Stocks)\n print('共有',length,'只股票,现在随机下载',stock_count,'只!')\n\n '''处理时间,将开始时间处理成当日的三年前的同一天'''\n now = time.localtime()\n year = now.tm_year - 3\n start = str(year)\n if now.tm_mon < 10:\n start = start + '0' + str(now.tm_mon)\n else:\n start = start + str(now.tm_mon)\n if now.tm_mday < 10:\n start = start + '0' + str(now.tm_mday)\n else:\n start = start + str(now.tm_mday)\n '''下载股票'''\n success_stocks=pd.DataFrame(columns=['code','name'])\n for i in range(stock_count):\n df=pd.DataFrame()\n while df.empty:\n index = random.randint(1, 1000000) % length\n ts_code, name = Stocks.iloc[index][['ts_code', 'name']]\n df = ts.pro_bar(ts_code=ts_code, start_date=start, adj='qfq') #复权可以��除由于除权除息造成的价格走势畸变,保持股价走势的连续性,便于神经网络分析,这是技术面分析常用到的数据。\n lastday =time.strptime(df.iloc[[df.shape[0]-1]]['trade_date'].values[0],'%Y%m%d') #按%Y%m%d格式,将时间字符串转化成元组\n if lastday.tm_year==year and (lastday.tm_mon==now.tm_mon or lastday.tm_mon==now.tm_mon+1):\n #判断获取的股票在三年前有没有交易数据\n pass\n else:\n df=pd.DataFrame()\n df.to_csv('Data\\\\交易数据\\\\'+ts_code+'.csv')\n #存于文件中\n success_stocks.loc[success_stocks.shape[0]+1]={'code':ts_code,'name':name}\n success_stocks.to_csv('Data\\\\交易数据\\\\download_stocks_symbol.csv')\n","sub_path":"Beta_0.1/Data_fetcher_tushare.py","file_name":"Data_fetcher_tushare.py","file_ext":"py","file_size_in_byte":2428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"7269216","text":"import sys\r\nimport os\r\nimport glob\r\nimport cv2\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom function.utils import print_time\r\nfrom function.pose.pose_net import POSE_NET\r\nfrom function.retrieval.codes.DCA import DCA\r\nfrom function.detection.DetectionModel import DetectionModel\r\nfrom function.detection.pascalvoc import pascalvoc\r\nfrom function.test.pascalvoc import pascalvoc as pascalvoc_test\r\nfrom function.test.pascalvoc_retrieval import pascalvoc as pascalvoc_retrieval\r\nfrom function.pose.pose_utils import manage_duplicate_pose\r\n\r\n\r\nclass QuantReportPose():\r\n\r\n def __init__(self, args):\r\n self.args = args\r\n self.mode = args.mode\r\n\r\n # Load models\r\n config = tf.ConfigProto()\r\n config.gpu_options.allow_growth = True\r\n \r\n # 선지\r\n if args.mode in ['detection_unit_test', 'detection', 'retrieval', 'pose', 'test']:\r\n self.graph_detection = tf.Graph()\r\n with self.graph_detection.as_default():\r\n self.sess_detection = tf.Session(config=config)\r\n self.detection_model = DetectionModel(self.args, self.graph_detection, self.sess_detection)\r\n \r\n \r\n # 민우\r\n if args.mode in ['retrieval_unit_test', 'retrieval', 'pose', 'test']:\r\n self.graph_retrieval = tf.Graph()\r\n with self.graph_retrieval.as_default():\r\n self.sess_retrieval = tf.Session(config=config)\r\n self.retrieval_model = DCA(self) \r\n\r\n # 이삭\r\n if args.mode in ['pose_unit_test', 'pose', 'test']:\r\n self.graph_pose = tf.Graph()\r\n with self.graph_pose.as_default():\r\n self.sess_pose = tf.Session(config=config)\r\n self.pose_model = POSE_NET(self)\r\n \r\n\r\n # Load data\r\n self.imgs, self.img_names, self.num_test_imgs, self.labels, self.cad_names = self.load_data()\r\n self.H, self.W, _ = self.imgs[0].shape\r\n\r\n # Results\r\n # WARINING : image index starts with 0\r\n # 선지\r\n self.detection_results = {} # (int) image index : [[x, y, w, h], ...]\r\n # 민우\r\n self.retrieval_results = {} # (int) image index : [cad_name, ...]\r\n # 이삭\r\n self.pose_results = {} # (int) image index : [pose_name, ...]\r\n\r\n\r\n def load_data(self):\r\n \"\"\"load data from npy\r\n \r\n Returns:\r\n imgs : (uint8) [10, 1700, 1200, 3]\r\n num_test_imgs : (int) number of test images\r\n cad_names : (str) list of cad names\r\n\r\n \"\"\"\r\n args = self.args\r\n\r\n # load image names\r\n files = sorted(glob.glob(args.image_path + '/*'))\r\n img_names = [os.path.basename(x).split('.')[0] for x in files]\r\n\r\n # load from npy\r\n with open(os.path.join(args.binary_path, 'test_data.npy'), 'rb') as f:\r\n imgs = np.load(f)\r\n print('loaded imgs : ', imgs.shape)\r\n num_test_imgs = len(imgs)\r\n\r\n # load labels\r\n labels = open(os.path.join(args.label_path, 'label.txt'), 'r').read().splitlines()\r\n\r\n # load cad names\r\n cad_adrs = sorted(glob.glob(args.cad_path + '/*'))\r\n cad_names = [os.path.splitext(os.path.basename(x))[0] for x in cad_adrs]\r\n\r\n return imgs, img_names, num_test_imgs, labels, cad_names\r\n\r\n\r\n def detection(self):\r\n \"\"\"STEP1 : detection\r\n \r\n detect furniture parts in test images\r\n\r\n Update:\r\n self.detection_results = {}\r\n key : cad index\r\n value : [[x, y, w, h], ...]\r\n \"\"\"\r\n # unit test\r\n if self.mode == 'detection_unit_test':\r\n detection_gt = self.ground_truth('detection')\r\n\r\n # do detection\r\n self.detection_results_withcls = {}\r\n\r\n for i in range(self.imgs.shape[0]):\r\n self.detection_results_withcls[i] = self.detection_model.test(self.imgs[i], i)\r\n temp = []\r\n for x in self.detection_results_withcls[i]['Mid']: temp.append(x)\r\n for x in self.detection_results_withcls[i]['New']: temp.append(x)\r\n temp = sorted(temp)\r\n self.detection_results[i] = temp\r\n if self.mode != 'test':\r\n pascalvoc(self.args).pascalvoc_calculate_iou()\r\n\r\n\r\n\r\n def retrieval(self): # 민우\r\n \"\"\"STEP 2 : retrieval\r\n\r\n retrieve cad name from cropped images of detection results\r\n\r\n Update:\r\n self.retrieval_results = {}\r\n key : cad index\r\n value : [cad_name, ...]\r\n \"\"\"\r\n # unit test\r\n if self.mode == 'retrieval_unit_test':\r\n self.detection_results = self.ground_truth('detection')\r\n retrieval_gt = self.ground_truth('retrieval')\r\n correct_num = 0\r\n for i in range(self.num_test_imgs):\r\n page_num = i\r\n whole_img = self.imgs[i]\r\n cropped_imgs = list()\r\n for x, y, w, h in self.detection_results[i]:\r\n cropped_img = whole_img[y : y + h, x : x + w, :]\r\n resized_img = self.retrieval_model.resize_and_pad(cropped_img)\r\n cropped_img = np.expand_dims(resized_img, axis=0)\r\n cropped_imgs = np.vstack((cropped_imgs, cropped_img)) if len(cropped_imgs) else cropped_img\r\n _, indices, correct_num_ = self.retrieval_model.test(self, page_num, cropped_imgs, retrieval_gt, self.cad_names)\r\n correct_num += correct_num_\r\n print(\"One Page Finished: {}\".format(page_num))\r\n print('-------------------------')\r\n print('Accuracy : {}%'.format(correct_num / self.num_test_imgs * 10))\r\n else:\r\n retrieval_gt = []\r\n self.save_retrieval_gt()\r\n for i in range(self.num_test_imgs):\r\n page_num = i\r\n whole_img = self.imgs[i]\r\n cropped_imgs = list()\r\n for x, y, w, h in self.detection_results[i]:\r\n cropped_img = whole_img[y : y + h, x : x + w, :]\r\n resized_img = self.retrieval_model.resize_and_pad(cropped_img)\r\n cropped_img = np.expand_dims(resized_img, axis=0)\r\n cropped_img = np.expand_dims(resized_img, axis=0)\r\n cropped_imgs = np.vstack((cropped_imgs, cropped_img)) if len(cropped_imgs) else cropped_img\r\n result_name, indices, _ = self.retrieval_model.test(self, page_num, cropped_imgs, retrieval_gt, self.cad_names)\r\n self.retrieval_results[i] = result_name\r\n self.save_retrieval_pred()\r\n _, __ = pascalvoc_retrieval(self.args).pascalvoc_calculate_iou()\r\n \r\n def pose(self): # 이삭\r\n \"\"\"STEP 3 : pose\r\n \r\n get pose from detection, retrieval results\r\n\r\n Update:\r\n self.pose_results = {}\r\n key : cad index\r\n value : [pose, ...]\r\n \"\"\"\r\n args = self.args\r\n\r\n # unit test\r\n if self.mode == 'pose_unit_test':\r\n self.detection_results = self.ground_truth('detection')\r\n self.retrieval_results = self.ground_truth('retrieval')\r\n self.pose_gt = self.ground_truth('pose')\r\n self.pose_results = self.pose_model.test()\r\n self.save_bbox()\r\n _, self.for_draw_bbox = pascalvoc_test(self.args).pascalvoc_calculate_iou()\r\n\r\n\r\n def output_visualization(self):\r\n \"\"\"visualize test output \"\"\"\r\n args = self.args\r\n for i in range(self.num_test_imgs):\r\n img = self.imgs[i].copy()\r\n img_name = self.img_names[i]\r\n detections = [x for x in self.for_draw_bbox if x[0] == img_name]\r\n for det in detections:\r\n class_name = det[1]\r\n cad_name, pose_idx = class_name.split('-')\r\n x, y, r, b = det[3]\r\n x, y, r, b = int(x), int(y), int(r), int(b)\r\n color = (0, 255, 0) if det[4] == 'TP' else (0, 0, 255)\r\n cv2.rectangle(img, (x, y), (r, b), color, 2)\r\n textLabel = 'class {}: {}'.format(cad_name, pose_idx)\r\n (retval, baseLine) = cv2.getTextSize(textLabel, cv2.FONT_HERSHEY_COMPLEX, 1, 1)\r\n textOrg = (x, y - 0)\r\n cv2.rectangle(img, (textOrg[0] - 5, textOrg[1] + baseLine - 5),\r\n (textOrg[0] + retval[0] + 5, textOrg[1] - retval[1] - 5), (0, 0, 0), 2)\r\n cv2.rectangle(img, (textOrg[0] - 5, textOrg[1] + baseLine - 5),\r\n (textOrg[0] + retval[0] + 5, textOrg[1] - retval[1] - 5), (255, 255, 255), -1)\r\n cv2.putText(img, textLabel, textOrg, cv2.FONT_HERSHEY_DUPLEX, 1, (0, 0, 0), 1)\r\n\r\n cv2.imwrite(os.path.join(args.output_path, img_name + '.png'), img)\r\n\r\n\r\n def save_test_data(self):\r\n \"\"\"create and save test data in binary format\r\n \r\n Read test images and save them into binary format\r\n\r\n Saves:\r\n imgs : (uint8) [10, 1700, 1200, 3]\r\n \r\n \"\"\"\r\n print('================')\r\n print(' SAVE TEST NPY')\r\n print('================')\r\n\r\n # read images\r\n img_adrs = sorted(glob.glob(self.args.image_path + '/*'))\r\n imgs = np.array([cv2.imread(img_adr) for img_adr in img_adrs])\r\n\r\n # save them as npy\r\n with open(os.path.join(self.args.binary_path, 'test_data.npy'), 'wb') as f:\r\n np.save(f, imgs)\r\n print('saved imgs : ', imgs.shape)\r\n\r\n # save ground truth labels for test map calculation\r\n self.detection_results = self.ground_truth('detection')\r\n self.retrieval_results = self.ground_truth('retrieval')\r\n self.pose_results = self.ground_truth('pose')\r\n self.new_mid_results = self.ground_truth('new_mid')\r\n\r\n # save ground_truth bbox answers\r\n self.save_detection_bbox_gt()\r\n self.save_bbox('gt')\r\n\r\n\r\n def ground_truth(self, type):\r\n detection_gt = {}\r\n retrieval_gt = {}\r\n pose_gt = {}\r\n new_mid_gt = {}\r\n \r\n NUM_CAD = 10\r\n\r\n index = 0\r\n for i in range(self.num_test_imgs):\r\n detection_gt[i] = []\r\n retrieval_gt[i] = []\r\n pose_gt[i] = []\r\n new_mid_gt[i] = []\r\n for j in range(NUM_CAD):\r\n _, x, y, w, h, new_mid, cad, pose = self.labels[index].split(',')\r\n x = int(x)\r\n y = int(y)\r\n w = int(w)\r\n h = int(h)\r\n detection_gt[i].append([x, y, w, h])\r\n retrieval_gt[i].append(cad)\r\n pose_gt[i].append(int(pose))\r\n new_mid_gt[i].append(new_mid)\r\n index += 1\r\n\r\n if type == 'detection':\r\n return detection_gt\r\n if type == 'retrieval':\r\n return retrieval_gt\r\n if type == 'pose':\r\n return pose_gt\r\n if type == 'new_mid':\r\n return new_mid_gt\r\n\r\n\r\n def save_bbox(self, type='det'):\r\n \"\"\"saves result dictionaries inorder to compute map\r\n Use this function after dictionaries are updated.\"\"\"\r\n args = self.args\r\n if self.mode in ['pose', 'pose_unit_test', 'test']:\r\n save_path = args.pose_intermediate_results_path\r\n elif self.mode in ['test_data']:\r\n save_path = args.input_bbox_path\r\n\r\n for i in range(self.num_test_imgs):\r\n detection_results = self.detection_results[i]\r\n retrieval_results = self.retrieval_results[i]\r\n pose_results = self.pose_results[i]\r\n img_name = self.img_names[i]\r\n with open(os.path.join(save_path, img_name + '.txt'), 'w') as f:\r\n for det, ret, pose in zip(detection_results, retrieval_results, pose_results):\r\n pose = manage_duplicate_pose(ret, pose)\r\n class_name = ret + '-' + str(pose)\r\n x, y, w, h = det\r\n r, b = x + w, y + h\r\n confidence = 1.0\r\n if type == 'gt':\r\n line = '%s %d %d %d %d\\n' % (class_name, x, y, r, b)\r\n else:\r\n line = '%s %f %d %d %d %d\\n' % (class_name, confidence, x, y, r, b)\r\n f.write(line)\r\n\r\n\r\n def save_detection_bbox_gt(self):\r\n \"\"\"saves detection bbox ground truth\"\"\"\r\n args = self.args\r\n save_path = args.detection_anns_label_path\r\n m = int(args.detection_bbox_margin)\r\n\r\n for i in range(self.num_test_imgs):\r\n img_name = self.img_names[i]\r\n new_mid_results = self.new_mid_results[i]\r\n detection_results = self.detection_results[i]\r\n with open(os.path.join(save_path, img_name + '.txt'), 'w') as f:\r\n for NM, det, in zip(new_mid_results, detection_results):\r\n x, y, w, h = det\r\n r, b = x + w, y + h\r\n # bbox margin\r\n x = max(0, x - m)\r\n y = max(0, y - m)\r\n r = min(self.W, r + m)\r\n b = min(self.H, b + m)\r\n line = '%s %d %d %d %d\\n' % (NM, x, y, r, b)\r\n f.write(line)\r\n\r\n def save_retrieval_gt(self):\r\n \"\"\"saves detection bbox ground truth\"\"\"\r\n args = self.args\r\n save_path = args.retrieval_gt_path\r\n m = int(args.detection_bbox_margin)\r\n\r\n for i in range(self.num_test_imgs):\r\n img_name = self.img_names[i]\r\n retrieval_label = self.ground_truth('retrieval')[i]\r\n detection_label = self.ground_truth('detection')[i]\r\n with open(os.path.join(save_path, img_name + '.txt'), 'w') as f:\r\n for ret_label, det, in zip(retrieval_label, detection_label):\r\n x, y, w, h = det\r\n r, b = x + w, y + h\r\n # bbox margin\r\n x = max(0, x - m)\r\n y = max(0, y - m)\r\n r = min(self.W, r + m)\r\n b = min(self.H, b + m)\r\n line = '%s %d %d %d %d\\n' % (ret_label, x, y, r, b)\r\n f.write(line)\r\n\r\n def save_retrieval_pred(self):\r\n \"\"\"saves result dictionaries inorder to compute map\r\n Use this function after dictionaries are updated.\"\"\"\r\n args = self.args\r\n save_path = args.retrieval_intermediate_results_path\r\n\r\n for i in range(self.num_test_imgs):\r\n detection_results = self.detection_results[i]\r\n retrieval_results = self.retrieval_results[i]\r\n img_name = self.img_names[i]\r\n with open(os.path.join(save_path, img_name + '.txt'), 'w') as f:\r\n for det, ret in zip(detection_results, retrieval_results):\r\n class_name = ret\r\n x, y, w, h = det\r\n r, b = x + w, y + h\r\n confidence = 1.0\r\n line = '%s %f %d %d %d %d\\n' % (class_name, confidence, x, y, r, b)\r\n f.write(line)\r\n\r\n\r\n\r\n","sub_path":"Evaluation/3/codes/quantitative_report_pose.py","file_name":"quantitative_report_pose.py","file_ext":"py","file_size_in_byte":15251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"284927851","text":"import math\n\nimport numpy\n\nfrom .appendix import appendix_m, appendix_g, appendix_c\nfrom .constants import DAYS_PER_MONTH, SUMMER_MONTHS\nfrom .domestic_hot_water import hot_water_use\nfrom .fuel_use import fuel_use\nfrom .lighting import lighting_consumption\nfrom .solar import solar\nfrom .utils import monthly_to_annual\nfrom .ventilation import ventilation\n\n\ndef heat_loss(dwelling):\n \"\"\"\n Return the attributes `h`, `hlp`, `h_fabric`, `h_bridging`, `h_vent`, `h_vent_annual`\n on the given dwelling object\n\n Args:\n dwelling:\n\n Returns:\n dict of heat loss attributes, to be added to dwelling using `update()`\n \"\"\"\n # TODO: what is \"h\"?\n if dwelling.get('hlp') is not None:\n\n return dict(h=dwelling.hlp * dwelling.GFA)\n\n UA = sum(e.Uvalue * e.area for e in dwelling.heat_loss_elements)\n A_bridging = sum(e.area for e in dwelling.heat_loss_elements if e.is_external)\n\n if dwelling.get(\"Uthermalbridges\") is not None:\n h_bridging = dwelling.Uthermalbridges * A_bridging\n else:\n h_bridging = sum(x['length'] * x['y'] for x in dwelling.y_values)\n\n h_vent = 0.33 * dwelling.infiltration_ach * dwelling.volume\n\n h = UA + h_bridging + h_vent\n return dict(\n h=h,\n hlp=h / dwelling.GFA,\n h_fabric=UA,\n h_bridging=h_bridging,\n h_vent=h_vent,\n h_vent_annual=monthly_to_annual(h_vent))\n\n\ndef water_heater_output(dwelling):\n if dwelling.get('fghrs') is not None:\n dwelling.savings_from_fghrs = appendix_g.fghr_savings(dwelling)\n else:\n dwelling.savings_from_fghrs = 0\n\n dwelling.output_from_water_heater = numpy.maximum(0,\n dwelling.total_water_heating +\n dwelling.input_from_solar +\n dwelling.fghrs_input_from_solar -\n dwelling.savings_from_wwhrs -\n dwelling.savings_from_fghrs)\n\n\ndef internal_heat_gain(dwelling):\n \"\"\"\n Calculate internal heat games.\n\n .. note::\n must have calculated the lighting first so that it can be\n included in the internal heat gains\n\n Args:\n dwelling:\n\n Returns:\n\n \"\"\"\n losses_gain = -40 * dwelling.Nocc\n water_heating_gains = (1000. / 24.) * dwelling.heat_gains_from_hw / DAYS_PER_MONTH\n\n mean_appliance_energy = 207.8 * (dwelling.GFA * dwelling.Nocc) ** 0.4714\n appliance_consumption_per_day = (mean_appliance_energy / 365.) * (\n 1 + 0.157 * numpy.cos((2. * math.pi / 12.) * (numpy.arange(12) - .78)))\n\n appliance_consumption = appliance_consumption_per_day * DAYS_PER_MONTH\n\n if dwelling.reduced_gains:\n met_gain = 50 * dwelling.Nocc\n cooking_gain = 23 + 5 * dwelling.Nocc\n appliance_gain = (0.67 * 1000. / 24) * appliance_consumption_per_day\n light_gain = 0.4 * dwelling.full_light_gain\n else:\n met_gain = 60 * dwelling.Nocc\n cooking_gain = 35 + 7 * dwelling.Nocc\n appliance_gain = (1000. / 24) * appliance_consumption_per_day\n light_gain = dwelling.full_light_gain\n\n total_internal_gains = (met_gain\n + light_gain\n + appliance_gain\n + cooking_gain\n + water_heating_gains\n + dwelling.pump_gain\n + losses_gain)\n\n if dwelling.reduced_gains:\n summer_met_gain = 60 * dwelling.Nocc\n summer_cooking_gain = 35 + 7 * dwelling.Nocc\n summer_appliance_gain = (1000. / 24) * appliance_consumption_per_day\n summer_light_gain = dwelling.full_light_gain\n total_internal_gains_summer = (summer_met_gain +\n water_heating_gains +\n summer_light_gain +\n summer_appliance_gain +\n summer_cooking_gain +\n dwelling.pump_gain +\n losses_gain\n - dwelling.heating_system_pump_gain)\n else:\n total_internal_gains_summer = total_internal_gains - dwelling.heating_system_pump_gain\n\n # Apply results to dwelling\n return dict(appliance_consumption=appliance_consumption,\n met_gain=met_gain,\n cooking_gain=cooking_gain,\n appliance_gain=appliance_gain,\n light_gain=light_gain,\n water_heating_gains=water_heating_gains,\n losses_gain=losses_gain,\n total_internal_gains=total_internal_gains,\n total_internal_gains_summer=total_internal_gains_summer)\n\n\ndef heating_requirement(dwelling):\n if not dwelling.get('thermal_mass_parameter'):\n ka = 0\n for t in dwelling.thermal_mass_elements:\n ka += t.area * t.kvalue\n dwelling.thermal_mass_parameter = ka / dwelling.GFA\n\n dwelling.heat_calc_results = calc_heat_required(\n dwelling, dwelling.Texternal_heating, dwelling.winter_heat_gains)\n Q_required = dwelling.heat_calc_results['heat_required']\n for i in SUMMER_MONTHS:\n Q_required[i] = 0\n dwelling.heat_calc_results['loss'][i] = 0\n dwelling.heat_calc_results['utilisation'][i] = 0\n dwelling.heat_calc_results['useful_gain'][i] = 0\n\n dwelling.Q_required = Q_required\n\n\ndef calc_heat_required(dwelling, Texternal, heat_gains):\n tau = dwelling.thermal_mass_parameter / (3.6 * dwelling.hlp)\n a = 1 + tau / 15.\n\n # These are for pcdf heat pumps - when heat pump is undersized it\n # can operator for longer hours on some days\n if dwelling.get('longer_heating_days'):\n N24_16_m, N24_9_m, N16_9_m = dwelling.longer_heating_days()\n else:\n N24_16_m, N24_9_m, N16_9_m = (None, None, None)\n\n L = dwelling.h * (dwelling.living_area_Theating - Texternal)\n util_living = heat_utilisation_factor(a, heat_gains, L)\n Tno_heat_living = temperature_no_heat(Texternal,\n dwelling.living_area_Theating,\n dwelling.heating_responsiveness,\n util_living,\n heat_gains,\n dwelling.h)\n\n Tmean_living_area = Tmean(\n Texternal, dwelling.living_area_Theating, Tno_heat_living,\n tau, dwelling.heating_control_type_sys1, N24_16_m, N24_9_m, N16_9_m, living_space=True)\n\n if dwelling.main_heating_fraction < 1 and dwelling.get('heating_systems_heat_separate_areas'):\n if dwelling.main_heating_fraction > dwelling.living_area_fraction:\n # both systems contribute to rest of house\n weight_1 = 1 - dwelling.main_heating_2_fraction / \\\n (1 - dwelling.living_area_fraction)\n\n Tmean_other_1 = temperature_rest_of_dwelling(\n dwelling, Texternal, tau, a, L, heat_gains, dwelling.heating_control_type_sys1, N24_16_m, N24_9_m,\n N16_9_m)\n Tmean_other_2 = temperature_rest_of_dwelling(\n dwelling, Texternal, tau, a, L, heat_gains, dwelling.heating_control_type_sys2, N24_16_m, N24_9_m,\n N16_9_m)\n\n Tmean_other = Tmean_other_1 * \\\n weight_1 + Tmean_other_2 * (1 - weight_1)\n else:\n # only sys2 does rest of house\n Tmean_other = temperature_rest_of_dwelling(\n dwelling, Texternal, tau, a, L, heat_gains, dwelling.heating_control_type_sys2, N24_16_m, N24_9_m,\n N16_9_m)\n else:\n Tmean_other = temperature_rest_of_dwelling(\n dwelling, Texternal, tau, a, L, heat_gains, dwelling.heating_control_type_sys1, N24_16_m, N24_9_m,\n N16_9_m)\n\n if not dwelling.get('living_area_fraction'):\n dwelling.living_area_fraction = dwelling.living_area / dwelling.GFA\n\n meanT = dwelling.living_area_fraction * Tmean_living_area + \\\n (1 - dwelling.living_area_fraction) * \\\n Tmean_other + dwelling.temperature_adjustment\n L = dwelling.h * (meanT - Texternal)\n utilisation = heat_utilisation_factor(a, heat_gains, L)\n return dict(\n tau=tau,\n alpha=a,\n Texternal=Texternal,\n Tmean_living_area=Tmean_living_area,\n Tmean_other=Tmean_other,\n util_living=util_living,\n Tmean=meanT,\n loss=L,\n utilisation=utilisation,\n useful_gain=utilisation * heat_gains,\n heat_required=(range_cooker_factor(dwelling) *\n 0.024 * (\n L - utilisation * heat_gains) * DAYS_PER_MONTH),\n )\n\n\ndef temperature_rest_of_dwelling(dwelling, Texternal, tau, a, L, heat_gains, control_type, N24_16_m, N24_9_m, N16_9_m):\n Theat_other = heating_temperature_other_space(dwelling.hlp, control_type)\n L = dwelling.h * (Theat_other - Texternal)\n Tno_heat_other = temperature_no_heat(Texternal,\n Theat_other,\n dwelling.heating_responsiveness,\n heat_utilisation_factor(\n a, heat_gains, L),\n heat_gains,\n dwelling.h)\n return Tmean(Texternal, Theat_other, Tno_heat_other, tau, control_type, N24_16_m, N24_9_m, N16_9_m,\n living_space=False)\n\n\ndef Tmean(Texternal, Theat, Tno_heat, tau, control_type, N24_16_m, N24_9_m, N16_9_m, living_space):\n tc = 4 + 0.25 * tau\n dT = Theat - Tno_heat\n\n if control_type == 1 or control_type == 2 or living_space:\n # toff1=7\n # toff2=8\n # toff3=0\n # toff4=8\n # weekday\n u1 = temperature_reduction(dT, tc, 7)\n u2 = temperature_reduction(dT, tc, 8)\n Tweekday = Theat - (u1 + u2)\n\n # weekend\n u3 = 0 # (since Toff3=0)\n u4 = u2 # (since Toff4=Toff2)\n Tweekend = Theat - (u3 + u4)\n else:\n # toff1=9\n # toff2=8\n # toff3=9\n # toff4=8\n u1 = temperature_reduction(dT, tc, 9)\n u2 = temperature_reduction(dT, tc, 8)\n Tweekday = Theat - (u1 + u2)\n Tweekend = Tweekday\n\n if N24_16_m is None:\n return (5. / 7.) * Tweekday + (2. / 7.) * Tweekend\n else:\n WEm = numpy.array([9, 8, 9, 8, 9, 9, 9, 9, 8, 9, 8, 9])\n WDm = numpy.array([22, 20, 22, 22, 22, 21, 22, 22, 22, 22, 22, 22])\n return ((N24_16_m + N24_9_m) * Theat + (WEm - N24_16_m + N16_9_m) * Tweekend + (\n WDm - N16_9_m - N24_9_m) * Tweekday) / (WEm + WDm)\n\n\ndef temperature_reduction(delta_T, tc, time_off):\n return numpy.where(time_off <= tc,\n (0.5 * time_off ** 2 / 24) * delta_T / tc,\n delta_T * (time_off / 24. - (0.5 / 24.) * tc))\n\n\ndef temperature_no_heat(\n Texternal, Theat, responsiveness, heat_utilisation_factor,\n gains, h):\n return (1 - responsiveness) * (Theat - 2) + responsiveness * (Texternal + heat_utilisation_factor * gains / h)\n\n\ndef range_cooker_factor(dwelling):\n \"\"\"\n Check if the main, system1 or system2 heating has a\n range cooker scaling factor and return it. If not, return 1\n\n :param dwelling:\n :return: the range cooker scaling factor or 1\n \"\"\"\n if dwelling.get('range_cooker_heat_required_scale_factor'):\n return dwelling.range_cooker_heat_required_scale_factor\n\n elif dwelling.main_sys_1.get('range_cooker_heat_required_scale_factor'):\n return dwelling.main_sys_1.range_cooker_heat_required_scale_factor\n\n elif dwelling.get(\"main_sys_2\") and dwelling.main_sys_2.get('range_cooker_heat_required_scale_factor'):\n return dwelling.main_sys_2.range_cooker_heat_required_scale_factor\n else:\n return 1\n\n\ndef cooling_requirement(dwelling):\n \"\"\"\n Assign the cooling requirement to the dwelling.\n Note that this modifies the dwelling properties rather than\n returning values\n\n :param dwelling:\n :return:\n \"\"\"\n fcool = dwelling.fraction_cooled\n if fcool == 0:\n dwelling.Q_cooling_required = numpy.array([0., ] * 12)\n return\n\n Texternal_summer = dwelling.external_temperature_summer\n L = dwelling.h * (dwelling.Tcooling - Texternal_summer)\n G = dwelling.summer_heat_gains\n\n gamma = G / L\n assert not 1 in gamma # !!! Sort this out!\n\n tau = dwelling.thermal_mass_parameter / (3.6 * dwelling.hlp)\n a = 1 + tau / 15.\n utilisation = numpy.where(gamma <= 0,\n 1,\n (1 - gamma ** -a) / (1 - gamma ** -(a + 1)))\n\n Qrequired = numpy.array([0., ] * 12)\n Qrequired[5:8] = (0.024 * (G - utilisation * L) * DAYS_PER_MONTH)[5:8]\n\n # No cooling in months where heating would be more than half of cooling\n heat_calc_results = calc_heat_required(\n dwelling, Texternal_summer, G + dwelling.heating_system_pump_gain)\n Qheat_summer = heat_calc_results['heat_required']\n Qrequired = numpy.where(3 * Qheat_summer < Qrequired,\n Qrequired,\n 0)\n\n fintermittent = .25\n dwelling.Q_cooling_required = Qrequired * fcool * fintermittent\n\n\ndef heating_temperature_other_space(hlp, control_type):\n hlp = numpy.where(hlp < 6, hlp, 6)\n if control_type == 1:\n return 21. - 0.5 * hlp\n else:\n return 21. - hlp + 0.085 * hlp ** 2\n\n\ndef heat_utilisation_factor(a, heat_gains, heat_loss):\n gamma = heat_gains / heat_loss\n if 1 in gamma:\n # !!! Is this really right??\n raise Exception(\"Do we ever get here?\")\n return numpy.where(gamma != 1,\n (1 - gamma ** a) / (1 - gamma ** (a + 1)),\n a / (a + 1))\n else:\n return (1 - gamma ** a) / (1 - gamma ** (a + 1))\n\n\ndef systems(dwelling):\n dwelling.Q_main_1 = dwelling.fraction_of_heat_from_main * dwelling.main_heating_fraction * dwelling.Q_required\n\n dwelling.sys1_space_effy = dwelling.main_sys_1.space_heat_effy(dwelling.Q_main_1)\n\n dwelling.Q_spaceheat_main = 100 * dwelling.Q_main_1 / dwelling.sys1_space_effy\n\n if dwelling.get('main_sys_2'):\n dwelling.Q_main_2 = dwelling.fraction_of_heat_from_main * \\\n dwelling.main_heating_2_fraction * dwelling.Q_required\n\n dwelling.sys2_space_effy = dwelling.main_sys_2.space_heat_effy(dwelling.Q_main_2)\n\n dwelling.Q_spaceheat_main_2 = 100 * dwelling.Q_main_2 / dwelling.sys2_space_effy\n\n else:\n dwelling.Q_spaceheat_main_2 = numpy.zeros(12)\n dwelling.Q_main_2 = [0, ]\n\n if dwelling.fraction_of_heat_from_main < 1:\n Q_secondary = (1 - dwelling.fraction_of_heat_from_main) * dwelling.Q_required\n\n dwelling.secondary_space_effy = dwelling.secondary_sys.space_heat_effy(Q_secondary)\n dwelling.Q_spaceheat_secondary = 100 * Q_secondary / dwelling.secondary_space_effy\n\n else:\n dwelling.Q_spaceheat_secondary = numpy.zeros(12)\n\n dwelling.water_effy = dwelling.water_sys.water_heat_effy(dwelling.output_from_water_heater)\n\n if hasattr(dwelling.water_sys, \"keep_hot_elec_consumption\"):\n dwelling.Q_waterheat = 100 * (\n dwelling.output_from_water_heater - dwelling.combi_loss_monthly) / dwelling.water_effy\n else:\n dwelling.Q_waterheat = 100 * dwelling.output_from_water_heater / dwelling.water_effy\n\n dwelling.Q_spacecooling = dwelling.Q_cooling_required / dwelling.cooling_seer\n\n\ndef sap(dwelling):\n sap_rating_energy_cost = dwelling.fuel_cost\n ecf = 0.47 * sap_rating_energy_cost / (dwelling.GFA + 45)\n dwelling.sap_energy_cost_factor = ecf\n dwelling.sap_value = 117 - 121 * math.log10(ecf) if ecf >= 3.5 else 100 - 13.95 * ecf\n\n report = dwelling.report\n report.start_section(\"\", \"SAP Calculation\")\n report.add_single_result(\"SAP value\", \"258\", dwelling.sap_value)\n\n\ndef fee(dwelling):\n dwelling.fee_rating = (sum(dwelling.Q_required) + sum(dwelling.Q_cooling_required)) / dwelling.GFA\n\n r = dwelling.report\n r.start_section(\"\", \"FEE Calculation\")\n r.add_single_result(\n \"Fabric energy efficiency (kWh/m2)\", \"109\", dwelling.fee_rating)\n\n\ndef der(dwelling):\n dwelling.der_rating = dwelling.emissions / dwelling.GFA\n\n r = dwelling.report\n r.start_section(\"\", \"DER Calculation\")\n r.add_single_result(\n \"Dwelling emissions (kg/yr)\", \"272\", dwelling.emissions)\n r.add_single_result(\"DER rating (kg/m2/year)\", \"273\", dwelling.der_rating)\n\n\ndef ter(dwelling, heating_fuel):\n # Need to convert from 2010 emissions factors used in the calc to\n # 2006 factors\n C_h = ((dwelling.emissions_water +\n dwelling.emissions_heating_main) / dwelling.main_sys_1.fuel.emission_factor_adjustment +\n (dwelling.emissions_heating_secondary +\n dwelling.emissions_fans_and_pumps) / dwelling.electricity_tariff.emission_factor_adjustment)\n C_l = dwelling.emissions_lighting / \\\n dwelling.electricity_tariff.emission_factor_adjustment\n\n FF = heating_fuel.fuel_factor\n EFA_h = heating_fuel.emission_factor_adjustment\n EFA_l = dwelling.electricity_tariff.emission_factor_adjustment\n dwelling.ter_rating = (C_h * FF * EFA_h + C_l * EFA_l) * (\n 1 - 0.2) * (1 - 0.25) / dwelling.GFA\n\n r = dwelling.report\n r.start_section(\"\", \"TER Calculation\")\n r.add_single_result(\n \"Emissions per m2 for space and water heating\", \"272a\", C_h / dwelling.GFA)\n r.add_single_result(\n \"Emissions per m2 for lighting\", \"272b\", C_l / dwelling.GFA)\n r.add_single_result(\"Heating fuel factor\", None, FF)\n r.add_single_result(\"Heating fuel emission factor adjustment\", None, EFA_h)\n r.add_single_result(\"Electricity emission factor adjustment\", None, EFA_l)\n r.add_single_result(\"TER\", 273, dwelling.ter_rating)\n\n\ndef perform_demand_calc(dwelling):\n \"\"\"\n Calculate the SAP energy demand for a dwelling\n :param dwelling:\n :return:\n \"\"\"\n\n # todo: convert the rest of these to use \"update\" semantics\n ventilation(dwelling)\n\n dwelling.update(heat_loss(dwelling))\n\n dwelling.update(hot_water_use(dwelling))\n\n dwelling.update(lighting_consumption(dwelling))\n\n dwelling.update(internal_heat_gain(dwelling))\n\n solar(dwelling)\n heating_requirement(dwelling)\n cooling_requirement(dwelling)\n water_heater_output(dwelling)\n\n\ndef perform_full_calc(dwelling):\n \"\"\"\n Perform a full SAP worksheet calculation on a dwelling, adding the results\n to the dwelling provided.\n This performs a demand calculation, and a renewable energies calculation\n\n :param dwelling:\n :return:\n \"\"\"\n perform_demand_calc(dwelling)\n systems(dwelling)\n\n dwelling.update(appendix_m.pv(dwelling))\n dwelling.update(appendix_m.wind_turbines(dwelling))\n dwelling.update(appendix_m.hydro(dwelling))\n dwelling.update(appendix_c.chp(dwelling))\n\n fuel_use(dwelling)\n","sub_path":"epctk/worksheet.py","file_name":"worksheet.py","file_ext":"py","file_size_in_byte":19195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"172584437","text":"from custom_exceptions import *\n\nclass Car:\n \"\"\"A class used to represent the Car object\n\n This car object can be parked inside a ParkingLot. An attribute named\n `registration_no` is the unique property of the car.\n\n Attributes\n ----------\n colour : str\n Major colour of the car used for identification\n registration_no : str\n Unique code issued to the car by the government\n slot : str\n A spot in the parking lot\n\n Methods\n -------\n create_and_park(parking_lot, registration_no, colour)\n Creates a car object and parks it in the `parking_lot`\n park(parking_lot)\n Allocates a slot for the car in the parking lot (Do not use directly)\n \"\"\"\n\n colour = None\n registration_no = None\n slot = None\n\n def __init__(self, registration_no, colour):\n \"\"\"Default constructor\n\n Do not use directly. Instead call the `create_and_park()` method\n which initializes a new object and calls `park()` and also does\n exception handling.\n\n Parameters\n ----------\n registration_no : str\n Unique code issued to the car by the government\n color : str\n Major colour of the car used for identification\n\n Returns\n -------\n message : str\n status message to be echoed in STDOUT\n\n Raises\n -------\n CarInvalidInputs\n If invalid inputs like no registration number or no colour\n are specified.\n \"\"\"\n\n if registration_no is None or colour is None:\n raise CarInvalidInputs\n\n self.registration_no = registration_no\n self.colour = colour\n\n def park(self, parking_lot):\n \"\"\"Parks the car in the `parking_lot`\n\n Do not use this directly. Instead prefer `create_and_park()`.\n\n Parameters\n ----------\n parking_lot : ParkingLot\n The `ParkingLot` object to which we want to add our car\n\n Returns\n ----------\n message : str\n status message to be echoed in STDOUT\n\n Raises\n ----------\n ParkingLotUnitialized\n If there are issues in creating a new parking not or trying\n to access a non-existent parking lot.\n ParkingLotFull\n If there is no space left in the parking lot for an extra\n car.\n ParkingSlotEmpty\n If for some serious reason `vehicles` attribute of parking_lot\n doesn't exist.\n \"\"\"\n\n if len(parking_lot.vehicles) < 1:\n raise ParkingLotUninitialized('Please initialize parking lot')\n\n try:\n self.slot, message = parking_lot.add(self)\n except Exception as e:\n raise e\n\n return message\n\n @staticmethod\n def create_and_park(parking_lot, registration_no, colour):\n \"\"\"Create and park a car\n\n This the recommended way of creating a new car and parking it\n in the parking lot.\n\n Parameters\n ----------\n parking_lot : ParkingLot\n The `ParkingLot` object to which we want to add our car\n registration_no : str\n Unique code issued to the car by the government\n color : str\n Major colour of the car used for identification\n\n Returns\n ----------\n car : Car\n The newly created car which is parked\n message : str\n status message to be echoed in STDOUT\n\n Raises\n ----------\n ParkingLotUninitialized\n If you try to add a car to a non-existent parking lot.\n ParkingLotFull\n If no slots available to park the new car.\n \"\"\"\n\n if parking_lot is None or parking_lot.vehicles is None:\n raise ParkingLotUninitialized('Please initialize parking lot')\n\n car = Car(registration_no, colour)\n try:\n message = car.park(parking_lot)\n return car, message\n\n except ParkingLotFull as e:\n raise e\n\n except Exception as e:\n return None, e\n\n def __str__(self):\n \"\"\"Readable string for debugging\"\"\"\n\n return '{0}. {1} {2}'.format(self.slot, self.registration_no,\n self.colour)\n","sub_path":"src/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":4321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"630599352","text":"import grpc\nfrom xbos_services_getter.lib import building_zone_names_pb2\nfrom xbos_services_getter.lib import building_zone_names_pb2_grpc\nfrom xbos_services_getter.lib import hvac_consumption_pb2\nfrom xbos_services_getter.lib import hvac_consumption_pb2_grpc\nfrom xbos_services_getter.lib import indoor_data_historical_pb2\nfrom xbos_services_getter.lib import indoor_data_historical_pb2_grpc\nfrom xbos_services_getter.lib import indoor_temperature_prediction_pb2\nfrom xbos_services_getter.lib import indoor_temperature_prediction_pb2_grpc\nfrom xbos_services_getter.lib import meter_data_historical_pb2\nfrom xbos_services_getter.lib import meter_data_historical_pb2_grpc\nfrom xbos_services_getter.lib import occupancy_pb2\nfrom xbos_services_getter.lib import occupancy_pb2_grpc\nfrom xbos_services_getter.lib import optimizer_pb2\nfrom xbos_services_getter.lib import optimizer_pb2_grpc\nfrom xbos_services_getter.lib import outdoor_temperature_historical_pb2\nfrom xbos_services_getter.lib import outdoor_temperature_historical_pb2_grpc\nfrom xbos_services_getter.lib import outdoor_temperature_prediction_pb2\nfrom xbos_services_getter.lib import outdoor_temperature_prediction_pb2_grpc\nfrom xbos_services_getter.lib import price_pb2\nfrom xbos_services_getter.lib import price_pb2_grpc\nfrom xbos_services_getter.lib import temperature_bands_pb2\nfrom xbos_services_getter.lib import temperature_bands_pb2_grpc\nfrom xbos_services_getter.lib import baseline_optimizer_pb2\nfrom xbos_services_getter.lib import baseline_optimizer_pb2_grpc\n\nimport datetime\nimport pytz\nimport pandas as pd\n\nimport os\n\n'''\nUtility constants\n'''\nNO_ACTION = 0\nHEATING_ACTION = 1\nCOOLING_ACTION = 2\nFAN = 3\nTWO_STAGE_HEATING_ACTION = 4\nTWO_STAGE_COOLING_ACTION = 5\n\ndef get_window_in_sec(s):\n \"\"\"Returns number of seconds in a given duration or zero if it fails.\n Supported durations are seconds (s), minutes (m), hours (h), and days(d).\"\"\"\n seconds_per_unit = {\"s\": 1, \"m\": 60, \"h\": 3600, \"d\": 86400}\n try:\n return int(float(s[:-1])) * seconds_per_unit[s[-1]]\n except:\n return 0\n\n\n# Building and Zone names\ndef get_building_zone_names_stub(BUILDING_ZONE_NAMES_HOST_ADDRESS=None,secure=True):\n \"\"\"Get the stub to interact with the building_zone_address service.\n\n :param BUILDING_ZONE_NAMES_HOST_ADDRESS: Optional argument to supply host address for given service. Otherwise,\n set as environment variable.\n :return: grpc Stub object.\n\n \"\"\"\n\n if BUILDING_ZONE_NAMES_HOST_ADDRESS is None:\n BUILDING_ZONE_NAMES_HOST_ADDRESS = os.environ[\"BUILDING_ZONE_NAMES_HOST_ADDRESS\"]\n\n if not secure:\n channel = grpc.insecure_channel(BUILDING_ZONE_NAMES_HOST_ADDRESS)\n else:\n credentials = grpc.ssl_channel_credentials()\n channel = grpc.secure_channel(BUILDING_ZONE_NAMES_HOST_ADDRESS, credentials)\n return building_zone_names_pb2_grpc.BuildingZoneNamesStub(channel)\n\n\n\ndef get_buildings(building_zone_names_stub):\n \"\"\"Gets all the building names supported by the services.\n\n :param building_zone_names_stub: grpc stub for building_zone_names service.\n :return: list (string) building names.\n\n \"\"\"\n\n building_names = building_zone_names_stub.GetBuildings(building_zone_names_pb2.BuildingRequest())\n return [bldg.name for bldg in building_names.names]\n\n\ndef get_zones(building_zone_names_stub, building):\n \"\"\"Gets all zone names for the given building which are supported by the services.\n\n :param building_zone_names_stub: grpc stub for building_zone_names service.\n :param building: (string) building name. Needs to be in the list returned by get_buildings.\n :return: list (string) zone names.\n\n \"\"\"\n zones = building_zone_names_stub.GetZones(building_zone_names_pb2.ZoneRequest(building=building))\n return [zone.name for zone in zones.names]\n\n\ndef get_all_buildings_zones(building_zone_names_stub):\n \"\"\"Gets all building and corresponding zones in a dictionary.\n\n :param building_zone_names_stub: grpc stub for building_zone_names service.\n :return: dictionary > (strings)\n\n \"\"\"\n buildings = get_buildings(building_zone_names_stub)\n zones = {}\n\n for bldg in buildings:\n zones[bldg] = get_zones(building_zone_names_stub, bldg)\n\n return zones\n\n\n# Temperature band functions\ndef get_temperature_band_stub(TEMPERATURE_BANDS_HOST_ADDRESS=None,secure=True):\n \"\"\"Get the stub to interact with the temperature_band service.\n\n :param TEMPERATURE_BANDS_HOST_ADDRESS: Optional argument to supply host address for given service. Otherwise,\n set as environment variable.\n :return: grpc Stub object.\n\n \"\"\"\n\n if TEMPERATURE_BANDS_HOST_ADDRESS is None:\n TEMPERATURE_BANDS_HOST_ADDRESS = os.environ[\"TEMPERATURE_BANDS_HOST_ADDRESS\"]\n if not secure:\n channel = grpc.insecure_channel(TEMPERATURE_BANDS_HOST_ADDRESS)\n else:\n credentials = grpc.ssl_channel_credentials()\n channel = grpc.secure_channel(TEMPERATURE_BANDS_HOST_ADDRESS, credentials)\n return temperature_bands_pb2_grpc.SchedulesStub(channel)\n\n\ndef get_comfortband(temperature_band_stub, building, zone, start, end, window):\n \"\"\"Gets comfortband as pd.df.\n\n :param temperature_band_stub: grpc stub for temperature_band microservice\n :param building: (str) building name\n :param zone: (str) zone name\n :param start: (datetime timezone aware) start of comfortband\n :param end: (datetime timezone aware) end of comfortband\n :param window: (str) the interval in which to split the comfortband.\n :return: pd.df columns=[\"t_low\", \"t_high\"], valus=float, index=time\n\n \"\"\"\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = start.timestamp() * 1e9\n end_unix = end.timestamp() * 1e9\n window_seconds = get_window_in_sec(window)\n\n # call service\n comfortband_response = temperature_band_stub.GetComfortband(\n temperature_bands_pb2.ScheduleRequest(building=building, zone=zone, start=int(start_unix), end=int(end_unix), window=window,\n unit=\"F\"))\n\n # process data\n comfortband_list = []\n for msg in comfortband_response:\n item = {\n \"datetime\" : datetime.datetime.utcfromtimestamp(msg.time / 1e9).replace(tzinfo=pytz.utc).astimezone(tz=start.tzinfo),\n \"t_high\" : msg.temperature_high,\n \"t_low\" : msg.temperature_low,\n \"unit\" : msg.unit\n }\n comfortband_list.append(item)\n df = pd.DataFrame(comfortband_list)\n df.set_index(\"datetime\",inplace=True)\n return df\n\n\ndef get_do_not_exceed(temperature_band_stub, building, zone, start, end, window):\n \"\"\"Gets do_not_exceed as pd.df.\n\n :param temperature_band_stub: grpc stub for temperature_band microservice\n :param building: (str) building name\n :param zone: (str) zone name\n :param start: (datetime timezone aware) start of do_not_exceed\n :param end: (datetime timezone aware) end of do_not_exceed\n :param window: (str) the interval in which to split the do_not_exceed.\n :return: pd.df columns=[\"t_low\", \"t_high\"], valus=float, index=time\n\n \"\"\"\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = start.timestamp() * 1e9\n end_unix = end.timestamp() * 1e9\n window_seconds = get_window_in_sec(window)\n\n # call service\n do_not_exceed_response = temperature_band_stub.GetDoNotExceed(\n temperature_bands_pb2.ScheduleRequest(building=building, zone=zone, start=int(start_unix), end=int(end_unix), window=window,\n unit=\"F\"))\n\n # process data\n do_not_exceed_list = []\n for msg in do_not_exceed_response:\n item = {\n \"datetime\" : datetime.datetime.utcfromtimestamp(msg.time / 1e9).replace(tzinfo=pytz.utc).astimezone(tz=start.tzinfo),\n \"t_high\" : msg.temperature_high,\n \"t_low\" : msg.temperature_low,\n \"unit\" : msg.unit\n }\n do_not_exceed_list.append(item)\n df = pd.DataFrame(do_not_exceed_list)\n df.set_index(\"datetime\",inplace=True)\n return df\n\n\n# occupancy functions\ndef get_occupancy_stub(OCCUPANCY_HOST_ADDRESS=None,secure=True):\n \"\"\"Get the stub to interact with the occupancy service.\n\n :param OCCUPANCY_HOST_ADDRESS: Optional argument to supply host address for given service. Otherwise,\n set as environment variable.\n :return: grpc Stub object.\n\n \"\"\"\n if OCCUPANCY_HOST_ADDRESS is None:\n OCCUPANCY_HOST_ADDRESS = os.environ[\"OCCUPANCY_HOST_ADDRESS\"]\n\n if not secure:\n channel = grpc.insecure_channel(OCCUPANCY_HOST_ADDRESS)\n else:\n credentials = grpc.ssl_channel_credentials()\n channel = grpc.secure_channel(OCCUPANCY_HOST_ADDRESS, credentials)\n return occupancy_pb2_grpc.OccupancyStub(channel)\n\n\ndef get_occupancy(occupancy_stub, building, zone, start, end, window):\n \"\"\"Gets occupancy as pd.series.\n\n :param occupancy_stub: grpc stub for occupancy microservice\n :param building: (str) building name\n :param zone: (str) zone name\n :param start: (datetime timezone aware)\n :param end: (datetime timezone aware)\n :param window: (str) the interval in which to split the data.\n :return: pd.series valus=float, index=time\n\n \"\"\"\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = start.timestamp() * 1e9\n end_unix = end.timestamp() * 1e9\n window_seconds = get_window_in_sec(window)\n\n # call service\n occupancy_response = occupancy_stub.GetOccupancy(\n occupancy_pb2.Request(building=building, zone=zone, start=int(start_unix), end=int(end_unix), window=window))\n\n # process data\n occupancy_list = []\n for msg in occupancy_response:\n item = {\n \"datetime\" : datetime.datetime.utcfromtimestamp(msg.time / 1e9).replace(tzinfo=pytz.utc).astimezone(tz=start.tzinfo),\n \"occupancy\" : msg.occupancy\n }\n occupancy_list.append(item)\n df = pd.DataFrame(occupancy_list)\n df.set_index(\"datetime\",inplace=True)\n return df\n\n\n# price functions\ndef get_price_stub(PRICE_HOST_ADDRESS=None,secure=True):\n \"\"\"Get the stub to interact with the price service.\n\n :param PRICEPRICE_HOST_ADDRESS: Optional argument to supply host address for given service. Otherwise,\n set as environment variable.\n :return: grpc Stub object.\n\n \"\"\"\n if PRICE_HOST_ADDRESS is None:\n PRICE_HOST_ADDRESS = os.environ[\"PRICE_HOST_ADDRESS\"]\n\n if not secure:\n channel = grpc.insecure_channel(PRICE_HOST_ADDRESS)\n else:\n credentials = grpc.ssl_channel_credentials()\n channel = grpc.secure_channel(PRICE_HOST_ADDRESS, credentials)\n return price_pb2_grpc.PriceStub(channel)\n\ndef get_all_tariffs(price_stub):\n \"\"\"Gets all available tariffs and utilities as a list of dictionaries.\n\n :param price_stub: grpc stub for price microservice\n :return: list of (dictionary) keys=[\"tariff\", \"utility\"]\n\n \"\"\"\n all_tariffs_utilities = price_stub.GetAllTariffsAndUtilities(price_pb2.Empty()).tariffs_utilities\n all_tariffs_utilities_list = []\n for tariff_and_utility in all_tariffs_utilities:\n all_tariffs_utilities_list.append({\"tariff\": tariff_and_utility.tariff, \"utility\": tariff_and_utility.utility})\n return all_tariffs_utilities_list\n\ndef get_tariff_and_utility(price_stub, building):\n \"\"\"Gets the tariff and utility for the given building as a dictionary.\n\n :param price_stub: grpc stub for price microservice\n :param building: (str) building name\n :return: (dictionary) keys=[\"tariff\", \"utility\"]\n \"\"\"\n tariff_and_utility = price_stub.GetTariffAndUtility(price_pb2.BuildingRequest(building=building))\n return {\"tariff\": tariff_and_utility.tariff, \"utility\": tariff_and_utility.utility}\n\n\ndef get_price_utility_tariff(price_stub,utility,tariff,price_type, start, end, window):\n \"\"\"Gets the price as a pandas dataframe.\n\n :param price_stub: grpc stub for price microservice\n :param building: (str) building name\n :param price_type: (str) \"ENERGY\" or \"DEMAND\"\n :param start: (datetime timezone aware)\n :param end: (datetime timezone aware)\n :param window: (str) the interval in which to split the data.\n :return: pd.DataFrame columns=[\"price\" (float), \"unit\" string] index=start to end with window intervals.\n \"\"\"\n if price_type not in [\"ENERGY\", \"DEMAND\"]:\n raise AttributeError(\"Given price type is invalid. Use ENERGY or DEMAND.\")\n\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = int(start.timestamp() * 1e9)\n end_unix = int(end.timestamp() * 1e9)\n window_seconds = get_window_in_sec(window)\n\n # call service\n price_response = price_stub.GetPrice(price_pb2.PriceRequest(utility=utility,\n tariff=tariff,\n price_type=price_type,\n start=start_unix,\n end=end_unix,\n window=window))\n # process data\n utility_tariff_list = []\n for msg in price_response:\n item = {\n \"datetime\" : datetime.datetime.utcfromtimestamp(msg.time / 1e9).replace(tzinfo=pytz.utc).astimezone(tz=start.tzinfo),\n \"price\" : msg.price,\n \"unit\" : msg.unit,\n \"window\" : msg.window\n }\n utility_tariff_list.append(item)\n df = pd.DataFrame(utility_tariff_list)\n df.set_index(\"datetime\",inplace=True)\n return df\n\ndef get_price(price_stub, building, price_type, start, end, window):\n \"\"\"Gets the price as a pandas dataframe.\n\n :param price_stub: grpc stub for price microservice\n :param building: (str) building name\n :param price_type: (str) \"ENERGY\" or \"DEMAND\"\n :param start: (datetime timezone aware)\n :param end: (datetime timezone aware)\n :param window: (str) the interval in which to split the data.\n :return: pd.DataFrame columns=[\"price\", \"unit\"], types=[float, string] index=start to end with window intervals.\n \"\"\"\n\n # call service\n tariff_and_utility = get_tariff_and_utility(price_stub, building)\n return get_price_utility_tariff(price_stub,tariff_and_utility[\"utility\"],tariff_and_utility[\"tariff\"],price_type, start, end, window)\n\n\ndef get_demand_response_forecast_utility(price_stub, utility,timezone=pytz.timezone('US/Pacific')):\n if utility.upper() not in [\"PGE\", \"SCE\"]:\n raise AttributeError(\"Given utility type is invalid. Use PGE or SCE.\")\n # call service\n demand_response = price_stub.GetDemandResponseForecast(price_pb2.DemandResponseRequest(utility=utility)).statuses\n # process data\n utility_tariff_list = []\n for msg in demand_response:\n item = {\n \"datetime\" : datetime.datetime.utcfromtimestamp(msg.time / 1e9).replace(tzinfo=pytz.utc).astimezone(tz=timezone),\n \"status\" : msg.status\n }\n utility_tariff_list.append(item)\n df = pd.DataFrame(utility_tariff_list)\n if len(utility_tariff_list)!= 0:\n df.set_index(\"datetime\",inplace=True)\n return df\n\n\ndef get_demand_response_confirmed_utility(price_stub, utility,timezone=pytz.timezone('US/Pacific')):\n if utility.upper() not in [\"PGE\", \"SCE\"]:\n raise AttributeError(\"Given utility type is invalid. Use PGE or SCE.\")\n # call service\n demand_response = price_stub.GetDemandResponseConfirmed(price_pb2.DemandResponseRequest(utility=utility)).statuses\n # process data\n utility_tariff_list = []\n for msg in demand_response:\n item = {\n \"datetime\" : datetime.datetime.utcfromtimestamp(msg.time / 1e9).replace(tzinfo=pytz.utc).astimezone(tz=timezone),\n \"status\" : msg.status\n }\n utility_tariff_list.append(item)\n\n df = pd.DataFrame(utility_tariff_list)\n if len(utility_tariff_list)!= 0:\n df.set_index(\"datetime\",inplace=True)\n return df\n\ndef get_demand_response_forecast(price_stub, building,timezone=pytz.timezone('US/Pacific')):\n tariff_and_utility = get_tariff_and_utility(price_stub, building)\n return get_demand_response_forecast_utility(price_stub,tariff_and_utility[\"utility\"])\n\ndef get_demand_response_confirmed(price_stub, building,timezone=pytz.timezone('US/Pacific')):\n tariff_and_utility = get_tariff_and_utility(price_stub, building)\n return get_demand_response_confirmed_utility(price_stub,tariff_and_utility[\"utility\"])\n\n# indoor historic functions\ndef get_indoor_historic_stub(INDOOR_DATA_HISTORICAL_HOST_ADDRESS=None,secure=True):\n \"\"\"Get the stub to interact with the indoor_data_historical service.\n\n :param INDOOR_DATA_HISTORICAL_HOST_ADDRESS: Optional argument to supply host address for given service. Otherwise,\n set as environment variable.\n :return: grpc Stub object.\n\n \"\"\"\n\n if INDOOR_DATA_HISTORICAL_HOST_ADDRESS is None:\n INDOOR_DATA_HISTORICAL_HOST_ADDRESS = os.environ[\"INDOOR_DATA_HISTORICAL_HOST_ADDRESS\"]\n\n if not secure:\n channel = grpc.insecure_channel(INDOOR_DATA_HISTORICAL_HOST_ADDRESS)\n else:\n credentials = grpc.ssl_channel_credentials()\n channel = grpc.secure_channel(INDOOR_DATA_HISTORICAL_HOST_ADDRESS, credentials)\n return indoor_data_historical_pb2_grpc.IndoorDataHistoricalStub(channel)\n\n\ndef get_indoor_temperature_historic(indoor_historic_stub, building, zone, start, end, window, agg=\"MEAN\"):\n \"\"\"Gets historic indoor temperature as pd.series.\n\n :param indoor_historic_stub: grpc stub for historic indoor temperature microservice\n :param building: (str) building name\n :param zone: (str) zone name\n :param start: (datetime timezone aware)\n :param end: (datetime timezone aware)\n :param window: (str) the interval in which to split the data.\n :return: pd.df columns=[\"temperature\", \"unit\"] values=[float, string], index=time\n\n \"\"\"\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = int(start.timestamp() * 1e9)\n end_unix = int(end.timestamp() * 1e9)\n window_seconds = get_window_in_sec(window)\n\n # call service\n historic_temperature_response = indoor_historic_stub.GetRawTemperatures(\n indoor_data_historical_pb2.Request(building=building, zone=zone, start=start_unix, end=end_unix,\n window=window,aggregation=agg))\n\n # process data\n temperature_list = []\n for msg in historic_temperature_response:\n item = {\n \"datetime\" : datetime.datetime.utcfromtimestamp(msg.time / 1e9).replace(tzinfo=pytz.utc).astimezone(tz=start.tzinfo),\n \"temperature\" : msg.temperature,\n \"unit\" : msg.unit\n }\n temperature_list.append(item)\n\n df = pd.DataFrame(temperature_list)\n df.set_index(\"datetime\",inplace=True)\n return df\n\ndef get_indoor_actions_historic(indoor_historic_stub, building, zone, start, end, window, agg=\"MAX\"):\n \"\"\"Gets historic indoor temperature as pd.series.\n\n :param indoor_historic_stub: grpc stub for historic indoor temperature microservice\n :param building: (str) building name\n :param zone: (str) zone name\n :param start: (datetime timezone aware)\n :param end: (datetime timezone aware)\n :param window: (str) the interval in which to split the data.\n :return: pd.df columns[\"action\"], types=[\"float\"], index=time\n\n \"\"\"\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = int(start.timestamp() * 1e9)\n end_unix = int(end.timestamp() * 1e9)\n window_seconds = get_window_in_sec(window)\n\n # call service\n historic_action_response = indoor_historic_stub.GetRawActions(\n indoor_data_historical_pb2.Request(building=building, zone=zone, start=start_unix, end=end_unix,\n window=window,aggregation=agg))\n\n # process data\n action_list = []\n for msg in historic_action_response:\n item = {\n \"datetime\" : datetime.datetime.utcfromtimestamp(msg.time / 1e9).replace(tzinfo=pytz.utc).astimezone(tz=start.tzinfo),\n \"action\" : msg.action\n }\n action_list.append(item)\n df = pd.DataFrame(action_list)\n df.set_index(\"datetime\",inplace=True)\n return df\n\ndef get_indoor_modes_historic(indoor_historic_stub, building, zone, start, end, window, agg=\"MAX\"):\n \"\"\"Gets historic indoor temperature as pd.series.\n\n :param indoor_historic_stub: grpc stub for historic indoor temperature microservice\n :param building: (str) building name\n :param zone: (str) zone name\n :param start: (datetime timezone aware)\n :param end: (datetime timezone aware)\n :param window: (str) the interval in which to split the data.\n :return: pd.df columns[\"mode\"], types=[\"float\"], index=time\n\n \"\"\"\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = int(start.timestamp() * 1e9)\n end_unix = int(end.timestamp() * 1e9)\n window_seconds = get_window_in_sec(window)\n\n # call service\n historic_mode_response = indoor_historic_stub.GetRawModes(\n indoor_data_historical_pb2.Request(building=building, zone=zone, start=start_unix, end=end_unix,\n window=window,aggregation=agg))\n\n # process data\n mode_list = []\n for msg in historic_mode_response:\n item = {\n \"datetime\" : datetime.datetime.utcfromtimestamp(msg.time / 1e9).replace(tzinfo=pytz.utc).astimezone(tz=start.tzinfo),\n \"mode\" : msg.mode\n }\n mode_list.append(item)\n df = pd.DataFrame(mode_list)\n df.set_index(\"datetime\",inplace=True)\n return df\n\n\ndef get_indoor_setpoints_historic(indoor_historic_stub, building, zone, start, end, window,agg=\"MIN\"):\n \"\"\"Gets historic setpoints temperature as pd.df.\n\n :param indoor_historic_stub: grpc stub for historic indoor temperature microservice\n :param building: (str) building name\n :param zone: (str) zone name\n :param start: (datetime timezone aware)\n :param end: (datetime timezone aware)\n :param window: (str) the interval in which to split the data.\n :return: pd.df columns=[\"t_low\", \"t_high\"] valus=float, index=time\n\n \"\"\"\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = int(start.timestamp() * 1e9)\n end_unix = int(end.timestamp() * 1e9)\n window_seconds = get_window_in_sec(window)\n\n # call service\n historic_setpoints_response = indoor_historic_stub.GetRawTemperatureBands(\n indoor_data_historical_pb2.Request(building=building, zone=zone, start=start_unix, end=end_unix,\n window=window,aggregation=agg))\n\n # process data\n setpoints_list = []\n for msg in historic_setpoints_response:\n item = {\n \"datetime\" : datetime.datetime.utcfromtimestamp(msg.time / 1e9).replace(tzinfo=pytz.utc).astimezone(tz=start.tzinfo),\n \"t_high\" : msg.temperature_high,\n \"t_low\" : msg.temperature_low,\n \"unit\" : msg.unit\n }\n setpoints_list.append(item)\n df = pd.DataFrame(setpoints_list)\n df.set_index(\"datetime\",inplace=True)\n return df\n\n# indoor prediction functions\ndef get_indoor_temperature_prediction_stub(INDOOR_TEMPERATURE_PREDICTION_HOST_ADDRESS=None,secure=True):\n \"\"\"Get the stub to interact with the indoor_temperature_prediction service.\n\n :param INDOOR_TEMPERATURE_PREDICTION_HOST_ADDRESS: Optional argument to supply host address for given service. Otherwise,\n set as environment variable.\n :return: grpc Stub object.\n\n \"\"\"\n\n if INDOOR_TEMPERATURE_PREDICTION_HOST_ADDRESS is None:\n INDOOR_TEMPERATURE_PREDICTION_HOST_ADDRESS = os.environ[\"INDOOR_TEMPERATURE_PREDICTION_HOST_ADDRESS\"]\n\n if not secure:\n channel = grpc.insecure_channel(INDOOR_TEMPERATURE_PREDICTION_HOST_ADDRESS)\n else:\n credentials = grpc.ssl_channel_credentials()\n channel = grpc.secure_channel(INDOOR_TEMPERATURE_PREDICTION_HOST_ADDRESS, credentials)\n return indoor_temperature_prediction_pb2_grpc.IndoorTemperaturePredictionStub(channel)\n\n\ndef get_indoor_temperature_prediction(indoor_temperature_prediction_stub, building, zone, current_time, action, t_in, t_out, t_prev,\n other_zone_temperatures):\n \"\"\"Gets prediction of indoor temperature.\n\n :param indoor_temperature_prediction_stub: grpc stub for prediction of indoor temperature microservice\n :param building: (str) building name\n :param zone: (str) zone name\n :param current_time: (datetime timezone aware)\n :param action: (int) Action as given in utils file.\n :param t_in: (float) current temperature inside of zone.\n :param t_out: (float) currrent outdoor temperature.\n :param t_prev: (float) the temperature 5 min ago.\n :param other_zone_temperatures: {zone_i: indoor temperature of zone_i}\n :return: (float) temperature in 5 minutes after current_time in Fahrenheit.\n\n \"\"\"\n current_time = current_time.replace(microsecond=0)\n\n current_time_unix = int(current_time.timestamp() * 1e9)\n\n # call service\n indoor_prediction_response = indoor_temperature_prediction_stub.GetSecondOrderPrediction(\n indoor_temperature_prediction_pb2.SecondOrderPredictionRequest(building=building, zone=zone, current_time=current_time_unix,\n action=action,\n indoor_temperature=t_in, previous_indoor_temperature=t_prev,\n outside_temperature=t_out,\n other_zone_temperatures=other_zone_temperatures,\n temperature_unit=\"F\"))\n\n return indoor_prediction_response.temperature,datetime.datetime.utcfromtimestamp(indoor_prediction_response.time / 1e9).replace(tzinfo=pytz.utc).astimezone(tz=current_time.tzinfo),indoor_prediction_response.unit\n\ndef get_indoor_temperature_prediction_error(indoor_temperature_prediction_stub, building, zone, action, start=None, end=None,\n temperature_unit=\"F\"):\n \"\"\"Gets mean and var of the error of indoor temperature predictions.\n\n :param indoor_temperature_prediction_stub: grpc stub for prediction of indoor temperature microservice\n :param building: (str) building name\n :param zone: (str) zone name\n :param action: (int) Action as given in utils file. Specifies for which action to get the error. -1 gets the error\n on the whole dataset, regardless of action.\n :param start: (datetime timezone aware). If None, get the training error.\n :param end: (datetime timezone aware). If None, get the training error.\n :param temperature_unit: temperature unit\n :return: mean error (float), varirance of error (float), unit of the error (string).\n \"\"\"\n if (start is None) or (end is None):\n end = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)\n start = end - datetime.timedelta(hours=24)\n\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = int(start.timestamp() * 1e9)\n end_unix = int(end.timestamp() * 1e9)\n\n # call service\n error_response = indoor_temperature_prediction_stub.GetSecondOrderError(\n indoor_temperature_prediction_pb2.ErrorRequest(building=building, zone=zone, action=action,\n start=start_unix,\n end=end_unix,\n unit=temperature_unit))\n\n return error_response.mean, error_response.var, error_response.unit\n\n# HVAC Consumption functions\ndef get_hvac_consumption_stub(HVAC_CONSUMPTION_HOST_ADDRESS=None,secure=True):\n \"\"\"Get the stub to interact with the hvac_consumption service.\n\n :param HVAC_CONSUMPTION_HOST_ADDRESS: Optional argument to supply host address for given service. Otherwise,\n set as environment variable.\n :return: grpc Stub object.\n\n \"\"\"\n\n if HVAC_CONSUMPTION_HOST_ADDRESS is None:\n HVAC_CONSUMPTION_HOST_ADDRESS = os.environ[\"HVAC_CONSUMPTION_HOST_ADDRESS\"]\n\n if not secure:\n channel = grpc.insecure_channel(HVAC_CONSUMPTION_HOST_ADDRESS)\n else:\n credentials = grpc.ssl_channel_credentials()\n channel = grpc.secure_channel(HVAC_CONSUMPTION_HOST_ADDRESS, credentials)\n return hvac_consumption_pb2_grpc.ConsumptionHVACStub(channel)\n\n\ndef get_hvac_consumption(hvac_consumption_stub, building, zone):\n hvac_consumption_response = hvac_consumption_stub.GetConsumption(\n hvac_consumption_pb2.Request(building=building, zone=zone))\n\n hvac_consumption_final = {NO_ACTION: 0,\n HEATING_ACTION: hvac_consumption_response.heating_consumption,\n COOLING_ACTION: hvac_consumption_response.cooling_consumption,\n FAN: hvac_consumption_response.ventilation_consumption,\n TWO_STAGE_HEATING_ACTION: hvac_consumption_response.heating_consumption_stage_two,\n TWO_STAGE_COOLING_ACTION: hvac_consumption_response.cooling_consumption_stage_two,\n \"UNIT\": hvac_consumption_response.unit}\n\n return hvac_consumption_final\n\n\n# Historic outdoor temperature functions\ndef get_outdoor_temperature_historic_stub(OUTDOOR_TEMPERATURE_HISTORICAL_HOST_ADDRESS=None,secure=True):\n \"\"\"Get the stub to interact with the outdoor_temperature_historical service.\n\n :param OUTDOOR_TEMPERATURE_HISTORICAL_HOST_ADDRESS: Optional argument to supply host address for given service.\n Otherwise, set as environment variable.\n :return: grpc Stub object.\n\n \"\"\"\n\n if OUTDOOR_TEMPERATURE_HISTORICAL_HOST_ADDRESS is None:\n OUTDOOR_TEMPERATURE_HISTORICAL_HOST_ADDRESS = os.environ[\"OUTDOOR_TEMPERATURE_HISTORICAL_HOST_ADDRESS\"]\n\n if not secure:\n channel = grpc.insecure_channel(OUTDOOR_TEMPERATURE_HISTORICAL_HOST_ADDRESS)\n else:\n credentials = grpc.ssl_channel_credentials()\n channel = grpc.secure_channel(OUTDOOR_TEMPERATURE_HISTORICAL_HOST_ADDRESS, credentials)\n return outdoor_temperature_historical_pb2_grpc.OutdoorTemperatureStub(channel)\n\n\ndef get_raw_outdoor_temperature_historic(outdoor_historic_stub, building, start, end, window, aggregate=\"MEAN\"):\n \"\"\"Gets historic outdoor temperature as pd.series.\n\n :param indoor_historic_stub: grpc stub for historic outdoor temperature microservice\n :param building: (str) building name\n :param zone: (str) zone name\n :param start: (datetime timezone aware)\n :param end: (datetime timezone aware)\n :param window: (str) the interval in which to split the data.\n :return: pd.series valus=float, index=time\n\n \"\"\"\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = int(start.timestamp() * 1e9)\n end_unix = int(end.timestamp() * 1e9)\n window_seconds = get_window_in_sec(window)\n\n # call service\n historic_outdoor_response = outdoor_historic_stub.GetRawTemperature(\n outdoor_temperature_historical_pb2.TemperatureRequest(\n building=building, start=int(start_unix), end=int(end_unix), window=window, aggregate=aggregate))\n\n # process data\n temperature_list = []\n for msg in historic_outdoor_response:\n item = {\n \"datetime\" : datetime.datetime.utcfromtimestamp(msg.time / 1e9).replace(tzinfo=pytz.utc).astimezone(tz=start.tzinfo),\n \"temperature\" : msg.temperature,\n \"unit\" : msg.unit\n }\n temperature_list.append(item)\n df = pd.DataFrame(temperature_list)\n df.set_index(\"datetime\",inplace=True)\n return df\n\ndef get_preprocessed_outdoor_temperature(outdoor_historic_stub, building, start, end, window):\n \"\"\"Gets historic outdoor temperature as pd.series.\n\n :param indoor_historic_stub: grpc stub for historic outdoor temperature microservice\n :param building: (str) building name\n :param zone: (str) zone name\n :param start: (datetime timezone aware)\n :param end: (datetime timezone aware)\n :param window: (str) the interval in which to split the data.\n :return: pd.series valus=float, index=time\n\n \"\"\"\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = int(start.timestamp() * 1e9)\n end_unix = int(end.timestamp() * 1e9)\n window_seconds = get_window_in_sec(window)\n\n # call service\n historic_outdoor_response = outdoor_historic_stub.GetPreprocessedTemperature(\n outdoor_temperature_historical_pb2.TemperatureRequest(\n building=building, start=int(start_unix), end=int(end_unix), window=window))\n\n # process data\n temperature_list = []\n for msg in historic_outdoor_response:\n item = {\n \"datetime\" : datetime.datetime.utcfromtimestamp(msg.time / 1e9).replace(tzinfo=pytz.utc).astimezone(tz=start.tzinfo),\n \"temperature\" : msg.temperature,\n \"unit\" : msg.unit\n }\n temperature_list.append(item)\n df = pd.DataFrame(temperature_list)\n df.set_index(\"datetime\",inplace=True)\n return df\n\n# Outdoor temperature prediction functions\ndef get_outdoor_temperature_prediction_stub(OUTDOOR_TEMPERATURE_PREDICTION_HOST_ADDRESS=None,secure=True):\n \"\"\"Get the stub to interact with the outdoor_temperature_prediction service.\n\n :param OUTDOOR_TEMPERATURE_PREDICTION_HOST_ADDRESS: Optional argument to supply host address for given service.\n Otherwise, set as environment variable.\n :return: grpc Stub object.\n\n \"\"\"\n\n if OUTDOOR_TEMPERATURE_PREDICTION_HOST_ADDRESS is None:\n OUTDOOR_TEMPERATURE_PREDICTION_HOST_ADDRESS = os.environ[\"OUTDOOR_TEMPERATURE_PREDICTION_HOST_ADDRESS\"]\n\n if not secure:\n channel = grpc.insecure_channel(OUTDOOR_TEMPERATURE_PREDICTION_HOST_ADDRESS)\n else:\n credentials = grpc.ssl_channel_credentials()\n channel = grpc.secure_channel(OUTDOOR_TEMPERATURE_PREDICTION_HOST_ADDRESS, credentials)\n return outdoor_temperature_prediction_pb2_grpc.OutdoorTemperatureStub(channel)\n\n\ndef get_outdoor_temperature_prediction(outdoor_prediction_stub, building, start, end, window):\n \"\"\"Gets prediction outdoor temperature as pd.series.\n\n :param outdoor_prediction_stub: grpc stub for outdoor temperature prediction microservice\n :param building: (str) building name\n :param zone: (str) zone name\n :param start: (datetime timezone aware)\n :param end: (datetime timezone aware)\n :param window: (str) the interval in which to split the data.\n :return: pd.series valus=float, index=time\n\n \"\"\"\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = int(start.timestamp() * 1e9)\n end_unix = int(end.timestamp() * 1e9)\n window_seconds = get_window_in_sec(window)\n\n # call service\n prediction_outdoor_response = outdoor_prediction_stub.GetTemperature(\n outdoor_temperature_prediction_pb2.TemperatureRequest(\n building=building, start=int(start_unix), end=int(end_unix), window=window))\n\n # process data\n prediction_list = []\n for msg in prediction_outdoor_response.temperatures:\n item = {\n \"datetime\" : datetime.datetime.utcfromtimestamp(msg.time / 1e9).replace(tzinfo=pytz.utc).astimezone(tz=start.tzinfo),\n \"temperature\" : msg.temperature,\n \"unit\" : msg.unit\n }\n prediction_list.append(item)\n df = pd.DataFrame(prediction_list)\n df.set_index(\"datetime\",inplace=True)\n return df\n\ndef get_meter_data_historical_stub(METER_DATA_HISTORICAL_HOST_ADDRESS=None,secure=True):\n \"\"\" Get stub to interact with meter data service.\n :param METER_DATA_HISTORICAL_HOST_ADDRESS: Optional argument to supply host address for given service. Otherwise,\n set as environment variable.\n :return: grpc Stub object.\n \"\"\"\n\n if METER_DATA_HISTORICAL_HOST_ADDRESS is None:\n METER_DATA_HISTORICAL_HOST_ADDRESS = os.environ[\"METER_DATA_HISTORICAL_HOST_ADDRESS\"]\n\n if not secure:\n channel = grpc.insecure_channel(METER_DATA_HISTORICAL_HOST_ADDRESS)\n else:\n credentials = grpc.ssl_channel_credentials()\n channel = grpc.secure_channel(METER_DATA_HISTORICAL_HOST_ADDRESS,credentials)\n return meter_data_historical_pb2_grpc.MeterDataHistoricalStub(channel)\n\n\ndef get_meter_data_historical(meter_data_stub, bldg, start, end, point_type, aggregate, window):\n \"\"\" Get meter data as a dataframe.\n\n :param meter_data_stub: grpc stub for meter data service.\n :param bldg: list(str) - list of buildings.\n :param start: datetime (timezone aware)\n :param end: datetime (timezone aware)\n :param point_type: (str) Building_Electric_Meter or Green_Button_Meter\n :param aggregate: (str) Values include MEAN, MAX, MIN, COUNT, SUM and RAW (the temporal window parameter is ignored)\n :param window: (str) Size of the moving window.\n :return: pd.DataFrame(), defaultdict(list) - Meter data, dictionary that maps meter data's columns (uuid's) to sites\n \"\"\"\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = int(start.timestamp() * 1e9)\n end_unix = int(end.timestamp() * 1e9)\n window_seconds = get_window_in_sec(window)\n\n # Create gRPC request object\n request = meter_data_historical_pb2.Request(\n building=bldg,\n start=int(start_unix),\n end=int(end_unix),\n point_type=point_type,\n aggregate=aggregate,\n window=window\n )\n\n historic_meter_data_response = meter_data_stub.GetMeterDataHistorical(request)\n\n # process data\n meter_list = []\n for msg in historic_meter_data_response:\n item = {\n \"datetime\" : datetime.datetime.utcfromtimestamp(msg.time / 1e9).replace(tzinfo=pytz.utc).astimezone(tz=start.tzinfo),\n \"power\" : msg.power\n }\n meter_list.append(item)\n df = pd.DataFrame(meter_list)\n df.set_index(\"datetime\",inplace=True)\n return df\n\n\ndef get_optimizer_stub(OPTIMIZER_HOST_ADDRESS=None,secure=True):\n \"\"\" Get stub to interact with optimizer service.\n :param OPTIMIZER_HOST_ADDRESS: Optional argument to supply host address for given service. Otherwise,\n set as environment variable.\n :return: grpc Stub object.\n \"\"\"\n\n if OPTIMIZER_HOST_ADDRESS is None:\n OPTIMIZER_HOST_ADDRESS = os.environ[\"OPTIMIZER_HOST_ADDRESS\"]\n\n if not secure:\n channel = grpc.insecure_channel(OPTIMIZER_HOST_ADDRESS)\n else:\n credentials = grpc.ssl_channel_credentials()\n channel = grpc.secure_channel(OPTIMIZER_HOST_ADDRESS,credentials)\n return optimizer_pb2_grpc.OptimizerStub(channel)\n\n\ndef get_mpc_optimization(optimizer_stub, building, zones, start, end, window, lambda_val, starting_temperatures,\n unit=\"F\"):\n \"\"\"Get the optimal actions according to MPC optimization.\n\n :param optimizer_stub: grpc stub for optimizer service\n :param building: (str) building name\n :param zones: (list str) zones names\n :param start: datetime (timezone aware)\n :param end: datetime (timezone aware)\n :param window: (str) the intervals in which to optimize\n :param lambda_val: (float) between 0 and 1. The lambda value to balance cost and discomfort.\n :param starting_temperatures: (dict) {str zone: float temperature} the starting temperatures of all zones in\n given building.\n :param unit: (string) the unit of the temperature.\n :return: (dict {(str) zone: (int) action) the optimal actions to take\n \"\"\"\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = int(start.timestamp() * 1e9)\n end_unix = int(end.timestamp() * 1e9)\n\n # call service\n optimizer_response = optimizer_stub.GetMPCOptimization(\n optimizer_pb2.MPCOptimizationRequest(\n building=building,\n zones=zones,\n start=int(start_unix),\n end=int(end_unix),\n window=window,\n lambda_val=lambda_val,\n starting_temperatures=starting_temperatures,\n unit=unit))\n\n return {iter_zone: optimizer_response.actions[iter_zone] for iter_zone in zones}\n\ndef get_mpc_simulation(optimizer_stub, building, zones, start, end, window,\n forecasting_horizon, lambda_val, starting_temperatures,\n unit=\"F\", num_runs=1):\n \"\"\"Get the simulation results according to MPC optimization. Stops get_mpc_simulation\n when param:end is reached.\n\n :param optimizer_stub: grpc stub for optimizer service\n :param building: (str) building name\n :param zones: (list str) zones names\n :param start: datetime (timezone aware)\n :param end: datetime (timezone aware)\n :param window: (str) the intervals in which to optimize\n :param forecasting_horizon: (str) the timeframe for which to simulate at every step.\n :param lambda_val: (float) between 0 and 1. The lambda value to balance cost and discomfort.\n :param starting_temperatures: (dict) {str zone: float temperature} the starting temperatures of all zones in\n given building.\n :param unit: (string) the unit of the temperature.\n :param num_runs: (int) the number of runs of simulation to get a better idea\n of the variance of the simulation.\n :returns:\n actions: {iter_zone: [actions]} actions that were excecuted for\n every step.\n temperatures: ({iter_zone: [temperatures]) temperature seen\n at every step.\n len(actions[zone]) = (end - start)/window\n len(temperatures[zone]) = (end - start)/temperatures + 1\n \"\"\"\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = int(start.timestamp() * 1e9)\n end_unix = int(end.timestamp() * 1e9)\n\n # call service\n simulation_response = optimizer_stub.GetMPCSimulation(\n optimizer_pb2.SimulationRequest(\n building=building,\n zones=zones,\n start=int(start_unix),\n end=int(end_unix),\n window=window,\n forecasting_horizon=forecasting_horizon,\n lambda_val=lambda_val,\n starting_temperatures=starting_temperatures,\n unit=unit,\n num_runs=num_runs))\n\n\n actions = []\n temperatures = []\n for simulation_result in simulation_response.simulation_results:\n actions.append({iter_zone: simulation_result.actions[iter_zone] for iter_zone in zones})\n temperatures.append({iter_zone: simulation_result.temperatures[iter_zone] for iter_zone in zones})\n\n return actions, temperatures\n\n\ndef check_data(data, start, end, window, check_nan=False):\n \"\"\"Checks if data has right times and optionally checks for nan.\n This includes checking that the daterange [param:start (inculsive) - param:end (exclusive)) is included in the data.\n And that the time-difference between datapoints equals to param:window.\n\n :param data: pd.df or pd.series\n :param start: datetime (timezone aware)\n :param end: datetime (timezone aware)\n :param window: (string)\n :param check_nan: If False (default) will not return an error if a datapoint is Nan. If True, will error on nan\n data points.\n :return: str err message. If no error, returns None.\"\"\"\n if not isinstance(data, pd.DataFrame) and not isinstance(data, pd.Series):\n return \"Is not a pd.DataFrame/pd.Series\"\n\n window = get_window_in_sec(window)\n time_diffs = data.index.to_series(keep_tz=True).diff()\n if (time_diffs.shape[0] > 1) and ((time_diffs.min() != time_diffs.max()) or (time_diffs.min().seconds != window)):\n return \"Missing rows or/and bad time frequency.\"\n if (start not in data.index) or ((end - datetime.timedelta(seconds=window)) not in data.index):\n return \"Does not have valid start or/and end time.\"\n if check_nan and (data.isna().values.any()):\n return \"Nan values in data.\"\n return None\n\ndef get_baseline_optimizer_stub(BASELINE_OPTIMIZER_HOST_ADDRESS=None,secure=True):\n \"\"\" Get stub to interact with optimizer service.\n :param BASELINE_OPTIMIZER_HOST_ADDRESS: Optional argument to supply host address for given service. Otherwise,\n set as environment variable.\n :return: grpc Stub object.\n \"\"\"\n\n if BASELINE_OPTIMIZER_HOST_ADDRESS is None:\n BASELINE_OPTIMIZER_HOST_ADDRESS = os.environ[\"BASELINE_OPTIMIZER_HOST_ADDRESS\"]\n\n if not secure:\n channel = grpc.insecure_channel(BASELINE_OPTIMIZER_HOST_ADDRESS)\n else:\n credentials = grpc.ssl_channel_credentials()\n channel = grpc.secure_channel(BASELINE_OPTIMIZER_HOST_ADDRESS,credentials)\n return baseline_optimizer_pb2_grpc.BaselineOptimizerStub(channel)\n\ndef get_normal_schedule_action(baseline_optimizer_stub,building,zones,start,end,window,starting_temperatures,unit,occupancy,do_not_exceed):\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = int(start.timestamp() * 1e9)\n end_unix = int(end.timestamp() * 1e9)\n\n baseline_optimizer_response = baseline_optimizer_stub.GetNormalScheduleAction(baseline_optimizer_pb2.NormalScheduleRequest(building=building,zones=zones,start=start_unix,end=end_unix,window=window,starting_temperatures=starting_temperatures,unit=unit,occupancy=occupancy,do_not_exceed=do_not_exceed))\n return baseline_optimizer_response.actions\n\ndef get_setpoint_expansion_action(baseline_optimizer_stub,building,zones,start,end,window,starting_temperatures,unit,occupancy,do_not_exceed,expansion_degrees):\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = int(start.timestamp() * 1e9)\n end_unix = int(end.timestamp() * 1e9)\n\n baseline_optimizer_response = baseline_optimizer_stub.GetSetpointExpansionAction(baseline_optimizer_pb2.SetpointExpansionRequest(building=building,zones=zones,start=start_unix,end=end_unix,window=window,starting_temperatures=starting_temperatures,unit=unit,occupancy=occupancy,do_not_exceed=do_not_exceed,expansion_degrees=expansion_degrees))\n return baseline_optimizer_response.actions\n\ndef get_demand_charge_action(baseline_optimizer_stub,building,zones,start,end,window,starting_temperatures,unit,occupancy,do_not_exceed,max_zones,include_all_zones):\n start = start.replace(microsecond=0)\n end = end.replace(microsecond=0)\n\n start_unix = int(start.timestamp() * 1e9)\n end_unix = int(end.timestamp() * 1e9)\n\n baseline_optimizer_response = baseline_optimizer_stub.GetDemandChargeAction(baseline_optimizer_pb2.DemandChargeRequest(building=building,zones=zones,start=start_unix,end=end_unix,window=window,starting_temperatures=starting_temperatures,unit=unit,occupancy=occupancy,do_not_exceed=do_not_exceed,max_zones=max_zones,include_all_zones=include_all_zones))\n return baseline_optimizer_response.actions\n","sub_path":"build/lib/xbos_services_getter/xbos_services_getter.py","file_name":"xbos_services_getter.py","file_ext":"py","file_size_in_byte":47124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"338511865","text":"# coding: utf-8\nimport socketserver\nimport os\n# Copyright 2013 Abram Hindle, Eddie Antonio Santos\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# Furthermore it is derived from the Python documentation examples thus\n# some of the code is Copyright © 2001-2013 Python Software\n# Foundation; All Rights Reserved\n#\n# http://docs.python.org/2/library/socketserver.html\n#\n# run: python freetests.py\n\n# try: curl -v -X GET http://127.0.0.1:8080/\n\n# Author: lappet\n# Discussion topic: serve html page via socketserver\n# URL: https://stackoverflow.com/questions/47726865/html-page-not-displaying-using-python-socket-programming\n# Usage in code: Inspired by this answer on how to send the content of a file through the socketserver\n#\n# Author: valentin\n# Discussion topic: parse encoded data\n# URL: https://stackoverflow.com/questions/29643544/python-a-bytes-like-object-is-required-not-str\n# Usage in code: Referred to this post on how to decode and parse data\n#\n# Reference for HTTP status code\n# https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_errors\n#\n# Function to check the prefix of a string. \n# https://www.tutorialspoint.com/python/string_startswith.htm\n\nclass MyWebServer(socketserver.BaseRequestHandler):\n def handle(self):\n self.data = self.request.recv(1024).strip()\n # Parse the data\n data = self.data.decode().split('\\r\\n')\n http_request = data[0].split()\n for i in data:\n # find the host\n if i.startswith(\"Host: \"):\n host = \"http://\"+i[6:]\n break\n # if the http header is invalid\n # or if the method is not allowed\n if len(http_request) != 3 or http_request[0] != \"GET\":\n msg = \"HTTP/1.1 405 Method Not Allowed\\r\\nContent-Type: text/html\\r\\nContent-Length: {}\\r\\n\\r\\n\"\n content = \"\"\"\n \n \n

405 Not Allowed

\n \n \"\"\"\n msg = msg.format(len(content))\n msg = msg + content\n self.request.sendall(msg.encode())\n # get the requested path\n http_request = http_request[1]\n # find the file\n root = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'www')\n if os.path.isfile(root+os.path.abspath(http_request)):\n # format the response header when the request is valid\n # HTTP code 200 OK\n msg = \"HTTP/1.1 200 OK\\r\\nContent-Type: {}\\r\\nContent-Length: {}\\r\\n\\r\\n\"\n # MIME type for css file\n if http_request[-4:] == \".css\":\n content = open(root+http_request).read()\n msg = msg.format(\"text/css\", len(content))\n msg = msg + content\n self.request.sendall(msg.encode())\n # MIME type for html file\n elif http_request[-5:] == \".html\":\n content = open(root+http_request).read()\n msg = msg.format(\"text/html\", len(content))\n msg = msg + content\n self.request.sendall(msg.encode())\n # find the directory\n elif os.path.isdir(root+os.path.abspath(http_request)):\n # redirect HTTP code 301\n if http_request[-1] != \"/\":\n new = host + http_request + \"/\"\n msg = \"HTTP/1.1 301 Moved Permanently\\r\\nLocation: {}\\r\\n\\r\\n\".format(\n new)\n self.request.sendall(msg.encode())\n # HTTP code 200\n content = open(os.path.join(\n root+http_request, \"index.html\")).read()\n msg = \"HTTP/1.1 200 OK\\r\\nContent-Type: text/html\\r\\nContent-Length: {}\\r\\n\\r\\n\"\n msg = msg.format(len(content))\n msg = msg + content\n self.request.sendall(msg.encode())\n # if no such directory/file\n else:\n msg = \"HTTP/1.1 404 Not Found\\r\\nContent-Type: text/html\\r\\nContent-Length: {}\\r\\n\\r\\n\"\n content = \"\"\"\n \n \n

404 Not Found

The requested URL was not found on this server.\n \n \"\"\"\n msg = msg.format(len(content))\n msg = msg + content\n self.request.sendall(msg.encode())\n\nif __name__ == \"__main__\":\n HOST, PORT = \"localhost\", 8080\n\n socketserver.TCPServer.allow_reuse_address = True\n # Create the server, binding to localhost on port 8080\n server = socketserver.TCPServer((HOST, PORT), MyWebServer)\n\n # Activate the server; this will keep running until you\n # interrupt the program with Ctrl-C\n server.serve_forever()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"124976229","text":"import numpy as np\n\nfrom imlib.cells.cells import pos_from_file_name\n\n# planes to rotate around, for x, y, z\nAXES = [(1, 2), (0, 2), (0, 1)]\n\n\ndef get_transf_matrix_from_res(pix_sizes):\n \"\"\" Create transformation matrix in mm\n from a dictionary of pixel sizes in um\n :param pix_sizes:\n :return:\n \"\"\"\n transformation_matrix = np.eye(4)\n for i, axis in enumerate((\"x\", \"y\", \"z\")):\n transformation_matrix[i, i] = pix_sizes[axis] / 1000\n return transformation_matrix\n\n\ndef flip_multiple(data, flips):\n \"\"\"Flips over each axis from list of booleans\n indicating if one axis has to be flipped\n :param data:\n :param flips:\n :return:\n \"\"\"\n\n for axis_idx, flip_axis in enumerate(flips):\n if flip_axis:\n data = np.flip(data, axis_idx)\n\n return data\n\n\ndef rotate_multiple(data, rotation_string):\n rotation_numbers = pos_from_file_name(rotation_string)\n for i in zip(AXES, rotation_numbers):\n data = rotate(data, i[0], i[1])\n return data\n\n\ndef rotate(data, axes, k):\n data = np.rot90(np.asanyarray(data), axes=axes, k=k)\n # data = np.swapaxes(data, 0, 1)\n return data\n","sub_path":"amap/utils/transformations.py","file_name":"transformations.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"594929872","text":"import readXML\n\ndef main():\n\n # Get all movies from the XML\n aMovieList = readXML.readMoviesXML(\"movies.xml\")\n\n while True:\n i = 0\n print(\"\\n\\n---------------------------------------------\")\n print(\"Movie Trailer App in Python\")\n print(\"(Enter 0 to exit)\")\n print(\"---------------------------------------------\")\n\n for movie in aMovieList:\n i = i + 1\n print(\"%d. %s\" %(i, movie.title))\n print(\"---------------------------------------------\")\n\n choice = input(\"Which movie trailer do you want to see? \")\n\n if choice == 0:\n print(\"Thank you for trying the app! Bye.\")\n print(\"---------------------------------------------\")\n break;\n\n if choice <= i: # len(aMovieList):\n aMovieList[choice-1].show_trailer()\n else:\n print(\"Sorry wrong option!. Retry\")\n\nmain()\n","sub_path":"Web Dev Examples/movie-trailers/show_movies.py","file_name":"show_movies.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"489990430","text":"import tensorflow as tf\r\nimport numpy as np\r\nfrom PIL import Image\r\nimport cv2\r\nimport os\r\n\r\nX = tf.placeholder(tf.float32, [1, 48, 48, 1])\r\nY = tf.placeholder(tf.float32, [1, 3])\r\nkeep_prob = tf.placeholder(tf.float32)\r\n\r\n#Similar to training. Takes similar steps to predict the image.\r\nprint(X)\r\nW1 = tf.Variable(tf.random_normal([3, 3, 1, 32], stddev=0.01))\r\nL1 = tf.nn.conv2d(X, W1, strides=[1, 1, 1, 1], padding='SAME')\r\nL1 = tf.nn.relu(L1)\r\nL1 = tf.nn.max_pool(L1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\r\nprint((L1.get_shape))\r\nW2 = tf.Variable(tf.random_normal([3, 3, 32, 64], stddev=0.01))\r\nL2 = tf.nn.conv2d(L1, W2, strides=[1, 1, 1, 1], padding='SAME')\r\nL2 = tf.nn.relu(L2)\r\nL2 = tf.nn.max_pool(L2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\r\nprint((L2.get_shape))\r\nW3 = tf.Variable(tf.random_normal([3, 3, 64, 128], stddev=0.01))\r\nL3 = tf.nn.conv2d(L1, W2, strides=[1, 1, 1, 1], padding='SAME')\r\nL3 = tf.nn.relu(L2)\r\nL3 = tf.nn.max_pool(L2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\r\nprint((L3.get_shape))\r\nW4 = tf.Variable(tf.random_normal([6 * 6 * 64, 512], stddev=0.01))\r\nL4 = tf.reshape(L3, [-1, 6 * 6 * 64])\r\nL4 = tf.matmul(L4, W4)\r\nL4 = tf.nn.relu(L4)\r\nL4 = tf.nn.dropout(L4, keep_prob)\r\nprint((L4.get_shape))\r\nW5 = tf.Variable(tf.random_normal([512, 3], stddev=0.01))\r\nmodel = tf.matmul(L4, W5)\r\nprint(model)\r\n\r\nsaver = tf.train.Saver(max_to_keep=10) #\r\n\r\ninit = tf.global_variables_initializer()\r\nsess = tf.Session()\r\nsess.run(init)\r\n\r\nsaver.restore(sess,os.path.join(os.getcwd(), 'my_model.ckpt')) #restore model here!\r\n\r\ntry:\r\n cam = cv2.VideoCapture(0) #Depending on camera port, the number inside the parenthesis must be changed!\r\nexcept:\r\n print('Check the Camera Port')\r\n\r\nwhile (cam.isOpened()):\r\n ret, frame = cam.read()\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n cv2.imshow('Camera',gray) #Only needed when you want to see the result.\r\n gray_resize = cv2.resize(gray, (48,48))\r\n normalized = np.zeros((48,48))\r\n normalized = cv2.normalize(gray_resize, normalized, 0, 255, cv2.NORM_MINMAX)\r\n #cv2.imwrite(\"realtime.jpg\", gray_resize)\r\n\r\n #im = Image.open(\"realtime.jpg\") # set the target image here!\r\n #pixel_values = list(im.getdata())\r\n pixel_values = normalized\r\n pixel_values = 1.0 * np.asarray(pixel_values)\r\n pixel_values = pixel_values / 255\r\n X_in = np.reshape(pixel_values, [1, 48, 48, 1])\r\n Y_in = np.zeros(3) # dummy label\r\n Y_in = np.reshape(Y_in, [1, 3])\r\n\r\n prob_vector = sess.run([model], feed_dict={X: X_in, Y: Y_in, keep_prob: 1.0})\r\n print(prob_vector) #You can add more codes in here to print out a more refined result.\r\n\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\ncam.release()\r\ncv2.destroyAllWindows()\r\n\r\n\r\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"535484994","text":"\n'''\n@authors: Tatiana Rijoff,\n Carlo Zannini\n@date: 01/03/2013\n@copyright CERN\n'''\nimport configparser\nimport tlwall\n\n\nclass CfgIo(object):\n def __init__(self, cfg_file=None):\n if cfg_file is not None:\n self.config = self.read_cfg(cfg_file)\n return\n\n def read_chamber(self, cfg_file=None):\n if cfg_file is not None:\n config = self.read_cfg(cfg_file)\n else:\n config = self.config\n pipe_len_m = config.getfloat('base_info', 'pipe_len_m')\n # pipe radius is equal to vertical dimension so in the cfg file or\n # it is defined the radius or the vertical dimension\n if config.has_option('base_info', 'pipe_radius_m'):\n pipe_rad_m = config.getfloat('base_info', 'pipe_radius_m')\n pipe_hor_m = pipe_rad_m\n pipe_ver_m = pipe_rad_m\n else:\n pipe_ver_m = config.getfloat('base_info', 'pipe_ver_m')\n pipe_rad_m = pipe_ver_m\n if config.has_option('base_info', 'pipe_hor_m'):\n pipe_hor_m = config.getfloat('base_info', 'pipe_hor_m')\n\n chamber_shape = config.get('base_info', 'chamber_shape')\n if config.has_option('base_info', 'component_name'):\n component_name = config.get('base_info', 'component_name')\n else:\n component_name = 'chamber'\n betax = config.getfloat('base_info', 'betax')\n betay = config.getfloat('base_info', 'betay')\n nbr_layers = config.getint('layers_info', 'nbr_layers')\n layers = []\n\n for i in range(nbr_layers):\n layer_type = config.get('layer' + str(i), 'type')\n thick_m = config.getfloat('layer' + str(i), 'thick_m')\n if layer_type == 'CW':\n muinf_Hz = config.getfloat('layer' + str(i), 'muinf_Hz')\n epsr = config.getfloat('layer' + str(i), 'epsr')\n sigmaDC = config.getfloat('layer' + str(i), 'sigmaDC')\n k_Hz = config.getfloat('layer' + str(i), 'k_Hz')\n tau = config.getfloat('layer' + str(i), 'tau')\n RQ = config.getfloat('layer' + str(i), 'RQ')\n layers.append(tlwall.Layer(layer_type=layer_type,\n thick_m=thick_m,\n muinf_Hz=muinf_Hz,\n epsr=epsr,\n sigmaDC=sigmaDC,\n k_Hz=k_Hz,\n tau=tau,\n RQ=RQ,\n boundary=False))\n else:\n layers.append(tlwall.Layer(layer_type=layer_type,\n thick_m=thick_m,\n boundary=False))\n\n layer_type = config.get('boundary', 'type')\n if layer_type == 'CW':\n muinf_Hz = config.getfloat('boundary', 'muinf_Hz')\n epsr = config.getfloat('boundary', 'epsr')\n sigmaDC = config.getfloat('boundary', 'sigmaDC')\n k_Hz = config.getfloat('boundary', 'k_Hz')\n tau = config.getfloat('boundary', 'tau')\n RQ = config.getfloat('boundary', 'RQ')\n layers.append(tlwall.Layer(layer_type=layer_type,\n thick_m=thick_m,\n muinf_Hz=muinf_Hz,\n epsr=epsr,\n sigmaDC=sigmaDC,\n k_Hz=k_Hz,\n tau=tau,\n RQ=RQ,\n boundary=True))\n chamber = tlwall.Chamber(pipe_len_m=pipe_len_m,\n pipe_rad_m=pipe_rad_m,\n pipe_hor_m=pipe_hor_m,\n pipe_ver_m=pipe_ver_m,\n chamber_shape=chamber_shape,\n betax=betax,\n betay=betay,\n layers=layers,\n component_name=component_name)\n return chamber\n\n def read_freq(self, cfg_file=None):\n if cfg_file is not None:\n config = self.read_cfg(cfg_file)\n else:\n config = self.config\n fmin = config.getfloat('frequency_info', 'fmin')\n fmax = config.getfloat('frequency_info', 'fmax')\n fstep = config.getfloat('frequency_info', 'fstep')\n freq = tlwall.Frequencies(fmin=fmin, fmax=fmax, fstep=fstep)\n return freq\n\n def read_beam(self, cfg_file=None):\n if cfg_file is not None:\n config = self.read_cfg(cfg_file)\n else:\n config = self.config\n test_beam_shift = config.getfloat('beam_info', 'test_beam_shift')\n if config.has_option('beam_info', 'betarel'):\n betarel = config.getfloat('beam_info', 'betarel')\n if config.has_option('beam_info', 'mass_MeV_c2'):\n mass_MeV_c2 = config.getfloat('beam_info', 'mass_MeV_c2')\n beam = tlwall.Beam(betarel=betarel,\n test_beam_shift=test_beam_shift,\n mass_MeV_c2=mass_MeV_c2)\n else:\n beam = tlwall.Beam(betarel=betarel,\n test_beam_shift=test_beam_shift)\n return beam\n if config.has_option('beam_info', 'gammarel'):\n gammarel = config.getfloat('beam_info', 'gammarel')\n if config.has_option('beam_info', 'mass_MeV_c2'):\n mass_MeV_c2 = config.getfloat('beam_info', 'mass_MeV_c2')\n beam = tlwall.Beam(gammarel=gammarel,\n test_beam_shift=test_beam_shift,\n mass_MeV_c2=mass_MeV_c2)\n else:\n beam = tlwall.Beam(gammarel=gammarel,\n test_beam_shift=test_beam_shift)\n return beam\n if config.has_option('beam_info', 'Ekin_MeV'):\n Ekin_MeV = config.getfloat('beam_info', 'Ekin_MeV')\n if config.has_option('beam_info', 'mass_MeV_c2'):\n mass_MeV_c2 = config.getfloat('beam_info', 'mass_MeV_c2')\n beam = tlwall.Beam(Ekin_MeV=Ekin_MeV,\n test_beam_shift=test_beam_shift,\n mass_MeV_c2=mass_MeV_c2)\n else:\n beam = tlwall.Beam(Ekin_MeV=Ekin_MeV,\n test_beam_shift=test_beam_shift)\n return beam\n if config.has_option('beam_info', 'p_MeV_c'):\n p_MeV_c = config.getfloat('beam_info', 'p_MeV_c')\n if config.has_option('beam_info', 'mass_MeV_c2'):\n mass_MeV_c2 = config.getfloat('beam_info', 'mass_MeV_c2')\n beam = tlwall.Beam(p_MeV_c=p_MeV_c,\n test_beam_shift=test_beam_shift,\n mass_MeV_c2=mass_MeV_c2)\n else:\n beam = tlwall.Beam(p_MeV_c=p_MeV_c,\n test_beam_shift=test_beam_shift)\n return beam\n\n def read_tlwall(self, cfg_file=None):\n if cfg_file is not None:\n config = self.read_cfg(cfg_file)\n else:\n config = self.config\n chamber = self.read_chamber()\n beam = self.read_beam()\n freq = self.read_freq()\n mywall = tlwall.TlWall(chamber, beam, freq)\n return mywall\n\n def read_cfg(self, cfg_file):\n config = configparser.ConfigParser()\n try:\n config.read(cfg_file)\n except IOError:\n print('The file %s does not exist, try again!' % cfg_file)\n\n return config\n","sub_path":"tlwall/cfg_io.py","file_name":"cfg_io.py","file_ext":"py","file_size_in_byte":7896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"540102358","text":"import cv2\n\ncap = cv2.VideoCapture(\"sony.mp4\")\n\nwhile True:\n sucess, img = cap.read()\n cv2.imshow(\"video\",img)\n if cv2.waitKey(1) & 0xFF ==ord('q'): #this line is for keyboard comand\n # when i will press 'q' key the video will be end.\n break","sub_path":"chapter 1/vidaccess.py","file_name":"vidaccess.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"586408849","text":"import turtle\nfrom random import *\nturtle.shape('turtle')\nturtle.width(3)\nturtle.color('red')\nn = randint(30, 60)\nfor i in range(n):\n a = randint(0, 100)\n b = randint(0, 360)\n turtle.forward(a)\n turtle.left(b)","sub_path":"Laba(cherepaha)/2chapter/1 zad.py","file_name":"1 zad.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"402785282","text":"from random import randint\r\n\r\nm = int(input(\"Zadajte prvy rozmer pola:\"))\r\nn = int(input(\"Zadajte druhy rozmer pola:\"))\r\n\r\npole = []\r\n\r\nfor i in range(m):\r\n pole.append([])\r\n for j in range(n):\r\n pole[i].append(randint(1,5))\r\n\r\nprint(*pole)\r\n\r\n#VYMENA MIN, MAX\r\nmax_index = []\r\nmin_index = []\r\n\r\nmaximum = 0\r\nminimum = pole[0][0]\r\n\r\nfor i in range(m):\r\n for j in range(n):\r\n if maximum < pole[i][j]:\r\n maximum = pole[i][j]\r\n max_index = [i,j]\r\n if minimum > pole[i][j]:\r\n minimum = pole[i][j]\r\n min_index = [i,j]\r\n\r\npole[min_index[0]][min_index[1]], pole[max_index[0]][max_index[1]] = pole[max_index[0]][max_index[1]], pole[min_index[0]][min_index[1]]\r\n\r\nprint(*pole)\r\n\r\n#VYMENA RIADKU\r\na = int(input(\"Zadajte prvy riadok na vymnenu:\"))\r\nb = int(input(\"Zadajte druhy riadok na vymenu:\"))\r\n\r\npole[a], pole[b] = pole[b], pole[a]\r\nprint(pole)\r\n\r\n#SUCET OBVODU MATICE\r\nsucet = 0\r\nfor i in range(m):\r\n if i == 0 or i == m-1:\r\n for j in range(n):\r\n sucet += pole[i][j]\r\n else:\r\n sucet += pole[i][0]\r\n sucet += pole[i][-1]\r\nprint(\"Sucet obvodu:\",sucet)\r\n\r\n#SUCET NA HLAVNEJ DIAGONALE MATICE\r\ndiagonala = 0\r\nj = 0\r\nfor i in range(m):\r\n if j > n-1:\r\n break\r\n diagonala += pole[i][j]\r\n j += 1\r\n\r\nprint(\"Sucet hlavnej diagonaly:\",diagonala)\r\n\r\n#VZOSTUPNE USPORIADANIE\r\nnum = int(input(\"Zadajte cislo riadku:\"))\r\nflag = True\r\nfor i in range(len(pole[num])-1):\r\n if pole[num][i] > pole[num][i+1]:\r\n flag = False\r\n\r\nif flag:\r\n print(\"Riadok\", num,\"je vzostupne usporiadany.\")\r\nelse:\r\n print(\"Riadok\", num,\"nie je vzostupne usporiadany.\")\r\n\r\n#ROTACIA MATICE\r\ntemp = []\r\nfor i in range(len(pole[0])):\r\n temp.append([])\r\n for j in range(len(pole)):\r\n temp[i].insert(0,pole[j][i])\r\n\r\nprint(*temp)","sub_path":"inf_2022/matica.py","file_name":"matica.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"425319253","text":"# Copyright (c) 2013, yashwanth and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\n\ndef execute(filters=None):\n\tcolumns = getColumns()\n\tdata = construct_report()\n\n\tif filters.get(\"committed_production_plan\"):\n\t\tf_data = []\n\t\tfor d in data:\n\t\t\tif d[1] == filters.get(\"committed_production_plan\"):\n\t\t\t\tf_data.append(d)\n\t\treturn columns, f_data\n\n\treturn columns, data\n\n\ndef construct_report():\n\tr_data = frappe.db.sql(\"\"\"select cmpi.week_ending, cmpi.parent, cmpi.dispatch_item, cmpi.dispatch_item_name,\n \t\t\t\t\t\tcmpi.production_quantity_committed, cmpi.quantity_in_tonnes\n \t\t\t\t\t\tfrom `tabCommitted Production Plan Items` as cmpi\n \t\t\t\t\t\tjoin `tabCommitted Production Plan` as cmp on cmpi.parent = cmp.name\n \t\t\t\t\t\twhere cmp.is_active=1\n \t\t\t\t\t\torder by cmpi.week_ending, cmpi.dispatch_item\"\"\", as_dict=1)\n\n\tif (len(r_data) > 0):\n\t\tdata = []\n\t\tfor r in r_data:\n\t\t\tif r['week_ending']:\n\t\t\t\tdata.append([r['week_ending'].strftime(\"%d-%m-%Y\"),r['dispatch_item'],\n\t\t\t\t\t\tr['dispatch_item_name'], r['production_quantity_committed'], r['quantity_in_tonnes']])\n\n\t\treturn data\n\ndef getColumns():\n\tcolumns = [\n\t\t(\"Week Ending\")+\"::190\",\n\t\t(\"Dispatch Item Code\")+\"::250\",\n\t\t(\"Dispatch Item Name\")+\"::250\",\n\t\t(\"Production Quantity Committed\")+\"::190\",\n\t\t(\"Quantity in Tonnes\")+\"::190\"\n\t]\n\n\treturn columns\n","sub_path":"foundryapp/foundryapp/report/committed_production_plan_report/committed_production_plan_report.py","file_name":"committed_production_plan_report.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"222971083","text":"import pika\nimport json\n\nimport rabmq, dae_lib\nfrom rabmq import *\nfrom dae_lib import *\n\n\ndef dae_shell_input_reader(argument, connection, channel):\n thread_name = threading.currentThread().getName()\n print(\"Starting thread {} with delay {}\\n\".format(thread_name, argument))\n time.sleep(3)\n while (True):\n next_input = input(\"Enter the full command:\")\n if ((next_input == 'q') or (next_input == 'Q')):\n break\n job = {\n 'source': 'DAE_SHELL',\n 'sender': DAE_SHELL_Q,\n 'input': next_input # Format - key_word param1=value1,param2=value2,param3=value3\n }\n body_dump = json.dumps(job)\n RABMQ_tx(channel, DAE_MAIN_Q, body_dump)\n\n return\n\ndef dae_shell_response_handler(ch, method, properties, body):\n '''\n This function simply prints out the response received given that this is the DAE shell\n '''\n print(body.decode(\"utf-8\"))\n return\n\ndef dae_shell_response_collector(argument):\n thread_name = threading.currentThread().getName()\n print(\"Starting thread {} with delay {}\\n\".format(thread_name, argument))\n\n print(\"DAE Shell setting up SUB message queue {} with AMQP RabbitMQ.....\".format(DAE_SHELL_Q))\n connection, channel = RABMQ_setup_as_sub(DAE_SHELL_Q, dae_shell_response_handler)\n\n return\n\nif __name__ == \"__main__\":\n connection, channel = RABMQ_setup_as_pub(DAE_MAIN_Q)\n\n import time\n import threading\n try:\n threads = []\n t = threading.Thread(name=\"Input Reader\", target=dae_shell_input_reader, args=(0, connection, channel))\n threads.append(t)\n t.start()\n\n t = threading.Thread(name=\"Response Collector\", target=dae_shell_response_collector, args=(0,))\n threads.append(t)\n t.start()\n except Exception as err:\n print(\"Error {}: unable to start thread\", err)\n\n while 1:\n pass\n\n connection.close()","sub_path":"Automate/dae_shell.py","file_name":"dae_shell.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"524612521","text":"# -*- coding: utf-8 -*-\r\n\"\"\"OVERLAP CLI\r\n\r\nUsage:\r\n overlap_detect.py [--input_dir=] [--output_dir=]\r\n overlap_detect.py --runall [--input_dir=] [--output_dir=]\r\n overlap_detect.py (-h | --help)\r\n overlap_detect.py (-v | --version)\r\n\r\nOptions:\r\n Ex. ADB_DHS\r\n --runall Processes all codebooks\r\n --input_dir= Specify a different input directory\r\n --output_dir= Specify a different output directory\r\n -h --help Show Usage and Options\r\n -v --version Show Version\r\n\"\"\"\r\n\r\nimport geopandas as gpd\r\nfrom geopandas import GeoDataFrame\r\nimport pandas as pd\r\nfrom shapely.geometry import MultiPoint, Point\r\nimport matplotlib.pyplot as plt\r\nfrom collections import Counter\r\nfrom matplotlib.collections import PatchCollection\r\nfrom descartes import PolygonPatch\r\nfrom docopt import docopt\r\nfrom pathlib import Path\r\nfrom PIL import Image\r\nimport sys\r\nimport glob\r\nimport re\r\nimport io\r\nimport os\r\n\r\n\r\ndef main(args):\r\n \r\n # Assigning output data directory based on user input\r\n if args['--output_dir'] is None: # Current working directory\r\n output_dir = os.getcwd() \r\n print(output_dir)\r\n else:\r\n output_dir = args['--output_dir'] \r\n\r\n # Assigning input data directory based on user input\r\n if args['--input_dir'] is None:\r\n codebook_file_path = 'J:/WORK//11_geospatial//05_survey shape'\\\r\n 'file library/codebooks//'\r\n shapefile_file_path = 'J:/WORK//11_geospatial//05_survey shape'\\\r\n 'file library/Shapefile directory//'\r\n else:\r\n codebook_file_path = args['--input_dir'] \r\n shapefile_file_path = args['--input_dir'] \r\n\r\n # Initializing column values for input and output dataframe\r\n labels = ['nid', 'iso3', 'location_code', 'shapefile', 'point_count',\r\n 'polygon_count', 'point_geospatial_ids',\r\n 'polygon_geospatial_ids', 'percent_point']\r\n fields = ['nid', 'iso3', 'start_year', 'geospatial_id', 'end_year',\r\n 'point', 'lat', 'long', 'location_code', 'shapefile']\r\n\r\n # Set of shapefiles won't be processed if encountered in codebook\r\n # shapefile column\r\n problem_shapefiles = ('buffered_points', 'geo1_pt2011_Y2017M06D29',\r\n 'IDN_DHS_1994')\r\n\r\n # Coordinate reference system used for projections\r\n crs = {'init': 'epsg:4326'}\r\n\r\n # Initilizing encoding\r\n encoding = 'latin-1'\r\n\r\n # Directory of entered codebook\r\n file_path = codebook_file_path + args[''] + '.csv'\r\n\r\n # Validating codebook file path\r\n file = Path(file_path)\r\n try:\r\n file.resolve()\r\n except FileNotFoundError:\r\n print('\\n\\nCodebook: ' + args[''] + ' not present '\r\n 'in\\n\\n' + codebook_file_path + '\\n\\n')\r\n return\r\n else:\r\n df = pd.read_csv(file, usecols=fields, encoding=encoding,\r\n low_memory=False)\r\n\r\n # Reading in metadata for each country - full name, iso3, stage\r\n # Needed for display output\r\n cx = pd.read_csv(\"J:/temp/jessicac/outputs/crosswalk1.csv\")\r\n\r\n # Isolate NIDs with both point and polygon values\r\n grouped_df = df.groupby('nid')['point'].nunique().reset_index()\r\n if len(grouped_df.point.unique()) < 2:\r\n print('\\n\\nCodebook: ' + args[''] + ' countains no '\r\n 'point/polygon overlap\\n\\n')\r\n return\r\n\r\n # Subset nids with both point and polygon data to be\r\n # tested for overlap\r\n points_df = (grouped_df.groupby('point')).get_group(2)\r\n subset_df = df[df['nid'].isin(points_df.nid)]\r\n\r\n # Drop all subnational strings included in iso3 column\r\n subset_df['iso3'].apply(lambda x: re.sub(r'_.*', '', x))\r\n\r\n print('\\n\\n******* Processing codebook: ' + args[''] +\r\n ' *******\\n')\r\n\r\n # Loop through each nid to detect overlap\r\n frames = subset_df.groupby('nid')\r\n for f, frame in frames:\r\n\r\n # Isolate nid for later output of files and titles\r\n nid = str(frame.nid.iloc[0])\r\n\r\n # Get points and polygons for individual processing\r\n rows = frame.groupby(frame.point)\r\n points = rows.get_group(1)[['long', 'lat', 'geospatial_id']].dropna()\r\n\r\n polys = rows.get_group(0)[['location_code', 'geospatial_id']].dropna()\r\n\r\n # location_codes being set to numerals for GAUL_CODE comparison\r\n polys['location_code'] = pd.to_numeric(polys['location_code'])\r\n poly_list = list(polys['location_code'].dropna().unique())\r\n\r\n # Transform point values to type geometry for finding\r\n # intersection with polygon geometry from shapefiles\r\n geometry = [Point(xy) for xy in zip(points.long, points.lat)]\r\n point_geo_df = (GeoDataFrame(points, crs=crs, # noqa\r\n geometry=geometry)).rename(\r\n columns={'geospatial_id': 'pnt_geospatial_id'})\r\n\r\n # Loop through each iso3 for NID\r\n isos = frame.iso3.dropna().unique()\r\n for iso in isos:\r\n\r\n # Merge the current nid with metadata for current iso3\r\n # necessary for title displayed in infograph\r\n iso_df = frame.set_index('iso3').join(\r\n cx.set_index('iso3')).drop_duplicates()\r\n iso3_metadata = iso_df.iloc[0].to_dict()\r\n\r\n # loop through all shapefiles for NID\r\n shapefiles = frame.shapefile.dropna().unique()\r\n for shapefile in shapefiles:\r\n\r\n # Cutting out of shapefile loop for all identified\r\n # discrepencies in codebook column\r\n if shapefile in problem_shapefiles:\r\n #print(\"false\", file=sys.stderr)\r\n continue\r\n elif shapefile.endswith('.shp'):\r\n shapefile = shapefile[: -4]\r\n\r\n # Reads in shapefile, determines if world admin shapefile\r\n # and subsets size if applicable\r\n m_df = process_shapefile(shapefile, iso, iso3_metadata,\r\n shapefile_file_path)\r\n\r\n # Validating shapefile dataframe\r\n if type(m_df) is bool:\r\n return\r\n elif len(m_df) == 0:\r\n continue\r\n\r\n # Assuring no String values\r\n m_df['GAUL_CODE'] = pd.to_numeric(m_df.GAUL_CODE)\r\n\r\n # Subsets shapefile dataframe to only the location codes\r\n # referenced in codebooks\r\n map_df = m_df[m_df['GAUL_CODE'].isin(poly_list)]\r\n\r\n # Joins point and polygon geometry and returns\r\n # point metadata for each overlapping point\r\n point_join = gpd.sjoin(point_geo_df, map_df, # noqa\r\n op='intersects').rename(\r\n columns={'GAUL_CODE': 'location_code'})\r\n\r\n # Generates a dataframe that holds location code\r\n # and count of how many times a point overlaps that polygon\r\n # necessary for choropleth highlighting and output summary\r\n counter = pd.DataFrame.from_dict(Counter # noqa\r\n (point_join.location_code),\r\n orient='index').reset_index(\r\n ).rename(columns={\r\n 'index': 'location_code',\r\n 0: 'pcount'})\r\n\r\n # Continues if there aren't any gaul codes affected when\r\n # an empty counter is returned\r\n if len(counter) == 0:\r\n continue\r\n print('Overlap detected: {:<8}| {:<5}| {}'.format(nid, iso,\r\n shapefile))\r\n\r\n # Joins all polygons and generated overlapped polygons\r\n # and returns metadata for each of those polygons\r\n poly_join = pd.merge(counter, polys, how='inner',\r\n on=['location_code'])\r\n\r\n # Prepares only the geometry detected to have overlap to be\r\n # plotted\r\n final_points = MultiPoint([tuple(x) for x in\r\n point_join[['long', 'lat']].values])\r\n final_polys = m_df.set_index('GAUL_CODE').join(counter # noqa\r\n .set_index('location_code'))\r\n\r\n # Assures no no null count values to be outputted in infograph\r\n final_polys['pcount'] = final_polys.pcount.fillna(0)\r\n\r\n # Plots map and metadata for each nid and outputs\r\n # image file\r\n plot_figure(final_polys, nid, iso, iso3_metadata, final_points,\r\n poly_join, counter, args[''],\r\n shapefile, output_dir)\r\n\r\n # Calculates all final stats to be outputted in summary\r\n overlap_summary(labels, point_join, poly_join, counter, nid,\r\n iso, shapefile, output_dir)\r\n\r\n if args['--runall'] is False:\r\n print('\\n\\nInfograph(s) and Summary Report(s) outputted to ' +\r\n output_dir)\r\n\r\n\r\ndef process_shapefile(shapefile, iso, iso3_metadata, shapefile_file_path):\r\n\r\n # Read in shapefile to be processed\r\n file_path = shapefile_file_path + shapefile + '.shp'\r\n\r\n # Validating shapefile file path\r\n file = Path(file_path)\r\n try:\r\n file.resolve()\r\n except FileNotFoundError:\r\n print(\"\\nShapefile: \" + shapefile + \" not present in\\n\\n\" +\r\n shapefile_file_path + '\\n\\n')\r\n return False\r\n else:\r\n m_df = gpd.read_file(file_path)\r\n\r\n # Subset shapefile to only the iso3 polygons if determined to be\r\n # a world admin shapefile\r\n if 'COUNTRY_ID' in m_df.columns:\r\n m_df = m_df[m_df.COUNTRY_ID == iso]\r\n elif 'ISO' in m_df.columns:\r\n m_df = m_df[m_df.ISO == iso]\r\n elif 'ADM0_NAME' in m_df.columns:\r\n name1 = iso3_metadata['location_name']\r\n m_df = m_df[m_df.ADM0_NAME == name1]\r\n\r\n m_df = m_df.dropna(subset=['GAUL_CODE'])\r\n\r\n return m_df\r\n\r\n\r\ndef plot_figure(final_polys, nid, iso, iso3_metadata, final_points, poly_join,\r\n counter, codebook_name, shapefile, output_dir):\r\n\r\n # Plot header that includes all metadata matched to this nid and iso3\r\n fig, ax = plt.subplots(1, figsize=(8, 5))\r\n title = 'NID - {:<12} {} - {:<16} {} - {:<11} Stage {}'.format(\r\n nid, iso, iso3_metadata['location_name'],\r\n iso3_metadata['start_year'], iso3_metadata['end_year'],\r\n iso3_metadata['Stage'])\r\n\r\n # Plot Footer that includes related stats and entered codebook\r\n polygon_total = str(len(counter))\r\n\r\n ax.annotate('{:^22} {:^40} from {}'.format(polygon_total + ' polygon(s)',\r\n shapefile + '.shp', codebook_name), xy=(0.025, 0.04),\r\n xycoords='figure fraction', horizontalalignment='left',\r\n verticalalignment='top', fontsize=12)\r\n\r\n # Plot points and polygons, prepares layout details of figure\r\n vmin = 0\r\n var = 'pcount'\r\n vmax = counter.pcount.max()\r\n final_polys.plot(column=var, cmap='Reds', linewidth=0.8,\r\n edgecolor='0.8', ax=ax, vmin=vmin, vmax=vmax)\r\n POINT = '#0000ff' # Blue\r\n point_patchs = [PolygonPatch(point.buffer(.03), fc=POINT) for point in\r\n final_points]\r\n ax.add_collection(PatchCollection(point_patchs, match_original=True))\r\n ax.axis('off')\r\n ax.set_xticks([])\r\n ax.set_yticks([])\r\n plt.title(title)\r\n plt.tight_layout()\r\n\r\n # Generates color bar for choropleth key\r\n sm = plt.cm.ScalarMappable(cmap='Reds', norm=plt.Normalize\r\n (vmin=vmin, vmax=vmax))\r\n sm._A = []\r\n fig.colorbar(sm)\r\n\r\n # Generating in-memory formatted image\r\n buf = io.BytesIO()\r\n plt.savefig(buf, format='png')\r\n buf.seek(0)\r\n im = Image.open(buf)\r\n\r\n # output figure as png infograph\r\n im.save(output_dir + iso + nid + shapefile + 'pic.png')\r\n\r\n # Closing all figure actions\r\n buf.close()\r\n plt.close(fig)\r\n\r\n\r\ndef overlap_summary(labels, point_join, poly_join, counter, nid, iso,\r\n shapefile, output_dir):\r\n\r\n # Prepares values to be called\r\n problem_df = pd.DataFrame(columns=labels)\r\n geo_points = point_join.groupby('location_code')\r\n geo_polys = poly_join.groupby('location_code')\r\n\r\n # Calculates all stats for output file\r\n for loc_code in counter.location_code:\r\n point_ids = geo_points.get_group(loc_code)\r\n poly_ids = geo_polys.get_group(loc_code)\r\n point_list = ', '.join(map(str, point_ids['pnt_geospatial_id']))\r\n location_list = ', '.join(map(str, poly_ids['geospatial_id']))\r\n cnt1 = len(point_ids)\r\n cnt2 = len(poly_ids)\r\n point_percent = format(cnt1 / (cnt1 + cnt2), '.2f')\r\n\r\n # Appends each polygon data to output file\r\n values = [(nid, iso, loc_code, shapefile, cnt1, cnt2, point_list,\r\n location_list, point_percent)]\r\n new_entry = pd.DataFrame.from_records(values, columns=labels)\r\n problem_df = pd.concat([problem_df, new_entry])\r\n\r\n # Outputs summary as csv\r\n # problem_df.to_csv(output_dir + iso + nid + shapefile + 'doc.csv',\r\n # index=False)\r\n\r\n\r\nif __name__ == '__main__':\r\n # Receive command line arguments\r\n arguments = docopt(__doc__, version='Overlap 1.0.1')\r\n\r\n if arguments['--runall']:\r\n if arguments['--input_dir']:\r\n inputs = arguments['--input_dir']\r\n else:\r\n inputs = 'J:/WORK//11_geospatial//05_survey shape'\\\r\n 'file library/codebooks/'\r\n\r\n file_names1 = [x[:-4] for x in glob.glob(inputs +'/*.csv' )]\r\n file_names = [y.replace(inputs, '') for y in file_names1]\r\n # Loop through and process all codebooks\r\n for codebook_name in file_names:\r\n arguments[''] = codebook_name\r\n main(arguments)\r\n\r\n elif arguments['']:\r\n main(arguments)\r\n else:\r\n print(arguments)\r\n","sub_path":"overlap_detect.py","file_name":"overlap_detect.py","file_ext":"py","file_size_in_byte":14505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"82912163","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCopyright (c) 2020 Jarosław Stańczyk \nSource code presented in the lectures \"Python programming language\"\n\n06/gen.py\n\"\"\"\nfrom __future__ import print_function\n\n\ndef gen(exp):\n\tfor x in exp:\n\t\tyield x**2\n\n\nif __name__ == \"__main__\":\n\tl1 = [x**2 for x in range(10)] # list\n\tprint(l1)\n\n\tg1 = (x**2 for x in range(10)) # gen\n\tprint(g1)\n\n\tg2 = gen(iter(range(10)))\n\tprint(g2)\n\n\n\t# eof.","sub_path":"06/20.gen.py","file_name":"20.gen.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"648651435","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 17 13:30:44 2017\n\n@author: bryson0083\n\"\"\"\n\nimport sqlite3\nimport datetime\nfrom dateutil import parser\nimport pandas as pd\n#import sys\n\ndef store_db(arg_df, arg_date):\n\t#前處理->清除先前已跌出榜外的資料\n\tsqlstr = \"delete from STOCK_GVI where STATUS='ABD' \"\n\tconn.execute(sqlstr)\n\tconn.commit()\n\t\n\t#前處理->所有資料狀態修改\n\tsqlstr = \"update STOCK_GVI set STATUS='ABD' \"\n\tconn.execute(sqlstr)\n\tconn.commit()\n\t\n\t#前處理->所有資料排名,備份到prev_rank\n\tsqlstr = \"update STOCK_GVI set prev_rank = rank \"\n\tconn.execute(sqlstr)\n\tconn.commit()\t\n\t\n\tcnt = 1\n\tcommit_flag = \"Y\"\n\tfor i in range(0,len(arg_df)):\n\t\tcomp_id = str(arg_df.iloc[i][0])\n\t\tcomp_name = str(arg_df.iloc[i][1])\n\t\tstock_type = str(arg_df.iloc[i][2])\n\t\tprice = arg_df.iloc[i][3]\n\t\teps = arg_df.iloc[i][4]\n\t\tbvps = arg_df.iloc[i][5]\n\t\tpbr = arg_df.iloc[i][6]\n\t\tsroe = arg_df.iloc[i][7]\n\t\testm_y_roe = arg_df.iloc[i][8]\n\t\tgvi = arg_df.iloc[i][9]\n\t\trank = cnt\n\t\trec_date = arg_date\n\t\t\n\t\t# 最後維護日期時間\n\t\tstr_date = str(datetime.datetime.now())\n\t\tdate_last_maint = parser.parse(str_date).strftime(\"%Y%m%d\")\n\t\ttime_last_maint = parser.parse(str_date).strftime(\"%H%M%S\")\n\t\tprog_last_maint = \"STOCK_GVI\"\n\t\t\n\t\t#print(comp_id + \" \" + comp_name + \" \" + str(price) + \"\\n\")\n\t\t\n\t\t#檢查是否已經在榜內清單中\n\t\tsqlstr = \"select PREV_RANK, REC_DATE from STOCK_GVI \"\n\t\tsqlstr += \"where COMP_ID = '\" + comp_id + \"'\"\n\t\t\n\t\t#print(sqlstr)\n\t\tcursor = conn.execute(sqlstr)\n\t\tresult = cursor.fetchone()\n\t\t\n\t\tif result is None:\n\t\t\tis_existed = \"N\"\n\t\telse:\n\t\t\tis_existed = \"Y\"\n\t\t\t\n\t\t\tif rank > result[0]:\n\t\t\t\tstatus = \"DOW\"\n\t\t\telif rank == result[0]:\n\t\t\t\tstatus = \"REM\"\n\t\t\telse:\n\t\t\t\tstatus = \"UPP\"\n\t\t\t\n\t\t\trec_date = result[1]\n\t\t\n\t\t#關閉cursor\n\t\tcursor.close()\n\t\t\n\t\t#計算各項績效值\n\t\t#RATE_1 計算進榜至今漲跌幅\n\t\tsqlstr = \"select CLOSE from STOCK_QUO \"\n\t\tsqlstr += \"where \"\n\t\tsqlstr += \"QUO_DATE='\" + rec_date + \"' and \"\n\t\tsqlstr += \"SEAR_COMP_ID='\" + comp_id + \".TW' \"\n\t\t\n\t\tcursor = conn.execute(sqlstr)\n\t\tresult = cursor.fetchone()\n\t\t\n\t\tif result is not None:\n\t\t\trec_price = result[0]\n\t\telse:\n\t\t\trec_price = price\n\t\t\n\t\trate_1 = (price - rec_price) / rec_price * 100\n\t\t\n\t\t#關閉cursor\n\t\tcursor.close()\n\t\t\n\t\t#print(comp_id + \" \" + rec_date + \" \" + str(price) + \" \" + str(rec_price) + \" \" + str(rate_1) + \"\\n\")\n\t\t#sys.exit(\"test end...\")\n\t\t\n\t\t#RATE_2 計算近一周績效(固定往前推7天)\n\t\tstr_date = str(datetime.datetime.now())\n\t\tstr_date = parser.parse(str_date).strftime(\"%Y/%m/%d\")\n\t\tend_date = str_date\n\t\t\n\t\tdate_1 = datetime.datetime.strptime(end_date, \"%Y/%m/%d\")\n\t\tprev_date = date_1 + datetime.timedelta(days=-7)\n\t\tprev_date = str(prev_date)[0:10]\n\t\tprev_date = parser.parse(prev_date).strftime(\"%Y%m%d\")\n\t\t\n\t\tsqlstr = \"select CLOSE from STOCK_QUO \"\n\t\tsqlstr += \"where \"\n\t\tsqlstr += \"QUO_DATE<='\" + prev_date + \"' and \"\n\t\tsqlstr += \"SEAR_COMP_ID='\" + comp_id + \".TW' \"\n\t\tsqlstr += \"order by QUO_DATE desc \"\n\t\tsqlstr += \"limit 1 \"\n\t\t\n\t\tcursor = conn.execute(sqlstr)\n\t\tresult = cursor.fetchone()\n\t\t\n\t\tif result is not None:\n\t\t\tprev_price = result[0]\n\t\telse:\n\t\t\tprev_price = price\n\t\t\n\t\trate_2 = (price - prev_price) / prev_price * 100\n\t\t#print(comp_id + \" \" + prev_date + \" \" + str(price) + \" \" + str(prev_price) + \" \" + str(rate_2) + \"\\n\")\n\t\t\n\t\t#關閉cursor\n\t\tcursor.close()\n\t\t\n\t\t#RATE_3 計算近一個月績效(固定往前推30天)\n\t\tstr_date = str(datetime.datetime.now())\n\t\tstr_date = parser.parse(str_date).strftime(\"%Y/%m/%d\")\n\t\tend_date = str_date\n\t\t\n\t\tdate_1 = datetime.datetime.strptime(end_date, \"%Y/%m/%d\")\n\t\tprev_date = date_1 + datetime.timedelta(days=-30)\n\t\tprev_date = str(prev_date)[0:10]\n\t\tprev_date = parser.parse(prev_date).strftime(\"%Y%m%d\")\n\t\t\n\t\tsqlstr = \"select CLOSE from STOCK_QUO \"\n\t\tsqlstr += \"where \"\n\t\tsqlstr += \"QUO_DATE<='\" + prev_date + \"' and \"\n\t\tsqlstr += \"SEAR_COMP_ID='\" + comp_id + \".TW' \"\n\t\tsqlstr += \"order by QUO_DATE desc \"\n\t\tsqlstr += \"limit 1 \"\n\t\t\n\t\tcursor = conn.execute(sqlstr)\n\t\tresult = cursor.fetchone()\n\t\t\n\t\tif result is not None:\n\t\t\tprev_price = result[0]\n\t\telse:\n\t\t\tprev_price = price\n\t\t\n\t\trate_3 = (price - prev_price) / prev_price * 100\n\t\t#print(comp_id + \" \" + prev_date + \" \" + str(price) + \" \" + str(prev_price) + \" \" + str(rate_2) + \"\\n\")\n\t\t\n\t\t#關閉cursor\n\t\tcursor.close()\n\t\t\n\t\t#RATE_4 計算近半年績效(固定往前推180天)\n\t\tstr_date = str(datetime.datetime.now())\n\t\tstr_date = parser.parse(str_date).strftime(\"%Y/%m/%d\")\n\t\tend_date = str_date\n\t\t\n\t\tdate_1 = datetime.datetime.strptime(end_date, \"%Y/%m/%d\")\n\t\tprev_date = date_1 + datetime.timedelta(days=-180)\n\t\tprev_date = str(prev_date)[0:10]\n\t\tprev_date = parser.parse(prev_date).strftime(\"%Y%m%d\")\n\t\t\n\t\tsqlstr = \"select CLOSE from STOCK_QUO \"\n\t\tsqlstr += \"where \"\n\t\tsqlstr += \"QUO_DATE<='\" + prev_date + \"' and \"\n\t\tsqlstr += \"SEAR_COMP_ID='\" + comp_id + \".TW' \"\n\t\tsqlstr += \"order by QUO_DATE desc \"\n\t\tsqlstr += \"limit 1 \"\n\t\t\n\t\tcursor = conn.execute(sqlstr)\n\t\tresult = cursor.fetchone()\n\t\t\n\t\tif result is not None:\n\t\t\tprev_price = result[0]\n\t\telse:\n\t\t\tprev_price = price\n\t\t\n\t\trate_4 = (price - prev_price) / prev_price * 100\n\t\t#print(comp_id + \" \" + prev_date + \" \" + str(price) + \" \" + str(prev_price) + \" \" + str(rate_2) + \"\\n\")\n\t\t\n\t\t#關閉cursor\n\t\tcursor.close()\n\t\t\n\t\tif is_existed == \"N\":\n\t\t\tsqlstr = \"insert into STOCK_GVI (COMP_ID, COMP_NAME, STOCK_TYPE, EPS, BVPS, PRICE, \"\n\t\t\tsqlstr += \"PBR, SROE, ESTM_Y_ROE, GVI, REC_DATE, RANK, PREV_RANK, \"\n\t\t\tsqlstr += \"STATUS,DATE_LAST_MAINT,TIME_LAST_MAINT,PROG_LAST_MAINT\"\n\t\t\tsqlstr += \") values (\"\n\t\t\tsqlstr += \"'\" + comp_id + \"', \"\n\t\t\tsqlstr += \"'\" + comp_name + \"',\"\n\t\t\tsqlstr += \"'\" + stock_type + \"',\"\n\t\t\tsqlstr += str(eps) + \",\"\n\t\t\tsqlstr += str(bvps) + \",\"\n\t\t\tsqlstr += str(price) + \",\"\n\t\t\tsqlstr += str(pbr) + \",\"\n\t\t\tsqlstr += str(sroe) + \",\"\n\t\t\tsqlstr += str(estm_y_roe) + \",\"\n\t\t\tsqlstr += str(gvi) + \",\"\n\t\t\tsqlstr += \"'\" + rec_date + \"',\"\n\t\t\tsqlstr += str(rank) + \",\"\n\t\t\tsqlstr += \"0,\"\n\t\t\tsqlstr += \"'NEW',\"\n\t\t\tsqlstr += \"'\" + date_last_maint + \"',\"\n\t\t\tsqlstr += \"'\" + time_last_maint + \"',\"\n\t\t\tsqlstr += \"'\" + prog_last_maint + \"' \"\n\t\t\tsqlstr += \")\"\n\t\telse:\n\t\t\tsqlstr = \"update STOCK_GVI set \"\n\t\t\tsqlstr += \"EPS=\" + str(eps) + \", \"\n\t\t\tsqlstr += \"BVPS=\" + str(bvps) + \", \"\n\t\t\tsqlstr += \"PRICE=\" + str(price) + \", \"\n\t\t\tsqlstr += \"PBR=\" + str(pbr) + \", \"\n\t\t\tsqlstr += \"SROE=\" + str(sroe) + \", \"\n\t\t\tsqlstr += \"ESTM_Y_ROE=\" + str(estm_y_roe) + \", \"\n\t\t\tsqlstr += \"GVI=\" + str(gvi) + \", \"\n\t\t\tsqlstr += \"RANK=\" + str(rank) + \", \"\n\t\t\tsqlstr += \"STATUS='\" + status + \"', \"\n\t\t\tsqlstr += \"RATE_1=\" + str(rate_1) + \", \"\n\t\t\tsqlstr += \"RATE_2=\" + str(rate_2) + \", \"\n\t\t\tsqlstr += \"RATE_3=\" + str(rate_3) + \", \"\n\t\t\tsqlstr += \"RATE_4=\" + str(rate_4) + \", \"\n\t\t\tsqlstr += \"DATE_LAST_MAINT='\" + date_last_maint + \"', \"\n\t\t\tsqlstr += \"TIME_LAST_MAINT='\" + time_last_maint + \"', \"\n\t\t\tsqlstr += \"PROG_LAST_MAINT='\" + prog_last_maint + \"' \"\n\t\t\tsqlstr += \"where \"\n\t\t\tsqlstr += \"COMP_ID='\" + comp_id + \"' \"\t\t\t\n\t\t\t\n\t\ttry:\n\t\t\t#print(sqlstr + \"\\n\")\n\t\t\tconn.execute(sqlstr)\n\t\texcept sqlite3.Error as er:\n\t\t\tcommit_flag = \"N\"\n\t\t\tprint(sqlstr + \"\\n\")\n\t\t\tprint(\"process STOCK_GVI error er=\" + er.args[0] + \"\\n\")\n\t\t\t\n\t\tcnt += 1\n\t\n\tif commit_flag == \"Y\":\n\t\tconn.commit()\n\telse:\n\t\tconn.execute(\"rollback\")\n\n############################################################################\n# Main #\n############################################################################\nprint(\"Executing STOCK_GVI_V2...\")\n\ndt = datetime.datetime.now()\nstr_date = parser.parse(str(dt)).strftime(\"%Y%m%d\")\nprint(str_date)\n\n#for 手動跑\n#str_date = \"20170124\"\n\n#建立資料庫連線\nconn = sqlite3.connect(\"market_price.sqlite\")\n\nsqlstr = \"SELECT a.SEAR_COMP_ID, b.COMP_ID, a.CLOSE, b.COMP_NAME, b.STOCK_TYPE \"\nsqlstr += \"from STOCK_QUO a, STOCK_COMP_LIST b \"\nsqlstr += \"where \"\nsqlstr += \"a.QUO_DATE = '\" + str_date + \"' AND \"\nsqlstr += \"a.SEAR_COMP_ID = b.SEAR_COMP_ID \"\nsqlstr += \"ORDER BY a.SEAR_COMP_ID \"\n#sqlstr += \"limit 100 \"\n\n#print(sqlstr)\ncursor = conn.execute(sqlstr)\nresult = cursor.fetchall()\n\nre_len = len(result)\nif re_len > 0:\n\tls_gvi = []\n\tfor row in result:\n\t\tsear_comp_id = row[0]\n\t\tcomp_id = row[1]\n\t\tprice = row[2]\n\t\tcomp_name = row[3]\n\t\tstock_type = row[4]\n\t\t\n\t\t#讀取EPS(資料來源是年累計值,因此要扣掉前一期,取得單季EPS)\n\t\tsqlstr = \"select EPS from MOPS_YQ \"\n\t\tsqlstr += \"where COMP_ID = '\" + comp_id + \"' \"\n\t\tsqlstr += \"order by YYYY || QQ desc \"\n\t\tsqlstr += \"limit 2 \"\n\t\t\n\t\tcursor2 = conn.execute(sqlstr)\n\t\tresult2 = cursor2.fetchall()\n\t\tre_len2 = len(result2)\n\t\t\n\t\tk = 1\n\t\teps1 = 0\n\t\teps0 = 0\n\t\tif re_len2 > 0:\n\t\t\tfor row2 in result2:\n\t\t\t\tif k == 1:\n\t\t\t\t\teps1 = row2[0]\n\t\t\t\telif k == 2:\n\t\t\t\t\teps0 = row2[0]\n\t\t\t\tk += 1\n\t\t\t\t\n\t\t\t#計算單季EPS\n\t\t\teps = eps1 - eps0\n\t\telse:\n\t\t\teps = 0\n\t\t\n\t\t#關閉cursor\n\t\tcursor2.close()\n\t\t\n\t\t#讀取BVPS\n\t\tsqlstr = \"select BVPS from MOPS_YQ \"\n\t\tsqlstr += \"where COMP_ID = '\" + comp_id + \"' \"\n\t\tsqlstr += \"order by YYYY || QQ desc \"\n\t\tsqlstr += \"limit 1 \"\n\t\t\n\t\tcursor2 = conn.execute(sqlstr)\n\t\tresult2 = cursor2.fetchone()\n\t\t\n\t\tif result2 is not None:\n\t\t\tbvps = result2[0]\n\t\telse:\n\t\t\tbvps = 0\n\t\t\n\t\t#關閉cursor\n\t\tcursor2.close()\n\t\t\n\t\t#print(sear_comp_id + \" \" + comp_id + \" \" + str(price) + \" \" + comp_name + \" \" + str(eps) + \" \" + str(bvps) + \"\\n\")\n\t\tif price != 0:\n\t\t\tbop = bvps / price \t#淨值股價比\n\t\telse:\n\t\t\tbop = 0\n\t\t\n\t\tif bvps != 0:\n\t\t\tpb = price / bvps \t#股價淨值比\n\t\telse:\n\t\t\tpb = 0\n\t\t\n\t\tif bvps != 0:\n\t\t\tsroe = eps / bvps \t#單季ROE\n\t\telse:\n\t\t\tsroe = 0\n\t\t\n\t\t#預估年ROE\n\t\t#(原書上有做判斷,若單季ROE超過5%以上,\n\t\t# 則以5%作為計算值,這部分我沒有照書上的設定)\n\t\t#estm_y_roe = 4 * min(sroe, 0.05)\n\t\testm_y_roe = 4 * sroe\n\t\t\n\t\t#GVI指標計算\n\t\tgvi = bop * (1 + estm_y_roe)**5\n\t\t\n\t\t#計算完的結果,塞到list\n\t\tdata = [comp_id, comp_name, stock_type, price, eps, bvps, pb, sroe, estm_y_roe, gvi]\n\t\tls_gvi.append(data)\n\t\t#print(sear_comp_id + \" \" + comp_id + \" \" + str(price) + \" \" + comp_name + \" \" + str(eps) + \" \" + str(bvps) + \" \" + str(gvi) + \"\\n\")\n\t\t\n\tdf = pd.DataFrame(ls_gvi, columns = ['股票編號', '股票名稱', '上市櫃別', '股價', 'EPS','BVPS','股價淨值比','季ROE','估計年ROE','GVI'])\n\tdf = df.sort_values(by=['GVI'], ascending=[False])[1:101]\n\t#print(df)\n\t\n\t\"\"\"\n\t#計算結果直接寫入excel檔\n\tfile_name = 'STOCK_GVI_' + str_date + '.xlsx'\n\twriter = pd.ExcelWriter(file_name, engine='xlsxwriter')\n\tdf.to_excel(writer, sheet_name='GVI', index=False)\n\twriter.save()\n\t\"\"\"\n\t\n\t#運算結果寫入db\n\tstore_db(df, str_date)\n\t\nelse:\n\tprint(str_date + \" no data....\")\n\n#關閉cursor\ncursor.close()\n\n#關閉資料庫連線\nconn.close\n\nprint(\"End of prog...\")","sub_path":"STOCK_GVI_V2.py","file_name":"STOCK_GVI_V2.py","file_ext":"py","file_size_in_byte":10711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"57315617","text":"#!/usr/bin/env python\n#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-\n\nimport os.path as path\nfrom bes.testing.unit_test import unit_test\nfrom bes.build.artifact_descriptor import artifact_descriptor as AD\nfrom bes.build.build_target import build_target as BT\nfrom bes.build.package_descriptor import package_descriptor as PD\nfrom bes.build.requirement_list import requirement_list as RL\nfrom rebuild._testing.fake_package_recipes import fake_package_recipes as RECIPES\nfrom rebuild._testing.artifact_manager_tester import artifact_manager_tester as AMT\n\nclass test_artifact_manager_tester(unit_test):\n\n #DEBUG = True\n\n def test_publish_new_version_manual(self):\n t = AMT(recipes = RECIPES.TWO_APPLES)\n tmp_tarball1 = t.create_package('apple;1.2.3;1;0;linux;release;x86_64;ubuntu;18;')\n t.am.publish(tmp_tarball1.filename, False, tmp_tarball1.metadata)\n self.assertEqual( [\n AD.parse('apple;1.2.3;1;0;linux;release;x86_64;ubuntu;18;'),\n ], t.am.list_all_by_descriptor(None) )\n\n tmp_tarball2 = t.create_package('apple;1.2.4;1;0;linux;release;x86_64;ubuntu;18;')\n t.am.publish(tmp_tarball2.filename, False, tmp_tarball2.metadata)\n self.assertEqual( [\n AD.parse('apple;1.2.3;1;0;linux;release;x86_64;ubuntu;18;'),\n AD.parse('apple;1.2.4;1;0;linux;release;x86_64;ubuntu;18;'),\n ], t.am.list_all_by_descriptor(None) )\n\n def test_publish_new_version_easier(self):\n recipes1 = '''\nfake_package aflatoxin 1.0.9 0 0 linux release x86_64 ubuntu 18 none\n'''\n recipes2 = '''\nfake_package aflatoxin 1.0.10 0 0 linux release x86_64 ubuntu 18 none\n'''\n\n t = AMT()\n x = t.add_recipes(recipes1)\n self.assertEqual( [\n ], t.am.list_all_by_descriptor(None) )\n \n x = t.publish(recipes1)\n self.assertEqual( [\n AD.parse('aflatoxin;1.0.9;0;0;linux;release;x86_64;ubuntu;18;'),\n ], t.am.list_all_by_descriptor(None) )\n\n t.add_recipes(recipes2)\n self.assertEqual( [\n AD.parse('aflatoxin;1.0.9;0;0;linux;release;x86_64;ubuntu;18;'),\n ], t.am.list_all_by_descriptor(None) )\n\n t.publish(recipes2)\n self.assertEqual( [\n AD.parse('aflatoxin;1.0.9;0;0;linux;release;x86_64;ubuntu;18;'),\n AD.parse('aflatoxin;1.0.10;0;0;linux;release;x86_64;ubuntu;18;'),\n ], t.am.list_all_by_descriptor(None) )\n\nif __name__ == '__main__':\n unit_test.main()\n","sub_path":"tests/lib/_rebuild_testing/test_artifact_manager_tester.py","file_name":"test_artifact_manager_tester.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"603025968","text":"# 283. Move Zeroes.\n# Given an array nums, write a function to move all 0's to the end of it\n# while maintaining the relative order of the non-zero elements.\n\n# Example:\n# Input: [0,1,0,3,12]\n# Output: [1,3,12,0,0]\n# Note:\n\n# You must do this in-place without making a copy of the array.\n# Minimize the total number of operations.\n\n# My solution: using two pointers, i.e., fast pointer and slow pointer to traverse the array.\nclass Solution:\n def moveZeroes(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n # # My method: using fast pointer and slow pointer to remove zeroes.\n # i = 0\n # for num in nums:\n # if num != 0:\n # nums[i] = num\n # i += 1\n # for j in range(i,len(nums)):\n # nums[j] = 0\n\n # Optimal method: swapping.\n slow_p = 0\n for fast_p in range(len(nums)):\n if nums[fast_p] != 0:\n # Swap a and b in python.\n nums[slow_p], nums[fast_p] = nums[fast_p], nums[slow_p]\n slow_p += 1\n","sub_path":"Week_01/Leetcode_283_Move Zeroes.py","file_name":"Leetcode_283_Move Zeroes.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"291677754","text":"#script example to transform scale of data, this targets to transform I-V data with different Vg scale\n#Juan Pablo Duarte\n\nrootfolder = '/home/juan/research/intern2015'\n\n#indicate path for folders containing required classes\nimport sys\nsys.path.insert(0, rootfolder+'/classesintern')\n\nimport matplotlib.pyplot as plt\nimport measurementtests as mt\n\npathfolder = '/home/juan/research/intern/data/'\npathdatafile = 'KL35LC12-S0118_16FET05Idgs@Vg51d3.txt'\npathdatafileout = 'KL35LC12-S0118_16FET05Idgs@Vg51d3SCALED.txt'\n\n###################################creating class mt\nM1 = mt.mt()\n\n####setting up parameters for scale transformation\nM1.updateparameter('var_scale_ref','Vg`') #ex: Vg, then data is y=f(Vg)\nM1.updateparameter('var_dependent',['Ig','Id','Is']) # ex: Id, Ig, Is\nM1.updateparameter('var_fixed',['Vd`'])# ex: Vd\n\n#scale reference: initial, final and delta values\nM1.updateparameter('var_scale_ref_init',-5.000e-01)\nM1.updateparameter('var_scale_ref_final',1.0)\nM1.updateparameter('var_scale_ref_delta',0.035)\nM1.convertscale(pathfolder + pathdatafile,pathfolder+pathdatafileout)\n\n##################################plot of both results\nM1.updateparameter('filetype','SAS')#update format type of data to be input\n#plot\nM1.updateparameter('symbol','o') \nM1.updateparameter('markersize',5)\nM1.updateparameter('color','r')\nM1.plotfiledata(pathfolder + pathdatafile,'Vg`','Id',1)\n\nM1.updateparameter('symbol','o') \nM1.updateparameter('markersize',5)\nM1.updateparameter('color','b')\nM1.plotfiledata(pathfolder + pathdatafileout,'Vg`','Id',1)\n\nplt.show() \n\n\n\n","sub_path":"userexample/transform_Vgscale_example.py","file_name":"transform_Vgscale_example.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"129705759","text":"from annotypes import Anno, Array, Sequence, Union\nfrom enum import Enum\n\nfrom malcolm.core import Part, PartRegistrar, ChoiceMeta, APartName, \\\n AMetaDescription\nfrom ..util import set_tags, AWriteable, AConfig, AGroup, AWidget\n\n\nwith Anno(\"Possible choices for this attribute\"):\n AChoices = Array[str]\nwith Anno(\"Initial value of the created attribute\"):\n AValue = str\nUChoices = Union[AChoices, Sequence[Enum], Sequence[str], str]\n\n# Pull re-used annotypes into our namespace in case we are subclassed\nAPartName = APartName\nAMetaDescription = AMetaDescription\nAWriteable = AWriteable\nAConfig = AConfig\nAGroup = AGroup\nAWidget = AWidget\n\n\nclass ChoicePart(Part):\n \"\"\"Create a single choice Attribute on the Block\"\"\"\n def __init__(self,\n name, # type: APartName\n description, # type: AMetaDescription\n choices, # type: UChoices\n value, # type: AValue\n writeable=False, # type: AWriteable\n config=1, # type: AConfig\n group=None, # type: AGroup\n widget=None, # type: AWidget\n ):\n # type: (...) -> None\n super(ChoicePart, self).__init__(name)\n meta = ChoiceMeta(description, choices)\n set_tags(meta, writeable, config, group, widget)\n self.attr = meta.create_attribute_model(value)\n self.writeable_func = self.attr.set_value if writeable else None\n\n def setup(self, registrar):\n # type: (PartRegistrar) -> None\n registrar.add_attribute_model(self.name, self.attr, self.writeable_func)\n","sub_path":"malcolm/modules/builtin/parts/choicepart.py","file_name":"choicepart.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"342494893","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nfrom urllib import request as ur\n\nfrom flask import render_template, request\nfrom aip import AipImageClassify\n\nfrom car_detect import app\nfrom config import HAOSERVICE_KEY, APP_ID, API_KEY, SECRET_KEY\nfrom car_detect.model import CarInfo\n\n# 数据库初始化操作\n\"\"\"\n@app.route('/init')\ndef init():\n # 删除旧表\n db.drop_all()\n # 创建新表\n db.create_all()\n # 插入获得json数据\n import json\n with open('car.json', 'r', encoding='utf-8') as f:\n car_data = json.load(f)\n car_info_list = []\n for car_brand_info in car_data['result']:\n car_brand_name = car_brand_info['N']\n car_brand_id = car_brand_info['I']\n print('车牌:%s,车牌ID:%s' % (car_brand_name, car_brand_id))\n for car_series_info in car_brand_info['List']:\n car_series_name = car_series_info['N']\n car_series_id = car_series_info['I']\n print('\\t车系:%s,车系ID:%s' % (car_series_name, car_series_id))\n for car_type_info in car_series_info['List']:\n car_type_name = car_type_info['N']\n car_type_id = car_type_info['I']\n print('\\t\\t车型:%s,车型ID:%s' % (car_type_name, car_type_id))\n # 处理字符串拿出索引字符串\n if car_brand_name in car_type_name:\n index = car_type_name.replace('·', '')\n else:\n index = car_brand_name.replace('·', '') + car_type_name.replace('·', '')\n car_info = CarInfo(\n brand_id=car_brand_id, brand_name=car_brand_name,\n series_id=car_series_id, series_name=car_series_name,\n type_id=car_type_id, type_name=car_type_name,\n index=index,\n )\n car_info_list.append(car_info)\n print(car_info_list)\n db.session.add_all(car_info_list)\n # 提交修改\n db.session.commit()\n return '初始化成功'\n\"\"\"\n\n\n# 首页(搜索)\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'GET':\n return render_template('index.html')\n else:\n img = request.files.get('img')\n if not img: # 没有上传图片则取url\n img_url = request.form.get('img_url')\n try:\n img = ur.urlopen(img_url)\n except Exception:\n return render_template('index.html', msg=\"请上传文件或URL地址\")\n # 上传到百度接口\n try:\n client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY)\n options = {'top_num': 1, 'baike_num': 5}\n car_info = client.carDetect(img.read(), options)\n if car_info['result'][0]['name'] == '非车类':\n return render_template('index.html', msg=\"未识别到车类\")\n car_index_name = car_info['result'][0]['name']\n print(car_index_name)\n except Exception:\n return render_template('index.html', msg=\"接口繁忙,请稍后再试\")\n try:\n cars_info = CarInfo.query.filter(CarInfo.index.ilike('%' + car_index_name + '%'))\n except Exception:\n cars_info = None\n if cars_info.count() != 0:\n return render_template('index.html', cars_info=cars_info)\n else:\n return render_template('index.html', msg=\"未识别到车类\")\n\n\n# 车型详情页\n@app.route('/typedetail/')\ndef typetail(car_type_id):\n index = request.args.get('index')\n try:\n response = ur.urlopen(\n 'http://apis.haoservice.com/lifeservice/car/GetModel/?id=' +\n car_type_id + '&key=' + HAOSERVICE_KEY + '&paybyvas=false'\n )\n type_result = eval(response.read().decode('utf-8'))['result']['List']\n except Exception:\n return render_template('typedetail.html', msg=\"非常抱歉,暂无此车型信息\")\n return render_template('typedetail.html', type_result=type_result, index=index)\n\n\n# 配置详情页\n@app.route('/detail/')\ndef detail(car_id):\n try:\n response = ur.urlopen(\n 'http://apis.haoservice.com/lifeservice/car?id=' +\n car_id + '&key=' + HAOSERVICE_KEY + '&paybyvas=false'\n )\n details = eval(response.read().decode('utf-8'))['result']\n except Exception:\n return render_template('detail.html', msg='非常抱歉,暂无此车型信息')\n index = request.args.get('index')\n price = request.args.get('price')\n return render_template('detail.html', details=details, index=index, price=price)\n","sub_path":"car_detect/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":4651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"288631339","text":"\"\"\"\r\nCreated on Wed Jul 3 13:24:41 2019\r\n\r\n@author: PC\r\n\"\"\"\r\n\r\nfrom torch.nn import Module, Sequential \r\nfrom torch.nn import Conv3d, ConvTranspose3d, BatchNorm3d, MaxPool3d, AvgPool1d\r\nfrom torch.nn import ReLU, Sigmoid\r\nfrom torch import nn\r\nimport torch\r\nimport torch.nn.functional as F\r\n\r\nclass Conv3D_Block(Module):\r\n \r\n def __init__(self, inp_feat, out_feat, kernel=3, stride=1, padding=1, dilation=1, residual=None):\r\n \r\n super(Conv3D_Block, self).__init__()\r\n\r\n self.conv1 = Sequential(\r\n Conv3d(inp_feat, out_feat, kernel_size=kernel, \r\n stride=stride, padding=padding, dilation=dilation, bias=True),\r\n BatchNorm3d(out_feat),\r\n ReLU())\r\n\r\n self.conv2 = Sequential(\r\n Conv3d(out_feat, out_feat, kernel_size=kernel, \r\n stride=stride, padding=padding, dilation=dilation, bias=True),\r\n BatchNorm3d(out_feat))\r\n \r\n \r\n \r\n self.residual = residual\r\n self.relu = ReLU()\r\n if self.residual is not None:\r\n self.residual_upsampler = Sequential(\r\n Conv3d(inp_feat, out_feat, kernel_size=1, stride=stride, bias=False),\r\n BatchNorm3d(out_feat))\r\n\r\n def forward(self, x):\r\n \r\n res = x\r\n\r\n if not self.residual:\r\n return self.conv2(self.conv1(x))\r\n else:\r\n return self.relu(self.conv2(self.conv1(x)) + self.residual_upsampler(res))\r\n\r\nclass Conv3D_Block0(Module):\r\n \r\n def __init__(self, inp_feat, out_feat, kernel=3, stride=1, padding=1, residual=None):\r\n \r\n super(Conv3D_Block0, self).__init__()\r\n\r\n self.conv = Sequential(\r\n Conv3d(inp_feat, out_feat, kernel_size=kernel, \r\n stride=stride, padding=padding, bias=True),\r\n BatchNorm3d(out_feat),\r\n ReLU())\r\n\r\n \r\n self.residual = residual\r\n self.relu = ReLU()\r\n if self.residual is not None:\r\n self.residual_upsampler = Sequential(\r\n Conv3d(inp_feat, out_feat, kernel_size=1, stride=stride, bias=False),\r\n BatchNorm3d(out_feat))\r\n\r\n def forward(self, x):\r\n \r\n res = x\r\n print(self.residual_upsampler(res).size())\r\n if not self.residual:\r\n return self.conv1(x)\r\n else:\r\n return self.relu(self.conv(x) + self.residual_upsampler(res))\r\n \r\ndef Maxpool3D_Block():\r\n \r\n pool = MaxPool3d(kernel_size=2, stride=2, padding=0)\r\n \r\n return pool \r\n \r\n\r\n \r\nclass ClassifyNet(Module):\r\n def __init__(self, num_feat=[16,32,64,128,256], residual='conv'):\r\n super(ClassifyNet, self).__init__()\r\n \r\n #Encoder process\r\n self.conv1_0 = Conv3D_Block(1, num_feat[0], residual=residual)\r\n self.conv1_1 = Conv3D_Block(1, num_feat[0], padding=2, dilation=2, residual=residual)\r\n self.pool1 = Maxpool3D_Block()\r\n self.conv2_0 = Conv3D_Block(num_feat[0]*2, num_feat[1], residual=residual)\r\n self.conv2_1 = Conv3D_Block(num_feat[0]*2, num_feat[1], padding=2, dilation=2, residual=residual)\r\n self.pool2 = Maxpool3D_Block()\r\n self.conv3_0 = Conv3D_Block(num_feat[1]*2, num_feat[2], residual=residual)\r\n self.conv3_1 = Conv3D_Block(num_feat[1]*2, num_feat[2], padding=2, dilation=2, residual=residual)\r\n self.pool3 = Maxpool3D_Block()\r\n self.conv4_0 = Conv3D_Block(num_feat[2]*2, num_feat[3], residual=residual)\r\n # self.conv4_1 = Conv3D_Block(num_feat[3], num_feat[3], padding=2, dilation=2,residual=residual)\r\n self.pool4 = Maxpool3D_Block()\r\n self.conv5 = Conv3D_Block(num_feat[3], num_feat[4], residual=residual)\r\n# self.conv6 = Conv3D_Block(num_feat[4], num_feat[4], residual=residual)\r\n# self.drop = nn.Dropout(p = 0.5)\r\n\r\n self.fc1 = nn.Linear(num_feat[4]*2*2*2,2)\r\n# self.fc2 = nn.Linear(512,2)\r\n# self.fc3 = nn.Linear(256,2)\r\n self.Relu = nn.ReLU()\r\n\r\n\r\n def forward(self, x):\r\n \r\n down_1_0 = self.conv1_0(x)\r\n down_1_1 = self.conv1_1(x)\r\n down_1 = torch.cat([down_1_0,down_1_1],dim=1)\r\n pool_1 = self.pool1(down_1)\r\n down_2_0 = self.conv2_0(pool_1)\r\n down_2_1 = self.conv2_1(pool_1)\r\n down_2 = torch.cat([down_2_0,down_2_1],dim=1)\r\n pool_2 = self.pool2(down_2)\r\n down_3_0 = self.conv3_0(pool_2)\r\n down_3_1 = self.conv3_1(pool_2)\r\n down_3 = torch.cat([down_3_0,down_3_1],dim=1)\r\n pool_3 = self.pool3(down_3)\r\n down_4_0 = self.conv4_0(pool_3)\r\n# down_4_1 = self.conv4_1(down_4_0)\r\n pool_4 = self.pool4(down_4_0)\r\n down_5 = self.conv5(pool_4) \r\n\r\n\r\n# down_6 = self.conv6(down_5) \r\n view1 = down_5.view(down_5.size(0),-1)\r\n# view1 = self.drop(view1)\r\n# fc1 = self.Relu(self.fc1(view1))\r\n# fc1 = self.drop(fc1)\r\n# out = F.avg_pool3d(down_5, 4)\r\n# out = out.view(out.size(0), -1)\r\n out = self.fc1(self.Relu(view1))\r\n \r\n return out\r\n","sub_path":"code/DNN_Task2.py","file_name":"DNN_Task2.py","file_ext":"py","file_size_in_byte":5275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"277307819","text":"import operator\nimport datetime\nimport time\nimport json\n\nfrom routes.models import Route\n\nfrom django.contrib.gis.geos import LineString, Point\n\nfrom fitparse import FitFile\nfrom polyline.codec import PolylineCodec\n\n\nclass AnalytseFile():\n def Validate(self, fileInMemory, rideId):\n AttemptCoordsOne = []\n AttemptCoordsTwo = []\n raceCoords = []\n fitStartTime = None\n\n fitfile = FitFile(fileInMemory)\n\n for session in fitfile.get_messages('session'):\n sessionVals = session.get_values()\n fitStartTime = sessionVals['start_time']\n\n ride = Route.objects.get(pk=rideId)\n\n race = ride.polyline\n DecodedRace = PolylineCodec().decode(race)\n\n for coord in DecodedRace:\n raceCoords.append((coord[1], coord[0]))\n\n raceRoute = LineString(raceCoords, srid=4326)\n\n for record in fitfile.get_messages('record'):\n lat = record.get_value('position_lat')\n lng = record.get_value('position_long')\n time = record.get_value('timestamp')\n speed = record.get_value('speed')\n distance = record.get_value('distance')\n elevation = record.get_value('altitude')\n\n if lng is not None or lat is not None:\n nlng = lng * (180.0/2**31)\n nlat = lat * (180.0/2**31)\n AttemptCoordsOne.append((nlng, nlat))\n AttemptCoordsTwo.append({'distance': distance, 'time': time, 'speed': speed, 'elevation': elevation, 'position': (nlng, nlat)})\n\n rideGeom = LineString(AttemptCoordsOne, srid=4326)\n rideGeomBuffer = rideGeom.buffer(0.0005)\n\n # First check if the actual ride intersects with the\n # set route and return the intersected route as a linestring\n # in case the rider has taken a wrong turn\n # and had to go back on themselves\n CheckIntersects = rideGeomBuffer.intersection(raceRoute)\n\n # Now create a buffer geom of the set route\n # and check whether it contains the intersected route\n racerouteGeomBuffer = raceRoute.buffer(0.0005)\n CheckMatch = racerouteGeomBuffer.contains(CheckIntersects)\n\n if CheckMatch is True:\n ClosestPoints = []\n ClosestLists = []\n\n raceBuffer = raceRoute.buffer(0.0001)\n refPoints = [(float(ride.start_long), float(ride.start_lat)), (float(ride.finish_long), float(ride.finish_lat))]\n\n for ref in refPoints:\n proximityPoint = None\n RacePointGeom = Point(ref, srid=4326)\n numbers = [self.distance(AttemptCoord, RacePointGeom) for AttemptCoord in AttemptCoordsTwo]\n sortedList = sorted(numbers, key=operator.itemgetter(1))\n\n for s in sortedList:\n sGeom = Point(s[0], srid=4326)\n CheckIsInRoute = raceBuffer.contains(sGeom)\n if CheckIsInRoute is True:\n proximityCheck = self.pointTooClose(ref, s[0])\n if proximityCheck is True:\n sortedList.remove(s)\n else:\n proximityPoint = s\n break\n\n ClosestLists.append(sortedList)\n ClosestPoints.append(proximityPoint)\n\n # Creating a json blob with all the interesting gps data\n json_data = []\n for json_position in AttemptCoordsTwo:\n json_point = Point(json_position['position'], srid=4326)\n CheckJsonIsInRoute = raceBuffer.contains(json_point)\n\n if CheckJsonIsInRoute is True:\n obj = self.GenerateJsonObject(json_position)\n json_data.append(obj)\n\n # Conditional to handle when ride goes back on itself\n if ClosestPoints[0][2] > ClosestPoints[1][2]:\n return 'reverse'\n else:\n TimeDiff = ClosestPoints[1][2] - ClosestPoints[0][2]\n\n avRaceSpeed = self.CalculateAverageRaceSpeed(TimeDiff, ride.distance)\n startTimeCheck = self.checkDiscrepencies(ClosestPoints, TimeDiff, refPoints[0], 'start', avRaceSpeed)\n FinalTime = self.checkDiscrepencies(ClosestPoints, startTimeCheck, refPoints[1], 'finish', avRaceSpeed)\n totalAvSpeed = self.CalculateAverageRaceSpeed(FinalTime, ride.distance)\n av_speed_converted = (totalAvSpeed * 60 * 60)/1000 # Convert meters per second to km per hour\n return {'duration': FinalTime, 'start_time': fitStartTime, 'average_speed': round(av_speed_converted, 1), 'data': json.dumps(json_data)}\n else:\n return False\n\n def GenerateJsonObject(self, position):\n obj = {}\n obj['latitude'] = position['position'][0]\n obj['longitude'] = position['position'][1]\n obj['time'] = position['time'].strftime('%Y-%m-%d %H:%M:%S')\n obj['speed'] = (position['speed'] * 60 * 60)/1000\n obj['elevation'] = position['elevation']\n\n return obj\n\n def CalculateAverageRaceSpeed(self, time, distance):\n d = distance*1000\n avSpeed = d/time.total_seconds()\n return avSpeed\n\n def pointTooClose(self, refPoint, closestPoint):\n refGeom = Point(refPoint, srid=4326).transform(3857, clone=True)\n closestGeom = Point(closestPoint, srid=4326).transform(3857, clone=True)\n\n dist = refGeom.distance(closestGeom)\n if dist < 20:\n return True\n else:\n return False\n\n def distance(self, point, ref):\n p = Point(point['position'], srid=4326)\n dist = p.distance(ref)\n resp = (point['position'], dist, point['time'], point['speed'], point['elevation'])\n return resp\n\n def checkDiscrepencies(self, ClosestPoints, TimeDiff, refPoints, flag, avRaceSpeed):\n # Start/End point of race\n A = Point(refPoints, srid=4326).transform(3857, clone=True)\n\n # The closest coordinate to the start/end point\n if flag == 'start':\n B = Point(ClosestPoints[0][0], srid=4326).transform(3857, clone=True)\n else:\n B = Point(ClosestPoints[1][0], srid=4326).transform(3857, clone=True)\n\n # Work out distance between the start/end point and its's closest point\n ABd = A.distance(B)\n\n # Time taken to ride between start/end point and the closest point\n startToClosestTimeTaken = ABd/avRaceSpeed\n\n # Round up time taken\n secs = int(round(startToClosestTimeTaken))\n return TimeDiff + datetime.timedelta(seconds=secs)\n","sub_path":"challenges/fitFileValidator.py","file_name":"fitFileValidator.py","file_ext":"py","file_size_in_byte":6665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"15486149","text":"import pandas as pd\nimport os\nimport imp\nimport re\n\nclass Context(object):\n pass\n\nclass TriggerSolar(object):\n def __init__(self, magnetModules, contexts, infix):\n self.magnets = magnetModules\n self.contexts = contexts\n self.infix = infix\n\n def setAsset(self, assets):\n for c in self.contexts:\n c.assets = assets\n\n def eval(self, stock):\n try:\n b = [module.eval(stock, self.contexts[idx]\n ) for idx, module in enumerate(self.magnets)]\n except:\n return False\n \n operators = re.findall('[&|]', self.infix)\n ops = ''\n for idx, op in enumerate(operators):\n ops += str(b[idx]) + op\n ops += str(b[len(operators)])\n\n\n ret = eval(ops)\n return ret\n\nclass EvalSolar(object):\n def __init__(self, magnetModules, contexts, infix, numStock=50):\n self.magnets = magnetModules\n self.contexts = contexts\n self.infix = infix\n self.numStock = numStock\n\n orbitStrs = self.infix.split('|')\n self.orbitIdxSet = []\n\n tail = 0\n for s in orbitStrs:\n n = len(s.split('&'))\n self.orbitIdxSet.append([i for i in range(tail, n)])\n tail += n\n\n def eval(self, stocks):\n ret = set()\n for idxs in self.orbitIdxSet:\n stockVal = [(sid, self.evalOrbitForSingleStock(stock, idxs)\n ) for sid, stock in stocks.items()]\n\n stockVal = filter(lambda r: r[1] != False, stockVal)\n stockVal = sorted(stockVal, key=lambda val: -val[1])\n #print(stockVal)\n \n ret |= set(stockVal[:self.numStock])\n return [d[0] for d in ret]\n \n def evalOrbitForSingleStock(self, stock, idxs):\n\n ret = 0\n for idx in idxs:\n try:\n b = self.magnets[idx].eval(stock, self.contexts[idx])\n except:\n b = False\n if isinstance(b, (float, int)):\n ret += b\n elif isinstance(b, bool) and b[cnt] == False:\n return False\n else:\n assert(0)\n return ret\n\n\nclass SolarFactory (object):\n\n def __init__(self, magnetManager):\n self.magnetManager = magnetManager\n\n def parse(self, s):\n try:\n strs = s.split('_')\n assert(len(strs) == 3)\n except:\n print('the 3 sub-string should be seperated with _')\n \n modules0, contexts0 = self.buildSolar(strs[0])\n modules1, contexts1 = self.buildSolar(strs[1])\n modules2, contexts2 = self.buildSolar(strs[2])\n \n evalSolar = EvalSolar(modules0, contexts0, strs[0])\n buySolar = TriggerSolar(modules1, contexts1, strs[1])\n sellSolar = TriggerSolar(modules2, contexts2, strs[2])\n\n return evalSolar, buySolar, sellSolar\n\n def buildSolar(self, s):\n magnetArgs = re.findall('[^&|]+', s)\n modules = self.findModules(magnetArgs)\n contexts = self.buildContext(magnetArgs)\n return modules, contexts\n \n def findModules(self, magnetArgs):\n magnetIDs = [s.split('-')[0] for s in magnetArgs]\n return [self.magnetManager.id2Module(mid) for mid in magnetIDs]\n\n def buildContext(self, magnetArgs):\n args = [s.split('-')[1:] for s in magnetArgs]\n contexts = []\n\n for a in args:\n context = Context()\n for es in a:\n e = es.split('=')\n context.__setattr__(e[0], e[1])\n contexts.append(context)\n\n return contexts\n","sub_path":"packages/simulator/SolarFactory.py","file_name":"SolarFactory.py","file_ext":"py","file_size_in_byte":3628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"528798260","text":"# %load q03_get_toss_win_count/build.py\n#Default Imports\nimport numpy as np\nipl_matches_array =np.genfromtxt('data/ipl_matches_small.csv', dtype='|S50', skip_header=1, delimiter=',')\n\n\n#Your Solution\ndef get_toss_win_count(team):\n # condition\n c = ipl_matches_array[:,5].astype(str) == team\n # getting the team's winning of toss and then making a set of matches\n return len(set(ipl_matches_array[c][:,1]))\n\nget_toss_win_count('Mumbai Indians')\n\n","sub_path":"q03_get_toss_win_count/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"585528068","text":"t=int(input())\nfor ex in range(0,t):\n n=int(input())\n num=[int(i) for i in input().split(\" \")]\n a,b,c,d=-1,-1,-1,-1\n for i in range(0,len(num)-1):\n for j in range(i+1,len(num)):\n temp=num[i]+num[j]\n for p in range(i+1,len(num)-1):\n for q in range(p+1,len(num)):\n if temp==num[p]+num[q] and not (p==j or q==j):\n a,b,c,d=i,j,p,q\n break\n else:\n continue\n break\n else:\n continue\n break\n else:\n continue\n break\n if -1 in [a,b,c,d]:\n print(\"no pairs\")\n else:\n print(a,b,c,d)","sub_path":"Code/CodeRecords/2593/60787/291443.py","file_name":"291443.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"163103090","text":"import numpy as np\nimport cvxopt\n\n\n# Problem 1: Linear Regression\nclass LinearRegression(object):\n \"\"\"\n A linear regression model.\n\n Methods\n -------\n fit() : takes data and targets as input and trains the model with it.\n predict() : takes data as input and predicts the target values with the trained model.\n \"\"\"\n \n def __init__(self):\n super(LinearRegression, self).__init__()\n \n \n def costFunction(self, X, y, theta):\n return np.sum(np.power(((X @ theta.T) - y), 2)) / (2 * len(X))\n \n\n def fit(self, X, y):\n \"\"\"\n This function should train the model. By invoking this function, a class member variable\n containing the coefficients of the model will be filled based on the input data. These coefficients\n will be used in the predict() function to make predictions about unknown data.\n\n X: Data. A numpy array of dimensions (number of samples, number of features). These are real values.\n y: Targets. A numpy array of dimensions (number of samples,). These are real values.\n :return: The mean squared error for the input training data.\n \"\"\"\n self.W = np.linalg.inv(X.T @ X) @ X.T @ y\n return self.costFunction(X, y, self.W)\n \n\n def predict(self, X):\n \"\"\"\n This function should predict the target values using the parameters learned with the fit() function given the\n input test data.\n\n X: Data. A numpy array of dimensions (number of samples, number of features).\n\n :return: A numpy array of dimensions (number of samples,) that contains predicted targets for the input data X.\n \"\"\"\n return np.dot(X, self.W.T)\n\n\nclass LogisticRegression(object):\n \"\"\"\n A logistic regression model.\n\n Methods\n -------\n fit() : takes data and targets as input and trains the model with it.\n predict() : takes data as input and predicts the target values with the trained model.\n \"\"\"\n \n def __init__(self, learning_rate=0.01, iterations=8000):\n \"\"\"\n This is one way of hard coding the hyperparameters you found. You dont have to follow this conventions.\n However, calling LogisticrRegression() without any parameters must create a model loaded with your best hyperparameters.\n \"\"\"\n self.learning_rate = learning_rate\n self.iterations = iterations\n super(LogisticRegression, self).__init__()\n\n def sigmoid(self, x):\n return 1 / (1 + np.exp(-x))\n \n def costFunction(self, h, y):\n return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()\n \n def gradientDescent(self, X, y, theta):\n cost = []\n for i in range(self.iterations):\n h = self.sigmoid(np.dot(X, theta))\n theta -= self.learning_rate * np.dot(X.T, (h - y)) / y.size\n cost.append(self.costFunction(h, y))\n return (cost, theta)\n \n \n def tuneHyperparameters(self, X, y):\n alpha = [0.01, 0.001]\n accuracy = 0\n for a in alpha:\n for i in range(6000, 10001, 1000):\n self.learning_rate = a\n self.iterations = i\n accur = self.k_fold(X, y)\n if accur > accuracy:\n tuned_alpha = a\n tuned_iter = i\n accuracy = accur\n print(tuned_alpha, tuned_iter)\n \n def k_fold(self, X, y, k=5):\n n = len(X) // k\n accuracy = 0\n for i in range(k):\n X_test = X[n * i : n * (i+1), :]\n y_test = y[n * i : n * (i+1)]\n X_train = np.concatenate((X[:n*i], X[n*(i+1):]), axis=0)\n y_train = np.concatenate((y[:n*i], y[n*(i+1):]), axis=0)\n theta = np.zeros(X_train.shape[1])\n cost, self.W = self.gradientDescent(X_train, y_train, theta)\n y_pred = self.predict(X_test)\n correct = np.sum(y_pred == y_test)\n accuracy += correct / len(y_test)\n return accuracy / k\n \n \n def fit(self, X, y, cv=False):\n \"\"\"\n This function should train the model. By invoking this function, a class member variable\n containing the coefficients of the model will be filled based on the input data. These coefficients\n will then be used in the predict() function to make predictions about unknown data.\n\n X: Data. A numpy array of dimensions (number of samples, number of features). These are real values.\n y: Targets. A numpy array of dimensions (number of samples,). These are discrete values(either 0 or 1).\n :return: A list containing loss values for each iteration.\n \"\"\"\n if cv:\n self.tuneHyperparameters(X, y)\n else:\n theta = np.zeros(X.shape[1])\n cost, self.W = self.gradientDescent(X, y, theta)\n return cost\n\n\n def predict(self, X):\n \"\"\"\n This function should predict the target values using the parameters learned with the fit() function given the\n input data.\n\n :param X: Data. A numpy array of dimensions (number of samples, number of features).\n :return: A numpy array of dimensions (number of samples,) that contains\n predicted targets for the input data X. These targets must be discrete: either 0 or 1.\n \"\"\"\n return (self.sigmoid(np.dot(X, self.W)) > 0.5)\n\n\nclass SVM(object):\n \"\"\"\n A support vector machine with RBF kernel.\n\n Methods\n -------\n fit() : takes data and targets as input and trains the model with it.\n predict() : takes data as input and predicts the target values with the trained model.\n \"\"\"\n def __init__(self, C=300, sigma=10.0):\n \"\"\"\n This is one way of hard coding the hyperparameters you found. You dont have to follow this conventions.\n However, calling LogisticrRegression() without any parameters must create a model loaded with your best hyperparameters.\n \"\"\"\n super(SVM, self).__init__()\n self.C = C\n self.sigma = sigma\n\n\n def kernel(self, x, y):\n \"\"\"\n RBF(Gaussian) kernel\n \"\"\"\n return np.exp(-np.power(np.linalg.norm(x - y), 2) / (2 * self.sigma * self.sigma))\n \n \n def tuneHyperparameters(self, X, y):\n C = range(100, 501, 100)\n # sigma = range(1, 11, 2)\n sigma = [10]\n accuracy = 0\n for c in C:\n for s in sigma:\n self.C = c\n self.sigma = c\n accur = self.k_fold(X, y)\n if accur > accuracy:\n tuned_C = c\n tuned_sigma = s\n accuracy = accur\n print(accuracy)\n print(tuned_C, tuned_sigma)\n \n def k_fold(self, X, y, k=5):\n n = len(X) // k\n accuracy = 0\n for i in range(k):\n X_test = X[n * i : n * (i+1), :]\n y_test = y[n * i : n * (i+1)]\n X_train = np.concatenate((X[:n*i], X[n*(i+1):]), axis=0)\n y_train = np.concatenate((y[:n*i], y[n*(i+1):]), axis=0)\n self.fit(X_train, y_train)\n y_pred = self.predict(X_test)\n correct = np.sum(y_pred == y_test)\n accuracy += correct / len(y_test)\n return accuracy / k\n \n \n def fit(self, X, y):\n \"\"\"\n This function should train the model. By invoking this function, a class member variable\n containing the coefficients of the model will be filled based on the input data. These coefficients\n will then be used in the predict() function to make predictions about unknown data.\n\n :param X: Data. A numpy array of dimensions (number of samples, number of features).\n :param y: Targets. A numpy array of dimensions (number of samples,). These are discrete values(either 0 or 1).\n :return: Not important.\n \"\"\"\n # Convert (0, 1) binary to (-1, 1) binary\n y = np.array(list(map(lambda n: -1. if n == 0 else 1., y)))\n \n num_samples = X.shape[0]\n K = np.zeros((num_samples, num_samples))\n for i in range(num_samples):\n for j in range(num_samples):\n K[i, j] = self.kernel(X[i], X[j])\n \n # Quadratic Programming\n P = cvxopt.matrix(np.outer(y, y) * K)\n q = cvxopt.matrix(-np.ones(num_samples))\n G = cvxopt.matrix(np.vstack((np.identity(num_samples) * -1, np.identity(num_samples))))\n h = cvxopt.matrix(np.hstack((np.zeros(num_samples), np.ones(num_samples) * self.C)))\n A = cvxopt.matrix(y, (1, num_samples))\n b = cvxopt.matrix(0.0)\n \n solve = cvxopt.solvers.qp(P, q, G, h, A, b)\n alphas = np.ravel(solve['x'])\n self.a = np.array(list(map(lambda x: 0 if x < 1e-5 else x, alphas)))\n self.x = X\n self.y = y\n \n self.b = np.sum(self.y)\n for i in range(num_samples):\n self.b += self.y[i]\n for j in range(num_samples):\n self.b -= np.sum(self.a[j] * self.y[j] * self.kernel(X[j], X[i]))\n self.b /= num_samples\n \n \n def predict(self, X):\n \"\"\"\n This function should predict the target values using the parameters learned with the fit() function given the\n input data.\n\n :param X: Data. A numpy array of dimensions (number of samples, number of features).\n :return: A numpy array of dimensions (number of samples,) that contains\n predicted targets for the input data X. These targets must be discrete: either 0 or 1.\n \"\"\"\n w_x = np.zeros(len(X))\n for i in range(len(X)):\n for a, x, y in zip(self.a, self.x, self.y):\n w_x[i] += a * y * self.kernel(X[i], x)\n y_pred = w_x + self.b\n y_pred = np.sign(y_pred)\n \n # Convert (-1, 1) binary to (0, 1) binary\n return np.array(list(map(lambda n: 0 if n == -1 else n, y_pred)))\n","sub_path":"hw2/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"564502513","text":"import cv2\nimport numpy as np\nimport time \nfrom math import sqrt\nfrom statistics import mode,mean\nkernelOpen=np.ones((5,5))\nkernelClose=np.ones((20,20))\ncrack_length=0\nk=1.5\ndataset=[]\ndef distanceformula(x1,y1,x2,y2):\n return(sqrt((x1-x2)**2 + (y1-y2)**2))\ndef findmean():\n global dataset\n if len(dataset)!=0:\n crac=mode(dataset)\n dataset=[]\n else:\n crac=0\n return round(crac,1)\n \ndef crackdetection(frame):\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n lower = np.array([-8,100,0])\n upper = np.array([9,250,250])\n mask = cv2.inRange(hsv, lower, upper)\n res = cv2.bitwise_and(frame,frame, mask= mask)\n maskOpen=cv2.morphologyEx(mask,cv2.MORPH_OPEN,kernelOpen)\n maskClose=cv2.morphologyEx(maskOpen,cv2.MORPH_CLOSE,kernelClose)\n maskFinal=maskClose\n _,conts,h=cv2.findContours(maskFinal.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)\n if len(conts)!=0:\n c=max(conts,key=cv2.contourArea)\n cv2.drawContours(frame,c,-1,(0,0,0),3)\n rect =cv2.minAreaRect(c)\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n cv2.drawContours(frame,[box],0,(0,0,255),2)\n l,b=distanceformula(box[0][0],box[0][1],box[1][0],box[1][1]),distanceformula(box[1][0],box[1][1],box[2][0],box[2][1])\n if l>b:\n crack1=((l/b)*k)\n else:\n crack1=((b/l)*k)\n return frame,crack1\n #dataset.append(round(crack1,1)) \n\n\"\"\" cv2.imshow('f',frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n cap.release()\n print(findmean())\n break\"\"\"\n\n","sub_path":"Image_Recognisation/crackmeasurement.py","file_name":"crackmeasurement.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"566888901","text":"aantal_kluizen = 12\ndef menu():\n menu = ['1: ik wil weten hoeveel kluizen vrij zijn','2: ik wil een nieuwe kluis','3: ik wil even iets terug halen uit mijn kluis','4: ik geef mijn kluis terug','5: Sluit']\n\n for i in menu:\n print(i)\n\ndef aantal_kluizen_vrij():\n file = open('kluizen.txt', 'r')\n lines = []\n lines.extend(file.readlines())\n\n aantal_regels = len(lines)\n print(aantal_kluizen - aantal_regels)\n file.close()\n\ndef nieuwe_kluis():\n file = open('kluizen.txt', 'r+')\n regellijst = file.readlines()\n list = [1,2,3,4,5,6,7,8,9,10,11,12]\n\n for regel in regellijst:\n kluis_combinatie = regel.split(';')\n kluis_nummer = kluis_combinatie[0]\n list.remove(int(kluis_nummer))\n\n if len(list) > 0 :\n print('Dit zijn de kluizen die nog vrij zijn ' + str(list))\n nieuw_nummer = list[0]\n print('Uw kluisnummer is: ' + str(nieuw_nummer))\n code = input('Geef uw code op: ')\n file.writelines('\\n' + str(nieuw_nummer) + ';' + code)\n\n else:\n print('Sorry, alle kluizen zijn bezet')\n file.close()\n\n\n\ndef open_kluis():\n file = open('kluizen.txt', 'r')\n t = file.readlines()\n kluis_nummer = str(input('kluisnummer: '))\n wachtwoord = str(input('wachtwoord: '))\n combinatie = False\n\n for i in t:\n e = i.split(';')\n z = e[0]\n h = e[1]\n\n if kluis_nummer == z and wachtwoord in h:\n print('Kluis geopend ')\n combinatie = True\n break\n\n if combinatie == False:\n\n print('De combinatie kluisnummer en wachtwoord is incorrect')\n\ndef kluis_terug():\n file = open('kluizen.txt', 'r+')\n kluis_info = file.readlines()\n k = input('wat is uw kluisnummer: ')\n w = input('Wat is uw code: ')\n file.seek(0)\n\n for i in kluis_info:\n\n e = i.split(';')\n\n if str(w) not in i and k != e[0]:\n\n file.write(i)\n\n file.truncate()\n\n file.close()\n\n print('uw kluis is teruggegeven')\n\nwhile True:\n menu()\n print()\n kies_menu = input('Kies een menu: ')\n if kies_menu == '1':\n print()\n print('Het aantal vrije kluizen is: ', end='')\n aantal_kluizen_vrij()\n print()\n\n\n elif kies_menu == '2':\n nieuwe_kluis()\n\n elif kies_menu == '3':\n open_kluis()\n print()\n elif kies_menu == '4':\n kluis_terug()\n elif kies_menu == '5':\n break\n else:\n print('Menu bestaat niet!')\n print()\n print('------------------------------')\n","sub_path":"les 8/bagagekluizen.py","file_name":"bagagekluizen.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}