diff --git "a/5170.jsonl" "b/5170.jsonl" new file mode 100644--- /dev/null +++ "b/5170.jsonl" @@ -0,0 +1,706 @@ +{"seq_id":"4872355","text":"# -*- coding: utf-8 -*-\n\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('stats', '0005_scenario_sentence_function'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='scenario',\n name='sentence_function',\n field=models.PositiveIntegerField(default=0, verbose_name=b'Sentence function', choices=[(0, b'none'), (1, b'declarative'), (2, b'interrogative'), (3, b'exclamatory'), (4, b'imperative')]),\n ),\n ]\n","sub_path":"stats/migrations/0006_auto_20180220_0941.py","file_name":"0006_auto_20180220_0941.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"308010013","text":"\"\"\"\nhttps://leetcode.com/problems/car-fleet-ii/\n\nA car only collide with the car in front of it. \nWe go from the end of the fleet, use a stack to maintain the index of car. We remove cars that will not collision with current car, or collision happend before. The collision of current car can be computed by comparing its position with the top element in the stack.\n\nTime complexity: O(N)\n\"\"\"\nclass Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n stack = []\n n = len(cars)\n ans = [-1] * n\n for i in range(n-1, -1, -1):\n p, s = cars[i]\n while stack and (s <= cars[stack[-1]][1] or (p - cars[stack[-1]][0]) / (cars[stack[-1]][1] - s) >= ans[stack[-1]] > 0):\n stack.pop()\n if stack:\n ans[i] = (p - cars[stack[-1]][0])/(cars[stack[-1]][1] - s)\n stack.append(i)\n \n return ans\n","sub_path":"1776_CarFleetII.py","file_name":"1776_CarFleetII.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"331597363","text":"import cv2\nimport sys\nfrom mail import sendEmail\nfrom flask import Flask, render_template, Response\nfrom camera import VideoCamera\nimport time\nimport threading\nfrom localtime import LocalTime\n\n\nemail_update_interval = 600 # sends an email only once in this time interval\nsave_update_interval = 30 #Save once per half minute\ncamera_settings = {\n \"night\":{\n \"fr\":2,\n \"speed\":500000,\n \"ex\":\"night\",\n \"iso\":800\n },\n \"day\":{\n \"fr\":16,\n \"speed\":0,\n \"ex\":\"auto\",\n \"iso\":0\n }\n}\n\n\nlt = LocalTime()\ncurrent_state = lt.current_state()\ncamera_mode = camera_settings[current_state]\nvideo_camera = VideoCamera(resolution=(640,480),framerate=camera_mode[\"fr\"]) # creates a camera object, flip vertically\nvideo_camera.shutter_speed(camera_mode[\"speed\"])\nvideo_camera.hflip()\nvideo_camera.vflip()\nvideo_camera.rotation(270)\nvideo_camera.iso(camera_mode[\"iso\"])\n\n# App Globals (do not edit)\napp = Flask(__name__)\nlast_epoch = 0\nlast_save_epoch = 0\n\ndef set_camera_mode(camera,cm):\n camera.change_framerate(cm[\"fr\"])\n camera.shutter_speed(cm[\"speed\"])\n camera.iso(cm[\"iso\"])\n\ndef check_camera_mode(camera,current_state,future_state):\n global camera_mode\n if current_state != future_state:\n current_state = future_state\n camera_mode = camera_settings[current_state]\n set_camera_mode(camera,camera_mode)\n return current_state\n\ndef check_for_objects():\n global last_epoch\n global last_save_epoch\n global current_state\n global video_camera\n while True:\n future_state = lt.current_state()\n current_state = check_camera_mode(video_camera,current_state, future_state)\n vis, found_obj = video_camera.get_object()\n if found_obj==True:\n if (time.time() - last_epoch) > email_update_interval:\n last_epoch = time.time()\n print(\"[INFO] sending email...\")\n ret, jpeg = cv2.imencode('.jpg', vis)\n frame = jpeg.tobytes()\n try:\n sendEmail(frame)\n print(\"[INFO] done!\")\n except:\n print(\"[ERROR] Error sending email: \", sys.exc_info()[0])\n print(\"[INFO] saving hardcopy...\")\n current_time = lt.now()\n ts = current_time.strftime(\"%Y-%m-%d-%H-%M-%S\")\n filename = \"/home/pi/Pictures/\"+ts+\".jpeg\"\n try:\n cv2.imwrite(filename,vis)\n print(\"[INFO] done!\")\n except:\n print(\"Error saving hardcopy: \", sys.exc_info()[0])\n if (time.time() - last_save_epoch) > save_update_interval:\n last_save_epoch = time.time()\n print(\"[INFO] saving hardcopy...\")\n current_time = lt.now()\n ts = current_time.strftime(\"%Y-%m-%d-%H-%M-%S\")\n filename = \"/home/pi/Pictures/\"+ts+\".jpeg\"\n try:\n cv2.imwrite(filename,vis)\n print(\"[INFO] done!\")\n except:\n print(\"[ERROR] Error saving hardcopy: \", sys.exc_info()[0])\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\ndef gen(camera):\n while True:\n frame = camera.get_frame()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n\\r\\n')\n\n@app.route('/video_feed')\ndef video_feed():\n return Response(gen(video_camera),\n mimetype='multipart/x-mixed-replace; boundary=frame')\n\nif __name__ == '__main__':\n t = threading.Thread(target=check_for_objects, args=())\n t.daemon = True\n t.start()\n app.run(host='0.0.0.0', debug=False, threaded=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"21987960","text":"from collections import defaultdict\nfrom enum import Enum\n\n\ndef get_val_from_opcodes(opcodes, pos, mode, rel_base) -> int:\n val = opcodes[pos]\n if mode == \"0\":\n if val >= len(opcodes):\n return -1\n return opcodes[val]\n elif mode == \"1\":\n return val\n elif mode == \"2\":\n new_pos = rel_base + val\n if new_pos < 0 or new_pos >= len(opcodes):\n return -1\n return opcodes[new_pos]\n raise Exception(\"Mode not recognized\")\n\n\ndef get_dest_from_opcodes(opcodes, pos, mode, rel_base) -> int:\n val = opcodes[pos]\n if mode == \"0\":\n return val\n elif mode == \"1\":\n raise Exception(\"Cannot save in immediate mode\")\n elif mode == \"2\":\n return rel_base + val\n\n\ndef run_int_comp(opcodes):\n pos = 0\n rel_base = 0\n while opcodes[pos] != 99:\n op = str(opcodes[pos])\n\n if len(op) < 5:\n op = \"0\" * (5-len(op)) + op\n\n mode_1 = op[2]\n mode_2 = op[1]\n mode_3 = op[0]\n\n code = op[3:]\n\n left = get_val_from_opcodes(opcodes, pos + 1, mode_1, rel_base)\n right = get_val_from_opcodes(opcodes, pos + 2, mode_2, rel_base)\n if len(opcodes) > pos+3:\n dest = get_dest_from_opcodes(opcodes, pos+3, mode_3, rel_base)\n\n if code == \"01\":\n opcodes[dest] = left + right\n pos += 4\n continue\n elif code == \"02\":\n opcodes[dest] = left * right\n pos += 4\n continue\n elif code == \"03\":\n left = opcodes[pos+1]\n if mode_1 == \"2\":\n left = rel_base + opcodes[pos+1]\n opcodes[left] = yield\n pos += 2\n elif code == \"04\":\n pos += 2\n yield left\n continue\n elif code == \"05\":\n if left != 0:\n pos = right\n else:\n pos += 3\n continue\n elif code == \"06\":\n if left == 0:\n pos = right\n else:\n pos += 3\n continue\n elif code == \"07\": # less than\n if left < right:\n opcodes[dest] = 1\n else:\n opcodes[dest] = 0\n pos += 4\n continue\n elif code == \"08\": # equals\n if left == right:\n opcodes[dest] = 1\n else:\n opcodes[dest] = 0\n pos += 4\n continue\n elif code == \"09\": # update relative base\n rel_base += left\n pos += 2\n continue\n elif op == \"99\":\n break\n else:\n raise Exception(\"Unrecognized opcode\")\n\n\nclass Direction(Enum):\n UP = 1,\n RIGHT = 2,\n DOWN = 3,\n LEFT = 4\n\n def rotate_left(self):\n if self is Direction.UP:\n return Direction.LEFT\n elif self is Direction.LEFT:\n return Direction.DOWN\n elif self is Direction.DOWN:\n return Direction.RIGHT\n elif self is Direction.RIGHT:\n return Direction.UP\n\n def rotate_right(self):\n if self is Direction.UP:\n return Direction.RIGHT\n elif self is Direction.LEFT:\n return Direction.UP\n elif self is Direction.DOWN:\n return Direction.LEFT\n elif self is Direction.RIGHT:\n return Direction.DOWN\n\n\ndef analyze(file):\n with open(file) as f:\n opcodes = [int(c) for c in f.readline().strip().split(\",\")]\n\n op_runner = run_int_comp(opcodes)\n next(op_runner)\n hull = defaultdict(lambda: 0)\n painted = set()\n pos_x, pos_y = 0, 0\n direction = Direction.UP\n while True:\n cur_paint = hull[(pos_x, pos_y)]\n try:\n to_paint = op_runner.send(cur_paint)\n to_dir = next(op_runner)\n c = next(op_runner)\n painted.add((pos_x, pos_y))\n except StopIteration:\n break\n hull[(pos_x, pos_y)] = to_paint\n if to_dir == 0:\n direction = Direction.rotate_left(direction)\n else:\n direction = Direction.rotate_right(direction)\n if direction is Direction.UP:\n pos_x, pos_y = pos_x, pos_y + 1\n elif direction is Direction.DOWN:\n pos_x, pos_y = pos_x, pos_y - 1\n elif direction is Direction.RIGHT:\n pos_x, pos_y = pos_x + 1, pos_y\n elif direction is Direction.LEFT:\n pos_x, pos_y = pos_x - 1, pos_y\n\n print(len(painted))\n\n\nif __name__ == '__main__':\n analyze(\"../inputs/day_11.txt\")\n","sub_path":"day_11/day_11_part_1.py","file_name":"day_11_part_1.py","file_ext":"py","file_size_in_byte":4577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"613564321","text":"from __future__ import print_function\nfrom caffe import layers as L, params as P, to_proto\nfrom caffe.proto import caffe_pb2\nimport os.path\n\ncaffe_root = '/home/reynoldscem/caffe'\n\n\ndef bn_relu_conv(bottom, kernel_size, nout, stride, pad, dropout, dilation=1):\n # batch_norm = L.BatchNorm(\n # bottom, in_place=False,\n # param=[\n # dict(lr_mult=0, decay_mult=0),\n # dict(lr_mult=0, decay_mult=0),\n # dict(lr_mult=0, decay_mult=0)\n # ]\n # )\n # scale = L.Scale(\n # batch_norm, bias_term=True, in_place=True,\n # filler=dict(value=1), bias_filler=dict(value=0)\n # )\n # relu = L.ReLU(scale, in_place=True)\n relu = L.ReLU(bottom, in_place=True)\n conv = L.Convolution(\n relu, kernel_size=kernel_size, stride=stride,\n num_output=nout, pad=pad, bias_term=False, dilation=dilation,\n weight_filler=dict(type='msra'), bias_filler=dict(type='constant')\n )\n if dropout > 0:\n conv = L.Dropout(conv, dropout_ratio=dropout)\n return conv\n\n\ndef add_layer(bottom, num_filter, dropout, pad=1, dilation=1):\n conv = bn_relu_conv(\n bottom, kernel_size=3, nout=num_filter,\n stride=1, pad=pad, dropout=dropout, dilation=dilation\n )\n concate = L.Concat(bottom, conv, axis=1)\n return concate\n\n\ndef transition(bottom, num_filter, dropout):\n conv = bn_relu_conv(\n bottom, kernel_size=1, nout=num_filter,\n stride=1, pad=0, dropout=dropout\n )\n # pooling = L.Pooling(conv, pool=P.Pooling.AVE, kernel_size=2, stride=2)\n return conv\n\n\n# change the line below to experiment with different setting\n# depth -- must be 3n+4\n# first_output -- #channels before entering the first dense block,\n# set it to be comparable to growth_rate\n# growth_rate -- growth rate\n# dropout -- set to 0 to disable dropout, non-zero number to set dropout rate\ndef densenet(\n data_file, mode='train', batch_size=64, depth=10,\n first_output=16, growth_rate=10, dropout=0.2,\n dense_blocks=2, split='trainval', tops=['color', 'label']\n):\n # mean_file = os.path.join(caffe_root, 'examples/cifar10/mean.binaryproto')\n # data, label = L.Data(\n # source=data_file, backend=P.Data.LMDB,\n # batch_size=batch_size, ntop=2,\n # transform_param=dict(\n # mean_file=mean_file\n # )\n # )\n\n data, label = L.Python(\n module='nyud_layers',\n layer='NYUDSegDataLayer', ntop=2,\n param_str=str(dict(\n nyud_dir='/media/reynoldscem/DATA/temp-datasets/nyud_gupta_new',\n split=split,\n tops=tops, seed=1337\n )))\n\n nchannels = first_output\n model = L.Convolution(\n data, kernel_size=3, stride=1, num_output=nchannels,\n pad=1, bias_term=False, weight_filler=dict(type='msra'),\n bias_filler=dict(type='constant')\n )\n if dropout > 0:\n model = L.Dropout(model, dropout_ratio=dropout)\n\n # 1 initial conv layer, a transition layer\n # between each pair of dense blocks,\n # and an inner product layer for classification.\n aux_layers = 1 + 1 + (dense_blocks - 1)\n N = (depth - aux_layers) / dense_blocks\n assert float(N).is_integer(), \\\n 'Depth != (depth - auxiliary layers) / num_blocks'\n dilation = dict(zip(range(N), [1, 1, 1, 2, 2, 2, 4, 4, 8, 8, 16, 16]))\n # dilation = dict(zip(range(N), [1, 1, 2, 2, 2, 4, 4, 8, 8, 16, 16, 16]))\n dilation = dict(zip(range(N), [1, 2, 4, 8]))\n # dilation = dict(zip(range(N), [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]))\n for block in range(dense_blocks):\n for i in range(N):\n model = add_layer(\n model, growth_rate, dropout,\n pad=dilation[i], dilation=dilation[i]\n )\n nchannels += growth_rate\n if block < dense_blocks - 1:\n model = transition(model, nchannels, dropout)\n\n # model = L.BatchNorm(\n # model, in_place=False,\n # param=[\n # dict(lr_mult=0, decay_mult=0),\n # dict(lr_mult=0, decay_mult=0),\n # dict(lr_mult=0, decay_mult=0)\n # ]\n # )\n # model = L.Scale(\n # model, bias_term=True, in_place=True,\n # filler=dict(value=1), bias_filler=dict(value=0)\n # )\n # model = L.ReLU(model, in_place=True)\n model = L.ReLU(model, in_place=True)\n\n model = transition(model, 40, 0.)\n # model = L.Pooling(model, pool=P.Pooling.AVE, global_pooling=True)\n # model = L.InnerProduct(\n # model, num_output=10, bias_term=True,\n # weight_filler=dict(type='xavier'), bias_filler=dict(type='constant')\n # )\n loss = L.SoftmaxWithLoss(model, label)\n accuracy = L.Accuracy(model, label)\n return to_proto(loss, accuracy)\n\n\ndef make_net():\n # lmbd_path = 'examples/cifar10/cifar10_{}_lmdb'\n # train_path = os.path.join(caffe_root, lmbd_path.format('train'))\n # test_path = os.path.join(caffe_root, lmbd_path.format('test'))\n # change the path to your data. If it's not lmdb format,\n # also change first line of densenet() function.\n with open('train_densenet.prototxt', 'w') as f:\n print(\n str(densenet(None, batch_size=1, split='trainval')),\n file=f\n )\n\n with open('test_densenet.prototxt', 'w') as f:\n print(str(densenet(None, batch_size=1, split='test')), file=f)\n\n\ndef make_solver():\n s = caffe_pb2.SolverParameter()\n s.random_seed = 0xCAFFE\n\n s.train_net = 'train_densenet.prototxt'\n s.test_net.append('test_densenet.prototxt')\n s.test_interval = 800\n s.test_iter.append(200)\n\n s.max_iter = 100000\n s.type = 'Nesterov'\n s.display = 10\n\n s.base_lr = 0.1\n s.momentum = 0.9\n s.weight_decay = 1e-4\n\n s.lr_policy = 'multistep'\n s.gamma = 0.1\n s.stepvalue.append(int(0.5 * s.max_iter))\n s.stepvalue.append(int(0.75 * s.max_iter))\n s.solver_mode = caffe_pb2.SolverParameter.GPU\n\n s.snapshot = 10000\n s.snapshot_prefix = 'snapshots/DenseNet_nyud'\n\n solver_path = 'solver.prototxt'\n with open(solver_path, 'w') as f:\n f.write(str(s))\n\nif __name__ == '__main__':\n make_net()\n make_solver()\n","sub_path":"make_densenet.py","file_name":"make_densenet.py","file_ext":"py","file_size_in_byte":6125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"621223492","text":"import inspect\nimport os.path\nimport watcherLogging\n\n\ndef read_cofig():\n\n myDic = {}\n\n try:\n from configparser import ConfigParser\n except ImportError:\n from ConfigParser import ConfigParser # ver. < 3.0\n\n # instantiate\n config = ConfigParser()\n\n try:\n filename = inspect.getframeinfo(inspect.currentframe()).filename\n path = os.path.dirname(os.path.abspath(\n filename)) + \"/Setup/the_watcher_config.ini\"\n print(\"Config Path :\" + path)\n\n # parse existing file\n config.read(path)\n\n # read values from a section\n battlemetrics_url = config.get('section_a', 'battlemetrics_url')\n myDic['battlemetrics_url'] = battlemetrics_url\n\n server_ip = config.get('section_a', 'server_ip')\n myDic['server_ip'] = server_ip\n\n server_port = config.get('section_a', 'server_port')\n myDic['server_port'] = server_port\n\n bot_id = config.get('section_b', 'bot_id')\n myDic['bot_id'] = bot_id\n\n bot_channel_player_joined = config.getint(\n 'section_b', 'bot_channel_player_joined')\n myDic['bot_channel_player_joined'] = bot_channel_player_joined\n\n bot_channel_commands = config.getint(\n 'section_b', 'bot_channel_commands')\n myDic['bot_channel_commands'] = bot_channel_commands\n\n bot_player_name_changes = config.getint(\n 'section_b', 'bot_player_name_changes')\n myDic['bot_player_name_changes'] = bot_player_name_changes\n\n bot_enable_name_changes = config.getboolean(\n 'section_b', 'bot_enable_name_changes')\n myDic['bot_enable_name_changes'] = bot_enable_name_changes\n\n return myDic\n\n except Exception as e:\n print(\"Error reading config ::\" + str(e))\n watcherLogging.error_logs(\n 'Error has occured in read_cofig ::' + str(e))\n","sub_path":"readSetupFile.py","file_name":"readSetupFile.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"96215818","text":"#\n#\nfrom Canvas import Bitmap\n\nname = \"\";\npwd = \"\";\nwhile True:\n if name != \"a\":\n name = raw_input(\"name:\");\n print(\"sorry.name\");\n elif pwd != \"111\":\n pwd = raw_input(\"pwd:\");\n print(\"sorry.pwd\");\n else:\n print(\"ok\");\n break;\n\n\n","sub_path":"src/main/py/demo3.py","file_name":"demo3.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"168104446","text":"import os\nimport time\nimport dateutil.relativedelta\nimport mysql.connector\nfrom datetime import datetime, date\nimport datetime\n\nnew_conn = mysql.connector.connect(host='192.168.50.151',user='search',password='search@zyxr.com', database='invest')\nnew_cursor = new_conn.cursor(dictionary=True)\n\ndef getAsset():\n with open(\"updatesql.20170124\", \"a+\") as f:\n sql=\"select * from product.t_assets where asset_type = 1 and asset_property & 65536 = 65536\"\n new_cursor.execute(sql)\n assetRows = new_cursor.fetchall()\n for assetRow in assetRows:\n assetId=assetRow[\"asset_id\"]\n assetSuffix=int(str(assetId)[-2:])\n totalAmount=assetRow[\"total_amount\"]\n sql=\"select sum(amount) as amount from product.t_investment_%02d where asset_id=%d and asset_type =1 \" % (int(str(assetId)[-2:]),assetId)\n new_cursor.execute(sql)\n investRows = new_cursor.fetchall()\n for investRow in investRows:\n amount=investRow[\"amount\"]\n if totalAmount!=amount:\n print(\"错误:asset_id is %d \" % (assetId))\n\n\n #找到这些标的所有投资记录\n #sql=\"select * from product.t_investment_%02d where asset_id=%d and asset_type = 1 \" % (int(str(assetId)[-2:]),assetId)\n #new_cursor.execute(sql)\n #investRows = new_cursor.fetchall()\n #for investRow in investRows:\n #investId=investRow[\"investment_id\"]\n #investSuffix=int(str(investId)[-2:])\n #sql1=\"update product.t_investment_%02d set asset_state = 10 and state = 4 where asset_id=%d and investmet_id=%d and state = 2 ;\\n\" % (assetSuffix,assetId,investId)\n #sql2=\"update invest.t_investment_%02d set asset_state = 10 and state = 4 where asset_id=%d and investment_id=%d and state = 2 ;\\n\" % (investSuffix,assetId,investId)\n #sql3=\"update financial_plan.t_investment_$02d set asset_state = 10 and state = 4 where asset_id=%d and investment_id=%d and state = 2 ;\\n\" % ()\n #sqls=\"update invest.t_investments set asset_state = 10 and state = 4 where asset_id=%d and investment_id=%d and state = 2 ;\\n \" % ()\n #f.write(sql1)\n #f.write(sql2)\n #f.write(sql3)\n #f.write(\"update product.t_assets set state=10 where asset_id=%d and asset_property & 65536 = 65536 ;\\n\" % (assetId))\n\ngetAsset()","sub_path":"python_self/工作/专门修复王武问题(未解决)/修改天标未完标的情况(待解决)/查看老的大标的状态.py","file_name":"查看老的大标的状态.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"430972577","text":"import connexion\nimport six\n\nfrom swagger_server.models.city_data import CityData # noqa: E501\nfrom swagger_server.models.error import Error # noqa: E501\nfrom swagger_server import util\nfrom swagger_server.__main__ import rj, Path\n\nfrom qwikidata.sparql import return_sparql_query_results\n\n\ndef query_wikidata(sparql_query):\n \"\"\"query_wikidata\n\n :param sparql_query: Sparql query\n :type sparql_query: str\n\n :rtype: list of objects of objects of type dict\n \"\"\"\n res = return_sparql_query_results(sparql_query)\n obj_json = res['results']['bindings']\n return obj_json\n\n\ndef get_cities_data(name=None): # noqa: E501\n \"\"\"get_city_data\n\n Retrieve information about cities with a given name.\n If no cities with this name found, return empty list\n\n :param name: City name\n :type name: str\n\n :rtype: list of objects of type CityData\n \"\"\"\n name = name.title()\n sparql_query = f'''\n SELECT DISTINCT ?name ?country ?population ?postal_code WHERE\n {{\n ?object wdt:P31/wdt:P279* wd:Q515;\n wdt:P1082 ?population;\n wdt:P17 ?country_obj;\n wdt:P281 ?postal_code.\n ?object rdfs:label|skos:altLabel \"{name}\"@en.\n SERVICE wikibase:label {{ bd:serviceParam wikibase:language \"en\".\n ?object rdfs:label ?name.\n ?country_obj rdfs:label ?country.\n }}\n }}\n '''\n\n cities_json = rj.jsonget(name)\n if not cities_json:\n cities_json = query_wikidata(sparql_query)\n rj.jsonset(name, Path('.'), cities_json)\n seconds = 60 * 60 * 24\n rj.expire(name, seconds)\n\n return cities_json if cities_json else \\\n Error(code=404, message='City not found')\n","sub_path":"swagger_server/controllers/default_controller.py","file_name":"default_controller.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"633444778","text":"'''This module contains all functions used to convert from sympy syntax to LaTeX equation syntax'''\n\nimport re\n\ndef handle_symbols(sympy_string):\n\n latex_string = sympy_string.replace(' ','')\n\n latex_string = latex_string.replace('**', '^')\n\n latex_string = latex_string.replace('*', ' ')\n\n latex_string = latex_string.replace('rho', r'\\rho')\n\n latex_string = latex_string.replace('phi', r'\\phi')\n\n latex_string = latex_string.replace('sin', r'\\sin')\n\n latex_string = latex_string.replace('cos', r'\\cos')\n\n latex_string = latex_string.replace('neg','-')\n\n return latex_string\n\ndef handle_expansioncoeffs(string):\n\n expansion_coeffs = re.findall('j(.*?)k', string)\n\n #Once expansion coefficients have been appended to list expansionCoefficients, the 'j' and 'k' character flags are removed from the strings.\n\n string = string.replace('j','')\n\n string = string.replace('k','')\n\n for coeff in expansion_coeffs:\n\n #Split coefficient string into list of independent characters, using character flag 'x' between independent characters.\n\n coefflist = coeff.split('x')\n\n #Write expansion coefficient in LaTeX typesetting format via character indices.\n\n latex_coeff = str(coefflist[0])+'^{'+str(coefflist[1])\n\n max_count = len(coefflist[2:]) - 1\n\n if len(coefflist[2:]) <= 2:\n\n latex_coeff += '}_{'\n\n for count,index in enumerate(coefflist[2:]):\n\n latex_coeff += str(index)\n\n if count != max_count:\n\n latex_coeff += ','\n\n else:\n\n latex_coeff += '}'\n\n elif len(coefflist[2:]) == 3:\n\n latex_coeff += ','\n\n for count,index in enumerate(coefflist[2:]):\n\n latex_coeff += str(index)\n\n if count == 0:\n\n latex_coeff += '}_{'\n\n elif count != max_count:\n\n latex_coeff += ','\n\n else:\n\n latex_coeff += '}'\n\n elif len(coefflist[2:]) == 4:\n\n latex_coeff += ','\n\n for count,index in enumerate(coefflist[2:]):\n\n latex_coeff += str(index)\n\n if count == 1:\n\n latex_coeff += '}_{'\n\n elif count != max_count:\n\n latex_coeff += ','\n\n else:\n\n latex_coeff += '}'\n\n #Replace old expansion coefficient with LaTeX syntax expansion coefficient in string.\n\n string = string.replace(coeff, latex_coeff)\n\n newstring = string\n\n return newstring\n\n\ndef is_integer(str_char):\n\n try:\n\n int(str_char)\n\n return True\n\n except ValueError:\n\n return False\n\ndef handle_exponents(string):\n\n stringlist = list(string)\n\n max_index = (len(stringlist) - 1)\n\n index = 0\n\n while (index <= max_index):\n\n if stringlist[index] == '^':\n\n hat_index = index\n\n integerlen = 0\n\n for value in range(4):\n\n if (hat_index+value+1) <= max_index:\n\n if is_integer(stringlist[hat_index+value+1]) == True:\n\n integerlen += 1\n\n continue\n\n else:\n\n break\n\n if integerlen > 0:\n\n stringlist.insert(hat_index + 1, '{')\n\n stringlist.insert(hat_index + 2 + integerlen, '}')\n\n max_index += 2\n\n index += 2 + integerlen\n\n index += 1\n\n newstring = ''.join(stringlist)\n\n return newstring\n\ndef handle_labels(string):\n\n string = string.replace('alpha',r'_{\\alpha}')\n\n string = string.replace('beta',r'_{\\beta}')\n\n return string\n\ndef simplify_algebra(string):\n\n string = string.replace('--','+')\n\n string = string.replace('+-','-')\n\n return string\n\ndef remove_zero_terms(string):\n\n string = string.replace('+0','')\n\n string = string.replace('-0','')\n\n string = string.replace('0+','')\n\n string = string.replace('0-','-')\n\n return string\n\ndef sympy_2_latex(sympy_str):\n\n convert_str = handle_symbols(sympy_str)\n\n convert_str = handle_expansioncoeffs(convert_str)\n\n convert_str = handle_labels(convert_str)\n\n convert_str = handle_exponents(convert_str)\n\n convert_str = remove_zero_terms(convert_str)\n\n latex_str = simplify_algebra(convert_str)\n\n return latex_str\n","sub_path":"modules/latex_convert.py","file_name":"latex_convert.py","file_ext":"py","file_size_in_byte":4408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"37004174","text":"inputMolecule = \"HOHOHO\"\n\ninputFile = \"/Users/rblount/OneDrive/AdventOfCode/2015/Day19-Input-Replacements-Test.txt\"\n\ndef readInput(filename):\n f = open(filename, \"r\")\n\n replacements = dict()\n\n for line in f.readlines():\n moleculeReplacement = line.rstrip().split(\" => \")\n label = moleculeReplacement[0]\n if label in replacements.keys():\n replacements[label].append(moleculeReplacement[1])\n else:\n replacements[label] = [moleculeReplacement[1]]\n\n return replacements\n\ndef breakInputMolecule(molecule, replacementList):\n singleCharMolecules = list(i for i in molecule if len(i) == 1)\n return singleCharMolecules\n\ndef combindMoleculeList(allNewMolecules):\n newMolecules = list()\n for i in range(len(allNewMolecules)):\n newMolecule = \"\"\n for letter in allNewMolecules[i]:\n newMolecule += letter\n newMolecules.append(newMolecule)\n return list(set(newMolecules))\n\n# Part 1\nmoleculeList = readInput(inputFile)\n# print(moleculeList)\nlistOfMolecule = breakInputMolecule(inputMolecule, moleculeList)\n# print(listOfMolecule)\nlistOfReplacements = []\nfor i in range(len(listOfMolecule)):\n # newMolecule = listOfMolecule\n molecule = listOfMolecule[i]\n if molecule in set(moleculeList.keys()):\n for k in moleculeList[molecule]:\n newMolecule = list(listOfMolecule)\n newMolecule[i] = k\n listOfReplacements.append(newMolecule)\n\n# uniqueMolecules = set(listOfReplacements)\nuniqueMolecules = combindMoleculeList(listOfReplacements)\n# print(listOfReplacements)\nprint(uniqueMolecules)\n","sub_path":"2015/Day19.py","file_name":"Day19.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"427997097","text":"import sys\ninput = sys.stdin.readline\n\narr = []\nn = int(input())\nfor _ in range(n):\n arr.append(input().rstrip())\n\narr = list(set(arr))\narr.sort(key=lambda x:(len(x), x))\n\nfor i in arr:\n print(i)\n","sub_path":"Baekjoon/1181.py","file_name":"1181.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"637766787","text":"from flask import render_template\n\nfrom newsservice.models import News\nfrom flask import (Blueprint, request, current_app)\n\nimport requests\n\nbp = Blueprint('index', __name__)\n\n\ndef check_cc_sites_status():\n \"\"\"\n checks if all compute center sites in config are accessible\n :return: an json array\n \"\"\"\n try:\n from config import config\n cc_sites = config.CC_SITES\n except:\n return []\n sites = {}\n for location, url in cc_sites.items():\n get_status(location, url, sites)\n return sites\n\n\ndef get_status(location, cc_url, sites):\n try:\n response = requests.head(cc_url, timeout=5)\n #status_code = response.status_code\n #reason = response.reason\n sites.update({location: {\n 'url': cc_url,\n 'status': 0\n }})\n except requests.exceptions.ConnectionError:\n #status_code = '000'\n #reason = 'ConnectionError'\n sites.update({location: {\n 'url': cc_url,\n 'status': 1\n }})\n\n\n@bp.route('/')\ndef render():\n \"\"\"\n This method renders the HTML website including the isOnline Status and the last 30 database entries.\n :return:\n \"\"\"\n # sites = check_cc_sites_status()\n queries = News.get_all_queries_by_request(request)\n articles = News.query \\\n .filter(*queries) \\\n .order_by(News.id.desc())\\\n .limit(30)\\\n .all()\n articles = [i.serialize for i in articles]\n\n return render_template(\"index.html\", news=articles, cc_sites=None)\n\n\n@bp.route('/')\ndef render_tag(tags):\n articles = News.query \\\n .filter(*News.get_tag_queries(tags)) \\\n .order_by(News.id.desc()) \\\n .all()\n articles = [i.serialize for i in articles]\n return render_template(\"index.html\", news=articles, cc_sites=None)\n\n\n@bp.route('/id/')\ndef render_id(id):\n articles = News.query.filter(News.id == id).all()\n articles = [i.serialize for i in articles]\n return render_template(\"index.html\", news=articles, cc_sites=None)\n\n\n@bp.route('/facility/')\ndef render_facility(facility_id):\n \"\"\"\n This method renders the HTML website with news for facility-id.\n :return:\n \"\"\"\n articles = News.query \\\n .filter(*News.get_facility_queries(facility_id)) \\\n .order_by(News.id.desc()) \\\n .all()\n articles = [i.serialize for i in articles]\n return render_template(\"index.html\", news=articles, cc_sites=None)\n","sub_path":"newsservice/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"635064532","text":"#!/usr/bin/env python\n# -*- coding: utf8 -*-\n#\n\"\"\"buttoncounter.py\n\nAppel d'API sur un Spark Core faisant fonctionner le programme\n buttoncounter.ino \n \n retourne la valeur du compteur. Demande un reset du compteur sur\n le spark core lorsque sa valeur dépasse 5.\n\nCopyright 2015 DMeurisse \n\nVoir tutoriel:\n http://wiki.mchobby.be/index.php?title=Spark-Core-Bouton\n \nOu acheter Spark Core -- et soutenir nos travaux --\n\n http://shop.mchobby.be/category.php?id_category=54\n\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n \nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n \nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\nMA 02110-1301, USA.\n\n------------------------------------------------------------------------\nHistory:\n 01 jan 2015 - Dominique - v 0.1 (première release)\n\"\"\" \nfrom sparkapi import SparkApi\nfrom sparkapi import Config \n\n# Ouvre le fichier sparkapi.ini pour éviter de Hard Coder des données\n# sensible comme l'access_token dans les programmes d'exemple publié sur\n# le Net.\n# \n# Créez votre propre fichier sparkapi.ini à partir du fichier \n# sparkapi-sample.ini\nconfig = Config()\n\n\ndef main():\n\t# Execute le programme qui récupère le nombre de pression sur \n\t# le Spark Core\n\tapi = SparkApi( access_token = config.access_token, debug = False )\n\t# ou utiliser directement votre access_token\n\t#api = SparkApi( access_token = '123412341234', debug = False )\n\t\t\n\t# Créer un objet Core à partir du core_id \n\t# le core_id provient du fichier de configuration sparkapi.ini\n\t# dans la section [CORES]\n\tcore = api.get_core( config.cores['core0'] ) \n\t# ou utiliser directement votre core_id\n\t#core = api.get_core( '0123456789abcdef' )\n\t\n\t# Lire une variable sur le core\n\t# retourne un tuple (connected, valeur)\n\tvalue = core.value_of( 'counter' )\n\t\n\tif( value[0] == False ):\n\t\tprint( 'le Core n est pas connecté' )\n\telse:\n\t\tprint( 'compteur = %i' % value[1] )\n\t\n\t# Si connecté et 'valeur > 5' ???\n\tif( value[0] and value[1]>5 ):\n\t\tprint( 'Envoyer ordre \"reset\" compteur' )\n\t\t# Faire un reset du compteur sur le core.\n\t\t# En utilisant sa fonction \"reset\" publier sur Spark Cloud\n\t\tresult = core.call( 'reset' ) \n\t\tprint( \"connecté=%s, résultat=%i\" % result ) \n\t\tif( result[0] == False ):\n\t\t\tprint( 'le Core n est pas connecté' )\n\t\telse:\n\t\t\tprint( 'La fonction à répondu %i' % result[1] )\n\t\n\treturn 0\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"PyCall/buttoncounter.py","file_name":"buttoncounter.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"607483309","text":"import requests\nfrom ichubOpenApi import const\nfrom ..sign.Passport import Identify\nimport json\nimport time\n\n\nclass requestBase:\n\n def __init__(self, host=None, v='1.0.0', app_id='', sign_type='', key='', public_key='', private_key=''):\n self.v = v\n self.verify = Identify(sign_type, key, public_key, private_key)\n self.app_id = app_id\n self.sign_type = sign_type\n self.host = host if host is not None else const.HOST\n\n def send_request(self, params=None, filter_param=None):\n params['timestamp'] = int(round(time.time() * 1000))\n params['v'] = self.v\n params['app_id'] = self.app_id\n params['sign_type'] = self.sign_type\n build_params = dict.copy(params)\n\n if filter_param is not None:\n for i in filter_param:\n del build_params[i]\n\n sign = self.verify.buildRequestMysign(build_params)\n params['sign'] = sign\n try:\n r = requests.post(self.host, data=params)\n r = r.text\n result = json.loads(r)\n return result\n except Exception as e:\n return False\n","sub_path":"ichubOpenApi/request/requestBase.py","file_name":"requestBase.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"270268592","text":"from socket import *\nimport sys\nimport threading\nimport json\nimport random\nfrom threading import *\nimport time\nfrom queue import Queue\nconfig=sys.argv[1]\nalgo=sys.argv[2]\nf=open(config,\"r\")\nd=dict()\ndata=json.loads(f.read())\nw=data['workers']\nglobal y\nlock=Lock()\nworker=None\nprevRR=None\nf1=open(algo,'a')\nwith open(\"logs.txt\",'a') as f:\n\tf.write(algo+'\\n')\n#joblist={}\n\ndef RR(work):\n\tglobal prevRR\n\tscheduledworker = -1\n\tselected = False\n\tend=-1\n\tj=0\n\tif prevRR==None:\n\t\twhile (j < len(work)) and not selected :\n\t\t\t\tif work[j]['slots']>0:\n\t\t\t\t\tscheduledworker=j\n\t\t\t\t\tselected=True\n\t\t\t\telif not selected:\n\t\t\t\t\tj+=1\n\telse:\n\t\tj=(prevRR+1)%len(work)\n\t\tend = prevRR\n\t\twhile (j!=end) and not selected:\n\t\t\tif work[j]['slots']>0:\n\t\t\t\tscheduledworker= j\n\t\t\t\tselected=True\n\t\t\tj=(j+1)%len(work)\n\n\tif scheduledworker!=-1:\n\t\tprevRR = scheduledworker\n\twork[scheduledworker]['slots']-=1\n\treturn work[scheduledworker]\n\t\t\n\t\t\n\t\ndef RANDOM(work):\n\twhile(1):\n\n\t\tp=random.choice(work)\n\t\t#print(p['slots'])\n\t\tif(p['slots']==0):\n\t\t\t\n\t\t\tcontinue\n\t\telse:\n\t\t\tp['slots']-=1\n\t\t\tbreak\n\treturn p\n\t\ndef LeastLoaded(work):\n\twhile(1):\n\t\tj=0\n\t\tfor i in range(1,len(work)):\n\t\t\tif work[j]['slots'] < work[i]['slots']:\n\t\t\t\tj= i\n\t\t \n\t\tif work[j]['slots']<1:\n\t\t\ttime.sleep(1)\n\t\telse:\n\t\t\tbreak\n\twork[j]['slots']-=1\n\treturn work[j]\n \ndef initial_assign_job():\n\tif(algo=='RR'):\n\t\ty=RR(w)\n\telif (algo=='LL'):\n\t\ty=LeastLoaded(w)\n\telif(algo=='RANDOM'):\n\t\ty=RANDOM(w)\n\telse:\n\t\tsys.exit()\n\t\n\treturn y\n\nlock1=Lock()\n\ndef launch_task(x):\n\t\n\t#global t\n\t\n\tt=initial_assign_job()\n\t#x=q.get()\n\tprint('task '+x['task_id']+' is assigned to worker_id '+str(t['worker_id'])+' '+str(t['slots']))\n\tz=socket(AF_INET,SOCK_STREAM)\n\tz.connect((\"localhost\",t['port']))\n\tmsg2=json.dumps(x)\n\tz.send((msg2).encode())\n\tz.close()\n\treturn 1\n\t\ndef request_for_job():\n\t#listen to job requests\n\ts=socket(AF_INET,SOCK_STREAM)\n\ts.bind(('localhost',5000))\n\ts.listen(1)\n\t\n\twhile 1:\n\t\tlock.acquire()\n\t\tconn,addr=s.accept()\n\t\tx=conn.recv(1024)\n\t\tda=json.loads(x)\n\t\td[da['job_id']]=len(da['map_tasks'])\n\t\t#joblist[int(da['job_id'])] = [str(time.time()),len(da['reduce_tasks'])]\n\t\twith open(algo,'a') as f:\n\t\t\tf.write(str(time.time())+','+'arrival time of job '+','+da['job_id']+','+str(len(da['reduce_tasks'])-1)+'\\n')\n\t\tfor i in range(len(da['map_tasks'])):\n\t\t\t#q.put(da['map_tasks'][i])\n\t\t\tlaunch_task(da['map_tasks'][i])\n\t\twhile(d[da['job_id']]!=0):\n\t\t\tcontinue\n\t\t\n\t\tfor i in range(len(da['reduce_tasks'])):\n\t\t\t#q.put(da['reduce_tasks'][i])\n\t\t\tlaunch_task(da['reduce_tasks'][i])\n\t\t\n\t\t#print(t['port'])\n\n\t\t\n\t\tlock.release()\n\tconn.close()\n\n\t\t\ndef update_from_worker(s1):\n\t\t\n\t\n\t\n\twhile(1):\n\t\t#lock.acquire()\n\t\tconn2,add=s1.accept()\n\t\tx1=conn2.recv(1024)\n\t\tdata=x1.decode().split('\\n')\n\t\tmsg1=json.loads(data[0])\n\t\tmsg2=data[1]\n\t\tif(msg1['task_id'].split(\"_\")[1][0]=='M'):\n\t\t\td[msg1['task_id'].split(\"_\")[0]]-=1\n\t\t \n\t\t#print(msg1,msg2)\n\t\tk=0\n\t\tfor i in w:\n\t\t\tif(i['worker_id']==int(msg2)):\n\t\t\t\ti['slots']+=1\n\t\t\t\tk=i['slots']\n\t\t\n\t\tprint('task completed '+msg1['task_id']+' from worker '+msg2+' '+str(k))\n\t\t\n\t\t#lock.release()\n\tconn2.close()\t\n\t\ndef main():\n\t#q=Queue()\n\t\n\ts1=socket(AF_INET,SOCK_STREAM)\n\ts1.bind(('localhost',5001))\n\ts1.listen(1)\n\tt1=threading.Thread(target=request_for_job)\n\tt2=threading.Thread(target=update_from_worker,args=(s1,))\n\tt1.start()\n\tt2.start()\n\tt1.join()\n\tt2.join()\nif __name__==\"__main__\":\n\tmain()\n\n","sub_path":"master.py","file_name":"master.py","file_ext":"py","file_size_in_byte":3359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"605060530","text":"import requests\nimport socket\n\nheaders = {\n \"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\"\n}\n\nQ = {\n \"key\": \"81d70d330760407b9102184d47874d2d\",\n \"location\": \"101190112\"\n}\n\nL = {\n \"key\": \"81d70d330760407b9102184d47874d2d\",\n \"location\": \"101280106\"\n}\n\nurl = \"https://devapi.qweather.com/v7/weather/now\"\n\n\ndef get_host_ip():\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect(('8.8.8.8', 80))\n ip = s.getsockname()[0]\n finally:\n s.close()\n\n return ip\n\n\ndef get_weather(name):\n if name == \"Q\":\n param = Q\n else:\n param = L\n res = \"\"\n try:\n response = requests.get(\n url=url,\n params=param,\n headers=headers,\n timeout=2.0\n )\n if response.status_code == 200:\n weather = response.json()[\"now\"]\n res = \"{0}:{1}/{2}/{3}%/{4}\".format(\n name,\n weather[\"temp\"],\n weather[\"feelsLike\"],\n weather[\"humidity\"],\n weather[\"text\"]\n )\n else:\n res = \"ERROR: {}\".format(response.status_code)\n except requests.Timeout:\n res = \"ERROR: TIMEOUT\"\n\n return res","sub_path":"get_info.py","file_name":"get_info.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"528084455","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def checkEqualTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n ## O(n) time complexity\n ## O(1) space complexity\n \n # edge case\n if not root:\n return False\n \n # get the total sum of values of each node in the tree\n total = self.getTotal(root)\n \n # if the total is odd, the answer is false\n if total%2 != 0:\n return False\n else:\n half = total//2\n \n # recurssively match the weight of a subtree with half the total of the tree\n def recur(node):\n '''\n input: TreeNode\n output: int, bool (subtree total, if the solution was found in any of its subtree)\n '''\n # edge case\n if not node:\n return 0, False\n \n # run on left and right subtree\n left, lbool = recur(node.left)\n right, rbool = recur(node.right)\n \n # compare\n if lbool or rbool:\n return 0, True\n else:\n if (node.left != None and left == half) or (node.right != None and right == half):\n return 0, True\n else:\n return left + node.val + right, False\n\n # run on root\n rval, rbool = recur(root)\n return rbool\n \n def getTotal(self,root):\n if not root:\n return 0\n \n return self.getTotal(root.left) + root.val + self.getTotal(root.right)\n \n \n \n","sub_path":"663. Equal Tree Partition/solution-optimized.py","file_name":"solution-optimized.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"99212147","text":"def count_primes(low,high):\n count = 0\n for i in range(low, high + 1):\n check = True\n if i > 1:\n for z in range(2, int(((i ** .5) + 1))):\n if (i % z) == 0:\n check = False\n if check == True:\n count += 1\n print(str(i) + ' is prime')\n return count\n","sub_path":"Codewars Highlights/Prime_counter.py","file_name":"Prime_counter.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"527922607","text":"# -*- encoding: utf-8 -*-\n#\n# Author: Endre Karlson \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 logging\nimport os\nimport pecan\nfrom oslo.config import cfg\nfrom wsgiref import simple_server\n\nfrom billingstack import service\nfrom billingstack.api import hooks\nfrom billingstack.openstack.common import log\n\ncfg.CONF.import_opt('state_path', 'billingstack.paths')\n\nLOG = log.getLogger(__name__)\n\n\ndef get_config():\n conf = {\n 'app': {\n 'root': 'billingstack.api.v2.controllers.root.RootController',\n 'modules': ['designate.api.v2'],\n }\n }\n return pecan.configuration.conf_from_dict(conf)\n\n\ndef setup_app(pecan_config=None, extra_hooks=None):\n app_hooks = [\n hooks.NoAuthHook()\n ]\n\n if extra_hooks:\n app_hooks.extend(extra_hooks)\n\n pecan_config = pecan_config or get_config()\n\n pecan.configuration.set_config(dict(pecan_config), overwrite=True)\n\n app = pecan.make_app(\n pecan_config.app.root,\n debug=cfg.CONF.debug,\n hooks=app_hooks,\n force_canonical=getattr(pecan_config.app, 'force_canonical', True)\n )\n\n return app\n\n\nclass VersionSelectorApplication(object):\n def __init__(self):\n self.v2 = setup_app()\n\n def __call__(self, environ, start_response):\n return self.v2(environ, start_response)\n\n\ndef start():\n service.prepare_service()\n\n root = VersionSelectorApplication()\n\n host = cfg.CONF['service:api'].api_listen\n port = cfg.CONF['service:api'].api_port\n\n srv = simple_server.make_server(host, port, root)\n\n LOG.info('Starting server in PID %s' % os.getpid())\n LOG.info(\"Configuration:\")\n \n \n cfg.CONF.log_opt_values(LOG, logging.INFO)\n\n if host == '0.0.0.0':\n LOG.info('serving on 0.0.0.0:%s, view at http://127.0.0.1:%s' %\n (port, port))\n else:\n LOG.info(\"serving on http://%s:%s\" % (host, port))\n\n srv.serve_forever()\n","sub_path":"billingstack/api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"136966526","text":"#!/usr/bin/env python\n\nimport tensorflow as tf\nimport json\nimport sys\nimport os\nimport shutil\n\nimport urllib\n\nfrom flask import Flask\nfrom flask import request\n\napp = Flask(__name__)\nservice = None\n\n\nclass InferenceService(object):\n def __init__(self, model, version, checkpoint_dir, graph_dir):\n self.model = model\n self.version = version\n self.checkpoint_dir = checkpoint_dir\n self.meta_graph_file = graph_dir\n\n self.sess = None\n self.inputs = None\n self.outputs = None\n self.load_model()\n\n def __del__(self):\n self.sess.close()\n\n def load_model(self):\n self.sess = tf.Session()\n\n ckpt = tf.train.get_checkpoint_state(self.checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n saver = tf.train.import_meta_graph(self.meta_graph_file)\n saver.restore(self.sess, ckpt.model_checkpoint_path)\n self.inputs = json.loads(tf.get_collection('inputs')[0])\n self.outputs = json.loads(tf.get_collection('outputs')[0])\n else:\n print(\"No model found, exit\")\n\n def process_json_file(self, json_file):\n result = []\n with open(json_file) as f:\n for line in f.readlines():\n # line = {'key': 1, 'X': 10.0, 'Y': 20.0}\n predict_sample = json.loads(line)\n result.append(self.process_request(predict_sample))\n return result\n\n def process_request(self, predict_sample):\n # request_data = {'key': 1, 'X': 10.0, 'Y': 20.0}\n # inputs = {'key_placeholder': placeholder1, 'X': placeholder2, 'Y': placeholder3}\n # outputs = {'key': identity_op, 'predict_op1': predict_op1, 'predict_op2': predict_op2}\n print(\"Request data: {}\".format(predict_sample))\n feed_dict = {}\n for key in self.inputs.keys():\n feed_dict[self.inputs[key]] = predict_sample[key]\n # TODO: this dict not works in docker container\n #response = self.sess.run(self.outputs, feed_dict=feed_dict)\n response = self.sess.run(self.outputs.values(), feed_dict=feed_dict)\n print(\"Response data: {}\".format(response))\n return response\n\n\n\n\n@app.route(\"/\", methods=[\"GET\"])\ndef index():\n return \"Test endpoint\"\n\n\n@app.route(\"/\", methods=[\"POST\"])\ndef main():\n # Predict request\n #json_file = \"./predict_sample.tensor.json\"\n #response = service.process_json_file(json_file)\n\n data = json.loads(request.data)\n\n result = []\n for predict_sample in data:\n response = service.process_request(predict_sample)\n result.append(response)\n\n return str(result)\n\n\nif __name__ == \"__main__\":\n\n #model = sys.argv[1]\n #version = sys.argv[2]\n # source = \"/tmp/mnist_160727_180616/model\"\n #source = sys.argv[3]\n\n model = \"mnist\"\n version = \"v1\"\n source = \"/tmp/mnist_160727_185504/model\"\n if os.path.exists(source) == False:\n os.makedirs(source)\n checkpoint_files = [\"checkpoint\"]\n for file in checkpoint_files:\n urllib.urlretrieve (\"https://raw.githubusercontent.com/tobegit3hub/tensorflow_examples/master/checkpoint_files/{}\".format(file), \"/tmp/mnist_160727_185504/model/{}\".format(file))\n checkpoint_files = [\"export-50100-00000-of-00001\", \"export-50100.meta\", \"export-60100-00000-of-00001\", \"export-60100.meta\", \"export-70100-00000-of-00001\", \"export-70100.meta\", \"export-80100-00000-of-00001\", \"export-80100.meta\", \"export-90100-00000-of-00001\", \"export-90100.meta\"]\n for file in checkpoint_files:\n urllib.urlretrieve (\"https://github.com/tobegit3hub/tensorflow_examples/blob/master/checkpoint_files/{}?raw=true\".format(file), \"/tmp/mnist_160727_185504/model/{}\".format(file))\n\n # /tmp/mnist/v7/\n new_model_path = os.path.join(\"/tmp\", model, version)\n if os.path.exists(new_model_path):\n print(\n \"The model {} with version {} exists, replce and run new model\".format(\n model, version))\n else:\n os.makedirs(new_model_path)\n\n for file in os.listdir(source):\n shutil.copy(os.path.join(source, file), new_model_path)\n\n checkpoint_dir = new_model_path\n #graph_dir = \"/tmp/mnist_160727_180616/model/export-60100.meta\"\n graph_dir = os.path.join(checkpoint_dir, \"export-60100.meta\")\n\n global service\n service = InferenceService(model, version, checkpoint_dir, graph_dir)\n\n app.run(host=\"0.0.0.0\")\n","sub_path":"kubernetes_platform/run_deploy/cmd.py","file_name":"cmd.py","file_ext":"py","file_size_in_byte":4410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"325446166","text":"#!/usr/bin/env python\nimport logging\n\nfrom docker_for_galaxy import start_container\n\nfrom ephemeris.shed_tools import InstallRepositoryManager\n\n# This line is needed because flake things the import for start_container is not used otherwise.\nstart_container_is_used = start_container\n\n\n# NOTE: For each series of tests that needs the same container, use the same class.\n# The start_container fixture has the \"class\" scope.\n\nclass TestMiscellaneous(object):\n \"\"\"This class is for miscellaneous tests that can use the same galaxy container\"\"\"\n\n def test_invalid_keys_in_repo_list(self, caplog, start_container):\n container = start_container\n irm = InstallRepositoryManager(container.gi)\n caplog.set_level(logging.WARNING)\n irm.install_repositories([\n dict(name=\"bwa\",\n owner=\"devteam\",\n tool_panel_section_name=\"NGS: Alignment\",\n sesame_ouvre_toi=\"Invalid key\")\n ], log=logging.getLogger())\n assert \"'sesame_ouvre_toi' not a valid key. Will be skipped during parsing\" in caplog.text\n","sub_path":"tests/test_shed_tools.py","file_name":"test_shed_tools.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"247713319","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport argparse\nfrom collections import defaultdict\nimport datetime\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-clip', action='store', type=str,\n help='The mirTargets-clip integrate file')\nparser.add_argument('-degradome', action='store', type=str,\n help='The mirTargets-degradome integrate file')\nparser.add_argument('-output', action='store', type=str, required=True,\n help='The integrated output file')\n\nargs = parser.parse_args()\nif len(sys.argv[1:])==0:\n parser.print_help()\n parser.exit()\n\nstarttime = datetime.datetime.now()\nsys.stderr.write(\"Program starting!\\n\")\n\nsys.stderr.write(\"reading mirTargets-degradome integrate file!\\n\")\n\nwith open(args.degradome, 'r') as f:\n degradList = f.readlines()\n\nsys.stderr.write(\"reading mirTargets-clip integrate file!\\n\")\nwith open(args.clip, 'r') as f:\n clipList = f.readlines()\n\nsys.stderr.write(\"Writing data to ouput!\\n\")\nwith open(args.output, 'w') as out:\n for i in range(len(clipList)):\n clipRow = clipList[i].strip().split('\\t')\n degradomeRow = degradList[i].strip().split('\\t')\n row = clipRow[0:11]\n clipExpNum = clipRow[11]\n clipSiteNum = clipRow[12]\n clipIDcat = clipRow[13]\n degradExpNum = degradomeRow[11]\n degradSiteNum = degradomeRow[12]\n degradIDcat = degradomeRow[13]\n row.extend([clipExpNum, clipSiteNum, clipIDcat, degradExpNum, degradSiteNum, degradIDcat])\n out.write('\\t'.join(row) + '\\n')\n\nendtime = datetime.datetime.now()\ncollapsed = (endtime - starttime).seconds\nsys.stderr.write(\"All jobs done!\\n\")\nsys.stderr.write(\"Total collapsed time: {0}s\\n\".format(collapsed))\n","sub_path":"miRmRNAwithSeq.py","file_name":"miRmRNAwithSeq.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"255095209","text":"from httplib2 import Http\r\nimport http\r\nfrom urllib.parse import urlencode\r\nfrom time import localtime, gmtime, strftime, strptime\r\nfrom base64 import b64encode\r\nfrom configparser import ConfigParser\r\nimport re\r\n\r\n\r\ndef get_current_time():\r\n return strftime(\"%Y-%m-%d--%H-%M-%S\", localtime())\r\n\r\n\r\ndef parse_fn_for_datetime(fn):\r\n print(fn)\r\n gr = re.match(r\"^.*-(\\d+)-(\\d+)-(\\d+)-(\\d+)_(\\d+)_(\\d+)\\.txt\",\r\n fn).groups(0)\r\n return \"%s-%s-%s--%s-%s-%s\" % (gr[0], gr[1], gr[2],\r\n gr[3], gr[4], gr[5])\r\n\r\n\r\nclass EventPutter(object):\r\n def __init__(self, id, host, protocol='http'):\r\n self.http_client = Http()\r\n self.id = id\r\n self.host = host\r\n self.protocol = protocol\r\n\r\n def put_event(self, fn):\r\n dt = parse_fn_for_datetime(fn)\r\n print(\"dt\", dt)\r\n ms = 0\r\n\r\n event_file = open(fn, 'r')\r\n chunk = event_file.read()\r\n event_file.close()\r\n\r\n data = {'dev_id': self.id,\r\n 'datetime': dt,\r\n 'ms' : ms,\r\n 'event_file': chunk}\r\n headers = {'Content-type': 'application/x-www-form-urlencoded',\r\n 'User-Agent': 'put_hantek_event.py'}\r\n url = \"%s://%s/put-hantek-event\" % (self.protocol, self.host)\r\n resp, content = self.http_client.request(url, \"POST\",\r\n headers=headers,\r\n body=urlencode(data))\r\n print(resp, \"\\n\", content)\r\n\r\n\r\nclass EventPutterConf(EventPutter):\r\n def __init__(self, config_fn):\r\n config = ConfigParser()\r\n config.read(config_fn)\r\n\r\n EventPutter.__init__(self,\r\n int(config['CLIENT']['id']),\r\n config['CLIENT']['host'])\r\n\r\n\r\nif __name__ == '__main__':\r\n from sys import argv\r\n\r\n evp = EventPutterConf('hantek_clicker.ini')\r\n evp.put_event(argv[1])\r\n","sub_path":"clients/hantek_clicker/put_hantek_event.py","file_name":"put_hantek_event.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"144568622","text":"import matplotlib\nmatplotlib.use('Agg')\nimport pymc3 as pm\nimport scipy\nimport numpy as np\nimport pandas as pd\nimport theano\nimport theano.tensor as T\nimport time\nfrom matplotlib import pyplot as plt\nfrom pymc3.distributions.timeseries import GaussianRandomWalk\n\ntheano.config.compute_test_value = 'raise'\n#theano.config.gcc.cxxflags = \"-fbracket-depth=16000 -O0\" # default is 256 | compilation optimizations are turned off for faster compilation\ntheano.config.exception_verbosity= 'high'\ntheano.config.openmp = True # this isn't working with gcc for some reason\ntheano.config.optimizer = 'fast_compile'\n\ndef load_data():\n temp_expected = pd.read_csv('../data/csv/expected.csv')\n E = theano.shared(np.array(temp_expected['x']))\n \n temp_sim = pd.read_csv('../data/csv/simulated.csv')\n temp_times = temp_sim[['Time1', 'Time2', 'Time3', 'Time4', 'Time5', 'Time6', 'Time7', 'Time8', 'Time9', 'Time10', 'Time11', 'Time12', 'Time13', 'Time14', 'Time15']]\n observed_values = np.matrix(temp_times)\n \n adj = pd.read_csv('../data/csv/adjacency.csv', index_col=0)\n W = np.matrix(adj)\n \n numRegions = observed_values.shape[0] #number of regions\n nt = observed_values.shape[1] #number of time points\n \n #making the inverse covariance matricies for the CAR models (ignoring their variances)\n alpha = 0.75 #this was 1 in the model but that makes the covariance matrix singular\n D = np.diag(np.array(W.sum(0))[0]) #diag(d_1,..,d_numRegions) with d_i the number of neighbours of region i\n Tau_v_unscaled = theano.shared(np.array(D - alpha*W))\n\n return numRegions, nt, E, Tau_v_unscaled, observed_values\n\nprob_z = 0.95 #probability of a region following the area specific model\n\nnumRegions, nt, E, Tau_v_unscaled, observed_values = load_data()\n\nmodel = pm.Model()\n\nobserved_values = theano.shared(observed_values)\n\n\nprint('Data loaded')\n\nprint('Starting time: ', time.ctime())\n\nnt = 3\n\nwith model:\n \"\"\"\n BYM prior on the spatial component\n \n lambda ~ Normal(v_i, sigma_lambda)\n \n v ~ CAR(W, sigma_v)\n \n where W is the adjacency matrix.\n \n The CAR model is equivalent to,\n \n v ~ N(0, T^-1)\n \n with, T = (D - alpha*W)*sigma_v\n \n D = diag(d_1, ..., d_n)\n d_i = 'degree' of region i\n alpha = level of spatial dependence \n \n We place vague priors on the variances.\n \n \"\"\"\n sigma_v = pm.HalfNormal('sigma_v', sd=1) # change this to something more vague\n sigma_lambda = pm.HalfNormal('sigma_lambda', sd=1)\n \n Tau_v = Tau_v_unscaled*sigma_v #covariance matirx for v\n v = pm.MvNormal('v',mu=np.zeros(numRegions), tau=Tau_v, shape=numRegions)\n lmbda = pm.MvNormal('lambda', mu=v, cov=np.identity(numRegions)*sigma_lambda, shape=numRegions)\n \n \n sigma_temporal = pm.HalfNormal('sigma_xi', sd=1)\n temporal = GaussianRandomWalk('temporal', sd=sigma_temporal, shape=nt)\n \n \n # mu_it = Expected*exp(lambda_i + temporal_t)\n \n mu_temp = [] #rate parameters over the time points\n for i in range(numRegions):\n mu_temp.append(T.stack([E[i]*T.exp(lmbda[i] + temporal[t]) for t in range(nt)]))\n mu = T.stack(mu_temp)\n \n observed = pm.Poisson('observed', mu = mu, observed=observed_values[:, :nt], shape=(numRegions, nt))\n \nprint('Model defined at ', time.ctime())\n\nwith model:\n step = pm.Metropolis()\n print('Metropolis initialized')\n db = pm.backends.Text('trace_save')\n trace = pm.sample(draws=2000, trace=db, step=step)\n\nprint('End time: ', time.ctime())\n\n#trace_burn = trace[:][3000:]\npm.traceplot(trace)\nplt.savefig('trace.png')\n\n#trace = pm.backends.text.load('test')\n","sub_path":"model/old/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"636552691","text":"from fractions import Fraction\n\nfrom .utils import ConfigDictMixin\n\n\"\"\"Store grades for components and parts.\"\"\"\n\n\nclass AssignmentComponentGrade(ConfigDictMixin):\n \"\"\"Hold the score for an assignment component.\"\"\"\n\n def __init__(self, part_grades=None, error=None, error_verbose=None):\n self.part_grades = part_grades\n self.error = error\n self.error_verbose = error_verbose\n\n if (self.part_grades is None) == (self.error is None):\n raise ValueError('need to specify either part-grades or error in '\n 'an AssignmentComponentGrade, but not both')\n\n def __repr__(self):\n return '' \\\n .format(self.part_grades)\n\n @classmethod\n def from_config_dict(cls, dict_):\n grade = super(AssignmentComponentGrade, cls).from_config_dict(dict_)\n if grade.part_grades:\n grade.part_grades = [PartGrade.from_config_dict(g)\n for g in grade.part_grades]\n return grade\n\n def to_config_dict(self, *args):\n dict_ = super(AssignmentComponentGrade, self).to_config_dict(*args)\n if dict_.get('part-grades', None):\n dict_['part-grades'] = [g.to_config_dict()\n for g in dict_['part-grades']]\n return dict_\n\n def is_broken(self):\n \"\"\"\n Return True if and only if this submission was 'broken'; that\n is, processing it produced an unrecoverable error such as a\n missing file or noncompiling code.\n \"\"\"\n return self.error is not None\n\n def calculate_grade(self, component_parts):\n # type: (List[ComponentPart]) -> fractions.Fraction\n \"\"\"\n Using the list of ComponentPart instances provided (which\n contain the weight of components) and the part grades held in\n this instance, calculate the percentage of this component\n earned.\n \"\"\"\n if self.is_broken():\n return Fraction(0)\n else:\n total_possible = sum(part.weight for part in component_parts)\n total_earned = sum(grade.score * part.weight\n for grade, part\n in zip(self.part_grades, component_parts))\n return Fraction(total_earned, total_possible)\n\n\nclass PartGrade(ConfigDictMixin):\n \"\"\"\n Hold the results of grading one part.\n\n score is the percentage passed as a Fraction instance, deductions is\n a list of deduction ids, and log is a string containing verbose logs\n for this part.\n \"\"\"\n\n __slots__ = ('score', 'deductions', 'log')\n\n def __init__(self, score, deductions=None, log=None):\n self.score = Fraction(score)\n self.deductions = deductions\n self.log = log\n\n def __repr__(self):\n return '' \\\n .format(self.score, self.deductions, self.log)\n\n def to_config_dict(self, *exclude):\n result = super(PartGrade, self).to_config_dict(exclude)\n # Convert Fraction instance to a string\n result['score'] = str(result['score'])\n return result\n\n @classmethod\n def from_config_dict(cls, config_dict):\n part_grade = super(PartGrade, cls).from_config_dict(config_dict)\n # Convert string to Fraction instance\n part_grade.score = Fraction(part_grade.score)\n return part_grade\n","sub_path":"zucchini/grades.py","file_name":"grades.py","file_ext":"py","file_size_in_byte":3455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"238545663","text":"# -----------------------\n# HEADER \n# -----------------------\n# Filename main.py\n# Python Version 3.6.10\n# Creator Rob Gauer\n#\n# -----------------------\n# ASSIGNMENT INSTRUCTIONS\n# ----------------------- \n# PyPoll\n#\n#\t• In this challenge, you are tasked with helping a small, rural town modernize its vote-counting process. \n# (Up until now, Uncle Cleetus had been trustfully tallying them one-by-one, but unfortunately, \n# his concentration is not what it used to be.)\n#\t• You will be give a set of poll data called election_data.csv. \n# The dataset is composed of three columns: Voter ID, County, and Candidate. \n# Your task is to create a Python script that analyzes the votes and calculates each of the following:\n#\t\tA. The total number of votes cast\n#\t\tB. A complete list of candidates who received votes\n#\t\tC. The percentage of votes each candidate won\n#\t\tD. The total number of votes each candidate won\n#\t\tE. The winner of the election based on popular vote.\n# F. In addition, your final script should both print the analysis to the terminal and \n# export a text file with the results.\n#\t\n# As an example, your analysis should look similar to the one below:\n#\n# Election Results\n# -------------------------\n# Total Votes: 3521001\n# -------------------------\n# Khan: 63.000% (2218231)\n# Correy: 20.000% (704200)\n# Li: 14.000% (492940)\n# OTooley: 3.000% (105630)\n# -------------------------\n# Winner: Khan\n# -------------------------\n#\n# -----------------------\n# PROGRAM CODE\n# -----------------------\n# _________________________________________________________\n# IMPORT CSV FILE\n# Read dataset file called election_data.csv. Import CSV file.\n# First we'll import the os module. This will allow us to create file paths across operating systems\nimport os\n# Module for reading CSV files\nimport csv\n\n# _________________________________________________________\n# IMPORT FILE # Locate source data path location\nPyPollcsv = os.path.join(\"Resources\",\"election_data.csv\")\n\n# _________________________________________________________\n# VARIABLES and LISTS\ntotal_votes = 0\ncandidate = \"\"\ncandidate_votes = {}\ncandidate_percentages ={}\nwinner_votes = 0\nwinner = \"\"\ndashsterminal = \" ------------------------------\"\ndashs = \" ----------------------------------\"\n\n# _________________________________________________________\n# IMPORT FILE # Open csv file\nwith open(PyPollcsv, newline=\"\") as csvfile:\n csvreader = csv.reader(csvfile, delimiter=\",\")\n\n next(csvreader)\n\n # _________________________________________________________ \n # A. The total number of votes cast\n for row in csvreader:\n total_votes = total_votes + 1\n candidate = row[2]\n if candidate in candidate_votes:\n candidate_votes[candidate] = candidate_votes[candidate] + 1\n else:\n candidate_votes[candidate] = 1\n\n# _________________________________________________________\n# B. A complete list of candidates who received votes\n# C. The percentage of votes each candidate won\n# D. The total number of votes each candidate won\n# E. The winner of the election based on popular vote.\n# calculate vote percentage and identify winner\nfor person, vote_count in candidate_votes.items():\n candidate_percentages[person] = '{0:.0%}'.format(vote_count / total_votes)\n if vote_count > winner_votes:\n winner_votes = vote_count\n winner = person\n\n# _________________________________________________________\n# F. Final script should both print the analysis to the terminal \n# and export a text file with the results\n# DISPLAY TO TERMINAL\nprint()\nprint()\nprint(\" Election Results\")\nprint(dashsterminal)\nprint(f\" Total Votes: {total_votes}\")\nprint(dashsterminal)\nfor person, vote_count in candidate_votes.items():\n print(f\" {person}: {candidate_percentages[person]} ({vote_count})\")\nprint(dashsterminal)\nprint(f\" Winner: {winner}\")\nprint(dashsterminal)\nprint()\nprint()\n\n# EXPORT to FILE # export a text file with the results\ntextoutput_path = os.path.join(\"..\", \"Output\", \"election_results.txt\")\nwith open('electrion_results.txt', 'w') as text:\n text.write(\" Election Results\\n\")\n text.write(dashs + \"\\n\")\n text.write(f\" Total Votes: {total_votes}\" + \"\\n\")\n text.write(dashs + \"\\n\")\n for person, vote_count in candidate_votes.items():\n text.write(f\" {person}: {candidate_percentages[person]} ({vote_count})\" + \"\\n\")\n text.write(dashs + \"\\n\")\n text.write(f\" Winner: {winner}\" + \"\\n\")\n text.write(dashs + \"\\n\")\n\n# ----------------------- \n# EOF\n# -----------------------","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"623874117","text":"#############################################################################\n#############################################################################\n################### Interpolate AQD and ADCP vertically ######################\n#############################################################################\n#############################################################################\n\nfrom aux_funcs import *\n\n#############################################################################\n################### Start with AQD data, then add ADCP and interp############\n#############################################################################\n\ndef Interp_vel(moornum):\n\n moorname='CF'+str(moornum)\n\n if moorname=='CF8':\n aqdlist=hstack((glob.glob(datadir+'NOC_M1/nocm1_01_2014/nor/*.edt'),\n glob.glob(datadir+'NOC_M1/nocm1_02_2015/nor/*.edt')))\n else:\n aqdlist=glob.glob(datadir+'AQD_Data_CF/OS_OSNAP-'+moorname+'*.nc')\n\n\n\n figure(figsize=(12,10))\n\n time=array([])\n u=array([])\n v=array([])\n prs=array([])\n meanprs=array([])\n date=array([])\n\n for dd in aqdlist:\n print(dd)\n if moorname=='CF8':\n dat=pd.read_csv(dd,header=12,sep='\\s*')\n prs_tmp=hrly_ave(dat.ix[:,5],hrcon)\n date_tmp=unique([datetime.datetime(int(dat.ix[ii,0]),\n int(dat.ix[ii,1]),\n int(dat.ix[ii,2])) for ii in range(len(dat))])[:len(prs_tmp)]\n time_tmp=array([datetime.datetime.toordinal(adate) for adate in date_tmp])\n u_tmp=hrly_ave(dat.ix[:,6]/100,hrcon)\n v_tmp=hrly_ave(dat.ix[:,7]/100,hrcon)\n mprs_tmp=mean(dat.ix[:,5])*ones(len(date_tmp))\n\n else:\n dat = Dataset(dd, 'r')\n u_tmp=hrly_ave([float(tt) for tt in dat.variables['UCUR'][:].flatten()],hrcon*2)\n v_tmp=hrly_ave([float(tt) for tt in dat.variables['VCUR'][:].flatten()],hrcon*2)\n prs_tmp=hrly_ave(list(dat.variables['PRES'][:].flatten()),hrcon*2)\n time_tmp=list(dat.variables['TIME'][:])[::hrcon*2][:len(prs_tmp)]\n mprs_tmp=nanmean(prs_tmp)*ones(len(time_tmp))\n date_tmp=array([datetime.datetime(1950,1,1)+datetime.timedelta(days=int(tt))\n for tt in time_tmp])\n u_tmp=u_tmp[:len(date_tmp)]\n v_tmp=v_tmp[:len(date_tmp)]\n prs_tmp=prs_tmp[:len(date_tmp)]\n\n prs=hstack((prs,prs_tmp))\n u=hstack((u,u_tmp))\n v=hstack((v,v_tmp))\n\n meanprs=hstack((meanprs,mprs_tmp))\n date=hstack((date,date_tmp))\n time=hstack((time,time_tmp))\n\n subplot(311)\n plot(date_tmp,prs_tmp)\n ylabel('pressure')\n subplot(312)\n plot(date_tmp,u_tmp)\n ylabel('u')\n subplot(313)\n plot(date_tmp,v_tmp)\n ylabel('v')\n\n len(date_tmp)\n len(prs_tmp)\n\n ##### Choose time and pressure bins\n #units are db\n pstep=2\n\n ##### Now add ADCP data\n\n lat=60\n\n\n ua=array([])\n va=array([])\n prsa=array([])\n meanprs=array([])\n datea=array([])\n if moorname=='CF8':\n adcplist=hstack((glob.glob(datadir+'NOC_M1/nocm1_01_2014/adcp/*.edt'),\n glob.glob(datadir+'NOC_M1/nocm1_02_2015/adcp/*.edt')))\n for dd in adcplist:\n print(dd)\n dat=pd.read_csv(dd,header=12,sep='\\s*')\n prs_tmp=hrly_ave(gsw.p_from_z(-dat.ix[:,4],lat),hrcon)\n datea_tmp=unique([datetime.datetime(int(dat.ix[ii,0]),\n int(dat.ix[ii,1]),\n int(dat.ix[ii,2])) for ii in range(len(dat))])[:len(prs_tmp)]\n ua_tmp=hrly_ave(dat.ix[:,6]/100,hrcon)\n va_tmp=hrly_ave(dat.ix[:,7]/100,hrcon)\n prsa=hstack((prsa,prs_tmp))\n ua=hstack((ua,ua_tmp))\n va=hstack((va,va_tmp))\n datea=hstack((datea,datea_tmp))\n plot(datea_tmp,ua_tmp)\n plot(datea_tmp,va_tmp)\n\n else:\n dat=io.loadmat(datadir+'ADCP_Data_CF/OSNAP_cf'+str(moornum)+'_Final1_ilebras.mat')\n shapmat=shape(dat['u'])\n shapmat1=int(shape(dat['u'])[1]/24)+1\n datea_tmp=unique([datetime.datetime(int(tt[0]),int(tt[1]),int(tt[2])) for tt in dat['time']])[:shapmat1]\n # Note that adcp \"depths\" from Dan Torres are also in db...\n prsa_tmp=zeros((shapmat[0],shapmat1))\n ua_tmp=zeros((shapmat[0],shapmat1))\n va_tmp=zeros((shapmat[0],shapmat1))\n for ii in range(shapmat[0]):\n prsa_tmp[ii,:]=hrly_ave(dat['z'][ii,:],hrcon)\n ua_tmp[ii,:]=hrly_ave(dat['u'][ii,:],hrcon)\n va_tmp[ii,:]=hrly_ave(dat['v'][ii,:],hrcon)\n\n ua=ua_tmp.flatten()\n va=va_tmp.flatten()\n prsa=prsa_tmp.flatten()\n datea=tile(datea_tmp,[1,shapmat[0]]).flatten()\n\n\n figure()\n plot(prsa)\n title('pressure')\n\n figure()\n plot(ua)\n title('u')\n\n figure()\n plot(va)\n title('v')\n\n pdall=pd.DataFrame({'pressure':hstack((prsa,prs)),\n 'u':hstack((ua,u)),\n 'v':hstack((va,v)),\n 'date bin':hstack((datea,date))})\n\n\n\n pdall['u'][pdall['u']<-2]=NaN\n pdall['v'][pdall['v']<-2]=NaN\n\n\n if moornum==4:\n plim=40\n else:\n plim=0\n\n pdall=pdall[pdall['pressure']>=plim]\n\n common_mindate=max(min(datea),min(date))\n common_maxdate=min(max(datea),max(date))\n\n common_maxdate\n\n prsvec=arange(0,int(max(pdall['pressure']))+1,2)\n\n\n dmin=min(pdall['date bin'])\n dmax=max(pdall['date bin'])\n dlen=int(divmod((dmax-dmin).total_seconds(),60*60*24)[0])+1\n datevec = array([dmin + datetime.timedelta(days=x) for x in range(0, dlen)])\n\n\n u_interp=pivspline_ML('u',datevec,prsvec,pdall)\n\n v_interp=pivspline_ML('v',datevec,prsvec,pdall)\n\n u_interp[(u_interp<-2) | (u_interp>1.5)]=nan\n v_interp[(v_interp<-2) | (v_interp>1.5)]=nan\n\n figure(figsize=(12,4))\n subplot(121)\n plot(u_interp,prsvec);\n plot(pdall['u'],pdall['pressure'],'k.');\n gca().invert_yaxis()\n title('u, zonal velocity (m/s)')\n ylabel('pressure (db)')\n subplot(122)\n plot(v_interp,prsvec);\n plot(pdall['v'],pdall['pressure'],'k.');\n gca().invert_yaxis()\n title('v, meridional velocity (m/s)')\n savefig('../figures/interpolation/VEL/'+moorname+'_uv_measinterp.png',bbox_inches='tight')\n\n\n plotcontour(u_interp,cm.RdBu_r,-2,2,moorname)\n savefig('../figures/interpolation/VEL/'+moorname+'_ucontour.png',bbox_inches='tight')\n\n\n plotcontour(v_interp,cm.RdBu_r,-2,2,moorname)\n savefig('../figures/interpolation/VEL/'+moorname+'_vcontour.png',bbox_inches='tight')\n\n\n pickle.dump([u_interp,v_interp],open('../pickles/VELinterp/'+moorname+'_uvinterp_SAtheta.pickle','wb'))\n","sub_path":"oldscripts/Interp_AQD_ADCP_1801messup.py","file_name":"Interp_AQD_ADCP_1801messup.py","file_ext":"py","file_size_in_byte":6879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"71593863","text":"# Exercise 5: This program records the domain name (instead of the address) where the message was sent from instead of who the mail came from (i.e., the whole email address). \n# At the end of the program, print out the contents of your dictionary.\n\n#file = open(input(\"Enter a file name: \"))\n#count = dict()\n#for line in file:\n# if not line.startswith('From'):\n# continue\n# if line.startswith('From:'):\n# continue\n# else:\n# line = line.split()\n# line = line[1]\n# line = line.split(\"@\")\n# line = line[1]\n# count[line] = count.get(line, 0) + 1\n\n#print(count)\n\n# These solutions produce the same results\n\nfile = open(input(\"Enter a file name: \"))\ncount = dict()\nfor line in file:\n words = line.split()\n # guardian in a compound statement\n if len(words) < 3 or words[0] != \"From\":\n continue\n else:\n words = words[1]\n words = words.split(\"@\")\n words = words[1]\n count[words] = count.get(words, 0) + 1\n\nprint(count)\n","sub_path":"10-Dictionaries/05-domain_email_address.py","file_name":"05-domain_email_address.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"219551649","text":"# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n ARKspatial\n A QGIS plugin for Archaeological Recording.\n Part of the Archaeological Recording Kit by L - P : Archaeology\n http://ark.lparchaeology.com\n -------------------\n copyright : 2017 by L - P : Heritage LLP\n email : ark@lparchaeology.com\n copyright : 2017 by John Layt\n email : john@layt.net\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program is free software; you can redistribute it and/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\nfrom PyQt4.QtCore import QCoreApplication, QFile, QFileInfo, QPoint, QPointF, QRectF\nfrom PyQt4.QtGui import QDialog, QGraphicsScene, QPixmap\n\nfrom qgis.core import QgsPoint\n\nfrom ArkSpatial.ark.lib import utils\nfrom ArkSpatial.ark.lib.core import ProcessStatus, Scale, geometry\n\nfrom ArkSpatial.ark.core import Drawing, Item\n\nfrom .georeferencer import Georeferencer\nfrom .transform import Transform\nfrom .ui.georef_dialog_base import Ui_GeorefDialogBase\n\n\nclass GeorefDialog(QDialog, Ui_GeorefDialogBase):\n\n def __init__(self, types, parent=None):\n super(GeorefDialog, self).__init__(parent)\n self.setupUi(self)\n\n # Internal variables\n self._closeOnDone = False\n self._types = {}\n self._georeferencer = None\n\n self._types = types\n self._scene = QGraphicsScene(self)\n self._georeferencer = Georeferencer(self)\n self._georeferencer.status.connect(self._updateStatus)\n self._georeferencer.error.connect(self._updateError)\n\n # Init the gui\n for group in self._types:\n self.typeCombo.addItem(self._types[group]['name'], group)\n self.typeCombo.setCurrentIndex(0)\n\n for scale in Scale.Scale:\n self.scaleCombo.addItem(Scale.Label[scale], scale)\n self.scaleCombo.setCurrentIndex(Scale.OneToTwenty)\n\n self.processButton.clicked.connect(self._process)\n self.saveButton.clicked.connect(self._save)\n self.runButton.clicked.connect(self._run)\n self.closeButton.clicked.connect(self._close)\n self.siteEdit.textChanged.connect(self._updateGeoreference)\n self.typeCombo.currentIndexChanged.connect(self._updateGeoreference)\n self.scaleCombo.currentIndexChanged.connect(self._updateGeoreference)\n self.numberSpin.valueChanged.connect(self._updateGeoreference)\n self.suffixEdit.textChanged.connect(self._updateGeoreference)\n self.eastSpin.valueChanged.connect(self._updateGeoreference)\n self.northSpin.valueChanged.connect(self._updateGeoreference)\n\n def loadImage(self, inputFile):\n self._setStatusLabel('load', ProcessStatus.Running)\n if (not inputFile.exists()):\n self._showStatus('ERROR: Input file not found! File path was ' + inputFile.absoluteFilePath())\n self._setStatusLabel('load', ProcessStatus.Failure)\n return False\n\n self._inputFile = inputFile\n pixmap = QPixmap(self._inputFile.absoluteFilePath())\n if pixmap.isNull():\n self._signalError('Loading of raw image failed.')\n return\n\n pixmap = QPixmap(self._inputFile.absoluteFilePath())\n w = pixmap.width()\n h = pixmap.height()\n\n self._scene.addPixmap(pixmap)\n self._scene.setSceneRect(QRectF(0, 0, w, h))\n\n self.planView.setSceneView(self._scene, QRectF(0, 0, w, h))\n self.headerView.setSceneView(self._scene, QRectF(0, 0, w, 200))\n self.footerView.setSceneView(self._scene, QRectF(100, h - 600, w - 200, 500))\n\n self.gcpWidget1.setScene(self._scene, 250, 100, 2)\n self.gcpWidget2.setScene(self._scene, 250, 3050, 2)\n self.gcpWidget3.setScene(self._scene, 3200, 3050, 2)\n self.gcpWidget4.setScene(self._scene, 3200, 100, 2)\n\n self.inputFileNameLabel.setText(self._inputFile.baseName())\n drawing = Drawing(self._inputFile)\n if drawing.isValid():\n self.siteEdit.setText(drawing.item().siteCode())\n self.typeCombo.setCurrentIndex(self.typeCombo.findData(drawing.item().classCode()))\n self.numberSpin.setValue(int(drawing.item().itemId()) or 0)\n self.eastSpin.setValue(drawing.easting() or 0)\n self.northSpin.setValue(drawing.northing() or 0)\n self.suffixEdit.setText(drawing.suffix())\n self._updateFileNames(drawing)\n self._updateGeoPoints()\n pointFile = self.pointFileInfo()\n if pointFile.exists():\n self._loadGcp(pointFile.absoluteFilePath())\n self._setStatusLabel('load', ProcessStatus.Success)\n QCoreApplication.processEvents()\n return True\n\n return False\n\n def _loadGcp(self, path):\n gc = Georeferencer.loadGcpFile(path)\n gcTo = Transform()\n for index in gc.points():\n gcp = gc.point(index)\n if gcp.map() == self.gcpWidget1.gcp().map():\n gcTo.setPoint(1, gcp)\n elif gcp.map() == self.gcpWidget2.gcp().map():\n gcTo.setPoint(2, gcp)\n elif gcp.map() == self.gcpWidget3.gcp().map():\n gcTo.setPoint(3, gcp)\n elif gcp.map() == self.gcpWidget4.gcp().map():\n gcTo.setPoint(4, gcp)\n\n if gcTo.isValid() and len(gcTo.points()) == 4:\n self.gcpWidget1.setRaw(gcTo.point(1).raw())\n self.gcpWidget2.setRaw(gcTo.point(2).raw())\n self.gcpWidget3.setRaw(gcTo.point(3).raw())\n self.gcpWidget4.setRaw(gcTo.point(4).raw())\n\n def _updateGeoPoints(self):\n mapUnits = Scale.Factor[self.drawingScale()]\n local1 = QPointF(self.eastSpin.value(), self.northSpin.value() + mapUnits)\n local2 = QPointF(self.eastSpin.value(), self.northSpin.value())\n local3 = QPointF(self.eastSpin.value() + mapUnits, self.northSpin.value())\n local4 = QPointF(self.eastSpin.value() + mapUnits, self.northSpin.value() + mapUnits)\n\n if self.drawingType() == 'sec':\n self.gcpWidget1.setGeo(local1, QgsPoint(local1))\n self.gcpWidget2.setGeo(local2, QgsPoint(local2))\n self.gcpWidget3.setGeo(local3, QgsPoint(local3))\n self.gcpWidget4.setGeo(local4, QgsPoint(local4))\n return\n\n typ = self._type()\n gridLayer = typ['grid']\n features = gridLayer.getFeatures()\n localX = gridLayer.fieldNameIndex(typ['local_x'])\n localY = gridLayer.fieldNameIndex(typ['local_y'])\n for feature in features:\n local = QPoint(feature.attributes()[localX], feature.attributes()[localY])\n map = geometry.toPoint(feature.geometry().geometry())\n if local == local1:\n self.gcpWidget1.setGeo(local, map)\n elif local == local2:\n self.gcpWidget2.setGeo(local, map)\n elif local == local3:\n self.gcpWidget3.setGeo(local, map)\n elif local == local4:\n self.gcpWidget4.setGeo(local, map)\n\n def _updateGeoreference(self):\n self._updateFileNames(self.drawing())\n self._updateGeoPoints()\n\n def _updateFileNames(self, drawing):\n self.rawFileNameLabel.setText(drawing.baseName())\n self.geoFileNameLabel.setText(drawing.baseName() + self._type()['suffix'])\n\n def _toggleUi(self, status):\n self.processButton.setEnabled(status)\n self.saveButton.setEnabled(status)\n self.runButton.setEnabled(status)\n self.closeButton.setEnabled(status)\n self.siteEdit.setEnabled(status)\n self.typeCombo.setEnabled(status)\n self.numberSpin.setEnabled(status)\n self.suffixEdit.setEnabled(status)\n self.eastSpin.setEnabled(status)\n self.northSpin.setEnabled(status)\n self.cropCheck.setEnabled(status)\n self.addToMapCheck.setEnabled(status)\n self.gcpWidget1.setEnabled(status)\n self.gcpWidget2.setEnabled(status)\n self.gcpWidget3.setEnabled(status)\n self.gcpWidget4.setEnabled(status)\n self.planView.setEnabled(status)\n if (status):\n self.progressBar.setRange(0, 100)\n else:\n self.progressBar.setRange(0, 0)\n\n def drawing(self):\n return Drawing(self.item(), self.easting(), self.northing(), self.suffix(), self.rawFileName())\n\n def item(self):\n return Item(self.siteCode(), self.classCode(), self.itemId())\n\n def siteCode(self):\n return self.siteEdit.text().strip()\n\n def classCode(self):\n return self.drawingType()\n\n def itemId(self):\n return unicode(self.numberSpin.value())\n\n def drawingType(self):\n return self.typeCombo.itemData(self.typeCombo.currentIndex())\n\n def drawingScale(self):\n return self.scaleCombo.itemData(self.scaleCombo.currentIndex())\n\n def easting(self):\n return self.eastSpin.value()\n\n def northing(self):\n return self.northSpin.value()\n\n def suffix(self):\n return self.suffixEdit.text().strip()\n\n def inputFileName(self):\n return self.inputFileNameLabel.text().strip()\n\n def rawFileName(self):\n return self.rawFileNameLabel.text().strip()\n\n def rawFileInfo(self):\n return QFileInfo(self._type()['raw'], self.rawFileName() + '.' + self._inputFile.suffix())\n\n def pointFileInfo(self):\n return QFileInfo(self._type()['raw'], self.rawFileName() + '.' + self._inputFile.suffix() + '.points')\n\n def geoFileName(self):\n return self.geoFileNameLabel.text().strip()\n\n def geoFileInfo(self):\n return QFileInfo(self._type()['geo'], self.geoFileName() + '.tif')\n\n def _type(self):\n return self._types[self.drawingType()]\n\n def _updateStatus(self, step, status):\n self._setStatusLabel(step, status)\n self._showStatus(Georeferencer.Label[step] + ': ' + ProcessStatus.Label[status])\n if step == Georeferencer.Stop and status == ProcessStatus.Success:\n if self._closeOnDone:\n self._close()\n else:\n self._toggleUi(True)\n\n def _updateError(self, step, msg):\n self._setStatusLabel(step, ProcessStatus.Failure)\n self._showStatus(msg)\n self._toggleUi(True)\n\n def _showStatus(self, text):\n self.statusBar.showMessage(text)\n\n def _save(self):\n self._copyInputFile()\n self._saveGcp()\n self._close()\n\n def _copyInputFile(self):\n if self.inputFileName() != self.rawFileName() or self._inputFile.dir() != self._type()['raw']:\n QFile.copy(self._inputFile.absoluteFilePath(), self.rawFileInfo().absoluteFilePath())\n\n def _saveGcp(self):\n gc = self._gc()\n if (gc.isValid()):\n Georeferencer.writeGcpFile(gc, self.pointFileInfo().absoluteFilePath())\n\n def _run(self):\n self._runGeoreference(False)\n\n def _process(self):\n self._runGeoreference(True)\n\n def _close(self):\n if (self._georeferencer.step() == Georeferencer.Stop):\n self.accept()\n else:\n self.reject()\n\n def _gc(self):\n gc = Transform()\n gc.crs = self._type()['crs']\n gc.setPoint(1, self.gcpWidget1.gcp())\n gc.setPoint(2, self.gcpWidget2.gcp())\n gc.setPoint(3, self.gcpWidget3.gcp())\n gc.setPoint(4, self.gcpWidget4.gcp())\n return gc\n\n def _runGeoreference(self, closeOnDone):\n self._closeOnDone = closeOnDone\n gc = self._gc()\n if (not gc.isValid()):\n self._showStatus('ERROR: Please set all 4 Ground Control Points!')\n return\n self._toggleUi(False)\n self._copyInputFile()\n QCoreApplication.processEvents()\n self._georeferencer.run(gc, self.rawFileInfo(), self.pointFileInfo(), self.geoFileInfo())\n\n def _finished(self, step, status):\n if step == Georeferencer.Stop and status == ProcessStatus.Success and self._closeOnDone:\n self._close()\n else:\n self._toggleUi(True)\n\n def _setStatusLabel(self, step, status):\n if step == 'load':\n label = self.loadStatusLabel\n elif step == Georeferencer.Crop:\n label = self.cropStatusLabel\n elif step == Georeferencer.Translate:\n label = self.translateStatusLabel\n elif step == Georeferencer.Warp:\n label = self.warpStatusLabel\n elif step == Georeferencer.Overview:\n label = self.overviewStatusLabel\n else:\n return\n\n if status == ProcessStatus.Success:\n label.setPixmap(QPixmap(':/plugins/ark/georef/success.png'))\n elif status == ProcessStatus.Failure:\n label.setPixmap(QPixmap(':/plugins/ark/georef/failure.png'))\n elif status == ProcessStatus.Running:\n label.setPixmap(QPixmap(':/plugins/ark/georef/running.png'))\n else:\n label.setPixmap(QPixmap(':/plugins/ark/georef/unknown.png'))\n","sub_path":"ark/georef/georef_dialog.py","file_name":"georef_dialog.py","file_ext":"py","file_size_in_byte":13686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"364813004","text":"from math import sqrt\nfrom common import prime_table, Watch\n\nWatch.start()\nlim = 10000\nprime_t = prime_table(lim)\nprimes = [p for p in range(2, lim) if prime_t[p]]\nfor odd in range(9, lim, 2):\n if not prime_t[odd]:\n i, found = 0, False\n while primes[i] < odd:\n if sqrt((odd - primes[i]) / 2) % 1 == 0:\n found = True\n break\n i += 1\n if not found:\n print(odd)\n break\nWatch.stop()\n\n ","sub_path":"1_49/src/task46/s46.py","file_name":"s46.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"570803250","text":"v = list(map(int, input().split()))\na = list(range(1,9))\nd = a[::-1]\nprint(a,d)\n\nif a == v:\n print(\"ascending\")\nelif v == d:\n print(\"descending\")\nelse:\n print(\"mixed\")","sub_path":"Day 1/음계.py","file_name":"음계.py","file_ext":"py","file_size_in_byte":176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"208839039","text":"from PIL import Image\r\nimport numpy as np\r\nimport glob\r\nimport platform\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n# Lets see what OS the user is running this from\r\ncurrent_os = platform.platform()\r\n# Lets fix our file location accordingly\r\nif current_os.startswith('Win'):\r\n file_directory = r'yalefaces\\subject*'\r\nelse:\r\n file_directory = r'yalefaces/subject*' # For Linux systems\r\n\r\ndata_matrix = np.zeros((154, 1600)) # Initializing our data matrix\r\nall_files = glob.glob(file_directory)\r\nfor i in range(len(all_files)): # iterates over all files in specified directory\r\n # The purpose of the try and except block is to ignore the readme file\r\n im = Image.open(all_files[i]) # Read in the image as a 2D array (234x320 pixels)\r\n im = im.resize((40, 40)) # resize the image to become a 40x40 pixel image\r\n im = im.getdata() # Flatten the image to a 1D array (1x1600)\r\n data_matrix[i, :] = np.asarray(im) # Adding the flattened data as a row\r\n\r\ndata_matrix = (data_matrix - data_matrix.mean(0)) / (data_matrix.std(0)) # lets standardize the data matrix\r\ncov_matrix = np.cov(data_matrix.T) # Finding the cov matrix\r\n\r\nw, v = np.linalg.eig(cov_matrix) # Finding the eigenvalues and vectors\r\n\r\nmax_w = np.amax(w) # Finding max eigenvalue\r\nmax_index = np.where(w == max_w) # Finding corresponding index\r\nmax_v = v[:, max_index[0]] # Finding corresponding eig vector\r\n\r\n# Lets update our eig values and vectors by removing the last picked values\r\nw = np.delete(w, max_index)\r\nv = np.delete(v, max_index, axis=1)\r\n\r\n# Lets find our second largest eigenvalue and vector pair\r\nmax_w_1 = np.amax(w) # Finding max eigenvalue\r\nmax_index_1 = np.where(w == max_w_1) # Finding corresponding index\r\nmax_v_1 = v[:, max_index_1[0]] # Finding corresponding eig vector\r\n\r\nv_tot = np.concatenate((max_v, max_v_1), axis=1) * -1 # This is our final eigenvectors\r\npca_proj = np.matmul(data_matrix, v_tot) # Lets project the points\r\n\r\nplt.scatter(pca_proj[:, 0], pca_proj[:, 1], facecolors='none', edgecolors='r')\r\nplt.title('PCA Projection of Data')\r\nplt.show()\r\n","sub_path":"machine_learning/dimensionality_reduction_via_pca.py","file_name":"dimensionality_reduction_via_pca.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"601813346","text":"import theano\nimport sys\nimport numpy\nimport collections\n\ninput_vector = theano.tensor.fvector('input_vector') #theano variable representing image\ntarget_values = theano.tensor.fvector('target_values') #theano variable representing the label of that image\n\ninput_size = 28 * 28\nl1_size = 100\nl2_size = 100\nnumber_of_classes = 10\nrng = numpy.random.RandomState(0)\n\n# We initialize trainable weights randomly:\nW = theano.shared(numpy.asarray(rng.normal(loc=0.0, scale=0.1, size=(l1_size, input_size)), dtype=theano.config.floatX), 'W')\nW1 = theano.shared(numpy.asarray(rng.normal(loc=0.0, scale=0.1, size=(l2_size, l1_size)), dtype=theano.config.floatX), 'W1')\nW2 = theano.shared(numpy.asarray(rng.normal(loc=0.0, scale=0.1, size=(number_of_classes, l2_size)), dtype=theano.config.floatX), 'W2')\n\nactivations_l1 = theano.tensor.dot(W, input_vector)\noutputs_l1 = theano.tensor.nnet.sigmoid(activations_l1)\n\nactivations_l2 = theano.tensor.dot(W1, outputs_l1)\noutputs_l2 = theano.tensor.nnet.sigmoid(activations_l2)\n\nactivations = theano.tensor.dot(W2, outputs_l2)\npredicted_values = theano.tensor.nnet.sigmoid(activations)\npredicted_class = theano.tensor.argmax(predicted_values)\nAccuracy = -theano.tensor.sqr(predicted_values - target_values).sum()\ngradients = theano.tensor.grad(Accuracy, [W, W1, W2])\nlearning_rate = 0.3\nlist_of_updates = [\n (W, W + learning_rate * theano.tensor.grad(Accuracy, W)),\n (W1, W1 + learning_rate * theano.tensor.grad(Accuracy, W1)), \n (W2, W2 + learning_rate * theano.tensor.grad(Accuracy, W2))\n]\n\n# defining Theano functions for training and testing the model:\ntrain = theano.function([input_vector, target_values], [Accuracy, predicted_class], updates=list_of_updates, allow_input_downcast=True)\ntest = theano.function([input_vector, target_values], [Accuracy, predicted_class], allow_input_downcast=True)\n #'allow_input_downcast=True' is needed to avoid any issues converting between 64 and 32 bit numbers\n\ndef read_dataset(path): #The function that reads training or testing data and returns it as an array of data points\n number_of_images = len(open(path).readlines()) / 28 #28 lines per each image\n f = open(path)\n dataset = [] #starts with an empty container\n for i in range(int(number_of_images)): \n data_vector = [] #we start with empty data vector, and then we read the data for each image from the 28 lines that it takes:\n for l in range(28): #each image takes 28 lines\n line = f.readline()\n line_parts = line.split() #split the line into all the numbers\n assert(len(line_parts) == 29) #should be total of 29: the label + 28 numbers for the image\n label = int(line_parts[0]) #very first number in the file is the label (the digit that the picture represents)\n assert (0 <= label <= 9) #only digits 0-9 are allowed as labels\n #now, we will create \"one-hot vector\":\n label_vector = [0,0,0,0,0,0,0,0,0,0] #a vector of 10 zeroes\n label_vector[label] = 1 #except 1 for the label\n data_vector += [float(line_parts[i])/255. for i in range(1, len(line_parts))]\n #we divide by 255 so the pixel brightness is represented by a number between 0 and 1\n\n dataset.append((label_vector, data_vector))\n return dataset\n\nprint(\"\")\nprint(\"Takes ages to run for me; on VM it runs quickly\")\nprint(\"Template itself already has right output, so pay attention to that.\")\nprint(\"Template gives 94.7%; basic implementation of 3rd layer gives 94.9%\")\nprint(\"Adding epochs easily pushes it over 95%\")\nprint(\"Things to look for in marking: new matrix, correct changing of sizes and activation/output pipeline, list of updates\")\nprint(\"\")\n\n#reading the data:\ndata_train = read_dataset(\"train.txt\")\ndata_test = read_dataset(\"test.txt\")\nprint(\"Completed reading input\")\n\n# training\nfor epoch in range(15):\n cost_sum = 0.0\n correct = 0\n for labelv, vector in data_train:\n Accuracy, predicted_class = train(vector, labelv)\n cost_sum += Accuracy\n if (labelv[predicted_class] == 1):\n correct += 1\n print (\"Epoch: \" + str(epoch) + \", Accuracy: \" + str(cost_sum) + \", %correct: \" + str(float(correct) / len(data_train)*100))\n\n# testing:\ncost_sum1 = 0.0\ncorrect1 = 0\nfor labelv, vector in data_test:\n Accuracy1, predicted_class = test(vector, labelv)\n cost_sum1 += Accuracy\n if (labelv[predicted_class] == 1):\n correct1 += 1\nprint (\"\\t%correct on the test set: \" + str(float(correct1) / len(data_test)*100))\n","sub_path":"Archive/CS412 - 2021/RNN App - A.py","file_name":"RNN App - A.py","file_ext":"py","file_size_in_byte":4605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"532232054","text":"# _*_ coding: utf-8 _*_\n\n\"\"\"\n by renjie\n\"\"\"\nimport asyncio\nimport random\nfrom threading import Timer\n\nasync def produce(queue, n):\n for x in range(n):\n # produce an item\n print('producing {}/{}'.format(x, n))\n # simulate i/o operation using sleep\n await asyncio.sleep(random.random())\n item = str(x)\n # put the item in the queue\n await queue.put(item)\n\n\nasync def consume(queue):\n while True:\n # wait for an item from the producer\n item = await queue.get()\n\n # process the item\n print('consuming {}...'.format(item))\n # simulate i/o operation using sleep\n await asyncio.sleep(random.random())\n\n # Notify the queue that the item has been processed\n queue.task_done()\n\n\nasync def run(n):\n queue = asyncio.Queue()\n # schedule the consumer\n consumer = asyncio.ensure_future(consume(queue))\n # run the producer and wait for completion\n await produce(queue, n)\n # wait until the consumer has processed all items\n await queue.join()\n # the consumer is still awaiting for an item, cancel it\n consumer.cancel()\n\ndef main():\n # loop = asyncio.get_event_loop()\n loop.run_until_complete(run(5))\n # loop.stop()\n\n# loop = asyncio.get_event_loop()\n# loop.run_until_complete(run(10))\n# loop.close()\nclass Scheduler(object):\n def __init__(self, sleep_time, function):\n self.sleep_time = sleep_time\n self.function = function\n self._t = None\n\n def start(self):\n if self._t is None:\n self._t = Timer(self.sleep_time, self._run)\n self._t.start()\n else:\n raise Exception(\"this timer is already running\")\n\n def _run(self):\n self.function()\n self._t = Timer(self.sleep_time, self._run)\n self._t.start()\n\n def stop(self):\n if self._t is not None:\n self._t.cancel()\n self._t = None\nloop = asyncio.get_event_loop()\nscheduler = Scheduler(5, main)\nscheduler.start()","sub_path":"other/uiuu.py","file_name":"uiuu.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"626382653","text":"#!/usr/bin/env python3\n# https://www.hackerrank.com/challenges/time-conversion\n\nimport os\nimport sys\n\n# Complete the timeConversion function below.\ndef timeConversion(s):\n hs, ms, ss = s.split(':')\n h, m, sn = int(hs), int(ms), int(ss[0:2])\n if s[-2:] == 'PM':\n if h != 12: h += 12\n elif h == 12: h = 0\n return '{:02d}:{:02d}:{:02d}'.format(h,m,sn)\n\nif __name__ == '__main__':\n f = open(os.environ['OUTPUT_PATH'], 'w')\n s = input()\n result = timeConversion(s)\n f.write(result + '\\n')\n f.close()\n","sub_path":"hackerrank/easy/time-conversion.py","file_name":"time-conversion.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"624395187","text":"# consts\n\nfrom enum import Enum\nfrom sys import platform\n\n\nclass TableType(Enum):\n normals = 1\n specials = 0\n\n\nCHARACTERS = ['akuma', 'alisa', 'armor-king', 'asuka', 'bob', 'bryan', 'claudio', 'devil-jin', 'dragunov', 'eddy',\n 'eliza', 'feng', 'geese', 'gigas', 'heihachi', 'hwoarang', 'jack7', 'jin', 'josie', 'julia', 'katarina',\n 'kazumi', 'kazuya', 'king', 'kuma', 'lars', 'lei', 'law', 'lee', 'leo', 'lili', 'lucky-chloe', 'marduk',\n 'master-raven', 'miguel', 'negan', 'nina', 'noctis', 'paul', 'shaheen', 'steve', 'xiaoyu', 'yoshimitsu']\n\nWEBSITE = r'http://rbnorway.org/{}-t7-frames/'\n\n# if mac then create mac file path\nif platform == 'darwin':\n EXPORT_FOLDER = '/Users/aaronb/Desktop/FrameData'\n EXPORT = EXPORT_FOLDER + r'/{}.csv'\n# if anything else then try create windows path\nelse:\n EXPORT_FOLDER = r'C:\\FrameData'\n EXPORT = EXPORT_FOLDER + r'\\{}.csv'\n","sub_path":"constant.py","file_name":"constant.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"613130843","text":"import time\nfrom threading import Thread\n\nfrom discord.ext.commands import Bot as DBot\nfrom schedule import Scheduler\n\n\nclass Bot(DBot):\n def __init__(self, db, **options):\n super().__init__(**options)\n self.db = db\n self.jobs = []\n self.run_jobs = True\n self.schedule = Scheduler()\n\n async def close(self):\n print(\"Shutting down!\")\n self.run_jobs = False\n await super().close()\n self.db.close_all()\n\n async def on_ready(self):\n print(f\"Bot is ready! Logged in as {self.user}.\")\n Thread(target=self.job_runner).start()\n\n def job_runner(self):\n print(\"Starting background timer runner.\")\n while self.run_jobs:\n try:\n self.schedule.run_pending()\n except Exception as e:\n print(f\"{type(e).__name__}: {e}\")\n time.sleep(10)\n\n def register_job_daily(self, daytime, f):\n print(f\"Registering job {f.__name__} to run every day at {daytime}\")\n self.schedule.every().day.at(daytime).do(f)\n\n def register_job(self, timer, f):\n print(f\"Registering job {f.__name__} to run every {timer} seconds\")\n self.schedule.every(timer).seconds.do(f)\n\n def dbconf_get(self, guild_id, name, default=None):\n result = self.db.get(guild_id).execute(\"SELECT value FROM config WHERE name = ?\", (name,)).fetchall()\n\n if len(result) < 1:\n return default\n\n return str(result[0][0])\n\n def dbconf_set(self, guild_id, name, value):\n saved = self.dbconf_get(guild_id, name)\n\n if saved is None:\n with self.db.get(guild_id) as db:\n db.execute(\"INSERT INTO config(name, value) VALUES(?, ?)\", (name, value))\n return\n\n if str(saved) == str(value):\n return\n\n with self.db.get(guild_id) as db:\n db.execute(\"UPDATE config SET value = ? WHERE name = ?\", (value, name))\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"458997024","text":"import greedy_assembly as gr\nfrom Bio import SeqIO\nimport os.path\n\n\n ## read in sequences in fasta file\nddir = \"data\"\nfname = \"test_data.fasta\"\nrecords_dict = SeqIO.index(os.path.join(ddir,fname), \"fasta\")\n\n## Create dictionary. For each left sequence, get the right sequence\n## with the most overlap.\nmax_overlap_dict = gr.create_max_overlap_dict(records_dict)\n\n## determine id of the left-most sequence\nleftmost_id = gr.leftmost_sequence(max_overlap_dict)\nprint('\\n','id of leftmost read: ', leftmost_id)\n \n## get list containing the order of the sequences\nread_order = gr.get_next_seq(leftmost_id, max_overlap_dict, thresh=2)\n\n## assemble genome\ngenome = gr.assemble_reads(records_dict[read_order[0]].seq,\n read_order[1:],\n records_dict)\nprint(genome)\n\nassert genome == 'ATTAGACCTGCCGGAATAC', \"Assembled genome output is incorrect.\"\n","sub_path":"test_simpledata.py","file_name":"test_simpledata.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"525852968","text":"\n\nfrom xai.brain.wordbase.nouns._rescue import _RESCUE\n\n#calss header\nclass _RESCUED(_RESCUE, ):\n\tdef __init__(self,): \n\t\t_RESCUE.__init__(self)\n\t\tself.name = \"RESCUED\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"rescue\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_rescued.py","file_name":"_rescued.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"536323309","text":"#!/usr/bin/env python3\n\n# date: 2020.05.21\n# https://stackoverflow.com/questions/61935547/saving-output-the-to-json-format/\n\nimport scrapy\nfrom webpreview import OpenGraph\n\nclass News18SSpider(scrapy.Spider):\n\n name = 'news18_story'\n page_number = 1\n start_urls = ['https://www.news18.com/movies/page-{}/'.format(number) for number in range(1, 21)]\n\n def parse(self, response):\n all_hrefs = response.xpath('//div[@class=\"blog-list-blog\"]/p/a/@href').getall()\n\n for href in all_hrefs:\n og = OpenGraph(href, [\"og:title\", \"og:description\", \"og:image\", \"og:url\"])\n\n yield {\n \"page_title\": og.title,\n \"description\": og.description,\n \"image_url\": og.image,\n \"post_url\": og.url\n } \n\n\n# --- run without project and save in `output.csv` ---\n\nfrom scrapy.crawler import CrawlerProcess\n\nc = CrawlerProcess({\n 'USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0',\n # save in file CSV, JSON or XML\n 'FEED_FORMAT': 'json', # csv, json, xml\n 'FEED_URI': 'output.json', #\n})\nc.crawl(News18SSpider)\nc.start() \n","sub_path":"__scraping__/news18.com - scrapy/main-2.py","file_name":"main-2.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"345562715","text":"'''\n MAIN ***PENDIENTE QUE FUNCIONE EL WHILE***\n'''\nimport time\nfrom listados import avanzar_motos, presentar_motos\nfrom preparar_carrera import preparar_motos\n\nganado = 0\n\nmotos = preparar_motos()\n\npresentar_motos(motos)\n\n\n\nreiniciar = True\n\nfin_carrera = False\n\nwhile reiniciar:\n insertado = input(\"Introduce el número del ganador : \")\n if ganado == 0:\n apostado = int(input(\"indica la cantidad que vas a apostar : \"))\n else:\n apostado == ganado\n if insertado.isnumeric():\n insertado_int = int(insertado)\n if insertado_int >= 1 and insertado_int < 6:\n while not fin_carrera:\n numero_ganador = avanzar_motos(motos)\n time.sleep(1)\n if numero_ganador != -1:\n fin_carrera = True\n print(\"Fin de la carrera, el ganador es el número : \" + str(numero_ganador))\n if insertado_int == numero_ganador: \n ganado = apostado * int(len(motos))\n print(\"Felicidades ,has ganado !! \" + str(ganado) + \"\\n\")\n volver_jugar = input(\"¿Quieres apostar de nuevo lo que has ganado? S/N : \")\n if volver_jugar == \"S\":\n numero_ganador = -1\n apostado = ganado\n else:\n print(\"Hasta la próxima\")\n reiniciar = False\n else:\n print(\"Lo siento, has perdido todo tu dinero\")\n reiniciar = False\n else:\n print(\"Debes elegir un número entro 1 y 5\")","sub_path":"APUNTES/PYTHON/EJEMPLOS_FORMACION/ejercicio03carrera/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"337955514","text":"import FWCore.ParameterSet.Config as cms\n\nexternalLHEProducer = cms.EDProducer('ExternalLHEProducer',\n scriptName = cms.FileInPath(\"GeneratorInterface/LHEInterface/data/run_madgraph_gridpack.sh\"),\n outputFile = cms.string(\"QCD_HT-500To1000_final.lhe\"),\n numberOfParameters = cms.uint32(10),\n args = cms.vstring('slc5_amd64_gcc472/13TeV/madgraph/V5_1.5.11/QCD_HT-500To1000/v2',\n 'QCD_HT-500To1000','false','false','qcd','5','54','true','2','4'),\n nEvents = cms.uint32(100000)\n)\n","sub_path":"genfragments/ThirteenTeV/QCD_HT_500To1000_13TeV_madgraph_cfg.py","file_name":"QCD_HT_500To1000_13TeV_madgraph_cfg.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"323768648","text":"'''\nCreated on 4 Jun 2015\n\n@author: dawright\n\nTest to Slush Cash to a player\n'''\n\nfrom data.Constants import Key\nfrom BaseTestCase import BaseTestCase\nfrom pages.PlayerDetailsPage import PlayerDetails\nfrom pages.SlushSeizePage import SlushFunds\nimport unittest\nimport time\n\nclass slushFundsTest(BaseTestCase, unittest.TestCase):\n \n def setUp(self):\n super(slushFundsTest, self).setUp()\n\n self.login_and_search_player()\n \n def test10_slush_funds(self):\n\n SelectSlushFunds_obj = PlayerDetails(self.driver)\n SelectSlushFunds_obj.SlushFundsOption() #Navigate to Slush Funds page\n \n SubmitSlushFunds_obj = SlushFunds(self.driver)\n SubmitSlushFunds_obj.slushfundsfields() #Fill in Slush Funds fields\n SubmitSlushFunds_obj.submitslushfunds() #Submit the Slush Funds details\n SubmitSlushFunds_obj.slushfunds_confirmation()\n time.sleep(2)\n\n def tearDown(self):\n super(slushFundsTest, self).tearDown()\n \nif __name__ == '__main__':\n unittest.main()","sub_path":"tests/SlushCashTest.py","file_name":"SlushCashTest.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"637819074","text":"#arreglos: otro ejercicio\n#Ejemplo:\n\n#(1,5,8,9,10,9,13)\n#Imprimir por pantalla los números impares a 3\n\nA=[1,5,8,9,30,9,13]\nB=[]\nfor i in A:\n if i>5 and i%2 !=0:\n B.append(i)\nprint(B)","sub_path":"arreglos/arreglos1(c35).py","file_name":"arreglos1(c35).py","file_ext":"py","file_size_in_byte":194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"373300063","text":"import pytest\n\nfrom tasks.lesson03.task304 import solution\n\n\n@pytest.mark.unit\ndef test():\n test_data = {\n \"\": \"!\",\n \"1\": \"1\",\n \"12\": \"12\",\n \"123\": \"123!\",\n \"1234\": \"1234\",\n \"12345\": \"12345\",\n \"123456\": \"123456!\",\n }\n\n for test_value, expected_value in test_data.items():\n got_value = solution(test_value)\n assert expected_value == got_value\n","sub_path":"tests/unit/tasks/lesson03/test_task304.py","file_name":"test_task304.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"594804300","text":"from nose import tools\n\nfrom p020 import factorial, sum_digits\n\n\ndef test_factorial():\n xy = [(0, 1), (1, 1), (2, 2), (3, 6)]\n for x, y in xy:\n yield tools.assert_equal, factorial(x), y, x\n\n\ndef test_sum_digits():\n xy = [(1, 1), (11, 2), (1230, 6)]\n for x, y in xy:\n yield tools.assert_equal, sum_digits(x), y, x\n","sub_path":"python/test_p020.py","file_name":"test_p020.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"200668772","text":"\n\nfrom django.conf.urls import patterns,include, url\n\nfrom Haka import views\n\nurlpatterns = patterns('',\n # Signup, signin and signout\n \n url(r'^api/getHaka/$', views.getHaka , name='getHaka'),\n url(r'^api/getAllHakas/$', views.getAllHakas , name='getAllHakas'),\n url(r'^api/getEvents/$', views.getEvents , name='getEvents'),\n url(r'^api/getEvent/$', views.getEvent , name='getEvent'),\n url(r'^api/getEventTeam/$', views.getEventTeam , name='getEventTeam'),\n url(r'^api/getEventsArchive/$', views.getEventsArchive , name='getEventsArchive'),\n url(r'^api/login/$', views.login_user , name='login_user'),\n url(r'^api/logout/$', views.logout_user , name='logout_user'),\n url(r'^api/register/$', views.register_user , name='register_user'),\n url(r'^$', views.showHomepage , name='showHomepage'),\n\n)","sub_path":"Haka/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"100501932","text":"from django.urls import path\nfrom .views import front_page, post_page, search_results,vote, topic_page,comment_vote\n\nurlpatterns = [\n \n path('post//', post_page, name='post'),\n path('search/', search_results, name='search'),\n path('vote/', vote, name='vote'),\n path('comment-vote/', comment_vote, name='comment_vote'),\n path('topic//', topic_page, name='topic'),\n]","sub_path":"src/pages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"13497776","text":"\n\nfrom xai.brain.wordbase.adjectives._vague import _VAGUE\n\n#calss header\nclass _VAGUER(_VAGUE, ):\n\tdef __init__(self,): \n\t\t_VAGUE.__init__(self)\n\t\tself.name = \"VAGUER\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"vague\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_vaguer.py","file_name":"_vaguer.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"385664595","text":"import numpy as np\nimport csv as C\n#f = open('values.txt', 'r')\n#x = f.read()\n#poly_shape = []\n#poly_shape.append(x)\n#y = np.array(poly_shape)\n\n#print(y)\n\n# with open('output2.txt') as f:\n# polyShape = []\n# y = []\n# for word in f:\n# word = word.split() # to deal with blank\n# if word: # lines (ie skip them)\n# word = [int(i) for i in word]\n# #np.append(y,word)\n# #y.reshape(-1,1)\n# polyShape.append(word)\n# X = np.array(polyShape)\n#X = np.array([[2], [3],[3],[3],[1],[3],[1],[3],[2],[2],[3],[1]])\n\n#X.reshape(1,-1)\n##print(X)\n\nnp.random.seed(42)\nf = open('filetest.csv')\ntry:\n reader = C.reader(f)\n floats = []\n for row in reader:\n floats.append(map(int, row))\nfinally:\n f.close()\n\ntrain_data = np.array(floats)\n#print(train_data)\n\ntest_data1 = np.array([[0], [2], [0], [0], [0], [2], [2], [2]])\nX1 = [[0], [2], [0], [0], [0], [2], [2], [2]]\nX2 = [[1], [2], [0], [1], [0], [1], [2], [0]]\nX = np.concatenate([X1, X2])\n#length = [len[X1], len[X2]]\ntest_data1.reshape(-1,1)\nprint(X)\n","sub_path":"scripts/HMMScripts/Filetest.py","file_name":"Filetest.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"12066867","text":"from installer.builders import Make, Autoreconf\nfrom .base import Formula\n\n\nclass Libsndfile(Formula):\n url = 'http://www.mega-nerd.com/libsndfile/files/libsndfile-1.0.28.tar.gz'\n builder_classes = (\n Autoreconf,\n Make\n )\n\n @property\n def options(self):\n return [\n f'--prefix={self.prefix}',\n '--disable-dependency-tracking',\n ]\n\n depends_on = [\n 'flac',\n 'libogg',\n 'libvorbis',\n ]\n","sub_path":"installer/formula/libsndfile.py","file_name":"libsndfile.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"121155835","text":"n = int(input())\r\nmatrix = [list(map(int, input().split())) for i in range(n)]\r\nrow_max_pos = []\r\ncol_min_pos = []\r\n\r\nfor i in range(n):\r\n mx = max(matrix[i])\r\n mn = min(int(matrix[j][i]) for j in range(n))\r\n row_max_pos += [(i, j) for j in range(n) if matrix[i][j] == mx]\r\n col_min_pos += [(j, i) for j in range(n) if matrix[j][i] == mn]\r\ns = list(set(row_max_pos) & set(col_min_pos))\r\nprint(len(s))","sub_path":"pythonProject/ZJU_Py_PTA/C5/C5_9.py","file_name":"C5_9.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"195406448","text":"#!/urs/bin/env python \n#-*- coding: utf:8 -*-\n\nfrom tkinter import *\nfrom tkinter import messagebox, filedialog\n\nclass app():\n\tdef __init__(self,master):\n\t\tself.frames = Frame(master)\n\t\tmaster.geometry('500x500')\n\t\tself.frames.pack()\n\n\t\tself.para_set()\n\t\tself.create_widget()\n\t\tself.check_maze()\n\t\t\n\tdef create_widget(self):\n\t\tB1 = Button(self.frames,text='Cancel')\n\t\tB1.grid(row=1,column=2)\t\t\n\t\tB2 = Button(self.frames,text='Ok')\n\t\tB2.grid(row=1,column=1)\n\t\tB1.bind(\"\",self.clr_screen)\n\t\tB3 = Button(self.frames,text = 'output')\n\t\tB3.grid(row=2,column=4)\n\t\tself.W1 = Canvas(self.frames,bg='white',width=350,height=350)\n\t\tself.W1.grid()\n\n \t\t#draw the frame line\n\t\tfor i in range(11):\n\t\t\tself.W1.create_line( self.__min_x, self.__min_y + i*self.step_y, self.__max_x, self.__min_y + i*self.step_y)#row\n\t\t\tself.W1.create_line( self.__min_x + i*self.step_x, self.__min_y, self.__min_x + i*self.step_x, self.__max_y)#column\n\t\t\n\t\tself.W1.bind(\"\",self.mouse_click)\n\t\tself.W1.bind(\"\",self.clr_screen)\n\t\t\n\tdef mouse_click(self,event):\n\t\t# the position that user click might not accurate\n\t\t# we have to caculate the closest blank based on the coord. of mouse click \n\t\ttmp_x = event.x - self.step_x/2\n\t\ttmp_y = event.y - self.step_y/2\n\t\tseq_x ,seq_y= self.seq(self.n,self.__min_x,self.step_x) , self.seq(self.n,self.__min_y,self.step_y)\n\t\tselect_x,select_y = self.close_x(seq_x,tmp_x), self.close_x(seq_y,tmp_y)\n\t\tselect_xn , select_yn = (select_x- self.__min_x)/self.step_x + 1,(select_y- self.__min_y)/self.step_y + 1 \n\t\t#fill the rectangle \n\t\tself.obj_rec = self.W1.create_rectangle(select_x, select_y, select_x + self.step_x, select_y + self.step_y,fill='blue')\t\t\n\t\tself.Maze_pos.append([select_xn,select_yn])\n\t\t\n\tdef para_set(self):\n\t\tprint('into para setting')\t\n\t\t# initialize the parameter s\n\t\tself.Maze_pos = [] # record position by list \n\t\tself.__min_x, self.__max_x = 10, 300\n\t\tself.__min_y, self.__max_y = 10, 300\n\t\tself.n = 10 \n\t\tself.step_x, self.step_y = (self.__max_x - self.__min_x)/self.n, (self.__max_y - self.__min_y)/self.n\n\t\t# set the start and exit of the maze\n\t\tself.pos_in = [1,3]\n\t\tself.pos_out = [9,10]\n\t\t\n\tdef clr_screen(self,event):\n\t\t#clean the canvas\n\t\tprint('into clear screen')\n\t\tself.W1.delete(self.obj_rec)\n\n\tdef seq(self,n,min_i,step):\n\t\t#create a sequence based on the given range and step\n\t\tans = [min_i + step*k for k in range(n)]\n\t\treturn ans\n\n\tdef close_x(self,s,x):\n\t\t# to find the closest point on the grid\n\t\t# s is the given sequence\n\t\t# x is the given number\n\t\tif x s[-1]:\n\t\t\tans = s[-1]\n\t\t\tprint('given x is larger than last no.')\n\t\telse:\n\t\t\tfor k in range(len(s)):\n\t\t\t\tif x - s[k] < 0:\n\t\t\t\t\tif abs(x-s[k]) > abs(x-s[k-1]):\n\t\t\t\t\t\tans = s[k-1]\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tans = s[k]\n\t\t\t\t\t\tbreak\n\t\treturn ans\n\t\t\n\tdef fill_col(self,x,y):\n\t\ttmp_x, tmp_y = self.__min_x + (x-1)*self.step_x , self.__min_y + (y-1)* self.step_y\n\t\tself.W1.create_rectangle(tmp_x,tmp_y,tmp_x+self.step_x,tmp_y+self.step_y,fill='green')\t\t\n\t\n\tdef fill_text(self,x,y,msg):\n\t\ttmp_x, tmp_y = self.__min_x + (x-0.5)*self.step_x , self.__min_y + (y-0.5)* self.step_y\n\t\tself.W1.create_text(tmp_x,tmp_y,text=msg)\n\t\n\tdef check_maze(self):\n\t\tprint('into check maze')\n\t\tself.fill_col(self.pos_in[0],self.pos_in[1])\n\t\tself.fill_col(self.pos_out[0],self.pos_out[1])\n\t\tself.fill_text(self.pos_in[0],self.pos_in[1],'Start')\n\t\tself.fill_text(self.pos_out[0],self.pos_out[1],'Exit')\n\nroot = Tk()\nb1 = app(root)\nroot.mainloop()\n","sub_path":"練習/path finding/maze/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"333707193","text":"from flask_restx import Resource, Namespace\n\nfrom ezbeq.catalogue import CatalogueProvider\n\napi = Namespace('1/meta', description='Provides access to metadata about the beq catalogue')\n\n\n@api.route('')\nclass CatalogueMeta(Resource):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.__provider: CatalogueProvider = kwargs['catalogue']\n\n def get(self):\n version = self.__provider.version\n loaded_at = self.__provider.loaded_at\n return {\n 'version': version,\n 'loaded': int(loaded_at.timestamp()) if loaded_at is not None else None,\n 'count': len(self.__provider.catalogue)\n }\n","sub_path":"ezbeq/apis/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"294352104","text":"from django.conf.urls import patterns, include, url\nfrom django.views.generic import TemplateView\nfrom django.contrib import admin\n\n# Uncomment the next two lines to enable the admin:\nadmin.autodiscover()\n\n# urlpatterns = patterns('keen.views',\n# url(r'^$', 'index'),\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\nurlpatterns = patterns('',\n url(r'^admin/', include(admin.site.urls)),\n (r'^$', TemplateView.as_view(template_name='index.html')),\n (r'^legal$', TemplateView.as_view(template_name='legal.html')),\n)\n\n#mdo special case\nurlpatterns += patterns('main.views.customers',\n url(r'^(?P[a-z]+)/signup/$', 'signup'),\n)\n\n\n#mdo special case\nurlpatterns += patterns('main.views.clients',\n url(r'^handlebar/redeem/(?P[0-9A-Za-z]+)/$', 'handlebar_redeem'),\n url(r'^handlebar/redeem/$', 'handlebar_redeem'),\n)\n","sub_path":"keen/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"551999202","text":"#!/usr/bin/env python3\n# coding: utf8\n\n# Author: Lenz Furrer, 2018\n\n\n'''\nParse the MEDIC terminology used for the NCBI disease corpus.\n'''\n\n\nimport csv\nfrom collections import defaultdict\n\nfrom ..terminology import DictEntry\nfrom ...util.util import smart_open\nfrom ...util.umls import read_RRF, iterconcepts, C\n\n\ndef parse_MEDIC_terminology(source):\n '''\n Parse the MEDIC TSV into an iterator of namedtuples.\n '''\n if hasattr(source, 'read'):\n yield from _parse_MEDIC_terminology(source)\n else:\n with open(source, encoding='utf-8') as f:\n yield from _parse_MEDIC_terminology(f)\n\n\ndef _parse_MEDIC_format(file):\n '''\n Input fields:\n DiseaseName\n DiseaseID\n AltDiseaseIDs\n Definition\n ParentIDs\n TreeNumbers\n ParentTreeNumbers\n Synonyms\n\n Output fields:\n name (str): preferred name\n id (str): concept ID\n alt (tuple): alternative IDs (if any)\n def_ (str): definition (if any)\n syn (tuple): synonyms (if any)\n '''\n reader = csv.reader(file, delimiter='\\t', quotechar=None)\n for row in reader:\n if row[0].startswith('#'):\n continue\n name, id_, alt, def_, _, _, _, syn = row\n yield name, id_, alt, def_, syn\n\n\ndef _parse_MEDIC_terminology(file):\n for name, id_, alt, def_, syn in _parse_MEDIC_format(file):\n yield DictEntry(\n name,\n id_,\n tuple(alt.split('|')) if alt else (),\n def_,\n tuple(syn.split('|')) if syn else (),\n )\n\n\ndef extend_MEDIC_with_UMLS(medic, metadir, target):\n '''\n Create an extended version of the MEDIC terminology TSV.\n '''\n with smart_open(medic) as r, smart_open(target, 'w') as w:\n _extend_MEDIC_with_UMLS(r, metadir, w)\n\n\ndef _extend_MEDIC_with_UMLS(medic, metadir, target):\n concepts = iterconcepts(read_RRF(metadir, 'CONSO'))\n with MedicBuffer(medic, target) as mbuf:\n for conc in concepts:\n ids = list(_medic_ids(conc))\n if not ids:\n continue\n names = (r[C.STR] for r in conc)\n mbuf.update(ids, names)\n\n\ndef _medic_ids(conc):\n for row in conc:\n try:\n prefix = _prefixes[row[C.SAB]]\n except KeyError:\n pass\n else:\n yield prefix + row[C.CODE]\n\n_prefixes = {'MSH': 'MESH:', 'OMIM': 'OMIM:'}\n\n\nclass MedicBuffer:\n '''\n Keep the MEDIC vocabulary in memory while adding synonyms.\n '''\n def __init__(self, infile, outfile):\n self._index = {}\n self._ambiguous = defaultdict(set)\n self._lines = []\n self._outfile = outfile\n self._read(infile)\n\n def _read(self, infile):\n _D = {} # reused empty dummy dict\n for line in infile:\n line = line.rstrip('\\n\\r')\n if line.startswith('#'):\n self._lines.append((line, _D))\n else:\n self._parse(line)\n\n def _parse(self, line):\n name, id_, alt, _, _, _, _, syn = line.split('\\t')\n syn, alt = ((s.split('|') if s else ()) for s in (syn, alt))\n names = {n.lower(): None for n in (name, *syn)}\n self._lines.append((line, names))\n for i in (id_, *alt):\n self._index.setdefault(i, []).append(names)\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n return False\n\n def update(self, ids, newnames):\n '''\n Add new synonyms to all rows that match the IDs.\n '''\n for i in ids:\n for names in self._index.get(i, ()):\n for n in newnames:\n names.setdefault(n.lower(), n)\n self._ambiguous[n].add(i)\n\n def close(self):\n '''\n Write the modified file to disk.\n '''\n for line, names in self._lines:\n newnames = [n for n in names.values()\n if n is not None and not self._is_ambiguous(n)]\n self._outfile.write(line)\n if newnames:\n self._outfile.write('|')\n self._outfile.write('|'.join(newnames))\n self._outfile.write('\\n')\n\n def _is_ambiguous(self, name):\n return len(self._ambiguous[name]) > 1\n","sub_path":"tzlink/datasets/ncbi_disease/term.py","file_name":"term.py","file_ext":"py","file_size_in_byte":4322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"345113981","text":"import argparse\nfrom operator import itemgetter\n\n\ndef parse_input(input_path: str) -> list:\n \"\"\"\n parse_input takes in the input file, and breaks it down into\n a managable data structure. It returns a list of matches,\n with each match represented as a tuple. This tuple is\n itself composed of two tuples, one for each team and their score.\n Tuples all the way down, really.\n \"\"\"\n parsed_input = []\n matches = []\n\n with open(input_path, \"r\") as f:\n for line in f:\n line = line.rstrip()\n matches.append(line.split(sep=\", \"))\n for match in matches:\n first_team = match[0].rsplit(\" \", 1)\n second_team = match[1].rsplit(\" \", 1)\n try:\n first_team_parsed = first_team[0], int(first_team[1])\n second_team_parsed = second_team[0], int(second_team[1])\n except ValueError:\n print(\n f\"Score invalid for match between {first_team_parsed[0]} and {second_team_parsed[0]}, skipping\"\n )\n continue\n match_tuple = first_team_parsed, second_team_parsed\n parsed_input.append(match_tuple)\n return parsed_input\n\n\ndef calculate_standings(parsed_input):\n \"\"\"\n calculate_standings takes the parsed input, and determines the winner\n of each match. If a team has already played, it adds the daily ranking\n to the match_history dictionary and begins a new\n \"\"\"\n day_count = 1\n daily_ranking = {}\n played_today = []\n for match_data in parsed_input:\n team_one, team_one_score = match_data[0]\n team_two, team_two_score = match_data[1]\n team_one_rank = daily_ranking.get(team_one, 0)\n team_two_rank = daily_ranking.get(team_two, 0)\n\n if team_one_score > team_two_score:\n team_one_rank += 3\n elif team_one_score < team_two_score:\n team_two_rank += 3\n elif team_one_score == team_two_score:\n team_one_rank += 1\n team_two_rank += 1\n\n # if a team has already played, it's safe to assume a new day\n if team_one in played_today or team_two in played_today:\n output_prettily(daily_ranking, day_count)\n played_today.clear()\n day_count += 1\n\n # update the daily rankings per team.\n daily_ranking[team_one] = team_one_rank\n daily_ranking[team_two] = team_two_rank\n played_today.append(team_one)\n played_today.append(team_two)\n\n # For the final day, we won't hit the last played_today check\n # so we need to call it one more time here.\n output_prettily(daily_ranking, day_count)\n\n\ndef output_prettily(daily_ranking: dict, day: int):\n \"\"\"\n output_prettily will write the rankings to stdout in the format required.\n \"\"\"\n count = 0\n # sort each item in the daily ranking based on value\n ranked = sorted(daily_ranking.items(), key=itemgetter(1), reverse=True)\n print(\"Matchday \" + str(day))\n while count < 3:\n team, score = ranked[count]\n if score == 1:\n units = \" pt\"\n else:\n units = \" pts\"\n print(team + \", \" + str(score) + units)\n count += 1\n print()\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Calculate soccer rankings after each match day\"\n )\n parser.add_argument(\n \"--input_path\", help=\"path to a file containing matches\", required=True\n )\n parser.add_argument(\n \"--output_path\",\n help=\"path to output results to. Defaults to STDOUT if not set.\",\n required=False,\n )\n args = parser.parse_args()\n\n match_list = parse_input(args.input_path)\n calculate_standings(match_list)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"425779060","text":"import csv\nimport pandas as pd\nimport plotly.express as px\n\nwith open(\"class2.csv\", newline='') as d:\n reader = csv.reader(d)\n fileData = list(reader)\n\nfileData.pop(0)\n\n# newData = []\ntotalMarks = 0\n\nfor i in range(len(fileData)):\n marks = fileData[i][1]\n totalMarks += float(marks)\n\nnumberOfStudents = len(fileData)\n\nmean = totalMarks / numberOfStudents\nprint(\"The mean is equal to\" + ' ' + ':' + ' ' + str(mean))\n\ndataFile = pd.read_csv(\"class2.csv\")\n\nfigure = px.scatter(dataFile, x=\"Student Number\", y=\"Marks\")\n\nfigure.update_layout(shapes=[\n dict(type=\"line\",\n x0=0, x1=len(fileData),\n y0=mean, y1=mean\n )\n])\nfigure.update_yaxes(rangemode=\"tozero\")\n\nfigure.show()\n","sub_path":"class2performance.py","file_name":"class2performance.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"390204114","text":"'''\r\n\r\nhttps://www.hackerrank.com/challenges/merge-list\r\n\r\n'''\r\n\r\nfrom math import factorial\r\nt= int(input())\r\nfor _ in range(t):\r\n n, m= map(int, input().split())\r\n print(factorial(n+m)//factorial(n)//factorial(m)%(10**9+7))","sub_path":"HackerRankExercise/maths/MergeList.py","file_name":"MergeList.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"308592345","text":"import numpy as np\nfrom scipy import linalg\nfrom numpy import pi\n#from scipy import stats\n\ndef entropy(C):\n '''\n Entropy of a gaussian variable with covariance matrix C\n '''\n if np.isscalar(C): # C is the variance\n return .5*(1 + np.log(2*pi)) + .5*np.log(C)\n else:\n n = C.shape[0] # dimension\n return .5*n*(1 + np.log(2*pi)) + .5*np.log(abs(linalg.det(C)))\n\n\ndef kullback_leibler_divergence(pm, pv, qm, qv):\n eps = 0.0001\n # Determinants of diagonal covariances pv, qv\n dpv = linalg.det(pv)\n dqv = linalg.det(qv)\n # Inverse of diagonal covariance qv\n iqv = linalg.inv(qv)\n # Difference between means pm, qm\n diff = qm - pm\n return (0.5 *\n (np.log((abs(dqv)+eps) / (abs(dpv)+eps))\n + (np.transpose(iqv * pv).sum())\n + ((diff * iqv * diff).sum())\n - len(pm)))\n\n\n#pm = np.asarray([0.1, 0.30000000000000004, 0.25])\n#pv = np.asarray([[0, 0, 0], [0, 0.020000000000000004, -0.030000000000000002], [0, 0, 0.045000000000000005]])\n#qm = np.asarray([0.3, 0.30000000000000004, 0.1])\n#qv = np.asarray([[0.08, 0.04, 0], [0, 0.020000000000000004, 0], [0, 0, 0]])\n","sub_path":"python/ontology/gmi.py","file_name":"gmi.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"318124090","text":"from text_query import TextQuery\nimport external_search\nimport full_text_search\nimport indexing\n\n\nclass Searcher(object):\n \"\"\"A utility class for searching person records in repositories.\"\"\"\n\n def __init__(\n self, repo, external_search_backends, enable_fulltext_search,\n max_results):\n self._repo = repo\n self._external_search_backends = external_search_backends\n self._enable_fulltext_search = enable_fulltext_search\n self._max_results = max_results\n\n def search(self, query_name, query_location=None):\n \"\"\"Get results for a query.\n\n Args:\n query_name: A name to query for (string).\n query_location: A location to query for (optional, string).\n \"\"\"\n text_query = TextQuery(\n '%s %s' % (query_name, query_location)\n if query_location\n else query_name)\n results = None\n if self._external_search_backends:\n results = external_search.search(\n self._repo, text_query, self._max_results,\n self._external_search_backends)\n # External search backends are not always complete. Fall back to the\n # original search when they fail or return no results.\n if not results:\n query_dict = {'name': query_name}\n if query_location:\n query_dict['location'] = query_location\n if self._enable_fulltext_search:\n results = full_text_search.search(\n self._repo, query_dict, self._max_results)\n else:\n results = indexing.search(\n self._repo, text_query, self._max_results)\n return results\n","sub_path":"app/search/searcher.py","file_name":"searcher.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"99135384","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom NDataLoader import DataLoader\nimport torch.optim as optim\nimport pickle\nfrom collections import deque\nimport numpy as np\nimport sys\nfrom copy import copy, deepcopy\nsys.path.insert(1, '../game_simulation')\nfrom parameters import Parameter\n## image size is 12 * 6\ntrain_data_path = \"/Users/joeleung/Documents/CUHK/yr4_term1/csfyp/csfyp/PG/train_data/\"\nPATH = '../PG/network/'\nTOTAL_EPOCH = 10\nNUM_OF_COLOR = Parameter.NUM_OF_COLOR\nROW_DIM = Parameter.ROW_DIM\nCOLUMN_DIM = Parameter.COLUMN_DIM\nMAX_POSSIBLE_MOVE = ROW_DIM * (COLUMN_DIM - 1)\n\nreplay_memory = deque(maxlen = 500000)\n#torch.set_num_threads(1)\n\nclass Net(nn.Module):\n\n def __init__(self):\n super(Net, self).__init__()\n\n self.data_loader = None\n self.trainloader = None\n self.testloader = None\n\n self.conv1 = nn.Conv2d(NUM_OF_COLOR, 54, 3, padding=1)\n\n self.fc1 = nn.Linear(54 * ROW_DIM * COLUMN_DIM, 128)\n\n self.fc2 = nn.Linear(1024, 512)\n\n self.fc3 = nn.Linear(128, MAX_POSSIBLE_MOVE)\n\n self.optimizer = optim.SGD(self.parameters(), lr=0.0001, momentum=0.5)\n\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = x.view(-1, self.num_flat_features(x))\n\n x = F.relu(self.fc1(x))\n #x = F.relu(self.fc2(x))\n probi = F.relu(self.fc3(x))\n return F.softmax(probi, dim=1)\n\n def num_flat_features(self, x):\n size = x.size()[1:] # all dimensions except the batch dimension\n num_features = 1\n for s in size:\n num_features *= s\n return num_features\n\n\n ## action is in respective of the network\n def train(self, all_states, all_actions, all_rewards, name):\n self.data_loader = DataLoader(all_states, all_actions, all_rewards)\n self.trainloader = self.data_loader.get_trainloader()\n self.testloader = self.data_loader.get_testloader()\n\n batch_size = self.data_loader.batch_size\n data_size = len(all_actions)\n min_batch_per_look = data_size // batch_size // 4\n running_loss = 0.0\n for epoch in range(TOTAL_EPOCH):\n for i, data in enumerate(self.trainloader, 0):\n # get the inputs; data is a list of [states, rewards, actions]\n states, rewards, actions = data\n # zero the parameter gradients\n self.optimizer.zero_grad()\n\n # forward + backward + optimize\n probi = self.forward(states)\n action_log_probs = probi.log().gather(1, actions.view(len(actions), -1))\n\n actor = -(rewards * action_log_probs).mean()\n\n loss = actor\n loss.backward(retain_graph=True)\n self.optimizer.step()\n\n # print statistics\n running_loss += loss.item()\n if i % min_batch_per_look == min_batch_per_look - 1: # print every 500 mini-batches\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, running_loss / min_batch_per_look))\n running_loss = 0.0\n\n torch.save(net.state_dict(), PATH + name)\n\n\n def test(self):\n test_loss = 0\n count = 0\n show_count = 0\n show_target = 20\n match = 0\n total = 0\n with torch.no_grad():\n for i, data in enumerate(self.testloader, 0):\n states, rewards, actions = data\n\n probi = self.forward(states)\n _, indexs = torch.max(probi, 1)\n\n\n action_log_probs = probi.log().gather(1, actions.view(len(actions), -1))\n\n actor = -(rewards * action_log_probs).mean()\n loss = actor\n\n for i in range(len(probi)):\n if indexs[i].item() == actions[i].item():\n match += 1\n total += 1\n\n test_loss += loss.item()\n count += 1\n\n print(\"total loss: \" + str(test_loss / count))\n print(\"total match: \" + str(match / total))\n\n\n\ndef get_batch_from_memory():\n ## min_batch are all python data type (state, action, reward)\n train_data = replay_memory\n\n states = np.zeros((len(train_data), ROW_DIM, COLUMN_DIM)).astype(int)\n actions = []\n rewards = []\n for i, value in enumerate(train_data):\n states[i] = value[0]\n actions.append(value[1])\n ## TODO remember to change to 2\n rewards.append(value[2])\n #rewards.append(value[3])\n\n return (states, actions, rewards)\n\ndef load_train_data():\n global replay_memory\n fullpathname = train_data_path + \"full_data_test\"\n fd = open(fullpathname, 'rb')\n replay_memory = pickle.load(fd)\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"enter new or continue or testonly\")\n exit(0)\n\n MODE = sys.argv[1]\n if MODE != \"new\" and MODE != \"continue\" and MODE != \"testonly\":\n print(\"enter new or continue or testonly\")\n exit(0)\n\n\n net = Net()\n load_train_data()\n #print(len(replay_memory))\n #print(replay_memory[10])\n states, actions, rewards = get_batch_from_memory()\n net.train(states, actions, rewards, \"network_test.pth\")\n net.test()\n","sub_path":"cnn/policy_net.py","file_name":"policy_net.py","file_ext":"py","file_size_in_byte":5284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"424446353","text":"\"\"\"\npicture.py\nAuthor: xNimbleNavigatorx\nCredit: notkezar\n\nAssignment:\n\nUse the ggame library to \"paint\" a graphical picture of something (e.g. a house, a face or landscape).\n\nUse at least:\n1. Three different Color objects.\n2. Ten different Sprite objects.\n3. One (or more) RectangleAsset objects.\n4. One (or more) CircleAsset objects.\n5. One (or more) EllipseAsset objects.\n6. One (or more) PolygonAsset objects.\n\nSee:\nhttps://github.com/HHS-IntroProgramming/Standards-and-Syllabus/wiki/Displaying-Graphics\nfor general information on how to use ggame.\n\nSee:\nhttp://brythonserver.github.io/ggame/\nfor detailed information on ggame.\n\n\"\"\"\nfrom ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset\n\n# add your code here \\/ \\/ \\/\n\nred = Color(0xff0000, 1.0)\ngreen = Color(0x6B8E23, 1.0)\nblue = Color(0x0000ff, 1.0)\nblack = Color(0x000000, 1.0)\nwhite = Color(0xffffff, 1.0)\n\nmediumline = LineStyle(5, black)\neraserline = LineStyle(5, white)\n\neye1 = EllipseAsset(80, 50, mediumline, white)\neyerim = EllipseAsset(90, 65, mediumline, green)\nrectangleface = RectangleAsset(500, 500, mediumline, green)\nlip = RectangleAsset(366, 40, mediumline, red)\nrectangel = RectangleAsset(50, 30, mediumline, white)\npupil = CircleAsset(30, mediumline, black)\ntop = PolygonAsset([(308, 100), (425, 10), (550, 60), (675, 10), (792, 100)], mediumline, green)\nchin = PolygonAsset([(700, 600), (900, 600), (900, 500)], eraserline, white)\n\nSprite(rectangleface, (400, 100))\nSprite(lip, (533, 420))\nSprite(lip, (533, 460))\n\nSprite(eyerim, (830, 244))\nSprite(eyerim, (700, 244))\n\nSprite(eye1, (830, 244))\nSprite(eye1, (700, 244))\n\nSprite(pupil, (845, 260))\nSprite(pupil, (715, 260))\n\nSprite(top, (100, 0))\nSprite(chin, (0, 0))\n\n# add your code here /\\ /\\ /\\\n\nmyapp = App()\nmyapp.run()","sub_path":"picture.py","file_name":"picture.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"306541017","text":"import time\r\nimport datetime\r\nfrom Exceptions import InternalDataError\r\nfrom DetectionWords import NUMBERS, DAYS, MONTHS, OTHER\r\n\r\nclass EventInfo:\r\n def __init__(self, InputString):\r\n self.InputString = InputString\r\n\r\n def Get_EventName(self):\r\n UserInput = (self.InputString).split()\r\n # Searching the event name on a string like this: 'Crea el evento EVENT_NAME'\r\n n = UserInput.index(\"evento\") + 1 # EVENT_NAME Position\r\n try:\r\n UserInput[n] # Trying to go to the EVENT_NAME position.\r\n except IndexError: # If there's no no EVENT_NAME after 'evento'.\r\n for Word in UserInput:\r\n if Word == \"añade\" or Word == \"crea\" or Word == \"apunta\": # Searching other ways to get the event name.\r\n n = UserInput.index(Word) + 1 # Going to the next word after our objective word.\r\n try:\r\n EventName = UserInput[n]\r\n except IndexError: # If we can't get the event name, we raise InternalDataError.\r\n raise InternalDataError(\"The event name wasn't identified correctly.\")\r\n else: # If there's no error, we return the EventName\r\n EventName = UserInput[n]\r\n\r\n return EventName.capitalize()\r\n\r\n def Get_EventDate(self):\r\n \"\"\"\r\n From a string, get a list with the days that we are requesting the information.\r\n :return: Requested days in datetime format.\r\n \"\"\"\r\n Text = (self.InputString).lower()\r\n Today = datetime.date.today()\r\n\r\n if OTHER[0] in Text: # Yesterday.\r\n return [Today - datetime.timedelta(1)]\r\n if OTHER[1] in Text: # Today.\r\n return [Today]\r\n if OTHER[2] in Text: # Tomorrow.\r\n return [Today + datetime.timedelta(1)]\r\n if OTHER[3] in Text: # Day after tomorrow.\r\n return [Today + datetime.timedelta(2)]\r\n\r\n if OTHER[4] in Text: # Weekend.\r\n if Text.count(\"siguiente\") > 1:\r\n n = (Text.count(\"siguiente\") - 1) * 7 # Counting how many next weekends we are requesting.\r\n Current = Today + datetime.timedelta(n)\r\n else:\r\n Current = Today\r\n Week_Position = datetime.date.weekday(Current)\r\n Weekend_1 = Current + datetime.timedelta(5 - Week_Position) # Saturday.\r\n Weekend_2 = Current + datetime.timedelta(6 - Week_Position) # Sunday.\r\n\r\n return [Weekend_1, Weekend_1]\r\n\r\n if OTHER[5] in Text: # This week.\r\n Week_Position = datetime.date.weekday(Today)\r\n Next_Days = []\r\n N = (len(DAYS) - 1) - Week_Position\r\n if N != 0:\r\n for i in range(1,N + 1): # Returning all days from today to next Sunday.\r\n Current = Today + datetime.timedelta(i)\r\n Next_Days.append(Current)\r\n else:\r\n for i in range(1, 8): # If todays is Sunday, we return all next week.\r\n Current = Today + datetime.timedelta(i)\r\n Next_Days.append(Current)\r\n\r\n return Next_Days\r\n\r\n if OTHER[6] in Text: # Next week.\r\n Week_Position = datetime.date.weekday(Today)\r\n Next_Week = []\r\n Next_Monday = Today + datetime.timedelta(7 - Week_Position) # Saving the distance to Monday.\r\n for i in range(7): # From the next Monday, getting all the other days from this week.\r\n Current = Next_Monday + datetime.timedelta(i)\r\n Next_Week.append(Current)\r\n\r\n return Next_Week\r\n\r\n Day = -1\r\n Day_Of_Week = -1\r\n Month = -1\r\n Year = Today.year\r\n\r\n for Word in Text.split():\r\n if Word in MONTHS:\r\n Month = MONTHS.index(Word) + 1 # Getting the month number.\r\n elif Word in DAYS:\r\n Day_Of_Week = DAYS.index(Word)\r\n elif Word.isdigit():\r\n Day = int(Word)\r\n elif Word in NUMBERS:\r\n Day = NUMBERS.index(Word)\r\n\r\n if Month < Today.month and Month != -1:\r\n Year += 1\r\n if Day < Today.day and Month == -1 and Day != -1:\r\n Month = Today.month + 1\r\n if Month == -1 and Day == -1 and Day_Of_Week != -1:\r\n Current_Day_Of_Week = Today.weekday()\r\n Dif = Day_Of_Week - Current_Day_Of_Week\r\n if Dif < 0:\r\n Dif += 7\r\n if Text.count(\"siguiente\") > 1:\r\n x = (Text.count(\"siguiente\") - 1) * 7 # Counting the 'next'.\r\n Dif += x\r\n return [Today + datetime.timedelta(Dif)]\r\n if Day != -1 and Month == -1: # If we have the day but not the month, it means that we are talking about actual month.\r\n if Day < Today.day:\r\n Month = Today.month + 1\r\n elif Day > Today.day:\r\n Month = Today.month\r\n\r\n if Month == -1 or Day == -1:\r\n raise InternalDataError(\"The event date wasn't identified correctly.\")\r\n else:\r\n return [datetime.date(day=Day, month=Month, year=Year)]\r\n\r\n def Get_EventTime(self):\r\n \"\"\"\r\n From a string with the numeric time, we return HH:MM:SS.\r\n :return: HH:MM:SS datetime format.\r\n \"\"\"\r\n UserInput = (self.InputString).lower()\r\n # Removing some useless stuf...\r\n PluralTime = False\r\n if \"las\" in UserInput: # Important to know if for 125 we are talking about 01:25 (PluralTime = False) or 12:05 (PluralTime = True).\r\n PluralTime = True\r\n UserInput = UserInput.replace(\"a\", \"\")\r\n UserInput = UserInput.replace(\"la\", \"\")\r\n UserInput = UserInput.replace(\"ls\", \"\") # Avoiding a little bug.\r\n UserInput = UserInput.replace(\"l\", \"\") # Avoiding a little bug.\r\n UserInput = UserInput.replace(\"las\", \"\")\r\n UserInput = UserInput.replace(\"de\", \"\")\r\n UserInput = UserInput.replace(\"y\", \"\")\r\n UserInput = UserInput.replace(\" \", \"\")\r\n\r\n if \":\" in UserInput: # If our input string has a HH:MM format, we add the seconds HH:MM ---> HH:MM:00\r\n return UserInput + str(\":00\")\r\n if len(UserInput) == 4: # If we have HHMM\r\n UserInput = str(UserInput[:2]) + str(\":\") + str(UserInput[2:]) + str(\":\") + str(\"00\")\r\n return UserInput\r\n if len(UserInput) == 3: # If we have HMM\r\n # Important to know if for 125 we are talking about 01:25 (PluralTime = False) or 12:05 (PluralTime = True).\r\n if not PluralTime:\r\n UserInput = str(\"0\") + str(UserInput[0]) + str(\":\") + str(UserInput[1:]) + str(\":\") + str(\"00\")\r\n elif PluralTime:\r\n UserInput = str(UserInput[:2]) + str(\":\") + str(\"0\") + str(UserInput[-1]) + str(\":\") + str(\"00\")\r\n return UserInput\r\n if len(UserInput) == 1: # If we have H\r\n UserInput = str(\"0\") + str(UserInput[0]) + str(\":\") + str(\"00\") + str(\":\") + str(\"00\")\r\n return UserInput\r\n # That's the old way of getting the time, sometimes is useful.\r\n Hour = None\r\n Minutes = None\r\n for Word in UserInput.split():\r\n if Word.isdigit(): # If we have something like '12', '22', '8'...\r\n if Hour is None: # If the hour isn't asigned, we asing it.\r\n Hour = int(Word)\r\n else: # If we already have the hour, we add the minutes\r\n Minutes = int(Word)\r\n if Hour is None:\r\n raise InternalDataError(\"No time was found.\")\r\n else:\r\n if Minutes is None: # If we say, 'At 10', there's no going to be minutes so it means its 10:00.\r\n Minutes = \"00\"\r\n if len(str(Minutes)) == 1:\r\n Minutes = str(\"0\") + str(Minutes) # Adding a zero if we have something like 12:5 ---> 12:05\r\n if len(str(Hour)) == 1:\r\n Hour = str(Hour) + str(\"0\") # Adding a zero if we have something like 2:15 ---> 02:15\r\n\r\n EventTime = str(Hour) + str(\":\") + str(Minutes) + str(\":\") + str(\"00\")\r\n return EventTime\r\n\r\n def Get_EventDescription(self): # Converting from 'event description' ---> 'Event description.'\r\n UserInput = list(self.InputString)\r\n UserInput[0] = UserInput[0].upper()\r\n if UserInput[-1] != \".\":\r\n UserInput.append(\".\")\r\n EventDescription = \"\"\r\n for UserChar in UserInput:\r\n EventDescription += str(UserChar)\r\n\r\n return EventDescription\r\n\r\n def Get_EventLocation(self):\r\n return str(self.InputString)\r\n\r\n def __len__(self):\r\n return len(self.InputString)\r\n\r\n def __str__(self):\r\n return str(self.InputString)\r\n","sub_path":"EventInfo_String.py","file_name":"EventInfo_String.py","file_ext":"py","file_size_in_byte":8816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"89428927","text":"class Solution(object):\n\n def maxSubArray(self, A):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not A:\n return 0\n\n curSum = maxSum = A[0]\n for num in A[1:]:\n curSum = max(num, curSum + num)\n maxSum = max(maxSum, curSum)\n print(num, ':', curSum, maxSum)\n return maxSum\n\n def maxSubArray2(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n for i in range(1, len(nums)):\n nums[i] = max(nums[i - 1] + nums[i], nums[i])\n print(nums)\n return max(nums) # 不能写nums[-1], 因为可能有负的元素使dp状态的大小降低\n\n\ns = Solution()\nl = [-2, 1, -3, 4, -1, 2, 1, -5, 4]\nprint(s.maxSubArray2(l))\n","sub_path":"LeetCode/53_Maximum_Subarray.py","file_name":"53_Maximum_Subarray.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"579180533","text":"from sportsreference.ncaab.teams import Teams\nfrom sportsreference.ncaab.boxscore import Boxscores\nfrom sportsreference.ncaab.boxscore import Boxscore\nfrom sportsreference.ncaab.conferences import Conferences\nimport statistics\nimport pickle\nfrom statistics import mean\nfrom scipy.linalg import eig\nimport numpy as np\nimport scipy.linalg as linalg\nfrom scipy.stats import norm\nfrom scipy.stats import zscore\nimport csv\nimport codecs\nimport math\nfrom datetime import datetime\nfrom datetime import date\nfrom scipy.sparse.linalg import eigs\nimport statsmodels.api as sm\nfrom datetime import timedelta\nimport pandas as pd\n\n\n\ndef save_pickle(obj, filename):\n\t# filename must be .pickle\n\tpickle_out = open(filename, 'wb')\n\tpickle.dump(obj, pickle_out)\n\ndef load_pickle(filename):\n\t# filename will be .pickle\n\tpickle_in = open(filename, \"rb\")\n\treturn pickle.load(pickle_in)\n\n\nYEAR = 2020\n# THIS IS THE ONLY VAR YOU HAVE TO CHANGE FOR EACH YEAR\n\nteams = Teams(YEAR)\nconferences = Conferences(YEAR)\n\ndef gen_HCA_data(csvfile):\n\td = {}\n\twith open('/Users/kylecox/Desktop/Projects/cb-revisited-2/kenpom_HCA_2020.csv', 'r') as f:\n\t\treader = csv.reader(f)\n\t\tfor row in reader:\n\t\t\td[str(row[0])] = float(str(row[2]))\n\treturn d\n\n\ndef index_teams():\n\tindex_teams_d = {}\n\ti = 0\n\tfor team in teams:\n\t\tindex_teams_d[team.name] = i\n\t\ti += 1\n\treturn index_teams_d\n\n\ndef reverse_index_teams():\n\tindex_teams_d = {}\n\ti = 0\n\tfor team in teams:\n\t\tindex_teams_d[i] = team.name\n\t\ti += 1\n\treturn index_teams_d\n\n# d1_team_names = []\n# for team in teams:\n# \td1_team_names.append(team.name)\n# save_pickle(d1_team_names, 'd1_team_names.pickle')\nd1_team_names = load_pickle('d1_team_names.pickle')\n\ndef index_team_games_played(interia=False):\n\tindex_teams_d = {}\n\tfor team in teams:\n\t\tgames_played = 0\n\t\tfor game in team.schedule:\n\t\t\tif game.opponent_name in d1_team_names or game.opponent_name == 'Virginia Military Institute':\n\t\t\t\tif game.datetime.date() < datetime.now().date():\n\t\t\t\t\t# this might have to change if i am updating past 12 am\n\t\t\t\t\tgames_played += 1\n\t\t\t\telse:\n\t\t\t\t\tbreak\n\t\t\t# only counts games played against d1 teams\n\t\tindex_teams_d[team.name] = games_played\n\treturn index_teams_d\n\n\n# global vars\n# R_INDEX_TEAMS_D = reverse_index_teams()\n# save_pickle(R_INDEX_TEAMS_D, str(YEAR) + '/r_index_teams_d_' + str(YEAR) + '.pickle')\nR_INDEX_TEAMS_D = load_pickle(str(YEAR) + '/r_index_teams_d_' + str(YEAR) + '.pickle')\n\n# HCA_DATA = gen_HCA_data('/Users/kylecox/Desktop/Projects/cb-revisited-2/kenpom_HCA_2020.csv')\n# save_pickle(HCA_DATA, str(YEAR) + '/hca_data_' + str(YEAR) + '.pickle')\nHCA_DATA = load_pickle(str(YEAR) + '/hca_data_' + str(YEAR) + '.pickle')\n\n# index_teams_d = index_teams()\n# save_pickle(index_teams_d, str(YEAR) + '/index_teams_d_' + str(YEAR) + '.pickle')\nindex_teams_d = load_pickle(str(YEAR) + '/index_teams_d_' + str(YEAR) + '.pickle')\nlogged_games = []\n\n# need to make this not commented out after a new day of play\n# index_team_games_played_d = index_team_games_played()\n# save_pickle(index_team_games_played_d, str(YEAR) + '/index_team_games_played_d_' + str(YEAR) + '.pickle')\nindex_team_games_played_d = load_pickle(str(YEAR) + '/index_team_games_played_d_' + str(YEAR) + '.pickle')\n\n# pace_d = dict() \n# for team in teams:\n# \tpace_d[team.name] = team.pace\n# save_pickle(pace_d, str(YEAR) + '/pace_d_' + str(YEAR) + '.pickle')\npace_d = load_pickle(str(YEAR) + '/pace_d_' + str(YEAR) + '.pickle')\n\n\nnum_teams = len(d1_team_names)\n\ndef filter_none(lst):\n\tres = [i for i in lst if i]\n\treturn res\n\ndef gen_poss_per_game(game):\n# takes game object\n\tpossessions = game.boxscore.pace\n\treturn possessions\n\ndef weigh_margin(n, k=6):\n\t# f = lambda x: 1 / (1 + math.exp(-4*x) )\n\t# f = lambda x: math.exp(3*x)\n\t# f = lambda x: (math.atan(8*x))*600 + 500\n\t# f = lambda x: x\n\tif n >= 0:\n\t\t# return 1\n\t\tf = lambda x: math.log((x+k)/k) + 1\n\t\t# f = lambda x: (4*x/70)**(.8) + 1 \n\telse:\n\t\t# return 0\n\t\tf = lambda x: 1/(math.log((-1*x+k)/k) + 1)\n\t\t# f = lambda x: 1/((-4*x/70)**(.8) + 1)\n\t# if True:\n\t# \tf = lambda x: x**3 + 1 - x**2\n\treturn f(n)\n\n\ndef gen_game_def_rating(game):\n# takes game object from schedules parent\n\td = load_pickle('off_eff_d_' + str(YEAR) + '.pickle')\n\topp_score = game.points_against\n\tpace = gen_poss_per_game(game)\n\topp_pts_per_poss = float(opp_score)/float(pace)\n\tif game.opponent_name in d1_team_names:\n\t\topp_off_l = d[game.opponent_name]\n\t\topp_off_l = filter_none(opp_off_l)\n\t\trating = mean(opp_off_l) - opp_pts_per_poss \n# lower points opp_score = higher percentile\n\telse:\n\t\trating = None\n# the game was not against another d1 team\n\treturn rating\n\t# positive rating indicates team defended better than expected,\n\t# i.e. opposing team scored less than average\n\n\ndef gen_game_off_rating(game):\n# takes game object from schedules parent\n\td = load_pickle('def_eff_d_' + str(YEAR) + '.pickle')\n\tteam_score = game.points_for\n\tpace = game.boxscore.pace\n\ttry:\n\t\tteam_pts_per_poss = float(team_score)/float(pace)\n\t\t# why would pace be a None type???\n\texcept:\n\t\trating = None\n\t\treturn None\n\tif game.opponent_name in d1_team_names:\n\t\topp_defense_l = d[game.opponent_name]\n\t\topp_defense_l = filter_none(opp_defense_l)\n\t\ttry:\n\t\t\trating = team_pts_per_poss - mean(opp_defense_l)\n\t\texcept:\n\t\t\trating = None\n\telse:\n\t\trating = None\n# the game was not against another d1 team\n\treturn rating\n\t# positive rating indicates team scored more than expected,\n\t# or scored more than opponent allows on average\n\ndef create_df(update=True):\n\tif update is True:\n\t\tgames_d = load_pickle('games_d_2020.pickle')\n\telse:\n\t\tgames_d = dict()\n\tfor team in teams:\n\t\tprint(team.name)\n\t\tfor game in team.schedule:\n\t\t\tindex = game.boxscore_index\n\t\t\tif game.boxscore in games_d.keys():\n\t\t\t\tcontinue\n\t\t\tif game.datetime.date() > datetime.now().date():\n\t\t\t\tcontinue\n\t\t\tif game.boxscore_index in games_d.keys():\n\t\t\t\tcontinue\n\t\t\tcol = game.boxscore_index\n\t\t\tmatch = (team.name, game.opponent_name)\n\t\t\tdate = str(game.datetime.date())\n\t\t\topponent = game.opponent_name\n\t\t\t# opponent_record = game.opponent\n\t\t\tif team.name not in d1_team_names or game.opponent_name not in d1_team_names:\n\t\t\t\td1 = False\n\t\t\telse:\n\t\t\t\td1 = True\n\t\t\tif game.result == 'Win':\n\t\t\t\twinner = team.name\n\t\t\telse:\n\t\t\t\twinner = game.opponent_name\n\t\t\tif game.points_for is not None and game.points_against is not None:\n\t\t\t\tmargin = game.points_for - game.points_against\n\t\t\telse:\n\t\t\t\tmargin = None\n\t\t\tpace = game.boxscore.pace\n\t\t\tif game.location == 'Home':\n\t\t\t\thome = team.name\n\t\t\telif game.location == 'Away':\n\t\t\t\thome = game.opponent_name\n\t\t\telse:\n\t\t\t\thome = 'Neutral'\n\t\t\t # home evalutates to a team name if either team is home or Neutral if game is neutral\n\t\t\t# ranks ??\n\t\t\t# location ??\n\t\t\tgames_d[col] = [index, date, match, opponent, d1, home, winner, margin, pace]\n\tsave_pickle(games_d, 'games_d_2020.pickle')\n\tdf = pd.DataFrame(data=games_d, index=['Boxscore Index', 'Date', 'Match', 'Opponent', 'D1', 'Home', 'Winner', 'Margin', 'Pace'])\n\tsave_pickle(df, 'games_df_2020.pickle')\n\treturn df\n\n\n\n\ndef gen_margin(team, game, HCA_DATA):\n\t# not adjusted based on opponent SOS, but adjusted for tempo\n\ttry:\n\t\toff_eff = float(game.points_for)\n\t\tdef_eff = float(game.points_against)\n\t\tmargin = off_eff - def_eff\n\t\tif game.location == 'Home':\n\t\t\tif team.name == 'Virginia Military Institute':\n\t\t\t\tname = 'VMI'\n\t\t\telse:\n\t\t\t\tname = team.name.replace('-', ' ')\n\t\t\thca = HCA_DATA[name]#/float(game.boxscore.pace)\n\t\t\tmargin -= hca\n\t\telif game.location == 'Away':\n\t\t\tif game.opponent_name == 'Virginia Military Institute':\n\t\t\t\tname = 'VMI'\n\t\t\telse:\n\t\t\t\tname = game.opponent_name.replace('-', ' ')\n\t\t\thca = HCA_DATA[name]#/float(game.boxscore.pace)\n\t\t\tmargin += hca\n\t\t# margin = weigh_margin(margin)\n\t\t# problems:\n\t\t\t# no way to check if neutral location - might take another function\n\t\t\t# what if ken poms team names do not match sportsreference?\n\texcept TypeError:\n\t\tmargin = None\n\treturn margin\n\n\n# test game offensive and defensive rating for team Virginia\ndef test_ratings():\n\td_ratings = {}\n\tfor team in teams:\n\t\tif team.name == 'Virginia':\n\t\t\to_r = []\n\t\t\td_r = []\n\t\t\tfor game in team.schedule:\n\t\t\t\to = gen_game_off_rating(game)\n\t\t\t\td = gen_game_def_rating(game)\n\t\t\t\to_r.append(o)\n\t\t\t\td_r.append(d)\n\t\t\tprint(o_r)\n\t\t\tprint(d_r)\n\t\t\td_ratings[team.name] = [mean(o_r), mean(d_r)]\n\tfor key in d_ratings.keys():\n\t\tprint(key)\n\t\tprint(d_ratings[key])\n\t\tprint('\\n')\n\n\ndef generate_margins_matrix(inertia=False):\n\tif inertia is True:\n\t\tdate = datetime.now().date() - timedelta(days=30)\n\tlogged_games = []\n\tpast_matchups = {}\n\tmatrix = np.zeros( (num_teams, num_teams) )\n\t# let's assume teams are even to start off\n\tfor team in teams:\n\t\tfor game in team.schedule:\n\t\t\tif game.boxscore_index in logged_games:\n\t\t\t\tcontinue\n\t\t\tif inertia is True:\n\t\t\t\tif game.datetime.date() < date:\n\t\t\t\t\tcontinue\n\t\t\tif game.opponent_name == 'Virginia Military Institute':\n\t\t\t\topponent_name = 'VMI'\n\t\t\telse:\n\t\t\t\topponent_name = game.opponent_name\n\t\t\tif opponent_name not in d1_team_names:\n\t\t\t\tlogged_games.append(game.boxscore_index)\n\t\t\t\tcontinue\n\t\t\tif team.name == 'Virginia Military Institute':\n\t\t\t\tteam_name = 'VMI'\n\t\t\telse:\n\t\t\t\tteam_name = team.name\n\t\t\topponent_index = index_teams_d[opponent_name]\n\t\t\tteam_index = index_teams_d[team_name]\n\t\t\t# how to deal with teams that play each other more than once ?\n\t\t\tmargin = gen_margin(team, game, HCA_DATA)\n\t\t\tif margin is None:\n\t\t\t\tprint(None)\n\t\t\t\tbreak\n\t\t\t\t# continue\n\t\t\tif matrix[team_index][opponent_index] == 0:\n\t\t\t\tprint(team_name + ' vs ' + opponent_name)\n\t\t\t\tprint(margin)\n\t\t\t\tprint('\\n')\n\n\t\t\t\tmatrix[team_index][opponent_index] = margin\n\t\t\telse:\n\t\t\t\tmatrix[team_index][opponent_index] += margin\n\t\t\tif matrix[opponent_index][team_index] == 0:\n\t\t\t\tmatrix[opponent_index][team_index] = margin * (-1)\n\t\t\telse:\n\t\t\t\tmatrix[opponent_index][team_index] += margin * (-1)\n\t\t\t\t# not sure about this part ?\n\t\t\t\t# tup = (team_name, opponent_name)\n\t\t\t\t# if tup in past_matchups.keys():\n\t\t\t\t# \t# what is margin is None\n\t\t\t\t# \tpast_matchups[tup].append(margin)\n\t\t\t\t# else:\n\t\t\t\t# \tpast_matchups[tup] = [matrix[team_index][opponent_index], margin]\n\t\t\t\t# matrix[team_index][opponent_index] = mean(past_matchups[tup])\n\t\t\t\t# this is where i run into a problem -- what if there's already a match played??\n\t\t\tif inertia is False:\n\t\t\t\tlogged_games.append(game.boxscore_index)\n\tif inertia is False:\n\t\tsave_pickle(logged_games, str(YEAR) + '/logged_games_' + str(YEAR) + '.pickle')\n\t\tsave_pickle(matrix, str(YEAR) + '/margins_matrix_' + str(YEAR) + '.pickle')\n\telse:\n\t\tsave_pickle(matrix, str(YEAR) + '/inertia_matrix_' + str(YEAR) + '.pickle')\n\treturn matrix\n\ndef update_margins_matrix(logged_games):\n\td = load_pickle('games_d_2020.pickle')\n\tdf = load_pickle('games_df_2020.pickle')\n\tpast_matchups = {}\n\t# matrix = load_pickle(str(YEAR) + '/margins_matrix_' + str(YEAR) + '.pickle')\n\tmatrix = np.zeros( (num_teams, num_teams) )\n\tfor game in d.keys():\n\t\tif d[game] in logged_games:\n\t\t\tcontinue\n\t\tif df.loc['Opponent', game] not in d1_team_names:\n\t\t\tlogged_games.append(game)\n\t\t\tcontinue\n\t\tif df.loc['Match', game][0] == 'Virginia Military Insitute':\n\t\t\tteam_name = 'VMI'\n\t\telse:\n\t\t\tteam_name = df.loc['Match', game][0]\n\t\tif df.loc['Match', game][1] == 'Virginia Military Insitute':\n\t\t \topponent_name = 'VMI'\n\t\telse:\n\t\t \topponent_name = df.loc['Match', game][1]\n\t\tteam_index = index_teams_d[team_name]\n\t\topponent_index = index_teams_d[opponent_name]\n\t\t# margin = gen_margin(team, game, HCA_DATA)\n\t\ttry:\n\t\t\tif df.loc['Home', game] == df.loc['Match', game][0]:\n\t\t\t\thca = HCA_DATA[team_name]\n\t\t\telif df.loc['Home', game] == df.loc['Match', game][1]:\n\t\t\t\thca = HCA_DATA[opponent_name] * -1\n\t\t\telif df.loc['Home', game] == 'Neutral':\n\t\t\t\thca = 0\n\t\t\tmargin = df.loc['Margin', game] + hca\n\t\texcept:\n\t\t\t# print('None')\n\t\t\tmargin = None\n\t\tif margin is None:\n\t\t\tcontinue\n\n\t\tif matrix[team_index][opponent_index] == 0:\n\t\t\tprint(team_name + ' vs ' + opponent_name)\n\t\t\tprint(margin)\n\t\t\tprint('\\n')\n\t\t\tmatrix[team_index][opponent_index] = margin\n\t\telse:\n\t\t\tmatrix[team_index][opponent_index] += margin\n\t\tif matrix[opponent_index][team_index] == 0:\n\t\t\tteam_name = R_INDEX_TEAMS_D[opponent_index]\n\t\t\topponent_name = R_INDEX_TEAMS_D[team_index]\n\t\t\tmatrix[opponent_index][team_index] = margin * (-1)\n\t\t\tprint(team_name + ' vs ' + opponent_name)\n\t\t\t# print(margin)\n\t\t\tprint(matrix[opponent_index][team_index])\n\t\t\tprint('\\n')\n\t\telse:\n\t\t\tmatrix[opponent_index][team_index] += margin * (-1)\n\t\tlogged_games.append(game)\n\tsave_pickle(logged_games, str(YEAR) + '/logged_games_' + str(YEAR) + '.pickle')\n\tsave_pickle(matrix, str(YEAR) + '/margins_matrix_' + str(YEAR) + '.pickle')\n\treturn matrix\n\t# for team in teams:\n\t# \tfor game in team.schedule:\n\t# \t\tif game.boxscore_index in logged_games or game.opponent_name not in d1_team_names:\n\t# \t\t\t# if game has already been logged continue to next game\n\t# \t\t\tcontinue\n\t# \t\tif game.opponent_name == 'Virginia Military Institute':\n\t# \t\t\topponent_name = 'VMI'\n\t# \t\telse:\n\t# \t\t\topponent_name = game.opponent_name\n\t# \t\tif opponent_name not in d1_team_names:\n\t# \t\t\tlogged_games.append(game.boxscore_index)\n\t# \t\t\tcontinue\n\t# \t\tif team.name == 'Virginia Military Institute':\n\t# \t\t\tteam_name = 'VMI'\n\t# \t\telse:\n\t# \t\t\tteam_name = team.name\n\t# \t\topponent_index = index_teams_d[opponent_name]\n\t# \t\tteam_index = index_teams_d[team_name]\n\t# \t\t# how to deal with teams that play each other more than once ?\n\t# \t\tmargin = gen_margin(team, game, HCA_DATA)\n\t# \t\tif margin is None:\n\t# \t\t\tbreak\n\n\t# \t\tif matrix[team_index][opponent_index] == 0:\n\t# \t\t\tprint(team_name + ' vs ' + opponent_name)\n\t# \t\t\tprint(margin)\n\t# \t\t\tprint('\\n')\n\t# \t\t\tmatrix[team_index][opponent_index] = margin\n\t# \t\telse:\n\t# \t\t\tmatrix[team_index][opponent_index] += margin\n\t# \t\tif matrix[opponent_index][team_index] == 0:\n\t# \t\t\tteam_name = R_INDEX_TEAMS_D[opponent_index]\n\t# \t\t\topponent_name = R_INDEX_TEAMS_D[team_index]\n\t# \t\t\tmatrix[opponent_index][team_index] = margin * (-1)\n\t# \t\t\tprint(team_name + ' vs ' + opponent_name)\n\t# \t\t\t# print(margin)\n\t# \t\t\tprint(matrix[opponent_index][team_index])\n\t# \t\t\tprint('\\n')\n\t# \t\telse:\n\t# \t\t\tmatrix[opponent_index][team_index] += margin * (-1)\n\t# \t\t\t# tup = (team_name, opponent_name)\n\t# \t\t\t# if tup in past_matchups.keys():\n\t# \t\t\t# \t# what if margin is None?\n\t# \t\t\t# \tpast_matchups[tup].append(margin)\n\t# \t\t\t# else:\n\t# \t\t\t# \tpast_matchups[tup] = [matrix[team_index][opponent_index], margin]\n\t# \t\t\t# matrix[team_index][opponent_index] = mean(past_matchups[tup])\n\t# \t\tlogged_games.append(game.boxscore_index)\n\t# save_pickle(logged_games, str(YEAR) + '/logged_games_' + str(YEAR) + '.pickle')\n\t# save_pickle(matrix, str(YEAR) + '/margins_matrix_' + str(YEAR) + '.pickle')\n\t# return matrix\n\n\n\ndef generate_eigen(matrix):\n\tM = matrix\n\tval, vec = eigs(M, which='LM', k=1)\n\treturn vec\n\t# should return a pair: eigen vals and eigenvectors\n\t# one of the eigenvalues should be real\n\t# this real eigenvalue corresponds to a real eigenvector (which is the vector of interest, i.e. the rankings)\n\t# check marksmath.org for more\n\n\ndef shift_matrix(matrix):\n\t# print('shifting')\n\trow_num = 0\n\tfor r in range(len(matrix)):\n\t\tteam_name = R_INDEX_TEAMS_D[r]\n\t\tgames_played = index_team_games_played_d[team_name]\n\t\tfor c in range(len(matrix[r])):\n\t\t\telement = matrix[r][c]\n\t\t\tif element != 0:\n\t\t\t\tmatrix[r][c] = weigh_margin(element)/float(games_played)\n\treturn matrix\n\n \ndef find_R(matrix):\n\tE = generate_eigen(matrix)\n\tzipped = zip(list(index_teams_d.keys()), E)\n\td = dict(zipped)\n\tsave_pickle(d, 'unweighted_ratings_2020.pickle')\n\treturn E\n\n\n\ndef normalize_vector(l):\n\t# takes list\n\tstandardized_l = zscore(l)\n\tnormalized_l = [norm.cdf(e) for e in standardized_l]\n\t# linear_model()\n\t# d = load_pickle('unweighted_ratings_2020.pickle')\n\t# l = []\n\t# for key in d.keys():\n\t# \tl.append(d[key])\n\t# avg = sum(l)/len(l)\n\t# reg = load_pickle(str(YEAR) + '/linear_model_' + str(YEAR) + '.pickle')\n\t# for team in teams:\n\t# \tif team.name == \"Virginia Military Institute\":\n\t# \t\tteam_name = 'VMI'\n\t# \telse:\n\t# \t\tteam_name = team.name\n\t# \trating = d[team_name]\n\t# \tprint(team.name)\n\t# \tprint(reg.predict(np.array([rating, avg, 0,]))[0]*100)\n\treturn normalized_l\n\n\ndef write_csv(R, YEAR, dataname='rankings', em=False):\n\tfilename = str(YEAR) + '/' + dataname + '_' + str(YEAR) + '_' + str(datetime.today()) + '.csv'\n\n\t# ratings = {}\n\t# with open('2020/weighted_rankings_2020_2019-11-22.csv', 'r') as f:\n\t# \t# need to change this so it automatically does most recent date\n\t# \treader = csv.reader(f)\n\t# \tfor row in reader:\n\t# \t\tname = row[0]\n\t# \t\trating = row[1]\n\t# \t\tratings[name] = rating\n\tif em is True:\n\t\tEMs = load_pickle('EMs_2020.pickle')\n\t\tadj_EM = load_pickle('EM_diff.pickle')\n\td = {}\n\tfor team in teams:\n\t\t# print(team.name)\n\t\twins = team.wins\n\t\tlosses = team.losses\n\t\t# print(wins)\n\t\t# print(losses)\n\t\t# print('\\n')\n\t\tif team.name == 'Virginia Military Institute':\n\t\t\tname = 'VMI'\n\t\telse:\n\t\t\tname = team.name\n\t\t# opp_strength = []\n\t\t# for game in team.schedule:\n\t\t# \ttry:\n\t\t# \t\topp_strength.append(float(ratings[game.opponent_name]))\n\t\t# \texcept:\n\t\t# \t\tpass\n\t\t# try:\n\t\t# \tsos = mean(opp_strength)\n\t\t# except:\n\t\t# \tprint('No SOS')\n\t\t# \tprint(team.name)\n\t\t# \tsos = None\n\t\trecord = str(wins) + '--' + str(losses)\n\t\tem = EMs[name]\n\t\tem_a = adj_EM[name]\n\t\tconf = team.conference.replace('-', ' ')\n\t\tconf_wins = team.conference_wins\n\t\tconf_losses= team.conference_losses\n\t\tconf_record = str(conf_wins) + '--' + str(conf_losses)\n\t\tpace = team.pace\n\n\t\tif em is False:\n\t\t\td[name] = [record, conf_record, conf, pace]\n\t\telse:\n\t\t\td[name] = [em, em_a, record, conf_record, conf, pace]\n\n\t\t\t\n\n\n\tneg_R = R[0] < 0\n\t# if R is negative\n\n\twith open(filename, 'w') as f:\n\t\twriter = csv.writer(f)\n\t\tif em is False:\n\t\t\twriter.writerow(['Team', 'CDF Rating', 'Record', 'Conf. Rec.', 'Conference', 'Tempo'])\n\t\telse:\n\t\t\twriter.writerow(['Team', 'CDF Rating', 'EM', 'Adj. EM', 'Record', 'Conf. Rec.', 'Conference', 'Tempo'])\n\t\tfor i in range(len(d1_team_names)):\n\t\t\t# print(R_INDEX_TEAMS_D[i])\n\t\t\tif R_INDEX_TEAMS_D[i] == 'VMI':\n\t\t\t\tR_INDEX_TEAMS_D[i] = 'Virginia Military Institute'\n\t\t\tif neg_R:\n\t\t\t\t# reflects R values over 0 if negative\n\t\t\t\trating = (((R[i])*(-1))+1)*100\n\t\t\telse:\n\t\t\t\trating = R[i]*100\n\t\t\tl = [R_INDEX_TEAMS_D[i], rating]\n\t\t\tif R_INDEX_TEAMS_D[i] == 'Virginia Military Institute':\n\t\t\t\tl.extend(d['VMI'])\n\t\t\telse:\n\t\t\t\tl.extend(d[R_INDEX_TEAMS_D[i]])\n\t\t\twriter.writerow(l)\n\t\t\t# print(str(R_INDEX_TEAMS_D[i]) + ': ' + str(rating))\n\t\t\t# might not need the negative 1\n\ndef update_rankings():\n\tindex_teams_d = load_pickle(str(YEAR) + '/index_teams_d_' + str(YEAR) + '.pickle')\n\tlogged_games = load_pickle(str(YEAR) + '/logged_games_' + str(YEAR) + '.pickle')\n\tmargins_matrix = update_margins_matrix(logged_games)\n\tsave_pickle(margins_matrix, str(YEAR) + '/margins_matrix_' + str(YEAR) + '.pickle')\n\tmargins_matrix = np.array( margins_matrix, dtype = 'float64' )\n\t# margins_matrix = np.array( margins_matrix )\n\tshifted_margins_matrix = shift_matrix(margins_matrix)\n\tprint(shifted_margins_matrix)\n\tsave_pickle(shifted_margins_matrix, str(YEAR) + '/shifted_margins_matrix_' + str(YEAR) + '.pickle')\n\tR = find_R(shifted_margins_matrix)\n\tsave_pickle(R, str(YEAR) + '/R_' + str(YEAR))\n\tR_normalized = normalize_vector(R)\n\tsave_pickle(R_normalized, str(YEAR) + '/R_normalized_' + str(YEAR) + '.pickle')\n\twrite_csv(R_normalized, YEAR, 'weighted_rankings')\n\ndef generate_new_rankings():\n\t# off_eff_d = gen_opp_off_eff_adjusted_d()\n\t# save_pickle(off_eff_d, 'off_eff_d_' + str(YEAR) + '.pickle')\n\n\t# def_eff_d = gen_opp_def_eff_adjusted_d()\n\t# save_pickle(def_eff_d, 'def_eff_d_' + str(YEAR) + '.pickle')\n\n\t# index_teams_d = index_teams()\n\t# save_pickle(index_teams_d, str(YEAR) + '/index_teams_d_' + str(YEAR) + '.pickle')\n\n\tmargins_matrix = generate_margins_matrix()\n\tsave_pickle(margins_matrix, str(YEAR) + '/margins_matrix_' + str(YEAR) + '.pickle')\n\t# # this serves as preference matrix for eigen operation\n\tprint('Preference matrix generated!')\n\n\tmargins_matrix = load_pickle(str(YEAR) + '/margins_matrix_' + str(YEAR) + '.pickle')\n\n\tmargins_matrix = np.array( margins_matrix, dtype = 'float64' )\n\n\t# save_pickle(generate_eigen(margins_matrix), str(YEAR) + '/eigen_pair_' + str(YEAR) + '.pickle')\n\t# eigen_pair = load_pickle(str(YEAR) + '/eigen_pair_' + str(YEAR) + '.pickle')\n\n\tshifted_margins_matrix = shift_matrix(margins_matrix)\n\tsave_pickle(shifted_margins_matrix, str(YEAR) + '/shifted_margins_matrix_' + str(YEAR) + '.pickle')\n\n\tshifted_margins_matrix = load_pickle(str(YEAR) + '/shifted_margins_matrix_' + str(YEAR) + '.pickle')\n\n\tR = find_R(shifted_margins_matrix)\n\tsave_pickle(R, str(YEAR) + '/R_' + str(YEAR))\n\n\tR_normalized = normalize_vector(R)\n\tsave_pickle(R_normalized, str(YEAR) + '/R_normalized_' + str(YEAR) + '.pickle')\n\n\tR_normalized = load_pickle(str(YEAR) + '/R_normalized_' + str(YEAR) + '.pickle')\n\n\twrite_csv(R_normalized, YEAR, 'weighted_rankings')\n\ndef logistic_model():\n\t# d = load_pickle('unweighted_rankings_2020.pickle')\n\t# d = {}\n\t# for team in rankings:\n\t# \td[team[0]] = team[1]\n\td = load_pickle('EM_diff.pickle')\n\tA = []\n\tB = []\n\tY = []\n\tL = []\n\tn = 0\n\tfor team in teams:\n\t\tprint(team.name)\n\t\tif team.name == \"Virginia Military Institute\":\n\t\t\tteam_name = 'VMI'\n\t\telse:\n\t\t\t team_name = team.name\n\t\tfor game in team.schedule:\n\t\t\tn += 1\n\t\t\tif n % 10 != 0:\n\t\t\t\tcontinue\n\t\t\tif game.datetime.date() > datetime.now().date():\n\t\t\t\tbreak\n\t\t\tif game.opponent_name == 'Virginia Military Institute':\n\t\t\t\topponent_name = 'VMI'\n\t\t\telse:\n\t\t\t\topponent_name = game.opponent_name\n\t\t\tif opponent_name not in d1_team_names or team_name not in d1_team_names:\n\t\t\t\tcontinue\n\t\t\ttry:\n\t\t\t\tif game.location == 'Home':\n\t\t\t\t\thca = HCA_DATA[team_name]\n\t\t\t\telif game.location == 'Away':\n\t\t\t\t\thca = HCA_DATA[opponent_name] * -1\n\t\t\t\telse:\n\t\t\t\t\thca = 0\n\t\t\texcept:\n\t\t\t\tcontinue\n\t\t\ttry:\n\t\t\t\ta = d[team_name]\n\t\t\t\tb = d[opponent_name]\n\t\t\t\tpace = (pace_d[team.name] + pace_d[game.opponent_name])/200\n\t\t\t\tem = (a-b)*pace + hca\n\t\t\texcept:\n\t\t\t\tcontinue\n\t\t\ttry:\n\t\t\t\tif game.boxscore.winning_abbr == team.abbreviation:\n\t\t\t\t\ty = 1\n\t\t\t\telse:\n\t\t\t\t\ty = 0\n\t\t\texcept:\n\t\t\t\tcontinue\n\t\t\ttry:\n\t\t\t\tA.append(em)\n\t\t\t\tY.append(y)\n\t\t\texcept:\n\t\t\t\tcontinue\n\tA = np.array(A).reshape(-1,1)\n\tY = np.array(Y).reshape(-1,1)\n\tsave_pickle(A, str(YEAR) + '/A_' + str(YEAR) + '.pickle')\n\tsave_pickle(Y, str(YEAR) + '/Y_' + str(YEAR) + '.pickle')\n\treg = sm.Logit(Y,A).fit()\n\tsave_pickle(reg, str(YEAR) + '/logistic_model_' + str(YEAR) + '.pickle')\n\treturn reg\n\ndef linear_model():\n\td = load_pickle('unweighted_ratings_2020.pickle')\n\tn = 0\n\tA = []\n\tB = []\n\tM = []\n\tP = []\n\tL = []\n\tfor team in teams:\n\t\tprint(team.name)\n\t\tif team.name == \"Virginia Military Institute\":\n\t\t\tteam_name = 'VMI'\n\t\telse:\n\t\t\t team_name = team.name\n\t\tfor game in team.schedule:\n\t\t\tn +=1\n\t\t\tif n % 10 != 0:\n\t\t\t\tcontinue\n\t\t\tif game.datetime.date() > datetime.now().date():\n\t\t\t\t# print('err 0')\n\t\t\t\tbreak\n\t\t\tif game.opponent_name == 'Virginia Military Institute':\n\t\t\t\topponent_name = 'VMI'\n\t\t\telse:\n\t\t\t\topponent_name = game.opponent_name\n\t\t\tif opponent_name not in d1_team_names or team_name not in d1_team_names:\n\t\t\t\tcontinue\n\t\t\ttry:\n\t\t\t\ta = d[team_name]\n\t\t\t\tb = d[opponent_name]\n\t\t\texcept:\n\t\t\t\tprint('err 1')\n\t\t\t\tcontinue\n\t\t\ttry:\n\t\t\t\tm = game.points_for - game.points_against\n\t\t\t\tp = game.boxscore.pace\n\t\t\t\tm = m/p\n\t\t\texcept:\n\t\t\t\tprint('err 2')\n\t\t\t\tcontinue\n\t\t\ttry:\n\t\t\t\tif game.location == 'Home':\n\t\t\t\t\tlocation = 1\n\t\t\t\telif game.location == 'Away':\n\t\t\t\t\tlocation = -1\n\t\t\t\telse:\n\t\t\t\t\tlocation = 0\n\t\t\texcept:\n\t\t\t\tprint('err 3')\n\t\t\t\tcontinue\n\t\t\ttry:\n\t\t\t\tA.append(a)\n\t\t\t\tB.append(b)\n\t\t\t\t# P.append(p)\n\t\t\t\tL.append(location)\n\t\t\t\tM.append(m)\n\t\t\texcept:\n\t\t\t\tprint('err 4')\n\t\t\t\tcontinue\n\tprint('1')\n\tA = np.array(A).reshape(-1,1)\n\tprint('1')\n\tB = np.array(B).reshape(-1,1)\n\tprint('1')\n\tL = np.array(L).reshape(-1,1)\n\tprint('1')\n\t# P = np.array(P).reshape(-1,1)\n\t# print('1')\n\tA = np.append(A, B, 1)\n\tprint('1')\n\tA = np.append(A, L, 1)\n\tprint('1')\n\t# A = np.append(A, P, 1)\n\t# print('1')\n\tM = np.array(M).reshape(-1,1)\n\tprint('1')\n\tsave_pickle(A, str(YEAR) + '/A_lin_' + str(YEAR) + '.pickle')\n\tsave_pickle(M, str(YEAR) + '/M_lin_' + str(YEAR) + '.pickle')\n\treg = sm.OLS(M,A).fit()\n\tsave_pickle(reg, str(YEAR) + '/linear_model_' + str(YEAR) + '.pickle')\n\t# A = load_pickle(str(YEAR) + '/A_lin_' + str(YEAR) + '.pickle')\n\t# M = load_pickle(str(YEAR) + '/M_lin_' + str(YEAR) + '.pickle')\n\t# reg = sm.OLS(M,A).fit()\n\t# save_pickle(reg, str(YEAR) + '/linear_model_' + str(YEAR) + '.pickle')\n\treturn reg\n\n\ndef predict_game(home, away, hca):\n\t# takes game object, returns float for prob of home team winning\n\t# if boxscore.winner == 'Home':\n\t# \treturn np.array([1.0])\n\t# elif boxscore.winner == 'Away' and game.datetime.date() < datetime.now().date():\n\t# \treturn np.array([0.0])\n\treg = load_pickle(str(YEAR) + '/logistic_model_' + str(YEAR) + '.pickle')\t\n\td = load_pickle('unweighted_rankings_2020.pickle')\n\n\tif home == \"Virginia Military Institute\":\n\t\tteam_name = 'VMI'\n\telse:\n\t\tteam_name = home\n\tif away == 'Virginia Military Institute':\n\t\topponent_name = 'VMI'\n\telse:\n\t\topponent_name = away\n\ttry:\n\t\ta = d[team_name]\n\t\tb = d[opponent_name]\n\t\tpace = (pace_d[team.name] + pace_d[game.opponent_name])/200\n\t\tem = (a-b)*pace + hca\n\texcept:\n\t\treturn None\n\treturn reg.predict(np.array([[a-b, loc]]))\n\ndef predict_game_binary(home, away, hca):\n\treg = load_pickle(str(YEAR) + '/logistic_model_' + str(YEAR) + '.pickle')\t\n\t# d = load_pickle('unweighted_ratings_2020.pickle')\n\td = load_pickle('EMs_2020.pickle')\n\tif home == \"Virginia Military Institute\":\n\t\tteam_name = 'VMI'\n\telse:\n\t\tteam_name = home\n\tif away == 'Virginia Military Institute':\n\t\topponent_name = 'VMI'\n\telse:\n\t\topponent_name = away\n\ttry:\n\t\ta = d[team_name]\n\t\tb = d[opponent_name]\n\t\tpace = (pace_d[team.name] + pace_d[game.opponent_name])/200\n\t\tem = (a-b)*pace + hca\n\texcept:\n\t\treturn None\n\tprob = reg.predict(np.array([em]))\n\tif prob[0] > .5:\n\t\treturn team_name\n\telse:\n\t\treturn opponent_name\n\t\t# return value is the predicted winner\n\n\ndef kaggle_evaluation():\n\tscore = 0\n\tnum_games = 0\n\tgames = Boxscores(datetime(2019, 3, 19), datetime(2019, 4, 8))\n\tfor date in games.games.keys():\n\t\tfor game in games.games[date]:\n\t\t\thome = game['home_name']\n\t\t\taway = game['away_name']\n\t\t\tprint(home + ' vs ' + away)\n\t\t\tprediction = predict_game(home, away)\n\t\t\tprint(home + ': ' + str(prediction))\n\t\t\tif prediction is None:\n\t\t\t\tcontinue\n\t\t\twinner = game['winning_name']\n\t\t\tprint(winner)\n\t\t\tif home == winner:\n\t\t\t\tyi = 1\n\t\t\telse:\n\t\t\t\tyi = 0\n\t\t\tresult = yi * math.log(prediction) + (1 - yi)* math.log(1-prediction)\n\t\t\tscore += result\n\t\t\tprint(result)\n\t\t\tprint('\\n')\n\t\t\tnum_games += 1\n\tscore = score/num_games * -1\n\tprint('*****' + str(score) + '*****')\n\treturn(score)\n\ndef raw_evaluation(simple=True):\n\n\td = load_pickle('EM_diff.pickle')\n\tscore = 0\n\tnum_games = 0\n\tfor team in teams:\n\t\tfor game in team.schedule:\n\t\t\tif game.datetime.date() > datetime.now().date():\n\t\t\t\tbreak\n\t\t\tif team.name == 'Virginia Military Institute':\n\t\t\t\tteam_name = 'VMI'\n\t\t\telse:\n\t\t\t\tteam_name = team.name\n\t\t\tif game.opponent_name == 'Virginia Military Institute':\n\t\t\t\topponent_name = 'VMI'\n\t\t\telse:\n\t\t\t\topponent_name = game.opponent_name\n\t\t\tloc = 1\n\t\t\t# if game.location == 'Away':\n\t\t\t# \thome = opponent_name\n\t\t\t# \taway = team_name\n\t\t\t# else:\n\t\t\t# \thome = team_name\n\t\t\t# \taway = opponent_name\n\t\t\t# \tif game.location == 'Neutral':\n\t\t\t# \t\tloc = 0\n\t\t\ttry:\n\t\t\t\t# home = team_name\n\t\t\t\t# away = opponent_name\n\t\t\t\tif game.location == 'Home':\n\t\t\t\t\thca = HCA_DATA[team_name]\n\t\t\t\telif game.location == 'Away':\n\t\t\t\t\thca = HCA_DATA[opponent_name] * -1\n\t\t\t\telse:\n\t\t\t\t\thca = 0\n\t\t\texcept:\n\t\t\t\tprediction = None\n\t\t\tprint(team_name + ' vs ' + opponent_name)\n\t\t\tif simple is True:\n\t\t\t\ttry:\n\t\t\t\t\tif d[team_name] > d[opponent_name]:\n\t\t\t\t\t\tprediction = team_name\n\t\t\t\t\telse:\n\t\t\t\t\t\tprediction = opponent_name\n\t\t\t\texcept:\n\t\t\t\t\tprediction = None\n\t\t\telif simple is False:\n\t\t\t\ttry:\n\t\t\t\t\tteam_EM = d[team_name]\n\t\t\t\t\topp_EM = d[opponent_name]\n\t\t\t\t\tpace = (pace_d[team.name] + pace_d[game.opponent_name])/200\n\t\t\t\t\texpected_margin = (team_EM - opp_EM) * pace + hca\n\t\t\t\t\tif expected_margin > 0:\n\t\t\t\t\t\tprediction = team_name\n\t\t\t\t\telse:\n\t\t\t\t\t\tprediction = opponent_name\n\t\t\t\texcept:\n\t\t\t\t\tprediction = None\n\t\t\tif prediction is None:\n\t\t\t\t\tcontinue\n\t\t\tprint('Predicted: ' + prediction)\n\t\t\tif game.result == 'Win':\n\t\t\t\twinner = team_name\n\t\t\tif game.result == 'Loss':\n\t\t\t\twinner = opponent_name\n\t\t\tprint('Winner: ' + winner)\n\t\t\tif prediction == winner:\n\t\t\t\tscore += 1\n\t\t\tnum_games += 1\n\t\t\tprint(score)\n\t\t\tprint(num_games)\n\t\t\tprint(score/num_games)\n\t\t\tprint('\\n')\n\n\tprint('************************************************')\n\tprint(score)\n\tprint(num_games)\n\tprint(score/num_games)\n\ndef run_raw_eval():\n\t# logistic_model()\n\traw_evaluation()\n\n\ndef analyze_predictions():\n\tindices = []\n\twith open('analyze_predictions_2020.csv', 'w') as f:\n\t\twriter = csv.writer(f)\n\t\twriter.writerow(['Team', 'Opponent', 'Prediction', 'Winner', 'Evaluation', 'Score'])\n\t\tfor team in teams:\n\t\t\tfor game in team.schedule:\n\t\t\t\ttry:\n\t\t\t\t\tif game.boxscore_index in indices:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t# no repeats\n\t\t\t\t\telse:\n\t\t\t\t\t\tindices.append(game.boxscore_index)\n\t\t\t\texcept:\n\t\t\t\t\tcontinue\n\t\t\t\tif game.datetime.date() > datetime.now().date():\n\t\t\t\t\tbreak\n\t\t\t\tif team.name == 'Virginia Military Institute':\n\t\t\t\t\tteam_name = 'VMI'\n\t\t\t\telse:\n\t\t\t\t\tteam_name = team.name\n\t\t\t\tif game.opponent_name == 'Virginia Military Institute':\n\t\t\t\t\topponent_name = 'VMI'\n\t\t\t\telse:\n\t\t\t\t\topponent_name = game.opponent_name\n\t\t\t\tif team_name not in d1_team_names or opponent_name not in d1_team_names:\n\t\t\t\t\tcontinue\n\t\t\t\tloc = 1\n\t\t\t\tif game.location == 'Away':\n\t\t\t\t\thome = opponent_name\n\t\t\t\t\taway = team_name\n\t\t\t\telse:\n\t\t\t\t\thome = team_name\n\t\t\t\t\taway = opponent_name\n\t\t\t\t\tif game.location == 'Neutral':\n\t\t\t\t\t\tloc = 0\n\t\t\t\tprint(home + ' vs ' + away)\n\t\t\t\tprediction = predict_game(home, away, loc)[0]\n\t\t\t\tif prediction is None:\n\t\t\t\t\tcontinue\n\t\t\t\tif game.result == 'Win':\n\t\t\t\t\twinner = team_name\n\t\t\t\tif game.result == 'Loss':\n\t\t\t\t\twinner = opponent_name\n\t\t\t\tif winner == home:\n\t\t\t\t\tevaluation = 1\n\t\t\t\telse:\n\t\t\t\t\tevaluation = 0\n\t\t\t\tscore = str(game.points_for) + ' - ' + str(game.points_against)\n\t\t\t\tl = [home, away, prediction, winner, evaluation, score]\n\t\t\t\twriter.writerow(l)\n\n\ndef predict_weekly_games():\n\tindices = []\n\tfor team in teams:\n\t\tfor game in team.schedule:\n\t\t\t# try:\n\t\t\t# \tif game.boxscore_index in indices:\n\t\t\t# \t\tcontinue\n\t\t\t# \t\t# no repeats\n\t\t\t# \telse:\n\t\t\t# \t\tindices.append(game.boxscore_index)\n\t\t\t# except:\n\t\t\t# \tcontinue\n\t\t\tif game.datetime.date() < datetime.now().date():\n\t\t\t\tcontinue\n\t\t\tif game.datetime.date() > date(2020, 1, 19):\n\t\t\t\tbreak\n\t\t\tif team.name == 'Virginia Military Institute':\n\t\t\t\tteam_name = 'VMI'\n\t\t\telse:\n\t\t\t\tteam_name = team.name\n\t\t\tif game.opponent_name == 'Virginia Military Institute':\n\t\t\t\topponent_name = 'VMI'\n\t\t\telse:\n\t\t\t\topponent_name = game.opponent_name\n\t\t\tif team_name not in d1_team_names or opponent_name not in d1_team_names:\n\t\t\t\tcontinue\n\t\t\tloc = 1\n\t\t\tif game.location == 'Away':\n\t\t\t\thome = opponent_name\n\t\t\t\taway = team_name\n\t\t\telse:\n\t\t\t\thome = team_name\n\t\t\t\taway = opponent_name\n\t\t\t\tif game.location == 'Neutral':\n\t\t\t\t\tloc = 0\n\t\t\tprint(home + ' vs ' + away)\n\t\t\tprediction = predict_game(home, away, loc)[0]\n\t\t\tif prediction is None:\n\t\t\t\tcontinue\n\t\t\tif prediction > .5:\n\t\t\t\twinner = home\n\t\t\t\tprobability = prediction\n\t\t\telse:\n\t\t\t\twinner = away\n\t\t\t\tprobability = 1-prediction\n\t\t\tprint(winner + ': ' + str(probability*100)[:4] + '%')\n\t\t\tprint('\\n')\n\ndef gen_EM():\n\tlinear_model()\n\td = load_pickle('unweighted_ratings_2020.pickle')\n\tl = []\n\tEMs = {}\n\tfor key in d.keys():\n\t\tl.append(d[key])\n\tavg = sum(l)/len(l)\n\treg = load_pickle(str(YEAR) + '/linear_model_' + str(YEAR) + '.pickle')\n\tfor team in teams:\n\t\tif team.name == \"Virginia Military Institute\":\n\t\t\tteam_name = 'VMI'\n\t\telse:\n\t\t\tteam_name = team.name\n\t\trating = d[team_name]\n\t\tprint(team_name)\n\t\tprint(reg.predict(np.array([rating, avg, 0]))[0]*100)\n\t\tEMs[team_name] = reg.predict(np.array([rating, avg, 0,]))[0]*100\n\tsave_pickle(EMs, 'EMs_2020.pickle')\n\ndef make_predictions(write=False):\n\tpredictions_list = []\n\t# gen_EM()\n\t# invokes linear model\n\tlogistic_model()\n\tlin_model = load_pickle(str(YEAR) + '/linear_model_' + str(YEAR) + '.pickle')\n\tlog_model = load_pickle(str(YEAR) + '/logistic_model_' + str(YEAR) + '.pickle')\n\tEMs = load_pickle('EM_diff.pickle')\n\tfor team in teams:\n\t\tfor game in team.schedule:\n\t\t\tif game.datetime.date() < datetime.now().date():\n\t\t\t\tcontinue\n\t\t\tdate = str(game.datetime.date())\n\t\t\ttime = str(game.datetime.time())\n\t\t\tif team.name == 'Virginia Military Institute':\n\t\t\t\tteam_name = 'VMI'\n\t\t\telse:\n\t\t\t\tteam_name = team.name\n\t\t\tif game.opponent_name == 'Virginia Military Institute':\n\t\t\t\topponent_name = 'VMI'\n\t\t\telse:\n\t\t\t\topponent_name = game.opponent_name\n\t\t\tif team_name not in d1_team_names or opponent_name not in d1_team_names:\n\t\t\t\tcontinue\n\t\t\tteam_EM = EMs[team_name]\n\t\t\topp_EM = EMs[opponent_name]\n\t\t\tif game.location == 'Away':\n\t\t\t\thca = -3.5805265646318376\n\t\t\tif game.location == 'Home':\n\t\t\t\thca = 3.5805265646318376\n\t\t\tif game.location == 'Neutral':\n\t\t\t\thca = 0\n\t\t\tpace = (pace_d[team_name] + pace_d[opponent_name])/200\n\t\t\texpected_margin = (team_EM - opp_EM) * pace + hca\n\t\t\tprobability = float(log_model.predict(np.array([expected_margin])))\n\t\t\tif expected_margin > 0:\n\t\t\t\twinner = team_name\n\t\t\telse:\n\t\t\t\twinner = opponent_name\n\t\t\t\texpected_margin = expected_margin * -1\n\t\t\t\tprobability = 1 - probability\n\t\t\tpredictions_list.append([date, time, team_name, opponent_name, winner, expected_margin, probability])\n\t\t\tprint([date, time, team_name, opponent_name, winner, expected_margin, probability])\n\tsave_pickle(predictions_list, str(YEAR) + '/predictions_list_' + str(YEAR) + '.pickle')\n\tif write is True:\n\t\tfilename = '2020_predictions.csv'\n\t\twith open(filename, 'w') as f:\n\t\t\twriter = csv.writer(f)\n\t\t\twriter.writerow(['Date', 'Time', 'Team 1', 'Team 2', 'Favorite', 'EM', 'Probability'])\n\t\t\tfor game in predictions_list:\n\t\t\t\twriter.writerow(game)\n\t\t\t\tprint(game)\n\ndef adjust_EM():\n\tEMs = load_pickle('EMs_2020.pickle')\n\tadj_EM = {}\n\ttotal = 0\n\tfor team in teams:\n\t\tif True:\n\t\t\tdifference = 0\n\t\t\tgames = 0\n\t\t\tfor game in team.schedule:\n\t\t\t\t# print(team.name + ' vs. ' + game.opponent_name)\n\t\t\t\tif game.opponent_name not in d1_team_names:\n\t\t\t\t\tcontinue\n\t\t\t\tif game.datetime.date() >= datetime.now().date():\n\t\t\t\t\tcontinue\n\t\t\t\tif game.points_for is None or game.points_against is None:\n\t\t\t\t\tcontinue\n\t\t\t\tif team.name == 'Virginia Military Institute':\n\t\t\t\t\tteam_name = 'VMI'\n\t\t\t\telse:\n\t\t\t\t\tteam_name = team.name\n\t\t\t\tif game.opponent_name == 'Virginia Military Institute':\n\t\t\t\t\topp_name = 'VMI'\n\t\t\t\telse:\n\t\t\t\t\topp_name = game.opponent_name\n\t\t\t\tprediction = (EMs[team_name] - EMs[opp_name]) * .7\n\t\t\t\tif game.location == 'Home':\n\t\t\t\t\tprediction += 3.7464416165160928\n\t\t\t\telif game.location == 'Away':\n\t\t\t\t\tprediction -= 3.7464416165160928\n\t\t\t\tmargin = game.points_for - game.points_against\n\t\t\t\t# print('Prediction: ' + str(prediction)[:5])\n\t\t\t\t# print('Margin: ' + str(margin)[:5])\n\t\t\t\tdifference += prediction - margin\n\t\t\t\tgames += 1\n\t\t\t# print('\\n')\n\t\t\t# print(team.name)\n\t\t\t# print(difference/games)\n\t\t\tadj_EM[team.name] = EMs[team.name] - (difference/games)*10/7\n\t\t\ttotal += difference/games\n\tsave_pickle(adj_EM, 'EM_diff.pickle')\n\t# print(total)\n\tfilename = '2020_adj_EM.csv'\n\twith open(filename, 'w') as f:\n\t\twriter = csv.writer(f)\n\t\twriter.writerow(['Team', 'Adjusted EM'])\n\t\tfor team in adj_EM.keys():\n\t\t\twriter.writerow([team, adj_EM[team]])\n\nif __name__ == '__main__':\n\t# for team in teams:\n\t# \tif team.name == 'Kansas':\n\t# \t\tfor game in team.schedule:\n\t# \t\t\tprint(game.boxscore.dataframe)\n\t# create_df()\n\t# adj_EM = load_pickle('EM_diff')\n\t# EMs = load_pickle('EMs_2020.pickle')\n\t# score = 0\n\t# count = 0\n\t# for team in teams:\n\t# \tfor game in team.schedule:\n\t# \t\tif game.location != 'Home':\n\t# \t\t\tcontinue\n\t# \t\tif game.datetime.date() >= datetime.today().date():\n\t# \t\t\tcontinue\n\t# \t\ttry:\n\t# \t\t\ta = EMs[team.name]\n\t# \t\t\tb = EMs[game.opponent_name]\n\t# \t\t\tpace = (pace_d[team.name] + pace_d[game.opponent_name])/200\n\t# \t\t\tprediction = (a - b)*pace\n\t# \t\t\tmargin = game.points_for - game.points_against\n\t# \t\t\tdiff = margin - prediction\n\t# \t\t\tscore += diff\n\t# \t\t\tcount += 1\n\t# \t\t\tprint(score/count)\n\t# \t\texcept:\n\t# \t\t\tcontinue\n\t# raw_evaluation(simple=False)\n\n\n\t# logged_games = load_pickle(str(YEAR) + '/logged_games_' + str(YEAR) + '.pickle')\n\tlogged_games = []\n\tmatrix = update_margins_matrix(logged_games)\n\t# matrix = generate_margins_matrix()\n\t# matrix = load_pickle(str(YEAR) + '/margins_matrix_' + str(YEAR) + '.pickle')\n\tmatrix = shift_matrix(matrix)\n\t\n\tR = find_R(matrix)\n\tR = np.ndarray.flatten(abs(R))*100\n\tR_normalized = normalize_vector(R)\n\tsave_pickle(R_normalized, 'R_normalized_2020.pickle')\n\t# R_normalized = load_pickle('R_normalized_2020.pickle')\n\tranks = [i for i in range(1, len(d1_team_names)+1)[::-1]]\n\tzipped = zip(list(index_teams_d.keys()), R)\n\td = dict(zipped)\n\tsave_pickle(d, 'unweighted_ratings_2020.pickle')\n\n\tzipped = zip(list(index_teams_d.keys()), R)\n\tteam_ratings = sorted(zipped, key = lambda x: x[1])\n\tteam_ranks = dict()\n\tfor n in range(0, len(d1_team_names)):\n\t\tteam_ranks[team_ratings[n][0]] = len(d1_team_names) - n\n\tcounter = 0\n\tfor key in team_ranks.keys():\n\t\tprint(str(team_ranks[key]) + '. ' + key + ': ' + str(team_ratings[counter][1])[:5])\n\t\tcounter += 1\n\tsave_pickle(team_ranks, 'team_ranks_2020.pickle')\n\n\n\tgen_EM()\n\tadjust_EM()\n\twrite_csv(R_normalized, YEAR, 'weighted_rankings', em=True)\n\tmake_predictions(write=True)\n\t# gen_EM()\n\t# run_raw_eval()\n\tnames = ['Gonzaga']\n\td = load_pickle('unweighted_rankings_2020.pickle')\n\tfor team_name in names:\n\t\t# team_name = 'Louisville'\n\t\tprint(team_name)\n\n\t\t\n\t\tcol_num = 0\n\t\tfor column in matrix:\n\t\t\tif R_INDEX_TEAMS_D[col_num] == team_name:\n\t\t\t\tgame_num = 0\n\t\t\t\tfor game in matrix[col_num]:\n\t\t\t\t\tif matrix[col_num][game_num] != 0:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tprint(team_name + ' vs. ' + R_INDEX_TEAMS_D[game_num])\n\t\t\t\t\t\t\tprint(matrix[col_num][game_num]*d[R_INDEX_TEAMS_D[game_num]]*10*index_team_games_played_d[team_name])\n\t\t\t\t\t\t\t# this is the game score\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\tpass\n\t\t\t\t\tgame_num += 1\n\t\t\tcol_num += 1\n\n\t# print('\\n')\n\t# res = load_pickle('unweighted_rankings_2020.pickle')\n\t# d = dict(res)\n\t# matrix = load_pickle(str(YEAR) + '/margins_matrix_' + str(YEAR) + '.pickle')\n\t# matrix = shift_matrix(matrix)\n\t# t10 = ['Maryland', 'Duke', 'Kansas', 'Ohio State', 'Butler', 'San Diego State', 'West Virginia', 'Oregon', 'Temple', 'Penn State']\n\t# for team_name in t10:\n\n\t# \tprint(team_name)\n\t# \tcol_num = 0\n\t# \tfor column in matrix:\n\t# \t\tif R_INDEX_TEAMS_D[col_num] == team_name:\n\t# \t\t\tgame_num = 0\n\t# \t\t\tfor game in matrix[col_num]:\n\t# \t\t\t\tif matrix[col_num][game_num] != 0:\n\t# \t\t\t\t\ttry:\n\t# \t\t\t\t\t\tprint(R_INDEX_TEAMS_D[game_num])\n\t# \t\t\t\t\t\tprint(matrix[col_num][game_num]*d[R_INDEX_TEAMS_D[game_num]]*1000)\n\t# \t\t\t\t\t\t# this is the game score\n\t# \t\t\t\t\texcept:\n\t# \t\t\t\t\t\tpass\n\t# \t\t\t\tgame_num += 1\n\t# \t\tcol_num += 1\n\n\t# \tprint('\\n')\n\n\n","sub_path":"v1/generate_rankings_v1.py","file_name":"generate_rankings_v1.py","file_ext":"py","file_size_in_byte":38660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"516085538","text":"'''\r\nCreated on Oct 9, 2018\r\n@author: Brandon Cao\r\nbcao4\r\nI pledge my honor that I have abided by the Stevens Honor System.\r\nCS115 - Hw 5\r\n'''\r\nimport turtle # Needed for graphics\r\n\r\n# Ignore 'Undefined variable from import' errors in Eclipse.\r\ndef sv_tree(trunk_length, levels):\r\n '''returns a stick figure of a tree'''\r\n if levels==0:\r\n return\r\n else:\r\n turtle.forward(trunk_length)\r\n turtle.left(30)\r\n sv_tree(trunk_length/2, levels-1) \r\n turtle.right(60)\r\n sv_tree(trunk_length/2, levels-1)\r\n turtle.left(30)\r\n turtle.backward(trunk_length)\r\n\r\n# def lucas(n):\r\n# if n==0:\r\n# return 2\r\n# if n==1:\r\n# return 1\r\n# return lucas(n-1) + lucas(n-2)\r\n\r\ndef fast_lucas(n):\r\n '''Returns the nth Lucas number using the memoization technique\r\n shown in class and lab. The Lucas numbers are as follows:\r\n [2, 1, 3, 4, 7, 11, ...]'''\r\n def fast_lucas_helper(n,memo):\r\n if n in memo:\r\n return memo[n]\r\n if n==0:\r\n result = 2\r\n elif n==1:\r\n result = 1\r\n else:\r\n result=fast_lucas_helper(n-1,memo) + fast_lucas_helper(n-2,memo)\r\n memo[n] = result\r\n return result\r\n return fast_lucas_helper(n,{})\r\n\r\n# def change(amount, coins):\r\n# '''returns the least number of coins that makes up that amount of money'''\r\n# if amount==0:\r\n# return 0\r\n# if coins==[] or 0>amount:\r\n# return float('inf')\r\n# use_it= 1 + change(amount-coins[0], coins)\r\n# lose_it= change(amount, coins[1:])\r\n# return min(use_it, lose_it)\r\n\r\ndef fast_change(amount, coins):\r\n '''Takes an amount and a list of coin denominations as input.\r\n Returns the number of coins required to total the given amount.\r\n Use memoization to improve performance.'''\r\n def fast_change_helper(amount, coins, memo):\r\n if (amount,coins) in memo:\r\n return memo[(amount,coins)]\r\n if amount==0:\r\n result = 0\r\n elif coins==() or 0>amount:\r\n result = float('inf')\r\n else:\r\n use_it= 1 + fast_change_helper(amount-coins[0], coins, memo)\r\n lose_it= fast_change_helper(amount, coins[1:], memo)\r\n result= min(use_it, lose_it)\r\n memo[(amount,coins)] = result\r\n return result\r\n # Call the helper. Note we converted the list to a tuple.\r\n return fast_change_helper(amount, tuple(coins), {})\r\n\r\n# If you did this correctly, the results should be nearly instantaneous.\r\nprint(fast_lucas(3)) # 4\r\nprint(fast_lucas(5)) # 11\r\nprint(fast_lucas(9)) # 76\r\nprint(fast_lucas(24)) # 103682\r\nprint(fast_lucas(40)) # 228826127\r\nprint(fast_lucas(50)) # 28143753123\r\n\r\nprint(fast_change(131, [1, 5, 10, 20, 50, 100]))\r\nprint(fast_change(292, [1, 5, 10, 20, 50, 100]))\r\nprint(fast_change(673, [1, 5, 10, 20, 50, 100]))\r\nprint(fast_change(724, [1, 5, 10, 20, 50, 100]))\r\nprint(fast_change(888, [1, 5, 10, 20, 50, 100]))\r\n\r\n# Should take a few seconds to draw a tree.\r\nsv_tree(50,5)\r\nturtle.done()\r\n","sub_path":"Homework/hw5.py","file_name":"hw5.py","file_ext":"py","file_size_in_byte":3067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"6281246","text":"#from google.transit import gtfs_realtime_pb2\r\nfrom classes import gtfs_realtime_pb2\r\nfrom classes import nyct_subway_pb2\r\nimport urllib\r\nimport json\r\nimport ConfigParser\r\n\r\n#read in the config file\r\nconfig = ConfigParser.ConfigParser()\r\nconfig.read('E:/GoogleDrive/DataSciW210/Final/Infrastructure_Capstone/config/capstone_config.ini')\r\nmta_api = config.get('MTA API','api_key')\r\nsubway_url = 'http://datamine.mta.info/mta_esi.php?key=%s&feed_id=1' % mta_api\r\n\r\n\r\ndef get_mta_status_update():\r\n feed = gtfs_realtime_pb2.FeedMessage()\r\n response = urllib.urlopen(subway_url)\r\n feed.ParseFromString(response.read())\r\n status = []\r\n \r\n for entity in feed.entity:\r\n trip = {}\r\n if entity.HasField('vehicle'):\r\n #trip information\r\n if entity.vehicle.HasField('trip'):\r\n trip['trip_id'] = entity.vehicle.trip.trip_id,\r\n trip['start_date'] = entity.vehicle.trip.start_date\r\n trip['route_id'] = entity.vehicle.trip.route_id\r\n #add the vehicle information\r\n vehicle = {}\r\n if entity.vehicle.HasField('current_stop_sequence'):vehicle['current_stop_sequence'] = entity.vehicle.current_stop_sequence\r\n if entity.vehicle.HasField('current_status'):vehicle['current_status'] = entity.vehicle.current_status\r\n if entity.vehicle.HasField('timestamp'):vehicle['timestamp'] = entity.vehicle.timestamp\r\n if entity.vehicle.HasField('stop_id'):vehicle['stop_id'] = entity.vehicle.stop_id\r\n \r\n trip['vehicle'] = vehicle\r\n \r\n if entity.HasField('stop_time_update'):\r\n #if entity.trip_update.HasField('stop_time_update'):\r\n updates = []\r\n #get all stop ETA/ETD updates\r\n for stop in entity.stop_time_update:#.stop_time_update:\r\n #trip update\r\n update = {}\r\n if stop.HasField('stop_id'):update['stop_id'] = stop.stop_id\r\n if stop.HasField('arrival'):update['arrival'] = stop.arrival.time\r\n if stop.HasField('departure'):update['departure'] = stop.departure.time\r\n updates.append(update)\r\n\r\n trip['trip_updates'] = updates\r\n\r\n status.append(trip)\r\n \r\n\r\n with open('status.json','w') as outfile: json.dump(status,outfile)\r\n\r\n","sub_path":"dataAcquisition/mta_status.py","file_name":"mta_status.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"105443257","text":"#!/usr/bin/env python \n# encoding: utf-8 \n \n# @Author: dragonhht \n# @Date: 2018-03-29 22:17:45 \n# @Last Modified by: dragonhht \n# @Last Modified time: 2018-03-29 22:17:45 \n\nimport pygame\nfrom pygame.locals import *\nfrom sys import exit\nfrom Button import *\n\ndef printf(s):\n print('点击' + s)\n\npygame.init()\n\n# 创建窗体\nscreen = pygame.display.set_mode((300, 300), 0, 32)\npygame.display.set_caption('hello')\n\nbtn = Button(screen, 'submit', (10, 20), (90, 40), 18)\n\nwhile True:\n event = pygame.event.wait()\n # 退出\n if event.type == QUIT:\n print('退出...')\n exit()\n\n if event.type == KEYDOWN:\n print('按下键盘: %s' % event.key) \n\n screen.fill((255, 255, 255))\n btn.create()\n btn.mouse_over()\n btn.mouse_click(event, func=lambda: printf('hello'))\n pygame.display.update()\n\n","sub_path":"pygame-study.py","file_name":"pygame-study.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"537741439","text":"import asyncio\nimport functools\n\n\ndef example():\n def callback(arg, *, kwarg='default'):\n print('callback invoked with {} and {}'.format(arg, kwarg))\n\n async def main(loop):\n print('registering callbacks')\n loop.call_soon(callback, 1)\n wrapped = functools.partial(callback, kwarg='not default')\n loop.call_soon(wrapped, 2)\n\n await asyncio.sleep(0.1)\n\n event_loop = asyncio.get_event_loop()\n try:\n print('entering event loop')\n event_loop.run_until_complete(main(event_loop))\n finally:\n print('closing event loop')\n event_loop.close()\n\n\ndef event_handler(loop, stop=False):\n print('Event handler called at {}'.format(loop.time()))\n if stop:\n print('stopping the loop')\n loop.stop()\n\n\nif __name__ == '__main__':\n \"\"\"\n If the timing of the callback does not matter, call_soon() can be used to schedule the call \n for the next iteration of the loop. Any extra positional arguments after the function are passed to \n the callback when it is invoked. To pass keyword arguments to the callback, use partial() from the functools module.\n \"\"\"\n\n loop = asyncio.get_event_loop()\n try:\n current_time = loop.time()\n loop.call_soon(functools.partial(event_handler, loop))\n loop.call_later(1, functools.partial(event_handler, loop))\n loop.call_at(current_time + 10, functools.partial(event_handler, loop, stop=True))\n print('starting event loop')\n\n loop.run_forever()\n finally:\n print('closing event loop')\n loop.close()\n","sub_path":"SELF_LEARNING/async/asyncio_register_call.py","file_name":"asyncio_register_call.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"88762325","text":"#Given a column title as appears in an Excel sheet, return its corresponding column number.\n#Examples:\n#\n#A -> 1\n# \n#B -> 2\n# \n#C -> 3\n# \n# ...\n# \n#Z -> 26\n# \n#AA -> 27\n# \n#AB -> 28 \ndef excel_column_to_number(column):\n val = 0\n val2 = 0\n val3 = 0\n for n in range (0,len(column)):\n if n==0:\n val = ord(column[n]) - 64\n #val2 = val2 + 26**val\n if n==1:\n val = 26*val\n val2 = (ord(column[n]) -64)\n if n==2:\n val = val*26\n val2 = val2*26\n val3 = ord(column[n]) - 64\n return val + val2 + val3\n \nprint(excel_column_to_number(\"BA\"))","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"64661017","text":"\"\"\"\nRun wagl NRT pipeline in Airflow.\n\"\"\"\nimport logging\nfrom datetime import datetime, timedelta\nfrom urllib.parse import urlparse\nimport json\n\nimport yaml\n\nfrom airflow import DAG\n\nfrom airflow.providers.cncf.kubernetes.operators.kubernetes_pod import (\n KubernetesPodOperator,\n)\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.operators.python_operator import PythonOperator, BranchPythonOperator\nfrom airflow.providers.amazon.aws.hooks.sns import AwsSnsHook\nfrom airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook as AwsHook\nfrom airflow.kubernetes.secret import Secret\nfrom airflow.kubernetes.volume import Volume\nfrom airflow.kubernetes.volume_mount import VolumeMount\n\nfrom infra.pools import WAGL_TASK_POOL\nfrom infra.images import WAGL_IMAGE, S3_TO_RDS_IMAGE\nfrom infra.connections import AWS_WAGL_NRT_CONN\n\n_LOG = logging.getLogger()\n\ndefault_args = {\n \"owner\": \"Imam Alam\",\n \"depends_on_past\": False,\n \"start_date\": datetime(2020, 9, 11),\n \"email\": [\"imam.alam@ga.gov.au\"],\n \"email_on_failure\": False,\n \"email_on_retry\": False,\n \"retries\": 0,\n \"retry_delay\": timedelta(minutes=5),\n \"pool\": WAGL_TASK_POOL,\n \"secrets\": [Secret(\"env\", None, \"wagl-nrt-aws-creds\")],\n}\n\nPROCESS_SCENE_QUEUE = \"https://sqs.ap-southeast-2.amazonaws.com/060378307146/dea-sandbox-eks-wagl-s2-nrt-process-scene\"\nDEADLETTER_SCENE_QUEUE = \"https://sqs.ap-southeast-2.amazonaws.com/060378307146/dea-sandbox-eks-wagl-s2-nrt-process-scene-deadletter\"\nPUBLISH_S2_NRT_SNS = (\n \"arn:aws:sns:ap-southeast-2:060378307146:dea-sandbox-eks-wagl-s2-nrt\"\n)\n\nESTIMATED_COMPLETION_TIME = 3 * 60 * 60\n\nSOURCE_BUCKET = \"sentinel-s2-l1c\"\nTRANSFER_BUCKET = \"dea-sandbox-eks-nrt-scene-cache\"\n\nBUCKET_REGION = \"ap-southeast-2\"\nS3_PREFIX = \"s3://dea-public-data/L2/sentinel-2-nrt/S2MSIARD/\"\n\nAWS_CONN_ID = AWS_WAGL_NRT_CONN\n\nNUM_PARALLEL_PIPELINE = 5\nMAX_ACTIVE_RUNS = 12\n\n# this should be 10 in dev for 10% capacity\n# then it would just discard the other 9 messages polled\nNUM_MESSAGES_TO_POLL = 1\n\nAWS_CONN_ID = AWS_WAGL_NRT_CONN\n\naffinity = {\n \"nodeAffinity\": {\n \"requiredDuringSchedulingIgnoredDuringExecution\": {\n \"nodeSelectorTerms\": [\n {\n \"matchExpressions\": [\n {\n \"key\": \"nodegroup\",\n \"operator\": \"In\",\n \"values\": [\n \"memory-optimised-wagl-s2-nrt-r5-l\",\n ],\n }\n ]\n }\n ]\n }\n }\n}\n\ntolerations = [\n {\"key\": \"dedicated\", \"operator\": \"Equal\", \"value\": \"wagl\", \"effect\": \"NoSchedule\"}\n]\n\n\nancillary_volume_mount = VolumeMount(\n name=\"wagl-nrt-ancillary-volume\",\n mount_path=\"/ancillary\",\n sub_path=None,\n read_only=False,\n)\n\n\nancillary_volume = Volume(\n name=\"wagl-nrt-ancillary-volume\",\n configs={\"persistentVolumeClaim\": {\"claimName\": \"wagl-nrt-ancillary-volume\"}},\n)\n\n\ndef setup_logging():\n \"\"\" \"\"\"\n _LOG.setLevel(logging.INFO)\n handler = logging.StreamHandler()\n handler.setLevel(logging.INFO)\n\n formatter = logging.Formatter(\n \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n )\n handler.setFormatter(formatter)\n\n _LOG.addHandler(handler)\n\n\nsetup_logging()\n\n\ndef decode(message):\n \"\"\"Decode stringified message.\"\"\"\n return json.loads(message[\"Body\"])\n\n\ndef copy_cmd_tile(tile_info):\n \"\"\"The bash scipt to run to copy the tile over to the cache bucket.\"\"\"\n datastrip = tile_info[\"datastrip\"]\n path = tile_info[\"path\"]\n granule_id = tile_info[\"granule_id\"]\n\n cmd = f\"\"\"\n set -e\n\n if ! aws s3api head-object --bucket {TRANSFER_BUCKET} --key {datastrip}/.done 2> /dev/null; then\n mkdir -p /transfer/{granule_id}\n echo sinergise -> disk [datastrip]\n aws s3 sync --only-show-errors --request-payer requester \\\\\n s3://{SOURCE_BUCKET}/{datastrip} /transfer/{granule_id}/{datastrip}\n echo disk -> cache [datastrip]\n aws s3 sync --only-show-errors \\\\\n /transfer/{granule_id}/{datastrip} s3://{TRANSFER_BUCKET}/{datastrip}\n touch /transfer/{granule_id}/{datastrip}/.done\n aws s3 cp \\\\\n /transfer/{granule_id}/{datastrip}/.done s3://{TRANSFER_BUCKET}/{datastrip}/.done\n else\n echo s3://{TRANSFER_BUCKET}/{datastrip} already exists\n fi\n\n if ! aws s3api head-object --bucket {TRANSFER_BUCKET} --key {path}/.done 2> /dev/null; then\n mkdir -p /transfer/{granule_id}\n echo sinergise -> disk [path]\n aws s3 sync --only-show-errors --request-payer requester \\\\\n s3://{SOURCE_BUCKET}/{path} /transfer/{granule_id}/{path}\n echo disk -> cache [path]\n aws s3 sync --only-show-errors \\\\\n /transfer/{granule_id}/{path} s3://{TRANSFER_BUCKET}/{path}\n touch /transfer/{granule_id}/{path}/.done\n aws s3 cp \\\\\n /transfer/{granule_id}/{path}/.done s3://{TRANSFER_BUCKET}/{path}/.done\n else\n echo s3://{TRANSFER_BUCKET}/{path} already exists\n fi\n\n rm -rf /transfer/{granule_id}\n \"\"\"\n\n return cmd\n\n\ndef get_tile_info(msg_dict):\n \"\"\"Minimal info to be able to run wagl.\"\"\"\n assert len(msg_dict[\"tiles\"]) == 1, \"was not expecting multi-tile granule\"\n tile = msg_dict[\"tiles\"][0]\n\n return dict(\n granule_id=msg_dict[\"id\"],\n path=tile[\"path\"],\n datastrip=tile[\"datastrip\"][\"path\"],\n )\n\n\ndef tile_args(tile_info):\n \"\"\"Arguments to the wagl container.\"\"\"\n path = tile_info[\"path\"]\n datastrip = tile_info[\"datastrip\"]\n\n return dict(\n granule_id=tile_info[\"granule_id\"],\n granule_url=f\"s3://{TRANSFER_BUCKET}/{path}\",\n datastrip_url=f\"s3://{TRANSFER_BUCKET}/{datastrip}\",\n )\n\n\ndef get_sqs():\n \"\"\"SQS client.\"\"\"\n return (\n AwsHook(aws_conn_id=AWS_CONN_ID, client_type=\"sqs\").get_session().client(\"sqs\")\n )\n\n\ndef get_s3():\n \"\"\"S3 client.\"\"\"\n return AwsHook(aws_conn_id=AWS_CONN_ID, client_type=\"s3\").get_session().client(\"s3\")\n\n\ndef get_message(sqs, url):\n \"\"\"Receive one message with an estimated completion time set.\"\"\"\n response = sqs.receive_message(\n QueueUrl=url, VisibilityTimeout=ESTIMATED_COMPLETION_TIME, MaxNumberOfMessages=1\n )\n\n if \"Messages\" not in response:\n return None\n\n messages = response[\"Messages\"]\n\n if len(messages) == 0:\n return None\n else:\n return messages[0]\n\n\ndef receive_task(**context):\n \"\"\"Receive a task from the task queue.\"\"\"\n task_instance = context[\"task_instance\"]\n index = context[\"index\"]\n\n sqs = get_sqs()\n message = get_message(sqs, PROCESS_SCENE_QUEUE)\n\n if message is None:\n _LOG.info(\"no messages\")\n return f\"nothing_to_do_{index}\"\n else:\n _LOG.info(\"received message\")\n _LOG.info(\"%r\", message)\n\n task_instance.xcom_push(key=\"message\", value=message)\n\n msg_dict = decode(message)\n tile_info = get_tile_info(msg_dict)\n\n task_instance.xcom_push(key=\"cmd\", value=copy_cmd_tile(tile_info))\n task_instance.xcom_push(key=\"args\", value=tile_args(tile_info))\n\n return f\"dea-s2-wagl-nrt-copy-scene-{index}\"\n\n\ndef finish_up(**context):\n \"\"\"Delete the SQS message to mark completion, broadcast to SNS.\"\"\"\n task_instance = context[\"task_instance\"]\n index = context[\"index\"]\n\n message = task_instance.xcom_pull(task_ids=f\"receive_task_{index}\", key=\"message\")\n sqs = get_sqs()\n\n _LOG.info(\"deleting %s\", message[\"ReceiptHandle\"])\n sqs.delete_message(\n QueueUrl=PROCESS_SCENE_QUEUE, ReceiptHandle=message[\"ReceiptHandle\"]\n )\n\n msg = task_instance.xcom_pull(\n task_ids=f\"dea-s2-wagl-nrt-{index}\", key=\"return_value\"\n )\n\n if msg == {}:\n _LOG.info(\"dataset already existed, did not get processed by this DAG\")\n return\n\n dataset_location = msg[\"dataset\"]\n parsed = urlparse(dataset_location)\n _LOG.info(\"dataset location: %s\", dataset_location)\n\n s3 = get_s3()\n response = s3.get_object(Bucket=parsed.netloc, Key=parsed.path.lstrip(\"/\"))\n body = json.dumps(yaml.safe_load(response[\"Body\"]), indent=2)\n\n _LOG.info(\"publishing to SNS: %s\", body)\n sns_hook = AwsSnsHook(aws_conn_id=AWS_CONN_ID)\n sns_hook.publish_to_target(PUBLISH_S2_NRT_SNS, body)\n\n\npipeline = DAG(\n \"k8s_ard_nrt_sentinel2\",\n doc_md=__doc__,\n default_args=default_args,\n description=\"DEA Sentinel-2 NRT processing\",\n concurrency=MAX_ACTIVE_RUNS * NUM_PARALLEL_PIPELINE,\n max_active_runs=MAX_ACTIVE_RUNS,\n catchup=False,\n params={},\n schedule_interval=timedelta(minutes=5),\n tags=[\"k8s\", \"dea\", \"psc\", \"ard\", \"sentinel-2\", \"wagl\", \"nrt\"],\n)\n\nwith pipeline:\n for index in range(NUM_PARALLEL_PIPELINE):\n SENSOR = BranchPythonOperator(\n task_id=f\"receive_task_{index}\",\n python_callable=receive_task,\n op_kwargs={\"index\": index},\n provide_context=True,\n )\n\n COPY = KubernetesPodOperator(\n namespace=\"processing\",\n name=\"dea-s2-wagl-nrt-copy-scene\",\n task_id=f\"dea-s2-wagl-nrt-copy-scene-{index}\",\n image_pull_policy=\"IfNotPresent\",\n image=S3_TO_RDS_IMAGE,\n affinity=affinity,\n tolerations=tolerations,\n startup_timeout_seconds=600,\n volumes=[ancillary_volume],\n volume_mounts=[ancillary_volume_mount],\n cmds=[\n \"bash\",\n \"-c\",\n \"{{ task_instance.xcom_pull(task_ids='receive_task_\"\n + str(index)\n + \"', key='cmd') }}\",\n ],\n labels={\n \"runner\": \"airflow\",\n \"product\": \"Sentinel-2\",\n \"app\": \"nrt\",\n \"stage\": \"copy-scene\",\n },\n resources={\n \"request_cpu\": \"1000m\",\n \"request_memory\": \"2Gi\",\n },\n get_logs=True,\n is_delete_operator_pod=True,\n )\n\n RUN = KubernetesPodOperator(\n namespace=\"processing\",\n name=\"dea-s2-wagl-nrt\",\n task_id=f\"dea-s2-wagl-nrt-{index}\",\n image_pull_policy=\"IfNotPresent\",\n image=WAGL_IMAGE,\n affinity=affinity,\n tolerations=tolerations,\n startup_timeout_seconds=600,\n # this is the wagl_nrt user in the wagl container\n security_context=dict(runAsUser=10015, runAsGroup=10015, fsGroup=10015),\n cmds=[\"/scripts/process-scene.sh\"],\n arguments=[\n \"{{ task_instance.xcom_pull(task_ids='receive_task_\"\n + str(index)\n + \"', key='args')['granule_url'] }}\",\n \"{{ task_instance.xcom_pull(task_ids='receive_task_\"\n + str(index)\n + \"', key='args')['datastrip_url'] }}\",\n \"{{ task_instance.xcom_pull(task_ids='receive_task_\"\n + str(index)\n + \"', key='args')['granule_id'] }}\",\n BUCKET_REGION,\n S3_PREFIX,\n ],\n labels={\n \"runner\": \"airflow\",\n \"product\": \"Sentinel-2\",\n \"app\": \"nrt\",\n \"stage\": \"wagl\",\n },\n env_vars=dict(\n bucket_region=BUCKET_REGION,\n datastrip_url=\"{{ task_instance.xcom_pull(task_ids='receive_task_\"\n + str(index)\n + \"', key='args')['datastrip_url'] }}\",\n granule_url=\"{{ task_instance.xcom_pull(task_ids='receive_task_\"\n + str(index)\n + \"', key='args')['granule_url'] }}\",\n granule_id=\"{{ task_instance.xcom_pull(task_ids='receive_task_\"\n + str(index)\n + \"', key='args')['granule_id'] }}\",\n s3_prefix=S3_PREFIX,\n ),\n get_logs=True,\n resources={\n \"request_cpu\": \"1000m\",\n \"request_memory\": \"12Gi\",\n },\n volumes=[ancillary_volume],\n volume_mounts=[ancillary_volume_mount],\n execution_timeout=timedelta(minutes=180),\n do_xcom_push=True,\n is_delete_operator_pod=True,\n )\n\n FINISH = PythonOperator(\n task_id=f\"finish_{index}\",\n python_callable=finish_up,\n op_kwargs={\"index\": index},\n provide_context=True,\n )\n\n NOTHING = DummyOperator(task_id=f\"nothing_to_do_{index}\")\n\n SENSOR >> COPY >> RUN >> FINISH\n SENSOR >> NOTHING\n","sub_path":"dags/ard/k8s_ard_nrt_sentinel2.py","file_name":"k8s_ard_nrt_sentinel2.py","file_ext":"py","file_size_in_byte":12713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"188287837","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport argparse\nimport os\nimport sys\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\ncudnn.benchmark = True\ncudnn.fastest = True\nimport torch.optim as optim\nimport torchvision.utils as vutils\nfrom torch.autograd import Variable\n\nfrom misc import *\nimport models.DenseUnet as net\nimport itertools\nfrom myutils.vgg16 import Vgg16\nfrom myutils import utils\n\n#test record\n#errGan_A+errLp_A+errc_A_P train512 repair Densely layers 4 cgan (freehaze)81.7%\n#errGan_A+errLp_A+errc_A_P+errc_A_F train512 repair Densely layers 4 cgan (freehaze)82.8%\n#errGan_A+errLp_A+errc_A_P+errc_A_F train512 repair Densely layers 6 cgan (freehaze)83.9% 84.3%\n#errGan_A+errLp_A+errc_A_P+errc_A_F train512 repair Densely layers 9 cgan (free,haze)84.4% \n#errGan_A+errLp_A+errc_A_P+errc_A_F train512 repair Densely layers 9 gan (free,haze)85% \n#errGan_A+errLp_A+errc_A_P+errc_A_F train512 repair Densely layers 9 gan truncation(free,haze)86.3% \n#errLp_A+errc_A_P+errc_A_F train512 repair Densely layers 9 83.8%\n#errGan_A+errLp_A+errc_A_P+errc_A_F train256 repair Densely layers 9 5 88% \n#errGan_A+errLp_A+errc_A_P+errc_A_F train256 repair Densely layers 9 2 92.1% \n#errLp_A+errc_A_P+errc_A_F train256 repair Densely layers 9 90.2% \n#no free 0.85\n#no D 0.89\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataset', required=False,\n default='haze', help='')\nparser.add_argument('--dataroot', required=False,\n default='./facades/train256_new', help='path to trn dataset')\nparser.add_argument('--datarootfree', required=False,\n default='./D_HAZE/NYU_GT/', help='path to trn dataset')\nparser.add_argument('--valDataroot', required=False,\n default='./facades/test256_new', help='path to val dataset')\nparser.add_argument('--mode', type=str, default='B2A', help='B2A: facade, A2B: edges2shoes')\nparser.add_argument('--batchSize', type=int, default=4, help='input batch size')\nparser.add_argument('--valBatchSize', type=int, default=1, help='input batch size')\nparser.add_argument('--originalSize', type=int,\n default=286, help='the height / width of the original input image')\nparser.add_argument('--imageSize', type=int,\n default=256, help='the height / width of the cropped input image to network')\nparser.add_argument('--condition_GAN', type=int,\n default=1, help='set to 0 to use unconditional discriminator')\nparser.add_argument('--inputChannelSize', type=int,\n default=3, help='size of the input channels')\nparser.add_argument('--outputChannelSize', type=int,\n default=3, help='size of the output channels')\nparser.add_argument('--ngf', type=int, default=64)\nparser.add_argument('--ndf', type=int, default=48)\nparser.add_argument('--niter', type=int, default=80, help='number of epochs to train for')\nparser.add_argument('--lrD', type=float, default=0.0002, help='learning rate, default=0.0002')\nparser.add_argument('--lrG', type=float, default=0.0002, help='learning rate, default=0.0002')\nparser.add_argument('--annealStart', type=int, default=0, help='annealing learning rate start to')\nparser.add_argument('--annealEvery', type=int, default=40, help='epoch to reaching at learning rate of 0')\nparser.add_argument('--lamdaA', type=float, default=0.0066, help='lambdaGAN')\nparser.add_argument('--lamdaP', type=float, default=1, help='lambdaIMG')\nparser.add_argument('--poolSize', type=int, default=50, help='Buffer size for storing previously generated samples from G')\nparser.add_argument('--wd', type=float, default=0.0000, help='weight decay in D')\nparser.add_argument('--beta1', type=float, default=0.5, help='beta1 for adam')\nparser.add_argument('--netG', default='', help=\"path to netG (to continue training)\")\nparser.add_argument('--netD', default='', help=\"path to netD (to continue training)\")\nparser.add_argument('--workers', type=int, help='number of data loading workers', default=1)\nparser.add_argument('--exp', default='sample_pair_256_free_0.1maxG', help='folder to output images and model checkpoints')\nparser.add_argument('--display', type=int, default=5, help='interval for displaying train-logs')\nparser.add_argument('--evalIter', type=int, default=50, help='interval for evauating(generating) images from valDataroot')\nopt = parser.parse_args()\nprint(opt)\n\ncreate_exp_dir(opt.exp)\nopt.manualSeed = random.randint(1, 10000)\n# opt.manualSeed = 101\nrandom.seed(opt.manualSeed)\ntorch.manual_seed(opt.manualSeed)\ntorch.cuda.manual_seed_all(opt.manualSeed)\nprint(\"Random Seed: \", opt.manualSeed)\nopt.workers=1\n\n\n# get dataloader\ndataloaderhaze = getLoader(opt.dataset,\n opt.dataroot,\n opt.originalSize,\n opt.imageSize,\n opt.batchSize,\n opt.workers,\n mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5),\n split='train',\n shuffle=False,\n seed=opt.manualSeed)\nopt.dataset='gt'\n#dataloaderfree = getLoader(opt.dataset,\n# opt.datarootfree,\n# opt.originalSize,\n# opt.imageSize,\n# opt.batchSize,\n# opt.workers,\n# mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5),\n# split='train',\n# shuffle=False,\n# seed=opt.manualSeed)\n#valDataloader = getLoader(opt.dataset,\n# opt.valDataroot,\n# opt.imageSize, #opt.originalSize,\n# opt.imageSize,\n# opt.valBatchSize,\n# opt.workers,\n# mean=(0, 0, 0), std=(1, 1, 1),\n# split='train',\n# shuffle=False,\n# seed=opt.manualSeed)\n# get logger\ntrainLogger = open('%s/train.log' % opt.exp, 'w')\n#train_list=glob.glob(opt.dataroot+'/*.jpg')\n#print(len(train_list))\n#取得重要参数\nreal_label = 1\nfake_label = 0\nngf = opt.ngf\nndf = opt.ndf\ninputChannelSize = opt.inputChannelSize\noutputChannelSize= opt.outputChannelSize\nidx_A = {inputChannelSize+1, inputChannelSize+outputChannelSize}\nidx_B = {1, inputChannelSize}\n\n#建立生成网络netG和判别网络netD\n\nnetG = net.G()\n#netG_B = net.G(inputChannelSize, outputChannelSize)\ninit_weights(netG)\n#netG_B.apply(weights_init)\n#if opt.netG != '':\n# netG.load_state_dict(torch.load(opt.netG))\nprint(netG)\n#print(netG_B)\n\n#netD_B = net.D(inputChannelSize,outputChannelSize, ndf,3)\n#netD_A = net.D2(inputChannelSize, ndf)\nnetD_A = net.D(inputChannelSize,outputChannelSize, ndf,3)\nnetD_A.apply(weights_init)\n#netD_B.apply(weights_init)\nif opt.netD != '':\n netD_A.load_state_dict(torch.load(opt.netD_A))\nprint(netD_A)\n\n#netG.train()\n#netD.train()\n\n\n#设置损失函数loss function\n\ncriterionBCE = nn.BCELoss()\ncriterionMSE = nn.MSELoss()\ncriterionCycle = nn.L1Loss()\n#留出空间\n#haze_train = torch.Tensor(opt.batchSize, inputChannelSize, opt.imageSize, opt.imageSize)\n#free_train = torch.Tensor(opt.batchSize, inputChannelSize, opt.imageSize, opt.imageSize)\n\nerrD, errG, errL1 = 0, 0, 0\n\n#haze_train = haze_train.cuda()\n#free_train = free_train.cuda()\nnetD_A.cuda()\n#netD_B.cuda()\nnetG.cuda()\ncriterionBCE.cuda()\ncriterionMSE.cuda()\ncriterionCycle.cuda()\nprint('done')\n\nlamdaA = opt.lamdaA\nlamdaP = opt.lamdaP\n\n# Initialize VGG-16\nvgg = Vgg16()\nutils.init_vgg16('./models/')\nvgg.load_state_dict(torch.load(os.path.join('./models/', \"vgg16.weight\")))\nvgg.cuda()\n\n\n\n# pdb.set_trace()\n''' set optimizer'''\n#optimizerD = optim.Adam(itertools.chain(netD_A.parameters(),netD_B.parameters()), lr = opt.lrD, betas = (opt.beta1, 0.999))\noptimizerD = optim.Adam(netD_A.parameters(), lr = opt.lrD, betas = (opt.beta1, 0.999))\noptimizerG = optim.Adam(netG.parameters(), lr = opt.lrG, betas = (opt.beta1, 0.999))\n\n\n'''test data'''\n#val_target = torch.FloatTensor(opt.valBatchSize, outputChannelSize, opt.imageSize, opt.imageSize)\n#val_input = torch.FloatTensor(opt.valBatchSize, inputChannelSize, opt.imageSize, opt.imageSize)\n#val_target, val_input = val_target.cuda(), val_input.cuda()\n#val_iter = iter(valDataloader)\n#data_val = val_iter.next()\n#m,val_input_cpu= data_val\n#val_input_cpu= val_input_cpu.float().cuda()\n#val_input.resize_as_(val_input_cpu).copy_(val_input_cpu)\n\n#def set_requires_grad(self, netts, requires_grad=False):\n# if not isinstance(netts, list):\n# netts = [netts]\n# for nett in netts:\n# if nett is not None:\n# for param in nett.parameters():\n# param.requires_grad = requires_grad\n# NOTE training loop\nganIterations = 0\n\nfor epoch in range(opt.niter):\n# if epoch > opt.annealStart:\n# adjust_learning_rate(optimizerD, opt.lrD, epoch, None, opt.annealEvery)\n# adjust_learning_rate(optimizerG, opt.lrG, epoch, None, opt.annealEvery)\n i=0\n for data_hazy,data_free in dataloaderhaze: \n #get img\n i+=1\n netG.train()\n# netG_B.train()\n# features_content_B = vgg(free_train)\n haze_train = data_hazy\n# print(haze_train)\n free_train = data_free\n# free_train = iter(dataloaderfree).next()\n haze_train,free_train = haze_train.float().cuda(), free_train.float().cuda()\n \n fake_free = netG(haze_train)\n# rec_haze = netG_B(fake_free)\n# fake_haze = netG_B(free_train)\n# rec_free = netG_A(fake_haze)\n generate_imgf_A=netG(free_train).detach()\n# generate_imgf_B=netG_B(haze_train) \n# fake_free,rec_haze,fake_haze,rec_free = fake_free.cuda(),rec_haze.cuda(),fake_haze.cuda(),rec_free.cuda()\n '''netG'''\n for p in netD_A.parameters():\n p.requires_grad = False\n# for p in netD_B.parameters():\n# p.requires_grad = False\n optimizerG.zero_grad() \n '''G_A GAN loss'''\n output_A = netD_A(fake_free) \n# output_A = netD_A(torch.cat([fake_free, generate_imgf_A], dim=1))\n label_A = torch.FloatTensor(output_A.size()).fill_(real_label).cuda()\n errGan_A_1 = criterionBCE(output_A, label_A)\n# output_B = netD_B(fake_free)\n# label_B = torch.FloatTensor(output_B.size()).fill_(free_label).cuda()\n# errGan_B_1 = criterionBCE(output_B, label_B) \n# output_A_2 = netD(generate_imgf_A)\n# label_A_2 = torch.FloatTensor(output_A_2.size()).fill_(free_label).cuda()\n# errGan_A_2 = criterionMSE(output_A_2, label_A_2)\n# output_A_3 = netD(rec_free)\n# label_A_3 = torch.FloatTensor(output_A_3.size()).fill_(free_label).cuda()\n# errGan_A_3 = criterionMSE(output_A_3, label_A_3)\n errGan_A = errGan_A_1# + 0.01*errGan_B_1\n# errGan_A = errGan_A_1\n '''G_B GAN loss'''\n# output_B = netD(fake_haze)\n# label_B = torch.FloatTensor(output_B.size()).fill_(haze_label).cuda()\n# errGan_B_1 = criterionMSE(output_B, label_B) \n# output_B_2 = netD(generate_imgf_B)\n# label_B_2 = torch.FloatTensor(output_B_2.size()).fill_(haze_label).cuda()\n# errGan_B_2 = criterionMSE(output_B_2, label_B_2)\n# output_B_3 = netD(rec_haze)\n# label_B_3 = torch.FloatTensor(output_B_3.size()).fill_(haze_label).cuda()\n# errGan_B_3 = criterionMSE(output_B_3, label_B_3) \n# errGan_B = errGan_B_1+errGan_B_2+errGan_B_3\n# '''G_A G_B cycle loss'''\n# err_cycle_A = criterionCycle(rec_haze,haze_train)\n# err_cycle_B = criterionCycle(rec_free,free_train)\n '''G_A G_B perceptual loss'''\n \n features_content_A = vgg(free_train)\n f_A = Variable(features_content_A[1].data, requires_grad=False)\n features_A = vgg(fake_free)\n errLp_A = criterionMSE(features_A[1], f_A)\n \n errc_A_F = criterionCycle(generate_imgf_A, free_train)\n# errc_A_F=errLp_A\n errc_A_P = criterionCycle(fake_free, free_train)\n# x=errGan_A.clone().item()\n# y1=errc_A_F.clone().item()\n# y2=errc_A_P.clone().item()\n# y3=errLp_A.clone().item()\n# r=x//(y1+y2+y3)\n# if errGan_A - 1.5*(errLp_A+errc_A_P+errc_A_F)>0:\n# errG = 0.1 * errGan_A + errLp_A+errc_A_P+errc_A_F\n# else:\n# errG = errGan_A+ errLp_A+errc_A_P+errc_A_F\n# if epoch>50 and errGan_A - (errLp_A+errc_A_P+errc_A_F)>0:\n# errG = 0.1 * errGan_A+ errLp_A+errc_A_P+errc_A_F\n# else:\n# errG = errGan_A+ errLp_A+errc_A_P+errc_A_F \n errG = errLp_A+0.1*errc_A_P+ errGan_A+errc_A_F\n# errG = errGan_A + errGan_B +err_cycle_A+ err_cycle_B + 0.0003*errLp_A+0.0003*errLp_B+errc_A+ errc_B\n# errG_A.backward(retain_graph=True)\n errG.backward()\n# print('vgg grad')\n# for p in vgg.parameters():\n# print(p.data)\n optimizerG.step()\n# print('vgg grad')\n# for p in vgg.parameters():\n# print(p.data)\n '''netD'''\n for p in netD_A.parameters():\n p.requires_grad = True\n# for p in netD_B.parameters():\n# p.requires_grad = True\n optimizerD.zero_grad() \n '''netD_A'''\n output_A_1 = netD_A(free_train)\n# output_A_1 = netD_A(torch.cat([free_train, free_train], dim=1))\n label_A_1 = torch.FloatTensor(output_A_1.size()).fill_(real_label).cuda()\n errD_A_real = criterionBCE(output_A_1,label_A_1) \n fake_free = netG(haze_train).detach()\n# generate_imgf_A=netG(free_train).detach() \n output_A_2 = netD_A(fake_free) \n# output_A_2 = netD_A(torch.cat([fake_free, generate_imgf_A], dim=1))\n label_A_2 = torch.FloatTensor(output_A_2.size()).fill_(fake_label).cuda()\n errD_A_fake = criterionBCE(output_A_2,label_A_2)\n## generate_imgf_A=netG(free_train)\n# output_A_3 = netD_A(fake_free)\n# output_B_1 = netD_B(fake_free).detach()\n## label3 = torch.FloatTensor(output_3.size()).fill_(haze_label).cuda()\n# errD_AB = criterionMSE(output_A_3,output_B_1) \n# generate_imgf_B=netG_B(haze_train)\n# output_4 = netD(generate_imgf_B)\n# label3_B = torch.FloatTensor(output_4.size()).fill_(free_label).cuda()\n# errD_F_B = criterionMSE(output_4,label3_B) \n# errD_A = errD_A_real + errD_A_fake\n errD_A = errD_A_real + errD_A_fake\n '''netD_B'''\n# output_B_1 = netD_B(haze_train)\n# label_B_1 = torch.FloatTensor(output_B_1.size()).fill_(haze_label).cuda()\n# errD_B_real = criterionMSE(output_B_1,label_B_1) \n## \n# output_B_3 = netD_B(free_train)\n# label_B_3 = torch.FloatTensor(output_B_3.size()).fill_(free_label).cuda()\n# errD_B_free = criterionMSE(output_B_3,label_B_3) \n# \n# errD_B = errD_B_real + errD_B_free \n# errD=errD_A+errD_B\n errD=errD_A\n errD_A.backward()\n# errD_B.backward()\n \n# print('netD grad')\n# for p in netG_A.parameters():\n# print(p.grad)\n# for p in netG_A.parameters():\n# print('netG parameters before')\n# print(p)\n# break\n optimizerD.step()\n# for p in netG_A.parameters():\n# print('netG parameters after')\n# print(p)\n# break\n ganIterations += 1\n# vutils.save_image(haze_train, '1.png', normalize=False, scale_each=False)\n# vutils.save_image(free_train, '2.png', normalize=False, scale_each=False) \n if ganIterations % opt.display == 0:\n print('[%d/%d][%d/%d]\\\n errGan_A: %f errc_A_F: %f errc_A_P: %f errLp_A: %f \\\n errD_A_real: %f errD_A_fake: %f\\\n errG: %f errD_A: %f'\n % (epoch, opt.niter, i, len(dataloaderhaze),\n errGan_A.data[0],errc_A_F.data[0],errc_A_P.data[0], errLp_A.data[0], \n errD_A_real.data[0], errD_A_fake.data[0],\n errG.data[0],errD_A.data[0]))\n sys.stdout.flush()\n trainLogger.write('%d\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n' % \\\n (i, \n errGan_A.data[0],errc_A_F.data[0],errc_A_P.data[0], errLp_A.data[0], \n errD_A_real.data[0], errD_A_fake.data[0],\n errG.data[0],errD_A.data[0]))\n trainLogger.flush()\n \n if epoch % 2 == 0: \n torch.save(netG.state_dict(), '%s/netG_newepoch_%d.pth' % (opt.exp, epoch))\n# torch.save(netD.state_dict(), '%s/netDepoch_%d.pth' % (opt.exp, epoch))\n# if ganIterations % opt.evalIter == 0: \n# val_batch_output = torch.FloatTensor(val_input.size()).fill_(0)\n# for idx in range(val_input.size(0)):\n# single_img = val_input[idx,:,:,:].unsqueeze(0)\n# val_inputv = Variable(single_img, volatile=True)\n# netG.eval()\n# dehaze21 = netG(val_inputv)\n# dehaze22 = dehaze21.clone()\n# dehaze22[:,0,:,:] = dehaze21[:,2,:,:]\n# dehaze22[:,1,:,:] = dehaze21[:,1,:,:]\n# dehaze22[:,2,:,:] = dehaze21[:,0,:,:]\n# val_batch_output[idx,:,:,:].copy_(dehaze22[0,:,:,:])\n# del dehaze21\n# del single_img\n# del val_inputv\n# vutils.save_image(val_batch_output, '%s/generated_epoch_%08d_iter%08d.png' % \\\n# (opt.exp, epoch, ganIterations), normalize=False, scale_each=False) \n# del val_batch_output\n\n \ntrainLogger.close()\n","sub_path":"newcycle.py","file_name":"newcycle.py","file_ext":"py","file_size_in_byte":17677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"128621260","text":"#26.10.2018\r\ndef mult_items_in_dict(given_dict, MODE):\r\n returnMultiply = 1\r\n if MODE == \"keys\":\r\n for element in given_dict.keys():\r\n if type(element) == float or type(element) == int:\r\n returnMultiply *= element\r\n else:\r\n continue\r\n elif MODE == \"values\":\r\n for element in given_dict.values():\r\n if type(element) == float or type(element) == int:\r\n returnMultiply *= element\r\n else:\r\n continue\r\n elif MODE == \"items\":\r\n for element in given_dict.items():\r\n for secondary_element in element:\r\n if type(secondary_element) == float or type(secondary_element) == int:\r\n returnMultiply *= secondary_element\r\n\r\n return returnMultiply\r\n\r\nprint(mult_items_in_dict({2: 4, 3:6}, \"values\"))\r\n \r\n","sub_path":"Dictionary/Problem_11.py","file_name":"Problem_11.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"29418418","text":"# -*- coding: utf-8 -*-\n#Projeto Super\n#Task: WP3-CETELI-2-IA\n#Curso: Programação Python\n#Bolsista 1: Alex Rocha\n#Bolsista 2: Diego Vieira\n#Bolsista 3: Thayla Moura\n\nimport random\n\ndef criarBase(nome):\n #essa lista define as palavras do jogo\n palavras = \"banana acerola caju laranja verde vermelho azul rosa carro moto barco casa cidade aula viajem pai comida aviao gato pizza escola\"\n #esse bloco criar um arquivo nome.txt escreve a string palavras\n base = open(nome, 'w')\n base.write(palavras)\n base.close()\n\n#essa função recupera as palavras do arquivo nome.txt em uma variável palavras\ndef listarPalavras(nome):\n base = open(nome, 'r')\n palavras = base.read().split()\n base.close()\n return palavras\n\n#essa função cria os parâmetros do jogo\ndef criarJogo():\n nome = \"base.txt\"\n criarBase(nome)\n palavra = random.choice(listarPalavras(nome))\n montagem = []\n for n in range(len(palavra)):\n montagem.append(\"-\")\n jogo = dict(palavra = palavra, montagem = montagem, acertos = [], erros = [], quantPalpites = 0, terminou = False, ganhou = False)\n return jogo\n\n#essa função pega os dados do jogador da partida\ndef criarJogador():\n\n nome = str(input(\"Insira seu nome: \"))\n email = str(input(\"Insira seu email: \"))\n jogador = dict(nome = nome, email = email)\n print(\"\")\n return jogador\n\n#essa funlão valida a entrada do usuário em termos de palpites no jogo\ndef validarEntrada(letra, acertos):\n if(len(letra) > 1):\n print(\"Insira apenas uma letra!\")\n return False\n elif(not letra.isalpha()):\n print(\"Insira uma letra do alfabeto!\")\n return False\n elif(letra in acertos):\n print(\"Insira uma letra diferente!\")\n return False\n else: return True\n\n#essa função permite ao jogador fazer uma jogada\ndef fazerJogada(jogo):\n if(len(jogo['erros']) <= 5):\n letra = str(input(\"\\nInsira uma letra: \").lower())\n if(not validarEntrada(letra, jogo['acertos'])):\n fazerJogada(jogo)\n elif(letra not in jogo['palavra']):\n jogo['erros'].append(letra)\n print(\"A letra inserida não ocorre na palavra.\\n\")\n else:\n jogo['acertos'].append(letra)\n print(\"Você acertou uma letra!\\n\")\n for n in range(len(jogo['palavra'])):\n if(jogo['palavra'][n] == letra): jogo['montagem'][n] = letra\n if(jogo['palavra'] == \"\".join(jogo['montagem'])):\n print(\"Parabéns, você acertou todas as letras da palavra e terminou o jogo!\\n\")\n jogo['terminou'] = jogo['ganhou'] = True\n else:\n print(\"Você já usou todas sua tentativas.\\n\")\n jogo['terminou'] = True\n\n#essa função permite ao jogador fazer um palpite\ndef fazerPalpite(jogo):\n if(jogo['quantPalpites'] <= 3):\n palpite = str(input(\"\\nInsira seu palpite: \").lower())\n if(palpite == jogo['palavra']):\n print(\"Parabéns, você acertou a palavra e terminou o jogo!\\n\")\n jogo['terminou'] = jogo['ganhou'] = True\n else:\n jogo['quantPalpites'] += 1\n print(\"Palpite incorreto.\")\n else:\n print(\"Você já usou todos seus palpites.\\n\")\n jogo['terminou'] = True\n\n#essa função mostra o resumo da partida\ndef imprimirResumo(jogo):\n print(\"Palavra: \", end = \"\")\n for letra in jogo['montagem']:\n if(letra == '-'): print(\"_ \", end = \"\")\n else: print(\"%s \" % letra, end = \"\")\n print(\"\\n\\nLetras acertadas: \", jogo['acertos'])\n print(\"Letras erradas: \", jogo['erros'])\n print(\"Tentativas de letra disponíveis: \", 5 - len(jogo['erros']))\n print(\"Palpites disponíveis: \", 3 - jogo['quantPalpites'])\n\n#essa função salva o resultado do jogo num arquivo\ndef salvarJogo(jogo, jogador):\n arquivo = open(\"jogo.txt\", 'a')\n arquivo.write(jogador['nome'] + \"\\n\")\n arquivo.write(jogador['email'] + \"\\n\")\n arquivo.write(jogo['palavra'] + \"\\n\")\n arquivo.write(\"Ganhou: \" + str(jogo['ganhou']) + \"\\n\\n\")\n arquivo.close()\n\n#essa é a função principal do jogo da forca\ndef main():\n jogo = criarJogo()\n print(\"Bem-vindo ao jogo de forca em Python!\\n\")\n jogador = criarJogador()\n imprimirResumo(jogo)\n fazerJogada(jogo)\n imprimirResumo(jogo)\n\n while(not jogo['terminou']):\n res = str(input(\"\\nGostaria de tentar mais uma letra ou tentar um palpite da palavra? (L/P): \").upper())\n if(res == 'L'):\n fazerJogada(jogo)\n imprimirResumo(jogo)\n elif(res == 'P'): fazerPalpite(jogo)\n else: print(\"Opção inválida!\")\n salvarJogo(jogo, jogador)\n\nmain()","sub_path":"Projeto-Super-Jogo-Forca/forca.py","file_name":"forca.py","file_ext":"py","file_size_in_byte":4646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"224254755","text":"from pokemongo_bot import logger\nfrom pokemongo_bot.human_behaviour import sleep\nfrom pokemongo_bot.item_list import Item\nfrom pokemongo_bot.cell_workers.base_task import BaseTask\n\nclass EvolveAll(BaseTask):\n def initialize(self):\n self.evolve_speed = self.config.get('evolve_speed', 3.7)\n self.use_lucky_egg = self.config.get('use_lucky_egg', False)\n\n def work(self):\n if not self._should_run():\n return\n\n response_dict = self.bot.get_inventory()\n cache = {}\n\n try:\n reduce(dict.__getitem__, [\n \"responses\", \"GET_INVENTORY\", \"inventory_delta\", \"inventory_items\"], response_dict)\n except KeyError:\n pass\n else:\n evolve_list = self._sort_by_cp_iv(\n response_dict['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'])\n if self.bot.config.evolve_all[0] != 'all':\n # filter out non-listed pokemons\n evolve_list = [x for x in evolve_list if str(x[1]) in self.bot.config.evolve_all]\n\n # enable to limit number of pokemons to evolve. Useful for testing.\n # nn = 3\n # if len(evolve_list) > nn:\n # evolve_list = evolve_list[:nn]\n #\n\n id_list1 = self.count_pokemon_inventory()\n for pokemon in evolve_list:\n try:\n self._execute_pokemon_evolve(pokemon, cache)\n except Exception:\n pass\n id_list2 = self.count_pokemon_inventory()\n release_cand_list_ids = list(set(id_list2) - set(id_list1))\n\n if release_cand_list_ids:\n print('[#] Evolved {} pokemons! Checking if any of them needs to be released ...'.format(\n len(release_cand_list_ids)\n ))\n self._release_evolved(release_cand_list_ids)\n\n def _should_run(self):\n # Will skip evolving if user wants to use an egg and there is none\n if not self.bot.config.evolve_all:\n return False\n\n # Evolve all is used - Don't run after the first tick or if the config flag is false\n if self.bot.tick_count is not 1 or not self.use_lucky_egg:\n return True\n\n lucky_egg_count = self.bot.item_inventory_count(Item.ITEM_LUCKY_EGG.value)\n\n # Lucky Egg should only be popped at the first tick\n # Make sure the user has a lucky egg and skip if not\n if lucky_egg_count > 0:\n logger.log('Using lucky egg ... you have {}'.format(lucky_egg_count))\n response_dict_lucky_egg = self.bot.use_lucky_egg()\n if response_dict_lucky_egg and 'responses' in response_dict_lucky_egg and \\\n 'USE_ITEM_XP_BOOST' in response_dict_lucky_egg['responses'] and \\\n 'result' in response_dict_lucky_egg['responses']['USE_ITEM_XP_BOOST']:\n result = response_dict_lucky_egg['responses']['USE_ITEM_XP_BOOST']['result']\n if result is 1: # Request success\n logger.log('Successfully used lucky egg... ({} left!)'.format(lucky_egg_count - 1), 'green')\n return True\n else:\n logger.log('Failed to use lucky egg!', 'red')\n return False\n else:\n # Skipping evolve so they aren't wasted\n logger.log('No lucky eggs... skipping evolve!', 'yellow')\n return False\n\n def _release_evolved(self, release_cand_list_ids):\n response_dict = self.bot.get_inventory()\n cache = {}\n\n try:\n reduce(dict.__getitem__, [\n \"responses\", \"GET_INVENTORY\", \"inventory_delta\", \"inventory_items\"], response_dict)\n except KeyError:\n pass\n else:\n release_cand_list = self._sort_by_cp_iv(\n response_dict['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'])\n release_cand_list = [x for x in release_cand_list if x[0] in release_cand_list_ids]\n\n ## at this point release_cand_list contains evolved pokemons data\n for cand in release_cand_list:\n pokemon_id = cand[0]\n pokemon_name = cand[1]\n pokemon_cp = cand[2]\n pokemon_potential = cand[3]\n\n if self.should_release_pokemon(pokemon_name, pokemon_cp, pokemon_potential):\n # Transfering Pokemon\n self.transfer_pokemon(pokemon_id)\n logger.log(\n '[#] {} has been exchanged for candy!'.format(pokemon_name), 'red')\n\n def _sort_by_cp_iv(self, inventory_items):\n pokemons1 = []\n pokemons2 = []\n for item in inventory_items:\n try:\n reduce(dict.__getitem__, [\n \"inventory_item_data\", \"pokemon_data\"], item)\n except KeyError:\n pass\n else:\n try:\n pokemon = item['inventory_item_data']['pokemon_data']\n pokemon_num = int(pokemon['pokemon_id']) - 1\n pokemon_name = self.bot.pokemon_list[int(pokemon_num)]['Name']\n v = [\n pokemon['id'],\n pokemon_name,\n pokemon['cp'],\n self._compute_iv(pokemon)\n ]\n if pokemon['cp'] > self.bot.config.evolve_cp_min:\n pokemons1.append(v)\n else:\n pokemons2.append(v)\n except Exception:\n pass\n\n # Sort larger CP pokemons by IV, tie breaking by CP\n pokemons1.sort(key=lambda x: (x[3], x[2]), reverse=True)\n\n # Sort smaller CP pokemons by CP, tie breaking by IV\n pokemons2.sort(key=lambda x: (x[2], x[3]), reverse=True)\n\n return pokemons1 + pokemons2\n\n def _execute_pokemon_evolve(self, pokemon, cache):\n pokemon_id = pokemon[0]\n pokemon_name = pokemon[1]\n pokemon_cp = pokemon[2]\n pokemon_iv = pokemon[3]\n\n if pokemon_name in cache:\n return\n\n self.bot.api.evolve_pokemon(pokemon_id=pokemon_id)\n response_dict = self.bot.api.call()\n status = response_dict['responses']['EVOLVE_POKEMON']['result']\n if status == 1:\n print('[#] Successfully evolved {} with {} CP and {} IV!'.format(\n pokemon_name, pokemon_cp, pokemon_iv\n ))\n\n sleep(self.evolve_speed)\n\n else:\n # cache pokemons we can't evolve. Less server calls\n cache[pokemon_name] = 1\n sleep(0.7)\n\n # TODO: move to utils. These methods are shared with other workers.\n def transfer_pokemon(self, pid):\n self.bot.api.release_pokemon(pokemon_id=pid)\n response_dict = self.bot.api.call()\n\n def count_pokemon_inventory(self):\n response_dict = self.bot.get_inventory()\n id_list = []\n return self.counting_pokemon(response_dict, id_list)\n\n def counting_pokemon(self, response_dict, id_list):\n try:\n reduce(dict.__getitem__, [\n \"responses\", \"GET_INVENTORY\", \"inventory_delta\", \"inventory_items\"], response_dict)\n except KeyError:\n pass\n else:\n for item in response_dict['responses']['GET_INVENTORY']['inventory_delta']['inventory_items']:\n try:\n reduce(dict.__getitem__, [\n \"inventory_item_data\", \"pokemon_data\"], item)\n except KeyError:\n pass\n else:\n pokemon = item['inventory_item_data']['pokemon_data']\n if pokemon.get('is_egg', False):\n continue\n id_list.append(pokemon['id'])\n\n return id_list\n\n def should_release_pokemon(self, pokemon_name, cp, iv):\n if self._check_always_capture_exception_for(pokemon_name):\n return False\n else:\n release_config = self._get_release_config_for(pokemon_name)\n cp_iv_logic = release_config.get('logic')\n if not cp_iv_logic:\n cp_iv_logic = self._get_release_config_for('any').get('logic', 'and')\n\n release_results = {\n 'cp': False,\n 'iv': False,\n }\n\n if 'release_below_cp' in release_config:\n min_cp = release_config['release_below_cp']\n if cp < min_cp:\n release_results['cp'] = True\n\n if 'release_below_iv' in release_config:\n min_iv = release_config['release_below_iv']\n if iv < min_iv:\n release_results['iv'] = True\n\n if release_config.get('always_release'):\n return True\n\n logic_to_function = {\n 'or': lambda x, y: x or y,\n 'and': lambda x, y: x and y\n }\n\n # logger.log(\n # \"[x] Release config for {}: CP {} {} IV {}\".format(\n # pokemon_name,\n # min_cp,\n # cp_iv_logic,\n # min_iv\n # ), 'yellow'\n # )\n\n return logic_to_function[cp_iv_logic](*release_results.values())\n\n def _get_release_config_for(self, pokemon):\n release_config = self.bot.config.release.get(pokemon)\n if not release_config:\n release_config = self.bot.config.release['any']\n return release_config\n\n def _get_exceptions(self):\n exceptions = self.bot.config.release.get('exceptions')\n if not exceptions:\n return None\n return exceptions\n\n def _get_always_capture_list(self):\n exceptions = self._get_exceptions()\n if not exceptions:\n return []\n always_capture_list = exceptions['always_capture']\n if not always_capture_list:\n return []\n return always_capture_list\n\n def _check_always_capture_exception_for(self, pokemon_name):\n always_capture_list = self._get_always_capture_list()\n if not always_capture_list:\n return False\n else:\n for pokemon in always_capture_list:\n if pokemon_name == str(pokemon):\n return True\n return False\n\n # TODO: should also go to util and refactor in catch worker\n def _compute_iv(self, pokemon):\n total_IV = 0.0\n iv_stats = ['individual_attack', 'individual_defense', 'individual_stamina']\n\n for individual_stat in iv_stats:\n try:\n total_IV += pokemon[individual_stat]\n except Exception:\n pokemon[individual_stat] = 0\n continue\n pokemon_potential = round((total_IV / 45.0), 2)\n return pokemon_potential\n","sub_path":"pokemongo_bot/cell_workers/evolve_all.py","file_name":"evolve_all.py","file_ext":"py","file_size_in_byte":10979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"86580148","text":"import numpy as np\n\nclass duboji: \n def __init__(self):\n self.last = 0\n self.count = 0\n np.random.seed(0)\n self.board = np.random.randint(0,100,10)\n def check_board(self):\n print(self.board)\n def dubo(self,No):\n r = self.board[No]\n if self.last == No:\n self.count += 1\n return np.round(r / self.count)\n else:\n self.last = No\n count = 1\n return r","sub_path":"ml_action/duboji.py","file_name":"duboji.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"640314040","text":"from selenium import webdriver\nimport time\nfrom selenium.webdriver.chrome.options import Options\ndriver = webdriver.Chrome(\"C:\\\\Git\\\\Amilineni\\\\Python\\\\Drivers\\\\chromedriver.exe\")\nwebsite_URL = \"http://demo.automationtesting.in/FileDownload.html\"\n\ndriver.get(website_URL)\n\ndriver.find_element_by_xpath(\"//textarea[@id='textbox']\").send_keys('hffodjsfodfpdspfs')\n\ntime.sleep(5)\ndriver.find_element_by_id(\"createTxt\").click()\n\ndriver.find_element_by_xpath(\"//a[@id='link-to-download']\").click()\n\n\n","sub_path":"Python/Selenium/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"377065874","text":"# -*- coding: utf-8 -*-\n\nfrom types import Environment, LispError, Closure\nfrom ast import is_boolean, is_atom, is_symbol, is_list, is_closure, is_integer\nfrom asserts import assert_exp_length, assert_valid_definition, assert_boolean\nfrom parser import unparse\n\n\"\"\"\nThis is the Evaluator module. The `evaluate` function below is the heart\nof your language, and the focus for most of parts 2 through 6.\n\nA score of useful functions is provided for you, as per the above imports, \nmaking your work a bit easier. (We're supposed to get through this thing \nin a day, after all.)\n\"\"\"\nmath_operands = [\"+\",\"-\",\"/\",\"*\",\"mod\"]\n\ndef evaluate(ast, env):\n if is_list(ast):\n first_exp = ast[0]\n if first_exp == \"atom\": return is_atom(evaluate(ast[1],env))\n elif first_exp == \"define\": return eval_define(ast[1:], env)\n elif first_exp == \"if\": return eval_if_statement(ast[1:], env)\n elif first_exp == \"lambda\": return eval_lambda(ast[1:], env)\n elif first_exp == \"quote\": return ast[1];\n elif first_exp == \"eq\": return eval_equation(ast[1:], env)\n elif first_exp == \"cons\": return eval_list_cons(ast[1:], env)\n elif first_exp == \"head\": return eval_list_head(ast[1:], env) \n elif first_exp == \"tail\": return eval_list_tail(ast[1:], env) \n elif first_exp == \"empty\": return eval_list_empty(ast[1:], env)\n elif first_exp in math_operands: return eval_math_operation(first_exp, ast[1:], env)\n elif first_exp == \"<\": return evaluate(ast[1], env) < evaluate(ast[2], env)\n elif first_exp == \"<=\": return evaluate(ast[1], env) <= evaluate(ast[2], env)\n elif first_exp == \">\": return evaluate(ast[1], env) > evaluate(ast[2], env)\n elif first_exp == \">=\": return evaluate(ast[1], env) >= evaluate(ast[2], env)\n elif is_list(first_exp) or is_symbol(first_exp): \n eval_first = evaluate(first_exp, env)\n return evaluate([eval_first]+ast[1:], env)\n elif is_closure(first_exp):\n arguments = ast[1:]\n return evaluate(first_exp.body, first_exp.env.extend(evaluate_function_arguments(first_exp, arguments, env)))\n else:\n raise LispError('{0} not a function'.format(first_exp))\n\n elif is_symbol(ast): return env.lookup(ast)\n elif is_atom(ast): return ast \n\ndef eval_list_cons(args, env):\n elem = evaluate(args[0], env)\n _list = evaluate(args[1], env)\n return [elem] + _list\n\ndef eval_list_head(args, env):\n _list = evaluate(args[0], env)\n if len(_list)==0:\n raise LispError('empty list')\n return _list[0]\n\ndef eval_list_tail(args, env):\n _list = evaluate(args[0], env)\n if len(_list)==0:\n raise LispError('empty list')\n return _list[1:]\n\ndef eval_list_empty(args, env):\n _list = evaluate(args[0], env)\n return len(_list)==0\n\ndef eval_define(args, env):\n if not len(args) == 2:\n raise LispError(\"Wrong number of arguments\")\n variable_name = args[0]\n if not is_symbol(variable_name):\n raise LispError(\"non-symbol\")\n variable_value = evaluate(args[1], env)\n env.set(variable_name, variable_value)\ndef eval_if_statement(args, env):\n evalPredicate = evaluate(args[0],env)\n if not (is_boolean(evalPredicate)):\n raise LispError('predicate must return boolean value')\n if evalPredicate:\n return evaluate(args[1], env)\n else:\n return evaluate(args[2], env)\ndef eval_equation(args, env):\n eval1 = evaluate(args[0],env)\n eval2 = evaluate(args[1],env)\n if not (is_atom(eval1) and is_atom(eval2)): \n return False\n return eval1 == eval2\ndef eval_lambda(args, env):\n if not len(args) == 2:\n raise LispError(\"number of arguments\")\n params = args[0]\n body = args[-1]\n if not (is_list(params)):\n raise LispError('arguments of lambda must be a list')\n return Closure(env, params, body)\ndef eval_math_operation(symbol, args, env):\n eval1 = evaluate(args[0],env)\n eval2 = evaluate(args[1],env)\n if not (is_integer(eval1) and is_integer(eval2)): \n raise LispError('math operands must be an integer values')\n if symbol == \"+\":\n return eval1 + eval2\n elif symbol == \"-\":\n return eval1 - eval2\n elif symbol == \"/\":\n return eval1 / eval2\n elif symbol == \"*\":\n return eval1 * eval2\n elif symbol == \"mod\":\n return eval1 % eval2\n else:\n return eval1\ndef evaluate_function_arguments(closure, params_values, env):\n params_count = len(params_values) \n closure_params_count = len(closure.params) \n if params_count != closure_params_count:\n raise LispError(\"wrong number of arguments, expected {0} got {1}\".format(closure_params_count, params_count))\n return dict((closure.params[idx], evaluate(param_value, env)) for idx, param_value in enumerate(params_values)) ","sub_path":"diylisp/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":4885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"289344862","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nTic-Tac-Toe\r\nAuthor: Shadman Ahmed\r\n\r\n\"\"\"\r\n\r\nfrom IPython.display import clear_output\r\nimport random\r\n\r\ndef display_board(board):\r\n clear_output()\r\n print(board[7]+'|'+board[8]+'|'+board[9])\r\n print(board[4]+'|'+board[5]+'|'+board[6])\r\n print(board[1]+'|'+board[2]+'|'+board[3])\r\n \r\ndef player_input():\r\n \r\n marker = ' '\r\n\r\n #Ask Player 1 to choose their marker\r\n while marker != 'X' and marker != 'O':\r\n marker = input('Player 1, choose X or O: ')\r\n \r\n #Assign Markers Upon Input\r\n player1 = marker\r\n if player1 == 'X':\r\n player2 = 'O'\r\n else: player2 = 'X'\r\n \r\n return(player1,player2)\r\n \r\ndef marker_assignment(board, marker, position):\r\n board[position] = marker\r\n \r\ndef check_win(board, mark): \r\n \r\n #ALL ROW CHECKER\r\n return ((board[1] == board[2] == board[3] == mark) or\r\n (board[4] == board[5] == board[6] == mark) or\r\n (board[7] == board[8] == board[9] == mark) or\r\n #ALL COLUMN CHECKER\r\n (board[7] == board[4] == board[1] == mark) or\r\n (board[8] == board[5] == board[2] == mark) or\r\n (board[9] == board[6] == board[3] == mark) or\r\n #DIAGONALS CHECKER\r\n (board[7] == board[5] == board[3] == mark) or\r\n (board[9] == board[5] == board[1] == mark))\r\n\r\ndef player_picker():\r\n \r\n flip = random.randint(0,1)\r\n if flip == 0:\r\n return 'Player 1'\r\n else:\r\n return 'Player 2'\r\n \r\ndef space_checker(board,position):\r\n return board[position] == ' '\r\n\r\ndef full_board_check(board):\r\n \r\n for i in range(1,10):\r\n if space_checker(board,i):\r\n return False\r\n return True\r\n\r\ndef player_choice(board,turn):\r\n \r\n \r\n position = 0\r\n while position not in [1,2,3,4,5,6,7,8,9] or not space_checker(board,position):\r\n position = int(input('{}, choose a position on the numpad: '.format(turn)))\r\n return position\r\n\r\n\r\ndef replay():\r\n \r\n choice = input('Play again? Type either \"Y\" to accept or \"N\" to decline: ')\r\n return choice == 'Y'\r\n\r\n#MAIN WHILE LOOP\r\n \r\nprint('Welcome to Tic-Tac-Toe')\r\n\r\nwhile True:\r\n \r\n ##SETUP\r\n the_board = [' ']*10\r\n player1_marker,player2_marker =player_input()\r\n turn = player_picker()\r\n print(turn + ' will go first!')\r\n play_game = input('Ready to play? Type either \"Y\" to accept or \"N\" to decline: ')\r\n if play_game =='Y':\r\n game_on = True\r\n elif play_game =='N':\r\n game_on = False\r\n \r\n #Gameplay \r\n while game_on:\r\n \r\n if turn =='Player 1':\r\n #Display the board\r\n display_board(the_board)\r\n #Choose a position\r\n position = player_choice(the_board,turn)\r\n #Place Marker at the position\r\n marker_assignment(the_board,player1_marker,position)\r\n #Check win\r\n if check_win(the_board,player1_marker):\r\n display_board(the_board)\r\n print('Player 1 has won!')\r\n game_on = False\r\n else:\r\n if full_board_check(the_board):\r\n display_board(the_board)\r\n print('The game is a tie!')\r\n game_on = False\r\n else:\r\n turn = 'Player 2'\r\n \r\n else:\r\n #Display the board\r\n display_board(the_board)\r\n #Choose a position\r\n position = player_choice(the_board,turn)\r\n #Place Marker at the position\r\n marker_assignment(the_board,player2_marker,position)\r\n #Check win\r\n if check_win(the_board,player2_marker):\r\n display_board(the_board)\r\n print('Player 2 has won!')\r\n game_on = False\r\n else:\r\n if full_board_check(the_board):\r\n display_board(the_board)\r\n print('The game is a tie!')\r\n game_on = False\r\n else:\r\n turn = 'Player 1'\r\n\r\n if not replay():\r\n break\r\n","sub_path":"TTT.py","file_name":"TTT.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"139635098","text":"import sys\n#sys.stdin=open('input.txt',\"r\")\ninput=sys.stdin.readline\nn,m,v=map(int,input().split())\n\nmatrix=[[0]*(n+1) for _ in range(n+1)]\n\nfor _ in range(m):\n adj=list(map(int,input().split()))\n matrix[adj[0]][adj[1]]=1\n matrix[adj[1]][adj[0]]=1\n\ndef dfs(point,row, visited):\n visited+=[point]\n for search in range(len(row[point])):\n if row[point][search] and search not in visited:\n visited=dfs(search,row,visited)\n return visited\n\ndef bfs(point,row,visited):\n queue=[point]\n visited=[point]\n while queue:\n point=queue.pop(0)\n for search in range(len(row[point])):\n if row[point][search] and search not in visited:\n visited+=[search]\n queue+=[search]\n return visited\nprint(*dfs(v,matrix,[]))\nprint(*bfs(v,matrix,[]))\n\n\n\n\n","sub_path":"조윤���/DFS_BFS/BOJ_1260.py","file_name":"BOJ_1260.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"109625765","text":"secretName = 'Arthur'\nsecretColor = 'green'\nwhile True:\n print('What is your name?')\n name = input()\n if name != secretName:\n continue\n print('What is your favorite color?') \n color = input()\n if color == secretColor:\n break\n else:\n print('Sorry, wrong color!')\nprint('Congrats!')\n\n","sub_path":"whileExamples/NameFavoriteColor.py","file_name":"NameFavoriteColor.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"312479768","text":"import torch\nimport numpy as np\nfrom torchvision import datasets\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom pythonML.notebooks.Pytorch.sandbox.LinearAutoencoderMnist import Autoencoder\n\nif __name__ == '__main__':\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n batch_size = 20\n n_epochs = 10\n\n # convert data to torch.FloatTensor\n transform = transforms.ToTensor()\n test_data = datasets.MNIST(root='~/.pytorch/MNIST_data/', train=False, download=True, transform=transform)\n test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size)\n\n encoding_dim = 32\n model = Autoencoder(encoding_dim).to(device)\n print(model)\n model.load_state_dict(torch.load('models/model_ae_linear_mnist.pt'))\n model.eval()\n with torch.no_grad():\n dataiter = iter(test_loader)\n images, labels = dataiter.next()\n images = images.to(device)\n labels = labels.to(device)\n\n images_flatten = images.view(images.size(0), -1)\n output = model(images_flatten)\n # prep images for display\n images = images.to('cpu').numpy()\n\n # output is resized into a batch of images\n output = output.view(batch_size, 1, 28, 28)\n # use detach when it's an output that requires_grad\n output = output.to('cpu').numpy()\n\n # plot the first ten input images and then reconstructed images\n fig, axes = plt.subplots(nrows=2, ncols=10, sharex=True, sharey=True, figsize=(25, 4))\n\n # input images on top row, reconstructions on bottom\n for images, row in zip([images, output], axes):\n for img, ax in zip(images, row):\n ax.imshow(np.squeeze(img), cmap='gray')\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n\n plt.show()","sub_path":"pythonML/notebooks/Pytorch/sandbox/LinearAutoencoderMnistVal.py","file_name":"LinearAutoencoderMnistVal.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"392823616","text":"import requests\nfrom bs4 import BeautifulSoup\nimport csv\nimport mysql.connector\n\ndb = mysql.connector.connect(host = 'db.sice.indiana.edu',\n user = 'i494f18_team58',\n passwd = 'my+sql=i494f18_team58',\n database = 'i494f18_team58')\n\nurl = \"https://iuhoosiers.com/cumestats.aspx?path=football\"\npage = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'})\n\nsoup = BeautifulSoup(page.content, 'html.parser')\n\nentry = []\nteamID = 2\nreceiving = soup.find('section', id='individual-offense-receiving')\n\nfieldnames = ['stat_type', 'stat_number','athleteID','teamID']\nwith open('FBRecstats.csv', mode=\"w\") as s:\n writer = csv.writer(s, delimiter=',')\n writer.writerow(fieldnames)\n for item in receiving.find_all('tr'):\n stats = item.find_all('td')\n name = item.find_all('span')\n for string in name:\n if len(str(string)) > 45:\n length = len(str(string))\n first = str(string).find(\" \")\n last = str(string).find(\", \")\n fname = str(string)[last +len(\", \"):length-len(\"\")]\n lname = str(string)[first+len(\" \"):last]\n #print(fname, lname)\n\n firstname = fname.replace(\" \", \"\")\n fname = firstname.upper()\n lastname = lname.replace(\" \", \"\")\n lname = lastname.upper()\n## if fname == \"MICHAEL\":\n## lname = \"PENIXJR.\"\n query =('SELECT DISTINCT athleteID FROM athlete WHERE fname =\"'+ fname +'\" AND lname =\"'+lname +'\"')\n cursor = db.cursor(buffered=True)\n cursor.execute(query)\n record = cursor.fetchone()\n #print(fname, lname, record)\n \n for line in stats:\n leng = len(str(line))\n## print(fname, leng)\n## print(line)\n## print(leng)\n if leng > 45 and leng < 55:\n one_pos = str(line).find('l=\"')\n two_pos = str(line).find('\">')\n three_pos = str(line).find(\"\")\n statType = str(line)[one_pos + len('l=\"'):two_pos]\n## print(fname, statType)\n if len(statType) < 10:\n stat_type = statType\n #entry.append(stat_type)\n stat_num = str(line)[two_pos + len('\">'):three_pos]\n stat_number = stat_num.replace(\"-\", \"\")\n## print(fname, stat_type, stat_num)\n #entry.append(stat_number)\n## print(fname, record)\n entry.append(stat_type)\n entry.append(stat_number)\n entry.append(record[0])\n entry.append(teamID)\n writer.writerow(entry)\n print(entry)\n if stat_type == \"AVG/G\":\n entry = []\n else:\n entry = []\n","sub_path":"Scraper_Files/FBrecScraper.py","file_name":"FBrecScraper.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"245260831","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nimport pygame\nimport random\nimport time\n\nWIDTH = 500\nHEIGHT = 500\n\npygame.init()\npygame.mixer.init()\npygame.font.init()\ngameDisplay = pygame.display.set_mode((HEIGHT, WIDTH))\npygame.display.set_caption('Star wars')\nclock = pygame.time.Clock()\n\nclass Object:\n def __init__(self, path_to_image):\n self.x = 250\n self.y = 468\n self.x_change = 0\n self.y_change = 0\n self.image = pygame.image.load(path_to_image)\n def create(self):\n if 0 < self.x + self.x_change < 473:\n self.x += self.x_change\n if 200 < self.y + self.y_change < 468:\n self.y += self.y_change\n gameDisplay.blit(self.image, (self.x, self.y))\n\ndef display_score():\n global score\n score += 1\n pygame.display.set_caption('Star wars: ' + str(score))\ndef check_key(event):\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n ship.x_change = -1\n if event.key == pygame.K_RIGHT:\n ship.x_change = 1\n if event.key == pygame.K_DOWN:\n ship.y_change = 1\n if event.key == pygame.K_UP:\n ship.y_change = -1\n if event.key == pygame.K_SPACE:\n BST.append([ship.x, ship.y])\n pygame.mixer.music.load(\"fire.mp3\")\n pygame.mixer.music.play()\n\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT and ship.x_change != 1:\n ship.x_change = 0\n if event.key == pygame.K_RIGHT and ship.x_change != -1:\n ship.x_change = 0\n if event.key == pygame.K_UP and ship.y_change != 1:\n ship.y_change = 0\n if event.key == pygame.K_DOWN and ship.y_change != -1:\n ship.y_change = 0\ndef check_bang():\n global TG, BST\n for j, i in enumerate(TG):\n x1 = i[0]\n y1 = i[1]\n for j1, i1 in enumerate(BST):\n x2 = i1[0] + 14\n y2 = i1[1] - 3\n if ((x1-x2)**2 + (y1-y2)**2) ** .5 <= 10:\n TG[j] = ()\n BST[j1] = ()\n display_score()\n pygame.mixer.music.load(\"bang.mp3\")\n pygame.mixer.music.play()\n BST = [i for i in BST if i]\n TG = [i for i in TG if i]\ndef bluster():\n for j, i in enumerate(BST):\n x = i[0]\n y = i[1]\n pygame.draw.line(gameDisplay,\n (250, 0, 0),\n (x+14, y), (x+14, y-3), 1)\n if y < 0:\n BST.pop(j)\n else:\n BST[j][1] = y-2\ndef target():\n global tg_clock\n if time.time() > tg_clock and len(TG) < 3:\n TG.append([random.randint(10, WIDTH-10), 0])\n tg_clock = time.time() + random.random()\n for j, i in enumerate(TG):\n pygame.draw.circle(gameDisplay,\n (250, 250, 250), i, 10)\n if TG[j][1] > 510:\n TG.pop(j)\n else:\n TG[j][1] += 1\n\n\nTG = []\nBST = []\nscore = 0\ntg_clock = time.time()\nship = Object('ship.png')\n\ncrashed = False\nwhile not crashed:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n crashed = True\n continue\n check_key(event)\n\n gameDisplay.fill((0, 0, 0))\n ship.create()\n check_bang()\n bluster()\n target()\n\n pygame.display.update()\n clock.tick(100)\n","sub_path":"Star_wars/star_wars.py","file_name":"star_wars.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"637017689","text":"from transformers import AutoModelWithLMHead, AutoTokenizer\n\ntokenizer = AutoTokenizer.from_pretrained(\"mrm8488/t5-base-finetuned-e2m-intent\")\nmodel = AutoModelWithLMHead.from_pretrained(\"mrm8488/t5-base-finetuned-e2m-intent\")\n\ndef get_intent(event, max_length=16):\n input_text = \"%s \" % event\n features = tokenizer([input_text], return_tensors='pt')\n\n output = model.generate(input_ids=features['input_ids'], \n attention_mask=features['attention_mask'],\n max_length=max_length)\n\n return tokenizer.decode(output[0])\n\nevent = \"Who is the president of the USA?\"\nprint(get_intent(event))","sub_path":"scripts/intent_example.py","file_name":"intent_example.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"543139944","text":"import requests\nimport json\n\nclass BaseClient:\n def __init__(self, host, port):\n self.base = 'http://{}:{}/'.format(host, port)\n self.game_over = False\n self.session = requests.Session()\n\n def get(self, command):\n if self.game_over:\n return\n return self.session.get(self.base + command).text\n\n def get_as_json(self, command):\n if self.game_over:\n return\n return self.session.get(self.base + command).json()\n\n def post(self, command, attributes):\n if self.game_over:\n return\n res = self.session.post(self.base + command, json=attributes)\\\n\n if res.status_code == 418:\n self.game_over = True\n return\n return res.json()\n\n def post_raw(self, command, attributes):\n return self.session.post(self.base + command, json=attributes).text\n\n # self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # self.socket.connect((host, port))\n #\n #\n # def get_message(self):\n # try:\n # message = self.socket.recv(2 ** 20)\n # except(BlockingIOError):\n # return\n # if message is None:\n # return\n # return message.decode('utf-8')\n #\n # def get_message_non_blocking(self):\n # self.socket.setblocking(False)\n # message = self.get_message()\n # self.socket.setblocking(True)\n # return message\n #\n # def get_msg(self):\n # m = ''\n # while True:\n # mm = self.get_message_non_blocking()\n # m = m + (mm or '')\n # if len(re.compile('\\n\\n').findall(m)) > 0:\n # return m\n #\n # def perform_command(self, command, expect_output=True):\n # while self.get_message_non_blocking() is not None:\n # pass\n # self.socket.send(command.encode('UTF-8'))\n # if expect_output:\n # return self.get_msg()\n","sub_path":"python_client/kosa/base_client.py","file_name":"base_client.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"154832323","text":"import boto3\nimport sys, os\n\nuuid = sys.argv[1]\n\n# Get the service client.\ns3 = boto3.client('s3')\nN_hours = 24\nurl_list = list()\n\ndirectory = '{:s}/gifs'.format(uuid)\nfor fn in os.listdir(directory):\n key = os.path.join(directory,fn)\n url = s3.generate_presigned_url(\n ClientMethod='get_object',\n Params={\n 'Bucket': 'kinetic-mechanical-twerk',\n 'Key': key\n },\n ExpiresIn=60*60*N_hours\n )\n url_list.append(url)\n\nwith open('{:s}/mturk_input.csv'.format(uuid),'w') as f:\n import csv\n writer = csv.writer(f)\n writer.writerow(['image_url'])\n for url in url_list:\n writer.writerow([url,])\n","sub_path":"generate_presigned_urls.py","file_name":"generate_presigned_urls.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"388464468","text":"# Basic info and help should be available if only argparse module is available.\r\nimport argparse\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"--show-figures\", \"-f\", default=True, help=\"show plotted figures. True by default\")\r\nparser.add_argument(\"--save-figures\", \"-s\", default=False, help=\"save plotted figures. False by default\")\r\nargs = parser.parse_args()\r\n\r\ndef headless_mode():\r\n args.show_figures = False\r\n args.save_figures = True\r\n\r\nargs.show_figures = True\r\nargs.save_figures = True\r\n\r\n# Uncomment to manually enable headless mode:\r\n# headless_mode()\r\n\r\n# Take into account parsed arguments and behave accordingly.\r\ndef display_or_save(fig, filename):\r\n if args.save_figures:\r\n plt.savefig(\"../figures/\" + filename + '.png', bbox_inches='tight')\r\n plt.savefig(\"../figures/\" + filename + '.svg', bbox_inches='tight')\r\n\r\n if not args.show_figures:\r\n plt.close(fig)\r\n\r\n if args.show_figures:\r\n plt.show()\r\n\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\ndef describe_plot():\r\n plt.xlabel(\"Input size\")\r\n # plt.xscale(\"log\")\r\n plt.ylabel(\"Execution time [s]\")\r\n # plt.yscale(\"log\")\r\n plt.legend(loc = \"upper left\")\r\n\r\nfig = plt.figure(figsize=(12, 8), dpi=120)\r\nplt.title(\"Comparison of execution time for varying input size\")\r\n\r\ndata_scheme = [('input_size', 'u4'), ('execution_time', 'f4')]\r\nfilenames = [\"standard\", \"managed\", \"stride_standard\", \"stride_managed\"]\r\nlabels = {\r\n \"standard\" : \"Standard memory\",\r\n \"managed\" : \"Managed (uniform) memory\",\r\n \"stride_standard\" : \"Standard memory, stride\",\r\n \"stride_managed\" : \"Uniform memory, stride\"}\r\ninputs = dict()\r\n\r\nfor filename in filenames:\r\n with open(filename+\".dat\", 'r') as file:\r\n inputs[filename] = np.loadtxt(file, dtype=data_scheme)\r\n\r\nfor filename in filenames:\r\n plt.plot(inputs[filename]['input_size'], inputs[filename]['execution_time'], label=labels[filename])\r\n\r\ndescribe_plot()\r\ndisplay_or_save(fig, \"matrix_multiplication\")","sub_path":"Lab3/data/matrix_multiplication.py","file_name":"matrix_multiplication.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"147401381","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n\r\ntrain = pd.read_csv('./kaggle_tasks/20210415_ottogroupproductclassification/train.csv')\r\ntest = pd.read_csv('./kaggle_tasks/20210415_ottogroupproductclassification/test.csv')\r\nsampleSubmission = pd.read_csv('./kaggle_tasks/20210415_ottogroupproductclassification/sampleSubmission.csv')\r\n\r\nprint(train.describe()) #id #feat_1 to 93 #target:Class #(61878, 95)\r\nprint(test.describe()) #id #feat_1 to 93 #(144368, 94)\r\nprint(sampleSubmission.describe()) #id #Class_1 to 9 #(144368, 10)\r\n# they don't have NULL\r\n\r\nprint(train.columns)\r\nprint(test.columns)\r\nprint(sampleSubmission.columns)\r\n\r\ndata = train.copy\r\nfinT = test.copy\r\nsS = sampleSubmission.copy\r\n###################################################################################################################################\r\n\r\n'''File descriptions\r\n trainData.csv - the training set\r\n testData.csv - the test set\r\n sampleSubmission.csv - a sample submission file in the correct format\r\n Data fields\r\n id - an anonymous id unique to a product\r\n feat_1, feat_2, ..., feat_93 - the various features of a product\r\n target - the class of a product'''\r\n\r\n###################################################################################################################################\r\n","sub_path":"20210415_ottogroupproductclassification.py","file_name":"20210415_ottogroupproductclassification.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"71269249","text":"import threading\nimport time\nfrom abc import ABC\nfrom typing import Union\n\n\n\n\n__all__ = ['AutoStartThread', 'AutoStartTargetedThread', 'Wait']\n\nclass AutoStartThread(threading.Thread, ABC):\n def __init__(self, *args, Name: str = None, AutoStart: bool = True, Daemon: bool = True, **kwargs):\n if not Name:\n try: Name = self.__class__.__qualname__\n except AttributeError: Name = self.__class__.__name__\n\n super().__init__(name=Name, args=args, kwargs=kwargs, daemon=Daemon)\n if AutoStart: self.start()\n def run(self): raise NotImplementedError()\n\nclass AutoStartTargetedThread(threading.Thread):\n def __init__(self, target: callable, *args, Name: str = None, AutoStart: bool = True, Daemon: bool = True, **kwargs):\n assert (callable(target))\n if not Name:\n try: Name = target.__qualname__\n except AttributeError: Name = target.__name__\n\n super().__init__(name=Name, target=target, args=args, kwargs=kwargs, daemon=Daemon)\n if AutoStart: self.start()\n\n\ndef Wait(delay: Union[int, float]): time.sleep(delay)\n","sub_path":"venv/Lib/site-packages/BaseExtensions/Threads.py","file_name":"Threads.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"203511875","text":"import tkinter as tk\r\nfrom tkinter import ttk, filedialog\r\nimport nidaqmx\r\nimport nidaqmx.stream_readers\r\nimport nidaqmx.constants as cts\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport json\r\n\r\n### dictionary for nidaqmx constants\r\ndict_ = {'Rising': cts.Slope.RISING,\r\n 'Falling': cts.Slope.FALLING,\r\n 'Continuous Samples': cts.AcquisitionType.CONTINUOUS,\r\n 'N Samples': cts.AcquisitionType.FINITE,\r\n '1 Sample (HW Timed)': cts.AcquisitionType.HW_TIMED_SINGLE_POINT,\r\n 'Entering Window': cts.WindowTriggerCondition1.ENTERING_WINDOW,\r\n 'Leaving Window': cts.WindowTriggerCondition1.LEAVING_WINDOW,\r\n 'Log Only': cts.LoggingMode.LOG,\r\n 'Log and Read': cts.LoggingMode.LOG_AND_READ,\r\n 'create': cts.LoggingOperation.CREATE_OR_REPLACE,\r\n 'open': cts.LoggingOperation.OPEN_OR_CREATE,\r\n }\r\nroot = tk.Tk()\r\nroot.winfo_toplevel().title('NiDAQmx Controller')\r\nroot.tk_setPalette(background='white')\r\n### Important Variables ###\r\n##Setting Variables\r\nchannel_list = []\r\nmax_InputRange = tk.StringVar(root, value=10)\r\nmin_InputRange = tk.StringVar(root, value=-10)\r\n##Timing Variables\r\nacquisition_mode = tk.StringVar(root, value='Continuous Samples')\r\nsamples_to_read = tk.StringVar(root, value='90000')\r\nrate = tk.StringVar(root, value='10000')\r\n##Triggering Variables\r\n#Start trigger\r\nstt_trigger_source = tk.StringVar(root, value='APFI0')\r\nstt_trigger_type = tk.StringVar(root, value='')\r\nstt_trigger_slope = tk.StringVar(root, value='Rising')\r\nstt_trigger_level = tk.StringVar(root, value='0')\r\nstt_window_top = tk.StringVar(root, value='0')\r\nstt_window_bot = tk.StringVar(root, value='0')\r\nstt_trigger_condition = tk.StringVar(root, value='Entering Window')\r\nstt_trigger_edge = tk.StringVar(root, value='Rising')\r\n#Reference Trigger\r\nref_trigger_source = tk.StringVar(root, value='APFI0')\r\nref_trigger_type = tk.StringVar(root, value='')\r\nref_trigger_slope = tk.StringVar(root, value='Rising')\r\nref_trigger_level = tk.StringVar(root, value='0')\r\nref_window_top = tk.StringVar(root, value='0')\r\nref_window_bot = tk.StringVar(root, value='0')\r\nref_trigger_condition = tk.StringVar(root, value='Entering Window')\r\nref_trigger_edge = tk.StringVar(root, value='Rising')\r\npreTriggerSamples = tk.StringVar(root, value='10000')\r\n## Advanced Timing Variables\r\ntimeout = tk.StringVar(root, value=10)\r\n##Logging Variables\r\nTDMSLogging = tk.IntVar(root)\r\nTDMS_filepath = tk.StringVar(root)\r\nappend = tk.IntVar()\r\nlogging_mode = tk.StringVar(root, value='Log and Read')\r\ngroup_name = tk.StringVar(root)\r\nsample_per_file = tk.StringVar(root, value='0')\r\nspan = tk.IntVar(root)\r\n\r\n# Channel class:\r\nclass Channel():\r\n channelsInTask = []\r\n def __new__(cls, *, name):\r\n for channel in cls.channelsInTask:\r\n if channel.name == name:\r\n print('channel already in task')\r\n return channel\r\n x = super(Channel, cls).__new__(cls)\r\n return x\r\n\r\n def __init__(self, *, name):\r\n self.name = name\r\n self.max_InputRange = tk.StringVar(root, value=10)\r\n self.min_InputRange = tk.StringVar(root, value=-10)\r\n Channel.channelsInTask.append(self)\r\n\r\n def find(name):\r\n for channel in Channel.channelsInTask:\r\n if channel.name == name:\r\n return channel\r\n return None\r\n\r\n def __repr__(self):\r\n dict_ = {'name': self.name, 'max': self.max_InputRange.get(), \r\n 'min': self.min_InputRange.get()}\r\n return dict_.__repr__()\r\n\r\n def remove(channel_name):\r\n for channel in Channel.channelsInTask:\r\n if channel.name == channel_name:\r\n Channel.channelsInTask.remove(channel)\r\n\r\n def channels_import(channels):\r\n for channel in channels:\r\n c = Channel(name=channel['name'])\r\n c.max_InputRange.set(channel['max'])\r\n c.min_InputRange.set(channel['min'])\r\n\r\n# Run task function\r\ndef run():\r\n task = nidaqmx.Task()\r\n for channel in Channel.channelsInTask:\r\n min_val = int(channel.min_InputRange.get())\r\n max_val = int(channel.max_InputRange.get())\r\n task.ai_channels.add_ai_voltage_chan(channel.name, min_val=min_val, max_val=max_val)\r\n stt_triggerType = stt_trigger_type.get()\r\n ref_triggerType = ref_trigger_type.get()\r\n samp_clk_src = 'Dev3/ai0'\r\n samples = int(samples_to_read.get())\r\n task.timing.cfg_samp_clk_timing(int(rate.get()),\r\n sample_mode=dict_[acquisition_mode.get()],\r\n samps_per_chan=samples\r\n )\r\n if stt_triggerType == 'Analog Edge':\r\n task.triggers.start_trigger.cfg_anlg_edge_start_trig(trigger_source=stt_trigger_source.get(),\r\n trigger_slope=dict_[stt_trigger_slope.get()],\r\n trigger_level=float(stt_trigger_level.get())\r\n )\r\n elif stt_triggerType == 'Analog Window':\r\n task.triggers.start_trigger.cfg_anlg_window_start_trig(trigger_source=stt_trigger_source.get(),\r\n window_top=float(stt_window_top.get()),\r\n window_bottom=float(stt_window_bot.get()),\r\n trigger_when=dict_[stt_trigger_condition.get()]\r\n )\r\n elif stt_triggerType == 'Digital Edge':\r\n task.triggers.start_trigger.cfg_dig_edge_start_trig(trigger_source=stt_trigger_source.get(),\r\n trigger_edge=dict_[stt_trigger_edge.get()]\r\n )\r\n if ref_triggerType == 'Analog Edge':\r\n task.triggers.reference_trigger.cfg_anlg_edge_ref_trig(trigger_source=ref_trigger_source.get(),\r\n pretrigger_samples=int(preTriggerSamples.get()),\r\n trigger_slope=dict_[ref_trigger_slope.get()],\r\n trigger_level=float(ref_trigger_level.get())\r\n )\r\n elif ref_triggerType == 'Analog Window':\r\n task.triggers.reference_trigger.cfg_anlg_window_ref_trig(trigger_source=ref_trigger_source.get(),\r\n window_top=float(ref_window_top.get()),\r\n window_bottom=float(ref_window_bot.get()),\r\n pretrigger_samples=int(preTriggerSamples.get()),\r\n trigger_when=dict_[ref_trigger_condition.get()]\r\n )\r\n elif ref_triggerType == 'Digital Edge':\r\n task.triggers.reference_trigger.cfg_dig_edge_ref_trig(trigger_source=ref_trigger_source.get(),\r\n pretrigger_samples=int(preTriggerSamples.get()),\r\n trigger_edge=dict_[ref_trigger_edge.get()]\r\n )\r\n if TDMSLogging.get():\r\n if append.get():\r\n operation = 'open'\r\n else:\r\n operation = 'create'\r\n task.in_stream.configure_logging(TDMS_filepath.get(), logging_mode=dict_[logging_mode.get()], \r\n group_name=group_name.get(), operation=dict_[operation])\r\n task.in_stream.logging_samps_per_file = int(sample_per_file.get())*span.get()\r\n r = task.read(number_of_samples_per_channel=samples, timeout=float(timeout.get()))\r\n data = pd.DataFrame(r)\r\n if len(channel_list) > 1:\r\n data = data.transpose()\r\n data.columns = channel_list\r\n data.plot()\r\n plt.show()\r\n task.close()\r\n\r\n# Decorative Frame\r\nclass BDFrame(tk.Frame):\r\n 'docstring for BDFrame'\r\n def __init__(self, root_, title):\r\n super(BDFrame, self).__init__(root_)\r\n self['highlightbackground'] = 'light steel blue'\r\n self['highlightcolor'] = 'light steel blue'\r\n self['highlightthickness'] = 1\r\n self.parent = root_\r\n self.title = title\r\n self.label = tk.Label(self.parent, text=self.title, fg='dodger blue')\r\n\r\n def pack(self):\r\n super(BDFrame, self).pack(padx=10, pady=10, fill=tk.BOTH)\r\n root.update()\r\n def set_title(self):\r\n root.update()\r\n x = self.winfo_x()\r\n y = self.winfo_y()\r\n self.label.place(x=x+10, y=y-10)\r\n\r\n#NoteBook tab change envent\r\ndef tab_change(event):\r\n index = event.widget.index('current')\r\n if index == 1:\r\n triggerChanged('')\r\n refTriggerChanged('')\r\n stt_tg_widgets[0].pack(fill=tk.BOTH)\r\n root.update()\r\n height = frame4.winfo_height()\r\n width = frame4.winfo_width()\r\n stt_tg_widgets[0].pack_forget()\r\n frame4.pack_propagate(False)\r\n frame4['height'] = height\r\n frame5.pack_propagate(False)\r\n frame5['height'] = height\r\n root.update()\r\n frame4.set_title()\r\n frame5.set_title()\r\n if acquisition_mode.get() == 'Continuous Samples':\r\n ref_TgOptions['state'] = tk.DISABLED\r\n ref_trigger_type.set('')\r\n refTriggerChanged('')\r\n # print(ref_tg_widgets[4]['state'])\r\n else:\r\n ref_TgOptions['state'] = tk.NORMAL\r\n elif index == 2:\r\n frame6.set_title()\r\n frame7.set_title()\r\n elif index == 3:\r\n frame8.set_title()\r\n enable_logging()\r\n\r\ntab_parent = ttk.Notebook(root)\r\ntab_parent.bind('<>', tab_change)\r\n# ttk.Style().configure('')\r\n\r\ntab1 = tk.Frame(tab_parent)\r\ntab2 = tk.Frame(tab_parent)\r\ntab3 = tk.Frame(tab_parent)\r\ntab4 = tk.Frame(tab_parent)\r\n\r\ntab_parent.add(tab1, text='Configuration')\r\ntab_parent.add(tab2, text='Triggering')\r\ntab_parent.add(tab3, text='Advanced Timing')\r\ntab_parent.add(tab4, text='Logging')\r\n\r\ntab_parent.pack()\r\n\r\n# Run Task Button\r\nrun_frame = tk.Frame(root, padx=20, pady=10)\r\nrun_frame.pack(fill=tk.BOTH)\r\ntk.Button(run_frame, text='Run', width=10, command=run).pack(side='right')\r\n\r\n'''tab1 - Configuration Tab'''\r\nframe1 = BDFrame(tab1, 'Channel Settings')\r\nframe1.pack()\r\ncs_frame = tk.Frame(frame1)\r\ncs_frame.pack(padx=10, pady=10, fill=tk.BOTH)\r\nframe2 = BDFrame(tab1, 'Timing Settings')\r\nframe2.pack()\r\nts_frame = tk.Frame(frame2)\r\nts_frame.pack(padx=10, pady=10)\r\n\r\n#Channel Setting Frame\r\nclist = tk.Frame(cs_frame)\r\nclist.pack(side=tk.LEFT)\r\n\r\n### Add channel function\r\ndef add_channel():\r\n def add_function():\r\n channel_name = '{}/{}'.format(device_name.get(), dev_channel.get())\r\n if Channel.find(channel_name) == None:\r\n channel = Channel(name=channel_name)\r\n channel_list.append(channel_name)\r\n channel_list.sort()\r\n lb.delete(0, tk.END)\r\n lb.insert(tk.END, *channel_list)\r\n max_Input['textvariable'] = channel.max_InputRange\r\n min_Input['textvariable'] = channel.min_InputRange\r\n add_window = tk.Toplevel(root)\r\n tk.Label(add_window, text='Device Name:').pack()\r\n device_name = tk.StringVar(root, value='Dev3')\r\n tk.Entry(add_window, justify=tk.CENTER, textvariable=device_name).pack()\r\n tk.Label(add_window, text='Channel:').pack()\r\n dev_channel = tk.StringVar(root, value='ai0')\r\n channels_numbers = ['ai{}'.format(str(i)) for i in range(10)]\r\n tk.OptionMenu(add_window, dev_channel, *channels_numbers).pack()\r\n tk.Button(add_window, text='add channel', command=add_function).pack()\r\n\r\ntk.Button(clist, text='Add', command=add_channel).grid(row=0, column=0, sticky='we')\r\n### Remove channel function\r\ndef remove_channel():\r\n index = lb.curselection()[0]\r\n name = channel_list.pop(index)\r\n Channel.remove(name)\r\n lb.delete(0, tk.END)\r\n lb.insert(tk.END, *channel_list)\r\n\r\ntk.Button(clist, text='Rem', command=remove_channel).grid(row=0, column=1, sticky='we')\r\n### selecting a channel\r\ndef select_channel(event):\r\n if len(lb.curselection()) > 0:\r\n index = lb.curselection()[0]\r\n channel_name = channel_list[index]\r\n channel = Channel.find(channel_name)\r\n max_Input['textvariable'] = channel.max_InputRange\r\n min_Input['textvariable'] = channel.min_InputRange\r\n root.update()\r\n\r\nlb = tk.Listbox(clist)\r\nlb.bind('<>', select_channel)\r\nlb.grid(row=1, column=0, columnspan=4)\r\n\r\ncsetup = tk.Frame(cs_frame)\r\ncsetup.pack(side=tk.LEFT, expand=True, fill=tk.BOTH)\r\ntk.Label(csetup, text='Voltage Input Setup', font=('Helvetica',14), anchor='w').pack(side=tk.TOP, fill=tk.BOTH)\r\nvoltage_IS = ttk.Notebook(csetup)\r\n\r\nsetting_tab = tk.Frame(voltage_IS)\r\ncalibration_tab = tk.Frame(voltage_IS)\r\n\r\nvoltage_IS.add(setting_tab, text='Settings')\r\nvoltage_IS.add(calibration_tab, text='Calibration')\r\n\r\nvoltage_IS.pack(side=tk.TOP, expand=True, fill=tk.BOTH)\r\n\r\nframe3 = BDFrame(setting_tab, 'Signal Input Range')\r\nframe3.pack()\r\nSIRange_frame = tk.Frame(frame3)\r\nSIRange_frame.pack(padx=10, pady=10, fill=tk.BOTH)\r\ntk.Label(SIRange_frame, text='Max').grid()\r\ntk.Label(SIRange_frame, text='Min').grid()\r\nmax_Input = tk.Entry(SIRange_frame, width=10, justify='right', textvariable=max_InputRange)\r\nmax_Input.grid(row=0, column=1, pady=5)\r\nmin_Input = tk.Entry(SIRange_frame, width=10, justify='right', textvariable=min_InputRange)\r\nmin_Input.grid(row=1, column=1)\r\n\r\n#Time Setting Frame\r\ntk.Label(ts_frame, text='Acquisition Mode', anchor='w').grid(row=0, column=0, padx=5, sticky='we')\r\ntk.Label(ts_frame, text='Sample to Read', anchor='w').grid(row=0, column=1, padx=5, sticky='we')\r\ntk.Label(ts_frame, text='Rate (Hz)', anchor='w').grid(row=0, column=2, padx=5, sticky='we')\r\n\r\naquisition_options = ['1 Sample (On Demand)', '1 Sample (HW Timed)', 'N Samples', 'Continuous Samples']\r\nAqOptions = tk.OptionMenu(ts_frame, acquisition_mode, *aquisition_options)\r\nAqOptions.config(width=25)\r\nAqOptions.grid(row=1, column=0, padx=5)\r\n\r\ntk.Entry(ts_frame, textvariable=samples_to_read, justify='right').grid(row=1, column=1, padx=5, sticky='we')\r\ntk.Entry(ts_frame, textvariable=rate, justify='right').grid(row=1, column=2, padx=5, sticky='we')\r\n\r\nframe1.set_title()\r\nframe2.set_title()\r\nframe3.set_title()\r\n\r\n\r\n'''tab2 - Triggering Tab'''\r\nframe4 = BDFrame(tab2, 'Start Trigger')\r\nframe4.pack()\r\nst_frame = tk.Frame(frame4)\r\nst_frame.pack(padx=10, pady=10, fill=tk.BOTH)\r\n\r\nframe5 = BDFrame(tab2, 'Reference Trigger')\r\nframe5.pack()\r\nrt_frame = tk.Frame(frame5)\r\nrt_frame.pack(padx=10, pady=10, fill=tk.BOTH)\r\n\r\n# Start Trigger Frame\r\ndef triggerChanged(event):\r\n global stt_tg_widgets\r\n new_choices = ['APFI0', 'APFI1'] + channel_list\r\n source = stt_trigger_source.get()\r\n for widget in stt_tg_widgets:\r\n widget.pack_forget()\r\n widget.grid_remove()\r\n if stt_trigger_type.get() != '':\r\n stt_tg_widgets[3].grid(row=0, column=1, padx=5, sticky='we')\r\n stt_trigger_source.set('APFI0')\r\n stt_tg_widgets[4].grid(row=1, column=1, padx=5, sticky='we')\r\n if stt_trigger_type.get() == 'Analog Edge':\r\n stt_tg_widgets[0].pack(fill=tk.BOTH)\r\n elif stt_trigger_type.get() == 'Analog Window':\r\n stt_tg_widgets[1].pack(fill=tk.BOTH)\r\n elif stt_trigger_type.get() == 'Digital Edge':\r\n stt_trigger_source.set('PFI0')\r\n stt_tg_widgets[2].pack(fill=tk.BOTH)\r\n new_choices = ['PFI{}'.format(i) for i in range(16)]\r\n stt_tg_widgets[4]['menu'].delete(0, 'end')\r\n for choice in new_choices:\r\n stt_tg_widgets[4]['menu'].add_command(label=choice, command=tk._setit(stt_trigger_source, choice))\r\n if source in new_choices:\r\n stt_trigger_source.set(source)\r\n\r\nstt_tgType_frame = tk.Frame(st_frame)\r\nstt_tgType_frame.pack(fill=tk.BOTH)\r\ntk.Label(stt_tgType_frame, text='Trigger Type', anchor='w').grid(row=0, column=0, padx=5, sticky='we')\r\ntg_options = ['', 'Analog Edge', 'Analog Window', 'Digital Edge']\r\nTgOptions = tk.OptionMenu(stt_tgType_frame, stt_trigger_type, *tg_options, command=triggerChanged)\r\nTgOptions.config(width=15)\r\nTgOptions.grid(row=1, column=0, padx=5, sticky='we')\r\n\r\nstt_tg_widgets = [tk.Frame(st_frame) for i in range(3)]\r\nstt_tg_widgets.append(tk.Label(stt_tgType_frame, text='Trigger Source', anchor='w'))\r\nstt_tg_widgets.append(tk.OptionMenu(stt_tgType_frame, stt_trigger_source, 'APFI0', 'APFI1'))\r\nstt_tg_widgets[-1].config(width=21)\r\n\r\n## Analog Edge\r\ntk.Label(stt_tg_widgets[0], text='Slope', anchor='w').grid(row=0, column=0, padx=5, sticky='we')\r\nslope_menu = tk.OptionMenu(stt_tg_widgets[0], stt_trigger_slope, 'Rising', 'Falling')\r\nslope_menu.config(width=11)\r\nslope_menu.grid(row=1, column=0, padx=5, sticky='we')\r\ntk.Label(stt_tg_widgets[0], text='Level', anchor='w').grid(row=0, column=1, padx=5, sticky='we')\r\ntk.Entry(stt_tg_widgets[0], textvariable=stt_trigger_level, justify='right', width=15).grid(row=1, column=1, padx=5, sticky='we')\r\n## Analog Window\r\ntk.Label(stt_tg_widgets[1], text='Window Top', anchor='w').grid(row=0, column=0, padx=5, sticky='we')\r\ntk.Entry(stt_tg_widgets[1], textvariable=stt_window_top, justify='right').grid(row=1, column=0, padx=5, sticky='we')\r\ntk.Label(stt_tg_widgets[1], text='Window Bottom', anchor='w').grid(row=0, column=1, padx=5, sticky='we')\r\ntk.Entry(stt_tg_widgets[1], textvariable=stt_window_bot, justify='right').grid(row=1, column=1, padx=5, sticky='we')\r\ntk.Label(stt_tg_widgets[1], text='Trigger Condition', anchor='w').grid(row=0, column=2, padx=5, sticky='we')\r\ncondition_menu = tk.OptionMenu(stt_tg_widgets[1], stt_trigger_condition, 'Entering Window', 'Leaving Window')\r\ncondition_menu.config(width=25)\r\ncondition_menu.grid(row=1, column=2, padx=5, sticky='we')\r\n\r\n## Digital Edge\r\ntk.Label(stt_tg_widgets[2], text='Slope', anchor='w').grid(row=0, column=0, padx=5, sticky='we')\r\nedge_menu = tk.OptionMenu(stt_tg_widgets[2], stt_trigger_edge, 'Rising', 'Falling')\r\nedge_menu.config(width=11)\r\nedge_menu.grid(row=1, column=0, padx=5, sticky='we')\r\n\r\n\r\n# ref Trigger Frame\r\ndef refTriggerChanged(event):\r\n global ref_tg_widgets\r\n new_choices = ['APFI0', 'APFI1'] + channel_list\r\n source = ref_trigger_source.get()\r\n for widget in ref_tg_widgets:\r\n widget.pack_forget()\r\n widget.grid_remove()\r\n if ref_trigger_type.get() != '':\r\n ref_tg_widgets[3].grid(row=0, column=1, padx=5, sticky='we')\r\n ref_trigger_source.set('APFI0')\r\n ref_tg_widgets[4].grid(row=1, column=1, padx=5, sticky='we')\r\n ref_tg_widgets[5].grid(row=0, column=2, padx=5, sticky='we')\r\n ref_tg_widgets[6].grid(row=1, column=2, padx=5, sticky='we')\r\n if ref_trigger_type.get() == 'Analog Edge':\r\n ref_tg_widgets[0].pack(fill=tk.BOTH)\r\n elif ref_trigger_type.get() == 'Analog Window':\r\n ref_tg_widgets[1].pack(fill=tk.BOTH)\r\n elif ref_trigger_type.get() == 'Digital Edge':\r\n ref_trigger_source.set('PFI0')\r\n ref_tg_widgets[2].pack(fill=tk.BOTH)\r\n new_choices = ['PFI{}'.format(i) for i in range(16)]\r\n ref_tg_widgets[4]['menu'].delete(0, 'end')\r\n for choice in new_choices:\r\n ref_tg_widgets[4]['menu'].add_command(label=choice, command=tk._setit(ref_trigger_source, choice))\r\n if source in new_choices:\r\n ref_trigger_source.set(source)\r\n\r\nref_tgType_frame = tk.Frame(rt_frame)\r\nref_tgType_frame.pack(fill=tk.BOTH)\r\ntk.Label(ref_tgType_frame, text='Trigger Type', anchor='w').grid(row=0, column=0, padx=5, sticky='we')\r\nref_TgOptions = tk.OptionMenu(ref_tgType_frame, ref_trigger_type, *tg_options, command=refTriggerChanged)\r\nref_TgOptions.config(width=15)\r\nref_TgOptions.grid(row=1, column=0, padx=5, sticky='we')\r\n\r\nref_tg_widgets = [tk.Frame(rt_frame) for i in range(3)]\r\nref_tg_widgets.append(tk.Label(ref_tgType_frame, text='Trigger Source', anchor='w'))\r\nref_tg_widgets.append(tk.OptionMenu(ref_tgType_frame, ref_trigger_source, 'APFI0', 'APFI1', 'Voltage'))\r\nref_tg_widgets[-1].config(width=21)\r\nref_tg_widgets.append(tk.Label(ref_tgType_frame, text='Pre-Trigger Samples', anchor='w'))\r\nref_tg_widgets.append(tk.Entry(ref_tgType_frame, textvariable=preTriggerSamples))\r\n\r\n## Analog Edge\r\ntk.Label(ref_tg_widgets[0], text='Slope', anchor='w').grid(row=0, column=0, padx=5, sticky='we')\r\nref_slope_menu = tk.OptionMenu(ref_tg_widgets[0], ref_trigger_slope, 'Rising', 'Falling')\r\nref_slope_menu.config(width=11)\r\nref_slope_menu.grid(row=1, column=0, padx=5, sticky='we')\r\ntk.Label(ref_tg_widgets[0], text='Level', anchor='w').grid(row=0, column=1, padx=5, sticky='we')\r\ntk.Entry(ref_tg_widgets[0], textvariable=ref_trigger_level, justify='right', width=15).grid(row=1, column=1, padx=5, sticky='we')\r\n## Analog Window\r\ntk.Label(ref_tg_widgets[1], text='Window Top', anchor='w').grid(row=0, column=0, padx=5, sticky='we')\r\ntk.Entry(ref_tg_widgets[1], textvariable=ref_window_top, justify='right').grid(row=1, column=0, padx=5, sticky='we')\r\ntk.Label(ref_tg_widgets[1], text='Window Bottom', anchor='w').grid(row=0, column=1, padx=5, sticky='we')\r\ntk.Entry(ref_tg_widgets[1], textvariable=ref_window_bot, justify='right').grid(row=1, column=1, padx=5, sticky='we')\r\ntk.Label(ref_tg_widgets[1], text='Trigger Condition', anchor='w').grid(row=0, column=2, padx=5, sticky='we')\r\nref_condition_menu = tk.OptionMenu(ref_tg_widgets[1], ref_trigger_condition, 'Entering Window', 'Leaving Window')\r\nref_condition_menu.config(width=25)\r\nref_condition_menu.grid(row=1, column=2, padx=5, sticky='we')\r\n\r\n## Digital Edge\r\ntk.Label(ref_tg_widgets[2], text='Slope', anchor='w').grid(row=0, column=0, padx=5, sticky='we')\r\nref_edge_menu = tk.OptionMenu(ref_tg_widgets[2], ref_trigger_edge, 'Rising', 'Falling')\r\nref_edge_menu.config(width=11)\r\nref_edge_menu.grid(row=1, column=0, padx=5, sticky='we')\r\n\r\n'''tab3 - Advanced Timing Tab'''\r\nframe6 = BDFrame(tab3, 'Sample Clock Settings')\r\nframe6.pack()\r\nscs_frame = tk.Frame(frame6)\r\nscs_frame.pack(padx=10, pady=10, fill=tk.BOTH)\r\nframe7 = BDFrame(tab3, 'Additional Time Settings')\r\nframe7.pack()\r\nats_frame = tk.Frame(frame7)\r\nats_frame.pack(padx=10, pady=10, fill=tk.BOTH)\r\n\r\ntk.Label(scs_frame, text='Sample Clock Type', anchor='w').grid(row=0, column=0, padx=5, sticky='we')\r\nclock_type = tk.StringVar(root, value='Internal')\r\nclockType_menu = tk.OptionMenu(scs_frame, clock_type, 'Internal')\r\nclockType_menu.config(width=11)\r\nclockType_menu.grid(row=1, column=0, padx=5, sticky='we')\r\n\r\ntk.Label(scs_frame, text='Clock Source', anchor='w').grid(row=2, column=0, padx=5, sticky='we')\r\nclock_source = tk.StringVar(root, value='PFI0')\r\nclockSource_menu = tk.OptionMenu(scs_frame, clock_source, 'PFI0')\r\nclockSource_menu.config(width=19, state=tk.DISABLED)\r\nclockSource_menu.grid(row=3, column=0, columnspan=2, padx=5, sticky='we')\r\n\r\ntk.Label(scs_frame, text='Active Edge', anchor='w').grid(row=2, column=2, padx=5, sticky='we')\r\nclock_type = tk.StringVar(root, value='Falling')\r\nclockType_menu = tk.OptionMenu(scs_frame, clock_type, 'Rising', 'Falling')\r\nclockType_menu.config(width=11, state=tk.DISABLED)\r\nclockType_menu.grid(row=3, column=2, padx=5, sticky='we')\r\n\r\ntk.Label(ats_frame, text='Timeout (s)', anchor='w').grid(padx=5, sticky='w')\r\nttk.Spinbox(ats_frame, from_=-1, to=10000, textvariable=timeout, width=10, justify='right').grid(padx=5, sticky='w')\r\n\r\n'''tab4 - Logging Tab'''\r\nframe8 = BDFrame(tab4, 'TDMS File Logging')\r\nframe8.pack()\r\ntdms_frame = tk.Frame(frame8)\r\ntdms_frame.pack(padx=10, pady=10, fill=tk.BOTH)\r\n\r\ndef enable_logging():\r\n if TDMSLogging.get() == 1:\r\n for widget in file_frame.winfo_children():\r\n try:\r\n widget.config(state=tk.NORMAL)\r\n except:\r\n pass\r\n span_files_function()\r\n else:\r\n for widget in file_frame.winfo_children():\r\n try:\r\n widget.config(state=tk.DISABLED)\r\n except:\r\n pass\r\n spanEntry['state'] = tk.DISABLED\r\n spanLabel['state'] = tk.DISABLED\r\n \r\n\r\ntk.Checkbutton(tdms_frame, text='Enable TDMS Logging', var=TDMSLogging, command=enable_logging, anchor='w').pack(padx=5, fill=tk.BOTH)\r\n\r\nfile_frame = tk.Frame(tdms_frame, highlightbackground='light steel blue', highlightcolor='light steel blue', highlightthickness=1)\r\nfile_frame.pack(padx=5, pady=5, ipady=5, fill=tk.BOTH)\r\n\r\ndef search_file():\r\n TDMS_filepath.set(filedialog.asksaveasfilename(title = 'Select file', \r\n filetypes = (('TDMS files','*.tdms'),\r\n ('TDM files','*.tdm'),\r\n ('all files','*.*')\r\n )))\r\ntk.Label(file_frame, text='File Path', anchor='w').grid(padx=5, sticky='we')\r\ntk.Entry(file_frame, textvariable=TDMS_filepath).grid(padx=5, sticky='we')\r\ntk.Button(file_frame, text='Search', command=search_file).grid(row=1, column=1)\r\ntk.Checkbutton(file_frame, text='Append data if file exists', variable=append).grid(padx=5, sticky='w')\r\n\r\ntk.Label(file_frame, text='Logging Mode', anchor='w').grid(padx=5, sticky='we')\r\nlogginMode_menu = tk.OptionMenu(file_frame, logging_mode, 'Log and Read', 'Log Only')\r\nlogginMode_menu.config(width=11)\r\nlogginMode_menu.grid(padx=5, sticky='we')\r\n\r\ndef span_files_function():\r\n if not span.get():\r\n spanEntry['state'] = tk.DISABLED\r\n spanLabel['state'] = tk.DISABLED\r\n else:\r\n spanEntry['state'] = tk.NORMAL\r\n spanLabel['state'] = tk.NORMAL\r\ntk.Label(file_frame, text='Group Name', anchor='w').grid(padx=5, sticky='we')\r\ntk.Entry(file_frame, textvariable=group_name).grid(padx=5, sticky='we')\r\ntk.Checkbutton(file_frame, text='Span multiple files', variable=span, command=span_files_function).grid(padx=5, sticky='w')\r\nsmf_frame = tk.Frame(file_frame)\r\nsmf_frame.grid(padx=30)\r\nspanLabel = tk.Label(smf_frame, text='Samples Per File', anchor='w')\r\nspanLabel.grid(sticky='we')\r\nspanEntry = tk.Entry(smf_frame, textvariable=sample_per_file)\r\nspanEntry.grid(sticky='we')\r\n\r\ndef variables_list():\r\n variables = [\r\n acquisition_mode,\r\n samples_to_read,\r\n rate,\r\n #Start Trigger\r\n stt_trigger_source,\r\n stt_trigger_type,\r\n stt_trigger_slope,\r\n stt_trigger_level,\r\n stt_window_top,\r\n stt_window_bot,\r\n stt_trigger_condition,\r\n stt_trigger_edge,\r\n #Reference Trigger\r\n ref_trigger_source,\r\n ref_trigger_type,\r\n ref_trigger_slope,\r\n ref_trigger_level,\r\n ref_window_top,\r\n ref_window_bot,\r\n ref_trigger_condition,\r\n ref_trigger_edge,\r\n preTriggerSamples,\r\n ## Advanced Timing Variables\r\n timeout,\r\n ##Logging Variables\r\n TDMSLogging,\r\n TDMS_filepath,\r\n append,\r\n logging_mode,\r\n group_name,\r\n sample_per_file,\r\n span]\r\n return variables\r\n\r\ndef save_task():\r\n path = filedialog.asksaveasfilename(title = 'Select file', defaultextension='.task',\r\n filetypes = (('task','*.task'),('all files','*.*')))\r\n file = open(path, 'w')\r\n variables = list(map(lambda x: str(x.get()), variables_list()))\r\n file.write('\\n'.join(variables) + '\\n')\r\n file.write(Channel.channelsInTask.__repr__())\r\n file.close()\r\n\r\ndef open_task():\r\n global channel_list\r\n variables = variables_list()\r\n path=filedialog.askopenfilename(title = 'Select file', \r\n filetypes = (('task','*.task'),('all files','*.*')))\r\n file = open(path, 'r')\r\n for variable in variables_list():\r\n variable.set(file.readline().replace('\\n',''))\r\n channels = file.readline().replace(\"'\",'\"')\r\n file.close()\r\n channel_list = []\r\n Channel.channelsInTask = []\r\n Channel.channels_import(json.loads(channels))\r\n for channel in Channel.channelsInTask:\r\n channel_list.append(channel.name)\r\n channel_list.sort()\r\n print(channel_list)\r\n lb.delete(0, tk.END)\r\n lb.insert(tk.END, *channel_list)\r\n max_InputRange.set('')\r\n min_InputRange.set('')\r\n\r\n''' Menu '''\r\nmenubar = tk.Menu(root)\r\nroot.config(menu=menubar)\r\n\r\nfilemenu = tk.Menu(menubar, tearoff=0)\r\nfilemenu.add_command(label = 'Save Task', command = save_task)\r\nfilemenu.add_command(label = 'Open Task', command = open_task)\r\nfilemenu.add_command(label = 'Exit', command = root.destroy)\r\nmenubar.add_cascade(label = 'File', menu = filemenu)\r\n\r\nroot.mainloop()","sub_path":"VoltageTaskControl.py","file_name":"VoltageTaskControl.py","file_ext":"py","file_size_in_byte":29220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"482461497","text":"#this code searchs, how many people comes from different countries\n\n#learner_id country in_course unit avg_score completion inv_rate\nimport sqlite3\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pie_chart\n\n\n\nconn = sqlite3.connect('PearsonData.db')\ncur = conn.cursor() \ncountry = []\npeople = []\nothers = 0\n\n#Give me distinct country\ncur.execute(\"\"\"SELECT \n DISTINCT\n country FROM data2018\n ORDER BY country\"\"\")\ndistinct_country = cur.fetchall()\nif distinct_country[0] == ('',): distinct_country = distinct_country[1:]\n\n\n#Search for number of people from cuntry X\n#If number < 200 add this to others\nfor x in distinct_country:\n cur.execute(\"\"\"SELECT COUNT(*) \n FROM (SELECT \n DISTINCT learner_id\n FROM data2018 \n WHERE country=(?))\"\"\", (x) )\n how_many = cur.fetchall()\n if how_many[0][0] < 200:\n others += how_many[0][0]\n continue\n country.append(x[0])\n people.append(how_many[0][0])\ncountry.append('Others')\npeople.append(others)\n\n\n\nfor x in range(len(country)): \n print(country[x], people[x])\npie_chart.pie_chart(tuple(country),people)\n","sub_path":"python_codes/People-I-country.py","file_name":"People-I-country.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"126047648","text":"# YARE wrapper without command line arguments\n\nfrom os import listdir, path, makedirs\nfrom pathlib import PurePath\nimport sys\nimport app\n\n\ndef main():\n cwd = path.realpath(path.dirname(__file__))\n\n print(\"Searching for RGSSAD files in \" + cwd)\n\n FileList = []\n Ind = 0\n\n for File in listdir(cwd):\n if File.endswith(('.rgssad', '.rgss2a', '.rgss3a')):\n Ind += 1\n print(\"#{} : {}\".format(Ind, File))\n FileList.append(PurePath(cwd, File))\n\n if not FileList:\n raise IOError(\"No RGSSAD files found\")\n\n ChosenOne = input(\"Please choose the file from the list above or ESC to exit\\r\\n\")\n if not ChosenOne:\n raise ValueError(\"I asked you nicely to choose the file\")\n if ChosenOne == \"ESC\":\n print(\"Got it, shutting down\")\n sys.exit()\n try:\n ChosenOne = int(ChosenOne) - 1\n except ValueError:\n raise ValueError(\"Whatever you typed is not a number\")\n if ChosenOne not in range(0, len(FileList)):\n raise ValueError(\"This number is not on the list\")\n #if ChosenOne < 0:\n #raise ValueError(\"This number is too small\")\n ChosenOne = FileList[ChosenOne]\n RGSSAD = create(ChosenOne)\n print(\"Chosen One, you overcame may trials, now you may become analyzed\")\n\n verbose = input(\"Should I go verbose? (Y/n)\\r\\n\")\n\n outPath = \"Extracted\"\n question = input(\"One more thing: do you want specify extraction destination? (Y/n)\\r\\n\")\n if question.lower() == \"y\":\n outPath = input(\"Type the folder name: \")\n else:\n input(\"Okay, I will put the data into 'Extracted' subfolder. Press Enter to continue or Ctrl+C to exit.\")\n\n outPath = PurePath(cwd, outPath) # Ultimate solution\n if not path.exists(outPath):\n if not input(\"Seems like the output folder doesn't exist. Continue? (Y/n) \").lower() == \"y\":\n sys.exit()\n \n try:\n makedirs(outPath, exist_ok = True)\n except OSError:\n if input(\"I can't create an output directory at {}. Continue with default? (Y/n) \".format(outPath)).lower() == \"y\":\n outPath = PurePath(cwd, \"Exctracted\")\n else:\n sys.exit()\n\n print(\"So it's settled then. Processing {}, with output to {}\".format(ChosenOne, outPath))\n del FileList\n\n RGSSAD.read(verbose.upper()) # since it's really the only version where it can be Y or y\n RGSSAD.DecryptFiles(outPath)\n print(\"\\r\\nJob's done.\")\n\n\ndef create(filePath):\n tmp = open(filePath, \"rb\")\n data = tmp.read(8)\n size = tmp.seek(0, 2)\n tmp.close()\n if data[0:6].decode('ASCII') == \"RGSSAD\":\n if data[7] == 1:\n return app.RGSSADv1.RGSSADv1(filePath, size)\n if data[7] == 3:\n return app.RGSSADv3.RGSSADv3(filePath, size)\n raise IOError(\"Headers look wrong, are you sure that's valid RGSSAD?\")\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except Exception as e:\n print(str(e))\n sys.exit()\n","sub_path":"app-prompt.py","file_name":"app-prompt.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"177911557","text":"import csv\nimport subprocess,multiprocessing\nimport sys\nimport pandas as pd\nimport time\nimport pymysql\nimport pickle\n\nimport numpy as np\nimport pandas as pd\nimport pickle\ndef map2major5(df):\n d = {\n 'normal.': 0,\n 'ipsweep.': 1,\n 'mscan.': 1,\n 'nmap.': 1,\n 'portsweep.': 1,\n 'saint.': 1,\n 'satan.': 1,\n 'apache2.': 1,\n 'back.': 1,\n 'mailbomb.': 1,\n 'neptune.': 1,\n 'pod.': 1,\n 'land.': 1,\n 'processtable.': 1,\n 'smurf.': 1,\n 'teardrop.': 1,\n 'udpstorm.': 1,\n 'buffer_overflow.': 1,\n 'loadmodule.': 1,\n 'perl.': 1,\n 'ps.': 1,\n 'rootkit.': 1,\n 'sqlattack.': 1,\n 'xterm.': 1,\n 'ftp_write.': 1,\n 'guess_passwd.': 1,\n 'httptunnel.': 1, # disputation resolved\n 'imap.': 1,\n 'multihop.': 1, # disputation resolved\n 'named.': 1,\n 'phf.': 1,\n 'sendmail.': 1,\n 'snmpgetattack.': 1,\n 'snmpguess.': 1,\n 'worm.': 1,\n 'xlock.': 1,\n 'xsnoop.': 1,\n 'spy.': 1,\n 'warezclient.': 1,\n 'warezmaster.': 1 # disputation resolved\n }\n\n # d = {\n # 'normal.': 0,\n # 'ipsweep.': 1,\n # 'mscan.': 1,\n # 'nmap.': 1,\n # 'portsweep.': 1,\n # 'saint.': 1,\n # 'satan.': 1,\n # 'apache2.': 2,\n # 'back.': 2,\n # 'mailbomb.': 2,\n # 'neptune.': 2,\n # 'pod.': 2,\n # 'land.': 2,\n # 'processtable.': 2,\n # 'smurf.': 2,\n # 'teardrop.': 2,\n # 'udpstorm.': 2,\n # 'buffer_overflow.': 3,\n # 'loadmodule.': 3,\n # 'perl.': 3,\n # 'ps.': 3,\n # 'rootkit.': 3,\n # 'sqlattack.': 3,\n # 'xterm.': 3,\n # 'ftp_write.': 4,\n # 'guess_passwd.': 4,\n # 'httptunnel.': 3, # disputation resolved\n # 'imap.': 4,\n # 'multihop.': 4, # disputation resolved\n # 'named.': 4,\n # 'phf.': 4,\n # 'sendmail.': 4,\n # 'snmpgetattack.': 4,\n # 'snmpguess.': 4,\n # 'worm.': 4,\n # 'xlock.': 4,\n # 'xsnoop.': 4,\n # 'spy.': 4,\n # 'warezclient.': 4,\n # 'warezmaster.': 4 # disputation resolved\n # }\n\n l = []\n for val in df['attack_type']:\n l.append(d[val])\n tmp_df = pd.DataFrame(l, columns=['attack_type'])\n df = df.drop('attack_type', axis=1)\n df = df.join(tmp_df)\n return df\n\n\ndef one_hot(df):\n service_one_hot = pd.get_dummies(df[\"service\"])\n df = df.drop('service', axis=1)\n df = df.join(service_one_hot)\n # test data has this column in service, clashes with protocol_type\n # and not seen in training data, won't be learn by the model, safely delete\n if 'icmp' in df.columns:\n df = df.drop('icmp', axis=1)\n\n protocol_type_one_hot = pd.get_dummies(df[\"protocol_type\"])\n df = df.drop('protocol_type', axis=1)\n df = df.join(protocol_type_one_hot)\n\n flag_type_one_hot = pd.get_dummies(df[\"flag\"])\n df = df.drop('flag', axis=1)\n df = df.join(flag_type_one_hot)\n return df\n\n\ndef merge_sparse_feature(df):\n df.loc[(df['service'] == 'ntp_u')\n | (df['service'] == 'urh_i')\n | (df['service'] == 'tftp_u')\n | (df['service'] == 'red_i')\n , 'service'] = 'normal_service_group'\n\n df.loc[(df['service'] == 'pm_dump')\n | (df['service'] == 'http_2784')\n | (df['service'] == 'harvest')\n | (df['service'] == 'aol')\n | (df['service'] == 'http_8001')\n , 'service'] = 'satan_service_group'\n return df\n\ndef make_test_df(path,id):\n __ATTR_NAMES = (\"duration\", # length (number of seconds) of the conn's\n \"protocol_type\", # symbolic, type of the protocol, e.g. tcp, udp, etc.\n \"service\", # symbolic, network service on the destination, e.g., http, telnet, etc.\n \"flag\", # symbolic, normal or error status of the conn\n \"src_bytes\", # number of data bytes from source to destination\n \"dst_bytes\", # number of data bytes from destination to source\n \"land\", # symbolic, 1 if conn is from/to the same host/port; 0 otherwise\n \"wrong_fragment\", # number of ''wrong'' fragments \n \"urgent\", # number of urgent packets\n # ----------\n # ----- Basic features of individual TCP conn's -----\n # ----------\n \"hot\", # number of ''hot'' indicators\n \"num_failed_logins\", # number of failed login attempts \n \"logged_in\", # symbolic, 1 if successfully logged in; 0 otherwise\n \"num_compromised\", # number of ''compromised'' conditions \n \"root_shell\", # 1 if root shell is obtained; 0 otherwise \n \"su_attempted\", # 1 if ''su root'' command attempted; 0 otherwise \n \"num_root\", # number of ''root'' accesses \n \"num_file_creations\", # number of file creation operations\n \"num_shells\", # number of shell prompts \n \"num_access_files\", # number of operations on access control files\n \"num_outbound_cmds\", # number of outbound commands in an ftp session \n \"is_host_login\", # symbolic, 1 if the login belongs to the ''hot'' list; 0 otherwise \n \"is_guest_login\", # symbolic, 1 if the login is a ''guest''login; 0 otherwise \n # ----------\n # ----- Content features within a conn suggested by domain knowledge -----\n # ----------\n \"count\", # number of conn's to the same host as the current conn in the past two seconds \n # Time-based Traffic Features (examine only the conn in the past two seconds):\n # 1. Same Host, have the same destination host as the current conn\n # 2. Same Service, have the same service as the current conn.\n \"srv_count\", # SH, number of conn's to the same service as the current conn\n \"serror_rate\", # SH, % of conn's that have SYN errors\n \"srv_serror_rate\", # SS, % of conn's that have SYN errors\n \"rerror_rate\", # SH, % of conn's that have REJ errors \n \"srv_rerror_rate\", # SS, % of conn's that have REJ errors \n \"same_srv_rate\", # SH, % of conn's to the same service \n \"diff_srv_rate\", # SH, % of conn's to different services \n \"srv_diff_host_rate\", # SH, % of conn's to different hosts \n # ----------\n # Host-base Traffic Features, constructed using a window of 100 conn's to the same host\n \"dst_host_count\",\n \"dst_host_srv_count\",\n \"dst_host_same_srv_rate\",\n \"dst_host_diff_srv_rate\",\n \"dst_host_same_src_port_rate\",\n \"dst_host_srv_diff_host_rate\",\n \"dst_host_serror_rate\",\n \"dst_host_srv_serror_rate\",\n \"dst_host_rerror_rate\",\n \"dst_host_srv_rerror_rate\",\n # ----------\n # category\n \"attack_type\"\n )\n\n # df = pd.read_csv(r'../data/4.csv', header=None, names=__ATTR_NAMES)\n df = pd.read_csv(path, header=None, names=__ATTR_NAMES)\n\n df.services = df.service.unique()\n df.flags = df.flag.unique()\n df.protocol_types = df.protocol_type.unique()\n df.attack_types = df.attack_type.unique()\n\n df = merge_sparse_feature(df) #合并稀疏特征\n df = one_hot(df)#独热编码\n\n with open(r'../data/selected_feat_names.pkl', 'rb') as f:\n selected_feat_names = pickle.load(f)\n for i in selected_feat_names:\n if i in df:\n print('ok')\n else:\n print(i)\n df[i] = '0'\n df.to_csv(path,header=None)\n # df = map2major5(df)#合并攻击类型\n\n# percentage check, to make sure the mapping is correct\n# print(df[df['attack_type'] == 0].shape[0] / df.shape[0])\n# print(df[df['attack_type'] == 1].shape[0] / df.shape[0])\n# print(df[df['attack_type'] == 2].shape[0] / df.shape[0])\n# print(df[df['attack_type'] == 3].shape[0] / df.shape[0])\n# print(df[df['attack_type'] == 4].shape[0] / df.shape[0])\n# f = open('.pkl'.format(id), 'wb')\n with open('{}.pkl'.format(id), 'wb') as f:\n pickle.dump(df, f)\n\ndef create_csv(path):\n with open(path,'wb') as f:\n csv_write = csv.writer(f)\ndef create_pkl(path):\n with open(path,'wb') as f:\n csv_write = csv.writer(f)\ndef write_csv(path,data):\n with open(path,'a+') as f:\n csv_write = csv.writer(f)\n data_row = data\n csv_write.writerow(data_row)\n\n\ndef RunShellWithReturnCode(command,print_output=True,universal_newlines=True,id=0):\n p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, universal_newlines=universal_newlines)\n n = 0\n if print_output:\n output_array = []\n path = '{}.csv'.format(id)\n create_csv(path)\n while True:\n # with open(r'../data/selected_feat_names.pkl', 'rb') as f:\n # selected_feat_names = pickle.load(f)\n line = p.stdout.readline().strip()\n if not line:\n break\n list1=line.split(',')\n print(list1)\n for i in range (0,13):\n list1.insert(9,'0')\n print(list1)\n str1=''.join(list1)#list to string\n print(str1)\n n = n+1\n write_csv(path,list1)\n print(n)\n if(n==1):\n make_test_df(path, id)\n with open('{}.pkl'.format(id), 'rb') as f:\n df = pickle.load(f)\n with open(r'../data/selected_feat_names.pkl', 'rb') as f:\n selected_feat_names = pickle.load(f)\n print(df)\n X = df[selected_feat_names].values\n print(\"data loaded\")\n\n time.sleep(1)\n n=0\n # print (line.strip(\"/n\"))\n # print(line)\n output_array.append(line)\n output =\"\".join(output_array)\n else:\n output = p.stdout.read()\n p.wait()\n errout = p.stderr.read()\n if print_output and errout:\n print >> sys.stderr, errout\n p.stdout.close()\n p.stderr.close()\n return output, p.returncode\n\np1 = multiprocessing.Process(target=RunShellWithReturnCode,args=('cd /home && cd .. &&./home/msi/Downloads/kdd99_feature_extractor-master/build-files/src/kdd99extractor -i 1',True,True,1))\n# p4 = multiprocessing.Process(target=RunShellWithReturnCode,args=('cd /home && cd .. &&./home/msi/Downloads/kdd99_feature_extractor-master/build-files/src/kdd99extractor -i 4',True,True,4))\n# p5 = multiprocessing.Process(target=RunShellWithReturnCode,args=('cd /home && cd .. &&./home/msi/Downloads/kdd99_feature_extractor-master/build-files/src/kdd99extractor -i 5',True,True,5))\n# p6 = multiprocessing.Process(target=RunShellWithReturnCode,args=('cd /home && cd .. &&./home/msi/Downloads/kdd99_feature_extractor-master/build-files/src/kdd99extractor -i 6',True,True,6))\n\np1.start()\n# p4.start()\n# p5.start()\n# p6.start()\nprint(\"The number of CPU is:\" + str(multiprocessing.cpu_count()))\nfor p in multiprocessing.active_children():\n print(\"child p.name:\" + p.name + \"\\tp.id\" + str(p.pid))\n\n# RunShellWithReturnCode('cd /home && cd .. &&./home/msi/Downloads/kdd99_feature_extractor-master/build-files/src/kdd99extractor -i 4')# centos7.0\n# RunShellWithReturnCode('cd /home && cd .. &&./home/msi/Downloads/kdd99_feature_extractor-master/build-files/src/kdd99extractor -i 5')# ubuntu1804\n# RunShellWithReturnCode('cd /home && cd .. &&./home/msi/Downloads/kdd99_feature_extractor-master/build-files/src/kdd99extractor -i 6')# win7\n","sub_path":"data/domaintokdd99.py","file_name":"domaintokdd99.py","file_ext":"py","file_size_in_byte":11929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"649967047","text":"#!/usr/bin/env python3\nimport sys\n\nn, m = map(int, sys.stdin.readline().strip().split())\narr = list(map(int, sys.stdin.readline().strip().split()))\n\ndef okay(mid):\n sm = 0\n for x in arr:\n sm += mid // x\n return sm >= m+1\n\nlo = 0\nhi = 1\nwhile not okay(hi):\n hi *= 2\n\nwhile lo <= hi:\n mid = (lo+hi)//2\n if okay(mid):\n res = mid\n hi = mid - 1\n else:\n lo = mid + 1\n\nprint(res)\n\n","sub_path":"2022/problems/almennirborgarar/submissions/accepted/bjarki_100.py","file_name":"bjarki_100.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"18862353","text":"#関数\r\ndef f(x):\r\n return x<10\r\n\r\nresult=f(2)\r\n\r\n#TrueのTは大文字で!\r\nif result==True:\r\n print(\"xは10未満\")\r\nelse:\r\n print(\"xは10以上\")\r\n\r\n#returnの部分をprintに変更しても同じ\r\ndef w(x,y,z):\r\n return x+y+z\r\n\r\n#関数定義にreturnがなかったら\r\ndef g():\r\n Z=1+1\r\n\r\n\r\n#組み込み関数\r\n#lenは文字列の長さを数字で返す関数(この状態で実行されないのはなぜ?)\r\nlen(\"aaa\")\r\n\r\n#上の物を実行するためにはprint(len(\"aaa\"))=>3\r\n#def lenで関数を作ると上書きされるので注意\r\n\r\n#str整数を文字列に変換\r\nstr(300)\r\n\r\n#intは文字列を整数に変換\r\nint(\"1\")\r\n\r\n#小数点以下を示すのはfloat(intだと2と表示される)\r\nfloat(\"2.0\")\r\n\r\n\r\n#「lenで変換したものは数値かどうか」を判別する関数\r\ndef g(x):\r\n a=str(x)\r\n b=len(a)\r\n return float(b)\r\n\r\n#inputはユーザーから情報を受け取る\r\nage=input(\"Enter your age:\")\r\nint_age=int(age)\r\nif int(int_age<=19):\r\n print(\"あなたは未成年です\")\r\nelse:\r\n print(\"あなたは成人しています\")\r\n\r\n#チャレンジ:上のプログラムのエラーを削除\r\n\r\n#関数の再利用(同じことを繰り返すときは関数を使おう!)\r\ndef even_odd(x):\r\n if x%2==0:\r\n print(\"偶数\")\r\n else:\r\n print(\"奇数\")\r\n\r\n#引数をあらかじめ定めておけば引数の欄が空欄でも大丈夫(引数がなければ2、あればその値に上書きされる。)\r\ndef f(x=2):\r\n return x*2\r\n\r\n#関数内のものをグローバル変数にするためには変数定義前にglobalを追加(global x)\r\nx=100\r\ndef t():\r\n global x\r\n x+=1\r\n print(x)\r\n\r\n#例外処理\r\nprint(\"これは1つ目の数字÷2つ目の数字を行うプログラムです。\")\r\n\r\n\r\n\r\n#userが0を入れる可能性を消す\r\n#try:の後には例外が発生するかもしれないが、実行したい処理\r\ntry:\r\n number_a=input(\"1つ目の数字を入力して下さい:\")\r\n int_number_a=int(number_a)\r\n number_b=input(\"2つ目の数字を入力して下さい:\") \r\n int_number_b=int(number_b)\r\n\r\n print(int_number_a/int_number_b)\r\n\r\n#exceptの後には起きうるエラー(2つある場合はまとめて()で書ける。と起きた場合の処理を記入\r\nexcept ZeroDivisionError:\r\n print(\"2番目の数字に0が入力されています。\")\r\nexcept ValueError: \r\n print(\"数字の入力をお願いします\")\r\n\r\n#ドキュメンテーション(関数定義の次の行に\"\"\"��わりに\"\"\")は関数に関するコメントのようなもの\r\ndef add(x,y):\r\n \"\"\"\r\n Returns x+y.\r\n :param x:int.\r\n :param y:int.\r\n :return: int sum of x and y.\r\n \"\"\"\r\n return x+y\r\n","sub_path":"4章関数.py","file_name":"4章関数.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"558978457","text":"#!/usr/bin/env python3\nimport requests\nimport time\nimport json\nimport os\nimport sys\nfrom datetime import datetime\nfrom pyfcm import FCMNotification\n\npush_service = FCMNotification(\n api_key=\"AAAAOL_f7Vw:APA91bHx4r3FM3rH2RxU2JtjoMRMm8At-c9XGrUnxpp6BCHtQLup1uvjAzIifOBAMMqCDOi_Z0O6wgqYGMtVJdt4EUdVzBXiUmpP_kTJRWB_9TmJBTp2II3tELBvSBhQvxMZxxLYP_Xu\")\nregistration_ids = [\n # \"dSvcsDop4ek:APA91bFcfxJak8NLbyxjpXavu3RLbf28jNLRRcAcTTN7_dzg-MS8rzN3uRsPvMgpmPNvpJCaRIFMOliUDX169uf3cH2V7isYYMa0F6Hn5VZRunVhz_ZJBUot5m9V2HotGtbBxtAULUvM\",\n \"fg09UzZglnc:APA91bHThBBv5LA-VmM3xrU1NkfCMqyZ5cR9_50PoiG_MNXpmJdoQ2XhX2s9hiFFQZnHirwLq032YH0HaTy_EBBX7YfKwiUr1disox8had4zU9Lo1DO9KP1PiExiYP9cMCd6LSNLdmP9\"\n]\nheaders = {\n 'User-Agent': 'Mozilla/51.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}\n\nnames = sys.argv[1::]\noldStates = {name: False for name in names} # False means offline\n\nwhile True:\n try:\n dcData = requests.get(\n \"https://discordapp.com/api/guilds/486990202154254376/embed.json\", headers=headers).text # link is under server settings widgets or similar\n dc = json.loads(dcData)\n on = [x['username'] for x in dc['members']]\n states = {name: name in on for name in names}\n for name in names:\n if states[name] != oldStates[name]: # if online state changed\n try:\n message_title = '[' + \\\n datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")+']'\n message_body = name\n message_body += \" geht on\" if not oldStates[name] else \" geht off\"\n result = push_service.notify_multiple_devices(\n registration_ids=registration_ids, message_title=message_title, message_body=message_body)\n print('['+datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\") +\n '] Online Message gesendet', flush=True)\n\n except Exception as e:\n print('['+datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\") +\n '] Online Message failed because of \\n'+str(e)+'\\n', flush=True)\n oldStates[name] = states[name]\n time.sleep(250)\n except KeyboardInterrupt:\n exit()\n\n except Exception as e:\n try:\n message_title = '[' + \\\n datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")+']'\n message_body = str(e)\n result = push_service.notify_multiple_devices(\n registration_ids=registration_ids, message_title=message_title, message_body=message_body)\n print('['+datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\") +\n '] Fehler Message gesendet für \\n'+str(e)+'\\n', flush=True)\n\n except Exception as e2:\n print('['+datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\") +\n '] Fehler Message failed because of \\n'+str(e2)+' für \\n'+str(e)+'\\n', flush=True)\n\n time.sleep(600)\n","sub_path":"python/discord/isonMulti.py","file_name":"isonMulti.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"181600707","text":"import datetime\r\nfrom enum import IntEnum\r\nimport os\r\nimport pymssql\r\nimport traceback\r\n\r\nfrom sql_connection_manager import SqlConnectionManager\r\nfrom vaccine_caregiver import VaccineCaregiver\r\nfrom enums import *\r\nfrom utils import *\r\nfrom COVID19_vaccine import COVID19Vaccine as covid\r\nfrom VaccinePatient import VaccinePatient as pat\r\n\r\n\r\nclass VaccineReservationScheduler:\r\n\r\n def __init__(self):\r\n return\r\n \r\n def ScheduleProcess(self, read_cursor, action_cursor, PatientId, Date, DateUpper='99-99-9999', Vaccine='Pfizer', TimeLower='00:00:00', TimeUpper='23:59:59'):\r\n '''\r\n Full process for scheduling a vaccine appointment. \r\n '''\r\n # put hold on slot of Caregiver Scheduler \r\n slotid = self.PutHoldOnAppointmentSlot(read_cursor, action_cursor, Date, DateUpper, TimeLower, TimeUpper) \r\n patient = pat()\r\n #check for invalid output 0, -1 or -2 \r\n if slotid <= 0:\r\n raise Exception('Error finding slot in Caregiver Schedule.')\r\n \r\n # creates vaccine appointment def ReserveAppointment(self, CaregiverSlotSchedulingId, Vaccine, PatientId, read_cursor, action_cursor):\r\n vaccineappointmentid = patient.ReserveAppointment(slotid, Vaccine, PatientId, read_cursor, action_cursor)\r\n \r\n # change status to scheduled\r\n scheduleslot = self.ScheduleAppointmentSlot(vaccineappointmentid, slotid, read_cursor, action_cursor)\r\n # check for invalid -1 or -2\r\n if scheduleslot <= 0:\r\n raise Exception('Error scheduling slot in Caregiver Schedule.')\r\n \r\n # update tables in database post scheduling\r\n patient.ScheduleAppointment(read_cursor, action_cursor, slotid, vaccineappointmentid)\r\n return None\r\n\r\n def FullScheduler(self, read_cursor, action_cursor, PatientId, Date, DateUpper='99-99-9999', Vaccine='Pfizer', TimeLower='00:00:00', TimeUpper='23:59:59'):\r\n '''\r\n Reserves appointment(s) for patient.\r\n '''\r\n # schedule first appointment\r\n self.ScheduleProcess(read_cursor, action_cursor, PatientId, Date, DateUpper, Vaccine, TimeLower, TimeUpper)\r\n \r\n # get vaccine number of doses and TimeBetweenLower/TimeBetweenUpper\r\n getVaccineInfo = 'SELECT * FROM Vaccines WHERE VaccineName=%s'\r\n read_cursor.execute(getVaccineInfo, Vaccine)\r\n row = read_cursor.fetchone()\r\n number_doses = row['DosesPerPatient']\r\n BetweenLower = row['DaysBetweenDosesLower']\r\n BetweenUpper = row['DaysBetweenDosesUpper']\r\n\r\n # check if needs 2nd appointment\r\n if number_doses == 2:\r\n NewDate = (datetime.datetime.strptime(Date, '%m-%d-%Y') + datetime.timedelta(days=BetweenLower)).strftime('%m-%d-%Y')\r\n NewDateUpper = (datetime.datetime.strptime(Date, '%m-%d-%Y') + datetime.timedelta(days=BetweenUpper)).strftime('%m-%d-%Y')\r\n self.ScheduleProcess (read_cursor, action_cursor, PatientId, NewDate, NewDateUpper, Vaccine, TimeLower, TimeUpper)\r\n\r\n return 'Your appointments for your 2 (two) doses are scheduled!'\r\n\r\n return 'Your appointment is scheduled!' \r\n\r\n \r\n\r\n\r\n\r\n def PutHoldOnAppointmentSlot(self, read_cursor, action_cursor, Date, DateUpper='99-99-9999', TimeLower='00:00:00', TimeUpper='23:59:59'):\r\n ''' Method that reserves a CareGiver appointment slot &\r\n returns the unique scheduling slotid\r\n Should return 0 if no slot is available or -1 if there is a database error'''\r\n # Note to students: this is a stub that needs to replaced with your code\r\n # Setting inventory to zero\r\n if DateUpper == '99-99-9999':\r\n DateUpper = Date\r\n self.sqltext = \"SELECT TOP 1 CaregiverSlotSchedulingId FROM CareGiverSchedule WHERE SlotStatus=0 AND WorkDay>= %s AND WorkDay <= %s AND SlotTime BETWEEN %s AND %s ORDER BY WorkDay, SlotTime ASC\"\r\n try:\r\n read_cursor.execute(self.sqltext, ((Date), (DateUpper), (TimeLower), (TimeUpper)))\r\n rows = read_cursor.fetchone()\r\n # No appointments available\r\n if rows is None:\r\n return 0\r\n slot_id = rows['CaregiverSlotSchedulingId']\r\n\r\n # Update status CaregiverSchedule to OnHold (statusCodeId=1, StatusCode='OnHold')\r\n self.updateCaregiverSQL = \"UPDATE CareGiverSchedule SET SlotStatus=1 WHERE CaregiverSlotSchedulingId=%s\"\r\n action_cursor.execute(self.updateCaregiverSQL, (str(slot_id)))\r\n\r\n action_cursor.connection.commit()\r\n return slot_id\r\n \r\n except pymssql.Error as db_err:\r\n print(\"Database Programming Error in SQL Query processing! \")\r\n print(\"Exception code: \" + str(db_err.args[0]))\r\n if len(db_err.args) > 1:\r\n print(\"Exception message: \" + db_err.args[1]) \r\n print(\"SQL text that resulted in an Error: \" + self.sqltext)\r\n action_cursor.connection.rollback()\r\n return -1\r\n\r\n #FOR VACCINEAPPOINTMENT\r\n #MARK PATIENT SCHEDULED\r\n #MARK CAREGIVER SCHEDULED\r\n #RESERVE DOSES\r\n def ScheduleAppointmentSlot(self, vaccineappointmentid, slotid, read_cursor, action_cursor):\r\n '''method that marks a slot on Hold with a definite reservation \r\n slotid is the slot that is currently on Hold and whose status will be updated \r\n returns the same slotid when the database update succeeds \r\n returns 0 is there if the database update dails \r\n returns -1 the same slotid when the database command fails\r\n returns 21 if the slotid parm is invalid '''\r\n # Note to students: this is a stub that needs to replaced with your code\r\n if slotid < 1:\r\n return -2\r\n self.slotSchedulingId = slotid\r\n self.getCGStatus = \"SELECT SlotStatus FROM CareGiverSchedule WHERE CaregiverSlotSchedulingId=%s\"\r\n self.getVAStatus = \"SELECT SlotStatus FROM VaccineAppointments WHERE VaccineAppointmentId=%s\"\r\n # Update caregiver slot status\r\n self.updateCaregiverSchedule = \"UPDATE CareGiverSchedule SET SlotStatus=SlotStatus+1 WHERE CaregiverSlotSchedulingId=%s\"\r\n # Update vaccine appointment status\r\n self.updateVaccineAppStatus = \"UPDATE VaccineAppointments SET SlotStatus=SlotStatus+1 WHERE VaccineAppointmentId=%s\"\r\n try:\r\n # Get cgsstatus\r\n read_cursor.execute(self.getCGStatus, (str(slotid)))\r\n row = read_cursor.fetchone()\r\n cgstatus = row['SlotStatus']\r\n # Get vastatus\r\n read_cursor.execute(self.getVAStatus, (str(vaccineappointmentid)))\r\n row = read_cursor.fetchone()\r\n vastatus = row['SlotStatus']\r\n # Check to make sure statuses are in correct position\r\n if cgstatus == 1 and vastatus == 1:\r\n action_cursor.execute(self.updateCaregiverSchedule, (str(slotid)))\r\n action_cursor.execute(self.updateVaccineAppStatus, (str(vaccineappointmentid)))\r\n print('Sucessfully scheduled slotid.')\r\n return self.slotSchedulingId\r\n else:\r\n raise Exception('One slot status was not marked as reserved.')\r\n except pymssql.Error as db_err:\r\n action_cursor.connection.rollback() \r\n print(\"Database Programming Error in SQL Query processing! \")\r\n print(\"Exception code: \" + db_err.args[0])\r\n if len(db_err.args) > 1:\r\n print(\"Exception message: \" + str(db_err.args[1])) \r\n print(\"SQL text that resulted in an Error: \" + self.getAppointmentSQL)\r\n return -1\r\n\r\nif __name__ == '__main__':\r\n with SqlConnectionManager(Server=os.getenv(\"Server\"),\r\n DBname=os.getenv(\"DBName\"),\r\n UserId=os.getenv(\"UserID\"),\r\n Password=os.getenv(\"Password\")) as sqlClient:\r\n vrs = VaccineReservationScheduler()\r\n\r\n # get a cursor from the SQL connection\r\n read_cursor = sqlClient.cursor(as_dict=True)\r\n action_cursor = sqlClient.cursor(as_dict=True)\r\n\r\n # Iniialize the caregivers, patients & vaccine supply\r\n # caregiversList = []\r\n # caregiversList.append(VaccineCaregiver('Carrie Nation', dbcursor))\r\n # caregiversList.append(VaccineCaregiver('Clare Barton', dbcursor))\r\n # caregivers = {}\r\n # for cg in caregiversList:\r\n # cgid = cg.caregiverId\r\n # caregivers[cgid] = cg\r\n\r\n # Add a vaccine and Add doses to inventory of the vaccine\r\n #vaccines = {'Moderna': {'Supplier': 'Moderna', 'inventory': 100, 'shotsnecessary': 2, 'DaysBetweenDosesLower': 21, 'DaysBetweenDosesUpper': 28}, 'Pfizer': {'Supplier': 'Pfizer', 'inventory': 100, 'shotsnecessary': 2, 'DaysBetweenDosesLower': 21, 'DaysBetweenDosesUpper': 28}, 'JohnsonJohnson': {'Supplier': 'JJ', 'inventory': 100, 'shotsnecessary': 1, 'DaysBetweenDosesLower': 21, 'DaysBetweenDosesUpper': 28}}\r\n #vaccinedb = covid(dbcursor, vaccines)\r\n # Ass patients\r\n # Schedule the patients\r\n #covid.AddDoses(dbcursor, 'Moderna', 30)\r\n # patientid = 1\r\n # slotid = vrs.PutHoldOnAppointmentSlot(read_cursor, action_cursor, '12-12-2021')\r\n # vaccinepatient = patient()\r\n # vaccineappointmentid = vaccinepatient.ReserveAppointment(slotid, 'Pfizer', patientid, read_cursor, action_cursor)\r\n # print(slotid)\r\n # print(vaccineappointmentid)\r\n # slotid = vrs.ScheduleAppointmentSlot(vaccineappointmentid, slotid, read_cursor, action_cursor)\r\n # patient.ScheduleAppointment(read_cursor, action_cursor, slotid, vaccineappointmentid)\r\n #FullScheduler(self, read_cursor, action_cursor, PatientId, Date, DateUpper='99-99-9999', Vaccine='Pfizer', TimeLower='00:00:00', TimeUpper='23:59:59'):\r\n #vrs.FullScheduler(read_cursor, action_cursor, 1, '12-12-2021', '12-12-2022', 'Pfizer', '10:00:00', '14:00:00')\r\n # Test cases done!\r\n #covid.ReserveDoses(dbcursor, 2)\r\n # clear_tables(sqlClient)\r\n\r\n\r\n#Call it 2x here\r\n","sub_path":"vaccine_reservation_scheduler.py","file_name":"vaccine_reservation_scheduler.py","file_ext":"py","file_size_in_byte":10323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"269776875","text":"# -*-coding:Utf-8 -*\n#Class qui gère le nom, le pin de la raspberry Pi de l'appareil et s'il fonctionne.\ntry:\n import RPi.GPIO as GPIO\nexcept ImportError:\n pass\nimport random\n\nimport Serveur.DomoticServeur\nimport Informations.ControlleHardWare\n\n\nclass DInformations():\n \"\"\"Class qui gère les informations et la partie hardware\"\"\"\n informations_appareils = list() #Variable de class qui contient tout les listes des appareils.\n #Les listes sont organisée de la façon suivante:\n #- Nom de l'appareil (0)\n #- Pin de la Raspberry Pi qui controle l'appareil en question (1)\n #- Pin de la Raspberry Pi qui va lire si la lumière est éteinte (2)\n #- 0 s'il marche, 1 s'il ne marche pas (3)\n #- Objet qui gère la partie hardware (4)\n def __init__(self,nom_appareil,pin_raspberry_pi_write,pin_raspberry_pi_read):\n self._nom_appareil = nom_appareil\n self._pin_write = pin_raspberry_pi_write\n self._pin_read = pin_raspberry_pi_read\n\n self.appareil_marche = False\n\n\n print(\"Appareil marche : {}\".format(self.appareil_marche))\n\n\n\n\n self._hard = Informations.ControlleHardWare.Control(self._pin_read,self._pin_write,self)\n self._hard.start()\n self.appareil_marche = self._hard.marche\n print(self.appareil_marche)\n self._append() #Met dans la liste de class toute les informations concernant l'appareil en question\n\n\n\n\n\n\n\n def _append(self):\n _liste = [self._nom_appareil,self._pin_write,self._pin_read,self.appareil_marche,self._hard]\n\n DInformations.informations_appareils.append(_liste)\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n @classmethod\n def getPinRead(cls,nom_appareil):\n for valeur in Informations.Dinformations_appareils:\n\n if valeur[0] is nom_appareil:\n return valeur[2]\n\n return None\n\n @classmethod\n def getPinWrite(cls,nom_appareil):\n for valeur in DInformations.informations_appareils:\n if valeur[0] is nom_appareil:\n return valeur[1]\n\n return None\n\n @classmethod\n def getFonctionne(cls,nom_appareil):\n for valeur in DInformations.informations_appareils:\n if valeur[0] is nom_appareil:\n return valeur[3]\n return None\n\n @classmethod\n def setMarche(cls,nom_appareil,value):\n for valeur in DInformations.informations_appareils:\n if valeur[0] == nom_appareil:\n valeur[4].write()\n\n\n\n return None\n\n\n def getNomAppareil(self):\n return self._nom_appareil\n\n def getPinReadRaspberryPi(self):\n return self._pin_read\n def getPinWriteRaspberryPi(self):\n return self._pin_write\n\n\n\n def marche(self,value):\n if value != self.appareil_marche:\n self.appareil_marche = value\n for appareil in DInformations.informations_appareils:\n if appareil[0] is self._nom_appareil:\n appareil[3] = value\n\n Serveur.DomoticServeur.DServeur.send_information()\n\n\n\n\n @classmethod\n def init_pin(cls):\n try:\n GPIO.setmode(GPIO.BCM)\n except NameError:\n pass\n\n @classmethod\n def cleanup_pin(cls):\n try:\n GPIO.cleanup()\n\n for appareil in DInformations.informations_appareils:\n appareil[4].stop()\n\n except NameError:\n pass\n\n\n\n\n\n\n\n\n","sub_path":"Informations/DomoticInformation.py","file_name":"DomoticInformation.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"35439048","text":"import json, os\ndef create_index(es_object, index_name='youtube_user_index'):\n file_path = os.path.normpath(os.getcwd())+'/persistance/elasticsearch/json/youtube-search-template.json'\n created = False\n # index settings\n with open(file_path) as f:\n settings = json.load(f)\n try:\n if not es_object.indices.exists(index_name):\n res = es_object.indices.create(\n index=index_name, body=settings)\n print(res)\n created = True\n except Exception as ex:\n print(str(ex))\n created=False\n finally:\n return created","sub_path":"persistance/elasticsearch/mapping/youtube_search_mapping.py","file_name":"youtube_search_mapping.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"154237599","text":"def sign(x):\r\n if x>0:\r\n return 1\r\n elif x<0:\r\n return -1\r\n else:\r\n return 0\r\n\r\n\r\nx = float(input('in X0:'))\r\ny = float(input('in Y0:'))\r\n\r\n\r\nx1 = -0\r\ny1 = -3\r\nx2 = -0.5\r\ny2 = 3\r\nx3 = -0\r\ny3 = -2.5\r\na = (x1-x)*(y2-y1)-(x2-x1)*(y1-y)\r\nb = (x2-x)*(y3-y1)-(x3-x2)*(y2-y)\r\nc = (x3-x)*(y1-y3)-(x1-x3)*(y3-y)\r\n\r\nif(sign(a) == sign(b) == sign(c)):\r\n print('Точка пренадлежит области')\r\nelse:\r\n print('Точка не пренадлежит области')","sub_path":"Треугольник и точка.py","file_name":"Треугольник и точка.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"266504560","text":"\nimport math\nimport pygame\n\ndef floor_transform(img, corners, tb):\n mx = max(corners)\n my = max(tb) + 1\n height = tb[1] - tb[0]\n\n new = pygame.Surface((mx,my))\n\n sc = pygame.transform.smoothscale(img, (img.get_rect().w, height))\n\n for rowIndex in range(height):\n frac = rowIndex / height\n ls = round(frac * corners[2] + (1 - frac) * corners[0])\n rs = round(frac * corners[3] + (1 - frac) * corners[1])\n rec = pygame.Rect(0, rowIndex, sc.get_rect().w, 1)\n rowPreScale = pygame.Surface((rec.w, rec.h))\n rowPreScale.blit(sc, (0,0), rec)\n rowPostScale = pygame.transform.smoothscale(rowPreScale, (rs - ls, 1))\n new.blit(rowPostScale, (ls, rowIndex + tb[0]))\n\n return new\n\ndef wall_transform(img, corners, lr):\n my = max(corners)\n mx = max(lr) + 1\n width = lr[1] - lr[0]\n\n new = pygame.Surface((mx,my))\n\n sc = pygame.transform.smoothscale(img, (width, img.get_rect().h))\n\n for colIndex in range(width):\n frac = colIndex / width\n ts = round(frac * corners[1] + (1 - frac) * corners[0])\n bs = round(frac * corners[3] + (1 - frac) * corners[2])\n rec = pygame.Rect(colIndex, 0, 1, sc.get_rect().h)\n colPreScale = pygame.Surface((rec.w, rec.h))\n colPreScale.blit(sc, (0,0), rec)\n colPostScale = pygame.transform.smoothscale(colPreScale, (1, bs - ts))\n new.blit(colPostScale, (colIndex + lr[0], ts))\n\n return new\n","sub_path":"transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"460462140","text":"#1723682\n#David van Vliet\n\n#Als je te klein bent zeggen dat ze niet in de attractie mag. Ben je groter of even groot als 120cm, dan mag je wel\ndef lang_genoeg(hoogte) :\n if (hoogte) >= 120 :\n return \"Je bent lang genoeg voor de attractie\"\n else :\n return \"Sorry, je bent te klein\"\n\nres = lang_genoeg(130)\nprint(res)\n","sub_path":"Python/les4/pe4_3.py","file_name":"pe4_3.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"174192441","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn import preprocessing\nfrom sklearn.metrics import mean_absolute_error\nst.write(\"\"\"\n\nWeather Prediciton\"\"\")\n\nst.sidebar.header(\"User Input\")\ndef user_input():\n temperature=st.sidebar.slider('Temperature in Celcius',-10,49,20)\n app_temperature=st.sidebar.slider('Apparent Temperature (C)',-10,49,20)\n humidity=st.sidebar.slider('Humidity in %',0.01,1.0,0.51)\n wind_speed=st.sidebar.slider('Wind Speed in Km/h',5,80,16)\n wind_bearing=st.sidebar.slider('Wind bearing',0,360,235)\n visibility=st.sidebar.slider('Visibility',0,30,15)\n loud_cover=st.sidebar.slider('Loud Cover',0,0,0)\n pressure=st.sidebar.slider('Pressure(millibar)',998,1050,1001)\n data={'Temperature':temperature,\n 'Apparent Temperature':app_temperature,\n 'Humidty':humidity,\n 'Wind Speed':wind_speed,\n 'Wind Bearing':wind_bearing,\n 'Visibility':visibility,\n 'Loud Cover':loud_cover,\n 'Pressure':pressure}\n f=pd.DataFrame(data,index=[0])\n return f\ndef user_input1():\n form=st.form(key='my_form')\n temperature=st.number_input(label='Temperature')\n humidity=st.number_input(label='Humidty')\n wind_speed=st.number_input(label='wind')\n visibility=st.number_input(label='visibility')\n pressure=st.number_input(label='pressure')\n data={'Temperature':35,\n \n 'Humidty':0.51,\n 'Wind Speed':16,\n \n 'Visibility':10,\n \n 'Pressure':1002}\n submit=form.form_submit_button('Submit')\n if submit:\n\t\t\n data={'Temperature':temperature,\n \n 'Humidty':humidity,\n 'Wind Speed':wind_speed,\n \n 'Visibility':visibility,\n \n 'Pressure':pressure}\n f=pd.DataFrame(data,index=[0])\n return f\n\n\ndef main():\n flag=0\n st.title(\"Upload File\")\n csv_file=st.file_uploader(\"Upload\",type=['csv','xslx'])\n \n if csv_file is not None:\n file_details = {\"Filename\":csv_file.name,\"FileType\":csv_file.type,\"FileSize\":csv_file.size}\n flag=1\n st.write(file_details)\n df=pd.read_csv(csv_file,parse_dates=['Formatted Date'])\n df['Formatted Date'] = pd.to_datetime(df['Formatted Date'], utc=True)\n df = df.set_index('Formatted Date')\n\n le=preprocessing.LabelEncoder()\n df['Summary']=le.fit_transform(df['Daily Summary'])\n\n unique_summary=df['Summary'].unique()\n unique_daily_summary=df['Daily Summary'].unique()\n weather_map={unique_summary[i]:unique_daily_summary[i] for i in range(len(unique_summary))}\n\n summary=df.pop('Daily Summary')\n summary.fillna('Dilemma')\n\n data_columns = ['Summary','Temperature (C)', 'Apparent Temperature (C)', 'Humidity', 'Wind Speed (km/h)', 'Wind Bearing (degrees)', 'Visibility (km)', 'Loud Cover', 'Pressure (millibars)']\n df_monthly_mean = df[data_columns].resample('MS').mean()\n df_monthly_mean.reset_index(inplace=True)\n\n summary1=pd.DataFrame(summary)\n\n col_y=df_monthly_mean[['Summary']]\n col_x_=df_monthly_mean[['Temperature (C)', 'Humidity', 'Wind Speed (km/h)', 'Visibility (km)', 'Pressure (millibars)']]\n\n x_train,x_test,y_train,y_test=train_test_split(col_x_,col_y,test_size=0.20,random_state=True)\n\n regression = LinearRegression()\n regression.fit(x_train, y_train)\n\n pred_y = regression.predict(x_test)\n\n prediction = pd.DataFrame({'P summary': [k for k in pred_y],'Actual summ':[j for j in y_test['Summary']]})\n\n call=user_input1()\n st.subheader('Input Data')\n st.write(call)\n t=np.array(call.values)\n temp=[]\n for i in range(5):\n temp.append(t[0][i])\n g=regression.predict([temp])\n if (int(g)>max(unique_summary)):\n out=weather_map[max(unique_summary)]\n\n else:\n out=weather_map[int(g)]\n st.subheader(\"Prediction\")\n st.write(out)\n\nif __name__== '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"266355825","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport json\nimport math\nimport random\nimport numpy as np\nfrom concurrent import futures\n\n\nclass BatchGenerator:\n def __init__(self, source_dir, batch_size, max_word_length, answer_key=\"assignee\", sentence_limit=5000, num_valid=100, threshold=0):\n self.source = source_dir\n self.batch_size = batch_size\n self.answer_key = answer_key\n self.sentence_limit = sentence_limit\n self.max_word_length = max_word_length\n self.report_threshold = threshold\n self.train_data, self.answer_dict = self.prepare()\n # calculate character embed size\n unique_chars = set()\n for item in self.train_data:\n unique_chars.update(item[1])\n self.chars_dict = {i: x for x, i in enumerate(unique_chars)}\n random.shuffle(self.train_data)\n self.valid_data = self.train_data[:num_valid]\n del self.train_data[:num_valid]\n self.num_classes = len(self.answer_dict)\n self.num_batches = int(math.ceil(len(self.train_data) / self.batch_size))\n self.num_valids = int(math.ceil(len(self.valid_data) / self.batch_size))\n print(\"Train data: {}, Validation data: {}, num_classes: {}\".format(len(self.train_data), len(self.valid_data), self.num_classes))\n\n def batches(self):\n random.shuffle(self.train_data)\n batch_x, batch_y = list(), list()\n for item in self.train_data:\n batch_y.append(self.answer_dict[item[0]])\n x_data = np.split(np.asarray([self.chars_dict[char] for char in item[1]] + [0] * (self.sentence_limit - len(item[1])),\n dtype=\"int32\"), self.sentence_limit//self.max_word_length)\n batch_x.append(x_data)\n if len(batch_x) >= self.batch_size:\n yield batch_x, batch_y\n batch_x.clear()\n batch_y.clear()\n if len(batch_x) > 0:\n yield batch_x, batch_y\n\n def valid_batches(self):\n random.shuffle(self.valid_data)\n batch_x, batch_y = list(), list()\n for item in self.valid_data:\n batch_y.append(self.answer_dict[item[0]])\n x_data = np.split(np.asarray([self.chars_dict[char] for char in item[1]] + [0] * (self.sentence_limit - len(item[1])),\n dtype=\"int32\"), self.sentence_limit//self.max_word_length)\n batch_x.append(x_data)\n if len(batch_x) >= self.batch_size:\n yield batch_x, batch_y\n batch_x.clear()\n batch_y.clear()\n if len(batch_x) > 0:\n yield batch_x, batch_y\n\n def prepare(self): # 모든 파일 읽으면서 데이터 변환해서 train/eval 나눠서 저장\n result, answers = list(), set()\n with futures.ProcessPoolExecutor(max_workers=os.cpu_count()) as executor:\n to_do = [executor.submit(self.convert, json_path) for json_path in self.read_json()]\n for future in futures.as_completed(to_do):\n data, answer_set = future.result()\n result += data\n answers.update(answer_set)\n report_count = {assignee: 0 for assignee in answers}\n for item in result:\n report_count[item[0]] += 1\n result = [item for item in result if report_count[item[0]] > self.report_threshold]\n answers = [assignee for assignee in answers if report_count[assignee] > self.report_threshold]\n answer_dict = dict()\n for i, answer in enumerate(answers):\n answer_dict[answer] = i\n return result, answer_dict\n\n def convert(self, json_file):\n result, answer_set = list(), set()\n for item in json.load(open(json_file)):\n sentence = \", \".join([\"[\" + k + \"] : \" + item[k] for k in item.keys() if k != self.answer_key])[:self.sentence_limit]\n answer = item[self.answer_key]\n answer_set.add(answer)\n result.append((answer, sentence))\n return result, answer_set\n\n def read_json(self):\n return [os.path.join(path, file_name) for (path, _, files) in os.walk(self.source) for file_name in files if file_name[-4:] == \"json\"]\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"423101992","text":"s = \"python\"\nfor i in range(len(s)):\n print(s[i], end = \",\")\nprint(\"\\n\")\n\nfile = \"20200101-104831.jpg\"\nprint(\"촬영 날짜\" + file[4:6] + \"월\" + file[6:8] + \"일\")\nprint(\"촬영 시간\" + file[9:11] + \"월\" + file[11:13] + \"일\")\nprint(\"확장자\" + file[-3:])\n\n# '생년-월-일'로 포맷팅해서 출력\n# 출신 지역 코드 출력\n\nsocialnum = '001212-3451231'\n\nyear = socialnum[:2]\nmonth = socialnum[2:4]\ndate = socialnum[4:6]\nregion = socialnum[8:10]\nger = socialnum[7]\n\nif ger == '1' or ger == '2':\n year = '19' + year\nelse: \n year = '20' + year\n\nprint(\"생일: \", year, \"-\", month, \"-\", date, sep='')\nprint(\"지역코드:\", socialnum[8:10])","sub_path":"ch08/ex02.py","file_name":"ex02.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"268044642","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 2018/8/7 07:31\n# @Author : pankui\n# @Site : https://github.com/pankui\n# @File : tcp_demo.py\n# @Software: PyCharm\n\nimport socket\n\n# 创建一个socket\ns = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\n# 建立连接\n\ns.connect(('www.sina.com.cn',80))\n\n# 发送数据\n\ns.send(b'GET / HTTP/1.1\\r\\nHost: www.sina.com.cn\\r\\nConnection: close\\r\\n\\r\\n')\n\n\n'''\nTCP连接创建的是双向通道,双方都可以同时给对方发数据。\n但是谁先发谁后发,怎么协调,要根据具体的协议来决定。\n例如,HTTP协议规定客户端必须先发请求给服务器,\n服务器收到后才发数据给客户端\n'''\n\n\n# 发送的文本格式必须符合HTTP标准,如果格式没问题,接下来就可以接收新浪服务器返回的数据了:\n\n\n# 接受数据\n\nbuffer = []\nwhile True:\n # 每次最多接受1k 字节\n d = s.recv(1024)\n if d:\n buffer.append(d)\n print(\"d=\",d)\n else:\n break\ndata = b''.join(buffer)\n\ns.close()\n\n\n# 接收到的数据包括HTTP头和网页本身,\n# 我们只需要把HTTP头和网页分离一下,把HTTP头打印出来,网页内容保存到文件:\n\nheader, html = data.split(b'\\r\\n\\r\\n', 1)\nprint(header.decode('utf-8'))\n# 把接收的数据写入文件:\nwith open('sina.html', 'wb') as f:\n f.write(html)","sub_path":"python-learn/basis/network_programming/tcp_demo.py","file_name":"tcp_demo.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"498887398","text":"import pandas as pd\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\nimport gffpandas.gffpandas as gffpd\nimport os\n\n# pd.set_option(\"precision\", 20)\npd.set_option(\"display.precision\", 20)\n\n__author__ = \"Anubhav \"\n\n\nclass DataOutputtable:\n \"\"\"\n Created based of data manipulation performed using MSSQLsever queries by\n Purvine, Samuel O \n \"\"\"\n\n def __init__(\n self,\n gff_file,\n resultant_file,\n fasta_txt_file,\n qvalue_threshold,\n dataset_id,\n genome_name,\n ):\n\n self.dataset_id = dataset_id\n self.genome_name = genome_name\n self.QValue_threshold = float(qvalue_threshold)\n # read annotation file.\n self.gff_file = gff_file\n self.annotation = gffpd.read_gff3(gff_file)\n self.resultant_df = pd.read_csv(\n resultant_file, sep=\"\\t\", float_precision=\"round_trip\"\n )\n\n col_of_interest = [\"ProteinName\", \"Sequence\"]\n self.fasta_df = pd.read_csv(fasta_txt_file, sep=\"\\t\")[col_of_interest]\n cols_to_rename = {\"ProteinName\": \"Protein\"}\n self.fasta_df.rename(columns=cols_to_rename, inplace=True)\n self.fasta_df[\"Index\"] = self.fasta_df.index + 1\n\n # saved to served multiple calls\n self.query_8_result = None\n self.peptide_report = None\n\n # building log excel files:\n file_loc = os.path.join(*self.gff_file.split(\"/\")[:-1])\n # self.writer = pd.ExcelWriter(f\"/{file_loc}/{DATA_LOG}.xlsx\", engine='xlsxwriter')\n\n # log dataframe.\n indexes = [f\"query_{idx}\" for idx in range(23)]\n indexes.extend([\"Peptide_Report\", \"Protein_Report\", \"qc_metrics\"])\n cols = [\"#row\", \"#col\", \"col_name\"]\n self.log_df = pd.DataFrame(columns=cols, index=indexes)\n\n def _DataOutputtable_xlsx(self, df, sheet_name):\n\n self.log_df.at[sheet_name, \"#row\"] = df.shape[0]\n self.log_df.at[sheet_name, \"#col\"] = df.shape[1]\n self.log_df.at[sheet_name, \"col_name\"] = \", \".join(df.columns.tolist())\n # df.to_excel(self.writer, sheet_name=sheet_name, index=False)\n\n def FiltPeps(self, df):\n qvalue_filtered_df = df[df[\"QValue\"] <= self.QValue_threshold]\n non_decoy_filtered_df = qvalue_filtered_df[\n ~qvalue_filtered_df[\"Protein\"].str.startswith(\"XXX\")\n ]\n non_decoy_filtered_df[\"PeptideSequence\"] = non_decoy_filtered_df[\n \"Peptide\"\n ].str.extract(r\"\\.(.*)\\.\")\n return non_decoy_filtered_df\n\n def get_FiltPeps_gen(self, df):\n FiltPeps_df = self.FiltPeps(df)\n return FiltPeps_df.drop_duplicates().sort_values(by=[\"PeptideSequence\"])\n\n def get_FiltPeps(self, df):\n FiltPeps_df = self.FiltPeps(df)\n return (\n FiltPeps_df[[\"PeptideSequence\", \"Protein\"]]\n .drop_duplicates()\n .sort_values(by=[\"PeptideSequence\"])\n )\n\n def query_2(self):\n \"\"\"\n counting distinct peptides per protein using 5% FDR filter and removing Decoy proteins\n :param query_1_df:\n :return: dataframe with col: 'Protein' 'PeptideSequence_Count'\n \"\"\"\n temp_df = self.resultant_df.copy()\n FiltPeps_df = self.get_FiltPeps(temp_df)\n grouped_by_protein = FiltPeps_df.groupby(\"Protein\")\n counted_peptides_df = (\n grouped_by_protein[\"PeptideSequence\"]\n .count()\n .reset_index(name=\"PeptideSequence_Count\")\n )\n\n self._DataOutputtable_xlsx(counted_peptides_df, \"query_2\")\n return counted_peptides_df\n\n def query_3(self):\n \"\"\"\n\n :param query_1_df:\n :return: dataframe with col: 'PeptideSequence' 'Protein_Count'\n \"\"\"\n temp_df = self.resultant_df.copy()\n FiltPeps_df = self.get_FiltPeps(temp_df)\n grouped_by_peptide = FiltPeps_df.groupby(\"PeptideSequence\")\n counted_protein_df = (\n grouped_by_peptide[\"Protein\"].count().reset_index(name=\"Protein_Count\")\n )\n\n self._DataOutputtable_xlsx(counted_protein_df, \"query_3\")\n return counted_protein_df\n\n def query_1(self):\n \"\"\"\n selecting distinct peptide and protein pairs from 5% FDR non-decoy results.\n :param resultant_df:\n :return:\n \"\"\"\n temp_df = self.resultant_df.copy()\n FiltPeps_df = self.get_FiltPeps(temp_df)\n\n self._DataOutputtable_xlsx(\n FiltPeps_df.drop_duplicates().sort_values(by=[\"PeptideSequence\"]), \"query_1\"\n )\n return FiltPeps_df.drop_duplicates().sort_values(by=[\"PeptideSequence\"])\n\n def query_4(self, table_1, table_2, table_3):\n\n # inner join on 'Protein'\n merge_1 = table_1.merge(table_2, how=\"inner\", on=\"Protein\")\n # inner join on 'Protein'\n merge_2 = merge_1.merge(self.fasta_df, how=\"inner\", on=\"Protein\")\n # inner join on 'PeptideSequence'\n merge_3 = merge_2.merge(table_3, how=\"inner\", on=\"PeptideSequence\")\n\n col_of_interest = [\n \"Protein\",\n \"PeptideSequence\",\n \"PeptideSequence_Count\",\n \"Index\",\n \"Protein_Count\",\n ]\n\n self._DataOutputtable_xlsx(\n merge_3[col_of_interest].sort_values(by=[\"PeptideSequence\"]), \"query_4\"\n )\n return merge_3[col_of_interest].sort_values(by=[\"PeptideSequence\"])\n\n def get_MaxPepCounts(self, table_4):\n peps_morethan_1_protein = table_4[table_4[\"Protein_Count\"] > 1]\n peps_morethan_1_protein[\n \"MaxPeptideSequenceCount\"\n ] = peps_morethan_1_protein.groupby([\"PeptideSequence\"])[\n \"PeptideSequence_Count\"\n ].transform(\n max\n )\n return peps_morethan_1_protein[\n [\"PeptideSequence\", \"MaxPeptideSequenceCount\"]\n ].drop_duplicates()\n\n def get_MaxPepCounts_table_4_joined(self, table_4):\n MaxPepCounts_df = self.get_MaxPepCounts(table_4)\n joined = MaxPepCounts_df.merge(\n table_4,\n how=\"inner\",\n left_on=[\"PeptideSequence\", \"MaxPeptideSequenceCount\"],\n right_on=[\"PeptideSequence\", \"PeptideSequence_Count\"],\n )\n joined[\"CountOfPeptideCounts\"] = joined.groupby([\"PeptideSequence\"])[\n \"PeptideSequence_Count\"\n ].transform(\"count\")\n return joined\n\n def get_BestSingleProteins(self, table_4):\n\n MaxPepCounts_table_4_joined_df = self.get_MaxPepCounts_table_4_joined(table_4)\n filtered = MaxPepCounts_table_4_joined_df[\n MaxPepCounts_table_4_joined_df[\"CountOfPeptideCounts\"] == 1\n ]\n filtered[\"MaxPeptideSequenceCount\"] = filtered.groupby([\"PeptideSequence\"])[\n \"PeptideSequence_Count\"\n ].transform(max)\n return filtered[\n [\"PeptideSequence\", \"CountOfPeptideCounts\", \"MaxPeptideSequenceCount\"]\n ]\n\n def get_BestIndexedProtein(self, table_4):\n MaxPepCounts_table_4_joined_df = self.get_MaxPepCounts_table_4_joined(table_4)\n filtered = MaxPepCounts_table_4_joined_df[\n MaxPepCounts_table_4_joined_df[\"CountOfPeptideCounts\"] > 1\n ]\n filtered[\"MinIndexValue\"] = filtered.groupby([\"PeptideSequence\"])[\n \"Index\"\n ].transform(min)\n return filtered[[\"PeptideSequence\", \"CountOfPeptideCounts\", \"MinIndexValue\"]]\n\n def query_5(self, table_4):\n peps_with_1_protein = table_4[table_4[\"Protein_Count\"] == 1]\n peps_with_1_protein.rename(columns={\"Protein\": \"BestProtein\"}, inplace=True)\n\n self._DataOutputtable_xlsx(\n peps_with_1_protein[[\"PeptideSequence\", \"BestProtein\"]], \"query_5\"\n )\n return peps_with_1_protein[[\"PeptideSequence\", \"BestProtein\"]]\n\n def query_6(self, table_4):\n BestSingleProteins_df = self.get_BestSingleProteins(table_4)\n joined = BestSingleProteins_df.merge(\n table_4,\n how=\"inner\",\n left_on=[\"PeptideSequence\", \"MaxPeptideSequenceCount\"],\n right_on=[\"PeptideSequence\", \"PeptideSequence_Count\"],\n )\n joined.rename(columns={\"Protein\": \"BestProtein\"}, inplace=True)\n\n self._DataOutputtable_xlsx(\n joined[[\"PeptideSequence\", \"BestProtein\"]], \"query_6\"\n )\n return joined[[\"PeptideSequence\", \"BestProtein\"]]\n\n def query_7(self, table_4):\n BestIndexedProtein_df = self.get_BestIndexedProtein(table_4)\n merged = BestIndexedProtein_df.merge(\n table_4,\n how=\"inner\",\n left_on=[\"PeptideSequence\", \"MinIndexValue\"],\n right_on=[\"PeptideSequence\", \"Index\"],\n )\n merged.rename(columns={\"Protein\": \"BestProtein\"}, inplace=True)\n\n self._DataOutputtable_xlsx(\n merged[[\"PeptideSequence\", \"BestProtein\"]].drop_duplicates(), \"query_7\"\n )\n return merged[[\"PeptideSequence\", \"BestProtein\"]].drop_duplicates()\n\n def get_best_protein_associated_with_peptide(self, table_4):\n # Take Union of 3 dataframes!\n table_5 = self.query_5(table_4)\n table_6 = self.query_6(table_4)\n table_7 = self.query_7(table_4)\n return pd.concat([table_5, table_6, table_7])\n\n def parse_MSGFjobs_MASIC_resultant(self):\n table_1 = self.query_1()\n table_2 = self.query_2()\n table_3 = self.query_3()\n table_4 = self.query_4(table_1, table_2, table_3)\n table_5_6_7_unioned = self.get_best_protein_associated_with_peptide(table_4)\n return table_5_6_7_unioned\n\n def query_0(self):\n \"\"\"\n\n :param gff_file: JGI annotation file.\n :return: dataframe with col: ['protein', 'Product', 'pfam', 'ko', 'ec_number', 'cog']\n \"\"\"\n filtered_df = self.annotation.filter_feature_of_type([\"CDS\"])\n col_of_interest = [\"ID\", \"product\", \"pfam\", \"ko\", \"ec_number\", \"cog\"]\n attributeTag_df = filtered_df.attributes_to_columns()[col_of_interest]\n cols_to_rename = {\"ID\": \"Protein\", \"product\": \"Product\"}\n attributeTag_df.rename(columns=cols_to_rename, inplace=True)\n # cleaning up columns\n # TODO: remove KO: EC: strings\n attributeTag_df[\"ko\"] = attributeTag_df[\"ko\"] # .str.replace('KO:', '')\n attributeTag_df[\"ec_number\"] = attributeTag_df[\n \"ec_number\"\n ] # .str.replace('EC:', '')\n\n self._DataOutputtable_xlsx(attributeTag_df, \"query_0\")\n return attributeTag_df\n\n def query_8(self):\n # TODO:remove all tables except table_5_6_7_unioned\n # 1. get best_protein_associated_with_peptide\n # table_1,table_2,table_3,table_4,\n table_5_6_7_unioned = self.parse_MSGFjobs_MASIC_resultant()\n # 2. get annotations\n AnnotationSplitout_df = self.query_0()\n\n merged = table_5_6_7_unioned.merge(\n AnnotationSplitout_df,\n how=\"left\",\n left_on=[\"BestProtein\"],\n right_on=[\"Protein\"],\n )\n col_of_interest = [\n \"PeptideSequence\",\n \"BestProtein\",\n \"Product\",\n \"ec_number\",\n \"pfam\",\n \"ko\",\n \"cog\",\n ]\n\n cols_to_rename = {\"ec_number\": \"EC_Number\", \"ko\": \"KO\", \"cog\": \"COG\"}\n PeptideBestProteinAnnotated = merged[col_of_interest]\n PeptideBestProteinAnnotated.rename(columns=cols_to_rename, inplace=True)\n\n self._DataOutputtable_xlsx(PeptideBestProteinAnnotated, \"query_8\")\n return PeptideBestProteinAnnotated\n\n def get_FwdPeptideSequences(self):\n FiltPeps_df = self.get_FiltPeps(self.resultant_df)\n FiltPeps_df[\"GeneCount\"] = FiltPeps_df.groupby([\"PeptideSequence\"])[\n \"Protein\"\n ].transform(\"nunique\")\n return FiltPeps_df[[\"PeptideSequence\", \"GeneCount\"]]\n\n def query_9(self):\n FwdPeptideSequences_df = self.get_FwdPeptideSequences()\n\n temp_df = self.resultant_df.copy()\n # temp_df['Peptide'] = temp_df['Peptide'].str.extract(r'\\.(.*)\\.')\n\n FiltPassPeptideAbundanceData = self.get_FiltPeps_gen(temp_df)[\n [\"PeptideSequence\", \"Protein\"]\n ]\n\n merged = FwdPeptideSequences_df.merge(\n FiltPassPeptideAbundanceData,\n how=\"inner\",\n left_on=[\"PeptideSequence\"],\n right_on=[\"PeptideSequence\"],\n )\n\n self._DataOutputtable_xlsx(\n merged[[\"PeptideSequence\", \"GeneCount\", \"Protein\"]]\n .drop_duplicates()\n .sort_values(by=[\"PeptideSequence\"]),\n \"query_9\",\n )\n return (\n merged[[\"PeptideSequence\", \"GeneCount\", \"Protein\"]]\n .drop_duplicates()\n .sort_values(by=[\"PeptideSequence\"])\n )\n\n def build_annotation_str(self, Protein, Product, pfam, ko, ec_number, cog):\n\n if not Protein.startswith(\"Contaminant\"):\n\n annotation_str = f\"gene_name={Protein}\"\n if Product and (Product != None) and (Product != \"nan\"):\n annotation_str = annotation_str + f\";product={Product}\"\n if pfam and (pfam != None) and (pfam != \"nan\"):\n annotation_str = annotation_str + f\";pfam={pfam}\"\n if ko and (ko != None) and (ko != \"nan\"):\n annotation_str = annotation_str + f\";ko={ko}\"\n if ec_number and (ec_number != None) and (ec_number != \"nan\"):\n annotation_str = annotation_str + f\";ec_number={ec_number}\"\n if cog and (cog != None) and (cog != \"nan\"):\n annotation_str = annotation_str + f\";cog={cog}\"\n else:\n # the contaminants aren't present in the JGI provided annotation files!\n # contaminants are added from PNNL.\n annotation_str = Protein\n return annotation_str\n\n def query_10(self):\n table_9 = self.query_9()\n AnnotationSplitout_df = self.query_0()\n merged = table_9.merge(\n AnnotationSplitout_df, how=\"left\", left_on=[\"Protein\"], right_on=[\"Protein\"]\n )\n merged[\"annotation\"] = merged.apply(\n lambda x: self.build_annotation_str(\n x.Protein, x.Product, x.pfam, x.ko, x.ec_number, x.cog\n ),\n axis=1,\n )\n\n self._DataOutputtable_xlsx(\n merged[\n [\"PeptideSequence\", \"GeneCount\", \"Protein\", \"annotation\"]\n ].sort_values(by=[\"PeptideSequence\"]),\n \"query_10\",\n )\n return merged[\n [\"PeptideSequence\", \"GeneCount\", \"Protein\", \"annotation\"]\n ].sort_values(by=[\"PeptideSequence\"])\n\n def query_11(self):\n table_10 = self.query_10()\n\n # prerare protein list\n table_10[\"FullGeneList\"] = (\n table_10.sort_values(\"Protein\")\n .groupby([\"PeptideSequence\", \"GeneCount\"])[\"Protein\"]\n .transform(lambda x: \", \".join(x))\n )\n\n # sort them!\n get_list_func = lambda x: x.split(\", \") if len(x.split(\", \")) > 1 else x\n f = (\n lambda x: \", \".join(sorted(get_list_func(x)))\n if isinstance(get_list_func(x), list)\n else get_list_func(x)\n )\n table_10[\"FullGeneList\"] = table_10[\"FullGeneList\"].apply(f)\n\n table_10[\"AnnotationList\"] = (\n table_10.sort_values(\"annotation\")\n .groupby([\"PeptideSequence\", \"GeneCount\"])[\"annotation\"]\n .transform(lambda x: \" | \".join(x))\n )\n\n self._DataOutputtable_xlsx(\n table_10[[\"PeptideSequence\", \"GeneCount\", \"FullGeneList\", \"AnnotationList\"]]\n .drop_duplicates()\n .sort_values(by=[\"PeptideSequence\"]),\n \"query_11\",\n )\n return (\n table_10[[\"PeptideSequence\", \"GeneCount\", \"FullGeneList\", \"AnnotationList\"]]\n .drop_duplicates()\n .sort_values(by=[\"PeptideSequence\"])\n )\n\n def query_12(self):\n\n temp_df = self.resultant_df.copy()\n FiltPassPeptideAbundanceData = self.get_FiltPeps_gen(temp_df)[\n [\"SpecIndex\", \"PeptideSequence\", \"StatMomentsArea\"]\n ].drop_duplicates(\n subset=[\"SpecIndex\", \"PeptideSequence\", \"StatMomentsArea\"]\n ) # .sort_values(by=[''])\n FiltPassPeptideAbundanceData[\n \"SpectralCount\"\n ] = FiltPassPeptideAbundanceData.groupby([\"PeptideSequence\"])[\n \"SpecIndex\"\n ].transform(\n \"count\"\n )\n FiltPassPeptideAbundanceData[\n \"sum(StatMomentsArea)\"\n ] = FiltPassPeptideAbundanceData.groupby([\"PeptideSequence\"])[\n \"StatMomentsArea\"\n ].transform(\n \"sum\"\n )\n\n self._DataOutputtable_xlsx(\n FiltPassPeptideAbundanceData[\n [\"PeptideSequence\", \"SpectralCount\", \"sum(StatMomentsArea)\"]\n ]\n .drop_duplicates()\n .sort_values(by=[\"PeptideSequence\"]),\n \"query_12\",\n )\n return (\n FiltPassPeptideAbundanceData[\n [\"PeptideSequence\", \"SpectralCount\", \"sum(StatMomentsArea)\"]\n ]\n .drop_duplicates()\n .sort_values(by=[\"PeptideSequence\"])\n )\n\n def query_13(self):\n temp_df = self.resultant_df.copy()\n filtered = self.get_FiltPeps_gen(temp_df)[\n [\"Dataset_x\", \"PeptideSequence\", \"QValue\"]\n ]\n groupby_columns = [\"Dataset_x\", \"PeptideSequence\"]\n filtered[\"min(QValue)\"] = filtered.groupby(groupby_columns)[\"QValue\"].transform(\n \"min\"\n )\n PeptideGeneListsANDAnnotationList_df = self.query_11()\n\n # inner join on 'PeptideSequence'\n merged_1 = filtered.merge(\n PeptideGeneListsANDAnnotationList_df,\n how=\"inner\",\n left_on=[\"PeptideSequence\"],\n right_on=[\"PeptideSequence\"],\n )\n\n PeptideBestProteinAnnotated_df = self.query_8()\n # saved for multiple call.\n self.query_8_result = PeptideBestProteinAnnotated_df.copy()\n\n # left outer join 'PeptideSequence'\n merged_2 = merged_1.merge(\n PeptideBestProteinAnnotated_df, how=\"left\", on=[\"PeptideSequence\"]\n )\n\n PeptideAbundanceInfo_df = self.query_12()\n # inner join on 'PeptideSequence'\n merged_3 = merged_2.merge(\n PeptideAbundanceInfo_df,\n how=\"inner\",\n left_on=[\"PeptideSequence\"],\n right_on=[\"PeptideSequence\"],\n )\n\n cols_to_rename = {\n \"Dataset_x\": \"DatasetName\",\n \"sum(StatMomentsArea)\": \"sum(MASICAbundance)\",\n }\n merged_3.rename(columns=cols_to_rename, inplace=True)\n\n self._DataOutputtable_xlsx(\n merged_3[\n [\n \"DatasetName\",\n \"PeptideSequence\",\n \"BestProtein\",\n \"Product\",\n \"EC_Number\",\n \"pfam\",\n \"KO\",\n \"COG\",\n \"GeneCount\",\n \"FullGeneList\",\n \"AnnotationList\",\n \"min(QValue)\",\n \"SpectralCount\",\n \"sum(MASICAbundance)\",\n ]\n ]\n .drop_duplicates()\n .sort_values(by=[\"DatasetName\"]),\n \"query_13\",\n )\n return (\n merged_3[\n [\n \"DatasetName\",\n \"PeptideSequence\",\n \"BestProtein\",\n \"Product\",\n \"EC_Number\",\n \"pfam\",\n \"KO\",\n \"COG\",\n \"GeneCount\",\n \"FullGeneList\",\n \"AnnotationList\",\n \"min(QValue)\",\n \"SpectralCount\",\n \"sum(MASICAbundance)\",\n ]\n ]\n .drop_duplicates()\n .sort_values(by=[\"DatasetName\"])\n )\n\n def query_14(self):\n Peptide_Report = self.query_13()\n\n Peptide_Report[\"UniquePeptideCount\"] = Peptide_Report.groupby([\"BestProtein\"])[\n \"PeptideSequence\"\n ].transform(\"count\")\n Peptide_Report[\"SummedSpectraCounts\"] = Peptide_Report.groupby([\"BestProtein\"])[\n \"SpectralCount\"\n ].transform(\"sum\")\n Peptide_Report[\"SummedPeptideMASICAbundances\"] = Peptide_Report.groupby(\n [\"BestProtein\"]\n )[\"sum(MASICAbundance)\"].transform(\"sum\")\n\n self._DataOutputtable_xlsx(\n Peptide_Report[\n [\n \"BestProtein\",\n \"UniquePeptideCount\",\n \"SummedSpectraCounts\",\n \"SummedPeptideMASICAbundances\",\n ]\n ]\n .drop_duplicates()\n .sort_values(by=[\"BestProtein\"]),\n \"query_14\",\n )\n return (\n Peptide_Report[\n [\n \"BestProtein\",\n \"UniquePeptideCount\",\n \"SummedSpectraCounts\",\n \"SummedPeptideMASICAbundances\",\n ]\n ]\n .drop_duplicates()\n .sort_values(by=[\"BestProtein\"])\n )\n\n def query_15(self):\n\n PeptideBestProteinAnnotated_df = self.query_8_result # self.query_8()\n temp_df = self.resultant_df.copy()\n temp_df[\"PeptideSequence\"] = temp_df[\"Peptide\"].str.extract(r\"\\.(.*)\\.\")\n merged = PeptideBestProteinAnnotated_df.merge(\n temp_df,\n how=\"inner\",\n left_on=[\"PeptideSequence\"],\n right_on=[\"PeptideSequence\"],\n )\n non_decoy_filtered_df = merged[~merged[\"Protein\"].str.startswith(\"XXX\")]\n self._DataOutputtable_xlsx(\n non_decoy_filtered_df[[\"BestProtein\", \"Protein\"]]\n .drop_duplicates(subset=[\"BestProtein\", \"Protein\"])\n .sort_values(by=[\"BestProtein\"]),\n \"query_15\",\n )\n return (\n non_decoy_filtered_df[[\"BestProtein\", \"Protein\"]]\n .drop_duplicates(subset=[\"BestProtein\", \"Protein\"])\n .sort_values(by=[\"BestProtein\"])\n )\n\n def query_16(self):\n BestProteinGeneLists = self.query_15() # .drop_duplicates(subset=['Protein'])\n\n # prepare protein list\n BestProteinGeneLists[\"FullGeneList\"] = BestProteinGeneLists.groupby(\n [\"BestProtein\"]\n )[\"Protein\"].transform(lambda x: \", \".join(x))\n # sort them!\n get_list_func = lambda x: x.split(\", \") if len(x.split(\", \")) > 1 else x\n f = (\n lambda x: \", \".join(sorted(get_list_func(x)))\n if isinstance(get_list_func(x), list)\n else get_list_func(x)\n )\n BestProteinGeneLists[\"FullGeneList\"] = BestProteinGeneLists[\n \"FullGeneList\"\n ].apply(f)\n\n BestProteinGeneLists[\"GeneCount\"] = BestProteinGeneLists.groupby(\n [\"BestProtein\"]\n )[\"Protein\"].transform(\"count\")\n BestProteinGeneLists.sort_values([\"FullGeneList\"], ascending=True, inplace=True)\n\n self._DataOutputtable_xlsx(\n BestProteinGeneLists[[\"BestProtein\", \"GeneCount\", \"FullGeneList\"]]\n .drop_duplicates()\n .sort_values(by=[\"BestProtein\"]),\n \"query_16\",\n )\n return (\n BestProteinGeneLists[[\"BestProtein\", \"GeneCount\", \"FullGeneList\"]]\n .drop_duplicates()\n .sort_values(by=[\"BestProtein\"])\n )\n\n def mod_build_annotation_str(\n self, BestProtein, Protein, Product, pfam, ko, ec_number, cog\n ):\n\n if Product != Product: # pd.isna(Product):\n # handle nan\n return BestProtein\n else:\n\n annotation_str = f\"gene_name={Protein}\" + f\";product={Product}\"\n if pfam and (pfam != None) and (pfam != \"nan\"):\n annotation_str = annotation_str + f\";pfam={pfam}\"\n if ko and (ko != None) and (ko != \"nan\"):\n annotation_str = annotation_str + f\";ko={ko}\"\n if ec_number and (ec_number != None) and (ec_number != \"nan\"):\n annotation_str = annotation_str + f\";ec_number={ec_number}\"\n if cog and (cog != None) and (cog != \"nan\"):\n annotation_str = annotation_str + f\";cog={cog}\"\n return annotation_str\n\n def query_17(self):\n\n AnnotationSplitout_df = self.query_0()\n\n table_15 = self.query_15() # have bestProtein\n ProteinBestProteinsAnnotated = table_15.merge(\n AnnotationSplitout_df, how=\"left\", left_on=[\"Protein\"], right_on=[\"Protein\"]\n )\n # display(ProteinBestProteinsAnnotated)\n ProteinBestProteinsAnnotated[\"annotation\"] = ProteinBestProteinsAnnotated.apply(\n lambda x: self.mod_build_annotation_str(\n x.BestProtein, x.Protein, x.Product, x.pfam, x.ko, x.ec_number, x.cog\n ),\n axis=1,\n )\n\n # display(ProteinBestProteinsAnnotated)\n self._DataOutputtable_xlsx(\n ProteinBestProteinsAnnotated[[\"BestProtein\", \"Protein\", \"annotation\"]]\n .drop_duplicates()\n .sort_values(by=[\"BestProtein\"]),\n \"query_17\",\n )\n\n return (\n ProteinBestProteinsAnnotated[[\"BestProtein\", \"Protein\", \"annotation\"]]\n .drop_duplicates()\n .sort_values(by=[\"BestProtein\"])\n )\n\n def query_18(self):\n\n BestProteinAnnotationLists = self.query_17()\n\n BestProteinAnnotationLists[\n \"AnnotationList\"\n ] = BestProteinAnnotationLists.groupby([\"BestProtein\"])[\"annotation\"].transform(\n lambda x: \" | \".join(x)\n )\n self._DataOutputtable_xlsx(\n BestProteinAnnotationLists[[\"BestProtein\", \"AnnotationList\"]]\n .drop_duplicates()\n .sort_values(by=[\"BestProtein\"]),\n \"query_18\",\n )\n return (\n BestProteinAnnotationLists[[\"BestProtein\", \"AnnotationList\"]]\n .drop_duplicates()\n .sort_values(by=[\"BestProtein\"])\n )\n\n def query_19(self):\n Peptide_Report_df = self.peptide_report.copy()[\n [\"DatasetName\", \"BestProtein\", \"Product\", \"EC_Number\", \"pfam\", \"KO\", \"COG\"]\n ]\n BestProteinGeneLists = self.query_16()\n merged_1 = Peptide_Report_df.merge(\n BestProteinGeneLists,\n how=\"inner\",\n left_on=[\"BestProtein\"],\n right_on=[\"BestProtein\"],\n )\n\n BestProteinAnnotationLists = self.query_18()\n merged_2 = merged_1.merge(\n BestProteinAnnotationLists,\n how=\"inner\",\n left_on=[\"BestProtein\"],\n right_on=[\"BestProtein\"],\n )\n\n PeptideAbundanceInfo_df = self.query_14()\n merged_3 = merged_2.merge(\n PeptideAbundanceInfo_df,\n how=\"inner\",\n left_on=[\"BestProtein\"],\n right_on=[\"BestProtein\"],\n )\n\n distinct_colm = [\n \"DatasetName\",\n \"BestProtein\",\n \"Product\",\n \"EC_Number\",\n \"pfam\",\n \"KO\",\n \"COG\",\n \"GeneCount\",\n \"FullGeneList\",\n \"AnnotationList\",\n \"UniquePeptideCount\",\n \"SummedSpectraCounts\",\n \"SummedPeptideMASICAbundances\",\n ]\n self._DataOutputtable_xlsx(\n merged_3[distinct_colm]\n .drop_duplicates(subset=distinct_colm)\n .sort_values(by=[\"DatasetName\"]),\n \"query_19\",\n )\n return (\n merged_3[distinct_colm]\n .drop_duplicates(subset=distinct_colm)\n .sort_values(by=[\"DatasetName\"])\n )\n\n def query_20(self):\n\n total_protein_count = pd.DataFrame(\n {\"total_protein_count\": self.fasta_df.Protein.nunique()}, index=[0]\n )\n self._DataOutputtable_xlsx(total_protein_count, \"query_20\")\n return total_protein_count\n\n def query_21(self):\n temp_df = self.resultant_df.copy()\n filtered = self.get_FiltPeps_gen(temp_df)[[\"Scan\", \"Charge\"]]\n PSM_Count = pd.DataFrame(\n {\"PSM_Count\": len(filtered.groupby([\"Scan\", \"Charge\"])[\"Scan\"])}, index=[0]\n )\n self._DataOutputtable_xlsx(PSM_Count, \"query_21\")\n return PSM_Count\n\n def query_22(self):\n temp_df = self.resultant_df.copy()\n Total_PSM_Count = pd.DataFrame(\n {\n \"Total_PSM_Count\": len(\n temp_df[[\"Scan\", \"Charge\"]].groupby([\"Scan\", \"Charge\"])[\"Scan\"]\n )\n },\n index=[0],\n )\n self._DataOutputtable_xlsx(Total_PSM_Count, \"query_22\")\n return Total_PSM_Count\n\n def query_23(self):\n Table12 = pd.DataFrame(\n {\n \"PSM_identification_rate\": (\n self.query_21().PSM_Count / self.query_22().Total_PSM_Count\n )\n * 100\n },\n index=[0],\n )\n self._DataOutputtable_xlsx(Table12, \"query_23\")\n return Table12\n\n def query_24(self):\n\n Peptide_Report_df = self.peptide_report.copy()\n unique_peptide_seq_count = (\n Peptide_Report_df.PeptideSequence.drop_duplicates().count()\n )\n BestProtein_count = Peptide_Report_df.BestProtein.drop_duplicates().count()\n mean_peptide_count = (unique_peptide_seq_count / BestProtein_count) * 100\n\n qc_metrics = pd.DataFrame(\n {\n \"total_protein_count\": self.query_20().total_protein_count,\n \"PSM_count\": self.query_21().PSM_Count,\n \"PSM_identification_rate\": self.query_23().PSM_identification_rate,\n \"unique_peptide_seq_count\": unique_peptide_seq_count,\n \"BestProtein_count\": BestProtein_count,\n \"mean_peptide_count\": mean_peptide_count,\n },\n index=[0],\n )\n\n self._DataOutputtable_xlsx(qc_metrics, \"query_24\")\n return qc_metrics\n\n def create_peptide_report(self):\n Peptide_Report_df = self.query_13()\n Peptide_Report_df.sort_values([\"GeneCount\"], ascending=False, inplace=True)\n self._DataOutputtable_xlsx(Peptide_Report_df, \"Peptide_Report\")\n return Peptide_Report_df\n\n def create_protein_report(self):\n Protein_Report_df = self.query_19()\n Protein_Report_df.sort_values([\"GeneCount\"], ascending=False, inplace=True)\n\n self._DataOutputtable_xlsx(Protein_Report_df, \"Protein_Report\")\n return Protein_Report_df\n\n def create_qc_metrics(self):\n qc_metrics_df = self.query_24()\n self._DataOutputtable_xlsx(qc_metrics_df, \"qc_metrics\")\n return qc_metrics_df\n\n def gen_reports(self):\n print(f\"ReportGen start {self.dataset_id} : {self.genome_name}\")\n self.peptide_report = self.create_peptide_report()\n protein_report = self.create_protein_report()\n qc_metrics_report = self.create_qc_metrics()\n print(f\"ReportGen end {self.dataset_id} : {self.genome_name}\")\n\n # rename to adhere nmdc.schema.json\n cols_to_rename = {\n \"PeptideSequence\": \"peptide_sequence\",\n \"BestProtein\": \"best_protein\",\n \"FullGeneList\": \"all_proteins\",\n \"min(QValue)\": \"min_q_value\",\n \"SpectralCount\": \"peptide_spectral_count\",\n \"sum(MASICAbundance)\": \"peptide_sum_masic_abundance\",\n }\n self.peptide_report.rename(columns=cols_to_rename, inplace=True)\n\n # rename to adhere nmdc.schema.json\n cols_to_rename = {\n \"BestProtein\": \"best_protein\",\n \"FullGeneList\": \"all_proteins\",\n \"sum(MASICAbundance)\": \"peptide_sum_masic_abundance\",\n }\n protein_report.rename(columns=cols_to_rename, inplace=True)\n\n # TODO: Change string type to \"min_q_value\", 'peptide_spectral_count', 'peptide_sum_masic_abundance' int!\n return self.peptide_report, protein_report, qc_metrics_report\n","sub_path":"src/post_processing/ficus_analysis.py","file_name":"ficus_analysis.py","file_ext":"py","file_size_in_byte":32111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"464157197","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\nfrom django.contrib import admin\nfrom django.utils.translation import ugettext_lazy as _\nimport logging\n\nfrom ..models import TaskHistory\nfrom dbaas import constants\n\nLOG = logging.getLogger(__name__)\n\nclass TaskHistoryAdmin(admin.ModelAdmin):\n perm_add_database_infra = constants.PERM_ADD_DATABASE_INFRA\n actions = None\n list_display_basic = [\"task_id\", \"friendly_task_name\", \"task_status\", \"arguments\", \"created_at\", \"ended_at\"]\n list_display_advanced = list_display_basic + [\"user\"]\n search_fields = ('task_id', \"task_name\", \"task_status\")\n list_filter_basic = [\"task_status\",]\n list_filter_advanced = list_filter_basic + [\"task_name\", \"user\", ]\n readonly_fields = ('created_at', 'ended_at', 'task_name', 'task_id', 'task_status', 'user', 'context', 'arguments', 'details')\n\n def friendly_task_name(self, task_history):\n if task_history.task_name:\n return \"%s\" % task_history.task_name.split('.')[::-1][0]\n else:\n return \"N/A\"\n friendly_task_name.short_description = \"Task Name\"\n\n def queryset(self, request):\n qs = None\n\n if request.user.has_perm(self.perm_add_database_infra):\n qs = super(TaskHistoryAdmin, self).queryset(request)\n return qs\n else:\n if request.GET.get('user'):\n query_dict_copy = request.GET.copy()\n del query_dict_copy['user']\n request.GET = query_dict_copy\n qs = super(TaskHistoryAdmin, self).queryset(request)\n\n return qs.filter(user=request.user.username)\n\n def changelist_view(self, request, extra_context=None):\n if request.user.has_perm(self.perm_add_database_infra):\n self.list_display = self.list_display_advanced\n self.list_filter = self.list_filter_advanced\n self.list_display_links = (\"task_id\",)\n else:\n self.list_display = self.list_display_basic\n self.list_filter = self.list_filter_basic\n self.list_display_links = (None,)\n \n return super(TaskHistoryAdmin, self).changelist_view(request, extra_context=extra_context)","sub_path":"dbaas/notification/admin/task_history.py","file_name":"task_history.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"526477459","text":"from django.contrib import admin\nfrom django.urls import path, include\n\nurlpatterns = [\n path('grappelli/', include('grappelli.urls')), # grappelli URLS\n path('articles/', include('articles.urls')),\n path('admin/', admin.site.urls),\n path('', include('start.urls')),\n path('accounts/', include('django.contrib.auth.urls')),\n path('account/', include('account.urls')),\n]\n","sub_path":"mysite/mysite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"559261381","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nAuthor: Wayne Isaac Tan Uy, PhD\n28 Dec 2020\n\"\"\"\nimport numpy as np\nimport numpy.linalg as LA\nfrom utils import *\nimport matplotlib.pyplot as plt\n\nData = np.load('LowPartialObsLowDim.npz')\n\nnp.random.seed(1)\n\n# simulation parameters\n\nN = 10 # dimension of full system\nnLag = 1 # lag of non-Markovian model\nnSteps = 50 # simulation time steps\nrdim = 2 # dimension of reduced observed state\npo = 30 # percentage of observed states\n\n# generate selection matrix\n\npoID, poIDC, Po, Poperp = genPartialObsMat(po,N)\n\n# generate discrete full system\n\nA = Data['A']\nB = np.zeros((N,1))\nSys = {\"A\":A, \"B\":B}\nsignal = np.zeros((1, nSteps))\n\n# generate reduced basis\n\nV = Data['V']\nVperp = Data['Vperp']\n\n# compute Markovian system\n\nQ = Po.T @ V\nQperp = np.hstack((Po.T @ Vperp, Poperp.T))\nMarkovianSys = genMarkovianSys(Sys,Q)\n\n# generate initial condition\n\nxInitTestQSpace = Data['xInitTestQSpace']\nxInitTest = Q @ xInitTestQSpace\nnInitTest = xInitTest.shape[1]\n\n# compute Markovian system\nMarkovianSysLag0 = genNonMarkovianModel(Sys,MarkovianSys,Q,Qperp,0)\n\n# compute non-Markovian system with lag 1\nnonMarkovianSysTrunc = genNonMarkovianModel(Sys,MarkovianSys,Q,Qperp,nLag)\n \n# compute exact non-Markovian system\nnonMarkovianSysExact = genNonMarkovianModel(Sys,MarkovianSys,Q,Qperp,nSteps)\n\n# time step various models\n\nObservedTraj = []\nMarkovianTraj = []\nnonMarkovianTruncTraj = []\nnonMarkovianExactTraj = []\nMarkovianErr = np.zeros((nInitTest, nSteps + 1)) \nnonMarkovianTruncErr = np.zeros((nInitTest, nSteps + 1)) \nnonMarkovianExactErr = np.zeros((nInitTest, nSteps + 1)) \nProjErr = np.zeros((nInitTest, nSteps + 1)) \n\nfor k in range(nInitTest):\n \n # obtain observed trajectory\n XTraj = TimeStepMarkovianSys(Sys,signal, xInitTest[:,k:k+1])\n ZTraj = XTraj[poID,:]\n ObservedTraj.append(ZTraj)\n \n # obtain Markovian model trajectory\n ZrTraj = TimeStepNonMarkovianSys(MarkovianSysLag0,signal, Q.T @ xInitTest[:,k:k+1])\n MarkovianTraj.append(ZrTraj)\n \n # obtain non-Markovian model with lag 1 trajectory\n ZrTruncTraj = TimeStepNonMarkovianSys(nonMarkovianSysTrunc,signal, Q.T @ xInitTest[:,k:k+1])\n nonMarkovianTruncTraj.append(ZrTruncTraj)\n \n # obtain exact non-Markovian model trajectory\n ZrExactTraj = TimeStepNonMarkovianSys(nonMarkovianSysExact,signal, Q.T @ xInitTest[:,k:k+1])\n nonMarkovianExactTraj.append(ZrExactTraj)\n \n # compute error\n MarkovianErr[k:k+1,:] = LA.norm(ZTraj - V @ ZrTraj, axis = 0).reshape(1,-1)\n nonMarkovianTruncErr[k:k+1,:] = LA.norm(ZTraj - V @ ZrTruncTraj, axis = 0).reshape(1,-1)\n nonMarkovianExactErr[k:k+1,:] = LA.norm(ZTraj - V @ ZrExactTraj, axis = 0).reshape(1,-1)\n ProjErr[k:k+1,:] = LA.norm(ZTraj - V @ V.T @ ZTraj, axis = 0).reshape(1,-1)\n \n#%%\n \n# plot\nIC = 1 # index for initial condition\n\nfig, ax = plt.subplots()\nax.plot(np.arange(nSteps), MarkovianErr[IC,1:], label = 'Markovian model')\nax.plot(np.arange(nSteps), nonMarkovianTruncErr[IC,1:], label = 'non-Markovian model with lag 1')\n\nax.set_yscale(\"log\")\nax.legend()\nax.set(xlabel='time', ylabel='reduced model error')\nax.grid()\n\nplt.show()\n \nfig, ax = plt.subplots()\nax.plot(np.arange(nSteps), nonMarkovianExactErr[IC,1:], label = 'exact non-Markovian model')\nax.plot(np.arange(nSteps), ProjErr[IC,1:], label = 'Projection error')\n\nax.set_yscale(\"log\")\nax.legend()\nax.set(xlabel='time', ylabel='reduced model error')\nax.grid()\n\nplt.show()\nfig, ax = plt.subplots()\naveRelErr = (MarkovianErr[IC,1:] - nonMarkovianTruncErr[IC,1:])/LA.norm(ObservedTraj[IC][:,1:], axis = 0)\nax.plot(np.arange(nSteps), aveRelErr, label = 'err diff')\nax.set(xlabel='time', ylabel='difference in relative error')\n\nax.grid()\nplt.show()\n","sub_path":"LowPartialObsLowDim.py","file_name":"LowPartialObsLowDim.py","file_ext":"py","file_size_in_byte":3738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"211219220","text":"#!/usr/bin/python\n# coding: utf-8\nfrom __future__ import print_function\nimport os\nimport peakAtState as peak\nfrom display import *\nfrom GridWorld import *\nfrom PIL import Image\nfrom pysrc.prediction.network.td_network import *\nfrom pysrc.prediction.network.off_policy_horde import HordeHolder, HordeLayer\nfrom pysrc.control.control_agents import RandomAgent\nfrom pysrc.function_approximation.StateRepresentation import Representation, TrackingRepresentation\nfrom pysrc.prediction.cumulants.cumulant import Cumulant\nfrom matplotlib import pyplot\nfrom pysrc.prediction.off_policy.gtd import *\nfrom os import system\n\nif sys.version_info[0] == 2:\n sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # flush print output immediately\nelse:\n import functools\n print = functools.partial(print, flush=True)\n\n\nclass MinecraftAgent(RandomAgent):\n \"\"\"\n A random agent which chooses actions equiprobably regardless of observations.\n \"\"\"\n\n def __init__(self, observation_space, action_space, **vals):\n super(RandomAgent, self).__init__(observation_space, action_space)\n self.state_prime = None\n self.i = 0\n\n @staticmethod\n def __str__():\n return \"RandomAgent\"\n\n def terminal_step(self, reward):\n pass\n\n def initialize_episode(self):\n pass\n\n def get_action(self, state_prime):\n action = np.random.randint(self.action_space)\n while action == 1:\n action = np.random.randint(self.action_space)\n return action\n\n def get_policy(self, observation):\n return np.ones(self.action_space)/self.action_space\n\n def step(self, observation, reward):\n pass\n\n\nclass MinecraftCumulantTouch(Cumulant):\n\n def cumulant(self, obs):\n return obs['touchData']\n\n\nclass MinecraftCumulantPrediction(Cumulant):\n\n def __init__(self, i):\n self.prediction_index = i\n\n def cumulant(self, obs):\n return obs['predictions'][self.prediction_index]\n\n\nclass MinecraftHordeLayer(HordeLayer):\n\n def step(self, observations, policy, action, remove_base=False, terminal_step=False, **vals):\n \"\"\"Update the Network\n Args:\n observations (list): real-valued list of observations from the environment.\n policy (list): list of length num_actions; the policy of the control policy for the given state.\n Returns:\n predictions (list): the predictions for each GVF given the observations and policy.\n \"\"\"\n # get the next feature vector\n phi_next = self.function_approximation.get_features(observations)\n if type(self.last_phi) is np.ndarray:\n discounts = np.array([discount.gamma(observations) for discount in self.discounts])\n\n if terminal_step:\n discounts = np.zeros(self.discounts.shape)\n # calculate importance sampling\n rho = (self.policies/policy)[:, action]\n # update the traces based on the new visitation\n self.eligibility_traces = accumulate(self.eligibility_traces, discounts, self.traces_lambda, self.last_phi, rho)\n # calculate the new cumulants\n current_cumulants = np.array([cumulant.cumulant(observations) for cumulant in self.cumulants])\n # get a vector of TD errors corresponding to the performance.\n td_error = calculate_temporal_difference_error(self.weights, current_cumulants, discounts, phi_next,\n self.last_phi)\n # update the weights based on the caluculated TD error\n self.weights = update_weights(td_error, self.eligibility_traces, self.weights, discounts, self.traces_lambda, self.step_sizes, self.last_phi, self.bias_correction)\n # update bias correction term\n self.bias_correction = update_h_trace(self.bias_correction, td_error, self.step_size_bias_correction\n , self.eligibility_traces, self.last_phi)\n\n\n # maintain verifiers\n self.rupee, self.tau, self.eligibility_avg = \\\n update_rupee(\n beta_naught=self.rupee_beta,\n tau=self.tau,\n delta_e=self.eligibility_avg,\n h=self.bias_correction,\n e=self.eligibility_traces,\n delta=td_error,\n alpha=self.step_sizes,\n phi=self.last_phi\n )\n self.ude, self.delta_avg, self.delta_var = update_ude(\n self.ude_beta,\n self.delta_avg,\n self.delta_var,\n td_error\n )\n self.avg_error = self.avg_error * 0.9 + 0.1 * np.abs(td_error)\n\n self.last_phi = phi_next\n self.last_prediction = np.inner(self.weights, phi_next)\n return self.last_prediction\n\n\nclass MinecraftHordeHolder(HordeHolder):\n \"\"\"The minecraft experiment setup is slightly different from what we're used to doing, so I'm extending the state\n construction functionality such that it\"\"\"\n\n def __init__(self, layers, num_actions):\n \"\"\"\"Initializes a horde holder which is responsible for managing a hierarchical collection of predictions.\n Args:\n layers (list): a list which contains instances of HordeLayer.\n num_actions (int): the number of actions in the current domain.\n \"\"\"\n super(MinecraftHordeHolder, self).__init__(layers=layers, num_actions=num_actions)\n self.state = None\n self.rupee = None\n self.ude = None\n self.prediction = None\n\n def step(self, observations, policy=None, action=None, recurrance=False, skip=False, ude=False, remove_base=False, **vals):\n predictions = None\n all_predictions = []\n for layer in self.layers:\n # Adds the most recent predictions to the observations; will be None if base layer.\n observations['predictions'] = predictions\n predictions = layer.step(observations, policy, action)\n all_predictions.append(predictions.tolist())\n\n rupee = self.get_rupee()\n ude = self.get_ude()\n try:\n for i in range(len(rupee)):\n self.rupee[i].append(rupee[i])\n self.ude[i].append(ude[i])\n self.prediction[i].append(all_predictions[i])\n except TypeError:\n self.rupee = []\n self.ude = []\n self.prediction = []\n for i in range(len(rupee)):\n self.rupee.append([])\n self.ude.append([])\n self.prediction.append([])\n self.rupee[i].append(rupee[i])\n self.ude[i].append(ude[i])\n self.prediction[i].append(all_predictions[i])\n self.state = observations\n\n\nclass Foreground:\n\n def __init__(self, show_display=True, steps_before_updating_display=0, steps_before_prompting_for_action=0):\n \"\"\"Initializes the experiment.\n Args:\n show_display (bool): a flag which determines whether the display is shown.\n steps_before_updating_display (int): the number of time-steps which are executed before presenting the display.\n steps_before_prompting_for_action (int): the number of time-steps which are executed before giving the user\n control.\n \"\"\"\n self.show_display = show_display\n self.steps_before_prompting_for_action = steps_before_prompting_for_action\n self.steps_before_updating_display = steps_before_updating_display\n self.grid_world = GridWorld('model/grids', initial_x=1, initial_y=1)\n self.agent = RandomAgent(action_space=5, observation_space=0)\n if self.show_display:\n self.display = Display(self)\n self.gvfs = {}\n self.state = None\n self.old_state = None\n self.network = self.configure_gvfs_net()\n self.tracking_network = self.configure_tracking_gvfs()\n self.action_count = 0\n\n @staticmethod\n def configure_gvfs_net():\n \"\"\"Follows the thought experiment from Ring (2016) to construct a multi-layer horde which gradually constructs\n predictions which are increasingly abstract. \"\"\"\n\n layers = [] # where we store horde layers; creates a hierarchy.\n number_of_actions = 4\n # actions = \"forward\", \"turn_left\", \"turn_right\", \"extend_hand\"\n # =============================================================================================================\n # Layer 1 - Touch (T)\n # =============================================================================================================\n\n number_of_active_features = 400\n eligibility_decay = np.array([0.9])\n discounts = np.array([0])\n function_approximation = Representation()\n init_alpha = np.array([0.3 /function_approximation.get_num_active()])\n policies = [[0, 0, 0, 1, 0]] # with probability 1, extend hand\n cumulant = [MinecraftCumulantTouch()]\n\n network = HordeLayer(\n function_approx=function_approximation,\n num_predictions=1,\n step_sizes=init_alpha,\n discounts=discounts,\n cumulants=cumulant,\n policies=policies,\n traces_lambda=eligibility_decay,\n protected_range=0,\n )\n layers.append(network) # add the new layer to the collection\n\n # =============================================================================================================\n # Layer 2 - Touch Left (TL) and Touch Right (TR)\n # =============================================================================================================\n\n base_rep_dimension = PIXEL_FEATURE_LENGTH * NUMBER_OF_PIXEL_SAMPLES + DID_TOUCH_FEATURE_LENGTH\n policies = [[0, 1, 0, 0, 0], [0, 0, 1, 0, 0]] # turn left and turn right\n discounts = np.array([0, 0])\n cumulant = [MinecraftCumulantPrediction(0), MinecraftCumulantPrediction(0)] # todo: what index?\n function_approximation = Representation(base_rep_dimension+1*PREDICTION_FEATURE_LENGTH)\n init_alpha = np.array(0.3 / function_approximation.get_num_active())\n network = HordeLayer(\n function_approx=function_approximation,\n num_predictions=2,\n step_sizes=init_alpha,\n discounts=discounts,\n cumulants=cumulant,\n policies=policies,\n traces_lambda=eligibility_decay,\n protected_range=0\n )\n layers.append(network)\n\n # =============================================================================================================\n # Layer 3 - Touch Behind\n # =============================================================================================================\n\n # Todo\n\n # =============================================================================================================\n # Layer 4 - Touch Adjacent (TA)\n # =============================================================================================================\n\n # Todo\n\n # =============================================================================================================\n # Layer 5 - Distance to touch adjacent (DTA)\n # Measures how many steps the agent is from being adjacent touch something.\n # * Note that because our agent only rotates 90 degrees at a time, this is basically the\n # number of steps to a wall. So the cumulant could be T. But we have the cumulant as TA instead\n # since this would allow for an agent whose rotations are not 90 degrees.\n # =============================================================================================================\n\n # Todo\n\n # =============================================================================================================\n # Layer 6 - Distance to Left (DTL), distance to right (DTR), distance back (DTB)\n # Measures how many steps to the left, or right, or behind,the agent is from a wall.\n # =============================================================================================================\n return MinecraftHordeHolder(layers, number_of_actions)\n\n @staticmethod\n def configure_tracking_gvfs():\n \"\"\"Follows the thought experiment from Ring (2016) to construct a multi-layer horde which gradually constructs\n predictions which are increasingly abstract. \"\"\"\n\n layers = [] # where we store horde layers; creates a hierarchy.\n number_of_actions = 4\n # actions = \"forward\", \"turn_left\", \"turn_right\", \"extend_hand\"\n # =============================================================================================================\n # Layer 1 - Touch (T)\n # =============================================================================================================\n\n number_of_active_features = 400\n eligibility_decay = np.array([0.9])\n discounts = np.array([0])\n\n function_approximation = Bias()\n init_alpha = np.array([0.3 / function_approximation.get_num_active()])\n policies = [[0, 0, 0, 1, 0]] # with probability 1, extend hand\n cumulant = [MinecraftCumulantTouch()]\n\n network = HordeLayer(\n function_approx=function_approximation,\n num_predictions=1,\n step_sizes=init_alpha,\n discounts=discounts,\n cumulants=cumulant,\n policies=policies,\n traces_lambda=eligibility_decay,\n protected_range=0,\n )\n layers.append(network) # add the new layer to the collection\n\n # =============================================================================================================\n # Layer 2 - Touch Left (TL) and Touch Right (TR)\n # =============================================================================================================\n\n base_rep_dimension = PIXEL_FEATURE_LENGTH * NUMBER_OF_PIXEL_SAMPLES + DID_TOUCH_FEATURE_LENGTH\n policies = [[0, 1, 0, 0, 0], [0, 0, 1, 0, 0]] # turn left and turn right\n discounts = np.array([0, 0])\n cumulant = [MinecraftCumulantPrediction(0), MinecraftCumulantPrediction(0)]\n function_approximation = Representation(base_rep_dimension + 1 * PREDICTION_FEATURE_LENGTH)\n init_alpha = np.array(0.1 / function_approximation.get_num_active())\n network = HordeLayer(\n function_approx=function_approximation,\n num_predictions=2,\n step_sizes=init_alpha,\n discounts=discounts,\n cumulants=cumulant,\n policies=policies,\n traces_lambda=eligibility_decay,\n protected_range=0\n )\n layers.append(network)\n\n return MinecraftHordeHolder(layers, number_of_actions)\n\n def update_ui(self, action):\n \"\"\"Re-draws the UI\n Args:\n action (int): the action taken this time-step.\n\n \"\"\"\n # Create a voronoi image\n if self.state:\n frame = self.state['visionData']\n if self.show_display:\n voronoi = voronoi_from_pixels(pixels=frame, dimensions=(WIDTH, HEIGHT),\n pixelsOfInterest=self.network.layers[0].function_approximation.pointsOfInterest)\n # cv2.imshow('My Image', voronoi)\n # cv2.waitKey(0)\n\n if self.state is False: # todo: should be None for first val, not bool.\n did_touch = False\n else:\n did_touch = self.state['touchData']\n\n # find the ground truth of the predictions.\n in_front = peak.isWallInFront(self.state['x'], self.state['y'], self.state['yaw'], self.grid_world)\n on_left = peak.isWallOnLeft(self.state['x'], self.state['y'], self.state['yaw'], self.grid_world)\n on_right = peak.isWallOnRight(self.state['x'], self.state['y'], self.state['yaw'], self.grid_world)\n is_behind = peak.isWallBehind(self.state['x'], self.state['y'], self.state['yaw'], self.grid_world)\n wall_adjacent = peak.isWallAdjacent(self.state['x'], self.state['y'], self.state['yaw'], self.grid_world)\n distance_to_adjacent = peak.distanceToAdjacent(self.state['x'], self.state['y'], self.state['yaw'],\n self.grid_world)\n distance_left = peak.distanceLeftToAdjacent(self.state['x'], self.state['y'], self.state['yaw'],\n self.grid_world)\n distance_right = peak.distanceRightToAdjacent(self.state['x'], self.state['y'], self.state['yaw'],\n self.grid_world)\n distance_back = peak.distanceBehindToAdjacent(self.state['x'], self.state['y'], self.state['yaw'],\n self.grid_world)\n wall_left_forward = peak.wallLeftForward(self.state['x'], self.state['y'], self.state['yaw'],\n self.grid_world)\n\n # get the most recent predictions\n touch_prediction = self.network.layers[0].last_prediction[0]\n track_touch_prediction = self.tracking_network.layers[0].last_prediction[0]\n\n turn_left_and_touch_prediction = self.network.layers[1].last_prediction[0]\n track_turn_left_and_touch_prediction = self.tracking_network.layers[1].last_prediction[0]\n\n # turn_left_and_touch_prediction = 0\n\n turn_right_and_touch_prediction = self.network.layers[1].last_prediction[1]\n track_turn_right_and_touch_prediction = self.tracking_network.layers[1].last_prediction[1]\n\n # turn_right_and_touch_prediction = 0\n # unimplemented, so zero...\n touch_behind_prediction = 0\n is_wall_adjacent_prediction = 0\n distance_to_adjacent_prediction = 0\n distance_left_prediction = 0\n distance_right_prediction = 0\n distance_back_prediction = 0\n wall_left_forward_prediction = 0\n\n game_image = Image.frombytes('RGB', (WIDTH, HEIGHT), bytes(frame))\n\n if self.show_display:\n if self.action_count > self.steps_before_updating_display:\n self.display.update(voronoiImage=voronoi,\n gameImage=game_image,\n numberOfSteps=self.action_count,\n currentTouchPrediction=touch_prediction,\n wallInFront=in_front,\n didTouch=did_touch,\n turnLeftAndTouchPrediction=turn_left_and_touch_prediction,\n wallOnLeft=on_left,\n turnRightAndTouchPrediction=turn_right_and_touch_prediction,\n touchBehindPrediction=touch_behind_prediction,\n wallBehind=is_behind,\n touchAdjacentPrediction=is_wall_adjacent_prediction,\n wallAdjacent=wall_adjacent,\n wallOnRight=on_right,\n distanceToAdjacent=distance_to_adjacent,\n distanceToAdjacentPrediction=distance_to_adjacent_prediction,\n distanceToLeft=distance_left,\n distanceToLeftPrediction=distance_left_prediction,\n distanceToRight=distance_right,\n distanceToRightPrediction=distance_right_prediction,\n distanceBack=distance_back,\n distanceBackPrediction=distance_back_prediction,\n wallLeftForward=wall_left_forward,\n wallLeftForwardPrediction=wall_left_forward_prediction,\n action=action,\n track_touch_prediction=track_touch_prediction,\n track_turn_left_and_touch_prediction=track_turn_left_and_touch_prediction,\n track_turn_right_and_touch_prediction=track_turn_right_and_touch_prediction\n )\n\n def learn_from_action(self, action):\n self.action_count += 1\n # If we've done 100 steps; pretty print the progress.\n if self.action_count % 100 == 0:\n print(\"Step \" + str(self.action_count) + \" ... \")\n observation = self.grid_world.take_action(action)\n # Do the learning\n self.network.step(observation, self.agent.get_policy(observation=None), action)\n self.tracking_network.step(observation, self.agent.get_policy(observation=None), action)\n self.state = self.network.state\n # Update our display (for debugging and progress reporting)\n self.update_ui(action)\n\n def learn_from_behavior_policy_action(self):\n \"\"\"Using the behaviour policy, selects an action. After selecting an action, updates the GVFs based on the\n action.\"\"\"\n # todo: this is set as a variable in learn_from_action; we don't need to have two dependent calls...\n action = self.agent.get_action(state_prime=None) # state doesn't matter; randint\n self.learn_from_action(action)\n\n\n def get_true_values(self):\n true_values = []\n in_front = peak.isWallInFront(self.state['x'], self.state['y'], self.state['yaw'], self.grid_world)\n\n true_values.append([in_front])\n\n on_left = peak.isWallOnLeft(self.state['x'], self.state['y'], self.state['yaw'], self.grid_world)\n on_right = peak.isWallOnRight(self.state['x'], self.state['y'], self.state['yaw'], self.grid_world)\n\n true_values.append([on_left, on_right])\n\n is_behind = peak.isWallBehind(self.state['x'], self.state['y'], self.state['yaw'], self.grid_world)\n wall_adjacent = peak.isWallAdjacent(self.state['x'], self.state['y'], self.state['yaw'], self.grid_world)\n distance_to_adjacent = peak.distanceToAdjacent(self.state['x'], self.state['y'], self.state['yaw'],\n self.grid_world)\n distance_left = peak.distanceLeftToAdjacent(self.state['x'], self.state['y'], self.state['yaw'],\n self.grid_world)\n distance_right = peak.distanceRightToAdjacent(self.state['x'], self.state['y'], self.state['yaw'],\n self.grid_world)\n distance_back = peak.distanceBehindToAdjacent(self.state['x'], self.state['y'], self.state['yaw'],\n self.grid_world)\n wall_left_forward = peak.wallLeftForward(self.state['x'], self.state['y'], self.state['yaw'],\n self.grid_world)\n return true_values\n\n def start(self):\n \"\"\"Initializes the plotter and runs the experiment.\"\"\"\n print(\"Mission ended\")\n\n track_rupee = []\n track_ude = []\n track_prediction = []\n\n exp_rupee = []\n exp_ude = []\n exp_prediction = []\n\n true_values = []\n\n for seed in [\n 8995, 6553, 2514, 6629, 7381, 1590, 1588, 2585, 1083, 822,\n 438, 3674, 8768, 8891, 6448, 5719, 5134, 8341, 5981,\n 3623, 6994, 1653, 5417, 6542,\n 4868, 9414, 6632, 1852, 1788, 3348\n ]:\n random.seed(seed)\n np.random.seed(seed)\n\n while self.action_count < self.steps_before_prompting_for_action:\n self.learn_from_behavior_policy_action()\n true_values_now = self.get_true_values()\n try:\n for i in range(len(true_values_now)):\n true_values[i].append(true_values_now[i])\n except IndexError:\n for i in range(len(true_values_now)):\n true_values.append([])\n true_values[i].append(true_values_now[i])\n\n # pyplot.plot(np.array(self.network.rupee[0]))\n self.action_count = 0\n # dump network rupee and error\n # dump the weights of the predictions & serialize function approximators\n try:\n for i in range(len(self.network.rupee)):\n exp_rupee[i].append(self.network.rupee[i])\n exp_ude[i].append(self.network.ude[i])\n exp_prediction[i].append(self.network.prediction[i])\n\n except IndexError:\n for i in range(len(self.network.rupee)):\n exp_rupee.append([])\n exp_ude.append([])\n exp_prediction.append([])\n\n track_rupee.append([])\n track_ude.append([])\n track_prediction.append([])\n\n exp_rupee[i].append(self.network.rupee[i])\n exp_ude[i].append(self.network.ude[i])\n exp_prediction[i].append(self.network.prediction[i])\n\n track_rupee[i].append(self.tracking_network.rupee[i])\n track_ude[i].append(self.tracking_network.ude[i])\n track_prediction[i].append(self.tracking_network.prediction[i])\n\n self.network = self.configure_gvfs_net() # reset network\n self.tracking_network = self.configure_tracking_gvfs()\n with open('results/experiment_results.pkl', \"wb\") as f:\n pickle.dump(\n {\n 'predictive_rupee': exp_rupee,\n 'predictive_ude': exp_ude,\n 'predictive_predictions' : exp_prediction,\n 'tracking_rupee': track_rupee,\n 'tracking_ude' : track_ude,\n 'tracking_predictions' : track_prediction,\n 'environment_values' : true_values,\n },\n f\n )\n\n for i in range(len(exp_rupee)):\n exp_prediction[i] = np.average(exp_prediction[i], axis=0)\n exp_ude[i] = np.average(exp_ude[i], axis=0)\n exp_rupee[i] = np.average(exp_rupee[i], axis=0)\n track_prediction[i] = np.average(track_prediction[i], axis=0)\n track_ude[i] = np.average(track_ude[i], axis=0)\n track_rupee[i] = np.average(track_rupee[i], axis=0)\n\n system('say your experiment is finished')\n print(\"plotting\")\n for i in [0,1]:\n pyplot.plot(exp_rupee[i], label=\"predictor\")\n pyplot.plot(track_rupee[i], alpha=0.2, label=\"tracker\")\n pyplot.legend()\n pyplot.show()\n\n\n def start_controlling(self):\n \"\"\"Initializes the plotter and runs the experiment.\"\"\"\n # Loop until mission ends:\n while self.action_count < self.steps_before_prompting_for_action:\n # Select and send action. Need to sleep to give time for simulator to respond\n self.learn_from_behavior_policy_action()\n self.display.root.mainloop()\n print(\"Mission ended\")\n # Mission has ended.\n # re\n\nif __name__ == \"__main__\":\n # fg.read_gvf_weights()\n\n fg = Foreground(show_display=False, steps_before_updating_display=1000, steps_before_prompting_for_action=25000)\n fg.start()\n #fg.start_controlling()\n","sub_path":"tracking_vs_regular.py","file_name":"tracking_vs_regular.py","file_ext":"py","file_size_in_byte":27988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"572627729","text":"import discord\nimport json\nimport asyncio\n\n\nclass IntroBot(discord.Client):\n config = None\n enabled = True\n async def on_ready(self):\n print('RUNNING ON AS {0}'.format(self.user))\n self.ad = discord.Streaming(name='Jerrekt', url='https://www.twitch.tv/jerrekt/', twitch_name='twitch:jerrekt')\n await self.change_presence(activity=self.ad)\n\n async def on_message(self, message):\n member= message.author\n if member.id != 327540758741778433 and member.id != 226898480482877440:\n return\n content = message.content\n print(content)\n if content == ',ei':\n await self.change_presence(status=None, activity=None)\n self.enabled = True\n if self.ad is not None:\n await self.change_presence(activity=self.ad)\n elif content == ',fdis':\n await self.disconnect_voice()\n elif content == ',di':\n self.enabled = False\n await self.change_presence(status=None, activity=None)\n await self.change_presence(status=discord.Status.dnd, activity=None)\n elif content.startswith(',setad'):\n split = content.split()\n if len(split) < 3:\n await message.channel.send('Need title and channel name')\n return\n else:\n self.ad = discord.Streaming(name=split[1], url='http://www.twitch.tv/'+split[2]+'/')\n return\n elif content.startswith(',rl'):\n load_config()\n else:\n return\n await message.channel.send('Enable status: ' + str(self.enabled))\n\n async def on_voice_state_update(self, member, before, after):\n dict_songs = self.config['members']\n if not self.enabled:\n return\n if str(member.id) not in dict_songs:\n return\n if after.channel is not None and before.channel is not after.channel:\n if len(self.voice_clients) > 0:\n for x in self.voice_clients:\n if not x.is_playing():\n await x.disconnect(force=True)\n \n print('DETECTED MEMBER JOIN')\n vc = await after.channel.connect()\n audio_player = discord.FFmpegPCMAudio(dict_songs[str(member.id)])\n vc.play(audio_player, after=lambda e : print('Done loading'))\n \n while vc.is_playing():\n await asyncio.sleep(1/1000)\n\n audio_player.cleanup()\n await vc.disconnect(force=True)\n pass\n async def disconnect_voice(self):\n for x in self.voice_clients:\n await x.disconnect(force=True)\n def set_config(self, _config):\n self.config = _config\n\n\ndefault_config = json.dumps({\"token\": \"\", \"selfbot\": True, \"members\": {226898480482877440: 'sounds/justin.mp3'}},\n indent=4, sort_keys=True)\nbot = IntroBot()\n\ndef load_config():\n global config\n global loaded\n try:\n config = open(\"config.txt\", \"r\")\n except OSError:\n config = open(\"config.txt\", \"w+\")\n config.write(default_config)\n config.seek(0)\n loaded = json.loads(config.read())\n config.close()\n bot.set_config(loaded)\n\nload_config()\n\ntry:\n bot.run(loaded['token'], bot=not loaded['selfbot'])\nexcept discord.LoginFailure:\n print('Invalid token for selfbot: ' + str(loaded['selfbot'])) \n\n","sub_path":"introbot.py","file_name":"introbot.py","file_ext":"py","file_size_in_byte":3431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"142004779","text":"import networkx as nx\nimport pandas as pd\nimport math\nimport itertools as it\nimport numpy as np\n\ndef query(G, edges_df, nodes_df, ev_df, queries_id, max_linkers):\n \n edges_df = edges_df.drop_duplicates(subset=['source_id', 'target_id'], keep=\"first\")\n\n output_num = math.factorial(len(queries_id))/(2*math.factorial((len(queries_id) - 2)))\n\n q_combinations = it.combinations(queries_id, 2)\n \n no_path=open(\"no_path.txt\",\"w\")\n\n stored_paths = {}\n for query_pair in q_combinations:\n source, target = query_pair\n try: \n stored_paths[f\"{source} -> {target}\"] = nx.shortest_path(G, source, target)\n except nx.NetworkXNoPath:\n no_path.write(f\"{source} -> {target} \\n\")\n pass\n except nx.NodeNotFound:\n pass\n\n query_nodes = {\"Query_Ids\": []}\n for key in stored_paths:\n for node in stored_paths[key]:\n query_nodes[\"Query_Ids\"].append(node)\n\n query_nodes[\"Query_Ids\"] = list(set(query_nodes[\"Query_Ids\"]))\n\n query_nodes_df = pd.DataFrame.from_dict(query_nodes)\n\n\n # Gets the labels for a Query Id.\n nodes_df = nodes_df.drop_duplicates(subset='Only_Id', keep=\"first\")\n node_merged_df = pd.merge(nodes_df, query_nodes_df, how=\"inner\", left_on=\"Only_Id\", right_on=\"Query_Ids\")[[\"Id\", \"Label\", \"Query_Ids\"]]\n node_merged_df.columns = [\"FullName\", \"Label\", \"Id\"]\n\n\n expanded_paths = {}\n for key in stored_paths:\n breakdown_list = stored_paths[key]\n if breakdown_list != None:\n sub_pairings = []\n for i in range(0, len(breakdown_list) - 1):\n sub_pairings.append(tuple([breakdown_list[i], breakdown_list[i + 1]]))\n expanded_paths[key] = sub_pairings\n if breakdown_list == None:\n expanded_paths[key] = None\n\n # Create a dictionary for all pair interactions\n edges_merger = {\n \"Source_Id\": [],\n \"Target_Id\": []\n }\n for key in expanded_paths:\n for pair in expanded_paths[key]:\n edges_merger[\"Source_Id\"].append(pair[0])\n edges_merger[\"Target_Id\"].append(pair[1])\n\n deletion_keys = []\n\n for key in expanded_paths:\n i = 2\n if len(expanded_paths[key]) > max_linkers + 2:\n deletion_keys.append(key)\n\n for key in deletion_keys:\n del expanded_paths[key]\n\n edges_merger_df = pd.DataFrame.from_dict(edges_merger)\n edges_merger_df = edges_merger_df.drop_duplicates(subset=['Source_Id', 'Target_Id'], keep=\"first\")\n edges_merged_df = pd.merge(edges_df, edges_merger_df, how=\"inner\", left_on=[\"source_id\", \"target_id\"], right_on=[\"Source_Id\", \"Target_Id\"])\n\n edges_merged_df = edges_merged_df[[\"source\", \"source_id\", \"target\", \"target_id\", \"color_col\", \"thickness\"]]\n edges_merged_df=pd.merge(edges_merged_df, ev_df, how=\"inner\", on=[\"source_id\",\"target_id\"])[[\"source\", \"source_id\", \"target\", \"target_id\", \"color_col\", \"thickness\", \"evidence\"]]\n edges_merged_df.columns = [\"source_lab\", \"source\", \"target_lab\", \"target\", \"color_col\", \"thickness\", \"evidence\"]\n\n \n node_merged_df.to_csv(\"query_nodes.csv\", index=False)\n edges_merged_df.to_csv(\"query_edges.csv\", index=False)\n \n\n","sub_path":"Query/.ipynb_checkpoints/llNetxQuery-checkpoint.py","file_name":"llNetxQuery-checkpoint.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"352269022","text":"import unittest\nimport os.path\nimport numpy as np\nimport numpy.lib.recfunctions as rfn\nfrom geodepy.convert import hp2dec, dec2hp\nfrom geodepy.geodesy import vincinv, vincdir, vincinv_utm, vincdir_utm\n\n\nclass TestGeodesy(unittest.TestCase):\n def test_vincinv(self):\n # Flinders Peak\n lat1 = hp2dec(-37.57037203)\n long1 = hp2dec(144.25295244)\n # Buninyong\n lat2 = hp2dec(-37.39101561)\n long2 = hp2dec(143.55353839)\n ell_dist, azimuth1to2, azimuth2to1 = vincinv(lat1, long1, lat2, long2)\n self.assertEqual(round(ell_dist, 3), 54972.271)\n self.assertEqual(round(dec2hp(azimuth1to2), 6), 306.520537)\n self.assertEqual(round(dec2hp(azimuth2to1), 6), 127.102507)\n\n def test_vincdir(self):\n # Flinders Peak\n lat1 = hp2dec(-37.57037203)\n long1 = hp2dec(144.25295244)\n # To Buninyong\n azimuth1to2 = hp2dec(306.520537)\n ell_dist = 54972.271\n lat2, long2, azimuth2to1 = vincdir(lat1, long1, azimuth1to2, ell_dist)\n self.assertEqual(round(dec2hp(lat2), 8), -37.39101561)\n self.assertEqual(round(dec2hp(long2), 8), 143.55353839)\n self.assertEqual(round(dec2hp(azimuth2to1), 6), 127.102507)\n\n def test_vincinv_utm(self):\n # Flinders Peak (UTM)\n zone1 = 55\n east1 = 273741.2966\n north1 = 5796489.7769\n # Buninyong (UTM)\n zone2 = 54\n east2 = 758173.7973\n north2 = 5828674.3402\n ell_dist, azimuth1to2, azimuth2to1 = vincinv_utm(zone1, east1, north1, zone2, east2, north2)\n self.assertEqual(round(ell_dist, 3), 54972.271)\n self.assertEqual(round(dec2hp(azimuth1to2), 6), 306.520537)\n self.assertEqual(round(dec2hp(azimuth2to1), 6), 127.102507)\n\n def test_vincdir_utm(self):\n # Flinders Peak (UTM)\n zone1 = 55\n east1 = 273741.2966\n north1 = 5796489.7769\n # To Buninyong\n azimuth1to2 = hp2dec(306.520537)\n ell_dist = 54972.271\n hemisphere2, zone2, east2, north2, azimuth2to1 = vincdir_utm(zone1, east1, north1, azimuth1to2, ell_dist)\n self.assertEqual(hemisphere2, 'South')\n self.assertEqual(zone2, 54)\n self.assertEqual(round(east2, 4), 758173.7968)\n self.assertEqual(round(north2, 4), 5828674.3395)\n self.assertEqual(round(dec2hp(azimuth2to1), 6), 127.102507)\n\n def test_equality_vincentys(self):\n # Test multiple point-to-point vincinv calculations\n abs_path = os.path.abspath(os.path.dirname(__file__))\n\n test_geo_coords =\\\n np.genfromtxt(os.path.join(abs_path,\n 'resources/Test_Conversion_Geo.csv'),\n delimiter=',',\n dtype='S4,f8,f8',\n names=['site', 'lat1', 'long1'],\n usecols=('lat1', 'long1'))\n\n test_geo_coord2 = \\\n np.genfromtxt(os.path.join(abs_path,\n 'resources/Test_Conversion_Geo.csv'),\n delimiter=',',\n dtype='S4,f8,f8',\n names=['site', 'lat2', 'long2'],\n usecols=('lat2', 'long2'))\n\n # Form array with point pairs from test file\n test_pairs = rfn.merge_arrays([test_geo_coords, np.roll(test_geo_coord2, 1)], flatten=True)\n\n # Calculate Vincenty's Inverse Result using Lat, Long Pairs\n vincinv_result = np.array(list(vincinv(*x) for x in test_pairs[['lat1', 'long1', 'lat2', 'long2']]))\n\n # Calculate Vincenty's Direct Result using Results from Inverse Function\n vincdir_input = rfn.merge_arrays([test_geo_coords, vincinv_result[:, 1], vincinv_result[:, 0]], flatten=True)\n vincdir_input.dtype.names = ['lat1', 'long1', 'az1to2', 'ell_dist']\n vincdir_result = np.array(list(vincdir(*x) for x in vincdir_input[['lat1', 'long1', 'az1to2', 'ell_dist']]))\n\n np.testing.assert_almost_equal(test_pairs['lat2'],\n vincdir_result[:, 0], decimal=8)\n np.testing.assert_almost_equal(test_pairs['long2'],\n vincdir_result[:, 1], decimal=8)\n np.testing.assert_almost_equal(vincinv_result[:, 2],\n vincdir_result[:, 2])\n\n def test_vincinv_edgecases(self):\n lat1 = -32.153892\n lon1 = -15.394827\n lat2 = -31.587369\n lon2 = -13.487739\n gdist, az12, az21 = vincinv(lat1, lon1, lat2, lon2)\n lon1 = lon1 + 14\n lon2 = lon2 + 14\n gdist_2, az12_2, az21_2 = vincinv(lat1, lon1, lat2, lon2)\n self.assertEqual(gdist, gdist_2)\n self.assertEqual(az12, az12_2)\n self.assertEqual(az21, az21_2)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"geodepy/tests/test_geodesy.py","file_name":"test_geodesy.py","file_ext":"py","file_size_in_byte":4944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"430678261","text":"from datetime import date\n\nimport pytest\n\nfrom src.people.domain_models.models import Person\nfrom src.people.repository.exceptions import RepositoryException\nfrom src.people.repository.repository import SqlAlchemyRepository\n\n\ndef insert_person(session, gender, title, first_name, second_name, date_of_birth):\n session.execute(\n 'INSERT INTO \"person\" (gender, title, first_name, second_name, date_of_birth) '\n 'VALUES '\n '(:gender, :title, :first_name, :second_name, :date_of_birth)',\n dict(gender=gender, title=title, first_name=first_name,\n second_name=second_name, date_of_birth=date_of_birth)\n )\n [[person_id]] = session.execute(\n 'SELECT id FROM person WHERE gender=:gender AND title=:title AND '\n 'first_name=:first_name AND second_name=:second_name AND '\n 'date_of_birth=:date_of_birth',\n dict(gender=gender, title=title, first_name=first_name,\n second_name=second_name, date_of_birth=date_of_birth)\n )\n\n return person_id\n\n\ndef populated_db_fixture(session):\n insert_person(session, 'male', 'mr', 'john', 'doe', '1997-01-01')\n insert_person(session, 'male', 'mr', 'mike', 'doe', '1998-01-01')\n insert_person(session, 'female', 'ms', 'jane', 'smith', '1999-01-01')\n\n\ndef test_repository_can_save_user(session, user_factory_fixture):\n user = user_factory_fixture()\n\n repo = SqlAlchemyRepository(session)\n repo.add(user)\n session.commit()\n\n rows = list(session.execute(\n 'SELECT * FROM user'\n ))\n assert rows == [(1, 1, 1, 1, 1, 1)]\n\n\ndef test_repository_can_retrieve_model(session):\n person_id = insert_person(session, 'male', 'mr', 'john', 'doe', '1997-01-01')\n\n repo = SqlAlchemyRepository(session)\n retrieved = repo.get(Person, person_id)\n\n expected_person = Person('male', 'mr', 'john', 'doe',\n date.fromisoformat('1997-01-01'))\n\n assert retrieved.gender == expected_person.gender\n assert retrieved.title == expected_person.title\n assert retrieved.first_name == expected_person.first_name\n assert retrieved.second_name == expected_person.second_name\n assert retrieved.date_of_birth == expected_person.date_of_birth\n\n\ndef test_repository_group_by(session):\n populated_db_fixture(session)\n\n repo = SqlAlchemyRepository(session)\n retrieved = repo.group_by_and_count(Person, 'gender', limit=1)\n\n assert retrieved[0][0].gender == 'male'\n assert retrieved[0][1] == 2\n\n\ndef test_repository_group_by_not_existing_column(session):\n populated_db_fixture(session)\n\n repo = SqlAlchemyRepository(session)\n with pytest.raises(RepositoryException):\n retrieved = repo.group_by_and_count(Person, 'idontexist', limit=1)\n\n\ndef test_repository_filter_by_between(session):\n populated_db_fixture(session)\n\n repo = SqlAlchemyRepository(session)\n retrieved = repo.filter_person_by_date_of_birth(date.fromisoformat('1998-01-01'),\n date.fromisoformat('1999-01-01'))\n\n assert len(retrieved) == 2\n assert retrieved[0].date_of_birth == date.fromisoformat('1998-01-01')\n assert retrieved[1].date_of_birth == date.fromisoformat('1999-01-01')\n\n\ndef test_filter_by(session):\n populated_db_fixture(session)\n\n repo = SqlAlchemyRepository(session)\n filters = {'gender': 'male', 'date_of_birth': date.fromisoformat('1998-01-01')}\n retrieved = repo.filter_model_by(Person, **filters)\n\n assert retrieved[0].gender == 'male'\n assert retrieved[0].date_of_birth == date.fromisoformat('1998-01-01')\n\n\ndef test_filter_by_not_existing_columns(session):\n populated_db_fixture(session)\n\n repo = SqlAlchemyRepository(session)\n filters = {'idontexist': 'male', 'andmetoo': date.fromisoformat('1998-01-01')}\n\n with pytest.raises(RepositoryException):\n retrieved = repo.filter_model_by(Person, **filters)\n","sub_path":"tests/integration/test_repository.py","file_name":"test_repository.py","file_ext":"py","file_size_in_byte":3886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"37710501","text":"import tensorflow\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom tensorflow.keras import layers\r\nfrom keras.utils import np_utils\r\nfrom keras.datasets import mnist\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense,Dropout, Flatten, Conv2D, MaxPooling2D\r\n#%matplotlib inline\r\n\r\ndef show_train_history(train_history, train, validation):\r\n plt.plot(train_history.history[train])\r\n plt.plot(train_history.history[validation])\r\n plt.title('Train History')\r\n plt.ylabel(\"Acc\")\r\n plt.xlabel(\"Epoch\")\r\n plt.legend(['train', 'validation'], loc='upper left')\r\n plt.show\r\n \r\n\r\ndef plot_images_labels_prediction(images, labels, prediction, idx, num = 10):\r\n fig = plt.gcf()\r\n fig.set_size_inches(12, 14)\r\n if num>25:\r\n num = 25\r\n for i in range(0, num):\r\n ax = plt.subplot(5, 5, 1+i)\r\n ax.imshow(images[idx], cmap = 'binary')\r\n title = \"label = \" + str(labels[idx])\r\n if len(prediction)>0:\r\n title += \", predict = \" +str(prediction[idx]) \r\n ax.set_title(title, fontsize=10)\r\n ax.set_xticks([])\r\n ax.set_yticks([])\r\n idx+=1\r\n plt.show()\r\n \r\n#----------------------------------------------------------------------------------------------\r\n\r\n\r\n(x_train_image, y_train_label), (x_test_image, y_test_label) = mnist.load_data()\r\n\r\nx_Train = x_train_image.reshape(60000, 28, 28, 1).astype('float32')\r\nx_Test = x_test_image.reshape(10000, 28, 28, 1).astype('float32')\r\n\r\nx_Train_normalize = x_Train/255\r\nx_Test_normalize = x_Test/255\r\n\r\ny_Train_OneHot = np_utils.to_categorical(y_train_label)\r\ny_Test_OneHot = np_utils.to_categorical(y_test_label)\r\n\r\nmodel = Sequential()\r\n\r\nmodel.add(Conv2D(filters=16,\r\n kernel_size=(5, 5),\r\n padding='same',\r\n input_shape=(28, 28, 1),\r\n activation='relu'))\r\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\r\nmodel.add(Conv2D(filters=36,\r\n kernel_size=(5, 5),\r\n padding='same',\r\n activation='relu'))\r\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\r\nmodel.add(Dropout(0.25))\r\nmodel.add(Flatten())\r\nmodel.add(Dense(128, activation='relu'))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(10, activation='softmax'))\r\n\r\nprint(model.summary())\r\n\r\nmodel.compile(loss='categorical_crossentropy',\r\n optimizer='adam',\r\n metrics=['accuracy'])\r\n\r\ntrain_history = model.fit(x=x_Train_normalize,\r\n y=y_Train_OneHot, \r\n validation_split=0.25,\r\n epochs=10,\r\n batch_size=200,\r\n verbose=2)\r\n\r\n\r\n\r\n\r\n\r\n\r\nshow_train_history(train_history, 'accuracy', 'val_accuracy')\r\n\r\nscores = model.evaluate(x_Test_normalize, y_Test_OneHot)\r\nprint()\r\nprint()\r\nprint()\r\nprint('accuracy = ', scores[1])\r\nprint('loss = ', scores[0])\r\n\r\n\r\n#-----------------------------------------------------------------------\r\nprediction = model.predict_classes(x_Test)\r\n#print(prediction)\r\n\r\nplot_images_labels_prediction(x_test_image, y_test_label, prediction, idx=340, num=25)\r\n\r\n#pd.crosstab(y_test_label, prediction, colnames=['predict'], rownames=['label'])\r\n","sub_path":"99% CNN MNIST Keras.py","file_name":"99% CNN MNIST Keras.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"631276178","text":"import os\n\nfrom threading import Thread\nimport subprocess\nimport platform\nfrom Queue import Queue\n\n\ndef ping_hosts(hosts, logger):\n \"\"\"\n Check that hosts are available.\n Each host ping in separate thread\n \"\"\"\n queue = Queue()\n res_queue = Queue()\n num_threads = len(hosts)\n\n #Place work in queue\n for host in hosts:\n queue.put(host.host)\n\n #Spawn thread pool\n for i in xrange(num_threads):\n thread = Thread(target=pinger, args=(i, queue, res_queue, logger))\n thread.setDaemon(False)\n thread.start()\n\n #Wait until worker threads are done to exit\n queue.join()\n if not res_queue.empty():\n return False\n return True\n\n\n# wraps system ping command\ndef pinger(i, q, r, logger):\n \"\"\"Pings host from queue\"\"\"\n result = True\n while True:\n host = q.get()\n logger.debug(\"Pinging %s\" % host)\n\n plat = platform.system()\n ret = None\n if plat == 'Windows':\n ret = subprocess.call(\"ping -n 1 -l 1 -w 100 %s\" % host,\n shell=True,\n stdout=open(os.devnull, 'w'),\n stderr=subprocess.STDOUT)\n elif plat == 'Linux':\n ret = subprocess.call(\"ping -c 1 %s\" % host,\n shell=True,\n stdout=open(os.devnull, 'w'),\n stderr=subprocess.STDOUT)\n if ret == 0:\n logger.debug(\"%s: is alive\" % host)\n result = False\n else:\n logger.error(\"%s: did not respond\" % host)\n r.put(1)\n q.task_done()\n if q.empty():\n break\n return result\n","sub_path":"p90diag/common/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"232150718","text":"\"\"\"Extract, clean, and normalize the EPACAMD-EIA crosswalk.\n\nThis module defines functions that read the raw EPACAMD-EIA crosswalk file and clean\nup the column names.\n\nThe crosswalk file was a joint effort on behalf on EPA and EIA and is published on the\nEPA's github account at www.github.com/USEPA/camd-eia-crosswalk\". It's a work in\nprogress and worth noting that, at present, only pulls from 2018 data.\n\"\"\"\nimport pandas as pd\n\nimport pudl.logging_helpers\nfrom pudl.helpers import remove_leading_zeros_from_numeric_strings, simplify_columns\nfrom pudl.metadata.fields import apply_pudl_dtypes\nfrom pudl.workspace.datastore import Datastore\n\nlogger = pudl.logging_helpers.get_logger(__name__)\n\n\ndef extract(ds: Datastore) -> pd.DataFrame:\n \"\"\"Extract the EPACAMD-EIA Crosswalk from the Datastore.\"\"\"\n logger.info(\"Extracting the EPACAMD-EIA crosswalk from Zenodo\")\n with ds.get_zipfile_resource(\"epacamd_eia\", name=\"epacamd_eia.zip\").open(\n \"camd-eia-crosswalk-master/epa_eia_crosswalk.csv\"\n ) as f:\n return pd.read_csv(f)\n\n\ndef transform(\n epacamd_eia: pd.DataFrame,\n generators_entity_eia: pd.DataFrame,\n boilers_entity_eia: pd.DataFrame,\n processing_all_eia_years: bool,\n) -> dict[str, pd.DataFrame]:\n \"\"\"Clean up the EPACAMD-EIA Crosswalk file.\n\n In its raw form, the crosswalk contains many fields. The transform process removes\n descriptive fields like state, location, facility name, capacity, operating status,\n and fuel type that can be found by linking this dataset to others already in the\n database. We're primarily concerned with linking ids in this table, not including\n any other plant information.\n\n The raw file contains several fields with the prefix `MOD`. These fields are used to\n create a single ID for matches with different spelling. For example, `EIA_PLANT_ID`\n (`plant_id_eia` in PUDL) has the generator ID `CTG5` in EPA and `GT5` in EIA. The\n `MOD` columns for both of these generators (`MOD_CAMD_GENERATOR_ID`,\n `MOD_EIA_GENERATOR_ID_GEN`) converts that value to 5. The `MATCH_TYPE_GEN`,\n `MATCH_TYPE_BOILER`, and `PLANT_ID_CHANGE_FLAG` fields indicate whether these `MOD`\n fields contain new information. Because we're not concerned with creating a new,\n modified ID field for either EPA or EIA data, we don't need these `MOD` or\n `MATCH_TYPE` columns in our final output. We just care which EPA value maps to which\n EIA value.\n\n In terms of cleaning, we implement the standard column name changes: lower-case, no\n special characters, and underscores instead of spaces. We also rename some of the\n columns for clarity and to match how they appear in the tables you will merge with.\n Besides standardizing datatypes (again for merge compatability) the only meaningful\n data alteration we employ here is removing leading zeros from numeric strings on\n the `generator_id` and `emissions_unit_id_epa` fields. This is because the same\n function is used to clean those same fields in all the other tables in which they\n appear. In order to merge properly, we need to clean the values in the crosswalk the\n same way. Lastly, we drop all rows without `EIA_PLANT_ID` (`plant_id_eia`) values\n because that means that they are unmatched and do not provide any useful information\n to users.\n\n It's important to note that the crosswalk is kept intact (and not seperated into\n smaller reference tables) because the relationship between the ids is not 1:1. For\n example, you can't isolate the plant_id fields, drop duplicates, and call it a day.\n The plant discrepancies depend on which generator ids it's referring to. This goes\n for all fields. Be careful, and do some due diligence before eliminating columns.\n\n We talk more about the complexities regarding EPA \"units\" in our Data Source\n documentation page for EPACEMS:\n https://catalystcoop-pudl.readthedocs.io/en/dev/data_sources/epacems.html\n\n It's also important to note that the crosswalk is a static file: there is no year\n field. The plant_id_eia and generator_id fields, however, are foreign keys from an\n annualized table. If the fast ETL is run (on one year of data) the test will break\n because the crosswalk tables with plant_id_eia and generator_id contain values from\n various years. To keep the crosswalk in alignment with the available eia data, we'll\n restrict it based on the generator entity table which has plant_id_eia and\n generator_id so long as it's not using the full suite of avilable years. If it is,\n we don't want to restrict the crosswalk so we can get warnings and errors from any\n foreign key discrepancies. This isn't an ideal solution, but it works for now.\n\n Args:\n epacamd_eia: The result of running this module's extract() function.\n generators_entity_eia: The generators_entity_eia table.\n boilers_entity_eia: The boilers_entitiy_eia table.\n processing_all_years: A boolean indicating whether the years from the\n Eia860Settings object match the EIA860 working partitions. This indicates\n whether or not to restrict the crosswalk data so the tests don't fail on\n foreign key restraints.\n\n Returns:\n A dictionary containing the cleaned EPACAMD-EIA crosswalk DataFrame.\n \"\"\"\n logger.info(\"Transforming the EPACAMD-EIA crosswalk\")\n\n column_rename = {\n \"camd_plant_id\": \"plant_id_epa\",\n \"camd_unit_id\": \"emissions_unit_id_epa\",\n \"camd_generator_id\": \"generator_id_epa\",\n \"eia_plant_id\": \"plant_id_eia\",\n \"eia_boiler_id\": \"boiler_id\", # Eventually change to boiler_id_eia\n \"eia_generator_id\": \"generator_id\", # Eventually change to generator_id_eia\n }\n\n # Basic column rename, selection, and dtype alignment.\n crosswalk_clean = (\n epacamd_eia.pipe(simplify_columns)\n .rename(columns=column_rename)\n .filter(list(column_rename.values()))\n .pipe(remove_leading_zeros_from_numeric_strings, col_name=\"generator_id\")\n .pipe(\n remove_leading_zeros_from_numeric_strings, col_name=\"emissions_unit_id_epa\"\n )\n .pipe(apply_pudl_dtypes, \"eia\")\n .dropna(subset=[\"plant_id_eia\"])\n )\n\n # Restrict crosswalk for tests if running fast etl\n if not processing_all_eia_years:\n logger.info(\n \"Selected subset of avilable EIA years--restricting EPACAMD-EIA Crosswalk \\\n to chosen subset of EIA years\"\n )\n crosswalk_clean = pd.merge(\n crosswalk_clean,\n generators_entity_eia[[\"plant_id_eia\", \"generator_id\"]],\n on=[\"plant_id_eia\", \"generator_id\"],\n how=\"inner\",\n )\n crosswalk_clean = pd.merge(\n crosswalk_clean,\n boilers_entity_eia[[\"plant_id_eia\", \"boiler_id\"]],\n on=[\"plant_id_eia\", \"boiler_id\"],\n how=\"inner\",\n )\n\n return {\"epacamd_eia\": crosswalk_clean}\n","sub_path":"src/pudl/glue/epacamd_eia.py","file_name":"epacamd_eia.py","file_ext":"py","file_size_in_byte":6976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"281759903","text":"# -*- coding: UTF-8 -*-\n# Copyright 2011-2014 Luc Saffre\n# License: BSD (see file COPYING for details)\n\n\"\"\"\nPart of the :xfile:`models` module for the :mod:`lino.modlib.cal` app.\n\nDefines the :class:`Task` model and its tables.\n\"\"\"\n\nfrom __future__ import unicode_literals\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom django.conf import settings\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom lino.api import dd\nfrom lino import mixins\n\nfrom .models import Component\n\nfrom .workflows import TaskStates\n\n\nclass Task(Component):\n \"\"\"A Task is when a user plans to to something\n (and optionally wants to get reminded about it).\n\n .. attribute:: state\n \n The state of this Task. one of :class:`TaskStates`\n\n\n \"\"\"\n class Meta:\n verbose_name = _(\"Task\")\n verbose_name_plural = _(\"Tasks\")\n abstract = dd.is_abstract_model(__name__, 'Task')\n\n due_date = models.DateField(\n blank=True, null=True,\n verbose_name=_(\"Due date\"))\n due_time = models.TimeField(\n blank=True, null=True,\n verbose_name=_(\"Due time\"))\n # ~ done = models.BooleanField(_(\"Done\"),default=False) # iCal:COMPLETED\n # iCal:PERCENT\n percent = models.IntegerField(_(\"Duration value\"), null=True, blank=True)\n state = TaskStates.field(default=TaskStates.todo) # iCal:STATUS\n # ~ status = models.ForeignKey(TaskStatus,verbose_name=_(\"Status\"),blank=True,null=True) # iCal:STATUS\n\n #~ @dd.action(_(\"Done\"),required=dict(states=['','todo','started']))\n #~ @dd.action(TaskState.todo.text,required=dict(states=['']))\n #~ def mark_todo(self,ar):\n #~ self.state = TaskState.todo\n #~ self.save()\n #~ return ar.success_response(refresh=True)\n\n #~ @dd.action(TaskState.done.text,required=dict(states=['','todo','started']))\n #~ def mark_done(self,ar):\n #~ self.state = TaskState.done\n #~ self.save()\n #~ return ar.success_response(refresh=True)\n\n #~ @dd.action(TaskState.started.text,required=dict(states=['','todo']))\n #~ def mark_started(self,ar):\n #~ self.state = TaskState.started\n #~ self.save()\n #~ return ar.success_response(refresh=True)\n\n #~ @dd.action(TaskState.sleeping.text,required=dict(states=['','todo']))\n #~ def mark_sleeping(self,ar):\n #~ self.state = TaskState.sleeping\n #~ self.save()\n #~ return ar.success_response(refresh=True)\n\n def before_ui_save(self, ar, **kw):\n if self.state == TaskStates.todo:\n self.state = TaskStates.started\n return super(Task, self).before_ui_save(ar, **kw)\n\n #~ def on_user_change(self,request):\n #~ if not self.state:\n #~ self.state = TaskState.todo\n #~ self.user_modified = True\n\n def is_user_modified(self):\n return self.state != TaskStates.todo\n\n @classmethod\n def on_analyze(cls, lino):\n #~ lino.TASK_AUTO_FIELDS = dd.fields_list(cls,\n cls.DISABLED_AUTO_FIELDS = dd.fields_list(\n cls, \"\"\"start_date start_time summary\"\"\")\n super(Task, cls).on_analyze(lino)\n\n #~ def __unicode__(self):\n # ~ return \"#\" + str(self.pk)\n\n\nclass Tasks(dd.Table):\n help_text = _(\"\"\"A calendar task is something you need to do.\"\"\")\n model = 'cal.Task'\n required = dd.required(user_groups='office', user_level='manager')\n column_names = 'start_date summary workflow_buttons *'\n order_by = [\"start_date\", \"start_time\"]\n\n detail_layout = \"\"\"\n start_date due_date id workflow_buttons\n summary\n user project\n #event_type owner created:20 modified:20\n description #notes.NotesByTask\n \"\"\"\n\n insert_layout = dd.FormLayout(\"\"\"\n summary\n user project\n \"\"\", window_size=(50, 'auto'))\n\n params_panel_hidden = True\n\n parameters = mixins.ObservedPeriod(\n user=dd.ForeignKey(settings.SITE.user_model,\n verbose_name=_(\"Managed by\"),\n blank=True, null=True,\n help_text=_(\"Only rows managed by this user.\")),\n project=dd.ForeignKey(settings.SITE.project_model,\n blank=True, null=True),\n state=TaskStates.field(blank=True,\n help_text=_(\"Only rows having this state.\")),\n )\n\n params_layout = \"\"\"\n start_date end_date user state project\n \"\"\"\n\n @classmethod\n def get_request_queryset(self, ar):\n #~ logger.info(\"20121010 Clients.get_request_queryset %s\",ar.param_values)\n qs = super(Tasks, self).get_request_queryset(ar)\n\n if ar.param_values.user:\n qs = qs.filter(user=ar.param_values.user)\n\n if settings.SITE.project_model is not None and ar.param_values.project:\n qs = qs.filter(project=ar.param_values.project)\n\n if ar.param_values.state:\n qs = qs.filter(state=ar.param_values.state)\n\n if ar.param_values.start_date:\n qs = qs.filter(start_date__gte=ar.param_values.start_date)\n if ar.param_values.end_date:\n qs = qs.filter(start_date__lte=ar.param_values.end_date)\n return qs\n\n @classmethod\n def get_title_tags(self, ar):\n for t in super(Tasks, self).get_title_tags(ar):\n yield t\n if ar.param_values.start_date or ar.param_values.end_date:\n yield unicode(_(\"Dates %(min)s to %(max)s\") % dict(\n min=ar.param_values.start_date or'...',\n max=ar.param_values.end_date or '...'))\n\n if ar.param_values.state:\n yield unicode(ar.param_values.state)\n\n if ar.param_values.user:\n yield unicode(ar.param_values.user)\n\n if settings.SITE.project_model is not None and ar.param_values.project:\n yield unicode(ar.param_values.project)\n\n @classmethod\n def apply_cell_format(self, ar, row, col, recno, td):\n \"\"\"\n Enhance today by making background color a bit darker.\n \"\"\"\n if row.start_date == settings.SITE.today():\n td.attrib.update(bgcolor=\"gold\")\n\n\nclass TasksByController(Tasks):\n master_key = 'owner'\n required = dd.required(user_groups='office')\n column_names = 'start_date summary workflow_buttons id'\n #~ hidden_columns = set('owner_id owner_type'.split())\n auto_fit_column_widths = True\n\nif settings.SITE.user_model:\n\n class TasksByUser(Tasks):\n \"\"\"\n Shows the list of automatically generated tasks for this user.\n \"\"\"\n master_key = 'user'\n required = dd.required(user_groups='office')\n\n class MyTasks(Tasks):\n \"\"\"All my tasks. Only those whose start_date is today or in the\nfuture. This table is used in\n:meth:`lino_welfare.projects.base.Site.get_admin_item`.\n\n \"\"\"\n label = _(\"My tasks\")\n required = dd.required(user_groups='office')\n #~ required = dict()\n help_text = _(\"Table of all my tasks.\")\n column_names = 'start_date summary workflow_buttons project'\n params_panel_hidden = True\n\n @classmethod\n def param_defaults(self, ar, **kw):\n kw = super(MyTasks, self).param_defaults(ar, **kw)\n kw.update(user=ar.get_user())\n kw.update(state=TaskStates.todo)\n kw.update(start_date=settings.SITE.today())\n return kw\n\n\nif settings.SITE.project_model:\n\n class TasksByProject(Tasks):\n required = dd.required(user_groups='office')\n master_key = 'project'\n column_names = 'start_date user summary workflow_buttons *'\n\n","sub_path":"lino/modlib/cal/models_task.py","file_name":"models_task.py","file_ext":"py","file_size_in_byte":7561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"485380738","text":"\n\n\n\n\n\n\ndef main():\n z = input(\"What file do you want to use? (test.txt for test) \")\n f = open(z, \"r\")\n k = [] \n for line in f :\n k.append(line[0:len(line)])\n p = k[0] \n s = k[1:len(k)] \n for i in range(len(s)): \n m = mismatches(p,s[i])\n m.sort()\n x = m[0] \n n = position(p,s[i],x)\n print(\"Sequence\",i+1,\"has\",x,\"errors at position\",n)\n\ndef mismatches(p,s): \n m = []\n for i in range(0,len(p)-len(s)-1): \n mismatch = 0\n for j in range(0,len(s)-1): \n if p[j+i] != s[j]:\n mismatch = mismatch + 1\n m.append(mismatch)\n return m\n\ndef position(p,s,x):\n n = 0\n for i in range(0,len(p)-len(s)-1): \n mismatch = 0\n for j in range(0,len(s)-1): \n if p[j+i] != s[j]:\n mismatch = mismatch + 1\n if mismatch == x:\n n = i\n break\n return n\n \nmain()","sub_path":"testFiles/match/match32.py","file_name":"match32.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"597074747","text":"#!/usr/bin/python3\n\"\"\"\nThis module hold a function that prints a square with the character #.\n\"\"\"\n\n\ndef print_square(size):\n \"\"\"\n This function prints square by the size\n Paramethers:\n size: length of the square\n Errors:\n TypeError: size must be an integer\n ValueError: size must be >= 0\n Returns:\n Nothing\n \"\"\"\n\n if type(size) is not int:\n raise TypeError(\"size must be an integer\")\n\n if size < 0:\n raise ValueError(\"size must be >= 0\")\n\n if (type(size) is float and size < 0):\n raise TypeError(\"size must be an integer\")\n\n for x in range(size):\n for y in range(size):\n print('#', end=\"\")\n print()\n","sub_path":"0x07-python-test_driven_development/4-print_square.py","file_name":"4-print_square.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"10996978","text":"word1 = ('Good')\nword2 = ('Cheese')\nword3 = ('Man')\nWord4 = ('Spoon')\n\nword1 = word1.replace ('oo', 'ooooo')\nword2 = word2.replace ('ee', 'eeeee')\nword3 = word3.replace ('a', 'aaaaa')\nWord4 = Word4.replace ('oo', 'ooooo')\n\nwords = [word1, word2, word3, Word4]\n\nfor word in words:\n print(word)\n","sub_path":"longvowel.py","file_name":"longvowel.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"10236112","text":"from openerp import models, fields, api\nfrom datetime import datetime, timedelta\nfrom openerp.tools.translate import _\nfrom openerp.exceptions import UserError\n\n\nimport logging\n_logger = logging.getLogger(__name__)\n\nclass hr_analytic_timesheet_improvements(models.Model):\n _inherit = 'account.analytic.line'\n\n _defaults = {\n 'is_timesheet ': lambda self, cr, uid, ctx=None: self._get_is_timesheet(cr, uid, context=ctx)\n }\n\n def _get_is_timesheet(self, cr, uid, context=None):\n if context is None:\n context = {}\n if 'default_is_timesheet' in context:\n if context['default_carrier_id']:\n return True \n return False\n\n def _get_default_date(self):\n return datetime.strftime(self.check_and_correct_date_in_fifteen_step(datetime.now()), '%Y-%m-%d %H:%M:%S')\n\n date_begin = fields.Datetime(string='Start Date', default=_get_default_date)\n \n def check_and_correct_date_in_fifteen_step(self, date):\n newdate = date\n newhour = newdate.hour\n step = 0\n round = False\n minute_under_fifteen = newdate.minute\n while (minute_under_fifteen > 15):\n minute_under_fifteen = minute_under_fifteen - 15\n step+=1\n if(minute_under_fifteen>=(15/2)):\n round = True\n if round:\n newminute = (step*15)+15\n if newminute==60:\n newdate = newdate + timedelta(hours=1)\n newminute = 0\n else:\n newminute = step*15\n \n newdate = newdate.replace(minute=newminute, second=0)\n return newdate\n\n # set the date of date_begin to \"date\" to avoid consistency problems\n @api.multi\n @api.onchange('date_begin')\n def copy_dates(self):\n self.date = self.date_begin\n\n @api.multi\n def write(self, vals):\n self._check_rights_to_write()\n newdate = False\n if vals.get('date_begin'):\n start_date = datetime.strptime(vals.get('date_begin'), '%Y-%m-%d %H:%M:%S')\n newdate = self.check_and_correct_date_in_fifteen_step(start_date)\n if start_date.minute != newdate.minute or start_date.second != newdate.second:\n vals.update({'date_begin': datetime.strftime(newdate, '%Y-%m-%d %H:%M:%S')})\n vals.update({'date': newdate.date()})\n \n result = super(hr_analytic_timesheet_improvements, self).write(vals)\n return result\n\n @api.model\n def create(self, vals):\n # Test if timesheet or not\n if vals.get('sheet_id'):\n if vals.get('date_begin'):\n start_date = datetime.strptime(vals.get('date_begin'), '%Y-%m-%d %H:%M:%S')\n newdate = self.check_and_correct_date_in_fifteen_step(start_date)\n if start_date.minute != newdate.minute or start_date.second != newdate.second:\n start_date = self.check_and_correct_date_in_fifteen_step(start_date)\n vals.update({'date_begin': datetime.strftime(start_date, '%Y-%m-%d %H:%M:%S')})\n vals.update({'date': newdate.date()})\n elif vals.get('date'):\n date = datetime.strptime(vals.get('date'), '%Y-%m-%d')\n date = self.check_and_correct_date_in_fifteen_step(date)\n vals.update({'date': date.date()})\n vals.update({'date_begin': datetime.strftime(date, '%Y-%m-%d %H:%M:%S')})\n else:\n date = self.check_and_correct_date_in_fifteen_step(datetime.now())\n vals.update({'date_begin': datetime.strftime(date, '%Y-%m-%d %H:%M:%S')})\n vals.update({'date': datetime.strftime(date, '%Y-%m-%d')})\n\n hr_analytic_timesheet_id = super(hr_analytic_timesheet_improvements, self).create(vals)\n return hr_analytic_timesheet_id\n\n def _set_date_begin_if_date_exits(self, cr, uid, ids=None, context=None):\n hr_analytic_timesheet_obj = self.pool.get('account.analytic.line')\n hr_analytic_timesheets = hr_analytic_timesheet_obj.search(cr, uid, [('date', 'like', '-')])\n if hr_analytic_timesheets:\n for hr_analytic_timesheet in hr_analytic_timesheet_obj.browse(cr, uid, hr_analytic_timesheets):\n if hr_analytic_timesheet.date:\n begin_date = datetime.strftime(datetime.strptime(hr_analytic_timesheet.date, '%Y-%m-%d').replace(hour=0,minute=0, second=0), '%Y-%m-%d %H:%M:%S')\n query = \"\"\"\n UPDATE account_analytic_line\n SET date_begin=%s\n WHERE id=%s\n \"\"\"\n cr.execute(query, (begin_date,hr_analytic_timesheet.id))\n\n @api.multi\n def unlink(self):\n self._check_rights_to_write()\n return super(hr_analytic_timesheet_improvements, self).unlink()\n\n # Inherit this method and call the new defined one instead\n # So, simply return True here\n def _check(self, cr, uid, ids):\n return True\n\n # The following method is called when writing on the AAL\n # I will inherit it to allow the HR Manager & Account Manager\n # to edit them even if the Timesheet is confirmed\n def _check_rights_to_write(self):\n f1 = self.env.user.has_group('base.group_hr_user')\n f2 = self.env.user.has_group('account.group_account_manager')\n if not (f1 or f2):\n for line in self:\n if line.sheet_id and line.sheet_id.state not in ('draft', 'new'):\n raise UserError(_('You cannot modify an entry in a confirmed timesheet. Only HR Officer and Account Manager can do it.'))\n return True","sub_path":"hr_analytic_timesheet_improvements/models/account_analytic_line.py","file_name":"account_analytic_line.py","file_ext":"py","file_size_in_byte":5693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"182122113","text":"# Compute whether the given year is a leap year.\n\n###################################################\n# Is leapyear formula\n# Student should enter function on the next lines.\ndef is_leap_year(year):\n\n if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:\n return True\n else:\n return False\n\n###################################################\n# Tests\n# Student should not change this code.\n\ndef test(year):\n\t\"\"\"Tests the is_leapyear function.\"\"\"\n\tif is_leap_year(year):\n\t\tprint(year, \"is a leap year.\")\n\telse:\n\t\tprint(year, \"is not a leap year.\")\n\ntest(2000)\ntest(1996)\ntest(1800)\ntest(2013)\ntest(2400)\ntest(2100)\ntest(2200)\ntest(2500)\n\n###################################################\n# Expected output\n# Student should look at the following comments and compare to printed output.\n\n#2000 is a leap year.\n#1996 is a leap year.\n#1800 is not a leap year.\n#2013 is not a leap year.\n","sub_path":"intro-cs/Introduction-to-Programming/fundamentals-of-computing/An Introduction to Interactive Programming in Python/Part1/1.week/b.Practice Exercises for Logic and Conditionals/is_leap_year.py","file_name":"is_leap_year.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"214474988","text":"from lights.PyGlow import PyGlow\nfrom time import sleep\nfrom threading import Thread\n\npyglow = PyGlow(speed = 1000) #max brightness 255\npyglow.all(0) #reset LEDs\n\nbrightness = 150\nspeed = 10\nspeed2 = 2\ncolors = [\"white\", \"blue\", \"green\", \"yellow\", \"orange\", \"red\"]\n\ndef pointWon():\n for c in colors:\n for i in range(0, brightness, speed):\n pyglow.color(c, i)\n for c in colors:\n for i in range(brightness, -1, -speed2):\n pyglow.color(c, i)\n\ndef asyncStart():\n t = Thread(target=pointWon)\n t.start()\n\n'''\nRED = [1,7,13]\nORANGE = [2,8,14]\nYELLOW = [3,9,15]\nGREEN = [4,10,16]\nBLUE = [5,11,17]\nWHITE = [6,12,18]\n'''\n","sub_path":"src/lights/LightFX.py","file_name":"LightFX.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"396267402","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Nov 3 15:57:38 2020\r\n\r\n@author: adharsh\r\n\"\"\"\r\nimport cv2\r\nimport numpy as np\r\nfrom tensorflow.keras.models import load_model\r\nfrom model_predict import prediction\r\nimport time\r\nimport math\r\n\r\n# Class for Streaming Webcam video\r\nclass VideoCamera(object):\r\n \r\n def __init__(self):\r\n self.prototxtPath = \"./face_detector/deploy.prototxt\"\r\n self.weightsPath =\"./face_detector/res10_300x300_ssd_iter_140000.caffemodel\"\r\n self.faceNet = cv2.dnn.readNet(self.prototxtPath,self.weightsPath)\r\n self.model=load_model('mv2_mask_detection.hdf5') \r\n #self.model=load_model('vgg19_mask_detection.hdf5') \r\n #self.model=load_model('effb7_mask_detection.hdf5') \r\n self.video = cv2.VideoCapture(0)\r\n \r\n def __del__(self):\r\n cv2.destroyAllWindows()\r\n self.video.release() \r\n \r\n # Get the webcamera video output apply model prediction on the frame and display with labels\r\n def get_frame(self):\r\n try:\r\n ret, frame = self.video.read()\r\n now=time.time()\r\n (locs, preds) = prediction(frame,self.faceNet,self.model)\r\n for (box, pred) in zip(locs, preds):\r\n (startX, startY, endX, endY) = box\r\n cla=np.argmax(pred[0])\r\n label = \"No Mask- No Entry\" if cla==0 else \"Wrong Mask- Not Safe\" if cla==1 else \"Mask- Safe\"\r\n color = (0, 0, 255) if cla == 0 else (0, 255, 255) if cla==1 else (255, 255, 0)\r\n\r\n # include the probability in the label\r\n label = \"{}: {:.2f}%\".format(label, max(pred[0]) * 100)\r\n\r\n # Create Text around the bounding box displaying label with probability percentage \r\n cv2.putText(frame, label, (startX, startY - 10),cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)\r\n cv2.line(frame,(startX,startY),(startX,startY+25),color,2)\r\n cv2.line(frame,(startX,startY),(startX+25,startY),color,2)\r\n \r\n cv2.line(frame,(endX,startY),(endX,startY+25),color,2)\r\n cv2.line(frame,(endX,startY),(endX-25,startY),color,2)\r\n \r\n cv2.line(frame,(startX,endY),(startX,endY-25),color,2)\r\n cv2.line(frame,(startX,endY),(startX+25,endY),color,2)\r\n \r\n cv2.line(frame,(endX, endY),(endX,endY-25),color,2)\r\n cv2.line(frame,(endX, endY),(endX-25,endY),color,2)\r\n \r\n \r\n # cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)\r\n (hei, wid) = frame.shape[:2]\r\n #fps=cap.get(cv2.CAP_PROP_FPS)\r\n end=time.time()\r\n f=1/(end-now)\r\n FPS='FPS : '+str(math.ceil(f))\r\n # Display the Frames Per Second below the streaming video\r\n cv2.putText(frame,str(FPS),(0,hei-20),cv2.FONT_HERSHEY_SIMPLEX, 0.45,(255,255,255), 1)\r\n no_faces='No. of faces in video : '+str(len(locs))\r\n # Display the Number of people on the webcam of streaming video\r\n cv2.putText(frame,str(no_faces),(80,hei-20),cv2.FONT_HERSHEY_SIMPLEX, 0.45,(255,255,255), 1)\r\n ret, jpeg = cv2.imencode('.jpg', frame)\r\n return jpeg.tobytes()\r\n except :\r\n pass","sub_path":"camera_detect.py","file_name":"camera_detect.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"647391562","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 6 19:43:36 2017\n\n@author: Bernardo.Roschke\n\"\"\"\n\nimport pandas as pd\nimport sqlite3 as lite\nimport datetime\nimport matplotlib.pyplot as plt\nimport collections\n\ncon = lite.connect('citi_bike.db')\ncur = con.cursor()\n\ndf = pd.read_sql_query(\"SELECT * FROM available_bikes ORDER BY execution_time\",con,index_col='execution_time')\n#print(df.head())\nhour_change = collections.defaultdict(int)\nfor col in df.columns:\n station_vals = df[col].tolist()\n station_id = col[1:] #trim the \"_\"\n station_change = 0\n for k,v in enumerate(station_vals):\n if k < len(station_vals) - 1:\n station_change += abs(station_vals[k] - station_vals[k+1])\n hour_change[int(station_id)] = station_change #convert the station id back to integer\n \ndef keywithmaxval(d):\n \"\"\"Find the key with the greatest value\"\"\"\n return max(d, key=lambda k: d[k])\n\n# assign the max key to max_station\nmax_station = keywithmaxval(hour_change)\n\n#query sqlite for reference information\ncur.execute(\"SELECT id, stationname, latitude, longitude FROM citibike_reference WHERE id = ?\", (max_station,))\ndata = cur.fetchone()\nprint(\"The most active station is station id %s at %s latitude: %s longitude: %s \" % data)\nprint(\"With %d bicycles coming and going in the hour between %s and %s\" % (\n hour_change[max_station], \n datetime.datetime.fromtimestamp(int(df.index[0])).strftime('%Y-%m-%dT%H:%M:%S'),\n datetime.datetime.fromtimestamp(int(df.index[-1])).strftime('%Y-%m-%dT%H:%M:%S'),\n))\n\nplt.bar(hour_change.keys(), hour_change.values())\nplt.title('Stations vs Bike activity')\nplt.xlabel('Bike activity')\nplt.ylabel('Stations')\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"citibike/citibike_analysis.py","file_name":"citibike_analysis.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"639402271","text":"# -*- coding: utf-8 -*-\n\nL = ['Bart','Lisa','Adam']\n\nfor name in L:\n\tprint('Hello %s' % name)\n\ndef power(x):\n return x*x\n\ndef power2(x,n):\n s = 1\n while n > 0:\n n = n - 1\n s = s * x\n return s\ndef power3(x,n=2):\n s = 1\n while n > 0:\n n = n -1\n s = s * x\n return s\n\nprint(power(5))\nprint(power2(5,3))\nprint(power3(5))\n\nprint([x * x for x in range(1,11)])\n\nprint([x * x for x in range(1,11) if x % 2 == 0])\n\nprint([m+n for m in 'ABC' for n in 'XYZ'])\nprint([m+n+o for m in 'ABC' for n in 'XYZ' for o in 'IJK'])\n\nimport os\n\nprint([d for d in os.listdir('.')])\n\nL = ['Hello','Apple','IBM','DELL',18,None]\n\n\nprint([s.lower() if isinstance(s, str)else s for s in L])","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"483863181","text":"#! /usr/bin/python\nimport cgi, cgitb\ncgitb.enable()\nimport EC_ProcessFile\ndef floatConvert(takeIn):\n try:\n float(takeIn)\n return True\n except:\n return False\ndef saveGame(username,gameName,score,level):\n games = EC_ProcessFile.makeGameDict()\n proceed = True\n if username in games:\n if gameName in games[username]:\n proceed = True\n if not proceed:\n return \"Username &/or save slot not recognized. Game could not be saved.\"\n games[username][gameName][\"score\"] = score\n games[username][gameName][\"level\"]=level\n if EC_ProcessFile.writeGameDict(games):\n return \"Successfully saved progress!\"\n else:\n return \"Unable to save progress due to an error with the program.\"\ndef main():\n form = cgi.FieldStorage()\n username = \"\"\n response = \"\"\n if \"username\" in form:\n username = form.getvalue(\"username\")\n if \"saveGame\" in form and \"score\" in form and \"level\" in form:\n s = form.getvalue(\"score\")\n l = form.getvalue(\"level\")\n if floatConvert(s) and floatConvert(l):\n response = saveGame(username,form.getvalue(\"saveGame\"), float(s), float(l))\nmain()\n","sub_path":"PythonWebServer/EC_Project/EC_Save.py","file_name":"EC_Save.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"169903925","text":"import sys\r\nimport numpy as np\r\nfrom numpy import linalg as LA\r\nfrom scipy.spatial.distance import cdist,cosine\r\nfrom tensorflow.keras.models import Model, load_model\r\n\r\nfrom tensorflow.keras.optimizers import SGD\r\nfrom sklearn.cluster import KMeans\r\nfrom sklearn.manifold import TSNE\r\n\r\nfrom keras.utils.np_utils import to_categorical\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n\r\ndef get_all_layer_outputs(basic_model,training_data):\r\n '''\r\n returns a list of length number of hidden layers + 1 (for output layer),\r\n where every element is an array of the activation for each training sample for the respective layer\r\n '''\r\n intermediate_model = Model(inputs=basic_model.layers[0].input,\r\n outputs=[l.output for l in basic_model.layers[1:]])\r\n activation_set = intermediate_model.predict(training_data)\r\n #for activation in activation_set:\r\n #print(np.shape(activation))\r\n #print(activation)\r\n #print(len(activation_set))\r\n return activation_set\r\n\r\n\r\n####for number data sets:\r\n\r\ndef make_explantation_from_distances(training_data,model,sample,number_explanations,linear_importance):\r\n '''\r\n calculates the euclidean distance between every activation of sample and training data\r\n and returns number_explanations closest training samples\r\n linear_importance is float number between 0 and 1 and weights the layer output with liner weights starting from linear_importance to 1\r\n '''\r\n\r\n for layer in model.layers:\r\n print(layer.__class__.__name__)\r\n\r\n weight = [1 if layer.__class__.__name__ == \"Dense\" else 0 for layer in model.layers]\r\n print(weight)\r\n\r\n layer_outputs_training = get_all_layer_outputs(model,training_data)\r\n layer_outputs_sample = get_all_layer_outputs(model,sample)\r\n\r\n number_training_samples = np.shape(training_data)[0]\r\n number_layers = len(layer_outputs_sample)\r\n distance_array = np.empty(shape=(number_training_samples,number_layers))\r\n\r\n for idx, (layer_output_training, layer_output_sample) in enumerate(zip(layer_outputs_training,layer_outputs_sample)):\r\n distances = cdist(layer_output_training,layer_output_sample,metric='euclidean')\r\n distance_array[:,idx] = np.transpose(distances)\r\n weights = np.linspace(start=linear_importance, stop=1, num=number_layers)\r\n sum_weighted_distance_array = np.dot(distance_array,weights)\r\n\r\n #find 'number_explanations' smallest values !!!Attention, does not return them sorted\r\n idx_winner = np.argpartition(sum_weighted_distance_array, number_explanations)[:number_explanations]\r\n\r\n explantation_samples = training_data[idx_winner]\r\n return_message = \"When the model 'saw' \\n\" \\\r\n + str(sample[0]) \\\r\n + \"\\n it was 'thinking' the same as when it 'saw' \\n\" \\\r\n + str(explantation_samples)\r\n\r\n return return_message\r\n\r\ndef what_if(trained_model,number_additional_layers,sample,class_id,epochs,confidence):\r\n\r\n trained_model.layers[1].trainable = True\r\n\r\n for idx in range(2,4 + number_additional_layers):\r\n print(idx)\r\n trained_model.layers[idx].trainable = False\r\n\r\n trained_model.compile(loss='sparse_categorical_crossentropy',\r\n optimizer='adam',\r\n metrics=['accuracy'])\r\n trained_model.save('trained_toy_model.h5')\r\n\r\n sample = np.asarray([sample])\r\n\r\n target = np.asarray([class_id])\r\n\r\n for epoch in range(epochs):\r\n trained_model.fit(sample, target, epochs=1, batch_size=1, verbose=2)\r\n new_sample = get_all_layer_outputs(trained_model, sample)[0]\r\n print(\"new_sample\")\r\n print(new_sample)\r\n print(\"prediction of new sample\")#TODO: PREDICT WITH OLD MODEL !!\r\n base_model = load_model(\"trained_toy_model.h5\")\r\n pred = base_model.predict(new_sample)\r\n print(pred)\r\n pred_class = np.argmax(pred[0])\r\n print(pred_class)\r\n\r\n if pred_class == class_id and pred[0][class_id] >= confidence:\r\n return \" In order to be classified \"+str(sample[0])+\" in class \"+ str(pred_class) +\" with at least \"+str(confidence*100)+\"% confidence,\\n \" \\\r\n \"the sample would need to look like \"+str(new_sample[0])+ \", which \"+str([\"really\" if np.argmax(new_sample[0]) != class_id else \"indeed\"][0]) +\" belongs to class \"+ str(np.argmax(new_sample[0]))+\".\"\r\n\r\n####for text classification\r\n\r\ndef what_if_for_text(trained_model,sample,class_id,reverse_word_map,confidence):\r\n \"\"\"\r\n does not work since Embedding layer is not trainable\r\n \"\"\"\r\n\r\n print(trained_model.summary())\r\n\r\n for idx in range(0,7):\r\n trained_model.layers[idx].trainable = False\r\n\r\n trained_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc'])\r\n print(\"nothing trainable\")\r\n print(trained_model.summary())\r\n\r\n trained_model.layers[0].trainable = True\r\n print(\"encoder trainable\")\r\n\r\n trained_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc'])\r\n print(trained_model.summary())\r\n sample = sample.reshape(1, -1)\r\n\r\n output_list = get_all_layer_outputs(trained_model,sample)\r\n\r\n new_text = [reverse_word_map.get(idx) for idx in output_list[0][0]]\r\n\r\n #just for entering while loop\r\n pred_class = class_id + 1\r\n pred = [[0]]\r\n target = np.asarray([class_id]).reshape(1,-1)\r\n while not (pred_class == class_id and pred[0][class_id] >= confidence):\r\n trained_model.fit(sample, target, epochs=1, batch_size=1, verbose=1)\r\n new_sample = get_all_layer_outputs(trained_model, sample)[1]\r\n print(\"predicted class of new sample\")\r\n base_model = load_model(\"trained_LSTM_auto_text_model.h5\")\r\n pred = base_model.predict(new_sample)\r\n pred_class = np.argmax(pred[0])\r\n print(pred_class)\r\n print(pred[0][pred_class])\r\n del base_model\r\n\r\n return new_sample\r\n\r\ndef make_explantation_from_distances_for_text(training_data,model,sample,number_explanations,reverse_word_map,linear_importance):\r\n '''\r\n calculates the euclidean distance between every activation of sample and training data\r\n and returns number_explanations closest training samples\r\n linear_importance is float number between 0 and 1 and weights the layer output with liner weights starting from linear_importance to 1\r\n '''\r\n\r\n for layer in model.layers:\r\n print(layer.__class__.__name__)\r\n\r\n sample = sample.reshape(1, -1)\r\n\r\n layer_outputs_training = get_all_layer_outputs(model,training_data)\r\n layer_outputs_sample = get_all_layer_outputs(model,sample)\r\n\r\n for i,layer in enumerate(layer_outputs_training):\r\n layer_outputs_training[i] = layer.reshape(layer.shape[0],-1)\r\n for i,layer in enumerate(layer_outputs_sample):\r\n layer_outputs_sample[i] = layer.reshape(layer.shape[0], -1)\r\n\r\n number_training_samples = np.shape(training_data)[0]\r\n number_layers = len(layer_outputs_sample)\r\n distance_array = np.empty(shape=(number_training_samples,number_layers))\r\n\r\n for idx, (layer_output_training, layer_output_sample) in enumerate(zip(layer_outputs_training,layer_outputs_sample)):\r\n for sample_idx, single_layer_output_training in enumerate(layer_output_training):\r\n distances = cosine(single_layer_output_training,layer_output_sample)\r\n distance_array[sample_idx,idx] = np.transpose(distances)\r\n\r\n #weights = [1 if layer.__class__.__name__ == \"Dense\" else 0 for layer in model.layers][1:]\r\n weights = np.linspace(start=linear_importance, stop=1, num=number_layers)\r\n\r\n sum_weighted_distance_array = np.dot(distance_array,weights)\r\n\r\n #find 'number_explanations' smallest values !!!Attention, does not return them sorted\r\n idx_winner = np.argpartition(sum_weighted_distance_array, number_explanations)[:number_explanations]\r\n\r\n explantation_samples = training_data[idx_winner]\r\n print('When the model \"saw\"')\r\n list_string = [reverse_word_map.get(idx) for idx in sample[0]]\r\n sentence = \" \".join(list(filter(None, list_string)))\r\n print(sentence)\r\n\r\n print('the neuron activity was similar to when it \"saw\" the following training samples:')\r\n for sample in explantation_samples:\r\n list_string = [reverse_word_map.get(idx) for idx in sample]\r\n sentence = \" \".join(list(filter(None, list_string)))\r\n print(sentence)\r\n\r\n return 'done'\r\n\r\n###for image classification\r\n\r\ndef what_if_for_mnsit(trained_model, sample, class_id, confidence):\r\n '''\r\n trained_model must have an encoder decoder structure in the first three layers\r\n :returns alternated sample which is classified into class_id with confidence*100 %\r\n '''\r\n\r\n for idx in range(2, 11):\r\n trained_model.layers[idx].trainable = False\r\n\r\n opt = SGD(lr=0.0001, momentum=0.9)\r\n trained_model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\r\n\r\n trained_model.layers[1].trainable = True\r\n\r\n opt = SGD(lr=0.0001, momentum=0.9)\r\n trained_model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\r\n\r\n print(trained_model.summary())\r\n\r\n target = to_categorical(class_id, num_classes=10).reshape(1, 10)\r\n\r\n # just for entering while loop\r\n pred_class = class_id + 1\r\n pred = [[0]]\r\n while not (pred_class == class_id and pred[0][class_id] >= confidence):\r\n trained_model.fit(sample, target, epochs=1, batch_size=1, verbose=1)\r\n new_sample = get_all_layer_outputs(trained_model, sample)[1]\r\n print(\"predicted class of new sample\")\r\n base_model = load_model(\"trained_base_model.h5\")\r\n pred = base_model.predict(new_sample)\r\n pred_class = np.argmax(pred[0])\r\n print(pred_class)\r\n print(pred[0][pred_class])\r\n del base_model\r\n return new_sample\r\n\r\n\r\n\r\ndef make_explantation_from_distances_for_mnist(training_data,model,sample,number_explanations,linear_importance):\r\n '''\r\n calculates the euclidean distance between every activation of sample and training data\r\n and returns number_explanations closest training samples\r\n linear_importance is float number between 0 and 1 and weights the layer output with liner weights starting from linear_importance to 1\r\n '''\r\n\r\n for layer in model.layers:\r\n print(layer.__class__.__name__)\r\n\r\n layer_outputs_training = get_all_layer_outputs(model,training_data)\r\n layer_outputs_sample = get_all_layer_outputs(model,sample)\r\n\r\n for i,layer in enumerate(layer_outputs_training):\r\n layer_outputs_training[i] = layer.reshape(layer.shape[0],-1)\r\n for i,layer in enumerate(layer_outputs_sample):\r\n layer_outputs_sample[i] = layer.reshape(layer.shape[0], -1)\r\n\r\n\r\n number_training_samples = np.shape(training_data)[0]\r\n number_layers = len(layer_outputs_sample)\r\n distance_array = np.empty(shape=(number_training_samples,number_layers))\r\n\r\n for idx, (layer_output_training, layer_output_sample) in enumerate(zip(layer_outputs_training,layer_outputs_sample)):\r\n for sample_idx, single_layer_output_training in enumerate(layer_output_training):\r\n distances = cosine(single_layer_output_training,layer_output_sample)\r\n distance_array[sample_idx,idx] = np.transpose(distances)\r\n\r\n #weights = [1 if layer.__class__.__name__ == \"Conv2D\" else 1 for layer in model.layers][1:]\r\n weights = np.linspace(start=linear_importance, stop=1, num=number_layers)\r\n sum_weighted_distance_array = np.dot(distance_array,weights)\r\n\r\n #find 'number_explanations' smallest values !!!Attention, does not return them sorted\r\n idx_winner = np.argpartition(sum_weighted_distance_array, number_explanations)[:number_explanations]\r\n\r\n explantation_samples = training_data[idx_winner]\r\n print('when the model saw')\r\n plt.imshow(sample.reshape((28,28)), cmap='gray', interpolation='none')\r\n plt.show()\r\n print('it was similar to')\r\n for sample in explantation_samples:\r\n plt.imshow(sample.reshape((28,28)), cmap='gray', interpolation='none')\r\n plt.show()\r\n\r\n return 'done'\r\n\r\n\r\ndef create_explanation_sets_for_mnist(trained_model,training_data,training_data_y,sample_id,number_explantation_sets):\r\n '''\r\n get unsupervised clusters for activations training samples and use them as explanation sets\r\n '''\r\n number_samples = training_data.shape[0]\r\n for layer in trained_model.layers:\r\n print(layer.__class__.__name__)\r\n\r\n layer_outputs_training = get_all_layer_outputs(trained_model, training_data)\r\n\r\n #weights = np.linspace(start=linear_importance, stop=1, num=number_layers)\r\n weights = [1 if layer.__class__.__name__ == \"Conv2D\" else 0 for layer in trained_model.layers][1:]\r\n weights[0]=0#get rid of Autoencoder Dense layer\r\n\r\n\r\n for i, layer in enumerate(layer_outputs_training):\r\n layer_outputs_training[i] = layer.reshape(layer.shape[0], -1)\r\n\r\n #mapping to 2 or 3d space of flattend activations\r\n vec_space_dimension = 0\r\n for layer_output, weight in zip(layer_outputs_training,weights):\r\n if weight != 0:\r\n vec_space_dimension += layer_output.shape[1]\r\n\r\n vector_space = np.empty(shape=(number_samples,vec_space_dimension))\r\n\r\n for sample_idx in range(number_samples):\r\n layer_dimension = 0\r\n for layer_idx,layer in enumerate(layer_outputs_training):\r\n if weights[layer_idx] != 0:\r\n current_layer_dimension = layer.shape[1]\r\n vector_space[sample_idx][layer_dimension:current_layer_dimension+layer_dimension] = layer[sample_idx][:]\r\n layer_dimension += current_layer_dimension\r\n\r\n model = TSNE(n_components = 2,learning_rate=100)\r\n transformed = model.fit_transform(vector_space)\r\n x_axis = transformed[:, 0]\r\n y_axis = transformed[:, 1]\r\n #z_axis = transformed[:, 2]\r\n\r\n data_y = [None] * number_samples\r\n for idx, single_training_data_y in enumerate(training_data_y):\r\n data_y[idx] = np.argmax(single_training_data_y)\r\n #from mpl_toolkits.mplot3d import Axes3D\r\n fig = plt.figure()\r\n ax = fig.add_subplot(111)\r\n ax.scatter(x_axis, y_axis, c = data_y)\r\n plt.show()\r\n\r\n #unsupervised clustering with fixed number of clusters of activations\r\n model = KMeans(n_clusters=number_explantation_sets)\r\n model.fit(vector_space)\r\n pred_kmeans = model.predict(vector_space)\r\n\r\n acc_score = 0\r\n data_y = [None]*number_samples\r\n for idx, single_training_data_y in enumerate(training_data_y):\r\n data_y[idx] = np.argmax(single_training_data_y)\r\n if np.argmax(single_training_data_y) == pred_kmeans[idx]:\r\n acc_score += 1\r\n acc_score /= number_samples\r\n print(pred_kmeans)\r\n print(acc_score)\r\n\r\n set_id = model.predict(vector_space[sample_id].reshape(1, -1))\r\n\r\n print('when the model saw')\r\n plt.imshow(training_data[sample_id].reshape((28, 28)), cmap='gray', interpolation='none')\r\n plt.show()\r\n print('it was similar to explanation sample set no '+str(set_id))\r\n count = 0\r\n for idx, entry in enumerate(pred_kmeans):\r\n if entry == set_id:\r\n plt.imshow(training_data[idx].reshape((28, 28)), cmap='gray', interpolation='none')\r\n plt.show()\r\n count += 1\r\n if count >= number_explantation_sets:\r\n break\r\n return 'done'\r\n\r\n\r\n####not used\r\n\r\ndef make_explantation_sets(features, model, number_additional_layers,number_explantation_sets):\r\n '''\r\n not used!\r\n calculates the norm between the activations of the sample with every training sample and splits them in number_explantation_sets\r\n '''\r\n\r\n distance_array = np.empty([np.shape(features)[0], 2])\r\n layer_outputs = get_all_layer_outputs(model, features)\r\n\r\n for idx, _ in enumerate(features):\r\n sample_distance = 0\r\n for i in range(number_additional_layers):\r\n sample_distance += LA.norm(layer_outputs[i][idx:idx + 1])\r\n distance_array[idx, 0] = idx\r\n distance_array[idx, 1] = sample_distance\r\n distance_array = distance_array[np.argsort(distance_array[:, 1])]\r\n explantation_sets = np.array_split(distance_array, number_explantation_sets)\r\n return explantation_sets\r\n\r\n\r\ndef generate_explanation_from_sets(training_data, trained_model, number_explantation_sets, sample):\r\n '''\r\n not used!\r\n generates explanations from explantation_sets\r\n '''\r\n explantation_sets = make_explantation_sets(training_data, trained_model, number_explantation_sets)\r\n score = make_explantation_sets(sample, trained_model, 1)[0][0][1]\r\n\r\n explantation_set_id = -1\r\n for idx, explantation_set in enumerate(explantation_sets):\r\n if score >= explantation_set[0, 1] and score <= explantation_set[-1, 1]:\r\n explantation_set_id = idx\r\n if explantation_set_id == -1:\r\n return \"Can not explain decision with training data\"\r\n else:\r\n mask = list(map(int, explantation_sets[explantation_set_id][:, 0]))\r\n explantation_samples = training_data[mask]\r\n return_message = \"When the model 'saw' \\n\" \\\r\n + str(sample[0]) \\\r\n + \"\\n it was 'thinking' the same as when it 'saw' \\n\" \\\r\n + str(explantation_samples)\r\n return return_message\r\n\r\n","sub_path":"explanation_methods.py","file_name":"explanation_methods.py","file_ext":"py","file_size_in_byte":17378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"387004652","text":"\n\nfrom xai.brain.wordbase.nouns._cavity import _CAVITY\n\n#calss header\nclass _CAVITIES(_CAVITY, ):\n\tdef __init__(self,): \n\t\t_CAVITY.__init__(self)\n\t\tself.name = \"CAVITIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"cavity\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_cavities.py","file_name":"_cavities.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"576704352","text":"from scripts.ToolBox import Downloader, DiskCache\nfrom lxml.html import fromstring\n\ndef manaRow(root):\n mana = []\n for child in root:\n mana.append(child.get(\"alt\"))\n return mana\n\n\ndef textRow(root):\n text = []\n for element in root.cssselect(\".cardtextbox\"):\n s = []\n for child in element:\n if child.tag == \"img\":\n s.append(child.get(\"alt\"))\n s.append(element.xpath(\"text()\")[0].strip())\n text.append(\" \".join(s))\n return text\n\n\ndef flavorRow(root):\n text = []\n for element in root.cssselect(\".flavortextbox\"):\n text.append(element.text.strip())\n return text\n\n\ndef setRow(root):\n for element in root.cssselect(\"a\"):\n if element.text:\n return element.text.strip()\n return None\n\n\ndef rarityRow(root):\n return root.cssselect(\"span\")[0].text.strip()\n\n\ndef otherSetsRow(root):\n sets = []\n for img in root.cssselect(\"img\"):\n sets.append(img.get(\"title\"))\n return sets\n\n\ndef artistRow(root):\n return root.cssselect(\"a\")[0].text.strip()\n\n\ndef ptRow(root):\n return root.cssselect(\"b\")[0].text.strip()\n\n\nfunction_lookup = {\"manaRow_v\": manaRow,\n \"textRow_v\": textRow,\n \"flavorRow_v\": flavorRow,\n \"setRow_v\": setRow,\n \"rarityRow_v\": rarityRow,\n \"otherSetsRow_v\": otherSetsRow,\n \"artistRow_v\": artistRow,\n \"ptRow_l\": ptRow}\n\ncard = {}\nD = Downloader(cache=DiskCache())\nfor multiverse_id in range(400000, 500000):\n url = \"http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid={}\".format(multiverse_id)\n tree = fromstring(D(url).encode())\n for container in tree.cssselect(\".cardComponentContainer\"):\n card = []\n for a in container.cssselect(\"div [id*='ctl00_ctl00_ctl00_MainContent_SubContent_SubContent_'].row\"):\n id_elements = a.get(\"id\").split(\"_\")\n\n label = a.cssselect(\".label\")[0]\n if len(label) > 0:\n label = function_lookup[id_elements[-1] + '_l'](label)\n else:\n label = label.text.strip()\n\n value = a.cssselect(\".value\")[0]\n if len(value) > 0:\n value = function_lookup[id_elements[-1] + '_v'](value)\n else:\n value = value.text.strip()\n\n print(label, value)\n","sub_path":"scripts/MTGScraper.py","file_name":"MTGScraper.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"603065960","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2019 CERN.\n#\n# inspirehep is free software; you can redistribute it and/or modify it under\n# the terms of the MIT License; see LICENSE file for more details.\n\n\nimport click\nfrom flask import current_app\nfrom flask_security.utils import hash_password\nfrom invenio_accounts.models import Role\nfrom invenio_db import db\nfrom invenio_oauth2server.models import Client, Token\n\n\ndef init_oauth_token():\n ds = current_app.extensions[\"invenio-accounts\"].datastore\n admin = Role.query.filter_by(name=\"admin\").one()\n with db.session.begin_nested():\n user = ds.create_user(\n email=\"admin@inspirehep.net\",\n password=hash_password(\"123456\"),\n active=True,\n roles=[admin],\n )\n db.session.commit()\n click.secho(\"User admin added successfully\", fg=\"green\")\n with db.session.begin_nested():\n client = Client(\n name=\"admin\",\n user_id=user.id,\n is_internal=True,\n is_confidential=False,\n _default_scopes=\"\",\n )\n client.gen_salt()\n\n token = Token(\n client_id=client.client_id,\n user_id=user.id,\n access_token=current_app.config[\"AUTHENTICATION_TOKEN\"],\n expires=None,\n _scopes=\"\",\n is_personal=True,\n is_internal=True,\n )\n\n db.session.add(client)\n db.session.add(token)\n db.session.commit()\n click.secho(\"Authentication token generated successfully\", fg=\"green\")\n","sub_path":"inspirehep/accounts/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"381587346","text":"\n# coding: utf-8\n\n# In[46]:\n\nmovies=[\"the holy girl\",\"the life of brain\",\"the meaning of litfe\"]\nprint(movies[2])\nprint(len(movies))\nmovies.append(\"yesterday once more\")\nprint(movies[3])\nmovies.pop()\nmovies.remove(\"the life of brain\")\nmovies.insert(1,\"the life of brain\")\nprint(movies)\nmovies.insert(1,1976)\nmovies.insert(3,1853)\nmovies.insert(5,1635)\nprint(movies)\nmovies=[\"the holy girl\",1975,\"the life of brain\",1979,\"the meaning of life\",1983,[\"Graham Chapman\",[\"Michael Palin\",\n \" John Cleese\",\" Terry Gilliam\",\"Eric Idle\",\"Terry Jones\"]]]\nfor i in movies:\n print(i)\n \ndef print_lol(movie):\n for i in movie:\n if isinstance(i,list):\n print_lol(i)\n else:\n print (i,end=\" \")\nprint_lol(movies)\n\nfor i in movies:\n if isinstance(i,list):\n for j in i:\n if isinstance(j,list):\n for k in j:\n print(k,end=\" \")\n else:\n print(j,end=\" \")\n else:\n print(i,end=\" \")\n\nprint(movies[6][1][3])\nprint(len(movies))\n\n\n# In[10]:\n\nmovies=[\"the holy girl\",1975,\"the life of brain\",1979,\"the meaning of life\",1983,[\"Graham Chapman\",[\"Michael Palin\",\n \"John Cleese\",\"Terry Gilliam\",\"Eric Idle\",\"Terry Jones\"]]]\ndef print_lol(movie,indent=False,level=0):\n for i in movie:\n if isinstance(i,list):\n print_lol(i,indent,level+1)\n else:\n if indent:\n for each_level in range(level):\n print(\"\\t\",end=\" \")\n print(i)\n else:\n print (i)\nprint_lol(movies,True)\n\n\n# In[44]:\n\nmovies=[\"the holy girl\",1975,\"the life of brain\",1979,\"the meaning of life\",1983,[\"Graham Chapman\",[\"Michael Palin\",\n \"John Cleese\",\"Terry Gilliam\",\"Eric Idle\",\"Terry Jones\"]]]\n\ndef print_lol2(the_list,level=0):\n for i in the_list:\n if isinstance(i,list):\n print_lol2(i,level+1)if level else print_lol2(i,level)\n else:\n if level:\n for step in range(level):\n print(\"\\t\",end=\" \")\n# print(i)\n print(i)\nprint_lol2(movies)\n\n\n# In[1]:\n\nimport os\nos.getcwd()\nfile=open('hello.txt')\nprint(file.readline())\nfile.seek(0)\nfor line in file:\n print(line,end=\"\\n\")\nfile.seek(0)\nfor i in file:\n role,subtitle=i.split(\": \")\n print(role+' said: '+subtitle)\nfile.close()\n\n\n# In[61]:\n\nimport os \n\n# read data\nman=[]\nothers=[]\ntry:\n data=open('hello.txt')\n for line in data: #read the data line by line\n (role,words)=line.split(':',1)\n if role=='A':\n man.append(words)\n if role=='B':\n others.append(words)\n print('a:',man)\n print('b:',others)\n data.close()\nexcept IOError as err:\n print('file error:'+str(err))\n\n# write data\ntry:\n man_data=open('man_data.txt','w')\n others_data=open('others_data.txt','w')\n print(man,file=man_data) #add 'file='\n print(others,file=others_data) #add 'file='\n man_data.close()\n others_data.close()\nexcept IOError:\n print('file error')\n \nfinally:\n man_data.close()\n others_data.close()\n\n \n\n\n# In[ ]:\n\n\n\n","sub_path":"head-first-python/headfirstpython.py","file_name":"headfirstpython.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"212969569","text":"# -*- coding:utf-8 -*-\n\nimport fasttext\nimport os\nimport sys\nimport itertools\nimport re\nimport json\nimport codecs\nimport pandas as pd\nimport numpy as np\nfrom pandas import DataFrame\nreload(sys)\nsys.setdefaultencoding('utf-8')\nensure_ascii=False\n\nlist_key = [u'705', u'556', u'65', u'81', u'1713', u'22', u'290548', u'47', u'42', u'107', u'328', u'1672', u'599873',\n u'69360', u'636', u'758', u'309067', u'307', u'557285', u'2127', u'115482', u'431', u'604330',u'175747']\nlist_value = [u'705', u'556', u'65', u'81', u'1713', u'22', u'290548', u'47', u'42', u'107', u'328', u'1672', u'599873',\n u'69360', u'636', u'758', u'309067', u'307', u'557285', u'2127', u'115482', u'431', u'604330', u'175747']\n\n\ndef model(**kwargs):\n dict_number = {}\n # 训练模型\n trainpath = os.getcwd()[:14] + '/modeltotal3/train3wadd1.txt'\n textpath = os.getcwd()[:14] + '/train/testdata.txt'\n modelpath = os.getcwd()[:14] + '/modeltotal3/train1'\n modelpath_1 = os.getcwd()[:14] + '/modeltotal3/train1100_0.1_10_ns.bin'\n # modelpath_23 = os.getcwd()[:14] + '/model/20171221.bin'\n # load训练好的模型\n classifier_1 = fasttext.load_model(modelpath_1, label_prefix='__label__')\n # # classifier_23 = fasttext.load_model(modelpath_23, label_prefix='__label__')\n #预测\n with codecs.open(textpath, \"rb\",'utf-8') as dtrain:\n content = dtrain.read()\n content_split= content.split('\\n')\n # count = 0\n # list_predict = []\n # list_really = []\n for m in list_key:\n for n in list_value:\n dict_number[(m,n)] = 0\n for i in range(0,len(content_split)-1):\n datalabel = content_split[i].split('__label__')\n data = datalabel[0]\n label = datalabel[1]\n dict = {}\n list = []\n list.append(data)\n # list_really.append(match)\n result = classifier_1.predict(list)\n dict_number[(result[0][0],label)]+=1\n dict[result[0][0]] = list[0]\n\n # with codecs.open('/Users/zlz/zlz/modeltotal2/predict7.txt', \"a+\", 'utf-8') as dtrain:\n # json_str = json.dumps(dict, ensure_ascii=False)\n # dtrain.write(json_str + '\\n')\n\n return dict_number\n#生成excel表格\ndef Statistics(dict_number):\n df1 = pd.DataFrame(index=list_key,columns=list_value)\n for i in list_key:\n for j in list_value:\n df1[j][i] = dict_number[(i,j)]\n writer = pd.ExcelWriter('/Users/zlz/zlz/modeltotal3/train3wadd1.xlsx')\n df1.to_excel(writer,'sheet1')\n writer.save()\n #调参\n # # 学习率lr,隐层的维数dim,n - grams的长度-ws等。\n # params = {'dim': [100, 150], 'lr': [0.1, 0.5, 1], 'loss': ['ns', 'hs'], 'ws': [5, 10]}\n # for k, v in kwargs.items():\n # params[k] = v\n # keys, values = params.keys(), params.values()\n # best, best_score = '', 0\n # for p in itertools.product(*values):\n # ps = {keys[i]: p[i] for i in xrange(4)}\n # clf = fasttext.supervised(trainpath, modelpath + '%s_%s_%s_%s' % (p[0], p[1], p[2], p[3]), label_prefix='__label__',**ps)\n # result = clf.test(textpath)\n # print '%s_%s_%s_%s' % (p[0], p[1], p[2], p[3])\n # print 'Precision: %.2f%%' % (result.precision * 100)\n # print 'Recall Rate: %.2f%%\\n' % (result.recall * 100)\n #\n # f1 = float(2.0 * result.precision * result.recall) / float(result.precision + result.recall)\n # if best_score < f1:\n # best, best_score, = '%s_%s_%s_%s' % (p[0], p[1], p[2], p[3]), f1\n # print '%s\\n%.2f' % (best, best_score)\n\nif __name__ == \"__main__\":\n # model()\n dict_number = model()\n Statistics(dict_number)\n\n","sub_path":"data/nlp/keywords/experiments/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"126265650","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.views import generic\nfrom django.utils import timezone\nfrom .models import Question, SeatPressure\nfrom django.views.decorators.csrf import csrf_exempt\nimport datetime\nimport json\nimport pytz\n\nclass IndexView(generic.ListView):\n template_name = 'health_graph/index.html'\n context_object_name = 'latest_question_list'\n\n def get_queryset(self):\n \"\"\"\n Return the last five published questions (not including those set to be published in the future).\n \"\"\"\n return Question.objects.filter(\n pub_date__lte=timezone.now()\n ).order_by('-pub_date')[:5]\n\nclass DetailView(generic.DetailView):\n model = Question\n template_name = 'health_graph/detail.html'\n\n def get_queryset(self):\n \"\"\"\n Excludes any questions that aren't published yet.\n \"\"\"\n return Question.objects.filter(pub_date__lte=timezone.now())\n\nclass ResultsView(generic.DetailView):\n model = Question\n template_name = 'health_graph/results.html'\n\ndef vote(request, question_id):\n question = get_object_or_404(Question, pk=question_id)\n try:\n selected_choice = question.choice_set.get(pk=request.POST['choice'])\n except (KeyError, Choice.DoesNotExist):\n return render(request, 'health_graph/detail.html', {\n 'question': question,\n 'error_message': \"You didn't select a choice.\",\n })\n else:\n selected_choice.votes += 1\n selected_choice.save()\n return HttpResponseRedirect(reverse('health_graph:results', args=(question.id,)))\n\n@csrf_exempt\ndef seat_pressure_append(request):\n seat_pressure = None\n try:\n pressure_data = json.loads(request.body)\n except ValueError:\n return Http404(\"Not data\")\n\n for data in pressure_data:\n timestamp = datetime.datetime.strptime(data['time'], \"%Y-%m-%d %H:%M\")\n sp = SeatPressure(\n seat_count=int(data['seat_count']),\n average=float(data['average']),\n minutes=timestamp.strftime(\"%Y-%m-%d %H:%M:00\")\n )\n sp.save()\n\n return HttpResponse('success', status=200)\n\ndef health_pressure_append(request, date):\n timestamp = datetime.datetime.strptime(date, \"%Y-%m-%d\")\n seat_pressure = None\n\n try:\n sp = SeatPressure.objects\n seat_pressure = sp \\\n .filter(minutes__gte=(timestamp).strftime(\"%Y-%m-%d 00:00:00\")) \\\n .filter(minutes__lt=(timestamp).strftime(\"%Y-%m-%d 23:59:59\"))\n except (KeyError, SeatPressure.DoesNotExist):\n pass\n\n pressure_output = []\n for seat in seat_pressure:\n pressure_output.append(\n {\n \"time\": seat.minutes.astimezone(pytz.timezone(\"Asia/Tokyo\")).strftime(\"%Y/%m/%d %H:%M:%S\"),\n \"seat_count\": seat.seat_count,\n \"average\": seat.average,\n }\n )\n\n return HttpResponse(\n json.dumps(pressure_output),\n content_type='application/json; charset=UTF-8',\n status=200\n )\n\n# Create your views here.\n","sub_path":"keep_health/health_graph/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"366118280","text":"import urllib.request\n\ndef get_claims_list():\n opener = urllib.request.build_opener()\n opener.addheaders.append(('Cookie', 'session=53616c7465645f5f979679f915a848580bba01ea0e2ed04cf63187d31932999ae9fbabca26d1cfdc36b3951649b6de85'))\n url = 'https://adventofcode.com/2018/day/3/input'\n f = opener.open(url)\n result = []\n for line in f.readlines():\n line = bytes.decode(line).splitlines()[0]\n segments = line.split(\" \")\n pos = segments[2].split(',')\n x = int(pos[0])\n y = int(pos[1][:-1])\n dims = segments[3].split('x')\n width = int(dims[0])\n height= int(dims[1])\n result.append((x,y, width, height))\n return result\n\ndef get_claims_list_with_id():\n opener = urllib.request.build_opener()\n opener.addheaders.append(('Cookie', 'session=53616c7465645f5f979679f915a848580bba01ea0e2ed04cf63187d31932999ae9fbabca26d1cfdc36b3951649b6de85'))\n url = 'https://adventofcode.com/2018/day/3/input'\n f = opener.open(url)\n result = []\n for line in f.readlines():\n line = bytes.decode(line).splitlines()[0]\n segments = line.split(\" \")\n ID = segments[0]\n pos = segments[2].split(',')\n x = int(pos[0])\n y = int(pos[1][:-1])\n dims = segments[3].split('x')\n width = int(dims[0])\n height= int(dims[1])\n result.append((ID, x,y, width, height))\n return result\n\ndef get_index_list(claim):\n (x, y, w, h) = claim\n results = []\n for i in range(0, w):\n for j in range(0, h):\n results.append((x+i, y+j))\n return results\n \ndef getAreaOfOverlaps():\n claims = get_claims_list()\n fabric = []\n for _ in range(1000):\n fabric.append([0]*1000)\n overlaps = 0\n for claim in claims:\n indices = get_index_list(claim)\n for index in indices:\n (i, j) = index\n fabric[i][j] += 1\n if fabric[i][j] == 2:\n overlaps += 1\n return overlaps\n\ndef getSafeId():\n dimension = 1000\n claims = get_claims_list_with_id()\n #claims = [(\"#123\", 1, 3, 4, 4), (\"#456\", 3, 1, 4, 4), (\"#789\", 5, 5, 2, 2)]\n fabric = []\n for _ in range(dimension):\n fabric.append([0]*dimension)\n cells = dict()\n for claim in claims:\n (ID, x, y, w, h) = claim\n indices = get_index_list((x,y,w,h))\n cells[ID] = len(indices)\n for index in indices:\n (i,j) = index\n if fabric[i][j] == 0:\n fabric[i][j] = ID\n else:\n fabric[i][j] = 'X'\n ids = dict()\n for i in range(dimension):\n for j in range(dimension):\n if fabric[i][j] != 'X' and fabric[i][j] != 0:\n if fabric[i][j] in ids:\n ids[fabric[i][j]] += 1\n else:\n ids[fabric[i][j]] = 1\n for key in ids:\n if key in cells:\n if ids[key] == cells[key]:\n return key\n\n\n\n\nprint(getAreaOfOverlaps())\nprint(getSafeId())","sub_path":"2018/day3/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"137001026","text":"#encoding:utf-8\nfrom django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_HOST_USER = 'sindicatochoferespasaje@gmail.com'\nEMAIL_HOST_PASSWORD = 'Pasaje??77'\nEMAIL_PORT = '587'\nEMAIL_USE_TLS = True\nADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)\n\nMANAGERS = ADMINS\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': 'prysindicato', # Or path to database file if using sqlite3.\n # The following settings are not used with sqlite3:\n 'USER': 'postgres',\n 'PASSWORD': 'root',\n 'HOST': 'localhost', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.\n 'PORT': '5432', # Set to empty string for default.\n }\n}\n\n# Hosts/domain names that are valid for this site; required if DEBUG is False\n# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts\nALLOWED_HOSTS = []\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# In a Windows environment this must be set to your system time zone.\nTIME_ZONE = 'America/Guayaquil'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'es-ec'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale.\nUSE_L10N = True\n\n# If you set this to False, Django will not use timezone-aware datetimes.\nUSE_TZ = True\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/var/www/example.com/media/\"\nMEDIA_ROOT = 'media'\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash.\n# Examples: \"http://example.com/media/\", \"http://media.example.com/\"\nMEDIA_URL = '/media/'\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n# Example: \"/var/www/example.com/static/\"\nSTATIC_ROOT = ''\n\n# URL prefix for static files.\n# Example: \"http://example.com/static/\", \"http://static.example.com/\"\nSTATIC_URL = '/static/'\n\n# Additional locations of static files\nSTATICFILES_DIRS = ('static',\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'xg3(g0dg_yqobod!zhm&-koebf_p)20z12!ml8qm%q=it#9ncr'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.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 # Uncomment the next line for simple clickjacking protection:\n # 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'PrySindicato.urls'\n\n# Python dotted path to the WSGI application used by Django's runserver.\nWSGI_APPLICATION = 'PrySindicato.wsgi.application'\n\nimport os\nTEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\\\','/'),)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n # Uncomment the next line to enable the admin:\n 'suit',\n 'django.contrib.admin',\n # Uncomment the next line to enable admin documentation:\n # 'django.contrib.admindocs',\n 'Usuarios','Estudiantes','Matricula','Reportes','Materia','Profesor','Nota','Turno','Noticia',\n)\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n#configuracion de dajgno swit:\n\nSUIT_CONFIG = {\n 'ADMIN_NAME' : 'Sindicato de Choferes',\n 'CONFIRM_UNSAVED_CHANGES': True,\n 'MENU_OPEN_FIRST_CHILD' : True,\n #'MENU_OPEN_FIRST_CHILD' : True,\n #'MENU_EXCLUDE': ('auth.group', 'auth'),\n 'MENU':(\n {'label': 'Seguridad', 'icon':'icon-lock', 'models': (\n 'auth.group',\n {'model': 'auth.user','label': 'Usuarios'}\n )},\n {'label': 'Gestionar Matriculas', 'models': (\n 'Matricula',\n {'model': 'Matricula.matricula','label': 'Matriculas'},\n {'model': 'Matricula.periodo','label': 'Periodos'},\n {'model': 'Matricula.seccion','label': 'Secciones'},\n {'model': 'Matricula.paralelo','label': 'Paralelos'},\n )},\n {'label': 'Gestionar Estudiantes', 'models': (\n 'Estudiantes',\n {'model': 'Estudiantes.estudiantes','label': 'Estudiantes'}\n )},\n {'label': 'Gestionar Docentes', 'models': (\n 'Profesor',\n {'model': 'Profesor.profesor','label': 'Profesores'}\n )},\n {'label': 'Gestionar Materias', 'models': (\n 'Materia',\n {'model': 'Materia.materia','label': 'Materias'},\n {'model': 'Materia.profesor_materia','label': 'Asignación de docentes'},\n\n )},\n {'label': 'Gestionar Calificaciones', 'models': (\n 'Nota',\n {'model': 'Nota.nota','label': 'Calificaciones'},\n )},\n {'label': 'Configuración', 'models': (\n 'Turno',\n {'model': 'Turno.tipo_tramite','label': 'Tipos de trámites'},\n )},\n {'label': 'Gestionar Turnos', 'models': (\n 'Turno',\n {'model': 'Turno.turno','label': 'Listar Turnos'},\n )},\n {'label': 'Personalización', 'models': (\n 'Turno',\n {'model': 'Noticia.noticia','label': 'Gestionar Noticias'},\n )},\n {'label': 'Reporte', 'models': (\n {'label': 'Promociones',\n 'url':'/Reporte/promocion/'},\n )},\n )\n\n}\n\nTEMPLATE_CONTEXT_PROCESSORS = TCP + (\n 'django.core.context_processors.request',\n)\n","sub_path":"PrySindicato/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":7815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"42812188","text":"# Copyright (c) 2013 Mirantis 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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport datetime\nimport uuid\n\nfrom oslo.config import cfg\nimport six\n\nfrom sahara import conductor as c\nfrom sahara import context\nfrom sahara.openstack.common import log\nfrom sahara.plugins import base as plugin_base\nfrom sahara.service.edp.binary_retrievers import dispatch\nfrom sahara.service.edp import hdfs_helper as h\nfrom sahara.service.edp import oozie as o\nfrom sahara.service.edp.workflow_creator import workflow_factory\nfrom sahara.utils import edp\nfrom sahara.utils import remote\nfrom sahara.utils import xmlutils as x\n\n\nLOG = log.getLogger(__name__)\n\nopts = [\n cfg.StrOpt('job_workflow_postfix',\n default='',\n help='Postfix for storing jobs in hdfs. Will be '\n 'added to /user/hadoop/.')\n]\n\nCONF = cfg.CONF\nCONF.register_opts(opts)\n\nconductor = c.API\n\nterminated_job_states = ['DONEWITHERROR', 'FAILED', 'KILLED', 'SUCCEEDED']\n\n\ndef get_job_status(job_execution_id):\n ctx = context.ctx()\n job_execution = conductor.job_execution_get(ctx, job_execution_id)\n if job_execution.oozie_job_id is None:\n # We don't have an Oozie id yet for this job, that's okay\n return job_execution\n\n cluster = conductor.cluster_get(ctx, job_execution.cluster_id)\n\n if cluster is None or cluster.status != 'Active':\n return job_execution\n\n client = _create_oozie_client(cluster)\n job_info = client.get_job_status(job_execution)\n update = {\"info\": job_info}\n if job_info['status'] in terminated_job_states:\n update['end_time'] = datetime.datetime.now()\n\n job_execution = conductor.job_execution_update(ctx, job_execution,\n update)\n return job_execution\n\n\ndef update_job_statuses():\n ctx = context.ctx()\n for je in conductor.job_execution_get_all(ctx, end_time=None):\n try:\n get_job_status(je.id)\n except Exception as e:\n LOG.exception(\"Error during update job execution %s: %s\" %\n (je.id, e))\n\n\ndef _get_plugin(cluster):\n return plugin_base.PLUGINS.get_plugin(cluster.plugin_name)\n\n\ndef _create_oozie_client(cluster):\n plugin = _get_plugin(cluster)\n return o.OozieClient(plugin.get_oozie_server_uri(cluster),\n plugin.get_oozie_server(cluster))\n\n\ndef cancel_job(job_execution_id):\n ctx = context.ctx()\n job_execution = conductor.job_execution_get(ctx, job_execution_id)\n cluster = conductor.cluster_get(ctx, job_execution.cluster_id)\n\n client = _create_oozie_client(cluster)\n client.kill_job(job_execution)\n\n job_info = client.get_job_status(job_execution)\n update = {\"info\": job_info,\n \"end_time\": datetime.datetime.now()}\n job_execution = conductor.job_execution_update(ctx, job_execution,\n update)\n\n return job_execution\n\n\ndef _update_job_execution_extra(job_execution, cluster):\n if CONF.use_namespaces and not CONF.use_floating_ips:\n oozie = _get_plugin(cluster).get_oozie_server(cluster)\n info = oozie.remote().get_neutron_info()\n extra = job_execution.extra.copy()\n extra['neutron'] = info\n\n job_execution = conductor.job_execution_update(\n context.ctx(), job_execution.id, {'extra': extra})\n return job_execution\n\n\ndef _get_data_sources(job_execution, job):\n if edp.compare_job_type(job.type, edp.JOB_TYPE_JAVA):\n return None, None\n\n ctx = context.ctx()\n input_source = conductor.data_source_get(ctx, job_execution.input_id)\n output_source = conductor.data_source_get(ctx, job_execution.output_id)\n return input_source, output_source\n\n\ndef _get_oozie_job_params(cluster, hdfs_user, path_to_workflow):\n plugin = _get_plugin(cluster)\n rm_path = plugin.get_resource_manager_uri(cluster)\n nn_path = plugin.get_name_node_uri(cluster)\n job_parameters = {\n \"jobTracker\": rm_path,\n \"nameNode\": nn_path,\n \"user.name\": hdfs_user,\n \"oozie.wf.application.path\": \"%s%s\" % (nn_path, path_to_workflow),\n \"oozie.use.system.libpath\": \"true\"}\n return job_parameters\n\n\ndef run_job(job_execution_id):\n try:\n _run_job(job_execution_id)\n except Exception as ex:\n LOG.exception(\"Can't run job execution '%s' (reason: %s)\",\n job_execution_id, ex)\n\n conductor.job_execution_update(\n context.ctx(), job_execution_id,\n {'info': {'status': 'FAILED'},\n 'start_time': datetime.datetime.now(),\n 'end_time': datetime.datetime.now()})\n\n\ndef _run_job(job_execution_id):\n ctx = context.ctx()\n\n job_execution = conductor.job_execution_get(ctx, job_execution_id)\n\n cluster = conductor.cluster_get(ctx, job_execution.cluster_id)\n if cluster.status != 'Active':\n return\n\n job_execution = _update_job_execution_extra(job_execution, cluster)\n\n job = conductor.job_get(ctx, job_execution.job_id)\n input_source, output_source = _get_data_sources(job_execution, job)\n\n for data_source in [input_source, output_source]:\n if data_source and data_source.type == 'hdfs':\n h.configure_cluster_for_hdfs(cluster, data_source)\n\n plugin = _get_plugin(cluster)\n hdfs_user = plugin.get_hdfs_user()\n oozie_server = plugin.get_oozie_server(cluster)\n\n wf_dir = create_workflow_dir(oozie_server, job, hdfs_user)\n upload_job_files(oozie_server, wf_dir, job, hdfs_user)\n\n wf_xml = workflow_factory.get_workflow_xml(\n job, cluster, job_execution, input_source, output_source)\n\n path_to_workflow = upload_workflow_file(oozie_server,\n wf_dir, wf_xml, hdfs_user)\n\n client = _create_oozie_client(cluster)\n job_params = _get_oozie_job_params(cluster, hdfs_user, path_to_workflow)\n oozie_job_id = client.add_job(x.create_hadoop_xml(job_params),\n job_execution)\n job_execution = conductor.job_execution_update(\n ctx, job_execution, {'oozie_job_id': oozie_job_id,\n 'start_time': datetime.datetime.now()})\n client.run_job(job_execution, oozie_job_id)\n\n\ndef upload_job_files(where, job_dir, job, hdfs_user):\n mains = job.mains or []\n libs = job.libs or []\n uploaded_paths = []\n\n with remote.get_remote(where) as r:\n for main in mains:\n raw_data = dispatch.get_raw_binary(main)\n h.put_file_to_hdfs(r, raw_data, main.name, job_dir, hdfs_user)\n uploaded_paths.append(job_dir + '/' + main.name)\n for lib in libs:\n raw_data = dispatch.get_raw_binary(lib)\n # HDFS 2.2.0 fails to put file if the lib dir does not exist\n h.create_dir(r, job_dir + \"/lib\", hdfs_user)\n h.put_file_to_hdfs(r, raw_data, lib.name, job_dir + \"/lib\",\n hdfs_user)\n uploaded_paths.append(job_dir + '/lib/' + lib.name)\n return uploaded_paths\n\n\ndef upload_workflow_file(where, job_dir, wf_xml, hdfs_user):\n with remote.get_remote(where) as r:\n h.put_file_to_hdfs(r, wf_xml, \"workflow.xml\", job_dir, hdfs_user)\n\n return \"%s/workflow.xml\" % job_dir\n\n\ndef create_workflow_dir(where, job, hdfs_user):\n constructed_dir = '/user/%s/' % hdfs_user\n constructed_dir = _add_postfix(constructed_dir)\n constructed_dir += '%s/%s' % (job.name, six.text_type(uuid.uuid4()))\n with remote.get_remote(where) as r:\n h.create_dir(r, constructed_dir, hdfs_user)\n\n return constructed_dir\n\n\ndef _add_postfix(constructed_dir):\n constructed_dir = _append_slash_if_needed(constructed_dir)\n if CONF.job_workflow_postfix:\n constructed_dir = ''.join([str(constructed_dir),\n str(CONF.job_workflow_postfix)])\n return _append_slash_if_needed(constructed_dir)\n\n\ndef _append_slash_if_needed(path):\n if path[-1] != '/':\n path += '/'\n return path\n","sub_path":"sahara/service/edp/job_manager.py","file_name":"job_manager.py","file_ext":"py","file_size_in_byte":8499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"211209955","text":"#!/usr/bin/python\n\"\"\" Project Euler | Problem 27\n\"\"\"\n\nimport time,sys\nsys.path.append('../')\nfrom functions import is_prime\n\nstart_time = time.time()\n\ndef solve_problem27():\n\n\tmax_n = 0\n\tmax_ab = 0\n\tfor a in range(-999,1000):\n\t\tfor b in range(-1000,1001):\n\t\t\tn = 0\n\t\t\twhile is_prime( n**2 + a*n + b):\n\t\t\t\tn += 1\t\n\t\t\tif n >= max_n:\n\t\t\t\tmax_n = n\n\t\t\t\tmax_ab = a*b\n\n\treturn max_ab\n\n\nanswer = solve_problem27()\nend_time = time.time()\nrun_time = end_time - start_time\n\n\nprint( \"-------------------------------------------\")\nprint( \"| Solution to Project Euler problem 27 |\" )\nprint( \"-------------------------------------------\")\nprint( \"Question: find the product of coefficients a and b (|a| < 1000, |b| <= 1000) such that n**2 + an + b produces the maximum number of primes for consecutive values of n, starting with n=0.\" )\nprint( \"Answer: a * b = {:d}\".format(answer) )\nprint( \"Wall time: {:3.5f} seconds\".format(run_time))\n","sub_path":"27/problem27.py","file_name":"problem27.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"557608964","text":"## Contains Duplicate II\n\n# Example 1:\n# Input: nums = [1,2,3,1], k = 3\n# Output: true\n\n# Example 2:\n# Input: nums = [1,0,1,1], k = 1\n# Output: true\n\n# Example 3:\n# Input: nums = [1,2,3,1,2,3], k = 2\n# Output: false\n\nclass Solution:\n def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:\n ## O(N^2)\n # temp={}\n # for idx, num in enumerate(nums):\n # if num not in temp:\n # temp[num]=[idx]\n # continue\n # temp[num].append(idx)\n \n # for x in temp:\n # N=len(temp[x])\n # i=0\n # while i 0 and reads!=0: #genus can't be empty\n\t\t\t\t\tgenus_dictionary[genus] = reads\n\t\t\t\t\t#genus_tally[genus] += 1\n\t\tskip +=1\n\t\t\n\tif len(genus_dictionary.keys()) == 0:\n\t\tprint(\"WARNING: File contains no reads of the specified kingdom (viral/bacterial)\")\n\t\tcontinue\n\t\t\n\t#re-order the dictionary by value - organisms with the most hits appear at the top of the list\n\td = collections.OrderedDict(sorted(genus_dictionary.items(),key=operator.itemgetter(1),reverse=True))\n\tgenus_dictionary = d\n\n\t#print and write to file the Genus and Total Read info (tab-delim)\n\tf_out.write(\"Genus\\tTotalReads\\n\")\n\tprint(\"\\nGenus\\tTotalReads\")\n\tfor k, v in genus_dictionary.items():#iteritems():\n\t\tprint(k + \"\\t\" +str(v) )\n\t\tf_out.write(k+\"\\t\" + str(v)+\"\\n\")\n\n\t#calculate the Simpsons Diversity score\n\tsimpsons_sum = 0\n\ttotal_num_organisms = sum(genus_dictionary.values())\n\tprint(total_num_organisms)\n\tfor i in genus_dictionary.keys():\n\t\tdiv = float(genus_dictionary[i])/float(total_num_organisms)\n\t\tsimpsons_sum += div*div\n\t\tgenus_proportions[i] = div \n\n\tdiversity = 1 - simpsons_sum\n\tprint(\"\\n\\nSimpsons Diversity: \" + str(diversity))\n\tf_out.write(\"\\n\\nSimpsons Diversity: \" + str(diversity))\n\tmetrics[\"Simpsons Diversity\"] = \"%.4f\" % diversity\n\t\n\t#CODE ADDED July 19th, 2016 -----\n\t#calculate other diversity scores\n\tif len(sys.argv) > 3:\n\t\t\n\n\t\t#set variables\n\t\trichness = len(genus_dictionary.keys())\n\t\tsimpsons_dominance = 0\n\t\tsimpsons_dominance_unbiased = 0\n\t\thill_numbers = {\"1D\":0,\"2D\":0,\"3D\":0,\"4D\":0,\"inf\":0}\n\n\t\tfor i in genus_proportions.keys(): #calculate shannons, simposons, and hill numbers\n\t\t\tprop = genus_proportions[i]\n\t\t\tsimpsons_dominance += prop*prop\n\t\t\tsimpsons_dominance_unbiased += (prop*prop*(genus_dictionary[i]-1))/(genus_dictionary[i]-1)\n\t\t\thill_numbers[\"1D\"] += -1*(math.log(prop))*prop\n\t\t\thill_numbers[\"2D\"] += prop*prop\n\t\t\thill_numbers[\"3D\"] += math.pow(prop,3)\n\t\t\thill_numbers[\"4D\"] += math.pow(prop,4)\n\t\t\n\t\tgini_simpson_index = 1-simpsons_dominance\n\t\tgini_simpson_unbiased = 1-simpsons_dominance_unbiased\n\t\ttry:\n\t\t\tequitability = (gini_simpson_index/(1-float(1)/float(richness)))\n\t\texcept:\n\t\t\tprint(\"WARNING: only 1 organism of type N found; equitability divide by zero error\")\n\t\t\tprint(\"equitability set to ZERO\")\n\t\t\tequitability = 0\n\n\t\thill_numbers[\"1D\"] = math.pow(math.e,hill_numbers[\"1D\"])\n\t\thill_numbers[\"2D\"] = math.pow(hill_numbers[\"2D\"],-1)\n\t\thill_numbers[\"3D\"] = math.pow(hill_numbers[\"3D\"],-.5)#-2)\n\t\thill_numbers[\"4D\"] = math.pow(hill_numbers[\"4D\"],-.33333)#-3)\n\t\thill_numbers[\"inf\"] = 1/(max(genus_proportions.values()))\n\t\t\n\t\tshannon_entropy = math.log(hill_numbers[\"1D\"])\n\n\t\trenyi_entropy = {}\n\t\trenyi_entropy[\"1D\"] = math.log(hill_numbers[\"1D\"])\n\t\trenyi_entropy[\"2D\"] = math.log(hill_numbers[\"2D\"])\n\t\trenyi_entropy[\"3D\"] = math.log(hill_numbers[\"3D\"])\n\t\trenyi_entropy[\"4D\"] = math.log(hill_numbers[\"4D\"])\n\t\trenyi_entropy[\"inf\"] = math.log(hill_numbers[\"inf\"])\n\n\t\td = collections.OrderedDict(sorted(hill_numbers.items()))\n\t\thill_numbers = d\n\n\t\td = collections.OrderedDict(sorted(renyi_entropy.items()))\n\t\trenyi_entropy = d\n\n\t\tprint(\"\\n\\nRichness:\\t\" + str(richness))\n\t\tprint(\"Shannon Entropy:\\t\" + str(shannon_entropy))\n\t\tprint(\"Simpsons Dominance:\\t\" + str(simpsons_dominance))\n\t\tprint(\"Simpsons Dominance (unbiased):\\t\" + str(simpsons_dominance_unbiased))\n\t\tprint(\"Gini-Simpson Index:\\t\" + str(gini_simpson_index))\n\t\tprint(\"Gini-Simpson Index (unbiased):\\t\" + str(gini_simpson_unbiased))\n\t\tprint(\"Equitability:\\t\" + str(equitability))\n\t\tprint(\"Berger-Parker Index:\\t\" + str(max(genus_proportions.values())*100))\n\n\t\tf_out.write(\"\\n\\nRichness:\\t\" + str(richness))\n\t\tf_out.write(\"\\nShannon Entropy:\\t\" + str(shannon_entropy))\n\t\tf_out.write(\"\\nSimpsons Dominance:\\t\" + str(simpsons_dominance))\n\t\tf_out.write(\"\\nSimpsons Dominance (unbiased):\\t\" + str(simpsons_dominance_unbiased))\n\t\tf_out.write(\"\\nGini-Simpson Index:\\t\" + str(gini_simpson_index))\n\t\tf_out.write(\"\\nGini-Simpson Index (unbiased):\\t\" + str(gini_simpson_unbiased))\n\t\tf_out.write(\"\\nEquitability:\\t\" + str(equitability))\n\t\tf_out.write(\"\\nBerger-Parker Index:\\t\" + str(max(genus_proportions.values())*100))\n\n\t\tmetrics[\"Richness\"] = \"%.4f\" % richness\n\t\tmetrics[\"Shannon Entropy\"] = \"%.4f\" % shannon_entropy\n\t\tmetrics[\"Simpsons Dominance\"] = \"%.4f\" % simpsons_dominance\n\t\tmetrics[\"Simpsons Dominance (unbiased)\"] = \"%.4f\" % simpsons_dominance_unbiased\n\t\tmetrics[\"Gini-Simpson Index\"] = \"%.4f\" % gini_simpson_index\n\t\tmetrics[\"Gini-Simpson Index (unbiased)\"] = \"%.4f\" % gini_simpson_unbiased\n\t\tmetrics[\"Equitability\"] = \"%.4f\" % equitability\n\t\tmetrics[\"Berger-Parker Index\"] = \"%.4f\" % (max(genus_proportions.values())*100)\t\t\n\t\t\n\t\tf_out.write(\"\\nHill Numbers:\\n\")\n\t\tprint(\"\\nHill Numbers: \")\n\t\tfor k, v in hill_numbers.items():\n\t\t\tprint(k + \"\\t\" +str(v) )\n\t\t\tmetrics[\"Hill Number - \"+k] = \"%.4f\" % v\n\t\tf_out.write(k+\"\\t\" + str(v)+\"\\n\")\n\n\t\tf_out.write(\"\\nRenyi Entropy:\\n\")\n\t\tprint(\"Renyi Entropy: \")\n\t\tfor k, v in renyi_entropy.items():\n\t\t\tprint(k + \"\\t\" +str(v) )\n\t\t\tmetrics[\"Renyi Entropy - \"+k] = \"%.4f\" % v\n\t\tf_out.write(k+\"\\t\" + str(v)+\"\\n\")\n\n\td = collections.OrderedDict(sorted(metrics.items()))\n\tmetrics = d\n\tfull_metrics[filename]=metrics\n\n#note: pd.DataFrame.from_dict(full_metrics) works as well as this vvv\ndf = pd.DataFrame.from_dict(full_metrics, orient='index').T\ndf.to_csv('results.tsv',sep='\\t') #write to output file results.tsv\nprint(\"\\nScript Completed Successfully\")\n#except:\n#\tprint(\"\\nERROR: Exit with error code -1\")\n#\tsys.exit(-1)","sub_path":"Diversity/diversity_counts.py","file_name":"diversity_counts.py","file_ext":"py","file_size_in_byte":7043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"168312510","text":"\"\"\"\r\n\n\nCreate a function that takes a list of names of superheroes and superheroines\nand returns a list of only the names of superheroes ending in _\"man\"_ in\nalphabetical order.\n\n### Examples\n\n superheroes([\"Batman\", \"Superman\", \"Spider-man\", \"Hulk\", \"Wolverine\", \"Wonder-Woman\"])\n ➞ [\"Batman\", \"Spider-man\", \"Superman\"]\n \n superheroes([\"Catwoman\", \"Deadpool\", \"Dr.Strange\", \"Captain-America\", \"Aquaman\", \"Hawkeye\"])\n ➞ [\"Aquaman\"]\n \n superheroes([\"Wonder-Woman\", \"Catwoman\", \"Invisible-Woman\"])\n ➞ []\n\n### Notes\n\nWonder-Woman, Catwoman and Invisible-Woman are superheroines.\n\n\"\"\"\r\n\ndef superheroes(heroes):\n lst = []\n for hero in heroes:\n if 'man' in hero.lower() and not 'woman' in hero.lower():\n lst.append(hero)\n return sorted(lst)\n\n","sub_path":"u3kiw2gTY3S3ngJqo_5.py","file_name":"u3kiw2gTY3S3ngJqo_5.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"534393920","text":"from django.conf.urls import include, url\nfrom . import views\nfrom django.contrib import admin\n\nurlpatterns = [\n # url(r'^admin/', include(admin.site.urls)),\n url(r'^our_mission', views.our_mission, name='our_mission'),\n url(r'^programs', views.programs, name='programs'),\n url(r'^events', views.events, name='events'),\n url(r'^news', views.news, name='news'),\n url(r'^events', views.events, name='events'),\n url(r'^fair_share', views.fair_share, name='fair_share'),\n url(r'^scholarships', views.scholarships, name='scholarships'),\n url(r'^alumni', views.alumni, name='alumni'),\n url(r'^officers', views.officers, name='officers'),\n url(r'^achiever', views.achiever, name='achiever'),\n url(r'^committee', views.committee, name='committee'),\n url(r'^bylaws', views.bylaws, name='bylaws'),\n url(r'^membership', views.membership, name='membership'),\n url(r'^swasap', views.swasap, name='swasap'),\n url(r'^(?P[\\w\\-]+)/$', views.event_post, name='event_post'),\n url(r'^$', views.index, name='index'), #this should be last\n\n]","sub_path":"trio_nm/trio_nm_main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"212575309","text":"from pyflights import PyFlight\nimport json\n\nflight = PyFlight(api_key='AIzaSyBNFMQ6w1pnPwjAudfZw-iliHUucHRxqiA')\n\n# parameters:\nadults = 1\norigin = 'SFO'\nprice = 'USD1000'\ndest = 'SIN'\ndate = '2017-10-25'\n\nsearch = flight.search(params={\n 'adult_count': '%d'%adults,\n 'origin': '%s'%origin,\n 'max_price': '%s'%price,\n 'destination': '%s'%dest,\n 'date': '%s'%date,\n 'solutions': 15\n})\n\n\n#For JSON output\nfor results in search:\n output = json.dumps({\n 'id' : results.flight_number(),\n 'date' : date,\n 'departs_at' : results.departure_time(),\n 'arrives_at' : results.arrival_time(),\n 'price' : results.sale_total()},\n sort_keys=True, indent=4, separators=(',',': '))\n\n print(output)\n\n# with open('jsondata.txt', 'w') as f:\n# json.dump(output, f, ensure_ascii=False)","sub_path":"python/flights/Flightscanner.py","file_name":"Flightscanner.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"517356822","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 17 16:47:15 2020\r\n\r\n@author: sri\r\n\"\"\"\r\n\r\n# Python prog to illustrate the following in a list \r\ndef find_len(list1): \r\n\tlength = len(list1) \r\n\tlist1.sort()\r\n\tprint(\"Largest element is:\", list1[length-1]) \r\n\tprint(\"Smallest element is:\", list1[0]) \r\n\tprint(\"Second Largest element is:\", list1[length-2]) \r\n\tprint(\"Second Smallest element is:\", list1[1]) \r\n\r\n# Driver Code \r\nlist1=[]\r\nc=[]\r\nlist1=input().split()\r\nlength=len(list1)\r\nfor i in range(length):\r\n last=int(list1[i])\r\n c.append(last)\r\nLargest = find_len(c) \r\n","sub_path":"2ndmax and 2ndmin of a list.py","file_name":"2ndmax and 2ndmin of a list.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"405342250","text":"import numpy as np\r\nimport pandas as pd\r\nimport pickle as pkl\r\n\r\nclass DNSSpaceProcess:\r\n\r\n\tdef __init__(self, file_path, label_prefix='__user__', embedding_dimension=50):\r\n\t\tself.file_path = file_path\r\n\t\tself.label_prefix = label_prefix\r\n\t\tself.embedding_dimension = embedding_dimension\r\n\r\n\tdef process(self, save=False):\r\n\t\tprint('Reading dns space data.')\r\n\t\tdns_space_df = pd.read_csv(self.file_path, sep='\\t', header=None)\r\n\t\tprint('Reading done.')\r\n\t\tprint('Splitting doman and user space...')\r\n\t\tdomain_space_df = dns_space_df[~dns_space_df[0].apply(lambda name: name.startswith('__user__'))].reset_index(drop=True)\r\n\t\tuser_space_df = dns_space_df[dns_space_df[0].apply(lambda name: name.startswith('__user__'))].reset_index(drop=True)\r\n\t\tprint('Splitting done.')\r\n\t\tprint('Mapping domains to embedding vectors...')\r\n\t\tdomain2embedding_map = dict(zip(domain_space_df[0].apply(lambda x: x), domain_space_df[list(range(1, self.embedding_dimension+1))].values))\r\n\t\tprint('Mapping done.')\r\n\t\tprint('Mapping domains to indices...')\r\n\t\tdomain2index_map = dict(zip(domain_space_df[0], range(1, len(domain_space_df[0])+1)))\r\n\t\tdomain2index_map['PAD_TOKEN'] = 0\r\n\t\tprint('Mapping done.')\r\n\t\tprint('Creating embedding matrix...')\r\n\t\tself.create_embedding_matrix(domain2embedding_map, domain2index_map)\r\n\t\tprint('Creating done.')\r\n\t\tif save:\r\n\t\t\tprint('Saving precess results...')\r\n\t\t\tpkl.dump(domain2index_map, open('./data/domain2index_map.pkl', 'wb'))\r\n\t\t\tself.embedding_matrix.dump('./data/embedding_matrix.npy')\r\n\t\t\tprint('Saving done.')\r\n\r\n\tdef create_embedding_matrix(self, domain2embedding_map, domain2index_map):\r\n\t\tdomains_count = len(domain2index_map)\r\n\t\tembedding_matrix = np.zeros((domains_count, self.embedding_dimension))\r\n\t\tfor domain, index in domain2index_map.items():\r\n\t\t\tif not domain == \"PAD_TOKEN\":\r\n\t\t\t\tembedding_matrix[index,:] = domain2embedding_map[domain]\r\n\t\tself.embedding_matrix = embedding_matrix\r\n\r\n","sub_path":"dns_space_process.py","file_name":"dns_space_process.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"455100140","text":"import config\nimport copy\nimport heuristics as hr\n\n# global variables\nclauses = []\nsolution = {}\n\n# metrics\nn_of_evaluations = 0\nn_of_tautologies = 0\nn_of_unit_clauses = 0\nn_of_pure_literals = 0\nn_of_splits = 0\nn_of_backtracks = 0\nn_of_conflicts = 0\n\n\n# Function definitions file\ndef dp(cls, soln):\n global n_of_tautologies, n_of_evaluations, n_of_tautologies, n_of_splits, n_of_backtracks, \\\n n_of_conflicts, n_of_unit_clauses, n_of_pure_literals\n\n # metrics\n n_of_evaluations = 0\n n_of_tautologies = 0\n n_of_unit_clauses = 0\n n_of_pure_literals = 0\n n_of_splits = -1\n n_of_backtracks = 0\n n_of_conflicts = 0\n if config.PRINT_PROGRESS:\n print('>>> ', end='', flush=True)\n\n # Checking for tautologies\n if config.TAUTOLOGY:\n for cl in cls[:]:\n for j in cl: # Iterate through all clauses\n if -j in cl: # If a tautology is found\n cls.remove(cl) # delete such clause, and recurse in DP Solver with new clause list\n n_of_tautologies += 1\n break # current clause we are iterating through does not exist anymore, so break\n return dp_solver(cls, soln)\n\n\ndef dp_solver(cls, soln, var=0, val=False):\n # Init calls (Leaving initial parameters untouched in case of backtracking)\n\n global clauses, solution\n # global metrics\n global n_of_evaluations, n_of_tautologies, n_of_splits, n_of_backtracks, \\\n n_of_conflicts, n_of_unit_clauses, n_of_pure_literals\n\n # split\n n_of_splits += 1 # metrics\n if config.PRINT_PROGRESS:\n print('.', end='', flush=True)\n\n # Updating current state using deep copies\n clauses = copy.copy(cls)\n solution = copy.copy(soln)\n\n # Set the value from the split operation, if any is defined\n if var != 0:\n solution[var] = val\n clauses = simplification(clauses, solution)\n\n # BASE CASES\n if not clauses:\n return True, solution\n if [] in clauses:\n clauses = copy.copy(cls)\n solution = copy.copy(soln)\n return False, None\n\n # --- Boolean Constraint Propagation (BCP) ---\n while True:\n unit_clause_values = []\n for clause in clauses: # iterate every clause\n # check in case there is an empty clause\n if len(clause) == 0:\n clauses = copy.copy(cls)\n solution = copy.copy(soln)\n # metrics\n n_of_backtracks += 1\n n_of_conflicts += 1\n if config.PRINT_PROGRESS:\n print('<', end='', flush=True)\n return False, None\n # if a clause has length 1, it is a unit clause, so append it to unit_clause_values\n if len(clause) == 1:\n unit_clause_values.append(clause[0])\n # iterate through all unit clause values found\n for value in unit_clause_values:\n # check for contradictions, i.e. any two unit clauses that contradict themselves\n if -value in unit_clause_values:\n clauses = copy.copy(cls)\n solution = copy.copy(soln)\n # metrics\n n_of_backtracks += 1\n n_of_conflicts += 1\n if config.PRINT_PROGRESS:\n print('<', end='', flush=True)\n return False, None\n # if no values contradict, then set the value and remove the respective clauses\n solution[abs(value)] = value > 0\n clauses.remove([value])\n n_of_unit_clauses += 1 # metrics\n # if unit clauses are present, then re-evaluate\n # and re-start the iteration to check for more unit clauses\n if unit_clause_values:\n clauses = simplification(clauses, solution)\n # else, break out of the unit clause propagation\n else:\n break\n # --- END of BCP ---\n\n # --- Pure Literal Check ---\n if config.PURE_LITERALS:\n unique_literals = list(set([item for y in clauses for item in y]))\n impure_literal = []\n\n # find impure literals\n for c in clauses:\n for l in c:\n if -l in unique_literals:\n impure_literal.append(l)\n\n # compare subtract impure literals from all literals to find pure literals\n pure_literals = list(set(unique_literals) - set(impure_literal))\n for l in pure_literals:\n solution[abs(l)] = l > 0\n n_of_pure_literals += 1 # metrics\n # --- END of Pure Literal Check ---\n\n # BASE CASES\n if not clauses:\n return True, solution\n if [] in clauses:\n clauses = copy.copy(cls)\n solution = copy.copy(soln)\n # metrics\n n_of_backtracks += 1\n n_of_conflicts += 1\n if config.PRINT_PROGRESS:\n print('<', end='', flush=True)\n return False, None\n\n # CHOOSE HEURISTICS\n unresolved = [k for k, v in solution.items() if v is None]\n val = True\n if config.HEURISTIC == 0:\n var, val = hr.random_h(unresolved)\n elif config.HEURISTIC == 1:\n var, val = hr.dlis(unresolved, clauses)\n elif config.HEURISTIC == 2:\n var, val = hr.jw_ts(unresolved, clauses)\n elif config.HEURISTIC == 3:\n var, val = hr.dlcs(unresolved, clauses)\n elif config.HEURISTIC == 4:\n var, val = hr.jw_os(unresolved, clauses)\n else:\n raise Exception(\"Heuristic does not exist\")\n\n # SPLIT\n a, b = dp_solver(clauses, solution, var, val)\n if a:\n return a, b\n a, b = dp_solver(clauses, solution, var, not val)\n if a:\n return a, b\n clauses = copy.copy(cls)\n solution = copy.copy(soln)\n\n # metrics\n n_of_backtracks += 1\n n_of_conflicts += 1\n if config.PRINT_PROGRESS:\n print('<', end='', flush=True)\n return False, None\n\n\n# simplification of clauses\ndef simplification(e_clauses, e_solution):\n global n_of_evaluations\n n_of_evaluations += 1\n unevaluated_clauses = []\n # iterate for every clause\n for c in e_clauses:\n new_clause = []\n true_flag = False\n false_flag = False\n # iterate for every literal\n for l in c:\n # if literal is None -> add to new_clause\n if e_solution[abs(l)] is None:\n new_clause.append(l)\n else:\n # if +literal\n if e_solution[abs(l)]:\n if l > 0:\n true_flag = True\n break\n else:\n false_flag = True\n # if -literal\n else:\n if l < 0:\n true_flag = True\n break\n else:\n false_flag = True\n # A clause is unverified if it contains more than 1 literal,\n # - at least one of them being None\n # the rest can be false literals\n # if True literal is found (true_flag), then it is evaluated and ignored\n if (false_flag or len(new_clause) > 1) and not true_flag:\n unevaluated_clauses.append(new_clause)\n return unevaluated_clauses\n","sub_path":"dp_functions.py","file_name":"dp_functions.py","file_ext":"py","file_size_in_byte":7216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"270668138","text":"from bs4 import BeautifulSoup as bs\nfrom collections import Counter\nimport argparse\nimport lxml\nimport os\n\nap = argparse.ArgumentParser()\nap.add_argument('-x', '--xml', required = True)\nap.add_argument('-n', '--name', required = False, default = 'regulizer')\nap.add_argument('-i', '--info', required = False, default = 'T')\nargs = vars(ap.parse_args())\n\nclass main:\n\n def __init__(self, xml, name, info = True):\n try:\n self.xml = xml\n self.name = name\n\n with open(self.xml, 'rb') as f:\n self.strHelper('XML file parsing...')\n self.soup = bs(f, 'lxml')\n self.strHelper('XML file parsing complete!\\n', helper='s')\n\n boxes = self.soup.select('images > image > box')\n labels = self.soup.select('images > image > box > label')\n\n lbList = []\n for lb in range(len(labels)):\n lbList.append(labels[lb].text)\n\n self.strHelper('ratio calculating...')\n counter, ratio = self.ratioCal(lbList)\n self.strHelper('ratio calculating complete!\\n', helper = 's') \n\n if info == True:\n for idx in range(len(counter)):\n self.strHelper(f'label name : {counter[idx][0]}, # of label : {counter[idx][1]}', helper = 'i')\n\n print('\\n')\n self.xmlWriter(counter, ratio)\n\n else:\n self.xmlWriter(counter, ratio)\n\n except KeyboardInterrupt:\n self.strHelper('Did you press ctrl + c?', 'e')\n\n except Exception as e:\n self.strHelper(e, helper = 'e')\n\n def ratioCal(self, lis):\n counter = Counter(lis).most_common()\n most = counter[0][1]\n ratio = [round(most / counter[idx][1]) for idx in range(len(counter))]\n return counter, ratio\n\n def strHelper(self, msg, helper = 'w'):\n if helper == 'w':\n print(f'[Please Wait] : {msg}')\n\n elif helper == 's':\n print(f'[System] : {msg}')\n\n elif helper == 'e':\n print(f'[Error] : {msg}')\n\n elif helper == 'i':\n print(f'[Info] : {msg}')\n\n def xmlWriter(self, counter, ratio):\n self.strHelper('writing xml file...')\n result = {}\n for idx in range(len(counter)):\n result[counter[idx][0]] = ratio[idx] \n\n string = \"\\n\\n\\nimglab dataset\\nCreated by imglab tool.\\n\\n\"\n for image in self.soup.find_all(\"image\"):\n file = image[\"file\"]\n string += f\"\\n\"\n for box in image.select('image > box'):\n label = box.find(\"label\").text\n for idx in range(result[label]):\n string += f'{box}\\n'\n string += \"\\n\"\n string += \"\\n\"\n \n with open(f'{self.name}.xml', 'w') as f:\n f.write(string)\n self.strHelper('writing xml file complete!', helper = 's')\n\nif __name__ == '__main__':\n info = True if args['info'].upper() == 'T' else False\n main(xml = args['xml'], name = args['name'], info = info)\n","sub_path":"UTILS/OBJD/for TF_API/xml_boundingbox_copier.py","file_name":"xml_boundingbox_copier.py","file_ext":"py","file_size_in_byte":3308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"36464234","text":"# Licensed under the Apache License, Version 2.0 (the “License”); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# 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 under\n# the License.\n\nimport os\nimport re\nimport sublime\nimport sublime_plugin\n\nfrom sublime import Region\nfrom sublime_plugin import TextCommand\n\ndef comment_block(view, edit, region):\n begin = get_non_whitespace_pos(view, region)\n end = max(begin, region.end())\n empty_region = False\n\n if begin == end and view.substr(begin).isspace():\n # Added to ensure that the cursor won’t be moved after the comment.\n view.replace(edit, Region(end), '!')\n empty_region = True\n\n comment_type = get_comment_type(view, begin)\n\n if comment_type == 'jsx':\n if empty_region:\n view.insert(edit, end + 1, \" */}\")\n view.erase(edit, Region(end, end + 1))\n else:\n view.insert(edit, end, \" */}\")\n\n view.insert(edit, begin, \"{/* \")\n else:\n if empty_region:\n view.insert(edit, end + 1, \" */\")\n view.erase(edit, Region(end, end + 1))\n else:\n view.insert(edit, end, \" */\")\n\n view.insert(edit, begin, \"/* \")\n\ndef comment_lines(view, edit, region):\n lines = view.lines(region)\n\n first_line = lines[0]\n comment_type = get_comment_type(view, get_non_whitespace_pos(view, first_line))\n\n for line in reversed(lines):\n begin = get_non_whitespace_pos(view, line)\n\n if comment_type == 'jsx':\n # JSX.\n view.insert(edit, line.end(), \" */}\")\n view.insert(edit, begin, \"{/* \")\n else:\n # Normal JS comment.\n view.insert(edit, begin, \"// \")\n\ndef expand_closing_block_punctuation(view, offset):\n begin = offset\n end = offset\n\n # Expand to the left.\n scopes = view.scope_name(begin)\n\n while begin > 0 and 'punctuation.definition.comment.end' in scopes:\n begin -= 1\n scopes = view.scope_name(begin)\n\n if view.substr(begin) != ' ':\n begin += 1\n\n # Expand to the right.\n scopes = view.scope_name(end)\n\n while end < view.size() and 'punctuation.definition.comment.end' in scopes:\n end += 1\n scopes = view.scope_name(end)\n\n return Region(begin, end)\n\ndef expand_openning_block_punctuation(view, offset):\n begin = offset\n end = offset\n\n # Expand to the left.\n scopes = view.scope_name(begin)\n\n while begin > 0 and 'punctuation.definition.comment.begin' in scopes:\n begin -= 1\n scopes = view.scope_name(begin)\n begin += 1\n\n # Expand to the right.\n scopes = view.scope_name(end)\n\n while end < view.size() and 'punctuation.definition.comment.begin' in scopes:\n end += 1\n scopes = view.scope_name(end)\n\n if view.substr(end) == ' ':\n end += 1\n\n return Region(begin, end)\n\ndef expand_partial_comments(view, region):\n begin = region.begin()\n end = region.end()\n\n # This will allow JSX block comments to be toggled when the cursor is at the\n # openning or closing brace.\n if is_jsx_open_brace(view, begin): begin += 1\n if is_jsx_open_brace(view, end): end += 1\n\n if is_jsx_close_brace(view, begin): begin -= 1\n if is_jsx_close_brace(view, end): end -= 1\n\n # Expand to the left.\n scopes = view.scope_name(begin)\n\n if 'comment.line' in scopes:\n while begin > 0:\n begin -= 1\n char = view.substr(begin)\n scopes = view.scope_name(begin)\n\n if char == '\\n' or 'comment.line' not in scopes:\n begin += 1\n break\n elif 'comment.block' in scopes:\n char = view.substr(begin)\n # It won’t be expaned if it is already at the beginning of the block.\n if char != '/' or 'punctuation.definition.comment.begin' not in scopes:\n while begin > 0:\n begin -= 1\n char = view.substr(begin)\n scopes = view.scope_name(begin)\n\n if char == '/' and 'punctuation.definition.comment.begin' in scopes:\n break\n\n # Expand to the right.\n scopes = view.scope_name(end)\n\n if 'comment.line' in scopes:\n char = view.substr(end)\n # If it’s a new line character, it does not need to be expanded.\n if char != '\\n':\n while end < view.size():\n end += 1\n char = view.substr(end)\n scopes = view.scope_name(end)\n\n if char == '\\n':\n break\n\n if 'comment.line' not in scopes:\n end -= 1\n break\n elif 'comment.block' in scopes:\n char = view.substr(end)\n # It won’t be expaned if it is already at the end of the block.\n if char != '/' or 'punctuation.definition.comment.end' not in scopes:\n while end < view.size():\n end += 1\n char = view.substr(end)\n scopes = view.scope_name(end)\n\n if char == '/' and 'punctuation.definition.comment.end' in scopes:\n end += 1\n break\n else:\n # We are at the end of the block already, this will correct the region to\n # include the forward slash.\n end += 1\n\n return Region(begin, end)\n\n# Scan from the right to the left.\ndef get_comment_beginning_pos(view, offset):\n scopes = view.scope_name(offset)\n not_comment_scopes = [ 'comment.line', 'comment.block' ]\n\n while offset > 0:\n comment = any(x in scopes for x in not_comment_scopes)\n\n # Not a comment or end of a block comment.\n if not comment or 'punctuation.definition.comment.end' in scopes:\n offset += 1\n break\n\n # New line at the end of a line comment.\n char = view.substr(offset)\n if char == '\\n' and 'comment.line' in scopes:\n offset += 1\n break\n\n offset -= 1\n scopes = view.scope_name(offset)\n\n return offset\n\n# Scan from the left to the right.\ndef get_comment_content_beginning(view, offset):\n scopes = view.scope_name(offset)\n while 'punctuation.definition.comment.begin' in scopes:\n offset += 1\n scopes = view.scope_name(offset)\n\n char = view.substr(offset)\n\n # The first space will be considered as part of the punctuation because it\n # might have been inserted by this script.\n if char == ' ':\n offset += 1\n\n return offset\n\n# Returns the comment type that must be applied calculed at the offset.\ndef get_comment_type(view, offset):\n scopes = view.scope_name(offset)\n\n unfenced_scopes = [ 'source.jsx', 'punctuation.definition.tag.begin' ]\n unfenced_tag = all(x in scopes for x in unfenced_scopes) and 'meta.jsx-fence' not in scopes\n\n meta_tag_scopes = [ 'source.jsx', 'meta.tag' ]\n meta_tag = all(x in scopes for x in meta_tag_scopes)\n\n comment_type = 'js'\n if unfenced_tag or ('source.jsx' in scopes and not meta_tag):\n comment_type = 'jsx'\n\n return comment_type\n\n# Returns the position for the first non whitespace character on the target line\n# or the line’s beginning if none is found.\ndef get_non_whitespace_pos(view, region, stop_on_new_line = True):\n begin = region.begin()\n end = region.end()\n\n while begin < end:\n char = view.substr(begin)\n if stop_on_new_line and char == '\\n':\n break\n if not char.isspace():\n break\n begin += 1\n\n return begin\n\ndef is_jsx_open_brace(view, offset):\n open_brace_scopes = ['source.jsx', 'punctuation.definition.template-expression.begin']\n scopes = view.scope_name(offset)\n return all(x in scopes for x in open_brace_scopes)\n\ndef is_jsx_close_brace(view, offset):\n close_brace_scopes = ['source.jsx', 'punctuation.definition.template-expression.end']\n scopes = view.scope_name(offset)\n return all(x in scopes for x in close_brace_scopes)\n\ndef trim_whitespace(view, region):\n begin = region.begin()\n end = region.end()\n\n # Trim from the left.\n char = view.substr(begin)\n while char.isspace():\n begin += 1\n char = view.substr(begin)\n\n # Trim from the right.\n char = view.substr(end)\n while char.isspace():\n end -= 1\n char = view.substr(end)\n\n return Region(begin, end + 1)\n\ndef uncomment_lines(view, edit, region):\n begin = region.begin()\n end = region.end()\n\n i = end + 1\n while i > begin:\n i -= 1\n scopes = view.scope_name(i)\n\n if 'punctuation.definition.comment' not in scopes:\n continue\n\n # Found the second forward slash for the “// ” comment.\n if 'comment.line' in scopes:\n i = get_comment_beginning_pos(view, i)\n content_begin = get_comment_content_beginning(view, i)\n view.erase(edit, Region(i, content_begin))\n continue\n\n # We found the beginning of the block comment first which means that there’s\n # no end to it and we can easily remove it. It can be “/* ”, “/** ”, “{/* ”\n # or “{/** ”.\n if 'punctuation.definition.comment.begin' in scopes:\n i = get_comment_beginning_pos(view, i)\n content_begin = get_comment_content_beginning(view, i)\n\n # We need to check the braces for possible JSX interpolation.\n if i > 0 and is_jsx_open_brace(view, i - 1):\n # It was a JSX block comment.\n i -= 1\n\n # We have “i” positioned at the beginning of the comment or the brace if\n # it is a JSX comment.\n view.erase(edit, Region(i, content_begin))\n continue\n\n # We are looping backwards, so it is expected to find the closing punctuation\n # first which can be “ */” or “ */}”.\n possible_jsx_comment = False\n\n if i < view.size() and is_jsx_close_brace(view, i + 1):\n possible_jsx_comment = True\n\n close_block = i\n\n # Now, we need to find the the openning of the block.\n while 'punctuation.definition.comment.begin' not in scopes:\n i -= 1\n scopes = view.scope_name(i)\n\n open_block = i\n\n # This will generate a region that allows us to remove the block punctuation.\n open_block = expand_openning_block_punctuation(view, open_block)\n close_block = expand_closing_block_punctuation(view, close_block)\n\n # Correct the regions to include the JSX braces if necessary.\n if possible_jsx_comment:\n if open_block.begin() > 0 and is_jsx_open_brace(view, open_block.begin() - 1):\n open_block = Region(open_block.begin() - 1, open_block.end())\n close_block = Region(close_block.begin(), close_block.end() + 1)\n\n view.erase(edit, close_block)\n view.erase(edit, open_block)\n\n # Move the cursor to the beginning of the block to “consume” it.\n i = open_block.begin()\n\n# Actual command to toggle the comment lines and blocks.\nclass NaomiToggleJsxCommentCommand(sublime_plugin.TextCommand):\n def __init__(self, view):\n self.view = view\n\n def run(self, edit, block):\n for region in reversed(self.view.sel()):\n # If the region is just 1 character, we will expand it to affect the entire\n # line.\n if region.size() < 2:\n region = self.view.line(region)\n\n scopes = self.view.scope_name(region.begin())\n\n # If the beginning of the region is a string but not the beginning of the\n # string, it’ll not be possible to comment this region.\n if 'string' in scopes:\n if 'punctuation.definition.string.begin' not in scopes:\n continue\n\n region = expand_partial_comments(self.view, region)\n region = trim_whitespace(self.view, region)\n\n # Comments will begin with “//”, “/*” or “{/*”, to simplify the detection\n # on the first line, we can ignore the first character.\n scopes = self.view.scope_name(get_non_whitespace_pos(self.view, region) + 1)\n\n if 'comment' in scopes:\n uncomment_lines(self.view, edit, region)\n else:\n if block:\n comment_block(self.view, edit, region)\n else:\n comment_lines(self.view, edit, region)\n","sub_path":"plugin/ToggleJsxComment.py","file_name":"ToggleJsxComment.py","file_ext":"py","file_size_in_byte":11670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"127865887","text":"#!/usr/bin/env python\n# coding=utf8\n\"\"\"\nhttps://leetcode.com//problems/jump-game/\n\nac_rate:\t27.2%\ndifficulty:\tMedium\n\n\nGiven an array of non-negative integers, you are initially positioned at the first index of the array.\nEach element in the array represents your maximum jump length at that position.\nDetermine if you are able to reach the last index.\nFor example:\nA = [2,3,1,1,4], return true.\nA = [3,2,1,0,4], return false.\n\nShow Tags:\tArray, Greedy\n\"\"\"\n\n\nclass Solution0(object):\n def canJump(self, nums):\n \"\"\"\n Time Limit Exceeded\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n size = len(nums)\n if size <= 1:\n return True\n\n reachable = [0] * size\n reachable[0] = 1\n for i in range(size):\n if reachable[i] == 1:\n for t in range(nums[i] + 1):\n reachable[min(i + t, size - 1)] = 1\n return reachable[size - 1] == 1\n\n\nclass Solution1(object):\n size = 0\n reach_end = []\n\n\n def canJump(self, nums):\n \"\"\"\n Time Limit Exceeded\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n self.size = len(nums)\n if self.size <= 1:\n return True\n\n self.reach_end = [0] * self.size\n return self._can(nums, 0)\n\n def _can(self, nums, start):\n if start >= self.size:\n return True\n\n i = nums[start]\n while i > 0:\n if self._can(nums, start + i):\n self.reach_end[start] = 1\n return True\n i -= 1\n else:\n return False\n","sub_path":"leetcode/todos/jump_game.py","file_name":"jump_game.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"34186565","text":"import json\nfrom urllib.parse import quote, unquote\n\nimport pytest\nfrom hypothesis import given\n\nimport schemathesis\nfrom schemathesis.specs.openapi.serialization import conversion\n\nPRIMITIVE_SCHEMA = {\"type\": \"integer\", \"enum\": [1]}\nARRAY_SCHEMA = {\"type\": \"array\", \"enum\": [[\"blue\", \"black\", \"brown\"]]}\nOBJECT_SCHEMA = {\n \"additionalProperties\": False,\n \"type\": \"object\",\n \"properties\": {\n \"r\": {\"type\": \"integer\", \"enum\": [100]}, # \"const\" is not supported by Open API\n \"g\": {\"type\": \"integer\", \"enum\": [200]},\n \"b\": {\"type\": \"integer\", \"enum\": [150]},\n },\n \"required\": [\"r\", \"g\", \"b\"],\n}\n\n\ndef chunks(items, n):\n for i in range(0, len(items), n):\n yield items[i : i + n]\n\n\n# Helpers to avoid dictionary ordering issues\n\n\nclass Prefixed:\n def __init__(self, instance, prefix=\"\"):\n self.instance = quote(instance)\n self.prefix = quote(prefix)\n\n def prepare(self, value):\n raise NotImplementedError\n\n def __eq__(self, other):\n if self.prefix:\n if not other.startswith(self.prefix):\n return False\n prefix_length = len(self.prefix)\n instance = self.instance[prefix_length:]\n other = other[prefix_length:]\n else:\n instance = self.instance\n return self.prepare(instance) == self.prepare(other)\n\n def __str__(self):\n return self.instance\n\n def __repr__(self):\n return f\"'{self.instance}'\"\n\n\nclass CommaDelimitedObject(Prefixed):\n def prepare(self, value):\n items = unquote(value).split(\",\")\n return dict(chunks(items, 2))\n\n\nclass DelimitedObject(Prefixed):\n def __init__(self, *args, delimiter=\",\", **kwargs):\n super().__init__(*args, **kwargs)\n self.delimiter = delimiter\n\n def prepare(self, value):\n items = unquote(value).split(self.delimiter)\n return dict(item.split(\"=\") for item in items)\n\n\ndef make_openapi_schema(*parameters):\n return {\n \"openapi\": \"3.0.2\",\n \"info\": {\"title\": \"Test\", \"description\": \"Test\", \"version\": \"0.1.0\"},\n \"paths\": {\n \"/teapot\": {\n \"get\": {\"summary\": \"Test\", \"parameters\": list(parameters), \"responses\": {\"200\": {\"description\": \"OK\"}}}\n }\n },\n }\n\n\ndef assert_generates(raw_schema, expected, parameter):\n schema = schemathesis.from_dict(raw_schema)\n\n @given(case=schema[\"/teapot\"][\"GET\"].as_strategy())\n def test(case):\n assert getattr(case, parameter) == expected\n\n test()\n\n\n@pytest.mark.hypothesis_nested\n@pytest.mark.parametrize(\n \"schema, explode, style, expected\",\n (\n # Based on examples from https://swagger.io/docs/specification/serialization/\n (OBJECT_SCHEMA, True, \"deepObject\", {\"color[r]\": 100, \"color[g]\": 200, \"color[b]\": 150}),\n (OBJECT_SCHEMA, True, \"form\", {\"r\": 100, \"g\": 200, \"b\": 150}),\n (OBJECT_SCHEMA, False, \"form\", {\"color\": CommaDelimitedObject(\"r,100,g,200,b,150\")}),\n (ARRAY_SCHEMA, False, \"pipeDelimited\", {\"color\": \"blue|black|brown\"}),\n (ARRAY_SCHEMA, True, \"pipeDelimited\", {\"color\": [\"blue\", \"black\", \"brown\"]}),\n (ARRAY_SCHEMA, False, \"spaceDelimited\", {\"color\": \"blue black brown\"}),\n (ARRAY_SCHEMA, True, \"spaceDelimited\", {\"color\": [\"blue\", \"black\", \"brown\"]}),\n (ARRAY_SCHEMA, False, \"form\", {\"color\": \"blue,black,brown\"}),\n (ARRAY_SCHEMA, True, \"form\", {\"color\": [\"blue\", \"black\", \"brown\"]}),\n ),\n)\ndef test_query_serialization_styles_openapi3(schema, explode, style, expected):\n raw_schema = make_openapi_schema(\n {\"name\": \"color\", \"in\": \"query\", \"required\": True, \"schema\": schema, \"explode\": explode, \"style\": style}\n )\n assert_generates(raw_schema, expected, \"query\")\n\n\n@pytest.mark.hypothesis_nested\n@pytest.mark.parametrize(\n \"schema, explode, expected\",\n (\n (ARRAY_SCHEMA, True, {\"X-Api-Key\": \"blue,black,brown\"}),\n (ARRAY_SCHEMA, False, {\"X-Api-Key\": \"blue,black,brown\"}),\n (OBJECT_SCHEMA, True, {\"X-Api-Key\": DelimitedObject(\"r=100,g=200,b=150\")}),\n (OBJECT_SCHEMA, False, {\"X-Api-Key\": CommaDelimitedObject(\"r,100,g,200,b,150\")}),\n ),\n)\ndef test_header_serialization_styles_openapi3(schema, explode, expected):\n raw_schema = make_openapi_schema(\n {\"name\": \"X-Api-Key\", \"in\": \"header\", \"required\": True, \"schema\": schema, \"explode\": explode}\n )\n assert_generates(raw_schema, expected, \"headers\")\n\n\n@pytest.mark.hypothesis_nested\n@pytest.mark.parametrize(\n \"schema, explode, expected\",\n (\n (ARRAY_SCHEMA, True, {}),\n (ARRAY_SCHEMA, False, {\"SessionID\": \"blue,black,brown\"}),\n (OBJECT_SCHEMA, True, {}),\n (OBJECT_SCHEMA, False, {\"SessionID\": CommaDelimitedObject(\"r,100,g,200,b,150\")}),\n ),\n)\ndef test_cookie_serialization_styles_openapi3(schema, explode, expected):\n raw_schema = make_openapi_schema(\n {\"name\": \"SessionID\", \"in\": \"cookie\", \"required\": True, \"schema\": schema, \"explode\": explode}\n )\n assert_generates(raw_schema, expected, \"cookies\")\n\n\n@pytest.mark.hypothesis_nested\n@pytest.mark.parametrize(\n \"schema, style, explode, expected\",\n (\n (ARRAY_SCHEMA, \"simple\", False, {\"color\": quote(\"blue,black,brown\")}),\n (ARRAY_SCHEMA, \"simple\", True, {\"color\": quote(\"blue,black,brown\")}),\n (OBJECT_SCHEMA, \"simple\", False, {\"color\": CommaDelimitedObject(\"r,100,g,200,b,150\")}),\n (OBJECT_SCHEMA, \"simple\", True, {\"color\": DelimitedObject(\"r=100,g=200,b=150\")}),\n (PRIMITIVE_SCHEMA, \"label\", False, {\"color\": quote(\".1\")}),\n (PRIMITIVE_SCHEMA, \"label\", True, {\"color\": quote(\".1\")}),\n (ARRAY_SCHEMA, \"label\", False, {\"color\": quote(\".blue,black,brown\")}),\n (ARRAY_SCHEMA, \"label\", True, {\"color\": quote(\".blue.black.brown\")}),\n (OBJECT_SCHEMA, \"label\", False, {\"color\": CommaDelimitedObject(\".r,100,g,200,b,150\", prefix=\".\")}),\n (OBJECT_SCHEMA, \"label\", True, {\"color\": DelimitedObject(\".r=100.g=200.b=150\", prefix=\".\", delimiter=\".\")}),\n (PRIMITIVE_SCHEMA, \"matrix\", False, {\"color\": quote(\";color=1\")}),\n (PRIMITIVE_SCHEMA, \"matrix\", True, {\"color\": quote(\";color=1\")}),\n (ARRAY_SCHEMA, \"matrix\", False, {\"color\": quote(\";blue,black,brown\")}),\n (ARRAY_SCHEMA, \"matrix\", True, {\"color\": quote(\";color=blue;color=black;color=brown\")}),\n (OBJECT_SCHEMA, \"matrix\", False, {\"color\": CommaDelimitedObject(\";r,100,g,200,b,150\", prefix=\";\")}),\n (OBJECT_SCHEMA, \"matrix\", True, {\"color\": DelimitedObject(\";r=100;g=200;b=150\", prefix=\";\", delimiter=\";\")}),\n ),\n)\ndef test_path_serialization_styles_openapi3(schema, style, explode, expected):\n raw_schema = {\n \"openapi\": \"3.0.2\",\n \"info\": {\"title\": \"Test\", \"description\": \"Test\", \"version\": \"0.1.0\"},\n \"paths\": {\n \"/teapot/{color}\": {\n \"get\": {\n \"summary\": \"Test\",\n \"parameters\": [\n {\n \"name\": \"color\",\n \"in\": \"path\",\n \"required\": True,\n \"schema\": schema,\n \"style\": style,\n \"explode\": explode,\n }\n ],\n \"responses\": {\"200\": {\"description\": \"OK\"}},\n }\n }\n },\n }\n schema = schemathesis.from_dict(raw_schema)\n\n @given(case=schema[\"/teapot/{color}\"][\"GET\"].as_strategy())\n def test(case):\n assert case.path_parameters == expected\n\n test()\n\n\n@pytest.mark.hypothesis_nested\ndef test_query_serialization_styles_openapi_multiple_params():\n raw_schema = make_openapi_schema(\n {\n \"name\": \"color1\",\n \"in\": \"query\",\n \"required\": True,\n \"schema\": ARRAY_SCHEMA,\n \"explode\": False,\n \"style\": \"pipeDelimited\",\n },\n {\n \"name\": \"color2\",\n \"in\": \"query\",\n \"required\": True,\n \"schema\": ARRAY_SCHEMA,\n \"explode\": False,\n \"style\": \"spaceDelimited\",\n },\n )\n assert_generates(raw_schema, {\"color1\": \"blue|black|brown\", \"color2\": \"blue black brown\"}, \"query\")\n\n\n@pytest.mark.hypothesis_nested\n@pytest.mark.parametrize(\n \"collection_format, expected\",\n (\n (\"csv\", {\"color\": \"blue,black,brown\"}),\n (\"ssv\", {\"color\": \"blue black brown\"}),\n (\"tsv\", {\"color\": \"blue\\tblack\\tbrown\"}),\n (\"pipes\", {\"color\": \"blue|black|brown\"}),\n (\"multi\", {\"color\": [\"blue\", \"black\", \"brown\"]}),\n ),\n)\ndef test_query_serialization_styles_swagger2(collection_format, expected):\n raw_schema = {\n \"swagger\": \"2.0\",\n \"info\": {\"title\": \"Test\", \"description\": \"Test\", \"version\": \"0.1.0\"},\n \"host\": \"127.0.0.1:8888\",\n \"basePath\": \"/\",\n \"schemes\": [\"http\"],\n \"produces\": [\"application/json\"],\n \"paths\": {\n \"/teapot\": {\n \"get\": {\n \"parameters\": [\n {\n \"in\": \"query\",\n \"name\": \"color\",\n \"required\": True,\n \"type\": \"array\",\n \"items\": {\"type\": \"string\"},\n \"collectionFormat\": collection_format,\n \"enum\": [[\"blue\", \"black\", \"brown\"]],\n }\n ],\n \"responses\": {\"200\": {\"description\": \"OK\"}},\n }\n }\n },\n }\n assert_generates(raw_schema, expected, \"query\")\n\n\n@pytest.mark.parametrize(\"item, expected\", (({}, {}), ({\"key\": 1}, {\"key\": \"TEST\"})))\ndef test_item_is_missing(item, expected):\n # When there is no key in the data\n\n @conversion\n def foo(data, name):\n data[name] = \"TEST\"\n\n foo(\"key\")(item)\n\n # Then the data should not be affected\n # And should be otherwise\n assert item == expected\n\n\nclass JSONString(Prefixed):\n def prepare(self, value):\n return json.loads(unquote(value))\n\n\ndef test_content_serialization():\n raw_schema = make_openapi_schema(\n {\"in\": \"query\", \"name\": \"filter\", \"required\": True, \"content\": {\"application/json\": {\"schema\": OBJECT_SCHEMA}}}\n )\n assert_generates(raw_schema, {\"filter\": JSONString('{\"r\":100, \"g\": 200, \"b\": 150}')}, \"query\")\n","sub_path":"test/specs/openapi/test_serializing.py","file_name":"test_serializing.py","file_ext":"py","file_size_in_byte":10428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"487590324","text":"import pandas as pd\nfrom tensorflow.keras.models import load_model\n\nfrom flask import Flask, request, render_template\napp = Flask(__name__)\n\nSUBMISSION_DIRECTORY = \"./results/\"\nSUBMISSION_NAME = \"submission.csv\"\nSUBMISSION_PATH = SUBMISSION_DIRECTORY + SUBMISSION_NAME\n\nSCATTER_PLOT_DIRECTORY = \"./static/images/scatterplots/\"\n\n# The number of top MOA's to be displayed in the output. (MoA stands for Mechanism of Action)\nNUMBER_OF_TOP_MOA = 10\n\n# Load the saved model (Deserialization)\nmodel = load_model('neural_network_model.h5')\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n@app.route('/predict',methods=['POST'])\ndef predict():\n test_features = pd.read_csv(request.files.get('csvfile'))\n test_features.loc[:, 'cp_type'] = test_features.loc[:, 'cp_type'].map({'trt_cp': 0, 'ctl_vehicle': 1})\n test_features.loc[:, 'cp_dose'] = test_features.loc[:, 'cp_dose'].map({'D1': 0, 'D2': 1})\n\n test_id = x_test=test_features['sig_id'].values\n x_test = test_features.drop(['sig_id'], axis='columns', inplace=False)\n\n y_pred = model.predict(x_test)\n print(\"Predicted values (y_pred) = \", y_pred)\n submissionColumns = pd.read_csv('submissionColumns.csv')\n column_names = submissionColumns.columns\n\n id_list= list(test_id)\n y_pred_list= list(y_pred)\n \n dictionary={}\n for column in column_names:\n dictionary[column]=[]\n column_names = list(column_names)\n column_names.remove('sig_id')\n dictionary['sig_id'] = test_id\n for i in range(len(y_pred_list)):\n for j in range(206):\n dictionary[column_names[j]].append(y_pred_list[i][j])\n df=pd.DataFrame(dictionary)\n df.to_csv(SUBMISSION_PATH, index=False)\n\n dfScatterPlot = pd.DataFrame(columns=[\"ID of the class of drug\", \"Probability\"]) \n dfScatterPlot[\"ID of the class of drug\"] = [class_id for class_id in range(1,207)] # Class of drugs varies from 1 to 206\n\n classOfDrugs = list(df.columns[1:])\n print(\"All the classes of drugs = \")\n print(classOfDrugs)\n\n finalListOfMoa = list()\n for index, row in df.iterrows():\n drugId = row[0]\n dfScatterPlot[\"Probability\"] = row[1:].values\n dfSortedProbability = dfScatterPlot.sort_values(by = \"Probability\", ascending = False) \n dfTopValues = dfSortedProbability[:NUMBER_OF_TOP_MOA]\n \n topIdOfClassOfDrugs = list(dfTopValues[\"ID of the class of drug\"])\n topClassOfDrugs = [classOfDrugs[class_id - 1] for class_id in topIdOfClassOfDrugs]\n\n topProbabilities = list(dfTopValues[\"Probability\"])\n topRoundedProbabilities = [round(probability, 4) for probability in topProbabilities]\n \n listOfTuples = list(zip(topIdOfClassOfDrugs,topClassOfDrugs, topRoundedProbabilities))\n\n currentMoa = list()\n currentMoa.append(drugId)\n currentMoa.extend(listOfTuples)\n finalListOfMoa.append(currentMoa)\n\n imageExtension = \".jpeg\"\n imageNumber = str(index)\n imageName = \"scatterimage\" + imageNumber + imageExtension\n SCATTER_PLOT_PATH = SCATTER_PLOT_DIRECTORY + imageName\n \n print(\"dfTopValues\", dfTopValues)\n figure = dfTopValues.plot( \n kind = \"scatter\",\n x='ID of the class of drug', \n y='Probability', \n title= \"Scatter plot for drug id : \" + drugId\n ).get_figure()\n figure.savefig(SCATTER_PLOT_PATH)\n \n print(\"DF SCATTER PLOT:\")\n print(dfScatterPlot)\n\n print(\"Final List of MoA values = \", finalListOfMoa)\n return render_template('index.html', \n moaList = finalListOfMoa, \n NUMBER_OF_TOP_MOA = NUMBER_OF_TOP_MOA,\n SCATTER_PLOT_DIRECTORY = SCATTER_PLOT_DIRECTORY\n )\n\nif __name__ == \"__main__\":\n app.run(debug=True, use_reloader=False)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"244214240","text":"from flask_restful import Resource, reqparse\nfrom flask_jwt import jwt_required\nimport sqlite3\n\n\nclass Item(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument(\"price\",\n type=float,\n required=True,\n help=\"Please pass price as well\"\n )\n\n @jwt_required()\n def get(self, name):\n item = Item.find_by_name(name)\n if item:\n return {\"item\": {\"name\": item[0], \"price\": item[1]}}\n return {\"message\": \"Item not found\"}, 400\n\n @classmethod\n def find_by_name(cls, name):\n connection = sqlite3.connect(\"data.db\")\n cursor = connection.cursor()\n\n query = \"SELECT * FROM items WHERE name=?\"\n result = cursor.execute(query, (name,))\n print(result)\n item = result.fetchone()\n\n connection.close()\n return item\n\n @classmethod\n def insert_item(cls, item):\n connection = sqlite3.connect(\"data.db\")\n cursor = connection.cursor()\n\n query = \"INSERT INTO items VALUES (?, ?)\"\n cursor.execute(query, (item[\"name\"], item[\"price\"]))\n\n connection.commit()\n connection.close()\n\n @classmethod\n def update_item(cls, item):\n connection = sqlite3.connect(\"data.db\")\n cursor = connection.cursor()\n\n query = \"UPDATE items SET price=? WHERE name=?\"\n cursor.execute(query, (item[\"price\"], item[\"name\"]))\n\n connection.commit()\n connection.close()\n\n def post(self, name):\n item = Item.find_by_name(name)\n if item:\n return {\"message\": f\"The item with name {name} is already exist.\"}, 400\n request_data = Item.parser.parse_args()\n\n item = {\"name\": name, \"price\": request_data[\"price\"]}\n try:\n Item.insert_item(item)\n except:\n return {\"message\": \"An error occurred inserting the item\"}, 500 # Internal Server Error\n return item, 201\n\n def delete(self, name):\n\n connection = sqlite3.connect(\"data.db\")\n cursor = connection.cursor()\n\n query = \"DELETE FROM items WHERE name=?\"\n cursor.execute(query, (name,))\n\n connection.commit()\n connection.close()\n return {\"message\": \"Item Deleted\"}\n\n def put(self, name):\n data = Item.parser.parse_args()\n item = Item.find_by_name(name)\n updated_item = {\"name\": name, \"price\": data[\"price\"]}\n\n if item is None:\n try:\n Item.insert_item(updated_item)\n except:\n return {\"message\": \"An error occurred inserting the item\"}, 500\n else:\n try:\n Item.update_item(updated_item)\n except:\n return {\"message\": \"An error occurred updating the item\"}, 500\n\n return updated_item\n\n\nclass ItemList(Resource):\n def get(self):\n connection = sqlite3.connect('data.db')\n cursor = connection.cursor()\n\n query = \"SELECT * FROM items\"\n all_items = []\n rows = cursor.execute(query)\n for row in rows:\n item = {\"name\": row[0], \"price\": row[1]}\n all_items.append(item)\n\n connection.close()\n return {\"items\": all_items}\n","sub_path":"item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"262050143","text":"from scipy.linalg import inv,pinv\nfrom scipy.stats import f, chi2\nfrom parametric_analysis.core.detectors import Threshold_Detector\nimport numpy as np\n\n#MARK Detector Routing\n\ndef Auto_detector(estimator,pfa=None,threshold=None,name=\"Auto Detector\"):\n\n if threshold is not None:\n if estimator.sigma2 is not None:\n detector=GLRT_detector_noise_known(estimator,threshold,name=name)\n else:\n detector=GLRT_detector_noise_unknown(estimator,threshold,name=name)\n else:\n if estimator.sigma2 is not None:\n detector=CFAR_detector_noise_known(estimator,pfa,name=name)\n else:\n detector=CFAR_detector_noise_unknown(estimator,pfa,name=name)\n return detector\n\n#MARK Detector Implementation\n\nclass GLRT_detector_noise_known(Threshold_Detector):\n \n \"\"\" This Class implements the GLRT detector for the classical Linear Model. The decision statistic is given by [KAY98] \"\"\"\n\n def __init__(self,estimator,threshold,name=\"GLRT detector\"):\n self.estimator=estimator\n self.threshold=threshold\n self.name=name\n\n def compute_criterion(self,signal):\n signal_estimated=self.estimator.estimate(signal)\n H=signal_estimated.H\n theta=signal_estimated.theta\n sigma2=signal_estimated.sigma2\n criterion=np.ravel(theta.T*(H.T*H)*theta/sigma2)\n return criterion\n\nclass CFAR_detector_noise_known(GLRT_detector_noise_known):\n \n \"\"\" This Class implements the CFAR detector \"\"\"\n def __init__(self,estimator,pfa,name=\"CFAR detector noise known\"):\n self.estimator=estimator\n self.pfa=pfa\n self.name=name\n \n @property\n def threshold(self):\n L=self.estimator.H.shape[1]\n return chi2.ppf(1-self.pfa,L)\n\n#MARK: Detector: Unknown Noise\n\nclass GLRT_detector_noise_unknown(Threshold_Detector):\n \n \"\"\" This Class implements the GLRT detector for the classical Linear Model. \"\"\"\n \n def __init__(self,estimator,threshold,name=\"GLRT detector\"):\n self.estimator=estimator\n self.threshold=threshold\n self.name=name\n \n def compute_criterion(self,signal):\n signal_estimated=self.estimator.estimate(signal)\n H=signal_estimated.H\n N,L=H.shape\n theta=signal_estimated.theta\n coef=(N-L)/L\n num=theta.T*(H.T*H)*theta\n den=signal.T*(np.eye(N)-H*pinv(H))*signal\n criterion=np.ravel(coef*num/den)\n return criterion\n\nclass CFAR_detector_noise_unknown(GLRT_detector_noise_unknown):\n \n \"\"\" This Class implements the CFAR detector for the classical Linear Model.\"\"\"\n\n def __init__(self,estimator,pfa,name=\"CFAR detector noise Unknown\"):\n self.estimator=estimator\n self.pfa=pfa\n self.name=name\n\n @property\n def threshold(self):\n N,L=self.estimator.H.shape\n return f.ppf(1-self.pfa,L,N-L)\n\n\n","sub_path":"parametric_analysis/linear_signal_model/detectors.py","file_name":"detectors.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"100448909","text":"from ..Models import (\n Station,\n MonitoredSite,\n Sensor,\n Base,\n fieldActivity,\n MonitoredSiteList\n)\nfrom ..GenericObjets import CollectionEngine\nimport json\nfrom sqlalchemy import select, desc, join\nfrom sqlalchemy.exc import IntegrityError\nfrom collections import OrderedDict\nfrom ..controllers.security import RootCore, context_permissions\nfrom . import DynamicObjectView, DynamicObjectCollectionView\n\nSensorType = Sensor.TypeClass\n\nclass MonitoredSiteView(DynamicObjectView):\n\n model = MonitoredSite\n\n def __init__(self, ref, parent):\n DynamicObjectView.__init__(self, ref, parent)\n self.actions = {'history': self.history,\n 'equipment': self.getEquipment,\n 'stations': self.getStations,\n 'getFields': self.getGrid,\n 'history': self.history}\n\n def __getitem__(self, ref):\n if ref in self.actions:\n self.retrieve = self.actions.get(ref)\n return self\n return self\n\n def update(self):\n try:\n response = DynamicObjectView.update(self)\n except IntegrityError as e:\n self.session.rollback()\n response = self.request.response\n response.status_code = 510\n response.text = \"IntegrityError\"\n return response\n\n def getGrid(self):\n cols = self.objectDB.getGrid(moduleName='MonitoredSiteGridHistory')\n return cols\n\n def getStations(self):\n id_site = self.objectDB.ID\n joinTable = join(Station, fieldActivity,\n Station.fieldActivityId == fieldActivity.ID)\n query = select([Station.StationDate,\n Station.LAT,\n Station.LON,\n Station.ID,\n Station.Name,\n fieldActivity.Name.label('fieldActivity_Name')]\n ).select_from(joinTable\n ).where(Station.FK_MonitoredSite == id_site)\n\n result = self.session.execute(query).fetchall()\n response = []\n for row in result:\n row = dict(row)\n row['StationDate'] = row['StationDate'].strftime('%Y-%m-%d %H:%M:%S')\n response.append(row)\n return response\n\n def history(self):\n _id = self.objectDB.ID\n data = self.request.params.mixed()\n searchInfo = {}\n searchInfo['criteria'] = [\n {'Column': 'ID', 'Operator': 'Is', 'Value': _id}]\n try:\n searchInfo['order_by'] = json.loads(data['order_by'])\n except:\n searchInfo['order_by'] = []\n\n moduleFront = self.parent.getConf('MonitoredSiteGridHistory')\n view = Base.metadata.tables['MonitoredSitePosition']\n listObj = CollectionEngine(MonitoredSite, moduleFront, View=view)\n dataResult = listObj.GetFlatDataList(searchInfo)\n\n if 'geo' in self.request.params:\n geoJson = []\n for row in dataResult:\n geoJson.append({\n 'type': 'Feature',\n 'properties': {'Date': row['StartDate']},\n 'geometry': {\n 'type': 'Point',\n 'coordinates': [row['LAT'], row['LON']]}\n })\n result = {'type': 'FeatureCollection', 'features': geoJson}\n else:\n countResult = listObj.count(searchInfo)\n result = [{'total_entries': countResult}]\n result.append(dataResult)\n return result\n\n def getEquipment(self):\n id_site = self.objectDB.ID\n table = Base.metadata.tables['MonitoredSiteEquipment']\n\n joinTable = join(table, Sensor, table.c['FK_Sensor'] == Sensor.ID)\n joinTable = join(joinTable, SensorType,\n Sensor._type_id == SensorType.ID)\n query = select([table.c['StartDate'],\n table.c['EndDate'],\n Sensor.UnicIdentifier,\n table.c['FK_MonitoredSite'],\n SensorType.Name.label('Type')]\n ).select_from(joinTable\n ).where(table.c['FK_MonitoredSite'] == id_site\n ).order_by(desc(table.c['StartDate']))\n\n result = self.session.execute(query).fetchall()\n response = []\n for row in result:\n curRow = OrderedDict(row)\n curRow['StartDate'] = curRow['StartDate'].strftime('%Y-%m-%d %H:%M:%S')\n if curRow['EndDate'] is not None:\n curRow['EndDate'] = curRow['EndDate'].strftime('%Y-%m-%d %H:%M:%S')\n else:\n curRow['EndDate'] = ''\n response.append(curRow)\n\n return response\n\n\nclass MonitoredSitesView(DynamicObjectCollectionView):\n\n Collection = MonitoredSiteList\n item = MonitoredSiteView\n moduleFormName = 'MonitoredSiteForm'\n moduleGridName = 'MonitoredSiteGrid'\n\n def __init__(self, ref, parent):\n DynamicObjectCollectionView.__init__(self, ref, parent)\n self.__acl__ = context_permissions[ref]\n\n if not self.typeObj:\n self.typeObj = 1\n\n def insert(self):\n try:\n response = DynamicObjectCollectionView.insert(self)\n except IntegrityError as e:\n self.session.rollback()\n self.request.response.status_code = 520\n response = self.request.response\n response.text = \"This name is already used for another monitored site\"\n pass\n return response\n\n\nRootCore.listChildren.append(('monitoredSites', MonitoredSitesView))\n","sub_path":"Back/ecoreleve_server/Views/monitoredSite.py","file_name":"monitoredSite.py","file_ext":"py","file_size_in_byte":5711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"493211591","text":"import sys\r\nprint(\"初始化第一个矩阵\")\r\nlong=int(input(\"请输入矩阵的列\"))\r\nwide=int(input(\"请输入矩阵的行\"))\r\nspace=long*wide\r\nfz1=1\r\na = [[0]*long for i in range(wide)]\r\nprint(a)\r\nprint(a[1][1])\r\nchoose1=int(input(\"请做出选择:\\n1:矩阵由代码默认生成\\n2:自行输入\\n\"))\r\nif choose1==1:#确定矩阵大小并赋值\r\n for i in range(wide):\r\n for j in range(long):\r\n a[i][j]=int(fz1)\r\n fz1+=1\r\n print(a)\r\n\r\nelse:\r\n #a = np.empty([long,wide], dtype=int)#确定矩阵类型\r\n for i in range(wide):#通过循环自行赋值\r\n for j in range(long):\r\n a[i][j]=int(input())\r\n print(a)\r\n\r\nprint(\"初始化第二个矩阵\")\r\nlong2=int(input(\"请输入矩阵的列\"))\r\nwide2=int(input(\"请输入矩阵的行\"))\r\nspace=long2*wide2\r\nfz1=1\r\nb = [[0]*long2 for i in range(wide2)]\r\nprint(b)\r\nprint(b[1][1])\r\nchoose1=int(input(\"请做出选择:\\n1:矩阵由代码默认生成\\n2:自行输入\\n\"))\r\nif choose1==1:#确定矩阵大小并赋值\r\n for i in range(wide2):\r\n for j in range(long2):\r\n b[i][j]=int(fz1)\r\n fz1+=1\r\n print(b)\r\n\r\nelse:\r\n #a = np.empty([long,wide], dtype=int)#确定矩阵类型\r\n for i in range(wide2):#通过循环自行赋值\r\n for j in range(long2):\r\n b[i][j]=int(input())\r\n print(b)\r\n\r\nprint(\"请选择矩阵间的运算关系\")\r\n\r\n\r\nchoose2=int(input(\"1:加法运算\\n2:减法运算\\n3:数乘运算\\n4:点乘运算\\n5:矩阵转置\"))\r\n\r\nif choose2==1:\r\n c = [[0] * long for i in range(wide)]\r\n for i in range(long):\r\n for j in range(wide):\r\n c[j][i]=a[j][i]+b[j][i]\r\n print(\"注意:应满足加法基本规则\")\r\n print(c)\r\nif choose2==2:\r\n c = [[0] * long for i in range(wide)]\r\n choose3=int(input(\"1:a-b\\n2:b-a\"))\r\n if choose3==1:\r\n for i in range(long):\r\n for j in range(wide):\r\n c[j][i]=a[j][i]-b[j][i]\r\n else:\r\n for i in range(long):\r\n for j in range(wide):\r\n c[j][i]=b[j][i]-a[j][i]\r\n print(c)\r\nif choose2==3:\r\n a3=int(input(\"请输入数乘的数字(数乘的对象默认为第一个)\"))\r\n print(a3*a)\r\nif choose2==4:\r\n if wide != long2:\r\n print(\"不满足矩阵的乘法条件\")\r\n else:\r\n c = [[0] * long2 for i in range(long2)]\r\n i=j=k=l=0\r\n fz2=0\r\n for i in range(long2):\r\n for j in range(long2):\r\n for k in range(long):\r\n #for l in range(wide2):\r\n fz2+=int(a[i][k])*int(b[k][j])\r\n print(a[i][k],b[k][j],fz2)\r\n c[i][j] =fz2\r\n print(c)\r\n fz2=0\r\n print('矩阵间的乘积为',c)\r\nif choose2==5:\r\n c = [[0] * wide for i in range(long)]\r\n d = [[0] * wide2 for i in range(long2)]\r\n for i in range(long):\r\n for j in range(wide):\r\n c[i][j]=a[j][i]\r\n for i in range(long2):\r\n for j in range(wide2):\r\n d[i][j]=b[j][i]\r\n print(c)\r\n print(d)\r\n\r\n\r\n\r\nif __name__ =='__main__':\r\n import doctest\r\n doctest.testmod()","sub_path":"320180941141-juyida/homework7/mymatrix.py","file_name":"mymatrix.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"633906052","text":"import os, sys, pdb, random, time\n\n# If in practice environment and will use relative path\nIN = \"./mnt/in\"\nOUT = \"./mnt/out\"\n\n# For real environment. This is where your algorithm will read and write data\n#IN = \"/mnt/in\"\n#OUT = \"/mnt/out\"\n\ninput_file_name = os.listdir(IN)[0]\noutput_file_name = \"output_data.csv\"\n\nclasses = ['a','b']\nif __name__ == \"__main__\":\n # Read from IN\n with open(os.path.join(IN,input_file_name), 'r') as input:\n lines = input.read()\n key = lines.split('\\n')[1:]\n\n # Simulate an algorithm running\n for i in range(10):\n print(f\"epoch: {i+1}\")\n time.sleep(0)\n \n # Write to OUT\n with open(os.path.join(OUT,output_file_name), 'w') as output:\n output.write(\"key,class\\n\")\n for id in key:\n if int(id) == len(key):\n output.write(f\"{id},{random.sample(classes,1)[0]}\")\n else:\n output.write(f\"{id},{random.sample(classes,1)[0]}\\n\")\n \n \n\n","sub_path":"Template/participant_execution_environment/submission.py","file_name":"submission.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"425095636","text":"# -*- coding: utf-8 -*-\n# Coded by @maxunof with power of Senko!\n\nimport time\n\nfrom .. import sdk\n\n\nclass Module(sdk.Module):\n def __init__(self):\n self.name: str = \"Suspension\"\n\n async def suspend_cmd(self, event: sdk.Event, command: sdk.Command):\n if command.arg == \"\":\n await sdk.send(event.message, \"You need to specify suspension time (in seconds).\")\n return\n\n try:\n seconds = int(command.arg)\n await sdk.send(\n event.message, f\"Bot is sleeping for {seconds} seconds 😴\"\n )\n time.sleep(seconds)\n except ValueError:\n await sdk.send(event.message, \"Invalid suspension time.\")\n","sub_path":"suspension.py","file_name":"suspension.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"602740644","text":"\"\"\"MeshNet implemented in TensorFlow.\n\nReference\n---------\nFedorov, A., Johnson, J., Damaraju, E., Ozerin, A., Calhoun, V., & Plis, S.\n(2017, May). End-to-end learning of brain tissue segmentation from imperfect\nlabeling. IJCNN 2017. (pp. 3785-3792). IEEE.\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.estimator import TowerOptimizer, replicate_model_fn\nfrom tensorflow.python.estimator.canned.optimizers import (\n get_optimizer_instance\n)\n\nfrom nobrainer.models.util import check_required_params, set_default_params, str2bool\nfrom nobrainer.models import vwn_conv\nfrom nobrainer.models.bayesian_dropout import concrete_dropout\n\ndef _layer(inputs,\n mode,\n layer_num,\n filters,\n kernel_size,\n dilation_rate,\n is_mc_b,\n is_mc_g,\n use_expectation):\n \"\"\"Layer building block of MeshNet.\n\n Performs 3D convolution, activation, batch normalization, and dropout on\n `inputs` tensor.\n\n Args:\n inputs : float `Tensor`, input tensor.\n mode : string, a TensorFlow mode key.\n layer_num : int, value to append to each operator name. This should be\n the layer number in the network.\n filters : int, number of 3D convolution filters.\n kernel_size : int or tuple, size of 3D convolution kernel.\n dilation_rate : int or tuple, rate of dilution in 3D convolution.\n dropout_rate : float, the dropout rate between 0 and 1.\n\n Returns:\n `Tensor` of same type as `inputs`.\n \"\"\"\n training = mode == tf.estimator.ModeKeys.TRAIN\n\n with tf.variable_scope('layer_{}'.format(layer_num)):\n conv = vwn_conv.conv3d(\n inputs, filters=filters, kernel_size=kernel_size,\n padding='SAME', dilation_rate=dilation_rate, activation=None,is_mc=is_mc_g\n )\n conv = concrete_dropout(conv,is_mc_b,filters,use_expectation=use_expectation)\n return tf.nn.relu(conv)\n\n\ndef model_fn(features,\n labels,\n mode,\n params):\n \"\"\"MeshNet model function.\n\n Args:\n features: 5D float `Tensor`, input tensor. This is the first item\n returned from the `input_fn` passed to `train`, `evaluate`, and\n `predict`. Use `NDHWC` format.\n labels: 4D float `Tensor`, labels tensor. This is the second item\n returned from the `input_fn` passed to `train`, `evaluate`, and\n `predict`. Labels should not be one-hot encoded.\n mode: Optional. Specifies if this training, evaluation or prediction.\n params: `dict` of parameters. All parameters below are required.\n - n_classes: number of classes to classify.\n - optimizer: instance of TensorFlow optimizer.\n - n_filters: number of filters to use in each convolution. The\n original implementation used 21 filters to classify brainmask\n and 71 filters for the multi-class problem.\n - dropout_rate: rate of dropout. For example, 0.1 would drop 10% of\n input units.\n\n Returns:\n `tf.estimator.EstimatorSpec`\n\n Raises:\n `ValueError` if required parameters are not in `params`.\n \"\"\"\n volume = features\n if isinstance(volume, dict):\n volume = features['volume']\n \n required_keys = {'n_classes'}\n default_params = {'optimizer': None,'n_filters': 96}\n check_required_params(params=params, required_keys=required_keys)\n set_default_params(params=params, defaults=default_params)\n\n tf.logging.debug(\"Parameters for model:\")\n tf.logging.debug(params)\n\n # Dilation rate by layer.\n dilation_rates = (\n (1, 1, 1),\n (1, 1, 1),\n (1, 1, 1),\n (2, 2, 2),\n (4, 4, 4),\n (8, 8, 8),\n (1, 1, 1),\n )\n \n is_mc_g = tf.constant(str2bool('False'),dtype=tf.bool)\n is_mc_b = tf.constant(str2bool(params['is_mc']),dtype=tf.bool)\n \n outputs = volume\n \n for ii, dilation_rate in enumerate(dilation_rates):\n outputs = _layer(\n outputs, mode=mode, layer_num=ii + 1, filters=params['n_filters'],\n kernel_size=3, dilation_rate=dilation_rate, is_mc_b=is_mc_b, is_mc_g=is_mc_g, use_expectation=str2bool(params['is_mc'])\n )\n\n with tf.variable_scope('logits'):\n logits = vwn_conv.conv3d(\n inputs=outputs, filters=params['n_classes'], kernel_size=(1, 1, 1),\n padding='SAME', activation=None, is_mc=is_mc_g\n )\n\n predicted_classes = tf.argmax(logits, axis=-1)\n\n if mode == tf.estimator.ModeKeys.PREDICT:\n predictions = {\n 'class_ids': predicted_classes,\n 'probabilities': tf.nn.softmax(logits),\n 'logits': logits,\n }\n export_outputs = {\n 'outputs': tf.estimator.export.PredictOutput(predictions)}\n return tf.estimator.EstimatorSpec(\n mode=mode,\n predictions=predictions,\n export_outputs=export_outputs)\n\n if params['prior_path'] != None:\n prior_np = np.load(params['prior_path'])\n \n with tf.variable_scope(\"prior\"):\n i=-1\n for v in tf.get_collection('ms'):\n i += 1\n if params['prior_path'] == None:\n tf.add_to_collection('ms_prior',tf.Variable(tf.constant(0, dtype = v.dtype, shape = v.shape),trainable = False))\n else:\n tf.add_to_collection('ms_prior',tf.Variable(tf.convert_to_tensor(prior_np[0][i], dtype = tf.float32),trainable = False))\n \n ms = tf.get_collection('ms')\n ms_prior = tf.get_collection('ms_prior')\n\n print(len(ms))\n i=-1\n for v in tf.get_collection('ms'):\n i += 1\n if params['prior_path'] == None:\n tf.add_to_collection('sigmas_prior',tf.Variable(tf.constant(0.1, dtype = v.dtype, shape = v.shape),trainable = False))\n else:\n tf.add_to_collection('sigmas_prior',tf.Variable(tf.convert_to_tensor(prior_np[1][i], dtype = tf.float32),trainable = False))\n\n sigmas = tf.get_collection('sigmas')\n sigmas_prior = tf.get_collection('sigmas_prior')\n \n nll_loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits))\n tf.summary.scalar('nll_loss', nll_loss)\n \n l2_loss = tf.add_n([tf.reduce_sum((tf.square(ms[i] - ms_prior[i])) / ((tf.square(sigmas_prior[i]) + 1e-8) * 2.0)) for i in range(len(ms))], name = 'l2_loss')\n tf.summary.scalar('l2_loss', l2_loss)\n \n \n sigma_squared_loss = tf.add_n([tf.reduce_sum(tf.square(sigmas[i]) / ((tf.square(sigmas_prior[i]) + 1e-8) * 2.0)) for i in range(len(sigmas))],name = 'sigma_squared_loss')\n tf.summary.scalar('sigma_squared_loss', sigma_squared_loss)\n \n log_sigma_loss = tf.add_n([tf.reduce_sum(tf.log(v+1e-8)) for v in sigmas],name='log_sigmas_loss')\n tf.summary.scalar('log_sigma_loss', log_sigma_loss)\n \n ps = tf.get_collection('ps')\n p_prior= 0.5\n b_kld_loss = tf.add_n([tf.reduce_sum(p * (tf.log(p+1e-7) - tf.log(p_prior)) + (1.0 - p) * (tf.log(1.0-p+1e-7) - tf.log(1.0-p_prior))) for p in ps],name='b_kld_loss')\n tf.summary.scalar('b_kld_loss', b_kld_loss)\n \n n_examples = tf.constant(params['n_examples'],dtype=ms[0].dtype)\n tf.summary.scalar('n_examples', n_examples)\n \n \n if not params['only_kld']:\n \n if str2bool(params['is_mc']):\n loss = nll_loss + (l2_loss + sigma_squared_loss - log_sigma_loss + b_kld_loss) / n_examples\n else:\n loss = nll_loss + (l2_loss) / n_examples\n \n else:\n mse_m_loss = tf.add_n([tf.reduce_sum(tf.square(ms[i] - ms_prior[i])) for i in range(len(ms))], name = 'mse_m_loss')\n tf.summary.scalar('mse_m_loss', l2_loss)\n \n mse_sigmas_loss = tf.add_n([tf.reduce_sum(tf.square(sigmas[i] - sigmas_prior[i])) for i in range(len(sigmas))], name = 'mse_sigmas_loss')\n tf.summary.scalar('mse_sigmas_loss', mse_sigmas_loss)\n loss = mse_m_loss + mse_sigmas_loss\n \n if mode == tf.estimator.ModeKeys.EVAL:\n return tf.estimator.EstimatorSpec(\n mode=mode, loss=loss, eval_metric_ops=None,\n )\n\n assert mode == tf.estimator.ModeKeys.TRAIN\n\n global_step = tf.train.get_global_step()\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_op = params['optimizer'].minimize(loss, global_step=global_step)\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)\n\n\nclass MeshNetCWN(tf.estimator.Estimator):\n \"\"\"MeshNet model.\n\n Example:\n ```python\n import numpy as np\n import tensorflow as tf\n\n shape = (1, 10, 10, 10) # Batch of 1.\n X = np.random.rand(*shape, 1).astype(np.float32)\n y = np.random.randint(0, 9, size=(shape), dtype=np.int32)\n dset_fn = lambda: tf.data.Dataset.from_tensors((X, y))\n estimator = nobrainer.models.MeshNet(\n n_classes=10, optimizer='Adam', n_filters=71, dropout_rate=0.25,\n learning_rate=0.001,\n )\n estimator.train(input_fn=dset_fn)\n ```\n\n Args:\n n_classes: int, number of classes to classify.\n optimizer: instance of TensorFlow optimizer or string of optimizer\n name.\n n_filters: int (default 21), number of filters to use in each\n convolution. The original implementation used 21 filters to\n classify brainmask and 71 filters for the multi-class problem.\n dropout_rate: float in range [0, 1] (default 0.25). Rate of dropout.For\n example, 0.1 would drop 10% of input units.\n learning_rate: float, only required if `optimizer` is a string.\n model_dir: Directory to save model parameters, graph, etc. This can\n also be used to load checkpoints from the directory in an estimator\n to continue training a previously saved model. If PathLike object,\n the path will be resolved. If None, the model_dir in config will be\n used if set. If both are set, they must be same. If both are None,\n a temporary directory will be used.\n config: Configuration object.\n warm_start_from: Optional string filepath to a checkpoint to warm-start\n from, or a `tf.estimator.WarmStartSettings` object to fully\n configure warm-starting. If the string filepath is provided instead\n of a `WarmStartSettings`, then all variables are warm-started, and\n it is assumed that vocabularies and Tensor names are unchanged.\n multi_gpu: boolean, if true, optimizer is wrapped in\n `tf.contrib.estimator.TowerOptimizer` and model function is wrapped\n in `tf.contrib.estimator.replicate_model_fn()`.\n \"\"\"\n def __init__(self,\n n_classes,\n optimizer,\n n_filters=64,\n n_examples=1.0,\n n_prior_samples=1.0,\n learning_rate=None,\n model_dir=None,\n config=None,\n warm_start_from=None,\n prior_path=None,\n multi_gpu=False,\n only_kld=False,\n is_mc='True'):\n print('Learning Rate: ' + str(learning_rate))\n params = {\n 'n_classes': n_classes,\n # If an instance of an optimizer is passed in, this will just\n # return it.\n 'optimizer': get_optimizer_instance(optimizer, learning_rate),\n 'n_filters': n_filters,\n 'n_examples': n_examples,\n 'prior_path': prior_path,\n 'n_prior_samples': n_prior_samples,\n 'only_kld': only_kld,\n 'is_mc': is_mc\n }\n\n _model_fn = model_fn\n\n if multi_gpu:\n params['optimizer'] = TowerOptimizer(params['optimizer'])\n _model_fn = replicate_model_fn(_model_fn)\n\n super(MeshNetCWN, self).__init__(\n model_fn=_model_fn, model_dir=model_dir, params=params,\n config=config, warm_start_from=warm_start_from\n )","sub_path":"nobrainer/models/meshnetcwn.py","file_name":"meshnetcwn.py","file_ext":"py","file_size_in_byte":12160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"92868308","text":"'''\nAim:: To read in Table 1 from Best et al. (2018, ApJS, 234, 1)\n http://adsabs.harvard.edu/abs/2018ApJS..234....1B\n Photometry and Proper Motions of M, L, and T Dwarfs from the Pan-STARRS1 3π Survey\n\nGood/useful links/URLs:: \n http://docs.astropy.org/en/v0.2.1/_generated/astropy.io.ascii.cds.Cds.html\n http://vizier.u-strasbg.fr/doc/catstd.htx\n https://github.com/astropy/astropy/blob/master/docs/io/unified.rst\n http://cds.u-strasbg.fr/doc/catstd.htx\n https://mail.scipy.org/pipermail/astropy/2016-May/004207.html\n http://docs.astropy.org/en/stable/table/\n http://jakevdp.github.io/astropy/api/astropy.io.ascii.Cds.html\n http://docs.astropy.org/en/v0.2.1/_generated/astropy.io.ascii.cds.Cds.html\n'''\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\nfrom matplotlib.ticker import AutoMinorLocator\n\nfrom astropy.table import Table\nfrom astropy.io import ascii\n\npath = '/cos_pc19a_npr/data/MLandT_dwarfs/'\ninfile = 'Best_2018_Table1_full.txt'\nreadin = path+infile\ntable = ascii.read(readin)\n\n## grizy from PS1\ngmag = table['PS1gmag'] \nrmag = table['PS1rmag']\nimag = table['PS1imag']\nzmag = table['PS1zmag']\nymag = table['PS1ymag']\n## 2MASS\nJ_tm = table['Jmag']\nH_tm = table['Hmag']\nKs_tm = table['Ksmag']\nW1mag = table['W1mag']\nW2mag = table['W2mag']\nW3mag = table['W3mag']\nW4mag = table['W4mag']\n\nSpT_optn = table['SpT-opt-n']\nSpT_nirn = table['SpT-nir-n']\n#SpT_opt = table['SpT-opt-n']\n\n## Just figuring out how many stars of a given Type\nno_types = int((table['SpT-opt-n'].max() - table['SpT-opt-n'].min()))\nfor ii in range(no_types):\n w =table[np.where(table['SpT-opt-n'] == ii) ]\n if (len(w)) > 0:\n print(ii, w['SpT-opt'][0], len(w))\n\n#path = '/cos_pc19a_npr/data/highest_z_QSOs/'\npath = '/cos_pc19a_npr/data/highest_z_QSOs/THE_TABLES/v0pnt97/'\nfilename ='THE_TABLE_v0pnt97x_PS1_ULAS_VHS_photom_v2.dat'\ntable=path+filename\nVHzQ = ascii.read(table)\n\nVHzQ = VHzQ[np.where( (VHzQ['iMag'] - VHzQ['zMag'] != 0.0))]\n\nredshift = VHzQ['redshift']\ng_PS1 = VHzQ['gMag']\nr_PS1 = VHzQ['rMag']\ni_PS1 = VHzQ['iMag']\nz_PS1 = VHzQ['zMag']\ny_PS1 = VHzQ['yMag']\nYmag = VHzQ['Yapermag']\nJmag = VHzQ['Jmag']\nHmag = VHzQ['Hmag']\nKmag = VHzQ['Kmag']\nW1mag = VHzQ['W1mag']\nW2mag = VHzQ['W2mag']\nW3mag = VHzQ['W3mag']\nW4mag = VHzQ['W4mag']\n\n\n## \n## Making the plot(s)\n##\nplt.rcParams.update({'font.size': 14})\n#matplotlib.rc('text', usetex=True)\nfig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(nrows=3, ncols=2, figsize=(14, 16),\n dpi=80, facecolor='w', edgecolor='k')\n\n#fig.tight_layout() # Or equivalently, \"plt.tight_layout()\"\n\n#minorLocator = AutoMinorLocator()\n\nlabelsize = 24\ntickwidth = 2.0\nmajorticklength = 12\nminorticklength = 6\nticklabelsize = labelsize\n\nls = 'solid'\nlw = 1.0\nms_clrsize = ((redshift-3.9)**5.5)\nms_large = 360.\nms = 120.\nms_small = 14.\ncmap = plt.cm.rainbow\n\nleft = 0.12 # the left side of the subplots of the figure\nright = 0.95 # the right side of the subplots of the figure\nbottom = 0.06 # the bottom of the subplots of the figure\ntop = 0.95 # the top of the subplots of the figure\nwspace = 0.35 # the amount of width reserved for space between subplots,\n # expressed as a fraction of the average axis width\nhspace = 0.35 # the amount of height reserved for space between subplots,\n # expressed as a fraction of the average axis height\nplt.subplots_adjust(left=left, bottom=bottom, right=right, top=top,\n wspace=wspace, hspace=hspace)\n \n##\n## Figure 7 of Best et al. (2018, ApJS, 234, 1)\n##\n## 1.\n## (r - i) vs. (z - y)\n##\nxmin=-0.4; xmax=3.8\nymin=-0.3; ymax=1.3\nax1.axis([xmin, xmax, ymin, ymax])\n## Quasars\ncmap = plt.cm.autumn_r\nax1.scatter((r_PS1 - i_PS1), (z_PS1 - y_PS1), c=redshift, cmap=cmap, s=ms, alpha=1.0)\n## Spectral Type\ncmap = plt.cm.rainbow\nax1.scatter((rmag - imag), (zmag - ymag), c=(SpT_optn**5.), cmap=cmap, alpha=0.60, s=ms_small)\n\nmajor_ticks = np.arange(0, 4, 1)\nax1.set_xticks(major_ticks)\nminorLocator = MultipleLocator(.1)\nax1.xaxis.set_minor_locator(minorLocator)\nminorLocator = MultipleLocator(.1)\nax1.yaxis.set_minor_locator(minorLocator)\n\nax1.tick_params(axis='both', which='major', labelsize=ticklabelsize, top=True, right=True, direction='in', length=majorticklength, width=tickwidth)\nax1.tick_params(axis='both', which='minor', top=True, right=True, direction='in', width=tickwidth)\nax1.set_xlabel(r\" r - i \", fontsize=labelsize)\nax1.set_ylabel(r\" z - y \", fontsize=labelsize)\n\n\n## 2.\n## (i - z) vs. (z - y)\n##\nxmin=-0.8; xmax=3.8\nymin=-0.6; ymax=1.6\nax2.axis([xmin, xmax, ymin, ymax])\n## Quasars\ncmap = plt.cm.autumn_r\nax2.scatter((i_PS1 - z_PS1), (z_PS1 - y_PS1), c=redshift, cmap=cmap, s=ms, alpha=1.0)\n## Spectral Type\ncmap = plt.cm.rainbow\nax2.scatter((imag - zmag), (zmag - ymag), c=(SpT_optn**5.), cmap=cmap, alpha=0.60, s=ms_small)\n\nmajor_ticks = np.arange(0, 4, 1)\nax2.set_xticks(major_ticks)\nminorLocator = MultipleLocator(.1)\nax2.xaxis.set_minor_locator(minorLocator)\nminorLocator = MultipleLocator(.1)\nax2.yaxis.set_minor_locator(minorLocator)\nax2.tick_params(axis='both', which='major', labelsize=ticklabelsize, top=True, right=True, direction='in', length=majorticklength, width=tickwidth)\nax2.tick_params(axis='both', which='minor', top=True, right=True, direction='in', width=tickwidth)\nax2.set_xlabel(r\" i - z \", fontsize=labelsize)\nax2.set_ylabel(r\" z - y \", fontsize=labelsize)\n\n\n## 3.\n## (i - z) vs. (z - J)\n##\nxmin=-0.8; xmax=3.8\nymin=-0.2; ymax=3.8\nax3.axis([xmin, xmax, ymin, ymax])\n## Quasars\ncmap = plt.cm.autumn_r\nax3.scatter((i_PS1 - z_PS1), (z_PS1 - Jmag), c=redshift, cmap=cmap, s=ms, alpha=1.0)\n## Spectral Type\ncmap = plt.cm.rainbow\nax3.scatter((imag - zmag), (zmag - J_tm), c=(SpT_optn**5.), cmap=cmap, alpha=0.60, s=ms_small)\n\nmajor_ticks = np.arange(0, 4, 1)\nax3.set_xticks(major_ticks)\nminorLocator = MultipleLocator(.1)\nax3.xaxis.set_minor_locator(minorLocator)\nminorLocator = MultipleLocator(.1)\nax3.yaxis.set_minor_locator(minorLocator)\nax3.tick_params(axis='both', which='major', labelsize=ticklabelsize, top=True, right=True, direction='in', length=majorticklength, width=tickwidth)\nax3.tick_params(axis='both', which='minor', top=True, right=True, direction='in', width=tickwidth)\nax3.set_xlabel(r\" i - z \", fontsize=labelsize)\nax3.set_ylabel(r\" z - J \", fontsize=labelsize)\n\n\n## 4.\n## (i - y) vs. (y - J)\n##\nxmin=-0.4; xmax=3.8\nymin=-0.4; ymax=2.8\nax4.axis([xmin, xmax, ymin, ymax])\n## Quasars\ncmap = plt.cm.autumn_r\nax4.scatter((i_PS1 - y_PS1), (y_PS1 - Jmag), c=redshift, cmap=cmap, s=ms, alpha=1.0)\n## Spectral Type\ncmap = plt.cm.rainbow\nax4.scatter((imag - ymag), (ymag - J_tm), c=(SpT_optn**5.), cmap=cmap, alpha=0.60, s=ms_small)\n\nmajor_ticks = np.arange(0, 4, 1)\nax4.set_xticks(major_ticks)\nminorLocator = MultipleLocator(.1)\nax4.xaxis.set_minor_locator(minorLocator)\nminorLocator = MultipleLocator(.1)\nax4.yaxis.set_minor_locator(minorLocator)\nax4.tick_params(axis='both', which='major', labelsize=ticklabelsize, top=True, right=True, direction='in', length=majorticklength, width=tickwidth)\nax4.tick_params(axis='both', which='minor', top=True, right=True, direction='in', width=tickwidth)\nax4.set_xlabel(r\" i - y \", fontsize=labelsize)\nax4.set_ylabel(r\" y - J \", fontsize=labelsize)\n\n\n## 5.\n## (i - J) vs. (J - K)\n##\nxmin=-0.2; xmax=7.8\nymin=-0.2; ymax=2.8\nax5.axis([xmin, xmax, ymin, ymax])\n## Quasars\ncmap = plt.cm.autumn_r\nax5.scatter((i_PS1 - Jmag), (Jmag - Kmag), c=redshift, cmap=cmap, s=ms, alpha=1.0)\n## Spectral Type\ncmap = plt.cm.rainbow\nax5.scatter((imag - J_tm), (J_tm - Ks_tm), c=(SpT_optn**5.), cmap=cmap, alpha=0.60, s=ms_small)\n\nminorLocator = MultipleLocator(.2)\nax5.xaxis.set_minor_locator(minorLocator)\nminorLocator = MultipleLocator(.1)\nax5.yaxis.set_minor_locator(minorLocator)\nax5.tick_params(axis='both', which='major', labelsize=ticklabelsize, top=True, right=True, direction='in', length=majorticklength, width=tickwidth)\nax5.tick_params(axis='both', which='minor', top=True, right=True, direction='in', width=tickwidth)\nax5.set_xlabel(r\" i - J \", fontsize=labelsize)\nax5.set_ylabel(r\" J - K \", fontsize=labelsize)\n\n\n## 6.\n## (z - y) vs. (y - J)\n##\nxmin=-0.8; xmax=2.2\nymin=-0.2; ymax=3.2\nax6.axis([xmin, xmax, ymin, ymax])\n## Quasars\ncmap = plt.cm.autumn_r\nax6.scatter((z_PS1 - y_PS1), (y_PS1 - Jmag), c=redshift, cmap=cmap, s=ms, alpha=1.0)\n## Spectral Type\ncmap = plt.cm.rainbow\nax6.scatter((zmag - ymag), (ymag - J_tm), c=(SpT_optn**5.), cmap=cmap, alpha=0.60, s=ms_small)\n\nminorLocator = MultipleLocator(.1)\nax6.xaxis.set_minor_locator(minorLocator)\nminorLocator = MultipleLocator(.1)\nax6.yaxis.set_minor_locator(minorLocator)\nax6.tick_params(axis='both', which='major', labelsize=ticklabelsize, top=True, right=True, direction='in', length=majorticklength, width=tickwidth)\nax6.tick_params(axis='both', which='minor', top=True, right=True, direction='in', width=tickwidth)\nax6.set_xlabel(r\" z - y \", fontsize=labelsize)\nax6.set_ylabel(r\" y - J \", fontsize=labelsize)\n\n\n\nplt.savefig('color_color_bluer_temp.png', format='png')\nplt.savefig('color_color_bluer_temp.pdf', format='pdf')\nplt.close(fig)\n\n#plt.show()\n\n","sub_path":"color_color/color_color_bluer.py","file_name":"color_color_bluer.py","file_ext":"py","file_size_in_byte":9309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"490139542","text":"'''\nscript copied from\nhttps://www.circuits.dk/temperature-logger-running-on-raspberry-pi/\n'''\n# -*- coding: utf-8 -*-\nimport os\nimport glob\nimport argparse\nimport time\nimport datetime\nimport sys\nfrom influxdb import InfluxDBClient\n\nos.system('modprobe w1-gpio')\nos.system('modprobe w1-therm')\n\n# add more sensor variables here based on your setup\n\ntemp=['sensor code','tttttttttt','ddddddddddd','ssssssssss']\nbase_dir = '/sys/bus/w1/devices/'\n\ndevice_folders = glob.glob(base_dir + '28*')\n\nsnum=4 #Number of connected temperature sensors\n\n# Sample period (s).\n# How frequently we will write sensor data from the temperature sensors to the database.\nsampling_period = 5\n\n# Set required InfluxDB parameters.\n# (this could be added to the program args instead of beeing hard coded...)\nhost = \"localhost\" #Could also use local ip address like \"192.168.1.136\"\nport = 8086\nuser = \"root\"\npassword = \"root\"\n \n\ndef read_temp_raw(device_file): \n f = open(device_file, 'r')\n lines = f.readlines()\n f.close()\n return lines\n \ndef read_temp(device_file): # checks the temp recieved for errors\n lines = read_temp_raw(device_file)\n while lines[0].strip()[-3:] != 'YES':\n time.sleep(0.2)\n lines = read_temp_raw(device_file)\n\n equals_pos = lines[1].find('t=')\n if equals_pos != -1:\n temp_string = lines[1][equals_pos+2:]\n # set proper decimal place for C\n temp = float(temp_string) / 1000.0\n # Round temp to 2 decimal points\n temp = round(temp, 1)\n # value of temp might be unknown here if equals_pos == -1\n return temp\n\ndef get_args():\n '''This function parses and returns arguments passed in'''\n # Assign description to the help doc\n parser = argparse.ArgumentParser(description='Program writes measurements data from the connected DS18B20 to specified influx db.')\n # Add arguments\n parser.add_argument(\n '-db','--database', type=str, help='Database name', required=True)\n parser.add_argument(\n '-sn','--session', type=str, help='Session', required=True)\n now = datetime.datetime.now()\n parser.add_argument(\n '-rn','--run', type=str, help='Run number', required=False,default=now.strftime(\"%Y%m%d%H%M\"))\n \n # Array of all arguments passed to script\n args=parser.parse_args()\n # Assign args to variables\n dbname=args.database\n runNo=args.run\n session=args.session\n return dbname, session,runNo\n \ndef get_data_points():\n # Get the three measurement values from the DS18B20 sensors\n for sensors in range (snum): # change number of sensors based on your setup\n device_file=device_folders[sensors]+ '/w1_slave'\n temp[sensors] = read_temp(device_file)\n print (device_file,sensors,temp[sensors])\n # Get a local timestamp\n timestamp=datetime.datetime.utcnow().isoformat()\n \n # Create Influxdb datapoints (using lineprotocol as of Influxdb >1.1)\n datapoints = [\n {\n \"measurement\": session,\n \"tags\": {\"runNum\": runNo,},\n \"time\": timestamp,\n \"fields\": {\"temperature 1\":temp[0],\"temperature 2\":temp[1],\"temperature 3\":temp[2],\"temperature 4\":temp[3]}\n }\n ]\n return datapoints\n\n# Match return values from get_arguments()\n# and assign to their respective variables\ndbname, session, runNo =get_args() \nprint (\"Session: \", session)\nprint (\"Run No: \", runNo)\nprint (\"DB name: \", dbname)\n\n# Initialize the Influxdb client\nclient = InfluxDBClient(host, port, user, password, dbname)\n \ntry:\n while True:\n # Write datapoints to InfluxDB\n datapoints=get_data_points()\n bResult=client.write_points(datapoints)\n print(\"Write points {0} Bresult:{1}\".format(datapoints,bResult))\n \n # Wait for next sample\n time.sleep(sampling_period)\n \n # Run until keyboard ctrl-c\nexcept KeyboardInterrupt:\n print (\"Program stopped by keyboard interrupt [CTRL_C] by user. \")\n","sub_path":"templogger.py","file_name":"templogger.py","file_ext":"py","file_size_in_byte":3963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"340470712","text":"import gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\n\nscope = ['http://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']\ncredentials = ServiceAccountCredentials.from_json_keyfile_name(\"DiceBag-e914cb26273e.json\", scope)\ngc = gspread.authorize(credentials)\nwks = gc.open('PyDiceList').sheet1\ndiceList = wks.get_all_values()\n\n#doe not work. Variable to wrong scope. need more coffee to fix.\ndef update_dice_list():\n diceList = wks.get_all_values() # Does not work Variable out of scope\n\n\ndef create_dice():\n dice_id = len(diceList)+1\n name = input(\"Name of dice: \")\n roll = input(\"times rolled: \")\n side = input(\"number of side: \")\n mod = input(\"value of modifiers: \")\n wks.append_row([dice_id, name, roll, side, mod])\n update_dice_list()\n\n\ndef update_dice(dice_id):\n current_dice = wks.findall(dice_id)\n current_dice[0].value = [\"new name\"]\n\n\ndef diceStripper():\n for dice in diceList:\n dice_id = dice[0]\n dice_name = dice[1]\n dice_rolls = dice[2]\n dice_sides = dice[3]\n dice_mod = dice[4]\n print(\"ID:{} {}: {}d{}+{}\".format(dice_id, dice_name, dice_rolls, dice_sides, dice_mod))\n\ndef roller(current_dice):\n roll_total = 0\n dice_name = current_dice[1]\n dice_rolls = int(current_dice[2])\n dice_sides = int(current_dice[3])\n dice_mod = int(current_dice[4])\n\n for rolls in range(dice_rolls):\n roll_total += dice_sides\n print(\"the total of your rolls is {}.\".format(roll_total))\n input(\"Press ENTER to return to main menu\")\n\n\ndef mainmenu():\n print(\"\\n\"*100)\n diceStripper()\n print(\" Q Quit\")\n print(\" E Edit existing dice\")\n print(\" A Add new dice\")\n user_selection = input(\"please enter id of dice you wish to roll: \").lower()\n menu_option = ''\n if user_selection == 'q':\n menu_option = 'q'\n elif user_selection == 'e':\n menu_option = 'e'\n elif user_selection == 'a':\n menu_option = 'a'\n else:\n roller(diceList[int(user_selection)-1])\n return menu_option\n\n\nwhile True:\n user_selection = mainmenu()\n\n if user_selection == 'q':\n print(\"Quit was selected\")\n break\n elif user_selection == 'a':\n create_dice()\n diceList = wks.get_all_values()\n else:\n print(\"back to the top\")\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"597473141","text":"import blynklib\nfrom adafruit_crickit import crickit\n\n#Obtained from the app or server admin page\nBLYNK_AUTH = 'authkeyhere'\n\n#initialize Blynk in this script. The port for a local instance is 8080\nblynk = blynklib.Blynk(BLYNK_AUTH, server='server_ip_address', port='8080')\n\n'''\nBlynk event handler breakdown:\n@blynk.handle_event('write V0')\n@blynk.handle_event = This section tells the script to wait for an action\n('write V0') = \"write\" in this case means writing \n\t\t\t\tto the pin(ie: turning the pin on)\n\t\t\t\t\"V0\" means virtual pin 0. \nYou can set the on and off values of the virtual pin in the app\n'''\n\n# The edit this section to change how the app works.\n# Define a function to happen here.\n# Give the function parameters of 'pin' and 'value'\n# Value returns a list so so use value[0] to get the base value\n# Be sure to use float if you're using half speed on dc motors\n@blynk.handle_event('write V0')\ndef when_button_is_pressed(pin, value):\n speed = float(value[0])\n motor1 = crickit.dc_motor_1 # This is how to call the dc motor object\n motor1.throttle = speed # This is one way of defining the speed\n\t\n# Run forever or until keyboard interrupt. \nwhile True:\n blynk.run()\n","sub_path":"examples/dc_blynk.py","file_name":"dc_blynk.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"263791111","text":"from .models import Thesis_Article\nfrom django.shortcuts import render, redirect, get_object_or_404\n\n\ndef thesis_portal(request):\n articles = Thesis_Article.objects.published()\n return render(request, 'thesis_portal.html', {'articles': articles})\n\ndef single_article(request, pk):\n article = get_object_or_404(Thesis_Article, pk=pk)\n if article.can_administer(request.user):\n admin = True\n else:\n admin = False\n if article.show_article_before_experation or admin:\n # attachments = article.otherattachment_set\n # image_attachments = article.imageattachment_set\n return render(request, 'model/thesis_article.html', {\n 'article': article,\n # 'attachments': attachments,\n # 'image_attachments': image_attachments,\n 'can_administer': admin})\n","sub_path":"wsgi/iportalen_django/thesis_portal/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"433379887","text":"import TFL_Man\nfrom Calculations import CurrContainer, PrevContainer\n\n#Read the Frames\nwith open('frames.pls') as f:\n read_data = f.readline()\n pkl_path = '0'\n frames = []\n for line in f:\n line = line.rstrip('\\n')\n if pkl_path == '0':\n pkl_path = line\n else:\n frames.append(line)\n#loop over each frame and send to TFL_MAN\nfor i in range(len(frames)):\n if i == 0:\n currframe = CurrContainer(frames[i])\n TFL_Man.work_on_frame(0,currframe,pkl_path)\n else:\n currframe = CurrContainer(frames[i])\n prevframe = PrevContainer(frames[i-1])\n TFL_Man.work_on_frame(prevframe, currframe,pkl_path)\n\n","sub_path":"Controller.py","file_name":"Controller.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"134907112","text":"import torch\nimport torch.nn.functional as F\n\nimport torch.nn.quantized as nnq\nimport torch.nn.quantized.dynamic as nnqd\nimport torch.nn.intrinsic.quantized as nniq\n\nfrom torch.quantization.fx import QuantType\n\n# test utils\nfrom torch.testing._internal.common_quantization import (\n QuantizationTestCase,\n skipIfNoFBGEMM,\n)\n\nimport itertools\nimport operator\n\nclass TestQuantizeFx(QuantizationTestCase):\n \"\"\" Unit tests for functionalities\n \"\"\"\n @skipIfNoFBGEMM\n def test_functional(self):\n \"\"\" Test quantizing functional conv and linear\n \"\"\"\n class Conv(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.stride = (1, 1)\n self.padding = (0, 0)\n self.dilation = (1, 1)\n self.groups = 1\n\n def forward(self, x, weight):\n return F.conv2d(x, weight, None, self.stride, self.padding, self.dilation, self.groups)\n\n conv_input = torch.rand(1, 3, 224, 224)\n conv_weight = torch.rand(3, 3, 3, 3)\n\n class Linear(torch.nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, x, weight):\n return F.linear(x, weight)\n\n linear_input = torch.rand(8, 5)\n linear_weight = torch.rand(10, 5)\n\n class LinearModule(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.linear = torch.nn.Linear(5, 10)\n\n def forward(self, x):\n return self.linear(x)\n\n linear_module_input = torch.rand(8, 5)\n\n tests = [\n (False, Conv, (conv_input, conv_weight), ('call_function', torch.ops.quantized.conv2d)),\n (True, Linear, (linear_input, linear_weight), ('call_function', torch.ops.quantized.linear_dynamic)),\n (False, Linear, (linear_input, linear_weight), ('call_function', torch.ops.quantized.linear)),\n (True, LinearModule, (linear_module_input,), ('call_module', torch.nn.quantized.dynamic.Linear)),\n (False, LinearModule, (linear_module_input,), ('call_module', torch.nn.quantized.Linear)),\n ]\n\n for is_dynamic, M, inputs, quantized_node in tests:\n quant_type = QuantType.DYNAMIC if is_dynamic else QuantType.STATIC\n self.checkGraphModeFxOp(M(), inputs, quantized_node, quant_type=quant_type)\n\nclass TestQuantizeFxOps(QuantizationTestCase):\n \"\"\"Unit tests for individual ops\n \"\"\"\n @skipIfNoFBGEMM\n def test_linear(self):\n class ModuleLinear(torch.nn.Module):\n def __init__(self, has_relu=False, f_relu=False):\n super(ModuleLinear, self).__init__()\n self.linear = torch.nn.Linear(30, 4).float()\n if has_relu:\n if f_relu:\n self.relu = F.relu\n else:\n self.relu = torch.nn.ReLU()\n else:\n self.relu = torch.nn.Identity()\n\n def forward(self, x):\n return self.relu(self.linear(x))\n\n class FuncLinear(torch.nn.Module):\n def __init__(self, has_relu=False, f_relu=False):\n super(FuncLinear, self).__init__()\n self.w = torch.randn(4, 30)\n self.b = torch.randn(4)\n if has_relu:\n if f_relu:\n self.relu = F.relu\n else:\n self.relu = torch.nn.ReLU()\n else:\n self.relu = torch.nn.Identity()\n\n def forward(self, x):\n return self.relu(F.linear(x, self.w, self.b))\n\n data = (torch.rand((1, 30), dtype=torch.float),)\n options = itertools.product(\n [(ModuleLinear(has_relu=False), True)],\n # TODO: enable after raw `tensor` is supported in fx\n # (FuncLinear(has_relu=False), False)],\n self.all_quant_types)\n quantized_nodes = {\n # is_module\n True: {\n # quant_type:\n QuantType.DYNAMIC: ('call_module', nnqd.Linear),\n QuantType.STATIC: ('call_module', nnq.Linear),\n # note that we are checking the final result\n QuantType.QAT: ('call_module', nnq.Linear),\n },\n False: {\n # quant_type:\n QuantType.DYNAMIC: ('call_function', torch.ops.quantized.linear_dynamic),\n QuantType.STATIC: ('call_function', torch.ops.quantized.linear),\n QuantType.QAT: ('call_function', torch.ops.quantized.linear),\n }\n }\n for (model, is_module), quant_type in options:\n self.checkGraphModeFxOp(model, data, quantized_nodes[is_module][quant_type], quant_type=quant_type)\n\n for f_relu, quant_type in itertools.product([True, False], [QuantType.STATIC, QuantType.QAT]):\n for model, quantized_node in [\n (ModuleLinear(has_relu=True, f_relu=f_relu), ('call_module', nniq.LinearReLU))]:\n # TODO: support functional linear + relu fusion\n # (FuncLinear(has_relu=True, f_relu=f_relu), ('call_function', torch.ops.quantized.linear_relu))]:\n self.checkGraphModeFxOp(model, data, quantized_node, quant_type=quant_type)\n\n @skipIfNoFBGEMM\n def test_quantized_conv(self):\n conv_module = {1 : torch.nn.Conv1d, 2 : torch.nn.Conv2d, 3 : torch.nn.Conv3d}\n\n class Conv(torch.nn.Module):\n def __init__(self, dim):\n super(Conv, self).__init__()\n self.conv = conv_module[dim](3, 3, 3).float()\n\n def forward(self, x):\n return self.conv(x)\n\n options = itertools.product([1, 2, 3], self.static_quant_types)\n quantized_nodes = {\n # dim\n 1: ('call_module', nnq.Conv1d),\n 2: ('call_module', nnq.Conv2d),\n 3: ('call_module', nnq.Conv3d),\n }\n for dim, quant_type in options:\n model = self.checkGraphModeFxOp(\n Conv(dim), self.img_data_dict[dim],\n quantized_nodes[dim], quant_type=quant_type)\n\n @skipIfNoFBGEMM\n def test_quantized_conv_relu(self):\n \"\"\"tests for conv1d_relu/conv2d_relu/conv3d_relu\"\"\"\n conv_module = {1 : torch.nn.Conv1d, 2 : torch.nn.Conv2d, 3 : torch.nn.Conv3d}\n\n class ConvNdRelu(torch.nn.Module):\n def __init__(self, dim, inplace):\n super(ConvNdRelu, self).__init__()\n self.conv = conv_module[dim](3, 3, 3).float()\n self.relu = torch.nn.ReLU(inplace)\n\n def forward(self, x):\n return self.relu(self.conv(x))\n\n class ConvNdFunctionalRelu(torch.nn.Module):\n def __init__(self, dim):\n super(ConvNdFunctionalRelu, self).__init__()\n self.conv = conv_module[dim](3, 3, 3).float()\n\n def forward(self, x):\n return F.relu(self.conv(x))\n\n class ConvNdInplaceFunctionalRelu(torch.nn.Module):\n def __init__(self, dim):\n super(ConvNdInplaceFunctionalRelu, self).__init__()\n self.conv = conv_module[dim](3, 3, 3).float()\n\n def forward(self, x):\n return F.relu(self.conv(x), True)\n\n options = itertools.product([1, 2, 3], self.static_quant_types)\n quantized_nodes = {\n # dim\n 1: ('call_module', nniq.ConvReLU1d),\n 2: ('call_module', nniq.ConvReLU2d),\n 3: ('call_module', nniq.ConvReLU3d),\n }\n for dim, quant_type in options:\n for orig_m in [ConvNdRelu(dim, True),\n ConvNdRelu(dim, False),\n ConvNdFunctionalRelu(dim),\n ConvNdInplaceFunctionalRelu(dim)]:\n conv_name = \"conv{}d\".format(dim)\n m = self.checkGraphModeFxOp(\n orig_m, self.img_data_dict[dim],\n quantized_nodes[dim], quant_type=quant_type)\n\n\n @skipIfNoFBGEMM\n def test_quantized_add(self):\n class QuantizedAdd(torch.nn.Module):\n def __init__(self):\n super(QuantizedAdd, self).__init__()\n self.conv1 = torch.nn.Conv2d(2, 2, 2).float()\n self.conv2 = torch.nn.Conv2d(2, 2, 2).float()\n\n def forward(self, x, y):\n x = self.conv1(x)\n y = self.conv2(y)\n return x + y\n\n class QuantizedInplaceAdd(torch.nn.Module):\n def __init__(self):\n super(QuantizedInplaceAdd, self).__init__()\n self.conv1 = torch.nn.Conv2d(2, 2, 2).float()\n self.conv2 = torch.nn.Conv2d(2, 2, 2).float()\n\n def forward(self, x, y):\n x = self.conv1(x)\n y = self.conv2(y)\n x += y\n return x\n\n # TODO: decide whether we want to quantize or not\n # in this case\n # class NonQuantizedAdd(torch.nn.Module):\n # def __init__(self):\n # super(NonQuantizedAdd, self).__init__()\n\n # def forward(self, x, y):\n # return x + y\n\n # class NonQuantizedInplaceAdd(torch.nn.Module):\n # def __init__(self):\n # super(NonQuantizedInplaceAdd, self).__init__()\n\n # def forward(self, x, y):\n # x += y\n # return x\n\n data = (torch.randn(1, 2, 3, 3, dtype=torch.float),\n torch.randn(1, 2, 3, 3, dtype=torch.float))\n quantized_node = ('call_function', torch.ops.quantized.add)\n non_quantized_node = ('call_function', operator.add)\n for m, quantized in [\n (QuantizedAdd(), True),\n (QuantizedInplaceAdd(), True),\n # (NonQuantizedAdd(), False),\n # (NonQuantizedInplaceAdd(), False)]:\n ]:\n for quant_type in self.static_quant_types:\n target_node = quantized_node if quantized else non_quantized_node\n self.checkGraphModeFxOp(m, data, target_node, quant_type=quant_type)\n\n @skipIfNoFBGEMM\n def test_quantized_add_scalar(self):\n class QuantizedAddScalar(torch.nn.Module):\n def __init__(self):\n super(QuantizedAddScalar, self).__init__()\n self.conv = torch.nn.Conv2d(2, 2, 2).float()\n\n def forward(self, x):\n x = self.conv(x)\n return x + 3\n\n class QuantizedInplaceAddScalar(torch.nn.Module):\n def __init__(self):\n super(QuantizedInplaceAddScalar, self).__init__()\n self.conv = torch.nn.Conv2d(2, 2, 2).float()\n\n def forward(self, x):\n x = self.conv(x)\n x += 3\n return x\n\n # TODO: decide whether we want to quantize or not\n # in this case\n # class NonQuantizedAddScalar(torch.nn.Module):\n # def __init__(self):\n # super(NonQuantizedAddScalar, self).__init__()\n\n # def forward(self, x):\n # return x + 3\n\n # class NonQuantizedInplaceAddScalar(torch.nn.Module):\n # def __init__(self):\n # super(NonQuantizedInplaceAddScalar, self).__init__()\n\n # def forward(self, x):\n # x += 3\n # return x\n\n data = (torch.randn(1, 2, 3, 3, dtype=torch.float),)\n quantized_node = ('call_function', torch.ops.quantized.add)\n non_quantized_node = ('call_function', operator.add)\n for m, quantized in [\n (QuantizedAddScalar(), True),\n (QuantizedInplaceAddScalar(), True),\n # (NonQuantizedAddScalar(), False),\n # (NonQuantizedInplaceAddScalar(), False)]:\n ]:\n for quant_type in self.static_quant_types:\n target_node = quantized_node if quantized else non_quantized_node\n self.checkGraphModeFxOp(m, data, target_node, quant_type=quant_type)\n\n @skipIfNoFBGEMM\n def test_quantized_add_relu(self):\n class AddRelu(torch.nn.Module):\n def __init__(self, inplace):\n super(AddRelu, self).__init__()\n self.conv1 = torch.nn.Conv2d(2, 2, 2).float()\n self.conv2 = torch.nn.Conv2d(2, 2, 2).float()\n self.relu = torch.nn.ReLU(inplace)\n\n def forward(self, x, y):\n x = self.conv1(x)\n y = self.conv2(y)\n x = x + y\n return self.relu(x)\n\n class InplaceAddRelu(torch.nn.Module):\n def __init__(self, inplace):\n super(InplaceAddRelu, self).__init__()\n self.conv1 = torch.nn.Conv2d(2, 2, 2).float()\n self.conv2 = torch.nn.Conv2d(2, 2, 2).float()\n self.relu = torch.nn.ReLU(inplace)\n\n def forward(self, x, y):\n x = self.conv1(x)\n y = self.conv2(y)\n x += y\n return self.relu(x)\n\n class AddFunctionalRelu(torch.nn.Module):\n def __init__(self):\n super(AddFunctionalRelu, self).__init__()\n self.conv1 = torch.nn.Conv2d(2, 2, 2).float()\n self.conv2 = torch.nn.Conv2d(2, 2, 2).float()\n\n def forward(self, x, y):\n x = self.conv1(x)\n y = self.conv2(y)\n x = x + y\n return F.relu(x)\n\n class InplaceAddFunctionalRelu(torch.nn.Module):\n def __init__(self):\n super(InplaceAddFunctionalRelu, self).__init__()\n self.conv1 = torch.nn.Conv2d(2, 2, 2).float()\n self.conv2 = torch.nn.Conv2d(2, 2, 2).float()\n\n def forward(self, x, y):\n x = self.conv1(x)\n y = self.conv2(y)\n x += y\n return F.relu(x)\n\n class AddInplaceFunctionalRelu(torch.nn.Module):\n def __init__(self):\n super(AddInplaceFunctionalRelu, self).__init__()\n self.conv1 = torch.nn.Conv2d(2, 2, 2).float()\n self.conv2 = torch.nn.Conv2d(2, 2, 2).float()\n\n def forward(self, x, y):\n x = self.conv1(x)\n y = self.conv2(y)\n x = x + y\n return F.relu(x, True)\n\n class InplaceAddInplaceFunctionalRelu(torch.nn.Module):\n def __init__(self):\n super(InplaceAddInplaceFunctionalRelu, self).__init__()\n self.conv1 = torch.nn.Conv2d(2, 2, 2).float()\n self.conv2 = torch.nn.Conv2d(2, 2, 2).float()\n\n def forward(self, x, y):\n x = self.conv1(x)\n y = self.conv2(y)\n x += y\n return F.relu(x, True)\n\n data = (torch.rand((1, 2, 5, 5), dtype=torch.float),\n torch.rand((1, 2, 5, 5), dtype=torch.float))\n quantized_node = ('call_function', torch.ops.quantized.add_relu)\n for m in [AddRelu(True), AddRelu(False),\n InplaceAddRelu(True), InplaceAddRelu(False),\n AddFunctionalRelu(), InplaceAddFunctionalRelu(),\n AddInplaceFunctionalRelu(), InplaceAddInplaceFunctionalRelu()]:\n for quant_type in self.static_quant_types:\n self.checkGraphModeFxOp(m, data, quantized_node, quant_type=quant_type)\n\n @skipIfNoFBGEMM\n def test_quantized_add_scalar_relu(self):\n class AddScalarRelu(torch.nn.Module):\n def __init__(self, inplace):\n super(AddScalarRelu, self).__init__()\n self.conv = torch.nn.Conv2d(2, 2, 2).float()\n self.relu = torch.nn.ReLU(inplace)\n\n def forward(self, x):\n x = self.conv(x)\n return self.relu(x + 3)\n\n class InplaceAddScalarRelu(torch.nn.Module):\n def __init__(self, inplace):\n super(InplaceAddScalarRelu, self).__init__()\n self.conv = torch.nn.Conv2d(2, 2, 2).float()\n self.relu = torch.nn.ReLU(inplace)\n\n def forward(self, x):\n x = self.conv(x)\n x += 3\n return self.relu(x)\n\n class AddScalarFunctionalRelu(torch.nn.Module):\n def __init__(self):\n super(AddScalarFunctionalRelu, self).__init__()\n self.conv = torch.nn.Conv2d(2, 2, 2).float()\n\n def forward(self, x):\n x = self.conv(x)\n return F.relu(x + 3)\n\n class InplaceAddScalarFunctionalRelu(torch.nn.Module):\n def __init__(self):\n super(InplaceAddScalarFunctionalRelu, self).__init__()\n self.conv = torch.nn.Conv2d(2, 2, 2).float()\n\n def forward(self, x):\n x = self.conv(x)\n x += 3\n return F.relu(x)\n\n class AddScalarInplaceFunctionalRelu(torch.nn.Module):\n def __init__(self):\n super(AddScalarInplaceFunctionalRelu, self).__init__()\n self.conv = torch.nn.Conv2d(2, 2, 2).float()\n\n def forward(self, x):\n x = self.conv(x)\n return F.relu(x + 3, True)\n\n class InplaceAddScalarInplaceFunctionalRelu(torch.nn.Module):\n def __init__(self):\n super(InplaceAddScalarInplaceFunctionalRelu, self).__init__()\n self.conv = torch.nn.Conv2d(2, 2, 2).float()\n\n def forward(self, x):\n x = self.conv(x)\n x += 3\n return F.relu(x, True)\n\n data = (torch.rand((1, 2, 5, 5), dtype=torch.float),)\n quantized_node = ('call_function', torch.ops.quantized.add_relu)\n for m in [AddScalarRelu(True), AddScalarRelu(False),\n InplaceAddScalarRelu(True), InplaceAddScalarRelu(False),\n AddScalarFunctionalRelu(),\n InplaceAddScalarFunctionalRelu(),\n AddScalarInplaceFunctionalRelu(),\n InplaceAddScalarInplaceFunctionalRelu()]:\n for quant_type in self.static_quant_types:\n self.checkGraphModeFxOp(m, data, quantized_node, quant_type=quant_type)\n\n\n @skipIfNoFBGEMM\n def test_quantized_cat(self):\n \"\"\" quantization of the output of cat will be depend on the\n input of cat. we only quantize the output of cat when its inputs are quantized.\n \"\"\"\n class QuantizedCat(torch.nn.Module):\n def __init__(self):\n super(QuantizedCat, self).__init__()\n self.conv1 = torch.nn.Conv2d(2, 2, 2).float()\n self.conv2 = torch.nn.Conv2d(2, 2, 2).float()\n\n def forward(self, x, y):\n x = self.conv1(x)\n y = self.conv2(y)\n return torch.cat([x, y], 1)\n\n # TODO: decide whether to quantize in this case\n # class NonQuantizedCat(torch.nn.Module):\n # def __init__(self):\n # super(NonQuantizedCat, self).__init__()\n\n # def forward(self, x, y):\n # return torch.cat([x, y], 1)\n\n data = (torch.randn(1, 2, 5, 5, dtype=torch.float),\n torch.randn(1, 2, 5, 5, dtype=torch.float))\n quantized_node = ('call_function', torch.ops.quantized.cat)\n for quant_type in self.static_quant_types:\n self.checkGraphModeFxOp(QuantizedCat(), data, quantized_node, quant_type=quant_type)\n","sub_path":"test/quantization/test_quantize_fx.py","file_name":"test_quantize_fx.py","file_ext":"py","file_size_in_byte":19648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"396748598","text":"#!/usr/bin/env python3\n\nfrom argparse import ArgumentParser\nimport xml.etree.ElementTree as ET\nimport csv\nimport sys\nimport os\nimport re\n\ng_xml_tree = None\ng_divisions = {}\nselected = set()\n\nTRACK_SINGLE_QUERY = 'track_single_query'\nTRACK_INCREMENTAL = 'track_incremental'\nTRACK_SINGLE_QUERY_CHALLENGE = 'track_single_query_challenge'\nTRACK_INCREMENTAL_CHALLENGE = 'track_incremental_challenge'\nTRACK_UNSAT_CORE = 'track_unsat_core'\nTRACK_MODEL_VALIDATION = 'track_model_validation'\n\n# Solver ID columns\nCOL_SOLVER_ID_PRELIM = 'Preliminary Solver ID'\nCOL_SOLVER_ID = 'Solver ID'\nCOL_SOLVER_ID_WRAPPED_SQ = 'Wrapped Solver ID Single Query'\nCOL_SOLVER_ID_WRAPPED_INC = 'Wrapped Solver ID Incremental'\nCOL_SOLVER_ID_WRAPPED_MV = 'Wrapped Solver ID Model Validation'\nCOL_SOLVER_ID_WRAPPED_UC = 'Wrapped Solver ID Unsat Core'\n# Track Columns\nCOL_SINGLE_QUERY_TRACK = 'Single Query Track'\nCOL_INCREMENTAL_TRACK = 'Incremental Track'\nCOL_CHALLENGE_TRACK_SINGLE_QUERY = 'Challenge Track (single query)'\nCOL_CHALLENGE_TRACK_INCREMENTAL = 'Challenge Track (incremental)'\nCOL_MODEL_VALIDATION_TRACK = 'Model Validation Track'\nCOL_UNSAT_CORE_TRACK = 'Unsat Core Track'\n\n# Print error message and exit.\ndef die(msg):\n print(\"error: {}\".format(msg))\n sys.exit(1)\n\n# Read csv with solver data of the form:\n# solver_id | solver_name | single_query_track | ... other tracks\n# .... | .... | entered divisions | ...\n# Order of tracks: single query, incremental, challenge, model val, unsat core\n# Columns are separated by ',' and divisions are separated by ';'.\n# If 'use_wrapped' is true, use wrapped solver IDs instead.\ndef read_csv(fname, track, use_wrapped):\n global g_divisions\n col_solver_id = COL_SOLVER_ID\n if use_wrapped:\n if track == TRACK_SINGLE_QUERY:\n col_solver_id = COL_SOLVER_ID_WRAPPED_SQ\n elif track == TRACK_INCREMENTAL:\n col_solver_id = COL_SOLVER_ID_WRAPPED_INC\n elif track == TRACK_SINGLE_QUERY_CHALLENGE:\n col_solver_id = COL_SOLVER_ID_WRAPPED_SQ\n elif track == TRACK_INCREMENTAL_CHALLENGE:\n col_solver_id = COL_SOLVER_ID_WRAPPED_INC\n elif track == TRACK_MODEL_VALIDATION:\n col_solver_id = COL_SOLVER_ID_WRAPPED_MV\n elif track == TRACK_UNSAT_CORE:\n col_solver_id = COL_SOLVER_ID_WRAPPED_UC\n with open(args.csv) as file:\n reader = csv.reader(file, delimiter=',')\n header = next(reader)\n for row in reader:\n drow = dict(zip(iter(header), iter(row)))\n solver_id = drow[col_solver_id]\n if not solver_id: continue\n divisions = None\n if track == TRACK_SINGLE_QUERY:\n divisions = drow[COL_SINGLE_QUERY_TRACK].split(';')\n elif track == TRACK_INCREMENTAL:\n divisions = drow[COL_INCREMENTAL_TRACK].split(';')\n elif track == TRACK_SINGLE_QUERY_CHALLENGE:\n divisions = drow[COL_CHALLENGE_TRACK_SINGLE_QUERY].split(';')\n elif track == TRACK_INCREMENTAL_CHALLENGE:\n divisions = drow[COL_CHALLENGE_TRACK_INCREMENTAL].split(';')\n elif track == TRACK_MODEL_VALIDATION:\n divisions = drow[COL_MODEL_VALIDATION_TRACK].split(';')\n elif track == TRACK_UNSAT_CORE:\n divisions = drow[COL_UNSAT_CORE_TRACK].split(';')\n assert (divisions)\n\n for division in divisions:\n if division == \"\":\n continue\n if division not in g_divisions:\n g_divisions[division] = []\n g_divisions[division].append(\n [drow[col_solver_id], drow['Solver Name']])\n\ndef read_selected(fname):\n global selected\n with open(fname) as file:\n for line in file:\n line = line.strip()\n if line:\n selected.add(line)\n\n\ndef is_model_validation_benchmark(benchmark):\n isSat = False\n isQF_BV = False\n for child in benchmark:\n if child.attrib['name'] == 'status' and child.attrib['value'] == \"sat\":\n isSat = True\n if child.attrib['name'] == 'set-logic' and child.attrib['value'] == \"QF_BV\":\n isQF_BV = True\n return isSat and isQF_BV\n\ndef filter_model_validation_benchmarks(space, select_benchmarks):\n spaces = space.findall('Space')\n for s in spaces: filter_model_validation_benchmarks(s, select_benchmarks)\n benchmarks = space.findall('Benchmark')\n for b in benchmarks:\n if (not is_model_validation_benchmark(b)):\n space.remove(b)\n\ndef space_is_empty(space):\n spaces = space.findall('Space')\n benchmarks = space.findall('Benchmark')\n return not spaces and not benchmarks\n\ndef space_has_no_solvers(space):\n solvers = space.findall('Solver')\n return not solvers\n\ndef remove_empty_spaces(space):\n spaces = space.findall('Space')\n for s in spaces:\n remove_empty_spaces(s)\n if space_is_empty(s):\n space.remove(s)\n\ndef remove_spaces_without_solvers(space):\n spaces = space.findall('Space')\n for s in spaces:\n remove_spaces_without_solvers(s)\n if space_has_no_solvers(s):\n space.remove(s)\n\ndef is_unsat_core_benchmark(benchmark):\n isUnsat = False\n hasNumAsrtsTag = False\n hasMoreThanOneAsrt = False\n\n for child in benchmark:\n if child.attrib['name'] == 'status' and child.attrib['value'] == \"unsat\":\n isUnsat = True\n if child.attrib['name'] == 'num_asrts':\n hasNumAsrtsTag = True\n if int(child.attrib['value']) > 1:\n hasMoreThanOneAsrt = True\n return isUnsat and (not hasNumAsrtsTag or hasMoreThanOneAsrt)\n\ndef filter_unsat_core_benchmarks(space, select_benchmarks):\n spaces = space.findall('Space')\n for s in spaces: filter_unsat_core_benchmarks(s, select_benchmarks)\n benchmarks = space.findall('Benchmark')\n for b in benchmarks:\n if (not is_unsat_core_benchmark(b)):\n space.remove(b)\n\n# Traverse space and remove all but one benchmark for each (sub)space with\n# benchmarks (for test runs on StarExec).\ndef filter_benchmarks_in_space(space, n, select_benchmarks,path):\n path = path+\"/\"+space.attrib['name']\n spaces = space.findall('Space')\n for s in spaces: filter_benchmarks_in_space(s, n, select_benchmarks,path)\n benchmarks = space.findall('Benchmark')\n if select_benchmarks:\n for b in benchmarks:\n bname = path +\"/\"+b.attrib['name']\n if bname not in selected:\n space.remove(b)\n else:\n selected.remove(bname)\n if n>0:\n for b in benchmarks[n:]: space.remove(b)\n\n# Traverse space and add solvers to divisions and their subspaces.\ndef add_solvers_in_space(space, solvers):\n spaces = space.findall('Space')\n for s in spaces: add_solvers_in_space(s, solvers)\n for solver in solvers:\n ET.SubElement(\n space,\n 'Solver',\n attrib = {'id': solver[0], 'name': solver[1]})\n\n# Parse xml and add solvers to divisions.\n# If 'filter_benchmarks' is true, remove all but one benchmark for each\n# (sub)space with benchmarks (for test runs on StarExec).\ndef add_solvers(track, filter_benchmarks, select_benchmarks):\n global g_xml_tree\n root = g_xml_tree.getroot()\n incremental_space = root.find('.//Space[@name=\"incremental\"]')\n non_incremental_space = root.find('.//Space[@name=\"non-incremental\"]')\n for space in [incremental_space, non_incremental_space]:\n if space:\n n = 1 # number of benchmarks to keep in each family\n if track == TRACK_MODEL_VALIDATION:\n filter_model_validation_benchmarks(space, select_benchmarks)\n n = 3\n elif track == TRACK_UNSAT_CORE:\n filter_unsat_core_benchmarks(space, select_benchmarks)\n # filter benchmarks\n if filter_benchmarks:\n filter_benchmarks_in_space(space, n, select_benchmarks,\"\")\n elif select_benchmarks:\n filter_benchmarks_in_space(space, 0, select_benchmarks,\"\")\n # remove spaces without benchmarks\n remove_empty_spaces(space)\n # add solvers\n subspaces = space.findall('Space')\n for subspace in subspaces:\n division = subspace.attrib['name']\n if division in g_divisions:\n solvers = g_divisions[division]\n # Only add solvers if the division is competitive\n # TODO make this check aware of non-competitive solvers and solver variants\n if len(solvers) > 1:\n add_solvers_in_space(subspace, solvers)\n # remove spaces without solvers\n remove_spaces_without_solvers(space)\n # remove top-level non-incremental/incremental space tag\n subspaces = space.findall('Space')\n root.extend(subspaces)\n root.remove(space)\n\n\nif __name__ == '__main__':\n parser = ArgumentParser(\n usage=\"prepare_space_xml \"\\\n \"-t \"\\\n \" \\n\\n\"\n \"Add solvers from csv to space with divisions \"\\\n \"(and benchmarks)\\nto upload as space xml to StarExec.\")\n parser.add_argument (\"space_xml\",\n help=\"the input space xml from the SMT-LIB space on StarExec \"\\\n \"(with divisions and benchmarks), top-level space: \"\\\n \"non-incremental or incremental\")\n parser.add_argument (\"csv\",\n help=\"the input csv with solvers and divisions as generated from\"\\\n \"tools/prep/extract_data_from_submission.py\")\n parser.add_argument (\"out_xml\",\n help=\"the output space xml (with solvers added to divisions)\")\n parser.add_argument('-t',\n type=str, dest=\"track\",\n help=\"SMT-COMP track name (one out of:\"\\\n \"'single_query', 'incremental', 'single_query_challenge',\"\\\n \"'incremental_challenge', 'model_validation', 'unsat_core'\",\n required = True)\n parser.add_argument (\"-f\",\n action=\"store_true\", dest=\"filter\", default=False,\n help=\"filter space to only keep one (the first) benchmark \" \\\n \"in each space with benchmarks (for test runs)\")\n parser.add_argument(\"-s\",\"--select\",\n action=\"store\",dest=\"select\",default=\"none\",\n help=\"A list of benchmarks to select\", required=False)\n parser.add_argument (\"-w\",\n action=\"store_true\", dest=\"wrapped\", default=False,\n help=\"use wrapped solver IDs\")\n args = parser.parse_args()\n\n if not os.path.exists(args.space_xml):\n die(\"file not found: {}\".format(args.space_xml))\n if not os.path.exists(args.csv):\n die(\"file not found: {}\".format(args.csv))\n\n if args.track not in ['single_query', 'incremental', 'single_query_challenge',\n 'incremental_challenge', 'model_validation', 'unsat_core']:\n die(\"invalid track name\")\n args.track = \"track_{}\".format(args.track)\n\n if args.select != \"none\":\n read_selected(args.select)\n print(\"selected \"+str(len(selected)))\n\n g_xml_tree = ET.parse(args.space_xml)\n read_csv(args.csv, args.track, args.wrapped)\n add_solvers(args.track, args.filter,args.select!=\"none\")\n g_xml_tree.write(args.out_xml)\n\n if args.select != \"none\":\n print(\"there are \"+str(len(selected))+\" benchmarks unselected\")\n for s in selected:\n print(s)\n","sub_path":"tools/prep/prepare_space_xml.py","file_name":"prepare_space_xml.py","file_ext":"py","file_size_in_byte":11610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"428747911","text":"from sqlalchemy import (\n and_,\n func,\n select,\n exists,\n join,\n cast,\n not_,\n or_,\n DATE,\n outerjoin)\nfrom sqlalchemy.orm import aliased\nfrom sqlalchemy.sql.expression import union_all\n\nfrom ecoreleve_server.core import Base\nfrom ecoreleve_server.core.base_collection import Query_engine, eval_\nfrom . import Station, Station_FieldWorker\nfrom ..observations import Observation\nfrom ..individuals import Individual\nfrom ..users import User\n\n\n@Query_engine(Station)\nclass StationCollection:\n pass\n\n\n@Query_engine.add_filter(StationCollection, 'FK_Individual')\ndef individual_filter(self, query, criteria):\n curProp = 'FK_Individual'\n if criteria['Operator'].lower() in ['is null', 'is not null']:\n subSelect = select([Observation]).where(\n and_(Station.ID == Observation.FK_Station,\n Observation.__table__.c[curProp] != None)\n )\n if criteria['Operator'].lower() == 'is not null':\n query = query.where(~exists(subSelect))\n else:\n query = query.where(exists(subSelect))\n else:\n subSelect = select([Observation]\n ).where(\n and_(Station.ID == Observation.FK_Station,\n eval_.eval_binary_expr(Observation.__table__.c[curProp],\n criteria['Operator'],\n criteria['Value'])))\n query = query.where(exists(subSelect))\n return query\n\n@Query_engine.add_filter(StationCollection, 'FK_FieldWorker')\ndef fieldworker_filter(self, query, criteria):\n joinTable = join(Station_FieldWorker, User, Station_FieldWorker.FK_FieldWorker == User.id)\n subSelect = select([Station_FieldWorker]\n ).select_from(joinTable).where(\n and_(Station.ID == Station_FieldWorker.FK_Station,\n eval_.eval_binary_expr(User.__table__.c['Login'],\n criteria['Operator'],\n criteria['Value'])))\n query = query.where(exists(subSelect))\n return query\n\n@Query_engine.add_filter(StationCollection, 'FK_ProtocoleType')\ndef protocoleType_filter(self, query, criteria):\n o = aliased(Observation)\n subSelect = select([o.ID]\n ).where(\n and_(Station.ID == o.FK_Station,\n eval_.eval_binary_expr(o._type_id, criteria['Operator'],\n criteria['Value'])))\n query = query.where(exists(subSelect))\n return query\n\n@Query_engine.add_filter(StationCollection, 'LastImported')\ndef last_imported_filter(self, query, criteria):\n st = aliased(Station)\n subSelect2 = select([st]).where(\n cast(st.creationDate, DATE) > cast(Station.creationDate, DATE))\n query = query.where(~exists(subSelect2))\n\n return query\n\n@Query_engine.add_filter(StationCollection, 'Species')\ndef species_filter(self, query, criteria):\n obsValTable = Base.metadata.tables['ObservationDynPropValuesNow']\n o2 = aliased(Observation)\n s2 = aliased(Station)\n\n joinStaObs = join(s2, o2, s2.ID == o2.FK_Station)\n\n operator = criteria['Operator']\n if 'not' in criteria['Operator']:\n operator = operator.replace('not ', '').replace(' not', '')\n\n existInd = select([Individual.ID]\n ).where(and_(o2.FK_Individual == Individual.ID,\n eval_.eval_binary_expr(Individual.Species, operator, criteria['Value']))\n )\n\n existObs = select([obsValTable.c['ID']]\n ).where(and_(obsValTable.c['FK_Observation'] == o2.ID,\n and_(or_(obsValTable.c['Name'].like('%taxon'), obsValTable.c['Name'].like('%species%')),\n eval_.eval_binary_expr(obsValTable.c['ValueString'], operator, criteria['Value']))\n )\n )\n\n selectCommon = select([s2.ID]).select_from(joinStaObs)\n\n selectInd = selectCommon.where(exists(existInd))\n selectObs = selectCommon.where(exists(existObs))\n\n unionQuery = union_all(selectInd, selectObs)\n if 'not' in criteria['Operator']:\n query = query.where(~Station.ID.in_(unionQuery))\n else:\n query = query.where(Station.ID.in_(unionQuery))\n return query","sub_path":"Back/ecoreleve_server/modules/stations/station_collection.py","file_name":"station_collection.py","file_ext":"py","file_size_in_byte":4359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"497311712","text":"from manimlib.imports import *\nfrom src.functions import make_screen_frame\n\n\nclass Intro(Scene):\n def construct(self):\n infty = TextMobject('$\\\\infty$').scale(7)\n q = TextMobject('?').scale(7)\n self.play(FadeIn(infty))\n self.wait(6)\n self.play(ReplacementTransform(infty, q), run_time=1.5)\n self.wait(5.5)\n","sub_path":"arithmetic_basics/natural_sum/src/Intro.py","file_name":"Intro.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"261899327","text":"import factory\n\nfrom copy import deepcopy\nfrom dateutil.parser import parse\nfrom django.contrib.auth.models import User\nfrom django.test import Client\nfrom django.test import override_settings\nfrom orchestra.models import Task\nfrom orchestra.models import TaskAssignment\nfrom orchestra.models import WorkerCertification\nfrom orchestra.slack import create_project_slack_group\nfrom orchestra.utils.task_properties import assignment_history\n\n\nclass UserFactory(factory.django.DjangoModelFactory):\n\n class Meta:\n model = User\n\n password = factory.PostGenerationMethodCall('set_password',\n 'defaultpassword')\n\n\nclass WorkerFactory(factory.django.DjangoModelFactory):\n\n class Meta:\n model = 'orchestra.Worker'\n\n\nclass CertificationFactory(factory.django.DjangoModelFactory):\n\n class Meta:\n model = 'orchestra.Certification'\n\n\nclass WorkerCertificationFactory(factory.django.DjangoModelFactory):\n\n class Meta:\n model = 'orchestra.WorkerCertification'\n\n task_class = WorkerCertification.TaskClass.REAL\n\n\nclass ProjectFactory(factory.django.DjangoModelFactory):\n\n class Meta:\n model = 'orchestra.Project'\n\n short_description = factory.Sequence(\n lambda n: 'Project {}'.format(n))\n priority = 0\n task_class = WorkerCertification.TaskClass.REAL\n\n\nclass TaskFactory(factory.django.DjangoModelFactory):\n\n class Meta:\n model = 'orchestra.Task'\n\n step_slug = 'step1'\n\n\nclass TaskAssignmentFactory(factory.django.DjangoModelFactory):\n\n class Meta:\n model = 'orchestra.TaskAssignment'\n\n status = TaskAssignment.Status.PROCESSING\n snapshots = {}\n\n\n@override_settings(SLACK_EXPERTS=True)\ndef setup_models(test_case):\n \"\"\" Set up models that we'll use in multiple tests \"\"\"\n # Certification generation data\n certifications = [\n {\n 'slug': 'certification1',\n 'name': 'The first certification',\n 'required_certifications': []\n },\n {\n 'slug': 'certification2',\n 'name': 'The second certification',\n 'required_certifications': ['certification1']\n }\n ]\n\n # Worker generation data\n workers = {\n 0: [\n ('certification1', WorkerCertification.Role.ENTRY_LEVEL)\n ],\n 1: [\n ('certification1', WorkerCertification.Role.ENTRY_LEVEL),\n ('certification1', WorkerCertification.Role.REVIEWER)\n ],\n 2: [],\n 3: [\n ('certification1', WorkerCertification.Role.ENTRY_LEVEL),\n ('certification1', WorkerCertification.Role.REVIEWER)\n ],\n 4: [\n ('certification1', WorkerCertification.Role.ENTRY_LEVEL),\n ('certification2', WorkerCertification.Role.ENTRY_LEVEL)\n ],\n 5: [\n ('certification1', WorkerCertification.Role.ENTRY_LEVEL),\n ('certification2', WorkerCertification.Role.ENTRY_LEVEL),\n ('certification2', WorkerCertification.Role.REVIEWER)\n ],\n 6: [\n ('certification1', WorkerCertification.Role.ENTRY_LEVEL),\n ('certification1', WorkerCertification.Role.REVIEWER),\n ('certification2', WorkerCertification.Role.ENTRY_LEVEL),\n ('certification2', WorkerCertification.Role.REVIEWER)\n ],\n 7: [\n ('certification1', WorkerCertification.Role.ENTRY_LEVEL),\n ('certification1', WorkerCertification.Role.REVIEWER)\n ],\n 8: [\n ('certification1', WorkerCertification.Role.ENTRY_LEVEL),\n ('certification1', WorkerCertification.Role.REVIEWER)\n ]\n }\n\n # Project generation data\n projects = {\n 'empty_project': 'test_workflow',\n 'base_test_project': 'test_workflow',\n 'test_human_and_machine': 'test_workflow_2',\n 'no_task_assignments': 'test_workflow',\n 'reject_entry_proj': 'test_workflow',\n 'reject_rev_proj': 'test_workflow',\n 'aborted_project': 'test_workflow',\n 'project_to_end': 'test_workflow',\n 'assignment_policy': 'assignment_policy_workflow',\n }\n\n # Task generation data\n test_case.test_step_slug = 'step1'\n test_data = {'test_key': 'test_value'}\n tasks = {\n 'review_task': {\n 'project_name': 'base_test_project',\n 'status': Task.Status.PENDING_REVIEW,\n 'assignments': [\n (0, test_data, TaskAssignment.Status.SUBMITTED)\n ],\n },\n 'processing_task': {\n 'project_name': 'no_task_assignments',\n 'status': Task.Status.AWAITING_PROCESSING,\n 'assignments': []\n },\n 'rejected_entry': {\n 'project_name': 'reject_entry_proj',\n 'status': Task.Status.POST_REVIEW_PROCESSING,\n 'assignments': [\n (4, test_data, TaskAssignment.Status.PROCESSING),\n (6, {}, TaskAssignment.Status.SUBMITTED)\n ]\n },\n 'rejected_review': {\n 'project_name': 'reject_rev_proj',\n 'status': Task.Status.POST_REVIEW_PROCESSING,\n 'assignments': [\n (5, {}, TaskAssignment.Status.SUBMITTED),\n (6, test_data, TaskAssignment.Status.PROCESSING),\n (7, {}, TaskAssignment.Status.SUBMITTED)\n ]\n },\n 'aborted': {\n 'project_name': 'aborted_project',\n 'status': Task.Status.ABORTED,\n 'assignments': [\n (4, test_data, TaskAssignment.Status.PROCESSING)\n ]\n },\n 'to_be_ended_1': {\n 'project_name': 'project_to_end',\n 'status': Task.Status.POST_REVIEW_PROCESSING,\n 'assignments': [\n (5, {}, TaskAssignment.Status.SUBMITTED),\n (6, test_data, TaskAssignment.Status.PROCESSING),\n (7, {}, TaskAssignment.Status.SUBMITTED)\n ]\n },\n 'to_be_ended_2': {\n 'project_name': 'project_to_end',\n 'status': Task.Status.PROCESSING,\n 'assignments': [\n (4, test_data, TaskAssignment.Status.SUBMITTED)\n ]\n },\n }\n\n # Create certifications and dependencies\n test_case.certifications = {}\n for details in certifications:\n new_slug = details['slug']\n test_case.certifications[new_slug] = CertificationFactory(\n slug=new_slug, name=details['name'])\n for required_slug in details['required_certifications']:\n test_case.certifications[new_slug].required_certifications.add(\n test_case.certifications[required_slug])\n\n # Create and certify workers\n test_case.workers = {}\n test_case.clients = {}\n for user_id, certifications in workers.items():\n # Create user, worker, client\n user = (UserFactory(username='test_user_{}'.format(user_id),\n first_name='test_first_{}'.format(user_id),\n last_name='test_last_{}'.format(user_id),\n password='test_{}'.format(user_id),\n email='test_user_{}@test.com'.format(user_id)))\n test_case.workers[user_id] = WorkerFactory(user=user)\n test_case.clients[user_id] = Client()\n test_case.clients[user_id].login(\n username='test_user_{}'.format(user_id),\n password='test_{}'.format(user_id))\n\n # Assign certifications\n for slug, role in certifications:\n WorkerCertificationFactory(\n certification=test_case.certifications[slug],\n worker=test_case.workers[user_id],\n role=role)\n\n # Create projects\n test_case.projects = {}\n for name, workflow_slug in projects.items():\n test_case.projects[name] = ProjectFactory(\n workflow_slug=workflow_slug,\n start_datetime=parse('2015-10-12T00:00:00+00:00'))\n create_project_slack_group(test_case.projects[name])\n\n # Create and assign taks\n test_case.tasks = {}\n for task_slug, details in tasks.items():\n task = TaskFactory(project=test_case.projects[details['project_name']],\n step_slug=test_case.test_step_slug,\n status=details['status'],\n start_datetime=parse('2015-10-12T01:00:00+00:00'))\n test_case.tasks[task_slug] = task\n for i, (user_id,\n task_data,\n assignment_status) in enumerate(details['assignments']):\n TaskAssignmentFactory(\n worker=test_case.workers[user_id],\n task=task,\n status=assignment_status,\n assignment_counter=i,\n in_progress_task_data=task_data,\n start_datetime=parse(\n '2015-10-12T0{}:00:00+00:00'.format(2 + i)))\n\n\ndef setup_task_history(test):\n task = test.tasks['rejected_review']\n\n test._submit_assignment(\n test.clients[6], task.id, seconds=35)\n test._submit_assignment(\n test.clients[7], task.id, command='reject', seconds=36)\n test._submit_assignment(\n test.clients[6], task.id, seconds=37)\n test._submit_assignment(\n test.clients[7], task.id, command='accept', seconds=38)\n\n # Fill out the snapshots for all assignments\n assignments = assignment_history(task)\n first_assignment = assignments[0]\n second_assignment = assignments[1]\n third_assignment = assignments[2]\n\n first_assignment.snapshots['snapshots'] = deepcopy(\n second_assignment.snapshots['snapshots'])\n second_assignment.snapshots['snapshots'] = (\n deepcopy(third_assignment.snapshots['snapshots']) +\n second_assignment.snapshots['snapshots'])[:-1]\n\n def fix_datetimes(snapshots, new_datetimes):\n for snapshot, new_datetime in zip(snapshots, new_datetimes):\n snapshot['datetime'] = new_datetime\n\n # Explicitly set the iteration datetimes. If we didn't, the timestamps\n # would be `datetime.now`, which we can't test against. The explicitly set\n # times are predictable distance apart, so we can test the\n # resulting latency reports.\n fix_datetimes(\n first_assignment.snapshots['snapshots'],\n ['2015-10-12T02:02:00+00:00', '2015-10-12T03:05:00+00:00'])\n fix_datetimes(\n second_assignment.snapshots['snapshots'],\n ['2015-10-12T03:01:00+00:00', '2015-10-12T03:07:00+00:00',\n '2015-10-12T04:03:00+00:00', '2015-10-12T04:10:00+00:00'])\n fix_datetimes(\n third_assignment.snapshots['snapshots'],\n ['2015-10-12T04:02:00+00:00', '2015-10-12T04:13:00+00:00'])\n\n first_assignment.save()\n second_assignment.save()\n third_assignment.save()\n\n return task\n","sub_path":"orchestra/tests/helpers/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":10802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"312744278","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport json\nimport re\nfrom scrapy.http import Request\nfrom urllib import parse as urlparse\nfrom StockInfoCrawler.items import BasicIndexesPowerItem\n\n\nclass BasicIndexesPowerSpider(scrapy.Spider):\n name = 'basic-indexes-power-spider'\n start_urls = ['http://www.cophieu68.vn/investment_basic_indexes.php']\n custom_settings = {\n 'FEED_FORMAT': 'csv',\n 'FEED_URI': 'data/stats/basic-indexes-power.csv',\n }\n\n def parse(self, response):\n last_page_xpath = \"//ul[@id='navigator']/li[7]/a/@href\"\n total_page = int(json.loads(json.dumps(urlparse.parse_qs(\n response.selector.xpath(last_page_xpath).extract_first())))['?currentPage'][0]) + 1\n for i in range(1, total_page, 1):\n page_link = 'http://www.cophieu68.vn/investment_basic_indexes.php?currentPage=' + str(i)\n yield Request(url=page_link, callback=self.parse_page)\n\n @staticmethod\n def parse_page(response):\n stock_table_xpath = \"//tbody[@id='fred']/tr\"\n stock_list = response.selector.xpath(stock_table_xpath)\n stock_list.pop(0)\n for stock in stock_list:\n index_powers = BasicIndexesPowerItem()\n index_powers[\"stock_id\"] = extract_str(stock.xpath(\"./td[2]//strong/text()\").extract_first())\n index_powers[\"eps\"] = extract_str(stock.xpath(\"./td[3]/text()\").extract_first())\n index_powers[\"pe\"] = extract_str(stock.xpath(\"./td[4]/text()\").extract_first())\n index_powers[\"roa\"] = extract_str(stock.xpath(\"./td[5]/text()\").extract_first())\n index_powers[\"roe\"] = extract_str(stock.xpath(\"./td[6]/text()\").extract_first())\n index_powers[\"best_effective\"] = len(stock.xpath(\"./td[7]/i\"))\n index_powers[\"p_on_b\"] = extract_str(stock.xpath(\"./td[8]//text()\").extract_first())\n index_powers[\"stock_at_btm\"] = extract_str(stock.xpath(\"./td[9]/text()\").extract_first())\n index_powers[\"debt_ratio\"] = extract_str(stock.xpath(\"./td[10]/text()\").extract_first())\n index_powers[\"best_value\"] = len(stock.xpath(\"./td[11]/i\"))\n index_powers[\"beta\"] = extract_str(stock.xpath(\"./td[12]/text()\").extract_first())\n index_powers[\"on_bal_vol_ratio\"] = extract_str(stock.xpath(\"./td[13]/text()\").extract_first())\n index_powers[\"best_surf\"] = len(stock.xpath(\"./td[14]/i\"))\n index_powers[\"avg_strength\"] = extract_str(stock.xpath(\"./td[15]//strong/text()\").extract_first())\n yield index_powers\n pass\n\n\ndef extract_str(xpath):\n regex_valid_data = r'[^A-Za-z0-9\\.%]+'\n return re.sub(regex_valid_data, '', xpath)\n","sub_path":"StockInfoCrawler/spiders/basic_indexes_power_spider.py","file_name":"basic_indexes_power_spider.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"389286380","text":"import sys\n''' \n ***algorithm for spec***\n\n So what’s the secret formula? Well, most cards use an algorithm invented by \n Hans Peter Luhn, a nice fellow from IBM. According to Luhn’s algorithm, you \n can determine if a credit card number is (syntactically) valid as follows:\n\n 1. Multiply every other digit by 2, starting with the number’s\n second-to-last digit, and then add those products' digits together.\n\n 2.Add the sum to the sum of the digits that weren’t multiplied by 2.\n\n 3.If the total’s last digit is 0 (or, put more formally, if the total \n modulo 10 is congruent to 0), the number is valid!\n\n'''\n\ndef main():\n #input\n num = input(\"Number: \")\n #looping until non-negative and integer\n while True:\n if (type(num) == int) :\n if (num > 0):\n break\n else:\n num = input(\"Retry: \")\n else:\n num = input(\"Retry: \")\n\n if (credit(num)% 10 == 0):\n print (\"Amex\")\n else: \n print(\"INVALID\")\n exit(0)\n\ndef credit(num):\n #cast to string\n string = str(num)\n index = len(string)\n #running total\n summation = 0\n # if string has a length greater than one \n if(index > 1):\n # mult and add every other digit starting from next to last digit\n # going backwards\n # add the other digits \n while(index >= 2):\n summation += int(string[index-1])\n summation += (adddigits(int(string[index-2])*2))\n index -= 2\n if(len(string) % 2 == 1 ):\n #if odd length\n summation += int(string[index-1])\n return summation\n else:\n #something went wrong here\n return num\n\n#goes through every digit in a number and adds the digits\ndef adddigits(num):\n sm = num//10\n sm += num%10\n return sm\n\n#main\nif __name__ == \"__main__\":\n main();\n","sub_path":"pset6/credit.py","file_name":"credit.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"551537150","text":"from __future__ import unicode_literals\n\nfrom ..permissions import (\n permission_document_version_revert, permission_document_version_view,\n)\n\nfrom .base import GenericDocumentViewTestCase\nfrom .literals import TEST_VERSION_COMMENT\nfrom .mixins import DocumentVersionTestMixin\n\n\nclass DocumentVersionTestCase(DocumentVersionTestMixin, GenericDocumentViewTestCase):\n def _request_document_version_list_view(self):\n return self.get(\n viewname='documents:document_version_list',\n kwargs={'pk': self.test_document.pk}\n )\n\n def test_document_version_list_no_permission(self):\n self._upload_new_version()\n\n response = self._request_document_version_list_view()\n self.assertEqual(response.status_code, 404)\n\n def test_document_version_list_with_access(self):\n self._upload_new_version()\n self.grant_access(\n obj=self.test_document, permission=permission_document_version_view\n )\n\n response = self._request_document_version_list_view()\n self.assertContains(\n response=response, text=TEST_VERSION_COMMENT, status_code=200\n )\n\n def _request_document_version_revert_view(self, document_version):\n return self.post(\n viewname='documents:document_version_revert',\n kwargs={'pk': document_version.pk}\n )\n\n def test_document_version_revert_no_permission(self):\n first_version = self.test_document.latest_version\n self._upload_new_version()\n\n response = self._request_document_version_revert_view(\n document_version=first_version\n )\n self.assertEqual(response.status_code, 404)\n\n self.assertEqual(self.test_document.versions.count(), 2)\n\n def test_document_version_revert_with_access(self):\n first_version = self.test_document.latest_version\n self._upload_new_version()\n\n self.grant_access(\n obj=self.test_document, permission=permission_document_version_revert\n )\n\n response = self._request_document_version_revert_view(\n document_version=first_version\n )\n self.assertEqual(response.status_code, 302)\n\n self.assertEqual(self.test_document.versions.count(), 1)\n","sub_path":"mayan/apps/documents/tests/test_document_version_views.py","file_name":"test_document_version_views.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"136771210","text":"def mathjaxify(code):\n splitted = code.split(\"$$\")\n result = \"\"\n for i, section in enumerate(splitted):\n if i % 2:\n section = section\\\n .replace('', '*')\\\n .replace('', '*')\\\n .replace('<', '<')\\\n .replace('>', '>')\\\n .replace(\"&\", \"&\")\n result += \"\"\n else:\n result += section\n return result","sub_path":"mathjaxify.py","file_name":"mathjaxify.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"366440046","text":"from scipy import *\nimport scipy.integrate as intg\nimport scipy.constants as con\nimport matplotlib.pyplot as plt\n\nrawDataF=loadtxt('Fluoresence_Pi_Sigma_NoADJ.dat')\nFxPi=rawDataF[:,0]\nFyPi=rawDataF[:,1]-0.1#noise\nFxSi=rawDataF[:,2]\nFySi=rawDataF[:,3]-0.1\n\ndef CalcIntg(wLeft,wRight):\n index=((FxPi>=wLeft) & (FxPi=wLeft) & (FxSi3H4:460~510nm\nsum3H5=CalcIntg(510,568) # 3PJ->3H5:510~560nm\nsum3H6=CalcIntg(568,630) # 3PJ->3H6:580~630nm\nsum3F2=CalcIntg(630,660) # 3PJ->3F2:630~657nm\nsum3F3=CalcIntg(660,712) # 3PJ->3F3:667~712nm\nsum3F4=CalcIntg(712,730) # 3PJ->3F4:712~730nm\nsumAll=sum3H4+sum3H5+sum3H6+sum3F2+sum3F3+sum3F4\n\nbRatio3H4=sum3H4/sumAll\nbRatio3H5=sum3H5/sumAll\nbRatio3H6=sum3H6/sumAll\nbRatio3F2=sum3F2/sumAll\nbRatio3F3=sum3F3/sumAll\nbRatio3F4=sum3F4/sumAll\n\nprint('-----Braching ratio of Pr:YLF------')\nprint('3PJ->3H4: 460~510nm, {:.2%}'.format(bRatio3H4))\nprint('3PJ->3H5: 510~560nm, {:.2%}'.format(bRatio3H5))\nprint('3PJ->3H6: 580~630nm, {:.2%}'.format(bRatio3H6))\nprint('3PJ->3F2: 630~660nm, {:.2%}'.format(bRatio3F2))\nprint('3PJ->3F3: 660~712nm, {:.2%}'.format(bRatio3F3))\nprint('3PJ->3F4: 712~730nm, {:.2%}'.format(bRatio3F4))\n\ndef nPi(lambdaIn):#nm, Refractive index\n A1 = 9.78193009e-1\n A2 = 5.16522465e-3\n A3 = 1.81188108e-1\n A4 = 1.38616379e-2\n A5 = 4.08617049e-1\n A6 = 1.03566880e2\n wLength = lambdaIn/1000#um\n n = (1 + A1 * wLength ** 2 / (wLength **2 - A2) + \\\n A3 * wLength ** 2 / (wLength ** 2 - A4 ) + \\\n A5 * wLength ** 2 / (wLength ** 2 - A6)) ** 0.5\n return n\ndef nSi(lambdaIn):\n A1 = 9.59953108e-1;\n A2 = 5.11910200e-3;\n A3 = 1.35057927e-1;\n A4 = 1.42473335e-2;\n A5 = 3.99834349e-1;\n A6 = 1.03566887e2;\n wLength=lambdaIn/1000\n n=( 1 + A1 * wLength ** 2 / (wLength ** 2 - A2) \\\n + A3 * wLength ** 2 / (wLength ** 2 - A4) + \\\n A5 * wLength ** 2 / (wLength ** 2 - A6)) ** 0.5\n return n\n#sumAll+=sum3H4\n\nc=con.c\ntao=50e-6 #50us\ncsPi=zeros([len(FxPi),2],dtype=float)\ncsPi[:,0]=FxPi\ni=0\nfor item in csPi:\n long=FxPi[i]\n signal=FyPi[i]\n item[0]=long\n n=nPi(long)\n long_m=long*1e-9 #m\n item[1]=3*long_m**5*signal/8/pi/n**2/c/tao/(sumAll*1e-18)\n item[1]*=1e4 #cm2\n i+=1\n\ncsSi=zeros([len(FxSi),2],dtype=float)\ncsSi[:,0]=FxSi\ni=0\nfor item in csSi:\n long=FxSi[i]\n signal=FySi[i]\n item[0]=long\n n=nSi(long)\n long_m=long*1e-9 #m\n item[1]=3*long_m**5*signal/8/pi/n**2/c/tao/(sumAll*1e-18)\n item[1]*=1e4 #cm2\n i+=1\n\nimport time\noutstr=time.ctime()\n\nfout=open('CS_Pi_Sigma.dat','w')\nfout.write('#wlengthpi'+'\\t'+'Pi'+'\\t'+'wlengthsi'+'\\t'+'Sigma\\t'+outstr+'\\n')\nresult=c_[csPi,csSi]\nfor row in result:\n fout.write(str(row[0])+'\\t'+str(row[1])+'\\t'+str(row[2])+'\\t'+str(row[3])+'\\n')\nfout.close()\nprint(\"new file saved:\")\n\nplt.subplot(211)\nplt.plot(FxPi,FyPi,FxSi,FySi)\nplt.ylabel('Intensity (a.u.)')\nplt.legend(['pi','sigma'])\nplt.grid(True)\n\nplt.subplot(212)\nplt.plot(csPi[:,0],csPi[:,1],csSi[:,0],csSi[:,1])\nplt.ylabel('Emission c-s (cm2)')\nplt.legend(['pi','sigma'])\nplt.grid(True)\nplt.show()","sub_path":"Calculation/Pr3+ c-cut emission spectrum/刘哲 program/F-L算发射截面/T12K/BrachingRatio_CrossSection.py","file_name":"BrachingRatio_CrossSection.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"520587804","text":"# Assignment 2 - Puzzle Game\n#\n# CSC148 Fall 2015, University of Toronto\n# Instructor: David Liu\n# ---------------------------------------------\n\"\"\"Module containing the Controller class.\"\"\"\nfrom view import TextView, WebView\nfrom puzzle import Puzzle\nfrom solver import *\n\nclass MoveUndoTree:\n def __init__(self, puzzle, move=\"\"):\n \"\"\"Create a new...........########\n @type move: str\n @type puzzle: Puzzle\n @rtype: None\n\n \"\"\"\n self.move = move\n self.puzzle = puzzle\n self.user_moves = []\n\n\nclass Controller:\n \"\"\"Class responsible for connection between puzzles and views.\n\n You may add new *private* attributes to this class to help you\n in your implementation.\n \"\"\"\n # === Private Attributes ===\n # @type _puzzle: Puzzle\n # The puzzle associated with this game controller\n # @type _view: View\n # The view associated with this game controller\n\n def __init__(self, puzzle, mode='text'):\n \"\"\"Create a new controller.\n\n is either 'text' or 'web', representing the type of view\n to use.\n\n By default, has a value of 'text'.\n\n @type puzzle: Puzzle\n @type mode: str\n @rtype: None\n \"\"\"\n self._puzzle = puzzle\n if mode == 'text':\n self._view = TextView(self)\n elif mode == 'web':\n self._view = WebView(self)\n else:\n raise ValueError()\n self._main_commands = [':SOLVE',':SOLVE-ALL']\n # Start the game.\n self._view.run()\n\n def state(self):\n \"\"\"Return a string representation of the current puzzle state.\n\n @type self: Controller\n @rtype: str\n \"\"\"\n return str(self._puzzle)\n\n def act(self, action):\n \"\"\"Run an action represented by string .\n\n Return a string representing either the new state or an error message,\n and whether the program should end.\n\n @type self: Controller\n @type action: str\n @rtype: (str, bool)\n \"\"\"\n # TODO: Add to this method to handle different actions.\n if action == 'exit':\n r_tup = ('', True)\n return r_tup\n elif action == ':SOLVE':\n answer = solve(self._puzzle)\n r_tup = (answer.__str__(), True)\n return r_tup\n elif action == ':SOLVE-ALL':\n answers = solve_complete(self._puzzle)\n ans_string_list = []\n for temp in answers:\n ans_string_list.append(temp.__str__())\n output_list = \"\\n\".join(ans_string_list)\n r_tup = (output_list, True)\n return r_tup\n elif action not in self._main_commands:\n try:\n new_state = self._puzzle.move(action)\n if new_state.is_solved():\n r_tup = (new_state, True)\n return r_tup\n else:\n r_tup = (new_state, False)\n return r_tup\n except ValueError:\n r_tup = (\"That is an invalid move, please try again\", False)\n return r_tup\n\n else:\n r_tup = (self.state(), False)\n return r_tup\n\n\"\"\"\nif __name__ == '__main__':\n from sudoku_puzzle import SudokuPuzzle\n\n s = SudokuPuzzle([['', '', '', ''],\n ['', '', '', ''],\n ['C', 'D', 'A', 'B'],\n ['A', 'B', 'C', 'D']])\n c = Controller(s)\n\"\"\"\n#\"\"\"\nif __name__ == '__main__':\n from sudoku_puzzle import SudokuPuzzle\n s = SudokuPuzzle(\n [['E', 'C', '', '', 'G', '', '', '', ''],\n ['F', '', '', 'A', 'I', 'E', '', '', ''],\n ['', 'I', 'H', '', '', '', '', 'F', ''],\n ['H', '', '', '', 'F', '', '', '', 'C'],\n ['D', '', '', 'H', '', 'C', '', '', 'A'],\n ['G', '', '', '', 'B', '', '', '', 'F'],\n ['', 'F', '', '', '', '', 'B', 'H', ''],\n ['', '', '', 'D', 'A', 'I', '', '', 'E'],\n ['', '', '', '', 'H', '', '', 'G', 'I']]\n )\n c = Controller(s)\n\n#\"\"\"\n\"\"\"\nif __name__ == '__main__':\n from word_ladder_puzzle import WordLadderPuzzle\n\n w = WordLadderPuzzle('phone', 'parts')\n\n c = Controller(w)\n\"\"\"\n","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":4248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"35692683","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\n\n\ndef reliability_diagrams(ob, fo, grade_list=None, save_path=None, diagona_color='r', regression_line_color='g',\n broken_line_color='b'):\n '''\n reliability_diagrams 可靠性图\n ----------------------------\n :param ob: 实况数据 一维numpy\n :param fo: 预测数据 一维numpy\n :param grade_list: 等级\n :param save_path: 保存地址\n :param diagona_color:理想线颜色\n :param regression_line_color: 回归线颜色\n :param broken_line_color: 折线颜色\n :return:\n '''\n if grade_list is None:\n clevs = np.arange(0, 1.0, 10) # 如果没有给定概率等级,就设置默认等级\n else:\n clevs = grade_list\n\n orfs = [0]\n for i in range(1, len(clevs)):\n index0 = np.where((fo > clevs[i - 1]) & (fo <= clevs[i]))\n num = np.sum(ob[index0] == 1)\n lenght = len(index0)\n orf = num / lenght\n orfs.append(orf)\n orfs = np.array(orfs)\n X = np.array(clevs)\n X = X.reshape((len(X), -1))\n model = LinearRegression().fit(X, orfs)\n y = model.predict(X)\n plt.plot(X, y, color=regression_line_color)\n plt.plot(clevs, orfs, color=broken_line_color)\n plt.scatter(clevs, orfs, color=broken_line_color)\n plt.plot([0, 1], [0, 1], color=diagona_color)\n\n if save_path is None:\n plt.show()\n else:\n plt.savefig(save_path)\n","sub_path":"nmc_verification/nmc_vf_method/probability/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"389347674","text":"import json\nimport falcon\n\nimport func_wakati as fc\n\n\nclass AppResource(object):\n\n def on_post(self, req, resp):\n body = req.stream.read()\n data = json.loads(body)\n\n waka1 = fc.wakati(data['in1'])\n waka2 = fc.wakati(data['in2'])\n\n\n msg = {'out1' : waka1,\n 'out2' : waka2}\n resp.body = json.dumps(msg)\n\n\napp = falcon.API()\napp.add_route(\"/\", AppResource())\n\n\nif __name__ == \"__main__\":\n from wsgiref import simple_server\n httpd = simple_server.make_server(\"127.0.0.1\", 8000, app)\n httpd.serve_forever()\n","sub_path":"api-server.py","file_name":"api-server.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"130722713","text":"import os\nimport pathlib\nfrom dataloaders.datasets.icdar import ICDAR\nfrom torch.utils.data import DataLoader\nimport torch\n\n\ndef collate_fn(batch):\n import pdb; pdb.set_trace()\n # list of batches\n return\n\ndef make_data_loader(config, **kwargs):\n if config['data_loader']['dataset'] == 'icdar2015':\n data_root = pathlib.Path(config['data_loader']['data_dir'])\n ICDAR_train_2015 = ICDAR(data_root, year='2015', type='training')\n ICDAR_val_2015 = ICDAR(data_root, year='2015', type='test')\n\n train_sampler = None\n val_sampler = None\n is_shuffle = True\n batch_size = config['data_loader']['batch_size']\n if kwargs.pop('distributed'):\n train_sampler = torch.utils.data.distributed.DistributedSampler(\n ICDAR_train_2015)\n val_sampler = torch.utils.data.distributed.DistributedSampler(\n ICDAR_val_2015)\n\n batch_size = batch_size // kwargs.pop('world_size')\n is_shuffle = False\n\n train_loader = DataLoader(ICDAR_train_2015, batch_size=batch_size,\n shuffle=is_shuffle, drop_last=True, collate_fn = collate_fn, **kwargs,\n )\n val_loader = DataLoader(ICDAR_val_2015, batch_size=batch_size,\n shuffle=False, collate_fn = collate_fn, **kwargs,\n )\n\n return train_loader, val_loader\n else:\n print(\"Dataset not implemented\")","sub_path":"dataloaders/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"132594957","text":"from jet.filters import RelatedFieldAjaxListFilter\nfrom django.contrib import admin\nfrom .models import Familias, Subfamilias, Marcas, UnidadesMedida, EquivalenciasUM, Articulos, PresentacionArticulos\nfrom .models import MarcaArticulo, ProveedorMA\nfrom django.http import JsonResponse\nfrom controlinv.mixins import ExportCsvMixin\nfrom django import forms\nfrom django.forms import widgets\nfrom django.contrib.admin.widgets import AdminRadioSelect \nfrom jet.admin import CompactInline\nimport nested_admin\nfrom django.db.models import Max\nfrom django.urls import reverse, path\nfrom django.utils.html import mark_safe, format_html\n#from django.core.urlresolvers import reverse\n\ndef custom_titled_filter(title): \n class Wrapper(admin.FieldListFilter): \n def __new__(cls, *args, **kwargs): \n instance = admin.FieldListFilter.create(*args, **kwargs) \n instance.title = title \n return instance \n return Wrapper\n \nclass SubfamiliasInline(admin.TabularInline):\n model = Subfamilias\n extra = 3\n readonly_fields = ('created_by',)\n fields = ['clave_subfamilia','nombre_subfamilia','activo']\n\nclass EquivalenciasUMInLine(admin.TabularInline):\n model = EquivalenciasUM\n extra = 1 \n readonly_fields = ('created_by',)\n fk_name = 'unidad_medida'\n fields = ['cantidad_conversion','unidad_medida_conversion']\n #list_display = ('id','area','empresa_padre','sucursal_padre','area_padre','activo')\n\n def get_formset(self, request, obj=None, **kwargs):\n # self.fields.field['cantidad_conversion'].localize=False\n return super(EquivalenciasUMInLine, self).get_formset(request, obj,**kwargs) \n\n\nclass ProveedorMAForm(forms.ModelForm):\n class Meta:\n model = ProveedorMA\n fields = '__all__'\n\n def clean(self):\n print(self._clean_fields) \n #print(self._errors['__all__']) \n \n return self.cleaned_data\n\nclass ProveedorMAInLine(admin.StackedInline):\n model = ProveedorMA\n form = ProveedorMAForm \n extra = 0 \n inline_classes = ('grp-collapse grp-open',)\n\n fieldsets = ( \n (None, {\n 'fields': ('proveedor',)\n }) , \n (None, {\n 'fields': ('prioridad_proveedor',)\n }),\n ('Datos de Localización del Artículo con el Proveedor', { \n 'fields': [ 'foto', 'sku', 'comentarios'], \n }), \n \n )\n\nclass MarcaArticuloForm(forms.ModelForm):\n class Meta:\n model = MarcaArticulo\n fields = '__all__'\n\n def clean(self):\n print(self._clean_fields) \n #print(self._errors['__all__']) \n \n return self.cleaned_data\n\nclass MarcaPAInLine(nested_admin.NestedTabularInline):\n model = MarcaArticulo\n form = MarcaArticuloForm \n extra = 0 \n sortable_field_name = \"prioridad_marca\" \n inlines = [ProveedorMAInLine]\n\nclass FamiliasAdmin(admin.ModelAdmin, ExportCsvMixin): \n readonly_fields = ('created_by', 'created','updated')\n list_display = ('clave_familia','nombre_familia','activo')\n ordering = ('clave_familia',)\n\n search_fields = ('clave_familia', 'nombre_familia',)\n\n inlines = [SubfamiliasInline]\n\n actions = [\"export_as_csv\"]\n\n def admin_action(self, request, queryset):\n export_as_csv.short_description = \"Exportar Selección\"\n\n def save_model(self, request, obj, form, change):\n if not change:\n obj.created_by = request.user\n obj.save()\n\n def save_formset(self, request, form, formset, change): \n for form in formset.forms: \n if (not form.instance.pk):\n form.instance.created_by = request.user \n\n formset.save() \n\n\n# Register your models here.\nclass SubfamiliasAdmin(admin.ModelAdmin, ExportCsvMixin):\n readonly_fields = ('created_by', 'created','updated')\n list_display = ('familia','clave_subfamilia','nombre_subfamilia','activo')\n ordering = ('clave_subfamilia',)\n list_filter = (('familia__nombre_familia',custom_titled_filter('Familia')),)\n\n search_fields = ('familias__nombre_familia','clave_subfamilia', 'nombre_subfamilia',)\n\n fields = ['familia','clave_subfamilia','nombre_subfamilia','activo']\n\n actions = [\"export_as_csv\"]\n #autocomplete_fields = ('familia',)\n\n def admin_action(self, request, queryset):\n export_as_csv.short_description = \"Exportar Selección\"\n\n def save_model(self, request, obj, form, change):\n if not change:\n obj.created_by = request.user\n obj.save()\n\nclass MarcasAdmin(admin.ModelAdmin, ExportCsvMixin):\n readonly_fields = ('created_by', 'created','updated')\n list_display = ('marca','activo')\n ordering = ('marca',)\n #list_filter = (('familia__nombre_familia',custom_titled_filter('Familia')),)\n\n search_fields = ('marca',)\n\n #fields = ['marca','clave_subfamilia','nombre_subfamilia','activo']\n\n actions = [\"export_as_csv\"]\n #autocomplete_fields = ('familia',)\n\n def admin_action(self, request, queryset):\n export_as_csv.short_description = \"Exportar Selección\"\n\n def save_model(self, request, obj, form, change):\n if not change:\n obj.created_by = request.user\n obj.save()\n\n# Register your models here.\nclass UnidadesMedidaAdmin(admin.ModelAdmin, ExportCsvMixin): \n readonly_fields = ('created_by', 'created','updated')\n list_display = ('unidad_medida','abreviatura','activo')\n ordering = ('unidad_medida',)\n\n search_fields = ('unidad_medida',)\n\n inlines = [EquivalenciasUMInLine]\n\n actions = [\"export_as_csv\"]\n\n def admin_action(self, request, queryset):\n export_as_csv.short_description = \"Exportar Selección\"\n\n def save_model(self, request, obj, form, change):\n if not change:\n obj.created_by = request.user\n obj.save()\n\n def save_formset(self, request, form, formset, change): \n for form in formset.forms: \n if (not form.instance.pk):\n form.instance.created_by = request.user \n\n formset.save() \n\nclass ArticulosForm(forms.ModelForm):\n class Meta:\n model = Articulos\n fields = '__all__'\n\n def clean(self):\n print(self._clean_fields) \n #print(self._errors['__all__']) \n \n return self.cleaned_data\n\n def __init__(self, *args, **kwargs): \n super(ArticulosForm, self).__init__(*args, **kwargs)\n \n campo_e = \"familia\"\n if self.data.get(campo_e, None):\n familia = self.data[campo_e]\n else:\n familia = 0\n try: \n familia = self.instance.familia.pk\n except:\n familia = 0 \n \n self.fields['subfamilia'].queryset = Subfamilias.objects.filter(familia_id=familia)\n\nclass ArticulosAdmin(admin.ModelAdmin, ExportCsvMixin): \n #change_list_template = \"admin/change_list_filter_sidebar.html\"\n form = ArticulosForm \n #readonly_fields = ('custom_add_presentacion',)\n list_display = ('clave_articulo','nombre_articulo','familia','subfamilia','custom_add_presentacion')\n list_display_links = ('custom_add_presentacion',)\n list_filter = ('familia','subfamilia',)\n\n\n #ordering = ('unidad_medida',)\n #fields = ('familia', 'subfamilia','clave_articulo','nombre_articulo','descripcion','tipo_articulo','unidad_medida_base',\n # 'foto','rendimiento','merma','custom_add_presentacion')\n radio_fields = {'tipo_articulo': admin.HORIZONTAL, 'clasificacion': admin.HORIZONTAL}\n search_fields = ('clave_articulo','nombre_articulo','familia__nombre_familia','subfamilia__nombre_subfamilia',)\n\n #inlines = [PresentacionArticulosInLine]\n #inlines = [PresentacionArticulosInLine, MarcaPAInLine]\n #autocomplete_fields = ('unidad_medida_base',)\n\n list_per_page = 20\n\n actions = [\"export_as_csv\"]\n\n #def __init__(self,*args,**kwargs):\n # super(ArticulosAdmin, self).__init__(*args, **kwargs)\n # self.list_display_links = (None, )\n\n def get_urls(self):\n urls = super().get_urls()\n custom_urls = [\n path(\n r'?/presentaciones/$',\n self.admin_site.admin_view(self.presentaciones_art),\n name='articulos_presentacionarticulos_add',\n ),\n \n ]\n return custom_urls + urls\n\n def custom_add_presentacion(self, obj):\n #add_url = reverse('admin:articulos_presentacionarticulos_add')\n #return mark_safe(f'Añadir Presentación')\n url0 = reverse('admin:articulos_articulos_change', args=(obj.pk,))\n url1 = reverse('admin:articulos_presentacionarticulos_changelist')\n url2 = reverse('admin:articulos_marcaarticulo_changelist')\n \"\"\"\n return format_html(\n \n 'Presentación ',\n #'Withdraw',\n reverse('admin:articulos_presentacionarticulos_changelist', args=[obj.pk]),\n #reverse('admin:articulos_presentacionarticulos_add', args=[obj.pk]),\n )\"\"\"\n html = format_html(''.format(url0))\n html += format_html(' '.format(url1, obj.pk))\n html += format_html(' '.format(url2, obj.pk))\n return html\n \n custom_add_presentacion.short_description = 'Acciones'\n custom_add_presentacion.allow_tags = True\n\n def presentaciones_art(self, request, art_id, *args, **kwargs):\n return self.process_action(\n request=request,\n art_id=art_id,\n action_form=PresentacionArticulos2Form,\n action_title='Presentación',\n )\n\n def clean(self):\n from django.core.exceptions import ValidationError\n # Don't allow draft entries to have a pub_date.\n #print(\"entre\")\n print (self.cleaned_data)\n return self.cleaned_data\n \n def admin_action(self, request, queryset):\n export_as_csv.short_description = \"Exportar Selección\"\n\n def get_form(self, request, obj=None, **kwargs):\n \"\"\"\n No permitir agregar Estados, Municipios y Localidades\n \"\"\"\n form = super(ArticulosAdmin, self).get_form(request, obj, **kwargs)\n css_style = 'style=\"display: inline-block; margin-right: 10px;\"'\n\n form.base_fields['tipo_articulo'].widget.attrs={'onchange':'valida_clasificacion(this, \"TA\");', 'style':'display: inline-block; margin-right: 10px;'}\n \n #form.base_fields['clasificacion'].widget = forms.ChoiceField(attrs={'onchange':'valida_clasificacion(this, \"CL\");'})\n\n #form.base_fields['rendimiento'].widget = forms.NumberInput(attrs={'onchange':'modificar_rendimiento_merma(this, \"rend\");','lang':'en'})\n #form.base_fields['merma'].widget = forms.NumberInput(attrs={'onchange':'modificar_rendimiento_merma(this, \"merma\");','lang':'en'})\n \n #form.base_fields['familia'].widget.can_add_related = False\n #form.base_fields['familia'].widget.can_change_related = False\n #form.base_fields['subfamilia'].widget.can_add_related = False\n #form.base_fields['subfamilia'].widget.can_change_related = False\n #form.base_fields['tipo_articulo'].widget = forms.RadioSelect() \n return form\n \n\n def save_model(self, request, obj, form, change):\n if not change:\n obj.created_by = request.user\n obj.save()\n\n def llenar_combo_subfamilias(request): \n familia = request.GET.get('familia',None) \n obj = request.GET.get('pk',None)\n valor_actual = request.GET.get('valor_actual',None) \n\n subfamilias = Subfamilias.objects.none()\n\n options = ''\n if familia:\n subfamilias = Subfamilias.objects.filter(familia_id=familia).order_by('nombre_subfamilia') \n for subfam in subfamilias:\n options += '