.*?)\\r\\n\", request[1]))\n self.headers = headers\n return True\n\n\n\n\nclass HTTPServer(object):\n\n def __init__(self, host='', port=8080):\n\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP Socket\n self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.s.bind((host, port))\n self.s.listen(BLACKLOG)\n\n self.host = socket.gethostbyname(host)\n self.port = port\n\n self.routes = {}\n \n def route(self, *args, **kwargs):\n def decorator(func):\n for arg in args:\n self.routes[arg] = {'func': func, 'kwargs': dict(kwargs)}\n return func\n return decorator\n\n def serve(self, output=True):\n logger.propagate = output\n logger.info(\"Serving on %s port %s\" % (self.host, self.port))\n logger.info(\"Server is awaiting for connections..\")\n while 1:\n conn, addr = self.s.accept()\n logger.info(\"Connection from %s\" % ':'.join([str(element) for element in addr]))\n data = conn.recv(4096)\n request = HTTPRequestParser(data)\n if not request.error:\n connection_type = request.headers.get('Connection', 'close')\n response = ''\n\n if request.method == 'GET':\n match = None\n for pattern, dictionary in iter(self.routes.items()):\n match = re.match(pattern, request.uri)\n if match:\n headers = gen_headers(**dictionary['kwargs'])\n response += headers\n response += dictionary['func'](*match.groups())\n break\n if not match:\n response += gen_headers(code=404)\n response += \"404 Not FoundNot found
The requested URL %s was not found on this server.
\" % (request.uri)\n\n if response:\n conn.sendall(bytes(response, 'UTF-8'))\n\n if connection_type == 'close':\n conn.close()\n\n conn.close() # Close anyway\n self.s.close()\n\n\n\n\n\n \n\n\n\n\n\n", "sub_path": "HTTPServ/HTTPServer.py", "file_name": "HTTPServer.py", "file_ext": "py", "file_size_in_byte": 6179, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "logging.getLogger", "line_number": 15, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 16, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 16, "usage_type": "attribute"}, {"api_name": "logging.StreamHandler", "line_number": 16, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 50, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 50, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 121, "usage_type": "call"}, {"api_name": "socket.socket", "line_number": 132, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 132, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 132, "usage_type": "attribute"}, {"api_name": "socket.SOL_SOCKET", "line_number": 133, "usage_type": "attribute"}, {"api_name": "socket.SO_REUSEADDR", "line_number": 133, "usage_type": "attribute"}, {"api_name": "socket.gethostbyname", "line_number": 137, "usage_type": "call"}, {"api_name": "re.match", "line_number": 165, "usage_type": "call"}]}
+{"seq_id": "195724259", "text": "#coding: utf-8\nimport math\nimport time\n#import numpy as np\nimport numpy.random as npr\nimport cupy as cp #GPUを使うためのnumpy\nimport chainer \nfrom chainer import cuda, Function, Variable, optimizers\nfrom chainer import Link, Chain\nimport chainer.functions as F\nimport chainer.links as L\n\nfrom NNFP import load_data \nfrom NNFP import result_plot \nfrom NNFP import normalize_array\nfrom NNFP import Deep_neural_network\nfrom NNFP import Finger_print\n\n\ntask_params = {'target_name' : 'measured log solubility in mols per litre',\n\t\t\t\t'data_file' : 'delaney.csv'}\n\nN_train = 70\nN_val = 1\nN_test = 10\n\n\nmodel_params = dict(fp_length = 50, \n\t\t\t\t\tfp_depth = 4, #NNの層と、FPの半径は同じ\n\t\t\t\t\tconv_width = 20, #必要なパラメータはこれだけ(?)\n\t\t\t\t\th1_size = 100, #最上位の中間層のサイズ\n\t\t\t\t\tL2_reg = cp.exp(-2))\n\ntrain_params = dict(num_iters = 100,\n\t\t\t\t\tbatch_size = 50,\n\t\t\t\t\tinit_scale = cp.exp(-4),\n\t\t\t\t\tstep_size = cp.exp(-6))\n\n\t\nclass Main(Chain):\n\tdef __init__(self, model_params):\n\t\tsuper(Main, self).__init__(\n\t\t\tfp = Finger_print.FP(model_params),\n\t\t\tdnn = Deep_neural_network.DNN(model_params),\n\t\t)\n\t\n\tdef __call__(self, x, y):\n\t\tt = time.time()\n\t\ty = Variable(cp.array(y, dtype=cp.float32))\n\t\tprint(\"variable : \", time.time() - t)\n\t\tpred = self.prediction(x)\n\t\treturn F.mean_squared_error(pred, y)\n\n\tdef prediction(self, x):\n\t\tx = Variable(cuda.to_cpu(x))\n\t\tfinger_print = self.fp(x)\n\t\tpred = self.dnn(finger_print)\n\t\treturn pred\n\n\tdef mse(self, x, y, undo_norm):\n\t\ty = Variable(cp.array(y, dtype=cp.float32))\n\t\tpred = undo_norm(self.prediction(x))\n\t\treturn F.mean_squared_error(pred, y)\n\t\ndef train_nn(model, train_smiles, train_raw_targets, seed=0,\n\t\t\t\tvalidation_smiles=None, validation_raw_targets=None):\n\n\tnum_print_examples = N_train\n\ttrain_targets, undo_norm = normalize_array(train_raw_targets)\n\ttraining_curve = []\n\toptimizer = optimizers.Adam()\n\toptimizer.setup(model)\n\toptimizer.add_hook(chainer.optimizer.WeightDecay(0.0001))\t\n\t\n\tnum_epoch = 100\n\tnum_data = len(train_smiles)\n\tbatch_size = 50\n\tx = train_smiles\n\ty = train_targets\n\tsff_idx = npr.permutation(num_data)\n\tTIME = time.time()\n\tfor epoch in range(num_epoch):\n\t\tepoch_time = time.time()\n\t\tfor idx in range(0,num_data, batch_size):\n\t\t\tbatched_x = x[sff_idx[idx:idx+batch_size\n\t\t\t\tif idx + batch_size < num_data else num_data]]\n\t\t\tbatched_y = y[sff_idx[idx:idx+batch_size\n\t\t\t\tif idx + batch_size < num_data else num_data]]\n\t\t\tupdate_time\t = time.time()\n\t\t\tmodel.zerograds()\n\t\t\tloss = model(batched_x, batched_y)\n\t\t\tloss.backward()\n\t\t\toptimizer.update()\n\t\t\tprint(\"UPDATE TIME : \", time.time() - update_time)\n\t\t#print \"epoch \", epoch, \"loss\", loss._data[0]\n\t\tif epoch % 10 == 0:\n\t\t\tprint_time = time.time()\n\t\t\ttrain_preds = model.mse(train_smiles, train_raw_targets, undo_norm)\n\t\t\tcur_loss = loss._data[0]\n\t\t\ttraining_curve.append(cur_loss)\n\t\t\tprint(\"PRINT TIME : \", time.time() - print_time)\n\t\t\tprint(\"Iteration\", epoch, \"loss\", math.sqrt(cur_loss), \\\n\t\t\t\t\"train RMSE\", math.sqrt((train_preds._data[0])))\n\t\t\tif validation_smiles is not None:\n\t\t\t\tvalidation_preds = model.mse(validation_smiles, validation_raw_targets, undo_norm)\n\t\t\t\tprint(\"Validation RMSE\", epoch, \":\", math.sqrt((validation_preds._data[0])))\n\t\tprint(\"1 EPOCH TIME : \", time.time() - epoch_time)\n\t\t#print loss\n\n\t\t\n\treturn model, training_curve, undo_norm\n\ndef main():\n\tprint(\"Loading data...\")\n\ttraindata, valdata, testdata = load_data(\n\t\ttask_params['data_file'], (N_train, N_val, N_test),\n\t\tinput_name = 'smiles', target_name = task_params['target_name'])\n\tx_trains, y_trains = traindata\n\tx_vals, y_vals = valdata\n\tx_tests, y_tests = testdata\n\tx_trains = cp.reshape(x_trains, (N_train, 1))\n\ty_trains = cp.reshape(y_trains, (N_train, 1)).astype(cp.float32)\n\tx_vals = cp.reshape(x_vals, (N_val, 1))\n\ty_vals = cp.reshape(y_vals, (N_val, 1)).astype(cp.float32)\n\tx_tests = cp.reshape(x_tests, (N_test, 1))\n\ty_tests = cp.reshape(y_tests, (N_test, 1)).astype(cp.float32)\n\n\tdef run_conv_experiment():\n\t\t'''Initialize model'''\n\t\tNNFP = Main(model_params) \n\t\toptimizer = optimizers.Adam()\n\t\toptimizer.setup(NNFP)\n\n\t\tgpu_device = 0\n\t\tcuda.get_device(gpu_device).use()\n\t\tNNFP.to_gpu(gpu_device)\n\t\t#xp = cuda.cupy\n\t\t'''Learn'''\n\t\ttrained_NNFP, conv_training_curve, undo_norm = \\\n\t\t\ttrain_nn(NNFP, \n\t\t\t\t\t x_trains, y_trains, \n\t\t\t\t\t validation_smiles=x_vals, \n\t\t\t\t\t validation_raw_targets=y_vals)\n\t\treturn math.sqrt(trained_NNFP.mse(x_tests, y_tests, undo_norm)._data[0]), conv_training_curve\n\n\tprint(\"Starting neural fingerprint experiment...\")\n\ttest_loss_neural, conv_training_curve = run_conv_experiment()\n\tprint() \n\tprint(\"Neural test RMSE\", test_loss_neural)\n\t#result_plot(conv_training_curve, train_params)\n\nif __name__ == '__main__':\n\tmain()\n", "sub_path": "Graduation-thesis/NNFP_chainer/regression_gpu/chainer_regression.py", "file_name": "chainer_regression.py", "file_ext": "py", "file_size_in_byte": 4742, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "cupy.exp", "line_number": 32, "usage_type": "call"}, {"api_name": "cupy.exp", "line_number": 36, "usage_type": "call"}, {"api_name": "cupy.exp", "line_number": 37, "usage_type": "call"}, {"api_name": "chainer.Chain", "line_number": 40, "usage_type": "name"}, {"api_name": "NNFP.Finger_print.FP", "line_number": 43, "usage_type": "call"}, {"api_name": "NNFP.Finger_print", "line_number": 43, "usage_type": "name"}, {"api_name": "NNFP.Deep_neural_network.DNN", "line_number": 44, "usage_type": "call"}, {"api_name": "NNFP.Deep_neural_network", "line_number": 44, "usage_type": "name"}, {"api_name": "time.time", "line_number": 48, "usage_type": "call"}, {"api_name": "chainer.Variable", "line_number": 49, "usage_type": "call"}, {"api_name": "cupy.array", "line_number": 49, "usage_type": "call"}, {"api_name": "cupy.float32", "line_number": 49, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 50, "usage_type": "call"}, {"api_name": "chainer.functions.mean_squared_error", "line_number": 52, "usage_type": "call"}, {"api_name": "chainer.functions", "line_number": 52, "usage_type": "name"}, {"api_name": "chainer.Variable", "line_number": 55, "usage_type": "call"}, {"api_name": "chainer.cuda.to_cpu", "line_number": 55, "usage_type": "call"}, {"api_name": "chainer.cuda", "line_number": 55, "usage_type": "name"}, {"api_name": "chainer.Variable", "line_number": 61, "usage_type": "call"}, {"api_name": "cupy.array", "line_number": 61, "usage_type": "call"}, {"api_name": "cupy.float32", "line_number": 61, "usage_type": "attribute"}, {"api_name": "chainer.functions.mean_squared_error", "line_number": 63, "usage_type": "call"}, {"api_name": "chainer.functions", "line_number": 63, "usage_type": "name"}, {"api_name": "NNFP.normalize_array", "line_number": 69, "usage_type": "call"}, {"api_name": "chainer.optimizers.Adam", "line_number": 71, "usage_type": "call"}, {"api_name": "chainer.optimizers", "line_number": 71, "usage_type": "name"}, {"api_name": "chainer.optimizer.WeightDecay", "line_number": 73, "usage_type": "call"}, {"api_name": "chainer.optimizer", "line_number": 73, "usage_type": "attribute"}, {"api_name": "numpy.random.permutation", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 80, "usage_type": "name"}, {"api_name": "time.time", "line_number": 81, "usage_type": "call"}, {"api_name": "time.time", "line_number": 83, "usage_type": "call"}, {"api_name": "time.time", "line_number": 89, "usage_type": "call"}, {"api_name": "time.time", "line_number": 94, "usage_type": "call"}, {"api_name": "time.time", "line_number": 97, "usage_type": "call"}, {"api_name": "time.time", "line_number": 101, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 102, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 103, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 106, "usage_type": "call"}, {"api_name": "time.time", "line_number": 107, "usage_type": "call"}, {"api_name": "NNFP.load_data", "line_number": 115, "usage_type": "call"}, {"api_name": "cupy.reshape", "line_number": 121, "usage_type": "call"}, {"api_name": "cupy.reshape", "line_number": 122, "usage_type": "call"}, {"api_name": "cupy.float32", "line_number": 122, "usage_type": "attribute"}, {"api_name": "cupy.reshape", "line_number": 123, "usage_type": "call"}, {"api_name": "cupy.reshape", "line_number": 124, "usage_type": "call"}, {"api_name": "cupy.float32", "line_number": 124, "usage_type": "attribute"}, {"api_name": "cupy.reshape", "line_number": 125, "usage_type": "call"}, {"api_name": "cupy.reshape", "line_number": 126, "usage_type": "call"}, {"api_name": "cupy.float32", "line_number": 126, "usage_type": "attribute"}, {"api_name": "chainer.optimizers.Adam", "line_number": 131, "usage_type": "call"}, {"api_name": "chainer.optimizers", "line_number": 131, "usage_type": "name"}, {"api_name": "chainer.cuda.get_device", "line_number": 135, "usage_type": "call"}, {"api_name": "chainer.cuda", "line_number": 135, "usage_type": "name"}, {"api_name": "NNFP.to_gpu", "line_number": 136, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 144, "usage_type": "call"}]}
+{"seq_id": "540318391", "text": "from django.shortcuts import render\nimport requests\nfrom .models import City\nfrom .forms import city_name\n\n\n\ndef index(request):\n url = 'http://api.openweathermap.org/data/2.5/forecast?q={}&APPID=4e3aadd76d19d3209156dccbff340001'\n\n form = city_name(request.POST)\n if request.method == 'POST':\n\n if form.is_valid():\n city = form.cleaned_data['name']\n else:\n city = \"Mumbai\" #Default City\n\n\n r = requests.get(url.format(city)).json()\n context = {\n 'city' : city,\n 'temperature' : r['list'][0]['main']['temp'],\n 'describe' : r['list'][0]['weather'][0]['description'] ,\n 'pressure' : r['list'][0]['main']['pressure'],\n 'sea_level' : r['list'][0]['main']['sea_level'],\n 'humidity' : r['list'][0]['main']['humidity'],\n 'form' : form,\n }\n\n return render(request,'weather/index.html',context = context)\n\n\ndef forms_view(request):\n form = forms.city_name()\n return render(request,'weather/forms.html',{'form' : form })\n", "sub_path": "the_weather/weather/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1038, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "forms.city_name", "line_number": 11, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 20, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 31, "usage_type": "call"}, {"api_name": "forms.city_name", "line_number": 35, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 36, "usage_type": "call"}]}
+{"seq_id": "152089468", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('usuario', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='usuario',\n name='avatar',\n field=models.ImageField(default=datetime.datetime(2015, 10, 15, 13, 31, 43, 387558, tzinfo=utc), upload_to=b'usuarios/avatar/'),\n preserve_default=False,\n ),\n ]\n", "sub_path": "server/usuario/migrations/0002_usuario_avatar.py", "file_name": "0002_usuario_avatar.py", "file_ext": "py", "file_size_in_byte": 570, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 9, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 9, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 16, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 16, "usage_type": "name"}, {"api_name": "django.db.models.ImageField", "line_number": 19, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 19, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 19, "usage_type": "call"}, {"api_name": "django.utils.timezone.utc", "line_number": 19, "usage_type": "name"}]}
+{"seq_id": "480973488", "text": "from django.shortcuts import render, HttpResponse, redirect\nfrom time import gmtime, strftime\n\n\n# Create your views here.\n\n# '/' OR '/session_words'\ndef index(request):\n return render(request,'words/index.html')\n\n\n# '/session_words/add'\ndef add(request):\n if 'words' not in request.session:\n request.session['words'] = []\n\n if 'size' not in request.POST:\n size = 'small'\n else:\n size = request.POST['size']\n \n time = strftime(\"%I:%M:%S %p, %B %d %Y\", gmtime())\n\n wordslist = request.session['words']\n wordslist.append({\n 'word': request.POST['word'],\n 'color': request.POST['color'],\n 'size': size,\n 'time': time\n })\n request.session['words'] = wordslist\n return redirect('/session_words')\n\n\n# '/session_words/clear'\ndef clear(request):\n request.session['words'] = []\n return redirect('/session_words')", "sub_path": "apps/words/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 890, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "django.shortcuts.render", "line_number": 9, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 22, "usage_type": "call"}, {"api_name": "time.gmtime", "line_number": 22, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 32, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 38, "usage_type": "call"}]}
+{"seq_id": "283483950", "text": "from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^post$', views.post, name='post'),\n url(r'^confirm_remove/(?P\\d+)$', views.confirm, name='confirm'),\n url(r'^remove/(?P\\d+)$', views.remove, name='remove'),\n url(r'^course/(?P\\d+)$', views.comment, name='comment'),\n url(r'^comment/(?P\\d+)$', views.postComment, name='postComment'),\n]\n", "sub_path": "apps/courses/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 443, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "django.conf.urls.url", "line_number": 5, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 6, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 7, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 8, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 9, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 10, "usage_type": "call"}]}
+{"seq_id": "310122589", "text": "##xmlファイルを読み込み、解析\n#\"\"\" xmlを読み込んで、新しいxmlに圧縮した値を作成\nimport xml.etree.ElementTree as ET\n\nFILE = 'pic_ (1).xml'\nfile = open(FILE)\ntree = ET.parse(file)\nroot = tree.getroot()\n\nall_list = []\n\n# 画像ファイル名を取得\nimg_name = root.find('filename').text\n\n# 画像ファイルのサイズ(幅・高さ)を取得\nimg_size = root.find('size')\nimg_w = int(img_size.find('width').text)\nimg_h = int(img_size.find('height').text)\n\nfor obj in root.iter('object'):\n cls = obj.find('name').text\n xmlbox = obj.find('bndbox')\n xmin = int(xmlbox.find('xmin').text)\n ymin = int(xmlbox.find('ymin').text)\n xmax = int(xmlbox.find('xmax').text)\n ymax = int(xmlbox.find('ymax').text)\n\n all_list.append([img_name] + [cls])\n\nprint(all_list)\nprint(\"画像サイズ width = {}, height = {}\".format(img_w,img_h))\n\nstring_ = '''\\\n\n {}\n \n original\n original\n XXX\n 0\n \n \n 0\n ?\n \n \n {}\n {}\n 3\n \n \n'''\n\nsize_changed = 500#画像変更サイズ\nx_ = size_changed / img_w#X軸方方向の圧縮倍率\ny_ = size_changed / img_h#X軸方方向の圧縮倍率\n\nre_img_w = round(img_w * x_)\nre_img_h = round(img_h * y_)\nre_xmin = round(xmin * x_)\nre_ymin = round(ymin * y_)\nre_xmax = round(xmax * x_)\nre_ymax = round(ymax * y_)\nprint(re_img_w,re_img_h, re_xmin, re_ymin, re_xmax, re_ymax)\n\nwith open('_9_pic_ (1)_pressed_value.xml', 'w') as f:\n f.write(string_.format(img_name,re_img_w, re_img_h, re_xmin,re_ymin,re_xmax,re_ymax))\n", "sub_path": "Python_Make_xml/_9_End_To_End_original_xml_maker.py", "file_name": "_9_End_To_End_original_xml_maker.py", "file_ext": "py", "file_size_in_byte": 2128, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "xml.etree.ElementTree.parse", "line_number": 7, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 7, "usage_type": "name"}]}
+{"seq_id": "298593017", "text": "import pandas as pd\r\nimport numpy\r\nimport xlrd\r\n\r\ndef strip_punctuation(file):\r\n \r\n text = []\r\n punctuation_chars = [\"'\", '\"', \",\", \".\", \"!\", \":\", \";\", \"#\", \"@\", \"-\", \"(\", \")\", \"_\"]\r\n \r\n for list in file:\r\n for z in list:\r\n for y in punctuation_chars:\r\n if y in z:\r\n z = z.replace(y, '')\r\n text.append(z)\r\n\r\n tx = \" \".join(text)\r\n return tx.lower()\r\n\r\n\r\n\r\ndef get_pos(file):\r\n count = 0\r\n positive_word = []\r\n \r\n main_file = strip_punctuation(file)\r\n with open(r\"C:\\Users\\ankit\\OneDrive\\Desktop\\PYTHON\\PROJECT_SENTIMENT_ANALYSIS\\positivewords.txt\") as posi:\r\n for lin in posi:\r\n if lin[0] != ';' and lin[0] != '\\n':\r\n positive_word.append(lin.strip()) \r\n for i in main_file.split(\" \"):\r\n for j in positive_word:\r\n if (j==i):\r\n count+=1\r\n return count\r\n\r\n\r\n\r\n\r\ndef get_neg(file):\r\n count = 0\r\n negative_word = []\r\n main_file = strip_punctuation(file)\r\n \r\n with open(r\"C:\\Users\\ankit\\OneDrive\\Desktop\\PYTHON\\PROJECT_SENTIMENT_ANALYSIS\\negativewords.txt\") as negi:\r\n for lin in negi:\r\n if lin[0] != ';' and lin[0] != '\\n':\r\n negative_word.append(lin.strip())\r\n for i in main_file.split(\" \"): \r\n for j in negative_word: \r\n if j==i:\r\n count+=1\r\n return count\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef run(data):\r\n df = pd.DataFrame(columns=[\"Positive Score\", \"Negative Score\", \"Net Score\"])\r\n i = 1\r\n for sheet in data.sheets():\r\n list_of_lists=[]\r\n for row in range(sheet.nrows): \r\n for column in range (sheet.ncols):\r\n k = str(sheet.cell(row, column).value) \r\n line_list = k.split()\r\n list_of_lists.append(line_list)\r\n \r\n #Positive Score\r\n positive_score = get_pos(list_of_lists)\r\n \r\n #Negative Score\r\n negative_score = get_neg(list_of_lists)\r\n \r\n #Net Score\r\n net_score = positive_score - negative_score\r\n df.loc[i, ['Positive Score']] = positive_score\r\n df.loc[i, ['Negative Score']] = negative_score\r\n df.loc[i, ['Net Score']] = net_score \r\n i = i+1\r\n print(df)\r\n \r\nif __name__ == \"__main__\":\r\n \r\n data = xlrd.open_workbook(r\"C:\\Users\\ankit\\OneDrive\\Desktop\\PYTHON\\PROJECT_SENTIMENT_ANALYSIS\\sample_movie_data.xlsx\")\r\n run(data)\r\n ", "sub_path": "data_modification_new.py", "file_name": "data_modification_new.py", "file_ext": "py", "file_size_in_byte": 2520, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "pandas.DataFrame", "line_number": 62, "usage_type": "call"}, {"api_name": "xlrd.open_workbook", "line_number": 88, "usage_type": "call"}]}
+{"seq_id": "228419709", "text": "from django.contrib import admin\nfrom .models import ContactForm\n\n__author__ = \"Aniruddha Ravi\"\n__license__ = \"MIT\"\n__version__ = \"1.0.3\"\n__email__ = \"aniruddha.ravi@gmail.com\"\n__status__ = \"Development\"\n\n\nclass ContactFormAdmin(admin.ModelAdmin):\n class Meta:\n model = ContactForm\n\nadmin.site.register(ContactForm, ContactFormAdmin)\n", "sub_path": "mvp/contact/admin.py", "file_name": "admin.py", "file_ext": "py", "file_size_in_byte": 344, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "django.contrib.admin.ModelAdmin", "line_number": 11, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 11, "usage_type": "name"}, {"api_name": "models.ContactForm", "line_number": 13, "usage_type": "name"}, {"api_name": "django.contrib.admin.site.register", "line_number": 15, "usage_type": "call"}, {"api_name": "models.ContactForm", "line_number": 15, "usage_type": "argument"}, {"api_name": "django.contrib.admin.site", "line_number": 15, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 15, "usage_type": "name"}]}
+{"seq_id": "135635285", "text": "import configparser\nimport random\nimport string\nimport base64\n\nclass Salting():\n\n def read_salt_policy(self):\n # reads in password policy, returns variables as a list. Written by KW\n # password_policy = open('password_policy.txt', 'r')\n policy = configparser.ConfigParser()\n policy.read('password_policy.txt')\n salt_lowercase = policy.getint('Policy', 'salt_lowercase')\n salt_uppercase = policy.getint('Policy', 'salt_uppercase')\n salt_numbers = policy.getint('Policy', 'salt_numbers')\n\n return [int(salt_lowercase), int(salt_uppercase), int(salt_numbers)]\n\n\n def generate_salt(self):\n\n # reading through the password policy and looping through to extract necessary values to check and generates the password\n policy_checklist = self.read_salt_policy()\n max_length = sum(policy_checklist)\n\n # Generating the password using random and string modules\n salt = \"\"\n for character in range(max_length):\n\n random_character = random.randint(1,4)\n\n if random_character == 1:\n salt += random.choice(string.ascii_lowercase)\n elif random_character == 3:\n salt += random.choice(string.ascii_uppercase)\n else:\n salt += random.choice(string.digits)\n\n return salt\n\n def generate_base64_salt(self, salt):\n salt_64 = base64.b64encode(salt.encode())\n salt_final = salt_64.decode()\n #print(\"This is the final salt\" + salt_final)\n return salt_final\n", "sub_path": "Account-Generator/hashing/salting.py", "file_name": "salting.py", "file_ext": "py", "file_size_in_byte": 1559, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "configparser.ConfigParser", "line_number": 11, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 30, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 33, "usage_type": "call"}, {"api_name": "string.ascii_lowercase", "line_number": 33, "usage_type": "attribute"}, {"api_name": "random.choice", "line_number": 35, "usage_type": "call"}, {"api_name": "string.ascii_uppercase", "line_number": 35, "usage_type": "attribute"}, {"api_name": "random.choice", "line_number": 37, "usage_type": "call"}, {"api_name": "string.digits", "line_number": 37, "usage_type": "attribute"}, {"api_name": "base64.b64encode", "line_number": 42, "usage_type": "call"}]}
+{"seq_id": "478814717", "text": "# This file is part of the Trezor project.\n#\n# Copyright (C) 2012-2019 SatoshiLabs and contributors\n#\n# This library is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License version 3\n# as published by the Free Software Foundation.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the License along with this library.\n# If not, see .\n\nimport pytest\n\nfrom trezorlib import btc, messages, tools\n\nfrom .. import bip32\nfrom ..common import MNEMONIC12\n\n\nclass TestMsgGetaddressShow:\n @pytest.mark.setup_client(mnemonic=MNEMONIC12)\n def test_show(self, client):\n assert (\n btc.get_address(client, \"Bitcoin\", [1], show_display=True)\n == \"1CK7SJdcb8z9HuvVft3D91HLpLC6KSsGb\"\n )\n assert (\n btc.get_address(client, \"Bitcoin\", [2], show_display=True)\n == \"15AeAhtNJNKyowK8qPHwgpXkhsokzLtUpG\"\n )\n assert (\n btc.get_address(client, \"Bitcoin\", [3], show_display=True)\n == \"1CmzyJp9w3NafXMSEFH4SLYUPAVCSUrrJ5\"\n )\n\n @pytest.mark.multisig\n @pytest.mark.setup_client(mnemonic=MNEMONIC12)\n def test_show_multisig_3(self, client):\n node = bip32.deserialize(\n \"xpub661MyMwAqRbcF1zGijBb2K6x9YiJPh58xpcCeLvTxMX6spkY3PcpJ4ABcCyWfskq5DDxM3e6Ez5ePCqG5bnPUXR4wL8TZWyoDaUdiWW7bKy\"\n )\n multisig = messages.MultisigRedeemScriptType(\n pubkeys=[\n messages.HDNodePathType(node=node, address_n=[1]),\n messages.HDNodePathType(node=node, address_n=[2]),\n messages.HDNodePathType(node=node, address_n=[3]),\n ],\n signatures=[b\"\", b\"\", b\"\"],\n m=2,\n )\n\n for i in [1, 2, 3]:\n assert (\n btc.get_address(\n client, \"Bitcoin\", [i], show_display=True, multisig=multisig\n )\n == \"3E7GDtuHqnqPmDgwH59pVC7AvySiSkbibz\"\n )\n\n @pytest.mark.skip_t1\n @pytest.mark.multisig\n def test_show_multisig_xpubs(self, client):\n nodes = [\n btc.get_public_node(\n client, tools.parse_path(f\"48h/0h/{i}h\"), coin_name=\"Bitcoin\"\n )\n for i in range(3)\n ]\n multisig = messages.MultisigRedeemScriptType(\n nodes=[n.node for n in nodes],\n signatures=[b\"\", b\"\", b\"\"],\n address_n=[0, 0],\n m=2,\n )\n\n xpubs = [[n.xpub[i * 16 : (i + 1) * 16] for i in range(5)] for n in nodes]\n\n for i in range(3):\n\n def input_flow():\n yield # show address\n assert client.debug.wait_layout().lines == [\n \"Multisig 2 of 3\",\n \"34yJV2b2GtbmxfZNw\",\n \"jPyuyUYkUbUnogqa8\",\n ]\n\n client.debug.press_no()\n yield # show QR code\n assert client.debug.wait_layout().text.startswith(\"Qr\")\n\n client.debug.press_no()\n yield # show XPUB#1\n lines = client.debug.wait_layout().lines\n assert lines[0] == \"XPUB #1 \" + (\"(yours)\" if i == 0 else \"(others)\")\n assert lines[1:] == xpubs[0]\n # just for UI test\n client.debug.swipe_up()\n\n client.debug.press_no()\n yield # show XPUB#2\n lines = client.debug.wait_layout().lines\n assert lines[0] == \"XPUB #2 \" + (\"(yours)\" if i == 1 else \"(others)\")\n assert lines[1:] == xpubs[1]\n # just for UI test\n client.debug.swipe_up()\n\n client.debug.press_no()\n yield # show XPUB#3\n lines = client.debug.wait_layout().lines\n assert lines[0] == \"XPUB #3 \" + (\"(yours)\" if i == 2 else \"(others)\")\n assert lines[1:] == xpubs[2]\n # just for UI test\n client.debug.swipe_up()\n\n client.debug.press_yes()\n\n with client:\n client.set_input_flow(input_flow)\n btc.get_address(\n client,\n \"Bitcoin\",\n tools.parse_path(f\"48h/0h/{i}h/0/0\"),\n show_display=True,\n multisig=multisig,\n script_type=messages.InputScriptType.SPENDMULTISIG,\n )\n\n @pytest.mark.multisig\n @pytest.mark.setup_client(mnemonic=MNEMONIC12)\n def test_show_multisig_15(self, client):\n node = bip32.deserialize(\n \"xpub661MyMwAqRbcF1zGijBb2K6x9YiJPh58xpcCeLvTxMX6spkY3PcpJ4ABcCyWfskq5DDxM3e6Ez5ePCqG5bnPUXR4wL8TZWyoDaUdiWW7bKy\"\n )\n\n pubs = []\n for x in range(15):\n pubs.append(messages.HDNodePathType(node=node, address_n=[x]))\n\n multisig = messages.MultisigRedeemScriptType(\n pubkeys=pubs, signatures=[b\"\"] * 15, m=15\n )\n\n for i in range(15):\n assert (\n btc.get_address(\n client, \"Bitcoin\", [i], show_display=True, multisig=multisig\n )\n == \"3QaKF8zobqcqY8aS6nxCD5ZYdiRfL3RCmU\"\n )\n", "sub_path": "tests/device_tests/test_msg_getaddress_show.py", "file_name": "test_msg_getaddress_show.py", "file_ext": "py", "file_size_in_byte": 5514, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "trezorlib.btc.get_address", "line_number": 29, "usage_type": "call"}, {"api_name": "trezorlib.btc", "line_number": 29, "usage_type": "name"}, {"api_name": "trezorlib.btc.get_address", "line_number": 33, "usage_type": "call"}, {"api_name": "trezorlib.btc", "line_number": 33, "usage_type": "name"}, {"api_name": "trezorlib.btc.get_address", "line_number": 37, "usage_type": "call"}, {"api_name": "trezorlib.btc", "line_number": 37, "usage_type": "name"}, {"api_name": "pytest.mark.setup_client", "line_number": 26, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 26, "usage_type": "attribute"}, {"api_name": "common.MNEMONIC12", "line_number": 26, "usage_type": "name"}, {"api_name": "trezorlib.messages.MultisigRedeemScriptType", "line_number": 47, "usage_type": "call"}, {"api_name": "trezorlib.messages", "line_number": 47, "usage_type": "name"}, {"api_name": "trezorlib.messages.HDNodePathType", "line_number": 49, "usage_type": "call"}, {"api_name": "trezorlib.messages", "line_number": 49, "usage_type": "name"}, {"api_name": "trezorlib.messages.HDNodePathType", "line_number": 50, "usage_type": "call"}, {"api_name": "trezorlib.messages", "line_number": 50, "usage_type": "name"}, {"api_name": "trezorlib.messages.HDNodePathType", "line_number": 51, "usage_type": "call"}, {"api_name": "trezorlib.messages", "line_number": 51, "usage_type": "name"}, {"api_name": "trezorlib.btc.get_address", "line_number": 59, "usage_type": "call"}, {"api_name": "trezorlib.btc", "line_number": 59, "usage_type": "name"}, {"api_name": "pytest.mark", "line_number": 41, "usage_type": "attribute"}, {"api_name": "pytest.mark.setup_client", "line_number": 42, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 42, "usage_type": "attribute"}, {"api_name": "common.MNEMONIC12", "line_number": 42, "usage_type": "name"}, {"api_name": "trezorlib.btc.get_public_node", "line_number": 69, "usage_type": "call"}, {"api_name": "trezorlib.btc", "line_number": 69, "usage_type": "name"}, {"api_name": "trezorlib.tools.parse_path", "line_number": 70, "usage_type": "call"}, {"api_name": "trezorlib.tools", "line_number": 70, "usage_type": "name"}, {"api_name": "trezorlib.messages.MultisigRedeemScriptType", "line_number": 74, "usage_type": "call"}, {"api_name": "trezorlib.messages", "line_number": 74, "usage_type": "name"}, {"api_name": "trezorlib.btc.get_address", "line_number": 125, "usage_type": "call"}, {"api_name": "trezorlib.btc", "line_number": 125, "usage_type": "name"}, {"api_name": "trezorlib.tools.parse_path", "line_number": 128, "usage_type": "call"}, {"api_name": "trezorlib.tools", "line_number": 128, "usage_type": "name"}, {"api_name": "trezorlib.messages.InputScriptType", "line_number": 131, "usage_type": "attribute"}, {"api_name": "trezorlib.messages", "line_number": 131, "usage_type": "name"}, {"api_name": "pytest.mark", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 66, "usage_type": "attribute"}, {"api_name": "trezorlib.messages.HDNodePathType", "line_number": 143, "usage_type": "call"}, {"api_name": "trezorlib.messages", "line_number": 143, "usage_type": "name"}, {"api_name": "trezorlib.messages.MultisigRedeemScriptType", "line_number": 145, "usage_type": "call"}, {"api_name": "trezorlib.messages", "line_number": 145, "usage_type": "name"}, {"api_name": "trezorlib.btc.get_address", "line_number": 151, "usage_type": "call"}, {"api_name": "trezorlib.btc", "line_number": 151, "usage_type": "name"}, {"api_name": "pytest.mark", "line_number": 134, "usage_type": "attribute"}, {"api_name": "pytest.mark.setup_client", "line_number": 135, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 135, "usage_type": "attribute"}, {"api_name": "common.MNEMONIC12", "line_number": 135, "usage_type": "name"}]}
+{"seq_id": "94923814", "text": "# -*- coding: utf-8 -*-\n\nfrom django.db import transaction\nfrom django.db import connection\n\nfrom . import models\nimport reversion\n\n\nclass UserStoriesService(object):\n @transaction.atomic\n def bulk_insert(self, project, user, data, callback_on_success=None):\n items = filter(lambda s: len(s) > 0,\n map(lambda s: s.strip(), data.split(\"\\n\")))\n\n for item in items:\n obj = models.UserStory.objects.create(subject=item, project=project, owner=user,\n status=project.default_us_status)\n if callback_on_success:\n callback_on_success(obj, True)\n\n @transaction.atomic\n def bulk_update_order(self, project, user, data):\n cursor = connection.cursor()\n\n sql = \"\"\"\n prepare bulk_update_order as update userstories_userstory set \"order\" = $1\n where userstories_userstory.id = $2 and\n userstories_userstory.project_id = $3;\n \"\"\"\n\n cursor.execute(sql)\n for usid, usorder in data:\n cursor.execute(\"EXECUTE bulk_update_order (%s, %s, %s);\",\n (usorder, usid, project.id))\n cursor.close()\n", "sub_path": "taiga/projects/userstories/services.py", "file_name": "services.py", "file_ext": "py", "file_size_in_byte": 1214, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "django.db.transaction.atomic", "line_number": 11, "usage_type": "attribute"}, {"api_name": "django.db.transaction", "line_number": 11, "usage_type": "name"}, {"api_name": "django.db.connection.cursor", "line_number": 24, "usage_type": "call"}, {"api_name": "django.db.connection", "line_number": 24, "usage_type": "name"}, {"api_name": "django.db.transaction.atomic", "line_number": 22, "usage_type": "attribute"}, {"api_name": "django.db.transaction", "line_number": 22, "usage_type": "name"}]}
+{"seq_id": "362868462", "text": "from django.urls import path\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom . import views\n\nurlpatterns = [\n # General links\n path('', views.index, name='homepage'),\n path('contact/', views.contact, name='contact'),\n path('index/', views.index, name='homepage'),\n\n # Course-based links\n path(\n 'course/create/',\n views.CoursesCreate.as_view(),\n name='course_create'),\n path(\n 'course//',\n views.course_detail,\n name='course_detail'\n ),\n path(\n 'course//update/',\n views.CoursesUpdate.as_view(),\n name='course_update'\n ),\n path(\n 'course//delete/',\n views.CoursesDelete.as_view(),\n name='course_delete'\n ),\n\n # JAKE - PATH for Project Detailview\n path(\n 'course//addproject/',\n views.ProjectCreate,\n name='ProjectCreate'\n ),\n\n # PREV:\n path(\n 'assignment//',\n views.assignment_detail,\n name='assignment_detail'\n ),\n path(\n 'assignment//update/',\n views.ProjectUpdate,\n name='ProjectUpdate'\n ),\n\n\n path(\n 'assignment//addsubmission/',\n views.model_form_upload,\n name='model_form_upload'\n ),\n path(\n '/viewsubmission/',\n views.submission_detail,\n name='submission_detail'\n ),\n path(\n 'deletesubmission/',\n views.SubmissionDelete.as_view(),\n name='submission_delete'\n ),\n path(\n 'downloadsubmission/',\n views.submission_download,\n name='submission_download'\n ),\n\n\n # Invite-based links\n path(\n 'course/invite/',\n views.create_invite,\n name='invite_create'\n ),\n path(\n 'invite//delete/',\n views.InviteDelete.as_view(),\n name='invite_delete'\n ),\n path(\n 'email/',\n views.email,\n name='email'\n ),\n\n #JAMES - Links for Help pages\n path(\n 'help/instructor/',\n views.instructor_help,\n name='instructor_help'\n ),\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n", "sub_path": "autograder/personal/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 2315, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 13, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 17, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 22, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 27, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 34, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 41, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 46, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 53, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 58, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 63, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 68, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 76, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 81, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 86, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 93, "usage_type": "call"}, {"api_name": "django.conf.settings.DEBUG", "line_number": 100, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 100, "usage_type": "name"}, {"api_name": "django.conf.urls.static.static", "line_number": 101, "usage_type": "call"}, {"api_name": "django.conf.settings.MEDIA_URL", "line_number": 101, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 101, "usage_type": "name"}, {"api_name": "django.conf.settings.MEDIA_ROOT", "line_number": 101, "usage_type": "attribute"}]}
+{"seq_id": "423566631", "text": "from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"contacts/\", views.contacts, name=\"contact\"),\n path(\"contacts/edit/\", views.edit, name=\"edit\"),\n path(\"contacts/delete/\", views.delete, name=\"delete\"),\n\n]", "sub_path": "contactBookApp/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 293, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "django.urls.path", "line_number": 6, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}]}
+{"seq_id": "533562354", "text": "# -*- coding: utf-8 -*-\n'''\nJust a simple test routine for checking if the integration scheme works properly.\n\n'''\n\nimport unittest\nimport copy\nimport numpy as np\nimport scipy as sp\n\nimport amfe\n\n#%%\n\nclass DynamicalSystem():\n\n def __init__(self, K, M, f_ext):\n self.q = []\n self.t = []\n self.K_int = K\n self.M_int = M\n self.D_int = M*0\n self.f_ext = f_ext\n\n def S_and_res(self, q, dq, ddq, dt, t, beta, gamma):\n S = self.K_int + 1/(beta*dt**2)*self.M_int\n f_ext = self.f_ext(q, dq, t)\n res = self.M_int @ ddq + self.K_int @ q - f_ext\n return S, res, f_ext\n\n def K(self):\n return self.K_int\n\n def M(self):\n return self.M_int\n\n def D(self):\n return self.D_int\n\n def write_timestep(self, t, q):\n self.t.append(t)\n self.q.append(q)\n\n def clear_timesteps(self):\n pass\n\n\nclass IntegratorTest(unittest.TestCase):\n def setUp(self):\n c1 = 10\n c2 = 20\n c3 = 10\n c4 = 0\n K = np.array([[c1 + c2,-c2,0],\n [-c2 , c2 + c3, -c3],\n [0, -c3, c3 + c4]])\n\n M = np.diag([3,1,2])\n\n omega = 2*np.pi*1\n amplitude = 5\n def f_ext(q, dq, t):\n return np.array([0, 0., amplitude*np.cos(omega*t)])\n\n\n self.my_system = DynamicalSystem(K, M, f_ext)\n\n self.q_start = np.array([1, 0, 2.])*0\n self.dq_start = np.zeros_like(self.q_start)\n\n self.T = np.arange(0,5,0.05)\n\n def test_linear_vs_nonlinear_integrator(self):\n dt = 1E-3\n alpha = 0.1\n system1 = self.my_system\n system2 = copy.deepcopy(self.my_system)\n\n amfe.integrate_nonlinear_system(system1, self.q_start, self.dq_start,\n self.T, dt, alpha)\n\n amfe.integrate_linear_system(system2, self.q_start, self.dq_start,\n self.T, dt, alpha)\n\n q_nl = sp.array(system1.q)\n t_nl = sp.array(system1.t)\n q_lin = sp.array(system2.q)\n t_lin = sp.array(system2.t)\n np.testing.assert_allclose(t_nl, t_lin, atol=1E-10)\n # why does that work and below not?\n assert(np.any(np.abs(q_nl - q_lin) < 1E-3))\n # np.testing.assert_allclose(q_nl, q_lin, rtol=1E-1, atol=1E-4)\n return q_nl, q_lin, t_lin\n\nif __name__ == '__main__':\n my_integrator_test = IntegratorTest()\n my_integrator_test.setUp()\n q_nl, q_lin, t = my_integrator_test.test_linear_vs_nonlinear_integrator()\n from matplotlib import pyplot\n pyplot.plot(t, q_nl)\n pyplot.plot(t, q_lin)\n\n\n #%%", "sub_path": "tests/test_integrator.py", "file_name": "test_integrator.py", "file_ext": "py", "file_size_in_byte": 2627, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "unittest.TestCase", "line_number": 49, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 61, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 72, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 78, "usage_type": "call"}, {"api_name": "amfe.integrate_nonlinear_system", "line_number": 80, "usage_type": "call"}, {"api_name": "amfe.integrate_linear_system", "line_number": 83, "usage_type": "call"}, {"api_name": "scipy.array", "line_number": 86, "usage_type": "call"}, {"api_name": "scipy.array", "line_number": 87, "usage_type": "call"}, {"api_name": "scipy.array", "line_number": 88, "usage_type": "call"}, {"api_name": "scipy.array", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.testing.assert_allclose", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.testing", "line_number": 90, "usage_type": "attribute"}, {"api_name": "numpy.any", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 92, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 101, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 101, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 102, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 102, "usage_type": "name"}]}
+{"seq_id": "266795291", "text": "#!/usr/bin/python\n\n#This script takes a string and returns all permutations of it. \n#if you use perms.perms(\"apple\") you will get all permutations of Apple\n#in order to get all dictionary words, you will need to use perms.getRealWords(yourString)\n#Note that this is very processor intensive, so it is best to stick to 16 or fewer characters. \n#aeiousadfe\n\nimport itertools\n\n\ndef getPerms(somestring, length):\n return itertools.permutations(somestring, length)\n \ndef permsToList(allperms):\n listOfPerms=set()\n while allperms.next:\n try:\n tempstring=\"\"\n nextHolder=allperms.next()\n for charPOS in range(len(nextHolder)):\n tempstring=tempstring+nextHolder[charPOS]\n listOfPerms.add(tempstring)\n except StopIteration:\n break\n return listOfPerms\n\ndef perms(aString):\n allperms=[]\n for length in range(len(aString)+1):\n allperms.append(permsToList(getPerms(aString, length)))\n return allperms\n \ndef getWordList():\n words=set()\n wordFile=open('/home/jlmarks/words.txt','r')\n for word in wordFile:\n words.add(word[:-1])\n wordFile.close()\n return words\n \ndef getRealWords(aString):\n actualWords=set()\n words=getWordList()\n allPerms=perms(aString)\n for wordLength in range(1, len(allPerms)):\n actualWords=actualWords.union(words&allPerms[wordLength])\n return actualWords\n\ndef example():\n a=getRealWords(\"aeeiouysadtrghb\")\n", "sub_path": "scripts/python/anagrams/perms.py", "file_name": "perms.py", "file_ext": "py", "file_size_in_byte": 1480, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "itertools.permutations", "line_number": 13, "usage_type": "call"}]}
+{"seq_id": "78039832", "text": "#!/usr/bin/env python\n# framework for retrieving map related data through weewar API (www.weewar.com)\n# using minidom\n# written by Mike McConnell\n\nimport re\nimport sys\nimport urllib\nfrom xml.dom import minidom\n\n\nclass Map:\n\n def __init__(self, id):\n \"\"\"\n Processes a map through API.\n Takes one argument (map ID), and stores all map information provided\n through API. Also generates counts on terrain types, starting units\n (by player) and starting bases (by player).\n \"\"\"\n # make sure ID passed is integer\n self.id = self._validate_int(id)\n \n # import api url\n baseurl = 'http://weewar.com/api1/map/'\n apiurl = baseurl + str(id)\n try:\n self.map_dom = minidom.parse(urllib.urlopen(apiurl))\n except:\n print(\"Error. Bad map link.\")\n\n # set map variables\n self.name = self._get_str_from_tag(self.map_dom, 'name')\n self.initialCredits = self._get_int_from_tag(self.map_dom, 'initialCredits')\n self.perBaseCredits = self._get_int_from_tag(self.map_dom, 'perBaseCredits')\n self.width = self._get_int_from_tag(self.map_dom, 'width')\n self.height = self._get_int_from_tag(self.map_dom, 'height')\n self.maxPlayers = self._get_int_from_tag(self.map_dom, 'maxPlayers')\n self.url = self._get_str_from_tag(self.map_dom, 'url')\n self.thumbnail = self._get_str_from_tag(self.map_dom, 'thumbnail')\n self.preview = self._get_str_from_tag(self.map_dom, 'preview')\n self.revision = self._get_int_from_tag(self.map_dom, 'revision')\n self.creator = self._get_str_from_tag(self.map_dom, 'creator')\n self.creatorProfile = self._get_str_from_tag(self.map_dom, 'creatorProfile')\n\n # regex patterns for grabbing terrain information\n typepattern = re.compile('type=(\"[a-zA-Z]+\")')\n unitpattern = re.compile('startUnit=(\"[a-zA-Z]+\")')\n ownerpattern = re.compile('startUnitOwner=(\"[0-9]\")')\n factionpattern = re.compile('startFaction=(\"[0-9]\")')\n \n # create dictionary to hold all terrain information\n self.terrain = {}\n \n # create list of dictionaries to hold unit and base information\n self.unit = [{} for player in range(self.maxPlayers)]\n self.base = [{} for player in range(self.maxPlayers)]\n\n # for each hex on map, record terrain, unit and base (if present)\n for hex in self.map_dom.getElementsByTagName('terrain'):\n \n # format terrain type information\n cur_hex = hex.toxml()\n type = re.search(typepattern, cur_hex).group(0)\n type = self._strip_tag(type, 'type')\n \n # count terrain type into dictionary\n if self.terrain.has_key(type):\n self.terrain[type] = self.terrain[type] + 1\n else:\n self.terrain[type] = 1\n\n # add starting unit information (if present)\n if re.search(unitpattern, cur_hex) and \\\n re.search(ownerpattern, cur_hex):\n \n # format start unit information\n startunit = re.search(unitpattern, cur_hex).group(0)\n startunit = self._strip_tag(startunit, 'startUnit')\n startunitowner = re.search(ownerpattern, cur_hex).group(0)\n startunitowner = self._strip_tag(startunitowner, 'startUnitOwner')\n\n # make sure unit extracted is an integer\n owner = self._validate_int(startunitowner)\n \n # count unit type into player's dictionary\n if self.unit[owner].has_key(startunit):\n self.unit[owner][startunit] = self.unit[owner][startunit] + 1\n else:\n self.unit[owner][startunit] = 1\n\n # add starting base information (if present)\n if re.search(typepattern, cur_hex) and \\\n re.search(factionpattern, cur_hex):\n\n # format start base information\n startbase = re.search(typepattern, cur_hex).group(0)\n startbase = self._strip_tag(startbase, 'type')\n startbaseowner = re.search(factionpattern, cur_hex).group(0)\n startbaseowner = self._strip_tag(startbaseowner, 'startFaction')\n\n # make sure base extracted is an integer\n owner = self._validate_int(startbaseowner)\n\n # count base type into player's dictionary\n if self.base[owner].has_key(startbase):\n self.base[owner][startbase] = self.base[owner][startbase] + 1\n else:\n self.base[owner][startbase] = 1\n\n # calculate total number of terrain (for percentages)\n self.total_terrain = 0\n for amount in self.terrain.values():\n self.total_terrain = self.total_terrain + amount\n\n def get_terrain_count(self, type):\n \"\"\"\n Takes one argument (terrain type).\n Returns number of terrain units on map. If type does not exist, returns\n None.\n \"\"\"\n if self.terrain.has_key(type):\n return self.terrain[type]\n else:\n return None\n\n def get_terrain_percentage(self, type, format=False):\n \"\"\"\n Takes one argument (terrain type). Optional second argument will format\n results to percentage (0.1882 -> '18.82%').\n Returns percentage of terrain (compared to all terrain). If type does\n not exist, returns None.\n \"\"\"\n if self.terrain.has_key(type):\n if (format == False):\n return (float(self.terrain[type]) / self.total_terrain)\n else:\n return \"{0:.2f}%\".format(float(self.terrain[type]) / \n self.total_terrain * 100)\n else:\n return None\n\n def get_starting_unit(self, player):\n \"\"\"\n Takes one argument (player number; starts at 0).\n Returns dictionary containing units player starts with.\n \"\"\"\n if self._validate_int(player) != None:\n return self.unit[player]\n \n def get_starting_base(self, player):\n \"\"\"\n Takes one argument (player number; starts at 0).\n Returns dictionary containing units player starts with.\n \"\"\"\n if self._validate_int(player) != None:\n return self.base[player]\n\n def _get_str_from_tag(self, dom, tag, count=0):\n \"\"\"\n Takes tag in given position and strips out brackets.\n Does not handle non-ascii characters.\n Returns as string.\n \"\"\"\n attr = dom.getElementsByTagName(tag)[count].toxml()\n attr = attr.replace(('<' + tag + '>'),'').replace(('' + tag + '>'),'')\n try:\n return str(attr)\n except ValueError:\n print(attr, \"could not be formatted as string\")\n\n def _get_int_from_tag(self, dom, tag, count=0):\n \"\"\"\n Takes tag in given position and strips out brackets.\n Returns as integer.\n \"\"\"\n attr = dom.getElementsByTagName(tag)[count].toxml()\n attr = attr.replace(('<' + tag + '>'),'').replace(('' + tag + '>'),'')\n try:\n return int(attr)\n except ValueError:\n print(attr, \"could not be formatted as integer\")\n \n def _strip_tag(self, tag, text):\n \"\"\"\n Removes quotation marks and tag information for legibility. 'text' is\n xml variable name.\n Returns as string.\n \"\"\"\n return str(tag.replace('\"', \"\").replace(text + '=', \"\"))\n\n def _validate_int(self, value):\n \"\"\"\n Returns value as integer.\n \"\"\"\n try:\n value = int(value)\n except ValueError:\n print(value, \"is not an integer.\")\n \n return value\n", "sub_path": "weemap.py", "file_name": "weemap.py", "file_ext": "py", "file_size_in_byte": 7897, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "xml.dom.minidom.parse", "line_number": 28, "usage_type": "call"}, {"api_name": "xml.dom.minidom", "line_number": 28, "usage_type": "name"}, {"api_name": "urllib.urlopen", "line_number": 28, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 47, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 48, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 49, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 50, "usage_type": "call"}, {"api_name": "re.search", "line_number": 64, "usage_type": "call"}, {"api_name": "re.search", "line_number": 74, "usage_type": "call"}, {"api_name": "re.search", "line_number": 75, "usage_type": "call"}, {"api_name": "re.search", "line_number": 78, "usage_type": "call"}, {"api_name": "re.search", "line_number": 80, "usage_type": "call"}, {"api_name": "re.search", "line_number": 93, "usage_type": "call"}, {"api_name": "re.search", "line_number": 94, "usage_type": "call"}, {"api_name": "re.search", "line_number": 97, "usage_type": "call"}, {"api_name": "re.search", "line_number": 99, "usage_type": "call"}]}
+{"seq_id": "646945333", "text": "import os\nimport logging\nfrom common.get_path import BASIC_PATH\nfrom common.get_config import config_data\n\n\ndef login_info(name, level, log_name, lf_level, ls_level):\n log = logging.getLogger(name)\n log.setLevel(level)\n\n formats = \"%(asctime)s - [%(filename)s-->line:%(lineno)d] - %(levelname)s: %(message)s\"\n log_format = logging.Formatter(formats)\n\n lf = logging.FileHandler(os.path.join(BASIC_PATH, log_name), encoding=\"utf-8\")\n lf.setLevel(lf_level)\n log.addHandler(lf)\n lf.setFormatter(log_format)\n\n ls = logging.StreamHandler()\n ls.setLevel(ls_level)\n log.addHandler(ls)\n ls.setFormatter(log_format)\n\n return log\n\n\nlog = login_info(name=config_data.get(\"login\", \"name\"),\n level=config_data.get(\"login\", \"level\"),\n log_name=config_data.get(\"login\", \"log_name\"),\n lf_level=config_data.get(\"login\", \"fh_level\"),\n ls_level=config_data.get(\"login\", \"sh_level\"))\n\n\n", "sub_path": "common/login_info.py", "file_name": "login_info.py", "file_ext": "py", "file_size_in_byte": 916, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "logging.getLogger", "line_number": 8, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 12, "usage_type": "call"}, {"api_name": "logging.FileHandler", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 14, "usage_type": "call"}, {"api_name": "common.get_path.BASIC_PATH", "line_number": 14, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "logging.StreamHandler", "line_number": 19, "usage_type": "call"}, {"api_name": "common.get_config.config_data.get", "line_number": 27, "usage_type": "call"}, {"api_name": "common.get_config.config_data", "line_number": 27, "usage_type": "name"}, {"api_name": "common.get_config.config_data.get", "line_number": 28, "usage_type": "call"}, {"api_name": "common.get_config.config_data", "line_number": 28, "usage_type": "name"}, {"api_name": "common.get_config.config_data.get", "line_number": 29, "usage_type": "call"}, {"api_name": "common.get_config.config_data", "line_number": 29, "usage_type": "name"}, {"api_name": "common.get_config.config_data.get", "line_number": 30, "usage_type": "call"}, {"api_name": "common.get_config.config_data", "line_number": 30, "usage_type": "name"}, {"api_name": "common.get_config.config_data.get", "line_number": 31, "usage_type": "call"}, {"api_name": "common.get_config.config_data", "line_number": 31, "usage_type": "name"}]}
+{"seq_id": "309786625", "text": "from urllib.request import urlopen as http_req\nfrom urllib.request import Request\nfrom bs4 import BeautifulSoup as Soup\nfrom urllib import parse\nimport time\nimport sys\n\n\ndef get_soup(search_term, start):\n search_term = parse.quote_plus(search_term)\n url = f'https://www.google.dk/search?q={search_term}&start={start}'\n\n req = Request(url, data=None, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'})\n\n u_client = http_req(req)\n page_html = u_client.read()\n u_client.close()\n page_soup = Soup(page_html, \"html.parser\")\n results = page_soup.find(\"body\")\n return results\n\n\ndef check_anchor(href, site, start):\n if href.startswith(site):\n if start == 0:\n start = 1\n else:\n start = 1 + int((start / 10))\n print(f\"Search term found on page: {start}\")\n sys.exit()\n\n\ndef start_scraping(search_term, start, site):\n soup = get_soup(search_term, start)\n\n results = soup.findAll(\"div\", {\"class\": 'g'})\n\n for result in results:\n anchor = None\n if result is not None:\n anchor = result.find(\"div\")\n if anchor is not None:\n anchor = anchor.find(\"div\", {\"class\": 'rc'})\n if anchor is not None:\n anchor = anchor.find(\"div\", {\"class\": 'r'})\n if anchor is not None:\n anchor = anchor.find(\"a\")\n if anchor is not None:\n if anchor['href'] is not None:\n check_anchor(anchor['href'], site, start)\n\n if len(results) == 0:\n sys.exit(\"Your search was not found\")\n\n if len(results) != 0:\n print(\"Sleeping 15 seconds\")\n time.sleep(15)\n print(f\"Start: {start}\")\n start_scraping(search_term, start + 10, site)\n", "sub_path": "scrape.py", "file_name": "scrape.py", "file_ext": "py", "file_size_in_byte": 1817, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "urllib.parse.quote_plus", "line_number": 10, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 10, "usage_type": "name"}, {"api_name": "urllib.request.Request", "line_number": 13, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 15, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 18, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 30, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 53, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 57, "usage_type": "call"}]}
+{"seq_id": "336648626", "text": "from data_loader import DataLoader\nfrom itertools import permutations\n\nclass FullSwitchSet:\n @staticmethod\n def call(set, h):\n total_time = sum(x[0] for x in set)\n due_date = int(h * total_time)\n minn = min([\n (FullSwitchSet.eval_result(perm, due_date), perm) for perm in permutations(set)\n ])\n return minn[0], list(minn[1])\n\n @staticmethod\n def eval_result(set, due_date):\n current_time = 0\n total_penelty = 0\n for [len, early, late] in set:\n current_time += len\n if current_time < due_date:\n total_penelty += early * (due_date - current_time)\n else:\n total_penelty += late * (current_time - due_date)\n return total_penelty\n", "sub_path": "full_switch_set.py", "file_name": "full_switch_set.py", "file_ext": "py", "file_size_in_byte": 690, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "itertools.permutations", "line_number": 10, "usage_type": "call"}]}
+{"seq_id": "458888247", "text": "import json\nimport datetime\nfrom ast import literal_eval\n\ndef utc_diff(zone):\n m = zone%100\n h = zone//100\n return h *3600 + m * 60\n\ndef date_format(date):\n arr = date.split()\n date = \" \".join(arr[1:-1])\n zone = int(arr[-1])\n date_obj = datetime.datetime.strptime(date, '%d %b %Y %H:%M:%S')\n return date_obj, zone\n\ndef seconds_between(date1, date2):\n arr = []\n date1 = date1.replace(\"_\",\" \")\n date2 = date2.replace(\"_\",\" \")\n date_obj1, zone1 = date_format(date1)\n date_obj2, zone2 = date_format(date2)\n date_diff = int((date_obj1 - date_obj2).total_seconds())\n zone_diff = utc_diff(zone1) - utc_diff(zone2)\n arr.append(str(abs(date_diff - zone_diff)))\n \n return (json.dumps(arr))\n\n", "sub_path": "Task B/Seconds_between.py", "file_name": "Seconds_between.py", "file_ext": "py", "file_size_in_byte": 735, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "datetime.datetime.strptime", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 14, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 27, "usage_type": "call"}]}
+{"seq_id": "63570652", "text": "# DB 연결\nimport pymysql\n\nconn = pymysql.connect(\n # private key\n)\n\ncurs = conn.cursor()\nprint(type(curs))\n\nsql = '''\nCREATE TABLE stock (\nstockcode varchar(255),\nstockname varchar(255),\ntime DATETIME,\nprice varchar(255),\nrate varchar(255))\n'''\ncurs.execute(sql)\nconn.commit()\nconn.close()\n", "sub_path": "Stock_Data/db_stock.py", "file_name": "db_stock.py", "file_ext": "py", "file_size_in_byte": 293, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "pymysql.connect", "line_number": 4, "usage_type": "call"}]}
+{"seq_id": "303281341", "text": "from pprint import pprint\r\nimport boto3\r\nfrom boto3.dynamodb.conditions import Key, Attr\r\nimport argparse\r\nimport time\r\nfrom decimal import *\r\n\r\ndef scan_movies(YearToFind,GenreToFind):\r\n region=boto3.session.Session().region_name\r\n dynamodb = boto3.resource('dynamodb', region_name=region) #low-level Client\r\n table = dynamodb.Table('movies') #define which dynamodb table to access\r\n\r\n recordcount = 0\r\n recordscannedcount = 0\r\n\r\n scanreturn = table.scan( # perform first scan\r\n FilterExpression=Key('year').eq(YearToFind) & Attr(\"genre\").eq(GenreToFind)\r\n )\r\n recordcount += scanreturn['Count']\r\n recordscannedcount += scanreturn['ScannedCount']\r\n while 'LastEvaluatedKey' in scanreturn.keys(): # if lastevaluatedkey is present, we need to keep scanning and adding to our counts until everything is scanned\r\n scanreturn = table.scan(\r\n FilterExpression=Key('year').eq(YearToFind) & Attr(\"genre\").eq(GenreToFind),\r\n ExclusiveStartKey = scanreturn['LastEvaluatedKey']\r\n )\r\n recordcount += scanreturn['Count']\r\n recordscannedcount += scanreturn['ScannedCount']\r\n return [recordcount, recordscannedcount]\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"Qyear\", help=\"Search by year and genre.. will return number of movies with that year and genre\")\r\n parser.add_argument(\"Qgenre\", help=\"Search by year and genre.. will return number of movies with that year and genre\")\r\n args = parser.parse_args()\r\n queryyear = Decimal(args.Qyear)\r\n querygenre = (args.Qgenre) #section to collect argument from command line\r\n\r\n start = time.time()\r\n movies = scan_movies(queryyear, querygenre) #scan_movies returns our total counts as two items of a list\r\n end = time.time()\r\n print(\"Count is \", movies[0]) # print the count of items returned by the scan\r\n print(\"ScannedCount is \", movies[1]) # print the count of items that had to be scanned to process the scan\r\n print('Total time: {} sec'.format(end - start))\r\n", "sub_path": "lab_reference_scripts/MoviesScanYG.py", "file_name": "MoviesScanYG.py", "file_ext": "py", "file_size_in_byte": 2090, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "boto3.session.Session", "line_number": 9, "usage_type": "call"}, {"api_name": "boto3.session", "line_number": 9, "usage_type": "attribute"}, {"api_name": "boto3.resource", "line_number": 10, "usage_type": "call"}, {"api_name": "boto3.dynamodb.conditions.Key", "line_number": 17, "usage_type": "call"}, {"api_name": "boto3.dynamodb.conditions.Attr", "line_number": 17, "usage_type": "call"}, {"api_name": "boto3.dynamodb.conditions.Key", "line_number": 23, "usage_type": "call"}, {"api_name": "boto3.dynamodb.conditions.Attr", "line_number": 23, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 31, "usage_type": "call"}, {"api_name": "time.time", "line_number": 38, "usage_type": "call"}, {"api_name": "time.time", "line_number": 40, "usage_type": "call"}]}
+{"seq_id": "262659597", "text": "from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^kmeans/', views.kmeans, name='kmeans'),\n url(r'^extraction/', views.extraction, name='extraction'),\n url(r'^reinit/', views.reinit, name='reinit'),\n\n]", "sub_path": "SpamDetector/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 281, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "django.conf.urls.url", "line_number": 6, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 7, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 8, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 9, "usage_type": "call"}]}
+{"seq_id": "169627085", "text": "#\n# MIT License\n#\n# Copyright (c) 2020 Airbyte\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n\n\nimport json\nimport pathlib\nimport random\n\nimport requests\nfrom requests.auth import HTTPBasicAuth\n\n\ndef create():\n source_directory = pathlib.Path(__file__).resolve().parent.parent.parent\n configs_path = source_directory.joinpath(\"secrets/config.json\")\n with open(configs_path) as json_configs:\n configs = json.load(json_configs)\n auth = HTTPBasicAuth(configs.get(\"email\"), configs.get(\"api_token\"))\n base_api_url = f'https://{configs.get(\"domain\")}/rest/api/3/issue'\n\n headers = {\"Accept\": \"application/json\", \"Content-Type\": \"application/json\"}\n\n projects = [\"EX\", \"IT\", \"P2\", \"TESTKEY1\"]\n issue_types = [\"10001\", \"10002\", \"10004\"]\n\n for index in range(1, 76):\n payload = json.dumps(\n {\n \"fields\": {\n \"project\": {\"key\": random.choice(projects)},\n \"issuetype\": {\"id\": random.choice(issue_types)},\n \"summary\": f\"Test {index}\",\n \"description\": {\n \"type\": \"doc\",\n \"version\": 1,\n \"content\": [{\"type\": \"paragraph\", \"content\": [{\"type\": \"text\", \"text\": f\"Test description {index}\"}]}],\n },\n }\n }\n )\n\n requests.request(\"POST\", base_api_url, data=payload, headers=headers, auth=auth)\n\n\nif __name__ == \"__main__\":\n create()\n", "sub_path": "airbyte-integrations/connectors/source-jira/integration_tests/fixtures/create_issues.py", "file_name": "create_issues.py", "file_ext": "py", "file_size_in_byte": 2498, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "pathlib.Path", "line_number": 35, "usage_type": "call"}, {"api_name": "json.load", "line_number": 38, "usage_type": "call"}, {"api_name": "requests.auth.HTTPBasicAuth", "line_number": 39, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 48, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 51, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 52, "usage_type": "call"}, {"api_name": "requests.request", "line_number": 63, "usage_type": "call"}]}
+{"seq_id": "471464325", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\n# python\nimport base64\nimport re\nimport struct\nimport time\nimport urllib.parse\nfrom datetime import datetime, timedelta\nfrom dateutil.parser import parse as dateutil_parse\n\n# django and drf\nfrom django.contrib.auth import get_user_model\nfrom django.utils import translation\nfrom django.core.exceptions import ValidationError\nfrom django.conf import settings\nfrom django.core.urlresolvers import NoReverseMatch\nfrom django.db.models import Q\nfrom django.shortcuts import get_object_or_404\nfrom django.utils.translation import ugettext_lazy as _\nfrom rest_framework import (\n serializers, relations, viewsets, filters, generics, status\n)\nfrom rest_framework.settings import api_settings\nfrom rest_framework.reverse import reverse\nfrom rest_framework.response import Response\nfrom rest_framework.exceptions import ParseError\n\n\n# 3rd party\nfrom isodate import Duration, duration_isoformat, parse_duration\nfrom modeltranslation.translator import translator, NotRegistered\nfrom haystack.query import AutoQuery\nfrom munigeo.api import (\n GeoModelSerializer, GeoModelAPIView, build_bbox_filter, srid_to_srs\n)\nimport pytz\n\n# events\nfrom events import utils\nfrom events.custom_elasticsearch_search_backend import (\n CustomEsSearchQuerySet as SearchQuerySet\n)\nfrom events.models import (\n Place, Event, Keyword, Language, OpeningHoursSpecification, EventLink,\n Offer, DataSource, Organization \n)\nfrom events.translation import EventTranslationOptions\n\n\nSYSTEM_DATA_SOURCE_ID = 'system'\n\n\nserializers_by_model = {}\n\nall_views = []\ndef register_view(klass, name, base_name=None):\n entry = {'class': klass, 'name': name}\n if base_name is not None:\n entry['base_name'] = base_name\n all_views.append(entry)\n\n if klass.serializer_class and \\\n hasattr(klass.serializer_class, 'Meta') and \\\n hasattr(klass.serializer_class.Meta, 'model'):\n model = klass.serializer_class.Meta.model\n serializers_by_model[model] = klass.serializer_class\n\n\ndef urlquote_id(link):\n \"\"\"\n URL quote link's id part, e.g.\n http://127.0.0.1:8000/v0.1/place/tprek:20879/\n -->\n http://127.0.0.1:8000/v0.1/place/tprek%3A20879/\n This is DRF backwards compatibility function, 2.x quoted id automatically.\n\n :param link: URL str\n :return: quoted URL str\n \"\"\"\n if isinstance(link, str):\n parts = link.split('/')\n if len(parts) > 1 and ':' in parts[-2]:\n parts[-2] = urllib.parse.quote(parts[-2])\n link = '/'.join(parts)\n return link\n\n\ndef generate_id(namespace):\n t = time.time() * 1000\n postfix = base64.b32encode(struct.pack(\">Q\", int(t)).lstrip(b'\\x00'))\n postfix = postfix.strip(b'=').lower().decode(encoding='UTF-8')\n return '{}:{}'.format(namespace, postfix)\n\ndef parse_id_from_uri(uri):\n \"\"\"\n Parse id part from @id uri like\n 'http://127.0.0.1:8000/v0.1/event/matko%3A666/' -> 'matko:666'\n :param uri: str\n :return: str id\n \"\"\"\n if not uri.startswith('http'):\n return uri\n path = urllib.parse.urlparse(uri).path\n _id = path.rstrip('/').split('/')[-1]\n _id = urllib.parse.unquote(_id)\n return _id\n\ndef perform_id_magic_for(data):\n if 'id' in data:\n err = \"Do not send 'id' when POSTing a new Event (got id='{}')\"\n raise ParseError(err.format(data['id']))\n data['id'] = generate_id(data['data_source'])\n return data\n\n\nclass JSONLDRelatedField(relations.HyperlinkedRelatedField):\n \"\"\"\n Support of showing and saving of expanded JSON nesting or just a resource\n URL.\n Serializing is controlled by query string param 'expand', deserialization\n by format of JSON given.\n\n Default serializing is expand=true.\n \"\"\"\n\n invalid_json_error = _('Incorrect JSON. Expected JSON, received %s.')\n\n def __init__(self, *args, **kwargs):\n self.related_serializer = kwargs.pop('serializer', None)\n self.hide_ld_context = kwargs.pop('hide_ld_context', False)\n super(JSONLDRelatedField, self).__init__(*args, **kwargs)\n\n def use_pk_only_optimization(self):\n if self.is_expanded():\n return False\n else:\n return True\n\n def to_representation(self, obj):\n if isinstance(self.related_serializer, str):\n self.related_serializer = globals().get(self.related_serializer, None)\n if self.is_expanded():\n return self.related_serializer(obj, hide_ld_context=self.hide_ld_context,\n context=self.context).data\n link = super(JSONLDRelatedField, self).to_representation(obj)\n link = urlquote_id(link)\n return {\n '@id': link\n }\n\n def to_internal_value(self, value):\n if '@id' in value:\n return super(JSONLDRelatedField, self).to_internal_value(value['@id'])\n else:\n raise ValidationError(\n self.invalid_json_error % type(value).__name__)\n\n def is_expanded(self):\n return getattr(self, 'expanded', False)\n\n\nclass EnumChoiceField(serializers.Field):\n \"\"\"\n Database value of tinyint is converted to and from a string representation\n of choice field.\n\n TODO: Find if there's standardized way to render Schema.org enumeration\n instances in JSON-LD.\n \"\"\"\n\n def __init__(self, choices, prefix=''):\n self.choices = choices\n self.prefix = prefix\n super(EnumChoiceField, self).__init__()\n\n def to_representation(self, obj):\n if obj is None:\n return None\n return self.prefix + utils.get_value_from_tuple_list(self.choices,\n obj, 1)\n\n def to_internal_value(self, data):\n return utils.get_value_from_tuple_list(self.choices,\n self.prefix + str(data), 0)\n\n\nclass ISO8601DurationField(serializers.Field):\n\n def to_representation(self, obj):\n if obj:\n d = Duration(milliseconds=obj)\n return duration_isoformat(d)\n else:\n return None\n\n def to_internal_value(self, data):\n if data:\n value = parse_duration(data)\n return (\n value.days * 24 * 3600 * 1000000\n + value.seconds * 1000\n + value.microseconds / 1000\n )\n else:\n return 0\n\n\nclass MPTTModelSerializer(serializers.ModelSerializer):\n def __init__(self, *args, **kwargs):\n super(MPTTModelSerializer, self).__init__(*args, **kwargs)\n for field_name in 'lft', 'rght', 'tree_id', 'level':\n if field_name in self.fields:\n del self.fields[field_name]\n\n\nclass TranslatedModelSerializer(serializers.ModelSerializer):\n def __init__(self, *args, **kwargs):\n super(TranslatedModelSerializer, self).__init__(*args, **kwargs)\n model = self.Meta.model\n try:\n trans_opts = translator.get_options_for_model(model)\n except NotRegistered:\n self.translated_fields = []\n return\n\n self.translated_fields = trans_opts.fields.keys()\n lang_codes = [x[0] for x in settings.LANGUAGES]\n # Remove the pre-existing data in the bundle.\n for field_name in self.translated_fields:\n for lang in lang_codes:\n key = \"%s_%s\" % (field_name, lang)\n if key in self.fields:\n del self.fields[key]\n del self.fields[field_name]\n\n # def get_field(self, model_field):\n # kwargs = {}\n # if issubclass(\n # model_field.__class__,\n # (django_db_models.CharField,\n # django_db_models.TextField)):\n # if model_field.null:\n # kwargs['allow_none'] = True\n # kwargs['max_length'] = getattr(model_field, 'max_length')\n # return fields.CharField(**kwargs)\n # return super(TranslatedModelSerializer, self).get_field(model_field)\n\n def to_representation(self, obj):\n ret = super(TranslatedModelSerializer, self).to_representation(obj)\n if obj is None:\n return ret\n return self.translated_fields_to_representation(obj, ret)\n\n def to_internal_value(self, data):\n \"\"\"\n Convert complex translated json objects to flat format.\n E.g. json structure containing `name` key like this:\n {\n \"name\": {\n \"fi\": \"musiikkiklubit\",\n \"sv\": \"musikklubbar\",\n \"en\": \"music clubs\"\n },\n ...\n }\n Transforms this:\n {\n \"name\": \"musiikkiklubit\",\n \"name_fi\": \"musiikkiklubit\",\n \"name_sv\": \"musikklubbar\",\n \"name_en\": \"music clubs\"\n ...\n }\n :param data:\n :return:\n \"\"\"\n lang = settings.LANGUAGES[0][0]\n for field_name in self.translated_fields:\n # FIXME: handle default lang like others!?\n lang = settings.LANGUAGES[0][0] # Handle default lang\n if data.get(field_name, None) is None:\n continue\n values = data[field_name].copy() # Save original values\n\n key = \"%s_%s\" % (field_name, lang)\n val = data[field_name].get(lang)\n if val:\n values[key] = val # field_name_LANG\n values[field_name] = val # field_name\n if lang in values:\n del values[lang] # Remove original key LANG\n for lang in [x[0] for x in settings.LANGUAGES[1:]]:\n key = \"%s_%s\" % (field_name, lang)\n val = data[field_name].get(lang)\n if val:\n values[key] = val # field_name_LANG\n values[field_name] = val # field_name\n if lang in values:\n del values[lang] # Remove original key LANG\n data.update(values)\n del data[field_name] # Remove original field_name from data\n\n # do remember to call the super class method as well!\n data.update(super().to_internal_value(data))\n\n return data\n\n def translated_fields_to_representation(self, obj, ret):\n for field_name in self.translated_fields:\n d = {}\n default_lang = settings.LANGUAGES[0][0]\n d[default_lang] = getattr(obj, field_name)\n for lang in [x[0] for x in settings.LANGUAGES[1:]]:\n key = \"%s_%s\" % (field_name, lang) \n val = getattr(obj, key, None)\n if val == None:\n continue \n d[lang] = val\n\n # If no text provided, leave the field as null\n for key, val in d.items():\n if val != None:\n break\n else:\n d = None\n ret[field_name] = d\n\n return ret\n\n\nclass LinkedEventsSerializer(TranslatedModelSerializer, MPTTModelSerializer):\n \"\"\"Serializer with the support for JSON-LD/Schema.org.\n\n JSON-LD/Schema.org syntax::\n\n {\n \"@context\": \"http://schema.org\",\n \"@type\": \"Event\",\n \"name\": \"Event name\",\n ...\n }\n\n See full example at: http://schema.org/Event\n\n Args:\n hide_ld_context (bool):\n Hides `@context` from JSON, can be used in nested\n serializers\n \"\"\"\n\n def __init__(self, instance=None, files=None,\n context=None, partial=False, many=None,\n allow_add_remove=False, hide_ld_context=False, **kwargs):\n super(LinkedEventsSerializer, self).__init__(\n instance=instance, context=context, **kwargs)\n if 'created_by' in self.fields:\n del self.fields['created_by']\n if 'modified_by' in self.fields:\n del self.fields['modified_by']\n\n if context is not None:\n include_fields = context.get('include', [])\n for field_name in include_fields:\n if not field_name in self.fields:\n continue\n field = self.fields[field_name]\n if isinstance(field, relations.ManyRelatedField):\n field = field.child_relation\n if not isinstance(field, JSONLDRelatedField):\n continue\n field.expanded = True\n\n self.hide_ld_context = hide_ld_context\n\n self.disable_camelcase = True\n if self.context and 'request' in self.context:\n request = self.context['request']\n if 'disable_camelcase' in request.QUERY_PARAMS:\n self.disable_camelcase = True\n\n def to_representation(self, obj):\n \"\"\"\n Before sending to renderer there's a need to do additional work on\n to-be-JSON dictionary data:\n 1. Add @context, @type and @id fields\n 2. Convert field names to camelCase\n Renderer is the right place for this but now loop is done just once.\n Reversal conversion is done in parser.\n \"\"\"\n ret = super(LinkedEventsSerializer, self).to_representation(obj)\n if 'id' in ret and 'request' in self.context:\n try:\n ret['@id'] = reverse(self.view_name,\n kwargs={u'pk': ret['id']},\n request=self.context['request'])\n except NoReverseMatch:\n ret['@id'] = str(ret['id'])\n ret['@id'] = urlquote_id(ret['@id'])\n\n # Context is hidden if:\n # 1) hide_ld_context is set to True\n # 2) self.object is None, e.g. we are in the list of stuff\n if not self.hide_ld_context and self.instance is not None:\n if hasattr(obj, 'jsonld_context') \\\n and isinstance(obj.jsonld_context, (dict, list)):\n ret['@context'] = obj.jsonld_context\n else:\n ret['@context'] = 'http://schema.org'\n\n # Use jsonld_type attribute if present,\n # if not fallback to automatic resolution by model name.\n # Note: Plan 'type' could be aliased to @type in context definition to\n # conform JSON-LD spec.\n if hasattr(obj, 'jsonld_type'):\n ret['@type'] = obj.jsonld_type\n else:\n ret['@type'] = obj.__class__.__name__\n\n return ret\n\n\ndef _clean_qp(query_params):\n \"\"\"\n Strip 'event.' prefix from all query params.\n :rtype : QueryDict\n :param query_params: dict self.request.QUERY_PARAMS\n :return: QueryDict QUERY_PARAMS\n \"\"\"\n query_params = query_params.copy() # do not alter original dict\n nspace = 'event.'\n for key in query_params.keys():\n if key.startswith(nspace):\n new_key = key[len(nspace):]\n # .pop() returns a list(?), don't use\n # query_params[new_key] = query_params.pop(key)\n query_params[new_key] = query_params[key]\n del query_params[key]\n return query_params\n\n\nclass KeywordSerializer(LinkedEventsSerializer):\n view_name = 'keyword-detail'\n\n class Meta:\n model = Keyword\n\n\nclass KeywordViewSet(viewsets.ReadOnlyModelViewSet):\n queryset = Keyword.objects.all()\n serializer_class = KeywordSerializer\n\n def get_queryset(self):\n \"\"\"\n Return Keyword queryset. If request has parameter show_all_keywords=1\n all Keywords are returned, otherwise only which have events.\n Additional query parameters:\n event.data_source\n event.start\n event.end\n \"\"\"\n queryset = Keyword.objects.all()\n if self.request.QUERY_PARAMS.get('show_all_keywords'):\n # Limit by data_source anyway, if it is set\n data_source = self.request.QUERY_PARAMS.get('data_source')\n if data_source:\n data_source = data_source.lower()\n queryset = queryset.filter(data_source=data_source)\n else:\n events = Event.objects.all()\n params = _clean_qp(self.request.QUERY_PARAMS)\n events = _filter_event_queryset(events, params)\n keyword_ids = events.values_list('keywords',\n flat=True).distinct().order_by()\n queryset = queryset.filter(id__in=keyword_ids)\n # Optionally filter keywords by filter parameter,\n # can be used e.g. with typeahead.js\n val = self.request.QUERY_PARAMS.get('filter')\n if val:\n queryset = queryset.filter(name__startswith=val)\n return queryset\n\nregister_view(KeywordViewSet, 'keyword')\n\n\nclass PlaceSerializer(LinkedEventsSerializer, GeoModelSerializer):\n view_name = 'place-detail'\n\n class Meta:\n model = Place\n\n\nclass PlaceViewSet(GeoModelAPIView, viewsets.ReadOnlyModelViewSet):\n queryset = Place.objects.all()\n serializer_class = PlaceSerializer\n\n def get_queryset(self):\n \"\"\"\n Return Place queryset. If request has parameter show_all_places=1\n all Places are returned, otherwise only which have events.\n Additional query parameters:\n event.data_source\n event.start\n event.end\n \"\"\"\n queryset = Place.objects.all()\n if self.request.QUERY_PARAMS.get('show_all_places'):\n pass\n else:\n events = Event.objects.all()\n params = _clean_qp(self.request.QUERY_PARAMS)\n events = _filter_event_queryset(events, params)\n location_ids = events.values_list('location_id',\n flat=True).distinct().order_by()\n queryset = queryset.filter(id__in=location_ids)\n return queryset\n\nregister_view(PlaceViewSet, 'place')\n\n\nclass OpeningHoursSpecificationSerializer(LinkedEventsSerializer):\n class Meta:\n model = OpeningHoursSpecification\n\n\nclass LanguageSerializer(LinkedEventsSerializer):\n view_name = 'language-detail'\n\n class Meta:\n model = Language\n\n\nclass LanguageViewSet(viewsets.ReadOnlyModelViewSet):\n queryset = Language.objects.all()\n serializer_class = LanguageSerializer\n\nregister_view(LanguageViewSet, 'language')\n\nLOCAL_TZ = pytz.timezone(settings.TIME_ZONE)\n\nclass EventLinkSerializer(serializers.ModelSerializer):\n def to_representation(self, obj):\n ret = super(EventLinkSerializer, self).to_representation(obj)\n if not ret['name']:\n ret['name'] = None\n return ret\n\n class Meta:\n model = EventLink\n exclude = ['id', 'event']\n\nclass OfferSerializer(TranslatedModelSerializer):\n class Meta:\n model = Offer\n exclude = ['id', 'event']\n\n\nclass EventSerializer(LinkedEventsSerializer, GeoModelAPIView):\n location = JSONLDRelatedField(serializer=PlaceSerializer, required=False,\n view_name='place-detail', read_only=True)\n # provider = OrganizationSerializer(hide_ld_context=True)\n keywords = JSONLDRelatedField(serializer=KeywordSerializer, many=True,\n required=False,\n view_name='keyword-detail', read_only=True)\n super_event = JSONLDRelatedField(required=False, view_name='event-detail',\n read_only=True)\n event_status = EnumChoiceField(Event.STATUSES)\n external_links = EventLinkSerializer(many=True)\n offers = OfferSerializer(many=True)\n sub_events = JSONLDRelatedField(serializer='EventSerializer',\n required=False, view_name='event-detail',\n many=True, read_only=True)\n\n view_name = 'event-detail'\n\n def __init__(self, *args, skip_empties=False, skip_fields=set(), **kwargs):\n super(EventSerializer, self).__init__(*args, **kwargs)\n # The following can be used when serializing when\n # testing and debugging.\n self.skip_empties = skip_empties\n self.skip_fields = skip_fields\n\n def get_location(self, data):\n \"\"\"\n Replace location id dict in data with a Place object\n \"\"\"\n location = data.get('location')\n if location and '@id' in location:\n location_id = parse_id_from_uri(location['@id'])\n try:\n data['location'] = Place.objects.get(id=location_id)\n except Place.DoesNotExist:\n err = 'Place with id {} does not exist'\n raise ParseError(err.format(location_id))\n return data\n\n def get_keywords(self, data):\n \"\"\"\n Replace list of keyword dicts in data with a list of Keyword objects\n \"\"\"\n new_kw = []\n\n for kw in data.get('keywords', []):\n\n if '@id' in kw:\n kw_id = parse_id_from_uri(kw['@id'])\n\n try:\n keyword = Keyword.objects.get(id=kw_id)\n except Keyword.DoesNotExist:\n err = 'Keyword with id {} does not exist'\n raise ParseError(err.format(kw_id))\n\n new_kw.append(keyword)\n\n data['keywords'] = new_kw\n return data\n\n def get_datetimes(self, data):\n for field in ['date_published', 'start_time', 'end_time']:\n val = data.get(field, None)\n if val:\n if isinstance(val, str):\n data[field] = parse_time(val, True)\n return data\n\n def to_internal_value(self, data):\n data = super().to_internal_value(data)\n\n # TODO: figure out how to get this via JSONLDRelatedField\n if 'location' in data:\n location_id = parse_id_from_uri(data['location']['@id'])\n data['location'] = Place.objects.get(id=location_id)\n\n # TODO: figure out how to get these via JSONLDRelatedField\n data = self.get_keywords(data)\n\n return data\n\n def create(self, validated_data):\n offers = validated_data.pop('offers', [])\n links = validated_data.pop('external_links', [])\n keywords = validated_data.pop('keywords', [])\n\n # create object\n e = Event.objects.create(**validated_data)\n\n # create and add related objects \n for offer in offers:\n Offer.objects.create(event=e, **offer)\n for link in links:\n EventLink.objects.create(event=e, **link)\n e.keywords.add(*keywords)\n\n return e\n\n def update(self, instance, validated_data):\n\n # prepare a list of fields to be updated\n update_fields = [\n 'start_time', 'end_time', 'location'\n ]\n\n languages = [x[0] for x in settings.LANGUAGES]\n for field in EventTranslationOptions.fields:\n for lang in languages:\n update_fields.append(field + '_' + lang)\n\n # update values\n for field in update_fields:\n orig_value = getattr(instance, field)\n new_value = validated_data.get(field, orig_value)\n setattr(instance, field, new_value)\n\n # also update `has_end_time` if needed\n if instance.end_time:\n instance.has_end_time = True\n\n # save changes\n instance.save()\n\n # update offers\n if 'offers' in validated_data:\n instance.offers.all().delete()\n for offer in validated_data.get('offers', []):\n Offer.objects.create(event=instance, **offer)\n\n # update ext links\n if 'external_links' in validated_data:\n instance.external_links.all().delete()\n for link in validated_data.get('external_links', []):\n EventLink.objects.create(event=instance, **link)\n\n # update keywords\n instance.keywords.clear() \n instance.keywords.add(*validated_data['keywords'])\n\n return instance\n\n def to_representation(self, obj):\n ret = super(EventSerializer, self).to_representation(obj)\n if 'start_time' in ret and not obj.has_start_time:\n # Return only the date part\n ret['start_time'] = obj.start_time.astimezone(LOCAL_TZ).strftime('%Y-%m-%d')\n if 'end_time' in ret and not obj.has_end_time:\n # If we're storing only the date part, do not pretend we have the exact time.\n if obj.end_time - obj.start_time <= timedelta(days=1):\n ret['end_time'] = None\n if hasattr(obj, 'days_left'):\n ret['days_left'] = int(obj.days_left)\n if self.skip_empties:\n for k in list(ret.keys()):\n val = ret[k]\n try:\n if val is None or len(val) == 0:\n del ret[k]\n except TypeError:\n # not list/dict\n pass\n for field in self.skip_fields:\n del ret[field]\n return ret\n\n class Meta:\n model = Event\n exclude = ['has_start_time', 'has_end_time', 'is_recurring_super']\n\n\ndef parse_time(time_str, is_start):\n time_str = time_str.strip()\n # Handle dates first. Assume dates are given in local timezone.\n # FIXME: What if there's no local timezone?\n try:\n dt = datetime.strptime(time_str, '%Y-%m-%d')\n dt = LOCAL_TZ.localize(dt)\n except ValueError:\n dt = None\n if not dt:\n if time_str.lower() == 'today':\n dt = datetime.utcnow().replace(tzinfo=pytz.utc)\n dt = dt.astimezone(LOCAL_TZ)\n dt = dt.replace(hour=0, minute=0, second=0, microsecond=0)\n if dt:\n # With start timestamps, we treat dates as beginning\n # at midnight the same day. End timestamps are taken to\n # mean midnight on the following day.\n if not is_start:\n dt = dt + timedelta(days=1)\n else:\n try:\n # Handle all other times through dateutil.\n dt = dateutil_parse(time_str)\n except (TypeError, ValueError):\n raise ParseError('time in invalid format (try ISO 8601 or yyyy-mm-dd)')\n return dt\n\n\nclass JSONAPIViewSet(viewsets.ReadOnlyModelViewSet):\n def initial(self, request, *args, **kwargs):\n ret = super(JSONAPIViewSet, self).initial(request, *args, **kwargs)\n self.srs = srid_to_srs(self.request.QUERY_PARAMS.get('srid', None))\n return ret\n\n def get_serializer_context(self):\n context = super(JSONAPIViewSet, self).get_serializer_context()\n\n include = self.request.QUERY_PARAMS.get('include', '')\n context['include'] = [x.strip() for x in include.split(',') if x]\n context['srs'] = self.srs\n\n return context\n\n\nclass LinkedEventsOrderingFilter(filters.OrderingFilter):\n ordering_param = 'sort'\n\n\nclass EventOrderingFilter(LinkedEventsOrderingFilter):\n def filter_queryset(self, request, queryset, view):\n queryset = super(EventOrderingFilter, self).filter_queryset(request, queryset, view)\n ordering = self.get_ordering(request, queryset, view)\n if not ordering:\n ordering = []\n if 'days_left' in [x.lstrip('-') for x in ordering]:\n queryset = queryset.extra(select={'days_left': 'date_part(\\'day\\', end_time - start_time)'})\n return queryset\n\n\ndef parse_duration(duration):\n m = re.match(r'(\\d+)\\s*(d|h|m|s)?$', duration.strip().lower())\n if not m:\n raise ParseError(\"Invalid duration supplied. Try '1d' or '2h'.\")\n val, unit = m.groups()\n if not unit:\n unit = 's'\n\n if unit == 'm':\n mul = 60\n elif unit == 'h':\n mul = 3600\n elif unit == 'd':\n mul = 24 * 3600\n\n return int(val) * mul\n\ndef _filter_event_queryset(queryset, params, srs=None):\n \"\"\"\n Filter events queryset by params\n (e.g. self.request.QUERY_PARAMS in EventViewSet)\n \"\"\"\n # Filter by string (case insensitive). This searches from all fields\n # which are marked translatable in translation.py\n val = params.get('text', None)\n if val:\n val = val.lower()\n # Free string search from all translated fields\n fields = EventTranslationOptions.fields\n # and these languages\n languages = [x[0] for x in settings.LANGUAGES]\n qset = Q()\n for field in fields:\n for lang in languages:\n kwarg = {field + '_' + lang + '__icontains': val}\n qset |= Q(**kwarg)\n queryset = queryset.filter(qset)\n\n val = params.get('last_modified_since', None)\n # This should be in format which dateutil.parser recognizes, e.g.\n # 2014-10-29T12:00:00Z == 2014-10-29T12:00:00+0000 (UTC time)\n # or 2014-10-29T12:00:00+0200 (local time)\n if val:\n dt = parse_time(val, is_start=False)\n queryset = queryset.filter(Q(last_modified_time__gte=dt))\n\n val = params.get('start', None)\n if val:\n dt = parse_time(val, is_start=True)\n queryset = queryset.filter(Q(end_time__gt=dt) | Q(start_time__gte=dt))\n\n val = params.get('end', None)\n if val:\n dt = parse_time(val, is_start=False)\n queryset = queryset.filter(Q(end_time__lt=dt) | Q(start_time__lte=dt))\n\n val = params.get('bbox', None)\n if val:\n bbox_filter = build_bbox_filter(srs, val, 'position')\n places = Place.geo_objects.filter(**bbox_filter)\n queryset = queryset.filter(location__in=places)\n\n val = params.get('data_source', None)\n if val:\n queryset = queryset.filter(data_source=val)\n\n # Filter by location id, multiple ids separated by comma\n val = params.get('location', None)\n if val:\n val = val.split(',')\n queryset = queryset.filter(location_id__in=val)\n\n # Filter by keyword id, multiple ids separated by comma\n val = params.get('keyword', None)\n if val:\n val = val.split(',')\n queryset = queryset.filter(keywords__pk__in=val)\n\n # Filter only super or sub events if recurring has value\n val = params.get('recurring', None)\n if val:\n val = val.lower()\n if val == 'super':\n queryset = queryset.filter(is_recurring_super=True)\n elif val == 'sub':\n queryset = queryset.filter(is_recurring_super=False)\n\n val = params.get('max_duration', None)\n if val:\n dur = parse_duration(val)\n cond = 'end_time - start_time <= %s :: interval'\n queryset = queryset.extra(where=[cond], params=[str(dur)])\n\n val = params.get('min_duration', None)\n if val:\n dur = parse_duration(val)\n cond = 'end_time - start_time >= %s :: interval'\n queryset = queryset.extra(where=[cond], params=[str(dur)])\n\n return queryset\n\n\nclass EventViewSet(viewsets.ModelViewSet, JSONAPIViewSet):\n \"\"\"\n # Filtering retrieved events\n\n Query parameters can be used to filter the retrieved events by\n the following criteria.\n\n ## Event time\n\n Use `start` and `end` to restrict the date range of returned events.\n Any events that intersect with the given date range will be returned.\n\n The parameters `start` and `end` can be given in the following formats:\n\n - ISO 8601 (including the time of day)\n - yyyy-mm-dd\n\n In addition, `today` can be used as the value.\n\n Example:\n\n event/?start=2014-01-15&end=2014-01-20\n\n [See the result](?start=2014-01-15&end=2014-01-20 \"json\")\n\n ## Event location\n\n ### Bounding box\n\n To restrict the retrieved events to a geographical region, use\n the query parameter `bbox` in the format\n\n bbox=west,south,east,north\n\n Where `west` is the longitude of the rectangle's western boundary,\n `south` is the latitude of the rectangle's southern boundary,\n and so on.\n\n Example:\n\n event/?bbox=24.9348,60.1762,24.9681,60.1889\n\n [See the result](?bbox=24.9348,60.1762,24.9681,60.1889 \"json\")\n\n # Getting detailed data\n\n In the default case, keywords, locations, and other fields that\n refer to separate resources are only displayed as simple references.\n\n If you want to include the complete data from related resources in\n the current response, use the keyword `include`. For example:\n\n event/?include=location,keywords\n\n [See the result](?include=location,keywords \"json\")\n\n # Response data for the current URL\n\n \"\"\"\n queryset = Event.objects.all()\n # Use select_ and prefetch_related() to reduce the amount of queries\n queryset = queryset.select_related('location')\n queryset = queryset.prefetch_related(\n 'offers', 'keywords', 'external_links', 'sub_events')\n serializer_class = EventSerializer\n filter_backends = (EventOrderingFilter,)\n ordering_fields = ('start_time', 'end_time', 'days_left')\n\n def get_object(self):\n # Overridden to prevent queryset filtering from being applied\n # outside list views.\n return get_object_or_404(Event.objects.all(), pk=self.kwargs['pk'])\n\n def filter_queryset(self, queryset):\n \"\"\"\n TODO: convert to use proper filter framework\n \"\"\"\n\n queryset = super(EventViewSet, self).filter_queryset(queryset)\n\n if 'show_all' not in self.request.QUERY_PARAMS:\n queryset = queryset.filter(\n Q(event_status=Event.SCHEDULED)\n )\n queryset = _filter_event_queryset(queryset, self.request.QUERY_PARAMS,\n srs=self.srs)\n return queryset\n\n\n def get_authorized_publisher(self, request, data):\n user = request.user\n\n # require user\n assert user.is_authenticated(), 'User needs to be authenticated.'\n\n # require permission to publish\n objs = user.organizations.all()\n assert objs, 'User needs to be authorized to publish events.'\n assert objs.count() == 1, (\n 'User is connected to multiple organizations. This is currently '\n 'not supported.'\n )\n\n # pick publisher\n data['publisher'] = objs.first().id\n return data\n\n def create(self, request, *args, **kwargs):\n data = request.data\n\n # all events created by api are marked coming from the system data\n # source\n data['data_source'] = SYSTEM_DATA_SOURCE_ID\n\n # get publisher from the auth user\n data = self.get_authorized_publisher(request, data)\n\n # generate event id\n data = perform_id_magic_for(data)\n\n # then do the usual stuff defined in `rest_framework.CreateModelMixin`\n serializer = self.get_serializer(data=data)\n serializer.is_valid(raise_exception=True)\n\n self.perform_create(serializer)\n\n return Response(\n serializer.data,\n status=status.HTTP_201_CREATED,\n headers=self.get_success_headers(serializer.data)\n )\n\n\nregister_view(EventViewSet, 'event')\n\n\nclass SearchSerializer(serializers.Serializer):\n def to_representation(self, search_result):\n model = search_result.model\n assert model in serializers_by_model, \"Serializer for %s not found\" % model\n ser_class = serializers_by_model[model]\n data = ser_class(search_result.object, context=self.context).data\n data['object_type'] = model._meta.model_name\n data['score'] = search_result.score\n return data\n\nDATE_DECAY_SCALE = '30d'\n\nclass SearchViewSet(GeoModelAPIView, viewsets.ViewSetMixin, generics.ListAPIView):\n serializer_class = SearchSerializer\n\n def list(self, request, *args, **kwargs):\n languages = [x[0] for x in settings.LANGUAGES]\n\n # If the incoming language is not specified, go with the default.\n self.lang_code = request.QUERY_PARAMS.get('language', languages[0])\n if self.lang_code not in languages:\n raise ParseError(\"Invalid language supplied. Supported languages: %s\" %\n ','.join(languages))\n\n input_val = request.QUERY_PARAMS.get('input', '').strip()\n q_val = request.QUERY_PARAMS.get('q', '').strip()\n if not input_val and not q_val:\n raise ParseError(\"Supply search terms with 'q=' or autocomplete entry with 'input='\")\n if input_val and q_val:\n raise ParseError(\"Supply either 'q' or 'input', not both\")\n\n old_language = translation.get_language()[:2]\n translation.activate(self.lang_code)\n\n queryset = SearchQuerySet()\n if input_val:\n queryset = queryset.filter(autosuggest=input_val)\n now = datetime.utcnow()\n queryset = queryset.filter(end_time__gt=now).decay({\n 'gauss': {\n 'end_time': {\n 'origin': now,\n 'scale': DATE_DECAY_SCALE }}})\n else:\n queryset = queryset.filter(text=AutoQuery(q_val))\n\n self.object_list = queryset.load_all()\n\n page = self.paginate_queryset(self.object_list)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(self.object_list, many=True)\n resp = Response(serializer.data)\n\n translation.activate(old_language)\n\n return resp\n\n\nregister_view(SearchViewSet, 'search', base_name='search')\n", "sub_path": "events/api.py", "file_name": "api.py", "file_ext": "py", "file_size_in_byte": 37180, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "urllib.parse.parse.quote", "line_number": 85, "usage_type": "call"}, {"api_name": "urllib.parse.parse", "line_number": 85, "usage_type": "attribute"}, {"api_name": "urllib.parse", "line_number": 85, "usage_type": "name"}, {"api_name": "time.time", "line_number": 91, "usage_type": "call"}, {"api_name": "base64.b32encode", "line_number": 92, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 92, "usage_type": "call"}, {"api_name": "urllib.parse.parse.urlparse", "line_number": 105, "usage_type": "call"}, {"api_name": "urllib.parse.parse", "line_number": 105, "usage_type": "attribute"}, {"api_name": "urllib.parse", "line_number": 105, "usage_type": "name"}, {"api_name": "urllib.parse.parse.unquote", "line_number": 107, "usage_type": "call"}, {"api_name": "urllib.parse.parse", "line_number": 107, "usage_type": "attribute"}, {"api_name": "urllib.parse", "line_number": 107, "usage_type": "name"}, {"api_name": "rest_framework.exceptions.ParseError", "line_number": 113, "usage_type": "call"}, {"api_name": "rest_framework.relations.HyperlinkedRelatedField", "line_number": 118, "usage_type": "attribute"}, {"api_name": "rest_framework.relations", "line_number": 118, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 128, "usage_type": "call"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 157, "usage_type": "call"}, {"api_name": "rest_framework.serializers.Field", "line_number": 164, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 164, "usage_type": "name"}, {"api_name": "events.utils.get_value_from_tuple_list", "line_number": 181, "usage_type": "call"}, {"api_name": "events.utils", "line_number": 181, "usage_type": "name"}, {"api_name": "events.utils.get_value_from_tuple_list", "line_number": 185, "usage_type": "call"}, {"api_name": "events.utils", "line_number": 185, "usage_type": "name"}, {"api_name": "rest_framework.serializers.Field", "line_number": 189, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 189, "usage_type": "name"}, {"api_name": "isodate.Duration", "line_number": 193, "usage_type": "call"}, {"api_name": "isodate.duration_isoformat", "line_number": 194, "usage_type": "call"}, {"api_name": "isodate.parse_duration", "line_number": 200, "usage_type": "call"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 210, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 210, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 218, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 218, "usage_type": "name"}, {"api_name": "modeltranslation.translator.translator.get_options_for_model", "line_number": 223, "usage_type": "call"}, {"api_name": "modeltranslation.translator.translator", "line_number": 223, "usage_type": "name"}, {"api_name": "modeltranslation.translator.NotRegistered", "line_number": 224, "usage_type": "name"}, {"api_name": "django.conf.settings.LANGUAGES", "line_number": 229, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 229, "usage_type": "name"}, {"api_name": "django.conf.settings.LANGUAGES", "line_number": 279, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 279, "usage_type": "name"}, {"api_name": "django.conf.settings.LANGUAGES", "line_number": 282, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 282, "usage_type": "name"}, {"api_name": "django.conf.settings.LANGUAGES", "line_number": 294, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 294, "usage_type": "name"}, {"api_name": "django.conf.settings.LANGUAGES", "line_number": 313, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 313, "usage_type": "name"}, {"api_name": "django.conf.settings.LANGUAGES", "line_number": 315, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 315, "usage_type": "name"}, {"api_name": "rest_framework.relations.ManyRelatedField", "line_number": 369, "usage_type": "attribute"}, {"api_name": "rest_framework.relations", "line_number": 369, "usage_type": "name"}, {"api_name": "rest_framework.reverse.reverse", "line_number": 395, "usage_type": "call"}, {"api_name": "django.core.urlresolvers.NoReverseMatch", "line_number": 398, "usage_type": "name"}, {"api_name": "events.models.Keyword", "line_number": 447, "usage_type": "name"}, {"api_name": "rest_framework.viewsets.ReadOnlyModelViewSet", "line_number": 450, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 450, "usage_type": "name"}, {"api_name": "events.models.Keyword.objects.all", "line_number": 451, "usage_type": "call"}, {"api_name": "events.models.Keyword.objects", "line_number": 451, "usage_type": "attribute"}, {"api_name": "events.models.Keyword", "line_number": 451, "usage_type": "name"}, {"api_name": "events.models.Keyword.objects.all", "line_number": 463, "usage_type": "call"}, {"api_name": "events.models.Keyword.objects", "line_number": 463, "usage_type": "attribute"}, {"api_name": "events.models.Keyword", "line_number": 463, "usage_type": "name"}, {"api_name": "events.models.Event.objects.all", "line_number": 471, "usage_type": "call"}, {"api_name": "events.models.Event.objects", "line_number": 471, "usage_type": "attribute"}, {"api_name": "events.models.Event", "line_number": 471, "usage_type": "name"}, {"api_name": "events.values_list", "line_number": 474, "usage_type": "call"}, {"api_name": "munigeo.api.GeoModelSerializer", "line_number": 487, "usage_type": "name"}, {"api_name": "events.models.Place", "line_number": 491, "usage_type": "name"}, {"api_name": "munigeo.api.GeoModelAPIView", "line_number": 494, "usage_type": "name"}, {"api_name": "rest_framework.viewsets.ReadOnlyModelViewSet", "line_number": 494, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 494, "usage_type": "name"}, {"api_name": "events.models.Place.objects.all", "line_number": 495, "usage_type": "call"}, {"api_name": "events.models.Place.objects", "line_number": 495, "usage_type": "attribute"}, {"api_name": "events.models.Place", "line_number": 495, "usage_type": "name"}, {"api_name": "events.models.Place.objects.all", "line_number": 507, "usage_type": "call"}, {"api_name": "events.models.Place.objects", "line_number": 507, "usage_type": "attribute"}, {"api_name": "events.models.Place", "line_number": 507, "usage_type": "name"}, {"api_name": "events.models.Event.objects.all", "line_number": 511, "usage_type": "call"}, {"api_name": "events.models.Event.objects", "line_number": 511, "usage_type": "attribute"}, {"api_name": "events.models.Event", "line_number": 511, "usage_type": "name"}, {"api_name": "events.values_list", "line_number": 514, "usage_type": "call"}, {"api_name": "events.models.OpeningHoursSpecification", "line_number": 524, "usage_type": "name"}, {"api_name": "events.models.Language", "line_number": 531, "usage_type": "name"}, {"api_name": "rest_framework.viewsets.ReadOnlyModelViewSet", "line_number": 534, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 534, "usage_type": "name"}, {"api_name": "events.models.Language.objects.all", "line_number": 535, "usage_type": "call"}, {"api_name": "events.models.Language.objects", "line_number": 535, "usage_type": "attribute"}, {"api_name": "events.models.Language", "line_number": 535, "usage_type": "name"}, {"api_name": "pytz.timezone", "line_number": 540, "usage_type": "call"}, {"api_name": "django.conf.settings.TIME_ZONE", "line_number": 540, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 540, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 542, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 542, "usage_type": "name"}, {"api_name": "events.models.EventLink", "line_number": 550, "usage_type": "name"}, {"api_name": "events.models.Offer", "line_number": 555, "usage_type": "name"}, {"api_name": "munigeo.api.GeoModelAPIView", "line_number": 559, "usage_type": "name"}, {"api_name": "events.models.Event.STATUSES", "line_number": 568, "usage_type": "attribute"}, {"api_name": "events.models.Event", "line_number": 568, "usage_type": "name"}, {"api_name": "events.models.Place.objects.get", "line_number": 592, "usage_type": "call"}, {"api_name": "events.models.Place.objects", "line_number": 592, "usage_type": "attribute"}, {"api_name": "events.models.Place", "line_number": 592, "usage_type": "name"}, {"api_name": "events.models.Place.DoesNotExist", "line_number": 593, "usage_type": "attribute"}, {"api_name": "events.models.Place", "line_number": 593, "usage_type": "name"}, {"api_name": "rest_framework.exceptions.ParseError", "line_number": 595, "usage_type": "call"}, {"api_name": "events.models.Keyword.objects.get", "line_number": 610, "usage_type": "call"}, {"api_name": "events.models.Keyword.objects", "line_number": 610, "usage_type": "attribute"}, {"api_name": "events.models.Keyword", "line_number": 610, "usage_type": "name"}, {"api_name": "events.models.Keyword.DoesNotExist", "line_number": 611, "usage_type": "attribute"}, {"api_name": "events.models.Keyword", "line_number": 611, "usage_type": "name"}, {"api_name": "rest_framework.exceptions.ParseError", "line_number": 613, "usage_type": "call"}, {"api_name": "events.models.Place.objects.get", "line_number": 634, "usage_type": "call"}, {"api_name": "events.models.Place.objects", "line_number": 634, "usage_type": "attribute"}, {"api_name": "events.models.Place", "line_number": 634, "usage_type": "name"}, {"api_name": "events.models.Event.objects.create", "line_number": 647, "usage_type": "call"}, {"api_name": "events.models.Event.objects", "line_number": 647, "usage_type": "attribute"}, {"api_name": "events.models.Event", "line_number": 647, "usage_type": "name"}, {"api_name": "events.models.Offer.objects.create", "line_number": 651, "usage_type": "call"}, {"api_name": "events.models.Offer.objects", "line_number": 651, "usage_type": "attribute"}, {"api_name": "events.models.Offer", "line_number": 651, "usage_type": "name"}, {"api_name": "events.models.EventLink.objects.create", "line_number": 653, "usage_type": "call"}, {"api_name": "events.models.EventLink.objects", "line_number": 653, "usage_type": "attribute"}, {"api_name": "events.models.EventLink", "line_number": 653, "usage_type": "name"}, {"api_name": "django.conf.settings.LANGUAGES", "line_number": 665, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 665, "usage_type": "name"}, {"api_name": "events.translation.EventTranslationOptions.fields", "line_number": 666, "usage_type": "attribute"}, {"api_name": "events.translation.EventTranslationOptions", "line_number": 666, "usage_type": "name"}, {"api_name": "events.models.Offer.objects.create", "line_number": 687, "usage_type": "call"}, {"api_name": "events.models.Offer.objects", "line_number": 687, "usage_type": "attribute"}, {"api_name": "events.models.Offer", "line_number": 687, "usage_type": "name"}, {"api_name": "events.models.EventLink.objects.create", "line_number": 693, "usage_type": "call"}, {"api_name": "events.models.EventLink.objects", "line_number": 693, "usage_type": "attribute"}, {"api_name": "events.models.EventLink", "line_number": 693, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 708, "usage_type": "call"}, {"api_name": "events.models.Event", "line_number": 726, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 735, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 735, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 741, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 741, "usage_type": "name"}, {"api_name": "pytz.utc", "line_number": 741, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 749, "usage_type": "call"}, {"api_name": "dateutil.parser.parse", "line_number": 753, "usage_type": "call"}, {"api_name": "rest_framework.exceptions.ParseError", "line_number": 755, "usage_type": "call"}, {"api_name": "rest_framework.viewsets.ReadOnlyModelViewSet", "line_number": 759, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 759, "usage_type": "name"}, {"api_name": "munigeo.api.srid_to_srs", "line_number": 762, "usage_type": "call"}, {"api_name": "rest_framework.filters.OrderingFilter", "line_number": 775, "usage_type": "attribute"}, {"api_name": "rest_framework.filters", "line_number": 775, "usage_type": "name"}, {"api_name": "re.match", "line_number": 791, "usage_type": "call"}, {"api_name": "rest_framework.exceptions.ParseError", "line_number": 793, "usage_type": "call"}, {"api_name": "events.translation.EventTranslationOptions.fields", "line_number": 818, "usage_type": "attribute"}, {"api_name": "events.translation.EventTranslationOptions", "line_number": 818, "usage_type": "name"}, {"api_name": "django.conf.settings.LANGUAGES", "line_number": 820, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 820, "usage_type": "name"}, {"api_name": "django.db.models.Q", "line_number": 821, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 825, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 834, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 839, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 844, "usage_type": "call"}, {"api_name": "munigeo.api.build_bbox_filter", "line_number": 848, "usage_type": "call"}, {"api_name": "events.models.Place.geo_objects.filter", "line_number": 849, "usage_type": "call"}, {"api_name": "events.models.Place.geo_objects", "line_number": 849, "usage_type": "attribute"}, {"api_name": "events.models.Place", "line_number": 849, "usage_type": "name"}, {"api_name": "isodate.parse_duration", "line_number": 879, "usage_type": "call"}, {"api_name": "isodate.parse_duration", "line_number": 885, "usage_type": "call"}, {"api_name": "rest_framework.viewsets.ModelViewSet", "line_number": 892, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 892, "usage_type": "name"}, {"api_name": "events.models.Event.objects.all", "line_number": 951, "usage_type": "call"}, {"api_name": "events.models.Event.objects", "line_number": 951, "usage_type": "attribute"}, {"api_name": "events.models.Event", "line_number": 951, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 963, "usage_type": "call"}, {"api_name": "events.models.Event.objects.all", "line_number": 963, "usage_type": "call"}, {"api_name": "events.models.Event.objects", "line_number": 963, "usage_type": "attribute"}, {"api_name": "events.models.Event", "line_number": 963, "usage_type": "name"}, {"api_name": "django.db.models.Q", "line_number": 974, "usage_type": "call"}, {"api_name": "events.models.Event.SCHEDULED", "line_number": 974, "usage_type": "attribute"}, {"api_name": "events.models.Event", "line_number": 974, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 1018, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 1020, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 1020, "usage_type": "name"}, {"api_name": "rest_framework.serializers.Serializer", "line_number": 1028, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 1028, "usage_type": "name"}, {"api_name": "munigeo.api.GeoModelAPIView", "line_number": 1040, "usage_type": "name"}, {"api_name": "rest_framework.viewsets.ViewSetMixin", "line_number": 1040, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 1040, "usage_type": "name"}, {"api_name": "rest_framework.generics.ListAPIView", "line_number": 1040, "usage_type": "attribute"}, {"api_name": "rest_framework.generics", "line_number": 1040, "usage_type": "name"}, {"api_name": "django.conf.settings.LANGUAGES", "line_number": 1044, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 1044, "usage_type": "name"}, {"api_name": "rest_framework.exceptions.ParseError", "line_number": 1049, "usage_type": "call"}, {"api_name": "rest_framework.exceptions.ParseError", "line_number": 1055, "usage_type": "call"}, {"api_name": "rest_framework.exceptions.ParseError", "line_number": 1057, "usage_type": "call"}, {"api_name": "django.utils.translation.get_language", "line_number": 1059, "usage_type": "call"}, {"api_name": "django.utils.translation", "line_number": 1059, "usage_type": "name"}, {"api_name": "django.utils.translation.activate", "line_number": 1060, "usage_type": "call"}, {"api_name": "django.utils.translation", "line_number": 1060, "usage_type": "name"}, {"api_name": "events.custom_elasticsearch_search_backend.CustomEsSearchQuerySet", "line_number": 1062, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 1065, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 1065, "usage_type": "name"}, {"api_name": "haystack.query.AutoQuery", "line_number": 1072, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 1082, "usage_type": "call"}, {"api_name": "django.utils.translation.activate", "line_number": 1084, "usage_type": "call"}, {"api_name": "django.utils.translation", "line_number": 1084, "usage_type": "name"}]}
+{"seq_id": "277497372", "text": "import http.server\nimport socketserver\nimport threading\nimport socketserver\n\ndef create_proxy_server():\n class RedirectServer(http.server.SimpleHTTPRequestHandler):\n def do_GET(self):\n self.send_response(301)\n self.send_header(\"Location\",\"http://www.meatspin.com\")\n self.end_headers()\n\n return RedirectServer\n\n\ndef set_up_proxy():\n print(\"Created port\")\n redirectHandler = create_proxy_server()\n handler = socketserver.TCPServer((\"127.0.0.1\", 8000), redirectHandler)\n print(\"serving at port 8000\")\n handler.serve_forever()\n\n\nif __name__ == \"__main__\":\n main_thread = threading.Thread(target=set_up_proxy)\n main_thread.setDaemon(False)\n main_thread.start()\n", "sub_path": "bones.py", "file_name": "bones.py", "file_ext": "py", "file_size_in_byte": 726, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "http.server.server", "line_number": 7, "usage_type": "attribute"}, {"api_name": "http.server", "line_number": 7, "usage_type": "name"}, {"api_name": "socketserver.TCPServer", "line_number": 19, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 25, "usage_type": "call"}]}
+{"seq_id": "366594310", "text": "from django import http\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django.views import View\nfrom django.core.paginator import Paginator\nfrom indexs.models import VideoModel\nimport random\nfrom indexs.models import ClassificationModel\n\nfrom indexs.models import MovieDelailModel\n\n\nclass VideoView(View):\n def get(self, request, view_id):\n try:\n video_delail = MovieDelailModel.objects.get(video_id=view_id)\n except:\n video_delail = ''\n try:\n video = VideoModel.objects.get(id=view_id)\n categroy = ClassificationModel.objects.filter(video=view_id)\n categroy = [i.categroy for i in categroy]\n reco = ClassificationModel.objects.filter(categroy__in=categroy)\n reco_video = [res.video for res in reco]\n video_order = VideoModel.objects.all().order_by(\"-activate\")[:8]#7376-1\n\n except Exception as e:\n return http.HttpResponseNotFound(e)\n page = Paginator(reco_video,10)\n pagesize = page.num_pages\n intpage = random.randint(0,pagesize)\n reco_video = [] if intpage==0 else page.page(intpage)\n\n\n context = {\n \"video\":video,\n \"categroy\":categroy,\n \"reco_video\":reco_video,\n \"video_order\":video_order,\n \"video_delail\":video_delail,\n }\n return render(request, \"views.html\",context=context)", "sub_path": "iQIYI/iQIYI/apps/videoviews/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1436, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "django.views.View", "line_number": 14, "usage_type": "name"}, {"api_name": "indexs.models.MovieDelailModel.objects.get", "line_number": 17, "usage_type": "call"}, {"api_name": "indexs.models.MovieDelailModel.objects", "line_number": 17, "usage_type": "attribute"}, {"api_name": "indexs.models.MovieDelailModel", "line_number": 17, "usage_type": "name"}, {"api_name": "indexs.models.VideoModel.objects.get", "line_number": 21, "usage_type": "call"}, {"api_name": "indexs.models.VideoModel.objects", "line_number": 21, "usage_type": "attribute"}, {"api_name": "indexs.models.VideoModel", "line_number": 21, "usage_type": "name"}, {"api_name": "indexs.models.ClassificationModel.objects.filter", "line_number": 22, "usage_type": "call"}, {"api_name": "indexs.models.ClassificationModel.objects", "line_number": 22, "usage_type": "attribute"}, {"api_name": "indexs.models.ClassificationModel", "line_number": 22, "usage_type": "name"}, {"api_name": "indexs.models.ClassificationModel.objects.filter", "line_number": 24, "usage_type": "call"}, {"api_name": "indexs.models.ClassificationModel.objects", "line_number": 24, "usage_type": "attribute"}, {"api_name": "indexs.models.ClassificationModel", "line_number": 24, "usage_type": "name"}, {"api_name": "indexs.models.VideoModel.objects.all", "line_number": 26, "usage_type": "call"}, {"api_name": "indexs.models.VideoModel.objects", "line_number": 26, "usage_type": "attribute"}, {"api_name": "indexs.models.VideoModel", "line_number": 26, "usage_type": "name"}, {"api_name": "django.http.HttpResponseNotFound", "line_number": 29, "usage_type": "call"}, {"api_name": "django.http", "line_number": 29, "usage_type": "name"}, {"api_name": "django.core.paginator.Paginator", "line_number": 30, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 32, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 43, "usage_type": "call"}]}
+{"seq_id": "435712690", "text": "\"\"\"School URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\r\nClass-based views\r\n 1. Add an import: from other_app.views import Home\r\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.urls import include, path\r\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.contrib import admin\r\nfrom django.urls import path\r\nfrom django.contrib.auth import views as auth_views\r\n\r\nfrom users import views\r\n\r\nurlpatterns = [\r\n path('admin/', admin.site.urls),\r\n path('', views.home, name='home'),\r\n path('register/', views.register, name='register'),\r\n\r\n path(\"login/\", views.login_request, name='login'),\r\n path('logout/', views.logout_request, name='logout'),\r\n\r\n path('welcome/', views.welcome_page, name='welcome'),\r\n path('quiz/', views.quiz_page, name='quiz'),\r\n path('result/', views.result, name='result'),\r\n\r\n path('full_result/', views.full_result, name='full_result')\r\n]", "sub_path": "School/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 1290, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "django.urls.path", "line_number": 23, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 23, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 23, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 24, "usage_type": "call"}, {"api_name": "users.views.home", "line_number": 24, "usage_type": "attribute"}, {"api_name": "users.views", "line_number": 24, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 25, "usage_type": "call"}, {"api_name": "users.views.register", "line_number": 25, "usage_type": "attribute"}, {"api_name": "users.views", "line_number": 25, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 27, "usage_type": "call"}, {"api_name": "users.views.login_request", "line_number": 27, "usage_type": "attribute"}, {"api_name": "users.views", "line_number": 27, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 28, "usage_type": "call"}, {"api_name": "users.views.logout_request", "line_number": 28, "usage_type": "attribute"}, {"api_name": "users.views", "line_number": 28, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 30, "usage_type": "call"}, {"api_name": "users.views.welcome_page", "line_number": 30, "usage_type": "attribute"}, {"api_name": "users.views", "line_number": 30, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 31, "usage_type": "call"}, {"api_name": "users.views.quiz_page", "line_number": 31, "usage_type": "attribute"}, {"api_name": "users.views", "line_number": 31, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 32, "usage_type": "call"}, {"api_name": "users.views.result", "line_number": 32, "usage_type": "attribute"}, {"api_name": "users.views", "line_number": 32, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 34, "usage_type": "call"}, {"api_name": "users.views.full_result", "line_number": 34, "usage_type": "attribute"}, {"api_name": "users.views", "line_number": 34, "usage_type": "name"}]}
+{"seq_id": "47697334", "text": "import cv2\r\nimport numpy as np\r\n\r\nimg = cv2.imread('panda.jpg',cv2.IMREAD_COLOR)\r\ncv2.line(img,(0,0),(150,150),(255,0,0),15) #drawing line\r\ncv2.rectangle(img,(250,250),(750,500),(0,0,255),10) #drawing rectangle\r\ncv2.circle(img,(640,320),20,(0,0,255),-1) #drawing circle thickness -1 fills up the circle\r\n\r\npts= np.array([[50,100],[250,100],[960,500],[50,500],[750,250]],np.int32) # points of polygon\r\ncv2.polylines(img,[pts],True,(255,255,0),3) #drawing a polygon\r\n\r\nfont = cv2.FONT_HERSHEY_SIMPLEX # font\r\ncv2.putText(img,'TEST',(750,600),font,3,(0,255,255),6,cv2.LINE_AA) #writing text\r\n\r\ncv2.imshow('image',img)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n", "sub_path": "Test/plotting.py", "file_name": "plotting.py", "file_ext": "py", "file_size_in_byte": 659, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "cv2.imread", "line_number": 4, "usage_type": "call"}, {"api_name": "cv2.IMREAD_COLOR", "line_number": 4, "usage_type": "attribute"}, {"api_name": "cv2.line", "line_number": 5, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 6, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 7, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 9, "usage_type": "attribute"}, {"api_name": "cv2.polylines", "line_number": 10, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 12, "usage_type": "attribute"}, {"api_name": "cv2.putText", "line_number": 13, "usage_type": "call"}, {"api_name": "cv2.LINE_AA", "line_number": 13, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 15, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 16, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 17, "usage_type": "call"}]}
+{"seq_id": "308936967", "text": "from setuptools import setup\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(name='fhem',\n version='0.5.5',\n description='Python API for FHEM home automation server',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'License :: OSI Approved :: MIT License',\n ],\n keywords='fhem home automation',\n url='http://github.com/domschl/python-fhem',\n author='Dominik Schloesser',\n author_email='dsc@dosc.net',\n license='MIT',\n packages=['fhem'],\n zip_safe=False)\n", "sub_path": "fhem/setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 652, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "setuptools.setup", "line_number": 6, "usage_type": "call"}]}
+{"seq_id": "198504753", "text": "# ---------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# ---------------------------------------------------------\n\n# pylint: disable=protected-access\n\n\"\"\"Contains functionality for sending telemetry to Application Insights via OpenCensus Azure Monitor Exporter.\"\"\"\n\nimport logging\n\n# import platform\nfrom os import getenv\n\n# from opencensus.ext.azure.log_exporter import AzureLogHandler\n\n# from azure.ai.ml._user_agent import USER_AGENT\n\n\nAML_INTERNAL_LOGGER_NAMESPACE = \"azure.ai.ml._telemetry\"\n\n# vienna-sdk-unitedstates\nINSTRUMENTATION_KEY = \"71b954a8-6b7d-43f5-986c-3d3a6605d803\"\n\nAZUREML_SDKV2_TELEMETRY_OPTOUT_ENV_VAR = \"AZUREML_SDKV2_TELEMETRY_OPTOUT\"\n\n# application insight logger name\nLOGGER_NAME = \"ApplicationInsightLogger\"\n\nSUCCESS = True\nFAILURE = False\n\nTRACEBACK_LOOKUP_STR = \"Traceback (most recent call last)\"\n\n# extract traceback path from message\nreformat_traceback = True\n\ntest_subscriptions = [\n \"b17253fa-f327-42d6-9686-f3e553e24763\",\n \"test_subscription\",\n \"6560575d-fa06-4e7d-95fb-f962e74efd7a\",\n \"b17253fa-f327-42d6-9686-f3e553e2452\",\n \"74eccef0-4b8d-4f83-b5f9-fa100d155b22\",\n \"4faaaf21-663f-4391-96fd-47197c630979\",\n \"00000000-0000-0000-0000-000000000\",\n]\n\n\nclass CustomDimensionsFilter(logging.Filter):\n \"\"\"Add application-wide properties to AzureLogHandler records\"\"\"\n\n def __init__(self, custom_dimensions=None): # pylint: disable=super-init-not-called\n self.custom_dimensions = custom_dimensions or {}\n\n def filter(self, record):\n \"\"\"Adds the default custom_dimensions into the current log record\"\"\"\n custom_dimensions = self.custom_dimensions.copy()\n custom_dimensions.update(getattr(record, \"custom_dimensions\", {}))\n record.custom_dimensions = custom_dimensions\n\n return True\n\n\ndef in_jupyter_notebook() -> bool:\n \"\"\"\n Checks if user is using a Jupyter Notebook. This is necessary because logging is not allowed in\n non-Jupyter contexts.\n\n Adapted from https://stackoverflow.com/a/22424821\n \"\"\"\n try: # cspell:ignore ipython\n from IPython import get_ipython\n\n if \"IPKernelApp\" not in get_ipython().config:\n return False\n except ImportError:\n return False\n except AttributeError:\n return False\n return True\n\n\ndef is_telemetry_collection_disabled():\n telemetry_disabled = getenv(AZUREML_SDKV2_TELEMETRY_OPTOUT_ENV_VAR)\n if telemetry_disabled and (telemetry_disabled.lower() == \"true\" or telemetry_disabled == \"1\"):\n return True\n if not in_jupyter_notebook:\n return True\n return False\n\n\n# def get_appinsights_log_handler(\n# user_agent,\n# *args, # pylint: disable=unused-argument\n# instrumentation_key=None,\n# component_name=None,\n# **kwargs\n# ):\n# \"\"\"Enable the OpenCensus logging handler for specified logger and instrumentation key to send info to AppInsights.\n\n# :param user_agent: Information about the user's browser.\n# :type user_agent: Dict[str, str]\n# :param instrumentation_key: The Application Insights instrumentation key.\n# :type instrumentation_key: str\n# :param component_name: The component name.\n# :type component_name: str\n# :param args: Optional arguments for formatting messages.\n# :type args: list\n# :param kwargs: Optional keyword arguments for adding additional information to messages.\n# :type kwargs: dict\n# :return: The logging handler.\n# :rtype: opencensus.ext.azure.log_exporter.AzureLogHandler\n# \"\"\"\n# try:\n# if instrumentation_key is None:\n# instrumentation_key = INSTRUMENTATION_KEY\n\n# if is_telemetry_collection_disabled():\n# return logging.NullHandler()\n\n# if not user_agent or not user_agent.lower() == USER_AGENT.lower():\n# return logging.NullHandler()\n\n# if \"properties\" in kwargs and \"subscription_id\" in kwargs.get(\"properties\"):\n# if kwargs.get(\"properties\")[\"subscription_id\"] in test_subscriptions:\n# return logging.NullHandler()\n\n# child_namespace = component_name or __name__\n# current_logger = logging.getLogger(AML_INTERNAL_LOGGER_NAMESPACE).getChild(child_namespace)\n# current_logger.propagate = False\n# current_logger.setLevel(logging.CRITICAL)\n\n# custom_properties = {\"PythonVersion\": platform.python_version()}\n# custom_properties.update({\"user_agent\": user_agent})\n# if \"properties\" in kwargs:\n# custom_properties.update(kwargs.pop(\"properties\"))\n# handler = AzureLogHandler(connection_string=f'InstrumentationKey={instrumentation_key}')\n# current_logger.addHandler(handler)\n# handler.addFilter(CustomDimensionsFilter(custom_properties))\n\n# return handler\n# except Exception: # pylint: disable=broad-except\n# # ignore exceptions, telemetry should not block\n# return logging.NullHandler()\n", "sub_path": "sdk/ml/azure-ai-ml/azure/ai/ml/_telemetry/logging_handler.py", "file_name": "logging_handler.py", "file_ext": "py", "file_size_in_byte": 4913, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "logging.Filter", "line_number": 48, "usage_type": "attribute"}, {"api_name": "IPython.get_ipython", "line_number": 73, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 83, "usage_type": "call"}]}
+{"seq_id": "28370439", "text": "\"\"\"cofouter URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import include, url, patterns\nfrom django.conf import settings\nfrom django.contrib import admin\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom cofouter import views\nfrom wiki.urls import get_pattern as get_wiki_pattern\nfrom django_nyt.urls import get_pattern as get_nyt_pattern\n\nurlpatterns = [\n url(r'^$', views.landing, name=\"landing\"),\n url(r'^register/$', views.register, name=\"register\"),\n url(r'^about/$', views.about, name=\"about\"),\n url(r'^evesso.*', views.ssologin, name=\"evesso\"),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^applications/', include('applications.urls', namespace='applications')),\n url(r'^srp/', include('srp.urls', namespace='srp')),\n url(r'^reddit/', include('subreddit.urls', namespace='subreddit')),\n url(r'^hipchat/', include('hipchat.urls', namespace='hipchat')),\n url(r'^timerboard/', include('timerboard.urls', namespace='timerboard')),\n url(r'^corpmarket/', include('corpmarket.urls', namespace=\"corpmarket\")),\n url(r'^helpdesk/', include('helpdesk.urls', namespace=\"helpdesk\")),\n url(r'^skillchecker/', include('skillchecker.urls', namespace=\"skillchecker\")),\n url(r'^wikinotifications/', get_nyt_pattern()),\n url(r'^wiki/', get_wiki_pattern()),\n url(r'^', include('core.urls', namespace='core')),\n]\n\nif settings.DEBUG:\n urlpatterns += staticfiles_urlpatterns()\n urlpatterns += patterns('',\n url(r'^media/(?P.*)$',\n 'django.views.static.serve',\n {'document_root': settings.MEDIA_ROOT,\n }),\n )", "sub_path": "cofouter/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 2310, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "django.conf.urls.url", "line_number": 25, "usage_type": "call"}, {"api_name": "cofouter.views.landing", "line_number": 25, "usage_type": "attribute"}, {"api_name": "cofouter.views", "line_number": 25, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 26, "usage_type": "call"}, {"api_name": "cofouter.views.register", "line_number": 26, "usage_type": "attribute"}, {"api_name": "cofouter.views", "line_number": 26, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 27, "usage_type": "call"}, {"api_name": "cofouter.views.about", "line_number": 27, "usage_type": "attribute"}, {"api_name": "cofouter.views", "line_number": 27, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 28, "usage_type": "call"}, {"api_name": "cofouter.views.ssologin", "line_number": 28, "usage_type": "attribute"}, {"api_name": "cofouter.views", "line_number": 28, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 29, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 29, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 29, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 29, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 30, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 30, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 31, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 31, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 32, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 32, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 33, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 33, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 34, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 34, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 35, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 35, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 36, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 36, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 37, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 37, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 38, "usage_type": "call"}, {"api_name": "django_nyt.urls.get_pattern", "line_number": 38, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 39, "usage_type": "call"}, {"api_name": "wiki.urls.get_pattern", "line_number": 39, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 40, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 40, "usage_type": "call"}, {"api_name": "django.conf.settings.DEBUG", "line_number": 43, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 43, "usage_type": "name"}, {"api_name": "django.contrib.staticfiles.urls.staticfiles_urlpatterns", "line_number": 44, "usage_type": "call"}, {"api_name": "django.conf.urls.patterns", "line_number": 45, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 46, "usage_type": "call"}, {"api_name": "django.conf.settings.MEDIA_ROOT", "line_number": 48, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 48, "usage_type": "name"}]}
+{"seq_id": "211118085", "text": "import argparse\nimport json\nimport os\nimport nltk\nimport torch\nimport numpy as np\nimport tensorflow as tf\nfrom model import dcn_plus_model\nfrom nltk.tokenize.moses import MosesDetokenizer\nfrom preprocessing.cove_encoder import MTLSTM as CoveEncoder\n\ndef load_glove(filename):\n vocab_dict = {}\n embedding = []\n file = open(filename, 'r')\n for id, line in enumerate(file.readlines()):\n row = line.strip().split(' ')\n if len(row) != 301:\n continue\n vocab_dict[row[0]] = id\n embedding.append([float(i) for i in row[1:]])\n file.close()\n embedding.append([0] * len(embedding[0]))\n return vocab_dict, embedding\n\n\ndef get_vocab_id(word, vocab_dict):\n if vocab_dict.get(word) is None:\n return len(vocab_dict)\n else:\n return vocab_dict[word]\n\n\ndef pad_ids(id_list, vocab_dict, max_sequence_length):\n if len(id_list) >= max_sequence_length:\n return id_list[:max_sequence_length]\n else:\n return id_list + [len(vocab_dict)] * (max_sequence_length - len(id_list))\n\n\ndef pad_tokens(tokens, max_sequence_length):\n if len(tokens) >= max_sequence_length:\n return tokens[:max_sequence_length]\n else:\n pad_token = \"\".encode('utf-8')\n return tokens + [pad_token] * (max_sequence_length - len(tokens))\n\n\ndef document_to_tensor(document, vocab_dict, embedding, max_sequence_length, cove_encoder):\n tokens = [token.replace(\"``\", '\"').replace(\n \"''\", '\"') for token in nltk.word_tokenize(document)]\n length = [min(len(tokens), max_sequence_length)]\n tokens = pad_tokens(tokens, max_sequence_length)\n ids = pad_ids([get_vocab_id(token, vocab_dict)\n for token in tokens], vocab_dict, max_sequence_length)\n tensor = [embedding[id] for id in ids]\n if cove_encoder is not None:\n inputs = torch.autograd.Variable(\n torch.LongTensor(np.asarray(ids))).unsqueeze(0).cuda()\n length = torch.LongTensor(np.asarray(length)).cuda()\n document_tensor, document_cove = cove_encoder(inputs, length)\n\n if document_cove.shape[1] < 600:\n document_cove = torch.cat([document_cove, torch.autograd.Variable(\n torch.zeros(1, 600 - document_cove.shape[1], 600)).cuda()], 1)\n document_tensor = torch.cat(\n [document_tensor, document_cove], 2).squeeze(0).data.cpu().numpy()\n\n for i in range(max_sequence_length):\n if ids[i] == len(vocab_dict):\n document_tensor[i] = np.zeros(900)\n tensor = document_tensor\n #document = tf.transpose(tf.constant(\n # np.expand_dims(np.array(tensor), axis=0)), [0, 2, 1])\n document = tf.constant(np.expand_dims(np.array(tensor), axis=0))\n length = tf.constant(np.expand_dims(np.array(length), axis=0))\n return document, length\n\n\ndef input_fn(context, question, context_length, question_length, context_tokens):\n \"\"\"\n features = [OrderedDict([('context', context), ('question', question), ('context_length', context_length),\n ('question_length', question_length), ('context_tokens', tf.constant(context_tokens)), ('id', tf.constant(np.array(\"id\")))])]\n dtypes = OrderedDict([('context', tf.float32), ('question', tf.float32), ('context_length', tf.int64),\n ('question_length', tf.int64), ('context_tokens', tf.string), ('id', tf.string)])\n shapes = OrderedDict([('context', context.shape), ('question', question.shape), ('context_length', context_length.shape),\n ('question_length', question_length.shape), ('context_tokens', tf.constant(context_tokens).shape), ('id', tf.constant(np.array(\"id\")).shape)])\n train_data = tf.data.Dataset.from_generator(lambda: (feature for feature in features), dtypes, shapes)\n \"\"\"\n context_tokens = np.expand_dims(context_tokens, axis=0)\n features = {'context': context, 'question': question, 'context_length': context_length, 'question_length': question_length, 'context_tokens': tf.constant(context_tokens), 'id': tf.constant(np.array([\"id\"]))}\n train_data = tf.data.Dataset.from_tensors(features)\n iterator = train_data.make_one_shot_iterator()\n return iterator.get_next()\n\n\nif __name__ == '__main__':\n params = json.load(open('params.json'))\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n max_sequence_length = params['model']['max_sequence_length']\n parser = argparse.ArgumentParser()\n parser.add_argument('--glove_file')\n parser.add_argument('--use_cove', action='store_true')\n parser.add_argument('--model_dir', nargs='?', default='pretrained', type=str)\n args = parser.parse_args()\n\n glove_file = args.glove_file\n if glove_file is None:\n print(\"Glove file needed\")\n\n else:\n context = input(\"Context: \")\n question = input(\"Question: \")\n vocab_dict, embedding = load_glove(glove_file)\n\n cove_encoder = None\n if args.use_cove:\n cove_encoder = CoveEncoder(n_vocab=len(\n embedding), vectors=torch.FloatTensor(embedding), residual_embeddings=False)\n cove_encoder.cuda()\n\n context_tokens = [token.replace(\"``\", '\"').replace(\n \"''\", '\"') for token in nltk.word_tokenize(context)]\n context_embedding, context_length = document_to_tensor(\n context, vocab_dict, embedding, max_sequence_length, cove_encoder)\n question_embedding, question_length = document_to_tensor(\n question, vocab_dict, embedding, max_sequence_length, cove_encoder)\n dcn_estimator = tf.estimator.Estimator(\n model_fn=dcn_plus_model, params=params['model'], model_dir=args.model_dir)\n prediction = dcn_estimator.predict(input_fn=lambda: input_fn(\n context_embedding, question_embedding, context_length, question_length, context_tokens))\n prediction = list(prediction)[0]\n detokenizer = nltk.tokenize.moses.MosesDetokenizer()\n prediction = detokenizer.detokenize([token.decode(\n 'utf-8') for token in prediction['context_tokens'][prediction['start']:prediction['end']+1]], return_str=True)\n print(\"Answer: {}\".format(prediction))\n", "sub_path": "interactive.py", "file_name": "interactive.py", "file_ext": "py", "file_size_in_byte": 5820, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "nltk.word_tokenize", "line_number": 51, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 58, "usage_type": "attribute"}, {"api_name": "torch.LongTensor", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 64, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 64, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 64, "usage_type": "attribute"}, {"api_name": "torch.zeros", "line_number": 65, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 71, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 75, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 90, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 91, "usage_type": "call"}, {"api_name": "tensorflow.data.Dataset.from_tensors", "line_number": 92, "usage_type": "call"}, {"api_name": "tensorflow.data", "line_number": 92, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 98, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 99, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 101, "usage_type": "call"}, {"api_name": "preprocessing.cove_encoder.MTLSTM", "line_number": 118, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 119, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 123, "usage_type": "call"}, {"api_name": "tensorflow.estimator.Estimator", "line_number": 128, "usage_type": "call"}, {"api_name": "tensorflow.estimator", "line_number": 128, "usage_type": "attribute"}, {"api_name": "model.dcn_plus_model", "line_number": 129, "usage_type": "name"}, {"api_name": "nltk.tokenize.moses.MosesDetokenizer", "line_number": 133, "usage_type": "call"}, {"api_name": "nltk.tokenize", "line_number": 133, "usage_type": "attribute"}]}
+{"seq_id": "540917336", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('catalog', '0003_auto_20150502_1639'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='category',\n options={'ordering': ('position',), 'verbose_name': 'категория', 'verbose_name_plural': 'категории'},\n ),\n migrations.AlterModelOptions(\n name='tattoo',\n options={'ordering': ('position',), 'verbose_name': 'тату', 'verbose_name_plural': 'тату'},\n ),\n migrations.AddField(\n model_name='tattoo',\n name='is_main',\n field=models.BooleanField(verbose_name='для главной', default=False),\n ),\n migrations.AlterField(\n model_name='category',\n name='position',\n field=models.PositiveSmallIntegerField(verbose_name='cортировка', help_text='Индекс сортировки (по возрастанию).', default=0),\n ),\n migrations.AlterField(\n model_name='tattoo',\n name='position',\n field=models.PositiveSmallIntegerField(verbose_name='cортировка', help_text='Индекс сортировки (по возрастанию).', default=0),\n ),\n ]\n", "sub_path": "catalog/migrations/0004_auto_20150512_1251.py", "file_name": "0004_auto_20150512_1251.py", "file_ext": "py", "file_size_in_byte": 1404, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 7, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterModelOptions", "line_number": 14, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 14, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterModelOptions", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 18, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 22, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 22, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 25, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 25, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 27, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 27, "usage_type": "name"}, {"api_name": "django.db.models.PositiveSmallIntegerField", "line_number": 30, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 30, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 32, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 32, "usage_type": "name"}, {"api_name": "django.db.models.PositiveSmallIntegerField", "line_number": 35, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 35, "usage_type": "name"}]}
+{"seq_id": "498527786", "text": "'''\nGiven an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.\n'''\nfrom time import time\nfrom typing import List\n\n\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n res, freq = [], {}\n for n in nums:\n freq[n] = 1 + freq.get(n, 0)\n\n for _ in range(k):\n # Get number corresponding to max count then delete\n num = max(freq, key=freq.get)\n res.append(num)\n del freq[num]\n\n return res\n\n def reference(self, nums: List[int], k: int) -> List[int]:\n count = {}\n freq = [[] for i in range(len(nums) + 1)]\n\n for n in nums:\n count[n] = 1 + count.get(n, 0)\n for n, c in count.items():\n freq[c].append(n)\n\n res = []\n for i in range(len(freq) - 1, 0, -1):\n for n in freq[i]:\n res.append(n)\n if len(res) == k:\n return res\n\n def quantify(self, test_cases, runs=50000):\n sol_start = time()\n for i in range(runs):\n for case in test_cases:\n if i == 0:\n print(self.topKFrequent(*case))\n else:\n self.topKFrequent(*case)\n print(f'Runtime for our solution: {time() - sol_start}\\n')\n\n ref_start = time()\n for i in range(0, runs):\n for case in test_cases:\n if i == 0:\n print(self.reference(*case))\n else:\n self.reference(*case)\n print(f'Runtime for reference: {time() - ref_start}')\n\n\nif __name__ == '__main__':\n test = Solution()\n test_cases = [([1, 1, 1, 2, 2, 3], 2), ([1], 1)]\n test.quantify(test_cases)\n", "sub_path": "Blind 75/01 - Arrays and Hashing/347-top-k-frequent-elements.py", "file_name": "347-top-k-frequent-elements.py", "file_ext": "py", "file_size_in_byte": 1802, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "typing.List", "line_number": 9, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 22, "usage_type": "name"}, {"api_name": "time.time", "line_number": 39, "usage_type": "call"}, {"api_name": "time.time", "line_number": 46, "usage_type": "call"}, {"api_name": "time.time", "line_number": 48, "usage_type": "call"}, {"api_name": "time.time", "line_number": 55, "usage_type": "call"}]}
+{"seq_id": "503743905", "text": "\"\"\"\r\nAssignment 4B - Machine Learning\r\nBy: David Walesby - 000732130\r\nPurpose: To implement a multilayer perceptron classifier\r\n\"\"\"\r\nfrom sklearn.neural_network import MLPClassifier\r\nimport csv\r\nimport numpy as np\r\nimport random\r\nfrom sklearn import tree\r\nfrom sklearn.preprocessing import normalize\r\n\r\n## Reads in the datafile and returns the arrays\r\ndef ReadFile(fileName):\r\n trainingData = []\r\n trainingLabels = []\r\n testingData = []\r\n testingLabels = []\r\n\r\n with open(fileName) as file:\r\n csv_reader = csv.reader(file , delimiter=\",\")\r\n line_count = 0\r\n for row in csv_reader:\r\n randomNumber = random.randint(1 , 101)\r\n if randomNumber > 25:\r\n testingData.append(row)\r\n else:\r\n trainingData.append(row)\r\n line_count += 1\r\n print(f'Processed {line_count} lines.')\r\n\r\n trainingData = np.array(trainingData, dtype=np.float32)\r\n testingData = np.array(testingData, dtype=np.float32)\r\n trainingLabels = trainingData[:,-1]\r\n testingLabels = testingData[:,-1]\r\n trainingData = np.delete(trainingData,-1, axis=1)\r\n testingData = np.delete(testingData,-1, axis=1)\r\n return trainingData, trainingLabels, testingData, testingLabels\r\n\r\n## Runs the data for classification through a decision tree classifier and a Multi Layer Perceptron classifier and displays the results\r\ndef RunTests(normalizedTrainingData, trainingLabels, normalizedTestingData, testingLabels, fileName):\r\n clf = tree.DecisionTreeClassifier()\r\n clf = clf.fit(normalizedTrainingData, trainingLabels)\r\n decisionPrediction = clf.predict(normalizedTestingData)\r\n decisionCorrect = (decisionPrediction == testingLabels).sum()\r\n decisionTreeAccuracy = decisionCorrect/len(decisionPrediction)*100\r\n\r\n mlpPerceptron = MLPClassifier(hidden_layer_sizes= 15,max_iter=250, learning_rate_init=0.17)\r\n mlpPerceptron.fit(normalizedTrainingData,trainingLabels)\r\n mlpPrediction = mlpPerceptron.predict(normalizedTestingData)\r\n mlpCorrect = (mlpPrediction == testingLabels).sum()\r\n mlpAccuracy = mlpCorrect/len(mlpPrediction)*100\r\n print()\r\n print(f'{fileName}')\r\n print(\"------------------------------------------------------------------------\")\r\n print(f'Accuracy Tree: {round(decisionTreeAccuracy,1)}%')\r\n print(f'Accuracy MLP: {round(mlpAccuracy,1)}%')\r\n print(f'{mlpPerceptron.get_params()}')\r\n print()\r\n\r\nclf = tree.DecisionTreeClassifier()\r\n\r\n## Store file information\r\ntrainingData1, trainingLabels1, testingData1, testingLabels1 = ReadFile(\"000732130_1.csv\")\r\ntrainingData2, trainingLabels2, testingData2, testingLabels2 = ReadFile(\"000732130_2.csv\")\r\ntrainingData3, trainingLabels3, testingData3, testingLabels3 = ReadFile(\"000732130_3.csv\")\r\ntrainingData4, trainingLabels4, testingData4, testingLabels4 = ReadFile(\"000732130_4.csv\")\r\ntrainingData5, trainingLabels5, testingData5, testingLabels5 = ReadFile(\"dexter.csv\")\r\n\r\n## Normalize the training data\r\nnormalizedTrainingData1 = normalize(trainingData1, axis=0, norm='max')\r\nnormalizedTrainingData2 = normalize(trainingData2, axis=0, norm='max')\r\nnormalizedTrainingData3 = normalize(trainingData3, axis=0, norm='max')\r\nnormalizedTrainingData4 = normalize(trainingData4, axis=0, norm='max')\r\nnormalizedTrainingData5 = normalize(trainingData5, axis=0, norm='max')\r\n\r\n## Normalize the testing data\r\nnormalizedTestingData1 = normalize(testingData1, axis=0, norm='max')\r\nnormalizedTestingData2 = normalize(testingData2, axis=0, norm='max')\r\nnormalizedTestingData3 = normalize(testingData3, axis=0, norm='max')\r\nnormalizedTestingData4 = normalize(testingData4, axis=0, norm='max')\r\nnormalizedTestingData5 = normalize(testingData5, axis=0, norm='max')\r\n\r\n## Run tests\r\nRunTests(normalizedTrainingData1, trainingLabels1, normalizedTestingData1, testingLabels1,\"000732130_1.csv\")\r\nRunTests(normalizedTrainingData2, trainingLabels2, normalizedTestingData2, testingLabels2,\"000732130_2.csv\")\r\nRunTests(normalizedTrainingData3, trainingLabels3, normalizedTestingData3, testingLabels3,\"000732130_3.csv\")\r\nRunTests(normalizedTrainingData4, trainingLabels4, normalizedTestingData4, testingLabels4,\"000732130_4.csv\")\r\nRunTests(normalizedTrainingData5, trainingLabels5, normalizedTestingData5, testingLabels5,\"dexter.csv\")\r\n", "sub_path": "assignment4b.py", "file_name": "assignment4b.py", "file_ext": "py", "file_size_in_byte": 4303, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "csv.reader", "line_number": 21, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 32, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 33, "usage_type": "attribute"}, {"api_name": "numpy.delete", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 37, "usage_type": "call"}, {"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 42, "usage_type": "call"}, {"api_name": "sklearn.tree", "line_number": 42, "usage_type": "name"}, {"api_name": "sklearn.neural_network.MLPClassifier", "line_number": 48, "usage_type": "call"}, {"api_name": "sklearn.tree.DecisionTreeClassifier", "line_number": 61, "usage_type": "call"}, {"api_name": "sklearn.tree", "line_number": 61, "usage_type": "name"}, {"api_name": "sklearn.preprocessing.normalize", "line_number": 71, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.normalize", "line_number": 72, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.normalize", "line_number": 73, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.normalize", "line_number": 74, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.normalize", "line_number": 75, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.normalize", "line_number": 78, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.normalize", "line_number": 79, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.normalize", "line_number": 80, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.normalize", "line_number": 81, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.normalize", "line_number": 82, "usage_type": "call"}]}
+{"seq_id": "627997238", "text": "import math, collections\nfrom collections import defaultdict\n\nclass BackoffModel:\n\n def __init__(self, corpus):\n \"\"\"Initialize your data structures in the constructor.\"\"\"\n self.unigramCounts = defaultdict(lambda: 0)\n self.table = defaultdict(lambda: defaultdict(int))\n self.words = set([])\n self.total = 0\n self.train(corpus)\n\n def train(self, corpus):\n \"\"\" Takes a corpus and trains your language model.\n Compute any counts or other corpus statistics in this function.\n \"\"\"\n for sentence in corpus.corpus:\n prevWord = None\n for datum in sentence.data:\n token = datum.word\n self.table[prevWord][token] = self.table[prevWord][token] + 1\n self.unigramCounts[token] = self.unigramCounts[token] + 1\n self.total += 1\n self.words.add(token)\n prevWord = token\n\n def score(self, sentence):\n \"\"\" Takes a list of strings as argument and returns the log-probability of the\n sentence using your language model. Use whatever data you computed in train() here.\n \"\"\"\n score = 0.0\n prevWord = None\n vocab = len(self.words)\n for token in sentence:\n occurances = self.table[prevWord][token]\n countPrev = self.unigramCounts[prevWord]\n\n probability = float(occurances) / (float(countPrev) + vocab)\n\n #Test results of bigram\n if probability > 0:\n score += math.log(probability)\n else: #Back off to unigram\n count = self.unigramCounts[token]\n if count > 0:\n score += math.log(count)\n score -= math.log(self.total)\n\n prevWord = token\n return abs(score)\n", "sub_path": "hw1/BackoffModel.py", "file_name": "BackoffModel.py", "file_ext": "py", "file_size_in_byte": 1621, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "collections.defaultdict", "line_number": 8, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 9, "usage_type": "call"}, {"api_name": "math.log", "line_number": 43, "usage_type": "call"}, {"api_name": "math.log", "line_number": 47, "usage_type": "call"}, {"api_name": "math.log", "line_number": 48, "usage_type": "call"}]}
+{"seq_id": "263269663", "text": "'''\nROC plot of a dataset\n'''\nimport argparse\nimport pickle\nimport numpy as np\nfrom scipy import interp\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import roc_curve, auc\n\ndef roc_process(roc_list, mean_fpr):\n '''\n Average the data over folds\n '''\n tprs = []\n aucs = [] \n i = 0\n for roc in roc_list:\n fpr = roc['fpr']\n tpr = roc['tpr']\n auc_value = roc['auc']\n tprs.append(interp(mean_fpr, fpr, tpr))\n aucs.append(auc_value)\n tprs[-1][0] = 0.0\n #plt.plot(fpr, tpr, lw=1, alpha=0.3, label='ROC fold %d (AUC = %0.2f)' % (i, auc))\n i+=1\n mean_tpr = np.mean(tprs, axis=0)\n mean_tpr[-1] = 1.0\n mean_auc = auc(mean_fpr, mean_tpr)\n return mean_tpr, mean_auc \n\n\nif __name__==\"__main__\":\n result_dir_0 = './results/roc_erneg_use_structual_features_True_p_value_0.05.pickle' \n result_dir_1 = './results/roc_erpos_use_structual_features_True_p_value_0.05.pickle'\n \n result_file_0 = open(result_dir_0, 'rb')\n roc_list_0 = pickle.load(result_file_0) \n result_file_1 = open(result_dir_1, 'rb')\n roc_list_1 = pickle.load(result_file_1)\n \n mean_fpr = np.linspace(0, 1, 100)\n mean_tpr_0, mean_auc_0 = roc_process(roc_list_0, mean_fpr)\n mean_tpr_1, mean_auc_1 = roc_process(roc_list_1, mean_fpr)\n\n # plot roc curve of random\n\n plt.plot(mean_fpr, mean_tpr_1, dashes = [6, 1, 1, 1, 1, 1], color='g', label='ER+', lw=2, alpha=.8)\n plt.plot(mean_fpr, mean_tpr_0, dashes = [6, 1, 1, 1], color='b', label='ER-', lw=2, alpha=.8)\n plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r', label='Random', alpha=.8)\n print('AUC for ER+:', mean_auc_1)\n print('AUC for ER-:', mean_auc_0)\n\n plt.xlim([-0.05, 1.05])\n plt.ylim([-0.05, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver operating characteristic')\n plt.legend(loc=\"lower right\")\n plt.show()", "sub_path": "p_value_classification/roc_machailidou.py", "file_name": "roc_machailidou.py", "file_ext": "py", "file_size_in_byte": 1947, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "scipy.interp", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 27, "usage_type": "call"}, {"api_name": "sklearn.metrics.auc", "line_number": 29, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 38, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 48, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 56, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 57, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 57, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 58, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 58, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 60, "usage_type": "name"}]}
+{"seq_id": "421082667", "text": "import django\ndjango.setup()\nfrom core.bo.curso import get_cursos\nfrom core.bo.sala import get_salas\nfrom django.test import TestCase\nfrom core.tests.povoar_testes import criar_dados, remover_dados\nfrom core.dao.centro_dao import get_centro_by_id, get_centros\nfrom core.dao.componente_dao import get_componentes_by_depto\nfrom core.dao.departamento_dao import get_depto_by_id, get_departamentos\n\n\nclass DAOTests(TestCase):\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n print('\\nDAOTests')\n criar_dados()\n\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n remover_dados()\n\n def test_get_centros(self):\n centros = get_centros()\n\n self.assertIsNotNone(centros, 'Testando centros')\n self.assertTrue(len(centros) > 0, 'Testando centros')\n\n def test_get_ceres(self):\n id_centro = 9999\n codigo = 9999\n sigla = 'CTESTE'\n nome = 'Centro de Teste'\n endereco = 'Rua Joaquim Gregório, Penedo, Caicó - RN'\n site = 'https://www.ceres.ufrn.br/'\n\n centro = get_centro_by_id(9999)\n\n self.assertEqual(id_centro, centro.id_unidade, 'Testando Id Unidade')\n self.assertEqual(codigo, centro.codigo, 'Testando Código')\n self.assertEqual(sigla, centro.sigla, 'Testando Sigla')\n self.assertEqual(nome, centro.nome, 'Testando Nome')\n self.assertEqual(endereco, centro.endereco, 'Testando Endereço')\n self.assertEqual(site, centro.site, 'Testando Site')\n\n centro = get_centro_by_id(6666)\n self.assertIsNone(centro)\n\n def test_get_centro(self):\n id_centro = 9999\n codigo = 9999\n sigla = 'CTESTE'\n nome = 'Centro de Teste'\n endereco = 'Rua Joaquim Gregório, Penedo, Caicó - RN'\n site = 'https://www.ceres.ufrn.br/'\n\n centro = get_centro_by_id(id_centro)\n\n self.assertEqual(id_centro, centro.id_unidade, 'Testando Id Unidade')\n self.assertEqual(codigo, centro.codigo, 'Testando Código')\n self.assertEqual(sigla, centro.sigla, 'Testando Sigla')\n self.assertEqual(nome, centro.nome, 'Testando Nome')\n self.assertEqual(endereco, centro.endereco, 'Testando Endereço')\n self.assertEqual(site, centro.site, 'Testando Site')\n\n def test_get_deptos_centro(self):\n deptos = get_departamentos()\n\n self.assertIsNotNone(deptos, 'Testando departamentos dos centros')\n self.assertTrue(len(deptos) > 0, 'Testando qtd departamentos')\n\n def test_get_componentes_by_depto(self):\n depto = get_depto_by_id(9998)\n ccs = get_componentes_by_depto(depto)\n\n self.assertEqual(4, len(ccs), 'Testando componentes')\n\n def test_get_salas(self):\n salas = get_salas()\n\n self.assertIsNotNone(salas, 'Testando salas')\n self.assertTrue(len(salas) > 0, 'Testando salas')\n\n def test_get_salas(self):\n cursos = get_cursos()\n\n self.assertIsNotNone(cursos, 'Testando cursos')\n self.assertTrue(len(cursos) > 0, 'Testando cursos')\n", "sub_path": "core/tests/test_dao.py", "file_name": "test_dao.py", "file_ext": "py", "file_size_in_byte": 3063, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "django.setup", "line_number": 2, "usage_type": "call"}, {"api_name": "django.test.TestCase", "line_number": 12, "usage_type": "name"}, {"api_name": "core.tests.povoar_testes.criar_dados", "line_number": 18, "usage_type": "call"}, {"api_name": "core.tests.povoar_testes.remover_dados", "line_number": 23, "usage_type": "call"}, {"api_name": "core.dao.centro_dao.get_centros", "line_number": 26, "usage_type": "call"}, {"api_name": "core.dao.centro_dao.get_centro_by_id", "line_number": 39, "usage_type": "call"}, {"api_name": "core.dao.centro_dao.get_centro_by_id", "line_number": 48, "usage_type": "call"}, {"api_name": "core.dao.centro_dao.get_centro_by_id", "line_number": 59, "usage_type": "call"}, {"api_name": "core.dao.departamento_dao.get_departamentos", "line_number": 69, "usage_type": "call"}, {"api_name": "core.dao.departamento_dao.get_depto_by_id", "line_number": 75, "usage_type": "call"}, {"api_name": "core.dao.componente_dao.get_componentes_by_depto", "line_number": 76, "usage_type": "call"}, {"api_name": "core.bo.sala.get_salas", "line_number": 81, "usage_type": "call"}, {"api_name": "core.bo.curso.get_cursos", "line_number": 87, "usage_type": "call"}]}
+{"seq_id": "87974004", "text": "\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndata = pd.read_csv('LinearRegression5_Data.csv')\nprint(data)\n\nprint(data.shape) #(6,2)\n\nX = data.iloc[ : , 0:1].values # [ rows , cols ]\ny = data.iloc[:, 1].values\n\nprint(\"X.shape = \", X.shape , \"\\n X=\\n\" , X)\n\nprint(\"y.shape = \", y.shape , \"\\n y=\" , y )\n\n\nfrom sklearn.linear_model import LinearRegression\n\nlin = LinearRegression()\nlin.fit(X, y)\ny_dash = lin.predict(X)\n\nplt.scatter(X, y, color='blue')\nplt.plot(X, y_dash , color='red')\nplt.title('Linear Regression')\nplt.xlabel('Engine Temperature')\nplt.ylabel('Engine Pressure')\n\nplt.show()\n\n# =========================================================\n\nfrom sklearn.preprocessing import PolynomialFeatures\n\npoly = PolynomialFeatures(degree=4)\nX_poly = poly.fit_transform(X)\n\n#poly.fit(X_poly, y)\nlin2 = LinearRegression()\nlin2.fit(X_poly, y)\n\n\nplt.scatter(X, y, color='blue')\n\nplt.plot(X, lin2.predict(poly.fit_transform(X)), color='red')\nplt.title('Polynomial Regression')\nplt.xlabel('Engine Temperature')\nplt.ylabel('Engine Pressure')\n\nplt.show()\n\n# Predicting a new result with Linear Regression\nprint( \"LinearRegresion: \", lin.predict([[110.0]]) )\n\n# Predicting a new result with Polynomial Regression\nprint( \"PolynomialRegresion: \",lin2.predict(poly.fit_transform([[110.0]])) )\n", "sub_path": "5. machine learning/2. Supervised Machine Learning/2. Polynomial/1. polynomial features.py", "file_name": "1. polynomial features.py", "file_ext": "py", "file_size_in_byte": 1335, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "pandas.read_csv", "line_number": 6, "usage_type": "call"}, {"api_name": "sklearn.linear_model.LinearRegression", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "sklearn.preprocessing.PolynomialFeatures", "line_number": 37, "usage_type": "call"}, {"api_name": "sklearn.linear_model.LinearRegression", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 48, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}]}
+{"seq_id": "362764089", "text": "\"\"\":\n FunFacts _urls.py\n\"\"\"\n\n\nfrom django.conf.urls import url,include\nfrom . import views\n\nurlpatterns = [\n #url(r'^admin/', admin.site.urls),\n url(r'^$', views.index),\n url(r'^funfacts_process$', views.funfacts_process),\n url(r'^funfacts$', views.funfacts),\n]\n", "sub_path": "funfacts/apps/funfacts_app/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 281, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "django.conf.urls.url", "line_number": 11, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 12, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 13, "usage_type": "call"}]}
+{"seq_id": "463921828", "text": "import my_log\nimport loader_from_file as lfl\nimport re\nimport config\nimport parser_command.command as p\n\nLOG = my_log.get_logger('update')\n\n\ndef update(words):\n num = None\n download = False\n\n company, privileged = p.name_and_priviledget(words)\n\n count_words = words.__len__()\n if count_words > 1:\n if re.compile(r'[0-9]+').match(words[1]):\n num = int(words[1])\n elif words[count_words - 1] in config.CMD_DOWNLOAD_FILES:\n company = ' '.join(words[1:count_words - 1])\n download = True\n else:\n company = ' '.join(words[1:count_words])\n\n LOG.info(\"Update %s files and %s download\" % (str(num) if num is not None else company, str(download)))\n if company is None or len(company) == 0:\n lfl.load_stocks(num, download)\n else:\n lfl.update_stock_from_file(company, download, privileged)\n\n\ndef update_metainfo():\n lfl.load_all()\n return config.RSP_UPDATE_METAINFO\n", "sub_path": "bot/updater.py", "file_name": "updater.py", "file_ext": "py", "file_size_in_byte": 963, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "my_log.get_logger", "line_number": 7, "usage_type": "call"}, {"api_name": "parser_command.command.name_and_priviledget", "line_number": 14, "usage_type": "call"}, {"api_name": "parser_command.command", "line_number": 14, "usage_type": "name"}, {"api_name": "re.compile", "line_number": 18, "usage_type": "call"}, {"api_name": "config.CMD_DOWNLOAD_FILES", "line_number": 20, "usage_type": "attribute"}, {"api_name": "loader_from_file.load_stocks", "line_number": 28, "usage_type": "call"}, {"api_name": "loader_from_file.update_stock_from_file", "line_number": 30, "usage_type": "call"}, {"api_name": "loader_from_file.load_all", "line_number": 34, "usage_type": "call"}, {"api_name": "config.RSP_UPDATE_METAINFO", "line_number": 35, "usage_type": "attribute"}]}
+{"seq_id": "131936425", "text": "#\n# Copyright (c) 2016, Novartis Institutes for BioMedical Research Inc.\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met: \n#\n# * Redistributions of source code must retain the above copyright \n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following \n# disclaimer in the documentation and/or other materials provided \n# with the distribution.\n# * Neither the name of Novartis Institutes for BioMedical Research Inc. \n# nor the names of its contributors may be used to endorse or promote \n# products derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n# Created by Nadine Schneider, June 2016\n\n\nimport numpy as np\nimport pandas as pd\nimport copy\nimport re\nfrom rdkit.Chem import PandasTools\nfrom IPython.display import SVG\n\n# generate an HTML table of the svg images to visulize them nicely in the Jupyter notebook \nPandasTools.RenderImagesInAllDataFrames(images=True)\ndef drawSVGsToHTMLGrid(svgs, cssTableName='default', tableHeader='', namesSVGs=[], size=(150,150), numColumns=4, numRowsShown=2, noHeader=False):\n rows=[]\n names=copy.deepcopy(namesSVGs)\n rows = [SVG(i).data if i.startswith(' 0:\n rows+=['']*(numColumns-x)\n d+=1\n if len(names)>0:\n names+=['']*(numColumns-x)\n rows=np.array(rows).reshape(d,numColumns)\n finalRows=[]\n if len(names)>0:\n names = np.array(names).reshape(d,numColumns)\n for r,n in zip(rows,names):\n finalRows.append(r)\n finalRows.append(n)\n d*=2\n else:\n finalRows=rows\n\n headerRemove = int(max(numColumns,d))\n df=pd.DataFrame(finalRows)\n\n style = '\\n'\n if not noHeader:\n style += ''+str(tableHeader)+'
\\n'\n style += '\\n'\n dfhtml=style+df.to_html()+'\\n
\\n'\n dfhtml=dfhtml.replace('class=\"dataframe\"','class=\"'+cssTableName+'\"')\n dfhtml=dfhtml.replace(' | ','')\n for i in range(0,headerRemove):\n dfhtml=dfhtml.replace(''+str(i)+' | ','')\n return dfhtml\n\n# build an svg grid image to print\ndef SvgsToGrid(svgs, labels, svgsPerRow=4,molSize=(250,150),fontSize=12):\n \n matcher = re.compile(r'^(<.*>\\n)(\\n)(.*)',re.DOTALL) \n hdr='' \n ftr='' \n rect='' \n nRows = len(svgs)//svgsPerRow \n if len(svgs)%svgsPerRow : nRows+=1 \n blocks = ['']*(nRows*svgsPerRow)\n labelSizeDist = fontSize*5\n fullSize=(svgsPerRow*(molSize[0]+molSize[0]/10.0),nRows*(molSize[1]+labelSizeDist))\n print(fullSize)\n\n count=0\n for svg,name in zip(svgs,labels):\n h,r,b = matcher.match(svg).groups()\n if not hdr: \n hdr = h.replace(\"width='\"+str(molSize[0])+\"px'\",\"width='%dpx'\"%fullSize[0])\n hdr = hdr.replace(\"height='\"+str(molSize[1])+\"px'\",\"height='%dpx'\"%fullSize[1])\n if not rect: \n rect = r\n legend = '\\n'\n legend += ''+name.split('|')[0]+'\\n'\n if len(name.split('|')) > 1:\n legend += ''+name.split('|')[1]+'\\n'\n legend += '\\n'\n blocks[count] = b + legend\n count+=1\n\n for i,elem in enumerate(blocks): \n row = i//svgsPerRow \n col = i%svgsPerRow \n elem = rect+elem \n blocks[i] = '%s'%(col*(molSize[0]+molSize[0]/10.0),row*(molSize[1]+labelSizeDist),elem) \n res = hdr + '\\n'.join(blocks)+ftr \n return res \n", "sub_path": "ChemTopicModel/utilsDrawing.py", "file_name": "utilsDrawing.py", "file_ext": "py", "file_size_in_byte": 5777, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "rdkit.Chem.PandasTools.RenderImagesInAllDataFrames", "line_number": 42, "usage_type": "call"}, {"api_name": "rdkit.Chem.PandasTools", "line_number": 42, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 45, "usage_type": "call"}, {"api_name": "IPython.display.SVG", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 57, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 66, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 92, "usage_type": "call"}, {"api_name": "re.DOTALL", "line_number": 92, "usage_type": "attribute"}]}
+{"seq_id": "461593840", "text": "import csv\nimport matplotlib.pyplot as plt\n\n\ncsvread = csv.reader(open('final_author_coauthor.csv','r'))\ncsvread2 = csv.reader(open('final_author_percitation_bk.csv','r'))\n\npaperlist = {}\npaperlist2 = {}\n\nfor row in csvread: \n\tpaperlist[int(row[0])] = int(row[2])\n\tpaperlist[int(row[1])] = int(row[2])\n\nfor row in csvread2: \n\tpaperlist2[int(row[0])] = int(row[2])\n\nkey1 = paperlist.keys()\nkey2 = paperlist2.keys()\n\nprint(len(key1))\nprint(len(key2))\ndiff = list(set(key2)-set(key1))\n\nprint (len(diff))\nplot = []\nfor key in diff:\n\tplot.append(key)\n\nplt.plot(plot,'b.')\n# plt.hist(plot,bins=6)\nplt.show()\n", "sub_path": "reduced/datasetcomparer.py", "file_name": "datasetcomparer.py", "file_ext": "py", "file_size_in_byte": 602, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "csv.reader", "line_number": 5, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 6, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}]}
+{"seq_id": "53654862", "text": "import os\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nmatplotlib.use('Agg')\n\nimport torch\nfrom torch.nn import functional as F\nfrom torch import tensor\n\nfrom nn.models import Encoder, Decoder, Classifier\nfrom plots.scatter_plot_test import plot\nimport constants_cmap\nfrom datasets import datasets\nimport numpy as np\nfrom sklearn.decomposition import PCA\n\nimport matplotlib.cm as cm\nimport matplotlib.colors as ml_colors\nfrom matplotlib.lines import Line2D\nfrom sklearn.neighbors import KNeighborsClassifier\n\nfrom sklearn.model_selection import train_test_split\n\ndef knn(X_train,y_train, X_test, y_test):\n neigh = KNeighborsClassifier(n_neighbors=10)\n neigh.fit(X_train, y_train)\n score=neigh.score(X_test, y_test)\n print(score)\n\n return score\n\n\ndef plot_bu(model, test_loader, device, suffix, path_to_save, dataset_names, colormap, bg_color):\n zs=tensor([])\n mus=tensor([])\n logvars=tensor([])\n labels=tensor([]).long()\n\n for batch_idx, (data, label) in enumerate(test_loader):\n data = data.to(device)\n z, mu, logvar, _ = model(data)\n zs=torch.cat((zs, z), 0)\n mus=torch.cat((mus, mu), 0)\n logvars=torch.cat((logvars, logvar), 0)\n labels=torch.cat((labels, label), 0)\n\n # xs,ys=list(zip(*zs.cpu().numpy()))\n zs=zs.cpu().numpy()\n labels=labels.cpu().numpy()\n\n # np.save(os.path.join(path_to_save, \"latent_features{}.npy\".format(suffix)), np.hstack([zs, labels.reshape(-1,1), [[dataset_names[a]] for a in labels]]))\n X_pca = zs # PCA(n_components=2).fit_transform(zs)\n\n limit=10\n labels=np.array([labels[i] for i, a in enumerate(zs) if np.abs(a[0]) \" + ETC_HOSTNAME )\n\nif confHostname:\n with open(ETC_HOSTNAME, 'w') as f:\n f.write(confHostname + '\\n')\n f.close()\n\n with open(ETC_HOSTS, 'r') as fp:\n lines = fp.read().split(\"\\n\")\n fp.close()\n\n with open(ETC_HOSTS, 'w') as fp: \n for i in lines:\n if '127.0.1.1' in i and DOMAIN_NAME in i:\n #print ('127.0.1.1\\t' + confHostname)\n fp.write ('127.0.1.1\\t' + confHostname+'\\n')\n else:\n if i:\n #print (i) \n fp.write (i+'\\n') \n fp.close()\n #os.system('sudo shutdown -r now')\n os.system('hostnamectl set-hostname ' + confHostname)\n", "sub_path": "hostnamer.py", "file_name": "hostnamer.py", "file_ext": "py", "file_size_in_byte": 1517, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "os.path.dirname", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 11, "usage_type": "attribute"}, {"api_name": "uuid.getnode", "line_number": 13, "usage_type": "call"}, {"api_name": "json.load", "line_number": 17, "usage_type": "call"}, {"api_name": "os.uname", "line_number": 21, "usage_type": "call"}, {"api_name": "os.system", "line_number": 53, "usage_type": "call"}]}
+{"seq_id": "270395771", "text": "from ortools.linear_solver import pywraplp\nimport networkx as nx\nfrom shapely.geometry import Point, LineString, MultiLineString\nimport os\nimport geojson\n\n\nclass RouteOptimizer():\n def __init__(self, trail_network, mindist = 0, maxdist = 100):\n \"\"\"\n This is a mixed-integer linear program. It will maximize distance\n such that each node is gone through symetrically from either side\n \"\"\"\n # Make Path object a more callable object -- Fix all this\n self.trail_network = trail_network\n self.mindist = mindist\n self.maxdist = maxdist\n self.variables = {}\n self.path_groups = {}\n self.group_vars = {}\n self.group_list = []\n self.starting_trails = {}\n self.constraints = {}\n self.solver = None\n self.objective = None\n self.results = None\n self.node_variables = {}\n self.edge_limit = {}\n \n\n def set_trip_length(self, mindist, maxdist):\n self.mindist = mindist\n self.maxdist = maxdist\n self.set_distance_constraint()\n \n\n def setup_solver(self):\n self.solver = pywraplp.Solver('Backpack Trip Planner',\n pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)\n \n self.objective = self.solver.Objective()\n self.objective.SetMaximization()\n \n\n def setup_variables(self):\n \"\"\"\n Each path is setup as an integer variable. It can either be 0 or 1.\n Paths can go from Origin_to_Destination, or Destnation_to_Origin\n \"\"\"\n \n self.set_distance_constraint()\n\n start = self.constraints[\"start_node\"] = self.solver.Constraint(0, 1) \n for path in self.trail_network.edges(data=True):\n pathwaycons = self.constraints[path[2][\"name\"]] = self.solver.Constraint(0, 1)\n pathd = path[2][\"length\"]\n constraint = self.constraints[\"Trip Distance\"]\n forward = (path[0],path[1], path[2][\"name\"])\n reverse = (path[1],path[0], path[2][\"name\"])\n \n # Add the node variables\n if path[0] not in self.node_variables:\n node1 = self.node_variables[path[0]] = self.solver.IntVar(0,1,\"node_var\"+str(path[0]))\n start.SetCoefficient(node1, 1)\n \n if path[1] not in self.node_variables:\n node2 = self.node_variables[path[1]] = self.solver.IntVar(0,1,\"node_var\"+str(path[1]))\n start.SetCoefficient(node2, 1)\n \n \n \n #Had previously set values at 2, not sure why?\n self.variables[forward] = self.solver.IntVar(0, 1, \"forward_\"+str(forward))\n self.variables[reverse] = self.solver.IntVar(0, 1, \"reverse_\"+str(reverse))\n \n # Add constraints so a pathway can go either forward or backward\n pathwaycons.SetCoefficient(self.variables[forward], 1)\n pathwaycons.SetCoefficient(self.variables[reverse], 1)\n\n # Add distances to the total distance constraint\n constraint.SetCoefficient(self.variables[forward], pathd)\n constraint.SetCoefficient(self.variables[reverse], pathd)\n \n # Add distances to objective function\n self.objective.SetCoefficient(self.variables[forward], pathd)\n self.objective.SetCoefficient(self.variables[reverse], pathd)\n \n\n def set_node_constraints(self):\n \"\"\"\n Each Pathway represents leaving a node or joining a node.\n All nodes must stay at 0, otherwise it is impossible to return to\n your origin\n \"\"\"\n \n # Have each node be a variable (Start Node) <-- Done: X\n # Constraint: Only have 1 start-node\n # Node Coefficient: 1 for Node Variable\n #Pathway Constraints Below can be 0 or 1\n # Start constraint prevents a -1\n # Pathway in single direction prevents doubling back\n \n if not self.variables:\n raise Exception(\"Pathway variables need to be setup first\")\n\n for pathway in self.variables:\n intvar = self.variables[pathway]\n\n \n if pathway[0] not in self.constraints:\n self.constraints[pathway[0]] = self.solver.Constraint(0, 1)\n edge1 = self.edge_limit[pathway[0]] = self.solver.Constraint(0,2)\n \n \n if pathway[1] not in self.constraints:\n self.constraints[pathway[1]] = self.solver.Constraint(0, 1)\n edge2 = self.edge_limit[pathway[1]] = self.solver.Constraint(0,2)\n \n node1 = self.constraints[pathway[0]]\n node2 = self.constraints[pathway[1]]\n edge1 = self.edge_limit[pathway[0]]\n edge2 = self.edge_limit[pathway[1]]\n \n \n node1.SetCoefficient(intvar, 1)\n node2.SetCoefficient(intvar, -1)\n edge1.SetCoefficient(intvar, 1)\n edge2.SetCoefficient(intvar, 1)\n \n # Allow start_condition to add a +1\n node1.SetCoefficient(self.node_variables[pathway[0]],1)\n node2.SetCoefficient(self.node_variables[pathway[1]],1)\n \n\n def set_distance_constraint(self):\n if \"Distance\" not in self.constraints:\n self.constraints[\"Trip Distance\"] = self.solver.Constraint(self.mindist, self.maxdist)\n else:\n self.constraints[\"Trip Distance\"].SetBounds(self.mindist, self.maxdist)\n \n \n def establish_groups(self):\n \"\"\"\n Create list that keeps track of which group \n (connnected component) each node belongs to\n \"\"\"\n d = list(self.trail_network.subgraph(c) for c in nx.connected_components(self.trail_network))\n for i, group in enumerate(d):\n for node in group:\n self.path_groups[node] = i\n self.group_list.append(i)\n \n ''' \n to return more than one trail, we could adjust the number of unique_starts, but we need to\n figure out what the solver is doing exactly and how to best optimize it\n '''\n def set_grouping_constraint(self, unique_starts = 1): \n \"\"\"\n A Constraint that allows only a number of networks equal to [unique_starts] chosen\n in a given area\n \"\"\"\n if not self.path_groups:\n self.establish_groups()\n \n grp_constraint = self.constraints[\"Trail Groups\"] = self.solver.Constraint(0, unique_starts)\n for group in self.group_list:\n grp_id = self.group_vars[group] = self.solver.IntVar(0,1,str(group))\n grp_constraint.SetCoefficient(grp_id, 1)\n \n for path_key in self.variables:\n \"\"\"\n Allows a path to be selected if it falls in the same group as the\n chosen hiking group\n \"\"\"\n grp_id = self.path_groups[path_key[0]]\n identifier = \"constraint_%s\" % str(grp_id)\n \n cons = self.group_vars[identifier] = self.solver.Constraint(0,self.solver.infinity())\n path_var = self.variables[path_key]\n grp_var = self.group_vars[grp_id]\n \n cons.SetCoefficient(path_var,-1)\n cons.SetCoefficient(grp_var, 1)\n \n \n def setup_lp(self):\n self.setup_solver()\n self.setup_variables()\n self.set_node_constraints()\n \n\n def solve(self):\n result_status = self.solver.Solve()\n return result_status\n \n\n def get_results(self):\n results = []\n print(\"Total Trip Length: %s km\" % self.objective.Value())\n for key in self.variables:\n intvar = self.variables[key]\n if intvar.solution_value() > 0:\n results.append(key)\n \n self.results = results\n return results\n\n\n def save_geojson(self,path_object):\n if not self.results:\n self.get_results()\n \n results = self.results\n \n lines = []\n for path_name in results:\n pointlist = []\n path = path_object.get(path_name).points\n if path.type == 'LineString':\n points = path.coords\n else:\n points = path[0].coords\n \n for coord in points:\n pointlist.append(Point([coord[0], coord[1]]))\n lines.append(LineString(pointlist))\n \n geom_in_geojson = geojson.Feature(geometry=MultiLineString(lines), properties={})\n return geojson.dumps(geom_in_geojson)\n \n\n\n \n \n", "sub_path": "app/app/tripopt/tripopt.py", "file_name": "tripopt.py", "file_ext": "py", "file_size_in_byte": 8798, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "ortools.linear_solver.pywraplp.Solver", "line_number": 38, "usage_type": "call"}, {"api_name": "ortools.linear_solver.pywraplp", "line_number": 38, "usage_type": "name"}, {"api_name": "ortools.linear_solver.pywraplp.Solver", "line_number": 39, "usage_type": "attribute"}, {"api_name": "ortools.linear_solver.pywraplp", "line_number": 39, "usage_type": "name"}, {"api_name": "networkx.connected_components", "line_number": 147, "usage_type": "call"}, {"api_name": "shapely.geometry.Point", "line_number": 225, "usage_type": "call"}, {"api_name": "shapely.geometry.LineString", "line_number": 226, "usage_type": "call"}, {"api_name": "geojson.Feature", "line_number": 228, "usage_type": "call"}, {"api_name": "shapely.geometry.MultiLineString", "line_number": 228, "usage_type": "call"}, {"api_name": "geojson.dumps", "line_number": 229, "usage_type": "call"}]}
+{"seq_id": "45433920", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nThis class is part of the MacGyver challenge\ninitiated with class variables to use them in the different methods\nall the methods have a quick explanation of their utility and usage\n\"\"\"\n# generic python libraries\nimport pygame as pg\nimport sys\n# own libraries\nimport classes.gameData as gd\nimport config.config as config\nimport classes.imgLoader as imgl\n\nclass GameLogic():\n\n def __init__(self):\n self.collected = 0\n # loading the game from file\n # and initializing game board\n self.board = gd.GameData()\n self.board.get_maps_to_list()\n self.board.find_walls()\n self.board.find_path()\n # randomly distribute objects in the board\n # free path\n self.board.distribute_object()\n\n # some generic values to update the game settings more easily\n # game window title\n pg.display.set_caption(config.SCREEN_TITLE)\n\n # sets the size of the screen of pygamge\n self.screen = pg.display.set_mode((config.SCREEN_W, config.SCREEN_H))\n\n # sets values of the background\n self.screen.fill(config.BACKGR_COLOR)\n\n # sets a font to call it\n pg.font.init()\n objectstxt = pg.font.SysFont('Comic Sans MS', 25, bold=1)\n hypodermictxt = pg.font.SysFont('Comic Sans MS', 25, italic=1)\n self.toptxt = objectstxt.render('Vous avez collecté ces objets ->', False, config.TXT_COLOR)\n self.undertxt = hypodermictxt.render('Vous avez fabriqué la seringue', False, config.TXT_COLOR)\n\n def initiator(self):\n # loads to screen all resources to start\n self.load_resource()\n self.static_to_screen(self.board.wallpositions, self.walls.image)\n self.static_to_screen(self.board.pathpositions, self.path.image)\n self.collectables_to_screen()\n self.macgyver_to_screen()\n self.enemy_to_screen()\n # refresh display\n pg.display.flip()\n\n def load_resource(self):\n # -------------- loads images\n # caracters\n self.macgyver = imgl.ImageLoader(config.MACGYVER_PX)\n self.macgyver_pos = self.board.find_object(config.MACGYVER_POS)\n\n self.enemy = imgl.ImageLoader(config.ENEMY_PX)\n self.enemy_pos = self.board.find_object(config.ENEMY_POS)\n\n # walls\n self.walls = imgl.ImageLoader(config.WALL_PX)\n\n # ground\n self.path = imgl.ImageLoader(config.GROUND_PX)\n\n # Collectables\n self.tube = imgl.ImageLoader(config.TUBE_PX)\n self.needle = imgl.ImageLoader(config.NEEDLE_PX)\n self.aether = imgl.ImageLoader(config.AETHER_PX)\n\n # Final object\n self.hypodermic = imgl.ImageLoader(config.HYPODERMIC_PX)\n\n # -------------- creates lists\n # we add some elements to a list so we can iterate through\n # objects in order to display them\n self.gameObjects = []\n self.gameObjects.append(self.tube)\n self.gameObjects.append(self.needle)\n self.gameObjects.append(self.aether)\n\n '''\n use list and distribute it through the windows using\n coordinates from list multiplied by the size of the\n tile or wall structure\n '''\n # displays repetitive elements to the screen such\n # as walls, pathwalks\n def static_to_screen(self, listofobj, image):\n # display list of objects given\n for pos in listofobj:\n x_px = pos[0] * config.TILE_SIZE\n y_px = pos[1] * config.TILE_SIZE\n self.screen.blit(image, (x_px, y_px))\n\n # displays collectables to the screen\n def collectables_to_screen(self):\n # distributes objects into the maze\n\n for pos, coord in enumerate(self.board.objects_pos):\n x_px = coord[0] * config.TILE_SIZE\n y_px = coord[1] * config.TILE_SIZE\n self.screen.blit(self.gameObjects[pos].image, (x_px, y_px))\n\n # displays macgyver to the screen\n def macgyver_to_screen(self):\n self.screen.blit(\n self.macgyver.image, (\n self.macgyver_pos[0] * config.TILE_SIZE,\n self.macgyver_pos[1] * config.TILE_SIZE))\n\n # displays enemy to the screen\n def enemy_to_screen(self):\n self.screen.blit(\n self.enemy.image, (\n self.enemy_pos[0] * config.TILE_SIZE,\n self.enemy_pos[1] * config.TILE_SIZE))\n\n def getPlayerinput(self):\n # gets keys pressed by user and returns them as tuple\n self.up = pg.key.get_pressed()[pg.K_UP]\n self.down = pg.key.get_pressed()[pg.K_DOWN]\n self.left = pg.key.get_pressed()[pg.K_LEFT]\n self.right = pg.key.get_pressed()[pg.K_RIGHT]\n\n # method to move MacGyver in the maze and update screen\n def setPlayerposition(self):\n self.getPlayerinput()\n if self.macgyver_pos in self.board.pathpositions:\n if self.right and self.board.checkwall((self.macgyver_pos[0]+1, self.macgyver_pos[1])):\n self.macgyver_pos = (self.macgyver_pos[0] + 1, self.macgyver_pos[1])\n\n elif self.left and self.board.checkwall((self.macgyver_pos[0]-1, self.macgyver_pos[1])):\n self.macgyver_pos = (self.macgyver_pos[0] - 1, self.macgyver_pos[1])\n\n elif self.up and self.board.checkwall((self.macgyver_pos[0], self.macgyver_pos[1]-1)):\n self.macgyver_pos = (self.macgyver_pos[0], self.macgyver_pos[1]-1)\n\n elif self.down and self.board.checkwall((self.macgyver_pos[0], self.macgyver_pos[1]+1)):\n self.macgyver_pos = (self.macgyver_pos[0], self.macgyver_pos[1]+1)\n\n if self.collected >= 3:\n self.enemy.image = self.hypodermic.image\n \n if self.macgyver_pos in self.board.objects_pos:\n index = self.board.objects_pos.index(self.macgyver_pos)\n self.board.objects_pos[index] = (10+self.collected, 0)\n self.collected += 1\n #self.board.objects_pos.remove(self.macgyver_pos)\n elif self.macgyver_pos == self.enemy_pos:\n if self.collected >= 3:\n print(\"tous les objects ont été ramassées et l'enemi endormi, jeux terminé !\")\n sys.exit()\n else:\n print(\"Vous avez été tué ! Too bad.\")\n sys.exit()\n\n # render objects\n self.static_to_screen(self.board.wallpositions, self.walls.image)\n self.static_to_screen(self.board.pathpositions, self.path.image)\n self.macgyver_to_screen()\n self.enemy_to_screen()\n self.collectables_to_screen()\n self.screen.blit(self.toptxt, (0, 0))\n\n if self.collected >= 3:\n self.screen.blit(self.undertxt, (0, 30))\n", "sub_path": "classes/gameLogic.py", "file_name": "gameLogic.py", "file_ext": "py", "file_size_in_byte": 6722, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "classes.gameData.GameData", "line_number": 22, "usage_type": "call"}, {"api_name": "classes.gameData", "line_number": 22, "usage_type": "name"}, {"api_name": "pygame.display.set_caption", "line_number": 32, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 32, "usage_type": "attribute"}, {"api_name": "config.config.SCREEN_TITLE", "line_number": 32, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 32, "usage_type": "name"}, {"api_name": "pygame.display.set_mode", "line_number": 35, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 35, "usage_type": "attribute"}, {"api_name": "config.config.SCREEN_W", "line_number": 35, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 35, "usage_type": "name"}, {"api_name": "config.config.SCREEN_H", "line_number": 35, "usage_type": "attribute"}, {"api_name": "config.config.BACKGR_COLOR", "line_number": 38, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 38, "usage_type": "name"}, {"api_name": "pygame.font.init", "line_number": 41, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 41, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 42, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 42, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 43, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 43, "usage_type": "attribute"}, {"api_name": "config.config.TXT_COLOR", "line_number": 44, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 44, "usage_type": "name"}, {"api_name": "config.config.TXT_COLOR", "line_number": 45, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 45, "usage_type": "name"}, {"api_name": "pygame.display.flip", "line_number": 56, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 56, "usage_type": "attribute"}, {"api_name": "classes.imgLoader.ImageLoader", "line_number": 61, "usage_type": "call"}, {"api_name": "classes.imgLoader", "line_number": 61, "usage_type": "name"}, {"api_name": "config.config.MACGYVER_PX", "line_number": 61, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 61, "usage_type": "name"}, {"api_name": "config.config.MACGYVER_POS", "line_number": 62, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 62, "usage_type": "name"}, {"api_name": "classes.imgLoader.ImageLoader", "line_number": 64, "usage_type": "call"}, {"api_name": "classes.imgLoader", "line_number": 64, "usage_type": "name"}, {"api_name": "config.config.ENEMY_PX", "line_number": 64, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 64, "usage_type": "name"}, {"api_name": "config.config.ENEMY_POS", "line_number": 65, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 65, "usage_type": "name"}, {"api_name": "classes.imgLoader.ImageLoader", "line_number": 68, "usage_type": "call"}, {"api_name": "classes.imgLoader", "line_number": 68, "usage_type": "name"}, {"api_name": "config.config.WALL_PX", "line_number": 68, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 68, "usage_type": "name"}, {"api_name": "classes.imgLoader.ImageLoader", "line_number": 71, "usage_type": "call"}, {"api_name": "classes.imgLoader", "line_number": 71, "usage_type": "name"}, {"api_name": "config.config.GROUND_PX", "line_number": 71, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 71, "usage_type": "name"}, {"api_name": "classes.imgLoader.ImageLoader", "line_number": 74, "usage_type": "call"}, {"api_name": "classes.imgLoader", "line_number": 74, "usage_type": "name"}, {"api_name": "config.config.TUBE_PX", "line_number": 74, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 74, "usage_type": "name"}, {"api_name": "classes.imgLoader.ImageLoader", "line_number": 75, "usage_type": "call"}, {"api_name": "classes.imgLoader", "line_number": 75, "usage_type": "name"}, {"api_name": "config.config.NEEDLE_PX", "line_number": 75, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 75, "usage_type": "name"}, {"api_name": "classes.imgLoader.ImageLoader", "line_number": 76, "usage_type": "call"}, {"api_name": "classes.imgLoader", "line_number": 76, "usage_type": "name"}, {"api_name": "config.config.AETHER_PX", "line_number": 76, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 76, "usage_type": "name"}, {"api_name": "classes.imgLoader.ImageLoader", "line_number": 79, "usage_type": "call"}, {"api_name": "classes.imgLoader", "line_number": 79, "usage_type": "name"}, {"api_name": "config.config.HYPODERMIC_PX", "line_number": 79, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 79, "usage_type": "name"}, {"api_name": "config.config.TILE_SIZE", "line_number": 99, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 99, "usage_type": "name"}, {"api_name": "config.config.TILE_SIZE", "line_number": 100, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 100, "usage_type": "name"}, {"api_name": "config.config.TILE_SIZE", "line_number": 108, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 108, "usage_type": "name"}, {"api_name": "config.config.TILE_SIZE", "line_number": 109, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 109, "usage_type": "name"}, {"api_name": "config.config.TILE_SIZE", "line_number": 116, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 116, "usage_type": "name"}, {"api_name": "config.config.TILE_SIZE", "line_number": 117, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 117, "usage_type": "name"}, {"api_name": "config.config.TILE_SIZE", "line_number": 123, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 123, "usage_type": "name"}, {"api_name": "config.config.TILE_SIZE", "line_number": 124, "usage_type": "attribute"}, {"api_name": "config.config", "line_number": 124, "usage_type": "name"}, {"api_name": "pygame.key.get_pressed", "line_number": 128, "usage_type": "call"}, {"api_name": "pygame.key", "line_number": 128, "usage_type": "attribute"}, {"api_name": "pygame.K_UP", "line_number": 128, "usage_type": "attribute"}, {"api_name": "pygame.key.get_pressed", "line_number": 129, "usage_type": "call"}, {"api_name": "pygame.key", "line_number": 129, "usage_type": "attribute"}, {"api_name": "pygame.K_DOWN", "line_number": 129, "usage_type": "attribute"}, {"api_name": "pygame.key.get_pressed", "line_number": 130, "usage_type": "call"}, {"api_name": "pygame.key", "line_number": 130, "usage_type": "attribute"}, {"api_name": "pygame.K_LEFT", "line_number": 130, "usage_type": "attribute"}, {"api_name": "pygame.key.get_pressed", "line_number": 131, "usage_type": "call"}, {"api_name": "pygame.key", "line_number": 131, "usage_type": "attribute"}, {"api_name": "pygame.K_RIGHT", "line_number": 131, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 160, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 163, "usage_type": "call"}]}
+{"seq_id": "122959745", "text": "from talon.voice import Word, Context, press, Key\nfrom talon import clip\n\nfrom ..utils import (\n insert,\n normalise_keys,\n parse_word,\n surround,\n text,\n sentence_text,\n word,\n parse_words,\n spoken_text,\n)\n\n\ndef title_case_capitalize_word(index, word, _):\n words_to_keep_lowercase = \"a,an,the,at,by,for,in,of,on,to,up,and,as,but,or,nor\".split(\n \",\"\n )\n if index == 0 or word not in words_to_keep_lowercase:\n return word.capitalize()\n else:\n return word\n\n\nformatters = normalise_keys(\n {\n \"thrack\": (True, lambda i, word, _: word[0:3] if i == 0 else \"\"),\n \"quattro\": (True, lambda i, word, _: word[0:4] if i == 0 else \"\"),\n \"(cram | camel)\": (\n True,\n lambda i, word, _: word if i == 0 else word.capitalize(),\n ),\n \"pathway\": (True, lambda i, word, _: word if i == 0 else \"/\" + word),\n \"dotsway\": (True, lambda i, word, _: word if i == 0 else \".\" + word),\n \"yellsmash\": (True, lambda i, word, _: word.upper()),\n \"(allcaps | yeller)\": (False, lambda i, word, _: word.upper()),\n \"yellsnik\": (\n True,\n lambda i, word, _: word.upper() if i == 0 else \"_\" + word.upper(),\n ),\n \"dollcram\": (\n True,\n lambda i, word, _: \"$\" + word if i == 0 else word.capitalize(),\n ),\n # \"champ\": (True, lambda i, word, _: word.capitalize() if i == 0 else \" \" + word),\n \"lowcram\": (\n True,\n lambda i, word, _: \"@\" + word if i == 0 else word.capitalize(),\n ),\n \"(criff | criffed)\": (True, lambda i, word, _: word.capitalize()),\n \"dotcriffed\": (True, lambda i, word, _: \".\" + word.capitalize() if i == 0 else word.capitalize()),\n \"tridal\": (False, lambda i, word, _: word.capitalize()),\n \"snake\": (True, lambda i, word, _: word if i == 0 else \"_\" + word),\n \"dotsnik\": (True, lambda i, word, _: \".\" + word if i == 0 else \"_\" + word),\n \"dot\": (True, lambda i, word, _: \".\" + word if i == 0 else \"_\" + word),\n \"smash\": (True, lambda i, word, _: word),\n \"(spine | kebab)\": (True, lambda i, word, _: word if i == 0 else \"-\" + word),\n \"title\": (False, title_case_capitalize_word),\n }\n)\n\nsurrounders = normalise_keys(\n {\n \"(surround dubstring | surround coif)\": (False, surround('\"')),\n \"(surround string | surround posh)\": (False, surround(\"'\")),\n \"(surround tics | surround glitch)\": (False, surround(\"`\")),\n \"surround prank\": (False, surround(\" \")),\n \"surround dunder\": (False, surround(\"__\")),\n \"surround angler\": (False, surround(\"<\", \">\")),\n \"surround brisk\": (False, surround(\"[\", \"]\")),\n \"surround kirk\": (False, surround(\"{\", \"}\")),\n \"surround precoif\": (False, surround('(\"', '\")')),\n \"surround prex\": (False, surround(\"(\", \")\")),\n }\n)\n\nformatters.update(surrounders)\n\n\ndef FormatText(m):\n fmt = []\n\n for w in m._words:\n if isinstance(w, Word) and w != \"over\":\n fmt.append(w.word)\n words = parse_words(m)\n if not words:\n try:\n with clip.capture() as s:\n press(\"cmd-c\")\n words = s.get().split(\" \")\n except clip.NoChange:\n words = [\"\"]\n\n tmp = []\n\n smash = False\n for i, w in enumerate(words):\n word = parse_word(w, True)\n for name in reversed(fmt):\n smash, func = formatters[name]\n word = func(i, word, i == len(words) - 1)\n tmp.append(word)\n\n sep = \"\" if smash else \" \"\n insert(sep.join(tmp))\n # if no words, move cursor inside surrounders\n if not words[0]:\n for i in range(len(tmp[0]) // 2):\n press(\"left\")\n\n\n# from ..noise import pop_control as pc\n\nctx = Context(\"formatters\")\n# ctx = Context(\"formatters\", func=lambda app, window: pc.PopControl.mode != pc.PopControl.DICTATION)\nctx.keymap(\n {\n \"phrase [over]\": spoken_text,\n \"phrase [tree]\": [spoken_text, \" tree\"],\n \"phrase [subtree]\": [spoken_text, \" subtree\"],\n\n \"squash [over]\": text,\n \"derek [] [over]\": [\" \", spoken_text],\n \"darren [] [over]\": [Key(\"cmd-right\"), \" \", spoken_text],\n \"(sentence | champ) [over]\": sentence_text,\n \"(comma | ,) [over]\": [\", \", spoken_text],\n \"period [over]\": [\". \", sentence_text],\n \"word \": word,\n \"(%s)+ [] [over]\" % (\" | \".join(formatters)): FormatText,\n # to match surrounder command + another command (i.e. not dgndictation)\n \"(%s)+\" % (\" | \".join(surrounders)): FormatText,\n }\n)\n\n\n", "sub_path": "text/formatters.py", "file_name": "formatters.py", "file_ext": "py", "file_size_in_byte": 4778, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "utils.word", "line_number": 21, "usage_type": "name"}, {"api_name": "utils.word.capitalize", "line_number": 22, "usage_type": "call"}, {"api_name": "utils.word", "line_number": 22, "usage_type": "name"}, {"api_name": "utils.word", "line_number": 24, "usage_type": "name"}, {"api_name": "utils.normalise_keys", "line_number": 27, "usage_type": "call"}, {"api_name": "utils.word", "line_number": 29, "usage_type": "name"}, {"api_name": "utils.word", "line_number": 30, "usage_type": "name"}, {"api_name": "utils.word", "line_number": 33, "usage_type": "name"}, {"api_name": "utils.word.capitalize", "line_number": 33, "usage_type": "call"}, {"api_name": "utils.word", "line_number": 35, "usage_type": "name"}, {"api_name": "utils.word", "line_number": 36, "usage_type": "name"}, {"api_name": "utils.word.upper", "line_number": 37, "usage_type": "call"}, {"api_name": "utils.word", "line_number": 37, "usage_type": "name"}, {"api_name": "utils.word.upper", "line_number": 38, "usage_type": "call"}, {"api_name": "utils.word", "line_number": 38, "usage_type": "name"}, {"api_name": "utils.word.upper", "line_number": 41, "usage_type": "call"}, {"api_name": "utils.word", "line_number": 41, "usage_type": "name"}, {"api_name": "utils.word", "line_number": 45, "usage_type": "name"}, {"api_name": "utils.word.capitalize", "line_number": 45, "usage_type": "call"}, {"api_name": "utils.word", "line_number": 50, "usage_type": "name"}, {"api_name": "utils.word.capitalize", "line_number": 50, "usage_type": "call"}, {"api_name": "utils.word.capitalize", "line_number": 52, "usage_type": "call"}, {"api_name": "utils.word", "line_number": 52, "usage_type": "name"}, {"api_name": "utils.word.capitalize", "line_number": 53, "usage_type": "call"}, {"api_name": "utils.word", "line_number": 53, "usage_type": "name"}, {"api_name": "utils.word.capitalize", "line_number": 54, "usage_type": "call"}, {"api_name": "utils.word", "line_number": 54, "usage_type": "name"}, {"api_name": "utils.word", "line_number": 55, "usage_type": "name"}, {"api_name": "utils.word", "line_number": 56, "usage_type": "name"}, {"api_name": "utils.word", "line_number": 57, "usage_type": "name"}, {"api_name": "utils.word", "line_number": 58, "usage_type": "name"}, {"api_name": "utils.word", "line_number": 59, "usage_type": "name"}, {"api_name": "utils.normalise_keys", "line_number": 64, "usage_type": "call"}, {"api_name": "utils.surround", "line_number": 66, "usage_type": "call"}, {"api_name": "utils.surround", "line_number": 67, "usage_type": "call"}, {"api_name": "utils.surround", "line_number": 68, "usage_type": "call"}, {"api_name": "utils.surround", "line_number": 69, "usage_type": "call"}, {"api_name": "utils.surround", "line_number": 70, "usage_type": "call"}, {"api_name": "utils.surround", "line_number": 71, "usage_type": "call"}, {"api_name": "utils.surround", "line_number": 72, "usage_type": "call"}, {"api_name": "utils.surround", "line_number": 73, "usage_type": "call"}, {"api_name": "utils.surround", "line_number": 74, "usage_type": "call"}, {"api_name": "utils.surround", "line_number": 75, "usage_type": "call"}, {"api_name": "talon.voice.Word", "line_number": 86, "usage_type": "argument"}, {"api_name": "utils.parse_words", "line_number": 88, "usage_type": "call"}, {"api_name": "talon.clip.capture", "line_number": 91, "usage_type": "call"}, {"api_name": "talon.clip", "line_number": 91, "usage_type": "name"}, {"api_name": "talon.voice.press", "line_number": 92, "usage_type": "call"}, {"api_name": "talon.clip.NoChange", "line_number": 94, "usage_type": "attribute"}, {"api_name": "talon.clip", "line_number": 94, "usage_type": "name"}, {"api_name": "utils.word", "line_number": 101, "usage_type": "name"}, {"api_name": "utils.parse_word", "line_number": 101, "usage_type": "call"}, {"api_name": "utils.word", "line_number": 104, "usage_type": "name"}, {"api_name": "utils.word", "line_number": 105, "usage_type": "argument"}, {"api_name": "utils.insert", "line_number": 108, "usage_type": "call"}, {"api_name": "talon.voice.press", "line_number": 112, "usage_type": "call"}, {"api_name": "talon.voice.Context", "line_number": 117, "usage_type": "call"}, {"api_name": "utils.spoken_text", "line_number": 121, "usage_type": "name"}, {"api_name": "utils.spoken_text", "line_number": 122, "usage_type": "name"}, {"api_name": "utils.spoken_text", "line_number": 123, "usage_type": "name"}, {"api_name": "utils.text", "line_number": 125, "usage_type": "name"}, {"api_name": "utils.spoken_text", "line_number": 126, "usage_type": "name"}, {"api_name": "talon.voice.Key", "line_number": 127, "usage_type": "call"}, {"api_name": "utils.spoken_text", "line_number": 127, "usage_type": "name"}, {"api_name": "utils.sentence_text", "line_number": 128, "usage_type": "name"}, {"api_name": "utils.spoken_text", "line_number": 129, "usage_type": "name"}, {"api_name": "utils.sentence_text", "line_number": 130, "usage_type": "name"}, {"api_name": "utils.word", "line_number": 131, "usage_type": "name"}]}
+{"seq_id": "454259555", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.db.models.deletion\nimport mptt.fields\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.BLANC_PAGES_MODEL),\n ('pages', '0004_rename_tables'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Contact',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=120, blank=True)),\n ('email', models.EmailField(max_length=70)),\n ('subject', models.CharField(max_length=120)),\n ('content', models.TextField()),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ],\n ),\n migrations.CreateModel(\n name='ContactFormBlock',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('recipient', models.EmailField(max_length=254)),\n ('content_block', models.ForeignKey(editable=False, to='pages.ContentBlock', null=True)),\n ('success_page', mptt.fields.TreeForeignKey(on_delete=django.db.models.deletion.SET_NULL, to=settings.BLANC_PAGES_MODEL, null=True)),\n ],\n options={\n 'abstract': False,\n },\n ),\n ]\n", "sub_path": "apps/contacts/migrations/0001_initial.py", "file_name": "0001_initial.py", "file_ext": "py", "file_size_in_byte": 1561, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "87", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 10, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 10, "usage_type": "name"}, {"api_name": "django.db.migrations.swappable_dependency", "line_number": 13, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 13, "usage_type": "name"}, {"api_name": "django.conf.settings.BLANC_PAGES_MODEL", "line_number": 13, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 13, "usage_type": "name"}, {"api_name": "django.db.migrations.CreateModel", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 18, "usage_type": "name"}, {"api_name": "django.db.models.AutoField", "line_number": 21, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 21, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 22, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 22, "usage_type": "name"}, {"api_name": "django.db.models.EmailField", "line_number": 23, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 23, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 24, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 24, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 25, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 25, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 26, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 26, "usage_type": "name"}, {"api_name": "django.db.migrations.CreateModel", "line_number": 29, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 29, "usage_type": "name"}, {"api_name": "django.db.models.AutoField", "line_number": 32, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 32, "usage_type": "name"}, {"api_name": "django.db.models.EmailField", "line_number": 33, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 33, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 34, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 34, "usage_type": "name"}, {"api_name": "mptt.fields.fields.TreeForeignKey", "line_number": 35, "usage_type": "call"}, {"api_name": "mptt.fields.fields", "line_number": 35, "usage_type": "attribute"}, {"api_name": "mptt.fields", "line_number": 35, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 35, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 35, "usage_type": "name"}, {"api_name": "django.conf.settings.BLANC_PAGES_MODEL", "line_number": 35, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 35, "usage_type": "name"}]}
+{"seq_id": "438658863", "text": "import streamlit as st\r\nimport tempfile\r\nimport warnings\r\nimport os\r\nfrom PIL import Image\r\nfrom video import *\r\n\r\nwarnings.filterwarnings(\"ignore\", message=r\"Passing\", category=FutureWarning)\r\n\r\n\r\n# hide hamburger menu\r\n# hide_streamlit_style = \"\"\"\r\n# \r\n# \"\"\"\r\n# st.markdown(hide_streamlit_style, unsafe_allow_html=True)\r\n\r\n\r\n# hide footer\r\nhide_footer_style = \"\"\"\r\n